jskelet 0.2.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/AGENTS.md +132 -132
  2. package/CHANGELOG.md +403 -383
  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 +293 -287
  7. package/docs/03-routing.md +486 -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 +1231 -1209
  11. package/docs/07-yapilandirma.md +44 -21
  12. package/docs/08-build.md +366 -366
  13. package/docs/09-dev-araclari.md +335 -335
  14. package/docs/10-dagitim.md +329 -329
  15. package/docs/11-tasima.md +1 -0
  16. package/docs/12-panel-ve-oturum.md +384 -384
  17. package/docs/README.md +105 -105
  18. package/docs/en/01-getting-started.md +292 -292
  19. package/docs/en/02-architecture.md +311 -305
  20. package/docs/en/03-routing.md +503 -497
  21. package/docs/en/04-rendering.md +504 -504
  22. package/docs/en/05-islands.md +492 -492
  23. package/docs/en/06-caching.md +1197 -1198
  24. package/docs/en/07-configuration.md +1009 -986
  25. package/docs/en/08-build.md +383 -383
  26. package/docs/en/09-dev-tools.md +342 -342
  27. package/docs/en/10-deployment.md +332 -332
  28. package/docs/en/11-migration.md +360 -359
  29. package/docs/en/12-dashboards-and-sessions.md +392 -392
  30. package/docs/en/README.md +112 -112
  31. package/package.json +102 -102
  32. package/src/build/ensure-build.mjs +15 -15
  33. package/src/build/paths.mjs +143 -143
  34. package/src/build/resolve-peer.mjs +36 -36
  35. package/src/build/tasks/client.mjs +268 -268
  36. package/src/build/tasks/css.mjs +124 -124
  37. package/src/build/tasks/fonts.mjs +146 -146
  38. package/src/build/tasks/icons.mjs +224 -224
  39. package/src/build/tasks/images.mjs +244 -244
  40. package/src/build/tasks/precompress.mjs +78 -78
  41. package/src/client/{cache-panel → admin}/i18n.js +756 -670
  42. package/src/client/{cache-panel → admin}/login.html +74 -74
  43. package/src/client/{cache-panel → admin}/panel.css +804 -756
  44. package/src/client/admin/panel.html +486 -0
  45. package/src/client/{cache-panel → admin}/panel.js +1242 -915
  46. package/src/client/devtools/report.html +185 -185
  47. package/src/client/devtools/report.js +725 -725
  48. package/src/client/dom.js +95 -95
  49. package/src/client/form.js +192 -192
  50. package/src/client/index.js +35 -35
  51. package/src/client/registry.js +297 -297
  52. package/src/client/safe-image.js +91 -91
  53. package/src/client/store.js +36 -36
  54. package/src/client/swap.js +188 -188
  55. package/src/config/defaults.js +16 -7
  56. package/src/config/index.js +38 -22
  57. package/src/config/pattern.js +107 -107
  58. package/src/http/control-flow.js +71 -71
  59. package/src/http/cookies.js +257 -257
  60. package/src/http/request-cache.js +46 -46
  61. package/src/http/request-context.js +162 -162
  62. package/src/index.js +83 -83
  63. package/src/init.mjs +221 -221
  64. package/src/log.mjs +58 -0
  65. package/src/runtime/alias-hooks.mjs +119 -119
  66. package/src/runtime/register.mjs +4 -4
  67. package/src/server/admin/actions.js +229 -0
  68. package/src/server/admin/auth.js +125 -0
  69. package/src/server/admin/event-log.js +151 -0
  70. package/src/server/admin/gate.js +209 -0
  71. package/src/server/admin/inventory.js +188 -0
  72. package/src/server/admin/mount.js +56 -0
  73. package/src/server/admin/router.js +216 -0
  74. package/src/server/admin/snapshot.js +126 -0
  75. package/src/server/assets.js +147 -147
  76. package/src/server/cache-deps.js +42 -42
  77. package/src/server/cloudflare.js +607 -607
  78. package/src/server/create-app.js +295 -291
  79. package/src/server/data-cache.js +462 -462
  80. package/src/server/dev/report.js +369 -369
  81. package/src/server/dev/socket.js +170 -170
  82. package/src/server/dev/version-check.mjs +139 -139
  83. package/src/server/html-cache.js +817 -817
  84. package/src/server/metadata.js +102 -102
  85. package/src/server/middleware/compression.js +205 -205
  86. package/src/server/middleware/csrf.js +134 -134
  87. package/src/server/middleware/dev-gate.js +62 -62
  88. package/src/server/middleware/headers.js +37 -37
  89. package/src/server/middleware/redirects.js +32 -32
  90. package/src/server/middleware/static-precompressed.js +100 -100
  91. package/src/server/middleware/trailing-slash.js +53 -0
  92. package/src/server/middleware/upstream-proxy.js +141 -141
  93. package/src/server/prewarm.js +601 -601
  94. package/src/server/redis.js +569 -569
  95. package/src/server/router.js +128 -128
  96. package/src/server/status-page.js +164 -164
  97. package/src/server/upstream-limiter.js +376 -376
  98. package/src/server/upstream-tracking.js +166 -166
  99. package/src/start.mjs +7 -7
  100. package/src/templates/layout.ejs +44 -44
  101. package/src/version.mjs +31 -31
  102. package/src/views/components/loader.js +85 -85
  103. package/src/views/helpers/html.js +102 -102
  104. package/src/views/helpers/tags.js +245 -245
  105. package/src/client/cache-panel/panel.html +0 -308
  106. package/src/server/cache-panel.js +0 -759
@@ -1,915 +1,1242 @@
1
- /**
2
- * Önbellek panelinin istemci tarafı.
3
- *
4
- * Build hattından geçmez, doğrudan diskten servis edilir: panelin açık olduğu
5
- * bir kurulumda `jskelet build` hiç koşmamış olabilir ve panel yine çalışmalı.
6
- * Bu yüzden burada import edilen bir framework modülü yok.
7
- *
8
- * Yenileme WebSocket değil, kısa aralıklı `fetch` ile: panel nadiren ve kısa
9
- * süre açık kalıyor, kalıcı bir kanal açmanın karşılığı yok.
10
- *
11
- * Bütün görünen metin `i18n.js` üzerinden geçiyor; sunucudan gelen cevaplar da
12
- * metin değil `code` taşıyor, yani dil değişimi tek yerden hallediliyor.
13
- */
14
- import { applyTranslations, languageSelect, t } from "./i18n.js";
15
-
16
- const REFRESH_MS = 3000;
17
-
18
- const $ = (/** @type {string} */ id) => document.getElementById(id);
19
-
20
- /** @type {"html" | "data"} */
21
- let tab = "html";
22
- let query = "";
23
- /** @type {any} */
24
- let latest = null;
25
- /** @type {number | null} */
26
- let timer = null;
27
- let busy = false;
28
-
29
- /* ------------------------------------------------------------ biçimlendirme */
30
-
31
- /**
32
- * @param {number} bytes
33
- * @returns {string}
34
- */
35
- function formatBytes(bytes) {
36
- if (!bytes) return "0 B";
37
- const units = ["B", "KB", "MB", "GB"];
38
- const power = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
39
- const value = bytes / 1024 ** power;
40
- return `${value >= 100 || power === 0 ? Math.round(value) : value.toFixed(1)} ${units[power]}`;
41
- }
42
-
43
- /**
44
- * @param {number} seconds
45
- * @returns {string}
46
- */
47
- function formatDuration(seconds) {
48
- const total = Math.max(0, Math.round(seconds));
49
- const [s, m, h, d] = [t("unit.second"), t("unit.minute"), t("unit.hour"), t("unit.day")];
50
-
51
- if (total < 60) return `${total}${s}`;
52
- if (total < 3600) return `${Math.floor(total / 60)}${m} ${total % 60}${s}`;
53
- if (total < 86_400) {
54
- return `${Math.floor(total / 3600)}${h} ${Math.floor((total % 3600) / 60)}${m}`;
55
- }
56
- return `${Math.floor(total / 86_400)}${d} ${Math.floor((total % 86_400) / 3600)}${h}`;
57
- }
58
-
59
- /**
60
- * @param {string} message
61
- * @param {boolean} [ok]
62
- */
63
- function toast(message, ok = true) {
64
- const node = document.createElement("div");
65
- node.className = ok ? "toast" : "toast bad";
66
- node.textContent = message;
67
- $("toast").append(node);
68
-
69
- setTimeout(() => node.remove(), 5000);
70
- }
71
-
72
- /* -------------------------------------------------------------------- veri */
73
-
74
- /**
75
- * Sunucu yetkisiz isteklere 404 dönüyor (panelin varlığını doğrulamamak
76
- * için). Oturum düştüyse sayfa yeniden yüklenir ve giriş formuna dönülür;
77
- * arka planda dönmeye devam eden bir yoklama, IP'yi kendi kendine
78
- * yasaklatırdı.
79
- *
80
- * @param {Response} response
81
- * @returns {boolean} İstek işlenebilir mi.
82
- */
83
- function alive(response) {
84
- if (response.status !== 404) return true;
85
-
86
- stopPolling();
87
- location.reload();
88
- return false;
89
- }
90
-
91
- async function load() {
92
- if (busy) return;
93
- busy = true;
94
-
95
- try {
96
- const response = await fetch(`data?q=${encodeURIComponent(query)}`, {
97
- headers: { Accept: "application/json" },
98
- });
99
- if (!alive(response)) return;
100
- if (!response.ok) return;
101
-
102
- latest = await response.json();
103
- render();
104
- } catch {
105
- // Sunucu yeniden başlıyor olabilir; bir sonraki tur dener.
106
- } finally {
107
- busy = false;
108
- }
109
- }
110
-
111
- /**
112
- * @param {Record<string, unknown>} body
113
- * @returns {Promise<void>}
114
- */
115
- async function act(body) {
116
- const response = await fetch("action", {
117
- method: "POST",
118
- headers: {
119
- "Content-Type": "application/json",
120
- // Panelin CSRF freni: çapraz siteden gönderilemeyen bir başlık.
121
- "X-JSkelet-Cache-Panel": "1",
122
- },
123
- body: JSON.stringify(body),
124
- });
125
-
126
- if (!alive(response)) return;
127
-
128
- const result = await response.json().catch(() => null);
129
- toast(describe(result), result?.ok !== false);
130
- await load();
131
-
132
- // Cloudflare ayarları değişmiş olabilir; genel bakış önbelleği atlanır.
133
- if (String(body.type ?? "").startsWith("cf:")) await loadCloudflare(true);
134
- }
135
-
136
- /**
137
- * Sunucu cevabını metne çevirir.
138
- *
139
- * `/action` dil taşımıyor: `{ ok, code, params }` dönüyor ve cümle burada
140
- * kuruluyor. Redis sayımı gibi parçalı cevaplar `parts` ile geliyor, çünkü
141
- * "veritabanında kaç anahtar var" bilgisi her zaman okunamıyor ve eksik parçayı
142
- * cümleden düşürmek tek düzgün yol.
143
- *
144
- * @param {any} result
145
- * @returns {string}
146
- */
147
- function describe(result) {
148
- if (!result) return t("toast.failed");
149
-
150
- if (Array.isArray(result.parts)) {
151
- const parts = result.parts
152
- .map((/** @type {any} */ part) => t(`msg.${part.code}`, part.params))
153
- .filter(Boolean);
154
- if (parts.length) return parts.join(" · ");
155
- }
156
-
157
- if (result.code) return t(`msg.${result.code}`, result.params);
158
- return t(result.ok ? "toast.done" : "toast.failed");
159
- }
160
-
161
- /* ------------------------------------------------------------------- çizim */
162
-
163
- function render() {
164
- if (!latest) return;
165
-
166
- const { process: proc, release, host, html, data, redis, prewarm } = latest;
167
-
168
- $("version").textContent = `v${release.version}`;
169
- $("foot-release").textContent = [
170
- `v${release.version}`,
171
- release.license,
172
- release.node ? `Node ${release.node}` : null,
173
- ]
174
- .filter(Boolean)
175
- .join(" · ");
176
- if (release.homepage) $("foot-repo").href = release.homepage;
177
-
178
- $("env").textContent = proc.env;
179
- $("pid").textContent = `pid ${proc.pid}`;
180
- $("uptime").textContent = t("chip.up", { value: formatDuration(proc.uptime) });
181
- $("memory").textContent = `rss ${formatBytes(proc.memory.rss)}`;
182
-
183
- $("html-size").textContent = html.size.toLocaleString();
184
- $("html-sub").textContent = t("card.limit", { count: html.maxEntries.toLocaleString() });
185
- $("html-bytes").textContent = formatBytes(html.bytes);
186
- $("html-stale").textContent = t("card.stale", { count: html.stale });
187
-
188
- $("data-size").textContent = data.size.toLocaleString();
189
- $("data-sub").textContent = t("card.staleAndLimit", {
190
- stale: data.stale,
191
- limit: data.maxEntries.toLocaleString(),
192
- });
193
-
194
- const redisState = !redis.enabled
195
- ? "off"
196
- : redis.bypassed
197
- ? "bypassed"
198
- : redis.connected
199
- ? "connected"
200
- : "disconnected";
201
-
202
- $("redis-state").textContent = t(`state.${redisState}`);
203
- $("redis-sub").textContent = redis.enabled
204
- ? t("redis.sub", { address: redis.address, errors: redis.errors })
205
- : t("redis.disabled");
206
-
207
- renderRedis(redis, redisState);
208
- renderHost(host, proc, redis);
209
-
210
- const done = prewarm.done ?? 0;
211
- const total = prewarm.total ?? 0;
212
- $("prewarm-state").textContent = prewarm.active ? `${done}/${total}` : t("state.idle");
213
- $("prewarm-sub").textContent = prewarm.active
214
- ? t("prewarm.inProgress")
215
- : total
216
- ? t("prewarm.lastRound", { done, total })
217
- : t("prewarm.never");
218
-
219
- renderTable();
220
- }
221
-
222
- /* ------------------------------------------------------------- cloudflare */
223
-
224
- /** @type {any} */
225
- let cloudflare = null;
226
-
227
- /**
228
- * Cloudflare genel bakışı ayrı bir uçtan gelir: zone bilgisi ve ayarlar ağa
229
- * çıkıyor, döküm turu ise saniyeler mertebesinde yenileniyor. Bu yüzden
230
- * yalnızca açılışta ve bir işlemden sonra istenir.
231
- *
232
- * @param {boolean} [force]
233
- */
234
- async function loadCloudflare(force = false) {
235
- const response = await fetch(`cloudflare${force ? "?force=1" : ""}`);
236
- if (!alive(response)) return;
237
-
238
- cloudflare = await response.json().catch(() => null);
239
- renderCloudflare();
240
- }
241
-
242
- function renderCloudflare() {
243
- if (!cloudflare) return;
244
-
245
- const ok = cloudflare.ok === true;
246
- const status = cloudflare.status ?? {};
247
- const settings = cloudflare.settings ?? {};
248
- const zone = cloudflare.zone ?? null;
249
-
250
- $("cf-heading").textContent = ok
251
- ? [zone?.name, zone?.plan].filter(Boolean).join(" · ") || t("state.connected")
252
- : status.configured
253
- ? t("cf.error", { error: cloudflare.error })
254
- : t("cf.notConnected");
255
-
256
- $("cf-tools").hidden = !ok;
257
- $("cf-suggest").hidden = ok || status.configured;
258
- $("cf-refresh").hidden = !status.configured;
259
-
260
- if (!ok) {
261
- $("cf-kv").replaceChildren();
262
- return;
263
- }
264
-
265
- const development = settings.developmentMode === "on";
266
- $("cf-dev").checked = development;
267
-
268
- /** @type {[string, string, string?][]} */
269
- const rows = [
270
- [t("cf.zone"), `${zone?.name ?? "—"} (${status.zoneId ?? "?"})`],
271
- [t("cf.plan"), zone?.plan ?? "—"],
272
- [
273
- t("cf.token"),
274
- status.tokenSource === "env" ? t("cf.token.env") : t("cf.token.config"),
275
- "on",
276
- ],
277
- [
278
- t("cf.devModeLabel"),
279
- development
280
- ? t("cf.devMode.on", { time: formatDuration(settings.developmentModeRemaining) })
281
- : t("state.off"),
282
- development ? "bad" : "on",
283
- ],
284
- [t("cf.cacheLevel"), String(settings.cacheLevel ?? "—")],
285
- [t("cf.browserTtl"), ttl(settings.browserCacheTtl)],
286
- [t("cf.edgeTtl"), ttl(settings.edgeCacheTtl)],
287
- [t("cf.sortQuery"), String(settings.sortQueryString ?? "—")],
288
- [t("cf.alwaysOnline"), String(settings.alwaysOnline ?? "—")],
289
- ...feature(t("cf.tiered"), settings.tieredCaching),
290
- ...feature(t("cf.regionalTiered"), settings.regionalTieredCache),
291
- ...feature(t("cf.reserve"), settings.cacheReserve),
292
- ];
293
-
294
- $("cf-kv").replaceChildren(...rows.map(kvRow));
295
- }
296
-
297
- /**
298
- * Plan dışı kalan bir özellik `null` döner. "off" yazmak yanıltıcı olurdu:
299
- * kapatılmış değil, o planda hiç yok.
300
- *
301
- * @param {string} label
302
- * @param {string | null} value
303
- * @returns {[string, string, string?][]}
304
- */
305
- function feature(label, value) {
306
- if (value === null || value === undefined) {
307
- return [[label, t("cf.unavailablePlan"), "off"]];
308
- }
309
- const on = value === "on";
310
- return [[label, on ? t("state.on") : t("state.off"), on ? "on" : "off"]];
311
- }
312
-
313
- /**
314
- * @param {unknown} seconds
315
- * @returns {string}
316
- */
317
- function ttl(seconds) {
318
- const value = Number(seconds);
319
- if (!Number.isFinite(value)) return "—";
320
- // Cloudflare 0'ı "Respect Existing Headers" olarak kullanıyor.
321
- if (value === 0) return t("cf.respectOrigin");
322
- return formatDuration(value);
323
- }
324
-
325
- /**
326
- * @param {[string, string, string?]} row
327
- * @returns {HTMLDivElement}
328
- */
329
- function kvRow([label, value, tone]) {
330
- const wrap = document.createElement("div");
331
- const dt = document.createElement("dt");
332
- dt.textContent = label;
333
- const dd = document.createElement("dd");
334
- if (tone) dd.className = tone;
335
- dd.textContent = value;
336
- wrap.append(dt, dd);
337
- return wrap;
338
- }
339
-
340
- /**
341
- * Analitik dökümü. İki soru tek uçtan cevaplanıyor: yol verilirse kolo
342
- * kırılımı, verilmezse zone genelinde cache durumu dağılımı.
343
- */
344
- async function loadCloudflareAnalytics() {
345
- const path = $("cf-path").value.trim();
346
- const target = $("cf-report");
347
-
348
- target.hidden = false;
349
- target.textContent = t("cf.querying");
350
-
351
- const response = await fetch("cloudflare/analytics", {
352
- method: "POST",
353
- headers: {
354
- "Content-Type": "application/json",
355
- "X-JSkelet-Cache-Panel": "1",
356
- },
357
- body: JSON.stringify({ path }),
358
- });
359
-
360
- if (!alive(response)) return;
361
-
362
- const result = await response.json().catch(() => null);
363
-
364
- if (!result?.ok) {
365
- target.textContent = t("msg.cf.failed", { error: result?.error ?? t("cf.queryFailed") });
366
- return;
367
- }
368
-
369
- // Son dökümü dil değişiminde yeniden kurmak için saklanır: tablo ağdan
370
- // geliyor ve dil değişti diye Cloudflare'e yeniden gitmek gereksiz.
371
- lastReport = result;
372
- renderReport();
373
- }
374
-
375
- /** @type {any} */
376
- let lastReport = null;
377
-
378
- function renderReport() {
379
- if (!lastReport) return;
380
- const result = lastReport;
381
-
382
- $("cf-report").replaceChildren(
383
- result.colos ? edgeTable(result) : statusTable(result),
384
- note(
385
- result.colos
386
- ? t("cf.edgeNote", {
387
- colos: result.colos.length,
388
- path: result.path,
389
- hours: result.hours,
390
- hits: result.hits,
391
- misses: result.misses,
392
- })
393
- : t("cf.zoneNote", { hours: result.hours }),
394
- ),
395
- );
396
- }
397
-
398
- /**
399
- * @param {any} result
400
- * @returns {HTMLTableElement}
401
- */
402
- function edgeTable(result) {
403
- return buildTable(
404
- [t("cf.colo"), t("cf.fromCache"), t("cf.toOrigin")],
405
- result.colos.map((/** @type {any} */ row) => [
406
- row.colo,
407
- String(row.hits),
408
- String(row.misses),
409
- ]),
410
- );
411
- }
412
-
413
- /**
414
- * @param {any} result
415
- * @returns {HTMLTableElement}
416
- */
417
- function statusTable(result) {
418
- const total = result.rows.reduce((sum, /** @type {any} */ row) => sum + row.requests, 0) || 1;
419
-
420
- return buildTable(
421
- [t("cf.cacheStatus"), t("cf.requests"), t("cf.share"), t("cf.edgeBytes")],
422
- result.rows.map((/** @type {any} */ row) => [
423
- row.status,
424
- row.requests.toLocaleString(),
425
- `${Math.round((row.requests / total) * 100)}%`,
426
- formatBytes(row.bytes),
427
- ]),
428
- );
429
- }
430
-
431
- /**
432
- * @param {string[]} headers
433
- * @param {string[][]} rows
434
- * @returns {HTMLTableElement}
435
- */
436
- function buildTable(headers, rows) {
437
- const table = document.createElement("table");
438
- const thead = document.createElement("thead");
439
- const headRow = document.createElement("tr");
440
-
441
- headers.forEach((label, index) => {
442
- const th = document.createElement("th");
443
- th.textContent = label;
444
- if (index > 0) th.className = "num";
445
- headRow.append(th);
446
- });
447
-
448
- thead.append(headRow);
449
-
450
- const tbody = document.createElement("tbody");
451
- for (const row of rows) {
452
- const tr = document.createElement("tr");
453
- row.forEach((value, index) => tr.append(cell(value, index > 0 ? "num" : undefined)));
454
- tbody.append(tr);
455
- }
456
-
457
- table.append(thead, tbody);
458
- return table;
459
- }
460
-
461
- /**
462
- * @param {string} text
463
- * @returns {HTMLParagraphElement}
464
- */
465
- function note(text) {
466
- const paragraph = document.createElement("p");
467
- paragraph.className = "note m0";
468
- paragraph.textContent = text;
469
- return paragraph;
470
- }
471
-
472
- /**
473
- * Paylaşımlı kademenin künyesi.
474
- *
475
- * "Bağlı mı" tek başına yetmiyor: yanlış `namespace` ya da beklenmeyen bir
476
- * `buildId` ile bağlı bir Redis de hiçbir şey paylaşmıyor gibi görünür. Bu
477
- * yüzden anahtarın **nerede** durduğu ve hangi türlerin paylaşıldığı da
478
- * yazılır.
479
- *
480
- * @param {any} redis
481
- * @param {string} state
482
- */
483
- function renderRedis(redis, state) {
484
- $("redis-heading").textContent = redis.enabled ? t(`state.${state}`) : t("state.notConfigured");
485
- $("redis-actions").hidden = !redis.enabled;
486
- $("redis-suggest").hidden = redis.enabled;
487
-
488
- /** @type {[string, string, string?][]} */
489
- const rows = redis.enabled
490
- ? [
491
- [
492
- t("redis.connection"),
493
- t(`state.${state}`),
494
- redis.connected && !redis.bypassed ? "on" : "bad",
495
- ],
496
- [t("redis.address"), `${redis.address}${redis.secure ? " (TLS)" : ""}`],
497
- [t("redis.database"), redis.db ?? t("state.default")],
498
- [t("redis.keyPrefix"), `${redis.keyPrefix}:${redis.namespace}`],
499
- [t("redis.buildId"), redis.buildId || "dev"],
500
- [
501
- t("redis.sharesHtml"),
502
- redis.html ? t("state.yes") : t("state.no"),
503
- redis.html ? "on" : "off",
504
- ],
505
- [
506
- t("redis.sharesData"),
507
- redis.data ? t("state.yes") : t("state.no"),
508
- redis.data ? "on" : "off",
509
- ],
510
- [
511
- t("redis.compressed"),
512
- redis.storeEncoded ? t("redis.compressed.shared") : t("redis.compressed.local"),
513
- redis.storeEncoded ? "on" : "off",
514
- ],
515
- [
516
- t("redis.broadcast"),
517
- redis.events
518
- ? redis.subscribed
519
- ? t("redis.broadcast.subscribed")
520
- : t("redis.broadcast.publish")
521
- : t("state.off"),
522
- redis.events && redis.subscribed ? "on" : "off",
523
- ],
524
- [t("redis.timeout"), `${redis.commandTimeoutMs} ${t("unit.ms")}`],
525
- [t("redis.errors"), String(redis.errors), redis.errors ? "bad" : "on"],
526
- ]
527
- : [
528
- [t("redis.tier"), t("redis.tier.inProcess")],
529
- [t("redis.replicas"), t("state.none")],
530
- [t("redis.broadcast"), t("redis.broadcast.local"), "off"],
531
- ];
532
-
533
- $("redis-kv").replaceChildren(...rows.map(kvRow));
534
- }
535
-
536
- /**
537
- * Makinenin RAM ve disk durumu. Paylaşımlı kademe kapalıyken önbelleğin
538
- * tamamı bu sürecin belleğinde yaşıyor; `maxEntries` ile RAM arasındaki
539
- * ilişkiyi görmeden ayar yapmak körlemesine oluyor.
540
- *
541
- * @param {any} host
542
- * @param {any} proc
543
- * @param {any} redis
544
- */
545
- function renderHost(host, proc, redis) {
546
- $("host-heading").textContent = [
547
- host.platform,
548
- `${host.cpus} cpu`,
549
- host.load ? `load ${host.load.toFixed(2)}` : null,
550
- ]
551
- .filter(Boolean)
552
- .join(" · ");
553
-
554
- const ramUsed = host.memory.used / host.memory.total;
555
- $("ram-text").textContent =
556
- `${formatBytes(host.memory.used)} / ${formatBytes(host.memory.total)}`;
557
- meter("ram-bar", ramUsed);
558
- $("ram-note").textContent = redis.connected
559
- ? t("host.ramShared", { rss: formatBytes(proc.memory.rss) })
560
- : t("host.ramOnly", {
561
- rss: formatBytes(proc.memory.rss),
562
- html: formatBytes(latest.html.bytes),
563
- });
564
-
565
- if (!host.disk) {
566
- $("disk-text").textContent = t("state.unavailable");
567
- meter("disk-bar", 0);
568
- $("disk-note").textContent = t("host.noStats");
569
- return;
570
- }
571
-
572
- const diskUsed = (host.disk.total - host.disk.free) / host.disk.total;
573
- $("disk-text").textContent =
574
- `${formatBytes(host.disk.total - host.disk.free)} / ${formatBytes(host.disk.total)}`;
575
- meter("disk-bar", diskUsed);
576
- // Önbellek diske yazılmıyor; disk build çıktısı ve log için önemli.
577
- $("disk-note").textContent = t("host.diskNote", {
578
- free: formatBytes(host.disk.free),
579
- path: host.disk.path,
580
- });
581
- }
582
-
583
- /**
584
- * @param {string} id
585
- * @param {number} ratio 0–1
586
- */
587
- function meter(id, ratio) {
588
- const bar = $(id);
589
- const percent = Math.max(0, Math.min(100, ratio * 100));
590
- bar.style.width = `${percent}%`;
591
- bar.className = percent >= 90 ? "bad" : percent >= 75 ? "warn" : "";
592
- }
593
-
594
- function renderTable() {
595
- const source = tab === "html" ? latest.html : latest.data;
596
- const thead = $("thead");
597
- const tbody = $("tbody");
598
-
599
- $("listed").textContent =
600
- source.matched > source.entries.length
601
- ? t("entries.shownPartial", { shown: source.entries.length, total: source.matched })
602
- : t("entries.shown", { total: source.matched });
603
-
604
- const columns =
605
- tab === "html"
606
- ? [
607
- ["entries.key"],
608
- ["entries.state"],
609
- ["entries.size", "num"],
610
- ["entries.status", "num"],
611
- ["entries.expires", "num"],
612
- ["entries.deps", "num"],
613
- ["entries.encodings"],
614
- [null],
615
- ]
616
- : [["entries.key"], ["entries.state"], ["entries.expires", "num"], [null]];
617
-
618
- const headRow = document.createElement("tr");
619
- for (const [key, className] of columns) {
620
- const th = document.createElement("th");
621
- if (className) th.className = className;
622
- if (key) th.textContent = t(key);
623
- headRow.append(th);
624
- }
625
- thead.replaceChildren(headRow);
626
-
627
- tbody.replaceChildren(
628
- ...source.entries.map((/** @type {any} */ entry) => row(entry)),
629
- );
630
-
631
- $("empty").hidden = source.entries.length > 0;
632
- }
633
-
634
- /**
635
- * @param {any} entry
636
- * @returns {HTMLTableRowElement}
637
- */
638
- function row(entry) {
639
- const tr = document.createElement("tr");
640
-
641
- const key = document.createElement("td");
642
- key.className = "key mono";
643
-
644
- if (tab === "html") {
645
- // HTML anahtarı gezilebilir bir yol: yeni sekmede açmak, bir sayfanın
646
- // neden bayat olduğunu anlamanın en kısa yolu. `noreferrer` panelin
647
- // yolunu `Referer` başlığıyla sızdırmamak için.
648
- const link = document.createElement("a");
649
- link.href = entry.url;
650
- link.target = "_blank";
651
- link.rel = "noreferrer noopener";
652
- link.textContent = entry.url;
653
- key.append(link);
654
- } else {
655
- // Veri anahtarı bir URL değil; tıklamanın işe yarar karşılığı onu
656
- // `clearDataCache()` çağrısına yapıştırabilmek.
657
- const copy = document.createElement("button");
658
- copy.className = "as-text";
659
- copy.type = "button";
660
- copy.title = t("entries.copyKey");
661
- copy.textContent = entry.key;
662
- copy.addEventListener("click", () => void copyKey(entry.key));
663
- key.append(copy);
664
- }
665
-
666
- tr.append(key);
667
-
668
- const state = document.createElement("td");
669
- const tag = document.createElement("span");
670
- tag.className = entry.stale ? "tag stale" : "tag fresh";
671
- tag.textContent = entry.stale ? t("entries.stale") : t("entries.fresh");
672
- state.append(tag);
673
- tr.append(state);
674
-
675
- if (tab === "html") {
676
- tr.append(
677
- cell(formatBytes(entry.bytes), "num"),
678
- cell(String(entry.status), "num"),
679
- cell(entry.stale ? "—" : formatDuration(entry.expiresIn), "num"),
680
- cell(String(entry.deps), "num"),
681
- cell(entry.encodings.length ? entry.encodings.join(", ") : "—"),
682
- );
683
- } else {
684
- tr.append(cell(entry.stale ? "—" : formatDuration(entry.expiresIn), "num"));
685
- }
686
-
687
- const actions = document.createElement("td");
688
- actions.className = "actions";
689
-
690
- // Tek satırı hem origin'den hem edge'den düşürmek en sık istenen çift
691
- // işlem; Cloudflare bağlı değilse düğme hiç çıkmaz.
692
- if (tab === "html" && cloudflare?.ok) {
693
- const purge = document.createElement("button");
694
- purge.className = "tiny";
695
- purge.textContent = t("cf.rowPurge");
696
- purge.title = t("cf.rowPurgeTitle");
697
- purge.addEventListener("click", () => {
698
- void act({ type: "cf:purge-urls", paths: [entry.url] });
699
- });
700
- actions.append(purge);
701
- }
702
-
703
- const drop = document.createElement("button");
704
- drop.className = "tiny danger";
705
- drop.textContent = t("entries.drop");
706
- drop.addEventListener("click", () => {
707
- void act({ type: tab === "html" ? "html:drop" : "data:drop", key: entry.key });
708
- });
709
-
710
- actions.append(drop);
711
- tr.append(actions);
712
-
713
- return tr;
714
- }
715
-
716
- /**
717
- * Panel `http://localhost` dışında da açılabiliyor ve tarayıcı güvensiz
718
- * kaynaklarda pano API'sini vermiyor; o durumda anahtar seçili bırakılır.
719
- *
720
- * @param {string} key
721
- */
722
- async function copyKey(key) {
723
- try {
724
- await navigator.clipboard.writeText(key);
725
- toast(t("toast.keyCopied"));
726
- } catch {
727
- $("prefix").value = key;
728
- $("prefix").focus();
729
- toast(t("toast.clipboard"), false);
730
- }
731
- }
732
-
733
- /**
734
- * @param {string} text
735
- * @param {string} [className]
736
- * @returns {HTMLTableCellElement}
737
- */
738
- function cell(text, className) {
739
- const td = document.createElement("td");
740
- if (className) td.className = className;
741
- td.textContent = text;
742
- return td;
743
- }
744
-
745
- /* ------------------------------------------------------------------ olaylar */
746
-
747
- function startPolling() {
748
- stopPolling();
749
- timer = setInterval(load, REFRESH_MS);
750
- }
751
-
752
- function stopPolling() {
753
- if (timer !== null) clearInterval(timer);
754
- timer = null;
755
- }
756
-
757
- $("auto").addEventListener("change", (event) => {
758
- if (/** @type {HTMLInputElement} */ (event.target).checked) startPolling();
759
- else stopPolling();
760
- });
761
-
762
- $("refresh").addEventListener("click", () => void load());
763
-
764
- $("logout").addEventListener("click", async () => {
765
- stopPolling();
766
- await fetch("logout", { method: "POST" });
767
- location.reload();
768
- });
769
-
770
- // Arama her tuşta sunucuya gitmez: on binlerce anahtarlı bir önbellekte
771
- // filtreleme sunucuda yapılıyor.
772
- let searchTimer = 0;
773
- $("search").addEventListener("input", (event) => {
774
- query = /** @type {HTMLInputElement} */ (event.target).value;
775
- clearTimeout(searchTimer);
776
- searchTimer = setTimeout(load, 200);
777
- });
778
-
779
- for (const name of /** @type {const} */ (["html", "data"])) {
780
- $(`tab-${name}`).addEventListener("click", () => {
781
- tab = name;
782
- $("tab-html").setAttribute("aria-selected", String(name === "html"));
783
- $("tab-data").setAttribute("aria-selected", String(name === "data"));
784
- renderTable();
785
- });
786
- }
787
-
788
- $("invalidate").addEventListener("click", () => {
789
- const target = $("target").value.trim();
790
- if (!target) {
791
- toast(t("toast.needTarget"), false);
792
- return;
793
- }
794
-
795
- void act({ type: "html:invalidate", target, hard: $("hard").checked });
796
- });
797
-
798
- $("clear-html").addEventListener("click", () => {
799
- if (!confirm(t("confirm.clearHtml"))) return;
800
- void act({ type: "html:clear" });
801
- });
802
-
803
- $("clear-data").addEventListener("click", () => {
804
- const prefix = $("prefix").value.trim();
805
- if (!prefix && !confirm(t("confirm.clearData"))) {
806
- return;
807
- }
808
-
809
- void act({ type: "data:clear", prefix });
810
- });
811
-
812
- $("prewarm").addEventListener("click", () => void act({ type: "prewarm" }));
813
-
814
- // Sayım ayrı bir düğme: her döküm turunda tüm keyspace'i taramak Redis'i
815
- // teşhis uğruna yormak olurdu.
816
- $("redis-inspect").addEventListener("click", () => void act({ type: "redis:inspect" }));
817
-
818
- $("redis-html").addEventListener("click", () =>
819
- void act({ type: "redis:drop", kind: "html" }),
820
- );
821
-
822
- $("redis-data").addEventListener("click", () =>
823
- void act({ type: "redis:drop", kind: "data" }),
824
- );
825
-
826
- /* ------------------------------------------------- cloudflare kontrolleri */
827
-
828
- $("cf-refresh").addEventListener("click", () => void loadCloudflare(true));
829
-
830
- $("cf-purge-all").addEventListener("click", () => {
831
- if (!confirm(t("confirm.purgeAll"))) return;
832
- void act({ type: "cf:purge-everything" });
833
- });
834
-
835
- // Bu kurulumda sıcak olan yollar zaten biliniyor; "her şeyi düşür" yerine
836
- // yalnızca gerçekten servis edilen sayfaları düşürmek edge'i boşa soğutmaz.
837
- $("cf-purge-cached").addEventListener("click", () => {
838
- const paths = (latest?.html.entries ?? []).map((/** @type {any} */ entry) => entry.url);
839
- if (!paths.length) {
840
- toast(t("toast.noCachedPages"), false);
841
- return;
842
- }
843
-
844
- if (!confirm(t("confirm.purgeUrls", { count: paths.length }))) return;
845
- void act({ type: "cf:purge-urls", paths });
846
- });
847
-
848
- $("cf-purge-keys").addEventListener("click", () => {
849
- const values = $("cf-values").value.trim();
850
- if (!values) {
851
- toast(t("toast.needValue"), false);
852
- return;
853
- }
854
-
855
- void act({ type: "cf:purge-keys", kind: $("cf-kind").value, values });
856
- });
857
-
858
- $("cf-dev").addEventListener("change", (event) => {
859
- const on = /** @type {HTMLInputElement} */ (event.target).checked;
860
- void act({ type: "cf:setting", id: "development_mode", value: on ? "on" : "off" });
861
- });
862
-
863
- $("cf-tiered").addEventListener("click", () => {
864
- const current = cloudflare?.settings?.tieredCaching;
865
- void act({ type: "cf:feature", feature: "tiered_caching", value: flip(current) });
866
- });
867
-
868
- $("cf-reserve").addEventListener("click", () => {
869
- const current = cloudflare?.settings?.cacheReserve;
870
- void act({ type: "cf:feature", feature: "cache_reserve", value: flip(current) });
871
- });
872
-
873
- $("cf-reserve-clear").addEventListener("click", () => {
874
- if (!confirm(t("confirm.clearReserve"))) return;
875
- void act({ type: "cf:clear-reserve" });
876
- });
877
-
878
- $("cf-analytics").addEventListener("click", () => void loadCloudflareAnalytics());
879
-
880
- /**
881
- * @param {string | null | undefined} value
882
- * @returns {"on" | "off"}
883
- */
884
- function flip(value) {
885
- return value === "on" ? "off" : "on";
886
- }
887
-
888
- // Sekme arkaya alındığında yoklama durur: panel açık kalmış bir sekmede
889
- // dakikalarca boşa istek atmasın.
890
- document.addEventListener("visibilitychange", () => {
891
- if (document.hidden) stopPolling();
892
- else if ($("auto").checked) {
893
- void load();
894
- startPolling();
895
- }
896
- });
897
-
898
- /* -------------------------------------------------------------------- dil */
899
-
900
- // Dil değişimi hiçbir isteğe yol açmaz: statik metinler sözlükten yeniden
901
- // yazılır, dinamik olanlar elde duran son dökümle tekrar çizilir.
902
- $("language").append(
903
- languageSelect(() => {
904
- applyTranslations();
905
- if (latest) render();
906
- renderCloudflare();
907
- renderReport();
908
- }),
909
- );
910
-
911
- applyTranslations();
912
-
913
- void load();
914
- void loadCloudflare();
915
- startPolling();
1
+ /**
2
+ * Admin panelinin istemci tarafı.
3
+ *
4
+ * Build hattından geçmez, doğrudan diskten servis edilir: panelin açık olduğu
5
+ * bir kurulumda `jskelet build` hiç koşmamış olabilir ve panel yine çalışmalı.
6
+ * Bu yüzden burada import edilen bir framework modülü yok.
7
+ *
8
+ * Yenileme WebSocket değil, kısa aralıklı `fetch` ile: panel nadiren ve kısa
9
+ * süre açık kalıyor, kalıcı bir kanal açmanın karşılığı yok. Log sayfası
10
+ * ayrıca SSE kullanır.
11
+ *
12
+ * Bütün görünen metin `i18n.js` üzerinden geçiyor; sunucudan gelen cevaplar da
13
+ * metin değil `code` taşıyor, yani dil değişimi tek yerden hallediliyor.
14
+ */
15
+ import { applyTranslations, languageSelect, t } from "./i18n.js";
16
+
17
+ const REFRESH_MS = 3000;
18
+ const PAGES = new Set(["overview", "cache", "routes", "views", "logs", "system"]);
19
+
20
+ const $ = (/** @type {string} */ id) => document.getElementById(id);
21
+
22
+ /** @type {"html" | "data"} */
23
+ let tab = "html";
24
+ let query = "";
25
+ /** @type {any} */
26
+ let latest = null;
27
+ /** @type {number | null} */
28
+ let timer = null;
29
+ let busy = false;
30
+ /** @type {string} */
31
+ let page = "overview";
32
+ /** @type {any} */
33
+ let routesPayload = null;
34
+ /** @type {any} */
35
+ let viewsPayload = null;
36
+ /** @type {any[]} */
37
+ let logBuffer = [];
38
+ /** @type {EventSource | null} */
39
+ let logSource = null;
40
+ let logsPaused = false;
41
+
42
+ /* ------------------------------------------------------------ biçimlendirme */
43
+
44
+ /**
45
+ * @param {number} bytes
46
+ * @returns {string}
47
+ */
48
+ function formatBytes(bytes) {
49
+ if (!bytes) return "0 B";
50
+ const units = ["B", "KB", "MB", "GB"];
51
+ const power = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
52
+ const value = bytes / 1024 ** power;
53
+ return `${value >= 100 || power === 0 ? Math.round(value) : value.toFixed(1)} ${units[power]}`;
54
+ }
55
+
56
+ /**
57
+ * @param {number} seconds
58
+ * @returns {string}
59
+ */
60
+ function formatDuration(seconds) {
61
+ const total = Math.max(0, Math.round(seconds));
62
+ const [s, m, h, d] = [t("unit.second"), t("unit.minute"), t("unit.hour"), t("unit.day")];
63
+
64
+ if (total < 60) return `${total}${s}`;
65
+ if (total < 3600) return `${Math.floor(total / 60)}${m} ${total % 60}${s}`;
66
+ if (total < 86_400) {
67
+ return `${Math.floor(total / 3600)}${h} ${Math.floor((total % 3600) / 60)}${m}`;
68
+ }
69
+ return `${Math.floor(total / 86_400)}${d} ${Math.floor((total % 86_400) / 3600)}${h}`;
70
+ }
71
+
72
+ /**
73
+ * @param {string} message
74
+ * @param {boolean} [ok]
75
+ */
76
+ function toast(message, ok = true) {
77
+ const node = document.createElement("div");
78
+ node.className = ok ? "toast" : "toast bad";
79
+ node.textContent = message;
80
+ $("toast").append(node);
81
+
82
+ setTimeout(() => node.remove(), 5000);
83
+ }
84
+
85
+ /* -------------------------------------------------------------------- veri */
86
+
87
+ /**
88
+ * Sunucu yetkisiz isteklere 404 dönüyor (panelin varlığını doğrulamamak
89
+ * için). Oturum düştüyse sayfa yeniden yüklenir ve giriş formuna dönülür;
90
+ * arka planda dönmeye devam eden bir yoklama, IP'yi kendi kendine
91
+ * yasaklatırdı.
92
+ *
93
+ * @param {Response} response
94
+ * @returns {boolean} İstek işlenebilir mi.
95
+ */
96
+ function alive(response) {
97
+ if (response.status !== 404) return true;
98
+
99
+ stopPolling();
100
+ location.reload();
101
+ return false;
102
+ }
103
+
104
+ async function load() {
105
+ if (busy) return;
106
+ busy = true;
107
+
108
+ try {
109
+ const response = await fetch(`data?q=${encodeURIComponent(query)}`, {
110
+ headers: { Accept: "application/json" },
111
+ });
112
+ if (!alive(response)) return;
113
+ if (!response.ok) return;
114
+
115
+ latest = await response.json();
116
+ render();
117
+ } catch {
118
+ // Sunucu yeniden başlıyor olabilir; bir sonraki tur dener.
119
+ } finally {
120
+ busy = false;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * @param {Record<string, unknown>} body
126
+ * @returns {Promise<void>}
127
+ */
128
+ async function act(body) {
129
+ const response = await fetch("action", {
130
+ method: "POST",
131
+ headers: {
132
+ "Content-Type": "application/json",
133
+ // Panelin CSRF freni: çapraz siteden gönderilemeyen bir başlık.
134
+ "X-JSkelet-Admin": "1",
135
+ },
136
+ body: JSON.stringify(body),
137
+ });
138
+
139
+ if (!alive(response)) return;
140
+
141
+ const result = await response.json().catch(() => null);
142
+ toast(describe(result), result?.ok !== false);
143
+ await load();
144
+
145
+ // Cloudflare ayarları değişmiş olabilir; genel bakış önbelleği atlanır.
146
+ if (String(body.type ?? "").startsWith("cf:")) await loadCloudflare(true);
147
+ }
148
+
149
+ /**
150
+ * Sunucu cevabını metne çevirir.
151
+ *
152
+ * `/action` dil taşımıyor: `{ ok, code, params }` dönüyor ve cümle burada
153
+ * kuruluyor. Redis sayımı gibi parçalı cevaplar `parts` ile geliyor, çünkü
154
+ * "veritabanında kaç anahtar var" bilgisi her zaman okunamıyor ve eksik parçayı
155
+ * cümleden düşürmek tek düzgün yol.
156
+ *
157
+ * @param {any} result
158
+ * @returns {string}
159
+ */
160
+ function describe(result) {
161
+ if (!result) return t("toast.failed");
162
+
163
+ if (Array.isArray(result.parts)) {
164
+ const parts = result.parts
165
+ .map((/** @type {any} */ part) => t(`msg.${part.code}`, part.params))
166
+ .filter(Boolean);
167
+ if (parts.length) return parts.join(" · ");
168
+ }
169
+
170
+ if (result.code) return t(`msg.${result.code}`, result.params);
171
+ return t(result.ok ? "toast.done" : "toast.failed");
172
+ }
173
+
174
+ /* ------------------------------------------------------------------- çizim */
175
+
176
+ function render() {
177
+ if (!latest) return;
178
+
179
+ const { process: proc, release, host, html, data, redis, prewarm } = latest;
180
+
181
+ $("version").textContent = `v${release.version}`;
182
+ $("foot-release").textContent = [
183
+ `v${release.version}`,
184
+ release.license,
185
+ release.node ? `Node ${release.node}` : null,
186
+ ]
187
+ .filter(Boolean)
188
+ .join(" · ");
189
+ if (release.homepage) $("foot-repo").href = release.homepage;
190
+
191
+ $("env").textContent = proc.env;
192
+ $("pid").textContent = `pid ${proc.pid}`;
193
+ $("uptime").textContent = t("chip.up", { value: formatDuration(proc.uptime) });
194
+ $("memory").textContent = `rss ${formatBytes(proc.memory.rss)}`;
195
+
196
+ $("html-size").textContent = html.size.toLocaleString();
197
+ $("html-sub").textContent = t("card.limit", { count: html.maxEntries.toLocaleString() });
198
+ $("html-bytes").textContent = formatBytes(html.bytes);
199
+ $("html-stale").textContent = t("card.stale", { count: html.stale });
200
+
201
+ $("data-size").textContent = data.size.toLocaleString();
202
+ $("data-sub").textContent = t("card.staleAndLimit", {
203
+ stale: data.stale,
204
+ limit: data.maxEntries.toLocaleString(),
205
+ });
206
+
207
+ const redisState = !redis.enabled
208
+ ? "off"
209
+ : redis.bypassed
210
+ ? "bypassed"
211
+ : redis.connected
212
+ ? "connected"
213
+ : "disconnected";
214
+
215
+ $("redis-state").textContent = t(`state.${redisState}`);
216
+ $("redis-sub").textContent = redis.enabled
217
+ ? t("redis.sub", { address: redis.address, errors: redis.errors })
218
+ : t("redis.disabled");
219
+
220
+ renderRedis(redis, redisState);
221
+ renderHost(host, proc, redis);
222
+ renderUpstream(latest.upstream);
223
+
224
+ const done = prewarm.done ?? 0;
225
+ const total = prewarm.total ?? 0;
226
+ $("prewarm-state").textContent = prewarm.active ? `${done}/${total}` : t("state.idle");
227
+ $("prewarm-sub").textContent = prewarm.active
228
+ ? t("prewarm.inProgress")
229
+ : total
230
+ ? t("prewarm.lastRound", { done, total })
231
+ : t("prewarm.never");
232
+
233
+ renderTable();
234
+ }
235
+
236
+ /**
237
+ * @param {any} upstream
238
+ */
239
+ function renderUpstream(upstream) {
240
+ const tbody = $("upstream-tbody");
241
+ const empty = $("upstream-empty");
242
+ const heading = $("upstream-heading");
243
+ if (!tbody || !empty || !heading) return;
244
+
245
+ const hosts = Array.isArray(upstream) ? upstream : [];
246
+ heading.textContent = String(hosts.length);
247
+ tbody.replaceChildren();
248
+
249
+ if (!hosts.length) {
250
+ empty.hidden = false;
251
+ return;
252
+ }
253
+
254
+ empty.hidden = true;
255
+ for (const info of hosts) {
256
+ const row = document.createElement("tr");
257
+ const state = info?.bypassed
258
+ ? "bypassed"
259
+ : info?.blockedMs > 0
260
+ ? "blocked"
261
+ : `${info?.active ?? 0} active`;
262
+ row.innerHTML = `<td class="mono">${escapeHtml(String(info.host ?? ""))}</td><td class="mono">${escapeHtml(String(info.rate ?? "—"))}</td><td class="mono">${escapeHtml(String(state))}</td>`;
263
+ tbody.append(row);
264
+ }
265
+ }
266
+
267
+ /**
268
+ * @param {string} value
269
+ * @returns {string}
270
+ */
271
+ function escapeHtml(value) {
272
+ return value
273
+ .replaceAll("&", "&amp;")
274
+ .replaceAll("<", "&lt;")
275
+ .replaceAll(">", "&gt;")
276
+ .replaceAll('"', "&quot;");
277
+ }
278
+
279
+ /* ------------------------------------------------------------- cloudflare */
280
+
281
+ /** @type {any} */
282
+ let cloudflare = null;
283
+
284
+ /**
285
+ * Cloudflare genel bakışı ayrı bir uçtan gelir: zone bilgisi ve ayarlar ağa
286
+ * çıkıyor, döküm turu ise saniyeler mertebesinde yenileniyor. Bu yüzden
287
+ * yalnızca açılışta ve bir işlemden sonra istenir.
288
+ *
289
+ * @param {boolean} [force]
290
+ */
291
+ async function loadCloudflare(force = false) {
292
+ const response = await fetch(`cloudflare${force ? "?force=1" : ""}`);
293
+ if (!alive(response)) return;
294
+
295
+ cloudflare = await response.json().catch(() => null);
296
+ renderCloudflare();
297
+ }
298
+
299
+ function renderCloudflare() {
300
+ if (!cloudflare) return;
301
+
302
+ const ok = cloudflare.ok === true;
303
+ const status = cloudflare.status ?? {};
304
+ const settings = cloudflare.settings ?? {};
305
+ const zone = cloudflare.zone ?? null;
306
+
307
+ $("cf-heading").textContent = ok
308
+ ? [zone?.name, zone?.plan].filter(Boolean).join(" · ") || t("state.connected")
309
+ : status.configured
310
+ ? t("cf.error", { error: cloudflare.error })
311
+ : t("cf.notConnected");
312
+
313
+ $("cf-tools").hidden = !ok;
314
+ $("cf-suggest").hidden = ok || status.configured;
315
+ $("cf-refresh").hidden = !status.configured;
316
+
317
+ if (!ok) {
318
+ $("cf-kv").replaceChildren();
319
+ return;
320
+ }
321
+
322
+ const development = settings.developmentMode === "on";
323
+ $("cf-dev").checked = development;
324
+
325
+ /** @type {[string, string, string?][]} */
326
+ const rows = [
327
+ [t("cf.zone"), `${zone?.name ?? "—"} (${status.zoneId ?? "?"})`],
328
+ [t("cf.plan"), zone?.plan ?? "—"],
329
+ [
330
+ t("cf.token"),
331
+ status.tokenSource === "env" ? t("cf.token.env") : t("cf.token.config"),
332
+ "on",
333
+ ],
334
+ [
335
+ t("cf.devModeLabel"),
336
+ development
337
+ ? t("cf.devMode.on", { time: formatDuration(settings.developmentModeRemaining) })
338
+ : t("state.off"),
339
+ development ? "bad" : "on",
340
+ ],
341
+ [t("cf.cacheLevel"), String(settings.cacheLevel ?? "—")],
342
+ [t("cf.browserTtl"), ttl(settings.browserCacheTtl)],
343
+ [t("cf.edgeTtl"), ttl(settings.edgeCacheTtl)],
344
+ [t("cf.sortQuery"), String(settings.sortQueryString ?? "—")],
345
+ [t("cf.alwaysOnline"), String(settings.alwaysOnline ?? "—")],
346
+ ...feature(t("cf.tiered"), settings.tieredCaching),
347
+ ...feature(t("cf.regionalTiered"), settings.regionalTieredCache),
348
+ ...feature(t("cf.reserve"), settings.cacheReserve),
349
+ ];
350
+
351
+ $("cf-kv").replaceChildren(...rows.map(kvRow));
352
+ }
353
+
354
+ /**
355
+ * Plan dışı kalan bir özellik `null` döner. "off" yazmak yanıltıcı olurdu:
356
+ * kapatılmış değil, o planda hiç yok.
357
+ *
358
+ * @param {string} label
359
+ * @param {string | null} value
360
+ * @returns {[string, string, string?][]}
361
+ */
362
+ function feature(label, value) {
363
+ if (value === null || value === undefined) {
364
+ return [[label, t("cf.unavailablePlan"), "off"]];
365
+ }
366
+ const on = value === "on";
367
+ return [[label, on ? t("state.on") : t("state.off"), on ? "on" : "off"]];
368
+ }
369
+
370
+ /**
371
+ * @param {unknown} seconds
372
+ * @returns {string}
373
+ */
374
+ function ttl(seconds) {
375
+ const value = Number(seconds);
376
+ if (!Number.isFinite(value)) return "—";
377
+ // Cloudflare 0'ı "Respect Existing Headers" olarak kullanıyor.
378
+ if (value === 0) return t("cf.respectOrigin");
379
+ return formatDuration(value);
380
+ }
381
+
382
+ /**
383
+ * @param {[string, string, string?]} row
384
+ * @returns {HTMLDivElement}
385
+ */
386
+ function kvRow([label, value, tone]) {
387
+ const wrap = document.createElement("div");
388
+ const dt = document.createElement("dt");
389
+ dt.textContent = label;
390
+ const dd = document.createElement("dd");
391
+ if (tone) dd.className = tone;
392
+ dd.textContent = value;
393
+ wrap.append(dt, dd);
394
+ return wrap;
395
+ }
396
+
397
+ /**
398
+ * Analitik dökümü. İki soru tek uçtan cevaplanıyor: yol verilirse kolo
399
+ * kırılımı, verilmezse zone genelinde cache durumu dağılımı.
400
+ */
401
+ async function loadCloudflareAnalytics() {
402
+ const path = $("cf-path").value.trim();
403
+ const target = $("cf-report");
404
+
405
+ target.hidden = false;
406
+ target.textContent = t("cf.querying");
407
+
408
+ const response = await fetch("cloudflare/analytics", {
409
+ method: "POST",
410
+ headers: {
411
+ "Content-Type": "application/json",
412
+ "X-JSkelet-Admin": "1",
413
+ },
414
+ body: JSON.stringify({ path }),
415
+ });
416
+
417
+ if (!alive(response)) return;
418
+
419
+ const result = await response.json().catch(() => null);
420
+
421
+ if (!result?.ok) {
422
+ target.textContent = t("msg.cf.failed", { error: result?.error ?? t("cf.queryFailed") });
423
+ return;
424
+ }
425
+
426
+ // Son dökümü dil değişiminde yeniden kurmak için saklanır: tablo ağdan
427
+ // geliyor ve dil değişti diye Cloudflare'e yeniden gitmek gereksiz.
428
+ lastReport = result;
429
+ renderReport();
430
+ }
431
+
432
+ /** @type {any} */
433
+ let lastReport = null;
434
+
435
+ function renderReport() {
436
+ if (!lastReport) return;
437
+ const result = lastReport;
438
+
439
+ $("cf-report").replaceChildren(
440
+ result.colos ? edgeTable(result) : statusTable(result),
441
+ note(
442
+ result.colos
443
+ ? t("cf.edgeNote", {
444
+ colos: result.colos.length,
445
+ path: result.path,
446
+ hours: result.hours,
447
+ hits: result.hits,
448
+ misses: result.misses,
449
+ })
450
+ : t("cf.zoneNote", { hours: result.hours }),
451
+ ),
452
+ );
453
+ }
454
+
455
+ /**
456
+ * @param {any} result
457
+ * @returns {HTMLTableElement}
458
+ */
459
+ function edgeTable(result) {
460
+ return buildTable(
461
+ [t("cf.colo"), t("cf.fromCache"), t("cf.toOrigin")],
462
+ result.colos.map((/** @type {any} */ row) => [
463
+ row.colo,
464
+ String(row.hits),
465
+ String(row.misses),
466
+ ]),
467
+ );
468
+ }
469
+
470
+ /**
471
+ * @param {any} result
472
+ * @returns {HTMLTableElement}
473
+ */
474
+ function statusTable(result) {
475
+ const total = result.rows.reduce((sum, /** @type {any} */ row) => sum + row.requests, 0) || 1;
476
+
477
+ return buildTable(
478
+ [t("cf.cacheStatus"), t("cf.requests"), t("cf.share"), t("cf.edgeBytes")],
479
+ result.rows.map((/** @type {any} */ row) => [
480
+ row.status,
481
+ row.requests.toLocaleString(),
482
+ `${Math.round((row.requests / total) * 100)}%`,
483
+ formatBytes(row.bytes),
484
+ ]),
485
+ );
486
+ }
487
+
488
+ /**
489
+ * @param {string[]} headers
490
+ * @param {string[][]} rows
491
+ * @returns {HTMLTableElement}
492
+ */
493
+ function buildTable(headers, rows) {
494
+ const table = document.createElement("table");
495
+ const thead = document.createElement("thead");
496
+ const headRow = document.createElement("tr");
497
+
498
+ headers.forEach((label, index) => {
499
+ const th = document.createElement("th");
500
+ th.textContent = label;
501
+ if (index > 0) th.className = "num";
502
+ headRow.append(th);
503
+ });
504
+
505
+ thead.append(headRow);
506
+
507
+ const tbody = document.createElement("tbody");
508
+ for (const row of rows) {
509
+ const tr = document.createElement("tr");
510
+ row.forEach((value, index) => tr.append(cell(value, index > 0 ? "num" : undefined)));
511
+ tbody.append(tr);
512
+ }
513
+
514
+ table.append(thead, tbody);
515
+ return table;
516
+ }
517
+
518
+ /**
519
+ * @param {string} text
520
+ * @returns {HTMLParagraphElement}
521
+ */
522
+ function note(text) {
523
+ const paragraph = document.createElement("p");
524
+ paragraph.className = "note m0";
525
+ paragraph.textContent = text;
526
+ return paragraph;
527
+ }
528
+
529
+ /**
530
+ * Paylaşımlı kademenin künyesi.
531
+ *
532
+ * "Bağlı mı" tek başına yetmiyor: yanlış `namespace` ya da beklenmeyen bir
533
+ * `buildId` ile bağlı bir Redis de hiçbir şey paylaşmıyor gibi görünür. Bu
534
+ * yüzden anahtarın **nerede** durduğu ve hangi türlerin paylaşıldığı da
535
+ * yazılır.
536
+ *
537
+ * @param {any} redis
538
+ * @param {string} state
539
+ */
540
+ function renderRedis(redis, state) {
541
+ $("redis-heading").textContent = redis.enabled ? t(`state.${state}`) : t("state.notConfigured");
542
+ $("redis-actions").hidden = !redis.enabled;
543
+ $("redis-suggest").hidden = redis.enabled;
544
+
545
+ /** @type {[string, string, string?][]} */
546
+ const rows = redis.enabled
547
+ ? [
548
+ [
549
+ t("redis.connection"),
550
+ t(`state.${state}`),
551
+ redis.connected && !redis.bypassed ? "on" : "bad",
552
+ ],
553
+ [t("redis.address"), `${redis.address}${redis.secure ? " (TLS)" : ""}`],
554
+ [t("redis.database"), redis.db ?? t("state.default")],
555
+ [t("redis.keyPrefix"), `${redis.keyPrefix}:${redis.namespace}`],
556
+ [t("redis.buildId"), redis.buildId || "dev"],
557
+ [
558
+ t("redis.sharesHtml"),
559
+ redis.html ? t("state.yes") : t("state.no"),
560
+ redis.html ? "on" : "off",
561
+ ],
562
+ [
563
+ t("redis.sharesData"),
564
+ redis.data ? t("state.yes") : t("state.no"),
565
+ redis.data ? "on" : "off",
566
+ ],
567
+ [
568
+ t("redis.compressed"),
569
+ redis.storeEncoded ? t("redis.compressed.shared") : t("redis.compressed.local"),
570
+ redis.storeEncoded ? "on" : "off",
571
+ ],
572
+ [
573
+ t("redis.broadcast"),
574
+ redis.events
575
+ ? redis.subscribed
576
+ ? t("redis.broadcast.subscribed")
577
+ : t("redis.broadcast.publish")
578
+ : t("state.off"),
579
+ redis.events && redis.subscribed ? "on" : "off",
580
+ ],
581
+ [t("redis.timeout"), `${redis.commandTimeoutMs} ${t("unit.ms")}`],
582
+ [t("redis.errors"), String(redis.errors), redis.errors ? "bad" : "on"],
583
+ ]
584
+ : [
585
+ [t("redis.tier"), t("redis.tier.inProcess")],
586
+ [t("redis.replicas"), t("state.none")],
587
+ [t("redis.broadcast"), t("redis.broadcast.local"), "off"],
588
+ ];
589
+
590
+ $("redis-kv").replaceChildren(...rows.map(kvRow));
591
+ }
592
+
593
+ /**
594
+ * Makinenin RAM ve disk durumu. Paylaşımlı kademe kapalıyken önbelleğin
595
+ * tamamı bu sürecin belleğinde yaşıyor; `maxEntries` ile RAM arasındaki
596
+ * ilişkiyi görmeden ayar yapmak körlemesine oluyor.
597
+ *
598
+ * @param {any} host
599
+ * @param {any} proc
600
+ * @param {any} redis
601
+ */
602
+ function renderHost(host, proc, redis) {
603
+ $("host-heading").textContent = [
604
+ host.platform,
605
+ `${host.cpus} cpu`,
606
+ host.load ? `load ${host.load.toFixed(2)}` : null,
607
+ ]
608
+ .filter(Boolean)
609
+ .join(" · ");
610
+
611
+ const ramUsed = host.memory.used / host.memory.total;
612
+ $("ram-text").textContent =
613
+ `${formatBytes(host.memory.used)} / ${formatBytes(host.memory.total)}`;
614
+ meter("ram-bar", ramUsed);
615
+ $("ram-note").textContent = redis.connected
616
+ ? t("host.ramShared", { rss: formatBytes(proc.memory.rss) })
617
+ : t("host.ramOnly", {
618
+ rss: formatBytes(proc.memory.rss),
619
+ html: formatBytes(latest.html.bytes),
620
+ });
621
+
622
+ if (!host.disk) {
623
+ $("disk-text").textContent = t("state.unavailable");
624
+ meter("disk-bar", 0);
625
+ $("disk-note").textContent = t("host.noStats");
626
+ return;
627
+ }
628
+
629
+ const diskUsed = (host.disk.total - host.disk.free) / host.disk.total;
630
+ $("disk-text").textContent =
631
+ `${formatBytes(host.disk.total - host.disk.free)} / ${formatBytes(host.disk.total)}`;
632
+ meter("disk-bar", diskUsed);
633
+ // Önbellek diske yazılmıyor; disk build çıktısı ve log için önemli.
634
+ $("disk-note").textContent = t("host.diskNote", {
635
+ free: formatBytes(host.disk.free),
636
+ path: host.disk.path,
637
+ });
638
+ }
639
+
640
+ /**
641
+ * @param {string} id
642
+ * @param {number} ratio 0–1
643
+ */
644
+ function meter(id, ratio) {
645
+ const bar = $(id);
646
+ const percent = Math.max(0, Math.min(100, ratio * 100));
647
+ bar.style.width = `${percent}%`;
648
+ bar.className = percent >= 90 ? "bad" : percent >= 75 ? "warn" : "";
649
+ }
650
+
651
+ function renderTable() {
652
+ const source = tab === "html" ? latest.html : latest.data;
653
+ const thead = $("thead");
654
+ const tbody = $("tbody");
655
+
656
+ $("listed").textContent =
657
+ source.matched > source.entries.length
658
+ ? t("entries.shownPartial", { shown: source.entries.length, total: source.matched })
659
+ : t("entries.shown", { total: source.matched });
660
+
661
+ const columns =
662
+ tab === "html"
663
+ ? [
664
+ ["entries.key"],
665
+ ["entries.state"],
666
+ ["entries.size", "num"],
667
+ ["entries.status", "num"],
668
+ ["entries.expires", "num"],
669
+ ["entries.deps", "num"],
670
+ ["entries.encodings"],
671
+ [null],
672
+ ]
673
+ : [["entries.key"], ["entries.state"], ["entries.expires", "num"], [null]];
674
+
675
+ const headRow = document.createElement("tr");
676
+ for (const [key, className] of columns) {
677
+ const th = document.createElement("th");
678
+ if (className) th.className = className;
679
+ if (key) th.textContent = t(key);
680
+ headRow.append(th);
681
+ }
682
+ thead.replaceChildren(headRow);
683
+
684
+ tbody.replaceChildren(
685
+ ...source.entries.map((/** @type {any} */ entry) => row(entry)),
686
+ );
687
+
688
+ $("empty").hidden = source.entries.length > 0;
689
+ }
690
+
691
+ /**
692
+ * @param {any} entry
693
+ * @returns {HTMLTableRowElement}
694
+ */
695
+ function row(entry) {
696
+ const tr = document.createElement("tr");
697
+
698
+ const key = document.createElement("td");
699
+ key.className = "key mono";
700
+
701
+ if (tab === "html") {
702
+ // HTML anahtarı gezilebilir bir yol: yeni sekmede açmak, bir sayfanın
703
+ // neden bayat olduğunu anlamanın en kısa yolu. `noreferrer` panelin
704
+ // yolunu `Referer` başlığıyla sızdırmamak için.
705
+ const link = document.createElement("a");
706
+ link.href = entry.url;
707
+ link.target = "_blank";
708
+ link.rel = "noreferrer noopener";
709
+ link.textContent = entry.url;
710
+ key.append(link);
711
+ } else {
712
+ // Veri anahtarı bir URL değil; tıklamanın işe yarar karşılığı onu
713
+ // `clearDataCache()` çağrısına yapıştırabilmek.
714
+ const copy = document.createElement("button");
715
+ copy.className = "as-text";
716
+ copy.type = "button";
717
+ copy.title = t("entries.copyKey");
718
+ copy.textContent = entry.key;
719
+ copy.addEventListener("click", () => void copyKey(entry.key));
720
+ key.append(copy);
721
+ }
722
+
723
+ tr.append(key);
724
+
725
+ const state = document.createElement("td");
726
+ const tag = document.createElement("span");
727
+ tag.className = entry.stale ? "tag stale" : "tag fresh";
728
+ tag.textContent = entry.stale ? t("entries.stale") : t("entries.fresh");
729
+ state.append(tag);
730
+ tr.append(state);
731
+
732
+ if (tab === "html") {
733
+ tr.append(
734
+ cell(formatBytes(entry.bytes), "num"),
735
+ cell(String(entry.status), "num"),
736
+ cell(entry.stale ? "—" : formatDuration(entry.expiresIn), "num"),
737
+ cell(String(entry.deps), "num"),
738
+ cell(entry.encodings.length ? entry.encodings.join(", ") : "—"),
739
+ );
740
+ } else {
741
+ tr.append(cell(entry.stale ? "—" : formatDuration(entry.expiresIn), "num"));
742
+ }
743
+
744
+ const actions = document.createElement("td");
745
+ actions.className = "actions";
746
+
747
+ // Tek satırı hem origin'den hem edge'den düşürmek en sık istenen çift
748
+ // işlem; Cloudflare bağlı değilse düğme hiç çıkmaz.
749
+ if (tab === "html" && cloudflare?.ok) {
750
+ const purge = document.createElement("button");
751
+ purge.className = "tiny";
752
+ purge.textContent = t("cf.rowPurge");
753
+ purge.title = t("cf.rowPurgeTitle");
754
+ purge.addEventListener("click", () => {
755
+ void act({ type: "cf:purge-urls", paths: [entry.url] });
756
+ });
757
+ actions.append(purge);
758
+ }
759
+
760
+ const drop = document.createElement("button");
761
+ drop.className = "tiny danger";
762
+ drop.textContent = t("entries.drop");
763
+ drop.addEventListener("click", () => {
764
+ void act({ type: tab === "html" ? "html:drop" : "data:drop", key: entry.key });
765
+ });
766
+
767
+ actions.append(drop);
768
+ tr.append(actions);
769
+
770
+ return tr;
771
+ }
772
+
773
+ /**
774
+ * Panel `http://localhost` dışında da açılabiliyor ve tarayıcı güvensiz
775
+ * kaynaklarda pano API'sini vermiyor; o durumda anahtar seçili bırakılır.
776
+ *
777
+ * @param {string} key
778
+ */
779
+ async function copyKey(key) {
780
+ try {
781
+ await navigator.clipboard.writeText(key);
782
+ toast(t("toast.keyCopied"));
783
+ } catch {
784
+ $("prefix").value = key;
785
+ $("prefix").focus();
786
+ toast(t("toast.clipboard"), false);
787
+ }
788
+ }
789
+
790
+ /**
791
+ * @param {string} text
792
+ * @param {string} [className]
793
+ * @returns {HTMLTableCellElement}
794
+ */
795
+ function cell(text, className) {
796
+ const td = document.createElement("td");
797
+ if (className) td.className = className;
798
+ td.textContent = text;
799
+ return td;
800
+ }
801
+
802
+ /* ------------------------------------------------------------------ olaylar */
803
+
804
+ function startPolling() {
805
+ stopPolling();
806
+ timer = setInterval(load, REFRESH_MS);
807
+ }
808
+
809
+ function stopPolling() {
810
+ if (timer !== null) clearInterval(timer);
811
+ timer = null;
812
+ }
813
+
814
+ $("auto").addEventListener("change", (event) => {
815
+ if (/** @type {HTMLInputElement} */ (event.target).checked) startPolling();
816
+ else stopPolling();
817
+ });
818
+
819
+ $("refresh").addEventListener("click", () => void load());
820
+
821
+ $("logout").addEventListener("click", async () => {
822
+ stopPolling();
823
+ await fetch("logout", { method: "POST" });
824
+ location.reload();
825
+ });
826
+
827
+ // Arama her tuşta sunucuya gitmez: on binlerce anahtarlı bir önbellekte
828
+ // filtreleme sunucuda yapılıyor.
829
+ let searchTimer = 0;
830
+ $("search").addEventListener("input", (event) => {
831
+ query = /** @type {HTMLInputElement} */ (event.target).value;
832
+ clearTimeout(searchTimer);
833
+ searchTimer = setTimeout(load, 200);
834
+ });
835
+
836
+ for (const name of /** @type {const} */ (["html", "data"])) {
837
+ $(`tab-${name}`).addEventListener("click", () => {
838
+ tab = name;
839
+ $("tab-html").setAttribute("aria-selected", String(name === "html"));
840
+ $("tab-data").setAttribute("aria-selected", String(name === "data"));
841
+ renderTable();
842
+ });
843
+ }
844
+
845
+ $("invalidate").addEventListener("click", () => {
846
+ const target = $("target").value.trim();
847
+ if (!target) {
848
+ toast(t("toast.needTarget"), false);
849
+ return;
850
+ }
851
+
852
+ void act({ type: "html:invalidate", target, hard: $("hard").checked });
853
+ });
854
+
855
+ $("clear-html").addEventListener("click", () => {
856
+ if (!confirm(t("confirm.clearHtml"))) return;
857
+ void act({ type: "html:clear" });
858
+ });
859
+
860
+ $("clear-data").addEventListener("click", () => {
861
+ const prefix = $("prefix").value.trim();
862
+ if (!prefix && !confirm(t("confirm.clearData"))) {
863
+ return;
864
+ }
865
+
866
+ void act({ type: "data:clear", prefix });
867
+ });
868
+
869
+ $("prewarm").addEventListener("click", () => void act({ type: "prewarm" }));
870
+
871
+ // Sayım ayrı bir düğme: her döküm turunda tüm keyspace'i taramak Redis'i
872
+ // teşhis uğruna yormak olurdu.
873
+ $("redis-inspect").addEventListener("click", () => void act({ type: "redis:inspect" }));
874
+
875
+ $("redis-html").addEventListener("click", () =>
876
+ void act({ type: "redis:drop", kind: "html" }),
877
+ );
878
+
879
+ $("redis-data").addEventListener("click", () =>
880
+ void act({ type: "redis:drop", kind: "data" }),
881
+ );
882
+
883
+ /* ------------------------------------------------- cloudflare kontrolleri */
884
+
885
+ $("cf-refresh").addEventListener("click", () => void loadCloudflare(true));
886
+
887
+ $("cf-purge-all").addEventListener("click", () => {
888
+ if (!confirm(t("confirm.purgeAll"))) return;
889
+ void act({ type: "cf:purge-everything" });
890
+ });
891
+
892
+ // Bu kurulumda sıcak olan yollar zaten biliniyor; "her şeyi düşür" yerine
893
+ // yalnızca gerçekten servis edilen sayfaları düşürmek edge'i boşa soğutmaz.
894
+ $("cf-purge-cached").addEventListener("click", () => {
895
+ const paths = (latest?.html.entries ?? []).map((/** @type {any} */ entry) => entry.url);
896
+ if (!paths.length) {
897
+ toast(t("toast.noCachedPages"), false);
898
+ return;
899
+ }
900
+
901
+ if (!confirm(t("confirm.purgeUrls", { count: paths.length }))) return;
902
+ void act({ type: "cf:purge-urls", paths });
903
+ });
904
+
905
+ $("cf-purge-keys").addEventListener("click", () => {
906
+ const values = $("cf-values").value.trim();
907
+ if (!values) {
908
+ toast(t("toast.needValue"), false);
909
+ return;
910
+ }
911
+
912
+ void act({ type: "cf:purge-keys", kind: $("cf-kind").value, values });
913
+ });
914
+
915
+ $("cf-dev").addEventListener("change", (event) => {
916
+ const on = /** @type {HTMLInputElement} */ (event.target).checked;
917
+ void act({ type: "cf:setting", id: "development_mode", value: on ? "on" : "off" });
918
+ });
919
+
920
+ $("cf-tiered").addEventListener("click", () => {
921
+ const current = cloudflare?.settings?.tieredCaching;
922
+ void act({ type: "cf:feature", feature: "tiered_caching", value: flip(current) });
923
+ });
924
+
925
+ $("cf-reserve").addEventListener("click", () => {
926
+ const current = cloudflare?.settings?.cacheReserve;
927
+ void act({ type: "cf:feature", feature: "cache_reserve", value: flip(current) });
928
+ });
929
+
930
+ $("cf-reserve-clear").addEventListener("click", () => {
931
+ if (!confirm(t("confirm.clearReserve"))) return;
932
+ void act({ type: "cf:clear-reserve" });
933
+ });
934
+
935
+ $("cf-analytics").addEventListener("click", () => void loadCloudflareAnalytics());
936
+
937
+ /**
938
+ * @param {string | null | undefined} value
939
+ * @returns {"on" | "off"}
940
+ */
941
+ function flip(value) {
942
+ return value === "on" ? "off" : "on";
943
+ }
944
+
945
+ // Sekme arkaya alındığında yoklama durur: panel açık kalmış bir sekmede
946
+ // dakikalarca boşa istek atmasın.
947
+ document.addEventListener("visibilitychange", () => {
948
+ if (document.hidden) {
949
+ stopPolling();
950
+ stopLogStream();
951
+ } else if ($("auto").checked) {
952
+ void load();
953
+ startPolling();
954
+ if (page === "logs") startLogStream();
955
+ }
956
+ });
957
+
958
+ /* -------------------------------------------------------------- sayfalar */
959
+
960
+ /**
961
+ * URL yolunun son segmentinden sayfa adı.
962
+ * @returns {string}
963
+ */
964
+ function pageFromLocation() {
965
+ const parts = location.pathname.replace(/\/+$/, "").split("/");
966
+ const last = parts[parts.length - 1] || "";
967
+ if (PAGES.has(last)) return last;
968
+ return "overview";
969
+ }
970
+
971
+ /**
972
+ * @param {string} next
973
+ * @param {{ push?: boolean }} [options]
974
+ */
975
+ function showPage(next, options = {}) {
976
+ const name = PAGES.has(next) ? next : "overview";
977
+ page = name;
978
+
979
+ for (const node of document.querySelectorAll(".page")) {
980
+ const el = /** @type {HTMLElement} */ (node);
981
+ el.hidden = el.dataset.page !== name;
982
+ }
983
+
984
+ for (const link of document.querySelectorAll("#nav a")) {
985
+ const a = /** @type {HTMLAnchorElement} */ (link);
986
+ if (a.dataset.page === name) a.setAttribute("aria-current", "page");
987
+ else a.removeAttribute("aria-current");
988
+ }
989
+
990
+ const sse = $("sse-status");
991
+ if (sse) sse.hidden = name !== "logs";
992
+
993
+ if (options.push !== false) {
994
+ const target = name === "overview" ? "./" : name;
995
+ history.pushState({ page: name }, "", target);
996
+ }
997
+
998
+ if (name === "routes") void loadRoutes();
999
+ if (name === "views") void loadViews();
1000
+ if (name === "logs") startLogStream();
1001
+ else stopLogStream();
1002
+ }
1003
+
1004
+ async function loadRoutes() {
1005
+ const response = await fetch("api/routes");
1006
+ if (!alive(response)) return;
1007
+ if (!response.ok) return;
1008
+ routesPayload = await response.json();
1009
+ renderRoutes();
1010
+ }
1011
+
1012
+ async function loadViews() {
1013
+ const response = await fetch("api/views");
1014
+ if (!alive(response)) return;
1015
+ if (!response.ok) return;
1016
+ viewsPayload = await response.json();
1017
+ renderViews();
1018
+ }
1019
+
1020
+ function renderRoutes() {
1021
+ if (!routesPayload) return;
1022
+
1023
+ const routes = routesPayload.routes ?? [];
1024
+ const modules = routesPayload.modules ?? [];
1025
+ const activity = routesPayload.activity ?? {};
1026
+
1027
+ $("routes-count").textContent = String(routes.length);
1028
+ $("modules-count").textContent = String(modules.length);
1029
+
1030
+ const tbody = $("routes-tbody");
1031
+ const empty = $("routes-empty");
1032
+ tbody.replaceChildren();
1033
+
1034
+ if (!routes.length) {
1035
+ empty.hidden = false;
1036
+ } else {
1037
+ empty.hidden = true;
1038
+ for (const route of routes) {
1039
+ const key = route.path;
1040
+ const act = activity[key] ?? null;
1041
+ const row = document.createElement("tr");
1042
+ row.innerHTML = `
1043
+ <td class="mono">${escapeHtml(route.method)}</td>
1044
+ <td class="mono"><button type="button" class="linkish" data-path="${escapeHtml(route.path)}">${escapeHtml(route.path)}</button></td>
1045
+ <td class="mono">${act ? act.status : "—"}</td>
1046
+ <td class="mono">${act ? Math.round(act.ms) : "—"}</td>
1047
+ <td class="mono">${act ? act.count : "—"}</td>`;
1048
+ tbody.append(row);
1049
+ }
1050
+
1051
+ tbody.querySelectorAll("button[data-path]").forEach((button) => {
1052
+ button.addEventListener("click", () => {
1053
+ const pathFilter = /** @type {HTMLElement} */ (button).dataset.path ?? "";
1054
+ $("logs-path").value = pathFilter;
1055
+ showPage("logs");
1056
+ renderLogs();
1057
+ });
1058
+ });
1059
+ }
1060
+
1061
+ const modulesBody = $("modules-tbody");
1062
+ modulesBody.replaceChildren();
1063
+ for (const mod of modules) {
1064
+ const row = document.createElement("tr");
1065
+ row.innerHTML = `<td class="mono">${escapeHtml(mod.relative)}</td>`;
1066
+ modulesBody.append(row);
1067
+ }
1068
+ }
1069
+
1070
+ function renderViews() {
1071
+ if (!viewsPayload) return;
1072
+
1073
+ const term = ($("views-search")?.value ?? "").trim().toLowerCase();
1074
+ const views = (viewsPayload.views ?? []).filter(
1075
+ (/** @type {{ relative: string }} */ view) =>
1076
+ !term || view.relative.toLowerCase().includes(term),
1077
+ );
1078
+
1079
+ $("views-count").textContent = String(views.length);
1080
+ const tbody = $("views-tbody");
1081
+ const empty = $("views-empty");
1082
+ tbody.replaceChildren();
1083
+
1084
+ if (!views.length) {
1085
+ empty.hidden = false;
1086
+ return;
1087
+ }
1088
+
1089
+ empty.hidden = true;
1090
+ for (const view of views) {
1091
+ const row = document.createElement("tr");
1092
+ row.innerHTML = `<td class="mono">${escapeHtml(view.relative)}</td><td>${escapeHtml(view.kind)}</td>`;
1093
+ tbody.append(row);
1094
+ }
1095
+ }
1096
+
1097
+ function startLogStream() {
1098
+ if (logSource) return;
1099
+
1100
+ const chip = $("sse-status");
1101
+ if (chip) {
1102
+ chip.hidden = false;
1103
+ chip.textContent = t("chip.sse.live");
1104
+ }
1105
+
1106
+ logSource = new EventSource("api/logs/stream");
1107
+ logSource.onmessage = (event) => {
1108
+ try {
1109
+ const entry = JSON.parse(event.data);
1110
+ if (!logsPaused) {
1111
+ logBuffer.push(entry);
1112
+ if (logBuffer.length > 1000) logBuffer.shift();
1113
+ renderLogs();
1114
+ }
1115
+ } catch {
1116
+ // bozuk çerçeve yok sayılır
1117
+ }
1118
+ };
1119
+ logSource.onerror = () => {
1120
+ if (chip) chip.textContent = t("chip.sse.error");
1121
+ };
1122
+ }
1123
+
1124
+ function stopLogStream() {
1125
+ if (logSource) {
1126
+ logSource.close();
1127
+ logSource = null;
1128
+ }
1129
+ const chip = $("sse-status");
1130
+ if (chip) {
1131
+ chip.textContent = t("chip.sse.off");
1132
+ chip.hidden = page !== "logs";
1133
+ }
1134
+ }
1135
+
1136
+ function renderLogs() {
1137
+ const list = $("logs-list");
1138
+ const empty = $("logs-empty");
1139
+ const count = $("logs-count");
1140
+ if (!list || !empty || !count) return;
1141
+
1142
+ const q = ($("logs-q")?.value ?? "").trim().toLowerCase();
1143
+ const kind = $("logs-kind")?.value ?? "";
1144
+ const method = $("logs-method")?.value ?? "";
1145
+ const statusClass = $("logs-status")?.value ?? "";
1146
+ const cache = $("logs-cache")?.value ?? "";
1147
+ const pathFilter = ($("logs-path")?.value ?? "").trim().toLowerCase();
1148
+
1149
+ const filtered = logBuffer.filter((entry) => {
1150
+ if (kind && entry.kind !== kind) return false;
1151
+ if (method && entry.method !== method) return false;
1152
+ if (statusClass && entry.status != null) {
1153
+ if (String(Math.floor(Number(entry.status) / 100)) !== statusClass) return false;
1154
+ }
1155
+ if (cache && entry.cache !== cache) return false;
1156
+ if (pathFilter) {
1157
+ const hay = `${entry.path ?? ""} ${entry.route ?? ""} ${entry.url ?? ""}`.toLowerCase();
1158
+ if (!hay.includes(pathFilter)) return false;
1159
+ }
1160
+ if (q) {
1161
+ const hay = `${entry.url ?? ""} ${entry.message ?? ""} ${entry.scope ?? ""} ${entry.path ?? ""}`.toLowerCase();
1162
+ if (!hay.includes(q)) return false;
1163
+ }
1164
+ return true;
1165
+ });
1166
+
1167
+ count.textContent = t("logs.shown", { shown: filtered.length, total: logBuffer.length });
1168
+ empty.hidden = filtered.length > 0;
1169
+
1170
+ const lines = filtered.slice(-300).map(formatLogLine);
1171
+ list.textContent = lines.join("\n");
1172
+ list.scrollTop = list.scrollHeight;
1173
+ }
1174
+
1175
+ /**
1176
+ * @param {any} entry
1177
+ * @returns {string}
1178
+ */
1179
+ function formatLogLine(entry) {
1180
+ const time = new Date(entry.at).toISOString().slice(11, 19);
1181
+ if (entry.kind === "http") {
1182
+ const cache = entry.cache ? ` ${entry.cache}` : "";
1183
+ const route = entry.route ? ` [${entry.route}]` : "";
1184
+ return `${time} ${String(entry.method).padEnd(6)} ${entry.status} ${Math.round(entry.ms)}ms${cache}${route} ${entry.url}`;
1185
+ }
1186
+ return `${time} ${entry.kind.padEnd(6)} ${entry.scope ?? ""} ${entry.message ?? ""}${entry.note ? ` ${entry.note}` : ""}`;
1187
+ }
1188
+
1189
+ for (const link of document.querySelectorAll("#nav a")) {
1190
+ link.addEventListener("click", (event) => {
1191
+ event.preventDefault();
1192
+ const next = /** @type {HTMLElement} */ (link).dataset.page ?? "overview";
1193
+ showPage(next);
1194
+ });
1195
+ }
1196
+
1197
+ window.addEventListener("popstate", () => {
1198
+ showPage(pageFromLocation(), { push: false });
1199
+ });
1200
+
1201
+ $("views-search")?.addEventListener("input", () => renderViews());
1202
+
1203
+ for (const id of ["logs-q", "logs-kind", "logs-method", "logs-status", "logs-cache", "logs-path"]) {
1204
+ $(id)?.addEventListener("input", () => renderLogs());
1205
+ $(id)?.addEventListener("change", () => renderLogs());
1206
+ }
1207
+
1208
+ $("logs-pause")?.addEventListener("change", (event) => {
1209
+ logsPaused = /** @type {HTMLInputElement} */ (event.target).checked;
1210
+ });
1211
+
1212
+ $("logs-clear")?.addEventListener("click", () => {
1213
+ logBuffer = [];
1214
+ renderLogs();
1215
+ });
1216
+
1217
+ /* -------------------------------------------------------------------- dil */
1218
+
1219
+ // Dil değişimi hiçbir isteğe yol açmaz: statik metinler sözlükten yeniden
1220
+ // yazılır, dinamik olanlar elde duran son dökümle tekrar çizilir.
1221
+ $("language").append(
1222
+ languageSelect(() => {
1223
+ applyTranslations();
1224
+ if (latest) render();
1225
+ renderCloudflare();
1226
+ renderReport();
1227
+ renderRoutes();
1228
+ renderViews();
1229
+ renderLogs();
1230
+ }),
1231
+ );
1232
+
1233
+ applyTranslations();
1234
+
1235
+ const params = new URLSearchParams(location.search);
1236
+ if (params.get("path")) $("logs-path").value = params.get("path") ?? "";
1237
+ if (params.get("route")) $("logs-path").value = params.get("route") ?? "";
1238
+
1239
+ showPage(pageFromLocation(), { push: false });
1240
+ void load();
1241
+ void loadCloudflare();
1242
+ startPolling();