jskelet 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +127 -0
- package/CHANGELOG.md +40 -0
- package/LICENSE +21 -0
- package/README.md +342 -0
- package/bin/jskelet.mjs +104 -0
- package/docs/01-baslangic.md +285 -0
- package/docs/02-mimari.md +287 -0
- package/docs/03-routing.md +437 -0
- package/docs/04-render-ve-sablonlar.md +490 -0
- package/docs/05-islands.md +429 -0
- package/docs/06-cache.md +409 -0
- package/docs/07-yapilandirma.md +673 -0
- package/docs/08-build.md +366 -0
- package/docs/09-dev-araclari.md +302 -0
- package/docs/10-dagitim.md +329 -0
- package/docs/11-tasima.md +352 -0
- package/docs/README.md +82 -0
- package/package.json +97 -0
- package/src/build/build.mjs +138 -0
- package/src/build/ensure-build.mjs +15 -0
- package/src/build/paths.mjs +118 -0
- package/src/build/resolve-peer.mjs +36 -0
- package/src/build/tasks/client.mjs +268 -0
- package/src/build/tasks/css.mjs +124 -0
- package/src/build/tasks/fonts.mjs +146 -0
- package/src/build/tasks/icons.mjs +224 -0
- package/src/build/tasks/images.mjs +244 -0
- package/src/build/tasks/precompress.mjs +78 -0
- package/src/client/devtools/overlay.js +1763 -0
- package/src/client/devtools/report.html +185 -0
- package/src/client/devtools/report.js +712 -0
- package/src/client/dom.js +95 -0
- package/src/client/index.js +26 -0
- package/src/client/registry.js +223 -0
- package/src/client/safe-image.js +91 -0
- package/src/client/store.js +36 -0
- package/src/config/defaults.js +102 -0
- package/src/config/index.js +433 -0
- package/src/config/pattern.js +107 -0
- package/src/dev-server.mjs +383 -0
- package/src/http/control-flow.js +56 -0
- package/src/http/request-cache.js +46 -0
- package/src/index.js +35 -0
- package/src/init.mjs +220 -0
- package/src/log.mjs +332 -0
- package/src/logo.png +0 -0
- package/src/runtime/alias-hooks.mjs +119 -0
- package/src/runtime/register.mjs +4 -0
- package/src/server/assets.js +119 -0
- package/src/server/create-app.js +167 -0
- package/src/server/dev/devtools.js +383 -0
- package/src/server/dev/report.js +351 -0
- package/src/server/head-hints.js +132 -0
- package/src/server/html-cache.js +166 -0
- package/src/server/metadata.js +102 -0
- package/src/server/middleware/compression.js +205 -0
- package/src/server/middleware/dev-gate.js +62 -0
- package/src/server/middleware/headers.js +37 -0
- package/src/server/middleware/redirects.js +32 -0
- package/src/server/middleware/static-precompressed.js +100 -0
- package/src/server/middleware/upstream-proxy.js +141 -0
- package/src/server/prewarm.js +283 -0
- package/src/server/render.js +356 -0
- package/src/server/router.js +121 -0
- package/src/server/status-page.js +164 -0
- package/src/server/upstream-tracking.js +51 -0
- package/src/start.mjs +7 -0
- package/src/templates/layout.ejs +44 -0
- package/src/version.mjs +17 -0
- package/src/views/components/loader.js +85 -0
- package/src/views/helpers/html.js +102 -0
- package/src/views/helpers/tags.js +193 -0
|
@@ -0,0 +1,351 @@
|
|
|
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 { prewarmProgress } from "../prewarm.js";
|
|
17
|
+
import { getConfig } from "../../config/index.js";
|
|
18
|
+
|
|
19
|
+
/** Yollar config'ten: framework paket içine taşındığında `../..` sayan her hesap bozulur. */
|
|
20
|
+
const ROOT = getConfig().root;
|
|
21
|
+
const PUBLIC_DIR = getConfig().dirs.public;
|
|
22
|
+
const GENERATED_DIR = getConfig().dirs.generated;
|
|
23
|
+
|
|
24
|
+
/* ------------------------------------------------------------- sayfa ölçümleri */
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @typedef {{
|
|
28
|
+
* url: string,
|
|
29
|
+
* title: string | null,
|
|
30
|
+
* at: number,
|
|
31
|
+
* visits: number,
|
|
32
|
+
* metrics: Record<string, number | null>,
|
|
33
|
+
* resources: { count: number, bytes: number, byType: Record<string, { count: number, bytes: number }> },
|
|
34
|
+
* islands: { total: number, ready: number, names: string[] },
|
|
35
|
+
* api: { url: string, ms: number, status: number, bytes: number, initiator: string }[],
|
|
36
|
+
* html: { bytes: number | null, cache: string | null, ms: number | null },
|
|
37
|
+
* }} PageReport
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/** @type {Map<string, PageReport>} */
|
|
41
|
+
const pages = new Map();
|
|
42
|
+
|
|
43
|
+
/** Tarayıcıdan gelen ölçüm paketini saklar. En yeni paket öncekini ezer. */
|
|
44
|
+
export function recordPageReport(payload) {
|
|
45
|
+
if (!payload?.url) return;
|
|
46
|
+
|
|
47
|
+
let url;
|
|
48
|
+
try {
|
|
49
|
+
url = new URL(payload.url).pathname + new URL(payload.url).search;
|
|
50
|
+
} catch {
|
|
51
|
+
url = String(payload.url);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const previous = pages.get(url);
|
|
55
|
+
|
|
56
|
+
pages.set(url, {
|
|
57
|
+
url,
|
|
58
|
+
title: payload.title ?? previous?.title ?? null,
|
|
59
|
+
at: Date.now(),
|
|
60
|
+
visits: (previous?.visits ?? 0) + 1,
|
|
61
|
+
metrics: payload.metrics ?? {},
|
|
62
|
+
resources: payload.resources ?? { count: 0, bytes: 0, byType: {} },
|
|
63
|
+
islands: payload.islands ?? { total: 0, ready: 0, names: [] },
|
|
64
|
+
api: Array.isArray(payload.api) ? payload.api.slice(0, 100) : [],
|
|
65
|
+
html: previous?.html ?? { bytes: null, cache: null, ms: null },
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Ölçümler tarayıcı sekmesinde değil sunucuda durur; sıfırlama da buradan. */
|
|
70
|
+
export function clearPageReports() {
|
|
71
|
+
pages.clear();
|
|
72
|
+
serverApiCalls.length = 0;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/* --------------------------------------------------- sunucu tarafı API çağrıları */
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* @type {{ url: string, host: string, method: string, status: number, ms: number,
|
|
79
|
+
* bytes: number, at: number, error: string | null }[]}
|
|
80
|
+
*/
|
|
81
|
+
const serverApiCalls = [];
|
|
82
|
+
const MAX_API_CALLS = 300;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* SSR sırasında yapılan dış çağrıları ölçer. `globalThis.fetch` sarılır;
|
|
86
|
+
* yalnızca dev'de çağrıldığı için üretim yolu dokunulmaz kalır.
|
|
87
|
+
*/
|
|
88
|
+
export function trackServerFetch() {
|
|
89
|
+
const original = globalThis.fetch;
|
|
90
|
+
if (original.__jskeletWrapped) return;
|
|
91
|
+
|
|
92
|
+
/** @type {typeof fetch} */
|
|
93
|
+
const wrapped = async (input, init) => {
|
|
94
|
+
const url = typeof input === "string" ? input : (input?.url ?? String(input));
|
|
95
|
+
const started = Date.now();
|
|
96
|
+
|
|
97
|
+
// Kendi sunucumuza yapılan istekler (ısıtma, sağlık kontrolü) API sayılmaz.
|
|
98
|
+
const isSelf = /^https?:\/\/(127\.0\.0\.1|localhost)/i.test(url);
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
const response = await original(input, init);
|
|
102
|
+
if (!isSelf) {
|
|
103
|
+
push({
|
|
104
|
+
url,
|
|
105
|
+
method: init?.method ?? "GET",
|
|
106
|
+
status: response.status,
|
|
107
|
+
ms: Date.now() - started,
|
|
108
|
+
bytes: Number(response.headers.get("content-length") ?? 0),
|
|
109
|
+
error: response.ok ? null : `HTTP ${response.status}`,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return response;
|
|
113
|
+
} catch (error) {
|
|
114
|
+
if (!isSelf) {
|
|
115
|
+
push({
|
|
116
|
+
url,
|
|
117
|
+
method: init?.method ?? "GET",
|
|
118
|
+
status: 0,
|
|
119
|
+
ms: Date.now() - started,
|
|
120
|
+
bytes: 0,
|
|
121
|
+
error: error instanceof Error ? error.message : String(error),
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
wrapped.__jskeletWrapped = true;
|
|
129
|
+
globalThis.fetch = wrapped;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** @param {{ url: string, method: string, status: number, ms: number, bytes: number, error: string | null }} call */
|
|
133
|
+
function push(call) {
|
|
134
|
+
let host = "—";
|
|
135
|
+
try {
|
|
136
|
+
host = new URL(call.url).host;
|
|
137
|
+
} catch {
|
|
138
|
+
// Göreli adres: host bilinmiyor.
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
serverApiCalls.push({ ...call, host, at: Date.now() });
|
|
142
|
+
while (serverApiCalls.length > MAX_API_CALLS) serverApiCalls.shift();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/* ------------------------------------------------------------ build çıktısı */
|
|
146
|
+
|
|
147
|
+
/** Boyut hesapları dosya değişmedikçe tekrarlanmaz. */
|
|
148
|
+
const sizeCache = new Map();
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* @param {string} file mutlak yol
|
|
152
|
+
* @returns {{ bytes: number, gzip: number, brotli: number | null } | null}
|
|
153
|
+
*/
|
|
154
|
+
function measure(file) {
|
|
155
|
+
let stat;
|
|
156
|
+
try {
|
|
157
|
+
stat = fs.statSync(file);
|
|
158
|
+
} catch {
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const key = `${file}:${stat.size}:${stat.mtimeMs}`;
|
|
163
|
+
const hit = sizeCache.get(key);
|
|
164
|
+
if (hit) return hit;
|
|
165
|
+
|
|
166
|
+
let gzip = 0;
|
|
167
|
+
let brotli = null;
|
|
168
|
+
|
|
169
|
+
try {
|
|
170
|
+
const buffer = fs.readFileSync(file);
|
|
171
|
+
// Build önceden sıkıştırılmış eşlerini üretiyorsa onları kullan; yoksa
|
|
172
|
+
// gzip'i burada hesapla (rapor tek seferlik, maliyeti kabul edilebilir).
|
|
173
|
+
brotli = statSize(`${file}.br`);
|
|
174
|
+
gzip = statSize(`${file}.gz`) ?? zlib.gzipSync(buffer, { level: 6 }).length;
|
|
175
|
+
} catch {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const value = { bytes: stat.size, gzip, brotli };
|
|
180
|
+
sizeCache.set(key, value);
|
|
181
|
+
return value;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** @param {string} file @returns {number | null} */
|
|
185
|
+
function statSize(file) {
|
|
186
|
+
try {
|
|
187
|
+
return fs.statSync(file).size;
|
|
188
|
+
} catch {
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** @returns {Record<string, string>} */
|
|
194
|
+
function readJson(file, fallback) {
|
|
195
|
+
try {
|
|
196
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
197
|
+
} catch {
|
|
198
|
+
return fallback;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Manifest girdileri + boyutları. Yol public/ altına göre çözülür.
|
|
204
|
+
*/
|
|
205
|
+
function assets() {
|
|
206
|
+
const manifest = readJson(path.join(GENERATED_DIR, "manifest.json"), {});
|
|
207
|
+
|
|
208
|
+
return Object.entries(manifest).map(([name, url]) => {
|
|
209
|
+
const size = measure(path.join(PUBLIC_DIR, url.replace(/^\//, "")));
|
|
210
|
+
return {
|
|
211
|
+
name,
|
|
212
|
+
url,
|
|
213
|
+
kind: path.extname(url).slice(1) || "other",
|
|
214
|
+
bytes: size?.bytes ?? null,
|
|
215
|
+
gzip: size?.gzip ?? null,
|
|
216
|
+
brotli: size?.brotli ?? null,
|
|
217
|
+
};
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* esbuild metafile'ından chunk analizi: her çıktı için boyut, hangi
|
|
223
|
+
* kaynaklardan oluştuğu ve hangi chunk'ları import ettiği.
|
|
224
|
+
*/
|
|
225
|
+
function chunks() {
|
|
226
|
+
const metafile = readJson(path.join(GENERATED_DIR, "metafile.json"), null);
|
|
227
|
+
if (!metafile?.outputs) return { outputs: [], groups: [], available: false };
|
|
228
|
+
|
|
229
|
+
/** @type {Record<string, number>} */
|
|
230
|
+
const groups = {};
|
|
231
|
+
|
|
232
|
+
const outputs = Object.entries(metafile.outputs)
|
|
233
|
+
.filter(([file]) => file.endsWith(".js") || file.endsWith(".css"))
|
|
234
|
+
.map(([file, output]) => {
|
|
235
|
+
const size = measure(path.join(ROOT, file));
|
|
236
|
+
|
|
237
|
+
const inputs = Object.entries(output.inputs ?? {})
|
|
238
|
+
.map(([source, info]) => ({ source, bytes: info.bytesInOutput ?? 0 }))
|
|
239
|
+
.filter((input) => input.bytes > 0)
|
|
240
|
+
.sort((a, b) => b.bytes - a.bytes);
|
|
241
|
+
|
|
242
|
+
for (const input of inputs) {
|
|
243
|
+
const group = groupOf(input.source);
|
|
244
|
+
groups[group] = (groups[group] ?? 0) + input.bytes;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
return {
|
|
248
|
+
file: `/${file.split(path.sep).join("/").replace(/^public\//, "")}`,
|
|
249
|
+
entry: output.entryPoint ?? null,
|
|
250
|
+
isChunk: file.includes("chunks"),
|
|
251
|
+
bytes: output.bytes,
|
|
252
|
+
gzip: size?.gzip ?? null,
|
|
253
|
+
brotli: size?.brotli ?? null,
|
|
254
|
+
imports: (output.imports ?? [])
|
|
255
|
+
.filter((item) => item.kind !== "file-loader")
|
|
256
|
+
.map((item) => ({
|
|
257
|
+
path: `/${item.path.split(path.sep).join("/").replace(/^public\//, "")}`,
|
|
258
|
+
kind: item.kind,
|
|
259
|
+
})),
|
|
260
|
+
inputs: inputs.slice(0, 40),
|
|
261
|
+
inputCount: inputs.length,
|
|
262
|
+
};
|
|
263
|
+
})
|
|
264
|
+
.sort((a, b) => b.bytes - a.bytes);
|
|
265
|
+
|
|
266
|
+
return {
|
|
267
|
+
available: true,
|
|
268
|
+
outputs,
|
|
269
|
+
groups: Object.entries(groups)
|
|
270
|
+
.map(([name, bytes]) => ({ name, bytes }))
|
|
271
|
+
.sort((a, b) => b.bytes - a.bytes),
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Kaynak dosyayı okunur bir gruba indirger: paket adı ya da üst klasör.
|
|
277
|
+
* @param {string} source
|
|
278
|
+
*/
|
|
279
|
+
function groupOf(source) {
|
|
280
|
+
const normalized = source.split(path.sep).join("/");
|
|
281
|
+
const modules = normalized.lastIndexOf("node_modules/");
|
|
282
|
+
|
|
283
|
+
if (modules >= 0) {
|
|
284
|
+
const rest = normalized.slice(modules + "node_modules/".length).split("/");
|
|
285
|
+
return rest[0].startsWith("@") ? `${rest[0]}/${rest[1]}` : rest[0];
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const parts = normalized.split("/").filter(Boolean);
|
|
289
|
+
return parts.slice(0, 2).join("/") || normalized;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/* ------------------------------------------------------------------- rapor */
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Rapor sayfasının tek veri kaynağı.
|
|
296
|
+
* @param {{ requests: object[], errors: object[] }} devtools
|
|
297
|
+
*/
|
|
298
|
+
export function buildReport(devtools) {
|
|
299
|
+
const usage = process.memoryUsage();
|
|
300
|
+
|
|
301
|
+
// SSR ölçümleri: ısıtma turu her sayfanın HTML boyutunu ve render süresini
|
|
302
|
+
// biliyor; gezilen sayfalarla eşleştirilir.
|
|
303
|
+
const warmByPath = new Map(
|
|
304
|
+
(prewarmProgress.entries ?? []).map((entry) => [entry.path, entry]),
|
|
305
|
+
);
|
|
306
|
+
|
|
307
|
+
const pageList = [...pages.values()].map((page) => {
|
|
308
|
+
const warm = warmByPath.get(page.url.split("?")[0]);
|
|
309
|
+
return {
|
|
310
|
+
...page,
|
|
311
|
+
html: warm
|
|
312
|
+
? { bytes: warm.bytes, cache: warm.cache, ms: warm.ms }
|
|
313
|
+
: page.html,
|
|
314
|
+
};
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
// Hiç gezilmemiş ama ısıtılmış sayfalar da listelenir: SSR tarafı bilinir,
|
|
318
|
+
// istemci ölçümleri boş kalır.
|
|
319
|
+
for (const entry of prewarmProgress.entries ?? []) {
|
|
320
|
+
if (pages.has(entry.path)) continue;
|
|
321
|
+
pageList.push({
|
|
322
|
+
url: entry.path,
|
|
323
|
+
title: null,
|
|
324
|
+
at: prewarmProgress.finishedAt ?? prewarmProgress.startedAt,
|
|
325
|
+
visits: 0,
|
|
326
|
+
metrics: {},
|
|
327
|
+
resources: { count: 0, bytes: 0, byType: {} },
|
|
328
|
+
islands: { total: 0, ready: 0, names: [] },
|
|
329
|
+
api: [],
|
|
330
|
+
html: { bytes: entry.bytes, cache: entry.cache, ms: entry.ms },
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
return {
|
|
335
|
+
generatedAt: Date.now(),
|
|
336
|
+
process: {
|
|
337
|
+
pid: process.pid,
|
|
338
|
+
node: process.version,
|
|
339
|
+
uptime: process.uptime(),
|
|
340
|
+
memory: { rss: usage.rss, heapUsed: usage.heapUsed },
|
|
341
|
+
env: process.env.NODE_ENV ?? "development",
|
|
342
|
+
},
|
|
343
|
+
pages: pageList.sort((a, b) => (b.visits - a.visits) || b.at - a.at),
|
|
344
|
+
serverApi: serverApiCalls.slice().reverse(),
|
|
345
|
+
build: { assets: assets(), ...chunks() },
|
|
346
|
+
cache: { size: getHtmlCacheSize(), entries: getHtmlCacheEntries() },
|
|
347
|
+
prewarm: { ...prewarmProgress },
|
|
348
|
+
requests: devtools.requests,
|
|
349
|
+
errors: devtools.errors,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `<head>` kaynak ipuçları — `react-dom`'un preconnect/preload çağrılarının
|
|
3
|
+
* karşılığı.
|
|
4
|
+
*
|
|
5
|
+
* Layout bu bloğu `<head>`in en başına basar: preconnect ve LCP preload'ını
|
|
6
|
+
* geciktirmek doğrudan LCP'ye yazılır. Preconnect listesi her sayfada aynı
|
|
7
|
+
* olduğu için bir kez hesaplanır; sayfaya özel görsel preload'ını
|
|
8
|
+
* controller `head` alanıyla `headHints()` üzerinden ekler.
|
|
9
|
+
*/
|
|
10
|
+
import { getConfig } from "../config/index.js";
|
|
11
|
+
import { preloadImage } from "../views/helpers/tags.js";
|
|
12
|
+
import { esc, jsonScript } from "../views/helpers/html.js";
|
|
13
|
+
|
|
14
|
+
/** @type {string | null} */
|
|
15
|
+
let cached = null;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* `jskelet.config.mjs` → `preconnect: ["https://cdn.example.com"]`.
|
|
19
|
+
* Üçüncü taraf kaynaklar (görsel CDN'i, API origin'i, font host'u) buraya
|
|
20
|
+
* yazılır. Boş liste geçerli bir yapılandırmadır.
|
|
21
|
+
*
|
|
22
|
+
* @returns {string}
|
|
23
|
+
*/
|
|
24
|
+
export function preconnectHints() {
|
|
25
|
+
if (cached != null) return cached;
|
|
26
|
+
|
|
27
|
+
cached = getConfig()
|
|
28
|
+
.preconnect.map((origin) => {
|
|
29
|
+
try {
|
|
30
|
+
return `<link rel="preconnect" href="${esc(new URL(origin).origin)}">`;
|
|
31
|
+
} catch {
|
|
32
|
+
console.warn(`[head] preconnect geçersiz URL, atlandı: ${origin}`);
|
|
33
|
+
return "";
|
|
34
|
+
}
|
|
35
|
+
})
|
|
36
|
+
.join("");
|
|
37
|
+
|
|
38
|
+
return cached;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Spekülasyondan her koşulda muaf tutulan bağlantılar. `nofollow` ve
|
|
43
|
+
* `target=_blank` zaten site içi gezinme değil; `data-no-prefetch` ise
|
|
44
|
+
* uygulamanın tek bir bağlantıyı elle dışarıda bırakma yolu (oturum kapatma
|
|
45
|
+
* gibi yan etkili hedefler için).
|
|
46
|
+
*/
|
|
47
|
+
const EXEMPT_SELECTORS = ["[rel~=nofollow]", "[target=_blank]", "[data-no-prefetch]"];
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Speculation Rules gövdesini üretir. `getConfig()`ten ayrı tutulmasının
|
|
51
|
+
* sebebi test edilebilirlik: kural üretimi saf bir dönüşüm.
|
|
52
|
+
*
|
|
53
|
+
* @param {import('../config/index.js').NavigationConfig} navigation
|
|
54
|
+
* @returns {object | null} Hiç kural yoksa `null`.
|
|
55
|
+
*/
|
|
56
|
+
export function buildSpeculationRules(navigation) {
|
|
57
|
+
/** @type {Record<string, object[]>} */
|
|
58
|
+
const rules = {};
|
|
59
|
+
|
|
60
|
+
// `href_matches: "/*"` yalnızca aynı origin'deki yolları eşler; dış
|
|
61
|
+
// bağlantılar için spekülasyon hem anlamsız hem gizlilik açısından istenmez.
|
|
62
|
+
const where = {
|
|
63
|
+
and: [
|
|
64
|
+
{ href_matches: "/*" },
|
|
65
|
+
...navigation.exclude.map((pattern) => ({ not: { href_matches: pattern } })),
|
|
66
|
+
...EXEMPT_SELECTORS.map((selector) => ({ not: { selector_matches: selector } })),
|
|
67
|
+
],
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
if (navigation.prefetch) {
|
|
71
|
+
rules.prefetch = [{ where, eagerness: navigation.prefetch }];
|
|
72
|
+
}
|
|
73
|
+
if (navigation.prerender) {
|
|
74
|
+
rules.prerender = [{ where, eagerness: navigation.prerender }];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return Object.keys(rules).length ? rules : null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** @type {string | null} */
|
|
81
|
+
let navigationCached = null;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Site içi gezinme ipuçları: Speculation Rules + cross-document view
|
|
85
|
+
* transition. İkisi de her sayfada aynı olduğu için bir kez hesaplanır.
|
|
86
|
+
*
|
|
87
|
+
* Bunlar bilinçli olarak client runtime'ı değil: tarayıcı bağlantı üzerinde
|
|
88
|
+
* duraksamayı, önceliklendirmeyi ve iptali kendisi yönetiyor. Aynı davranışı
|
|
89
|
+
* JS ile yazmak hem daha fazla bayt hem daha kötü bir tahmin demek.
|
|
90
|
+
*
|
|
91
|
+
* @returns {string}
|
|
92
|
+
*/
|
|
93
|
+
export function navigationHints() {
|
|
94
|
+
if (navigationCached != null) return navigationCached;
|
|
95
|
+
|
|
96
|
+
const { navigation } = getConfig();
|
|
97
|
+
const rules = buildSpeculationRules(navigation);
|
|
98
|
+
|
|
99
|
+
// Geçiş kuralı hem eski hem yeni belgede bulunmalı; her sayfaya basılan
|
|
100
|
+
// satır içi bir kural bunu build çıktısına bağımlı olmadan garanti eder.
|
|
101
|
+
// Hareket azaltma tercihi burada karşılanır: sayfa geçişi tam ekran bir
|
|
102
|
+
// çapraz geçiş üretir ve bu, vestibüler rahatsızlığı olan kullanıcılar için
|
|
103
|
+
// kaçınılması gereken türden bir animasyon.
|
|
104
|
+
const transition = navigation.viewTransition
|
|
105
|
+
? "<style>@view-transition{navigation:auto}" +
|
|
106
|
+
"@media (prefers-reduced-motion:reduce){@view-transition{navigation:none}}</style>"
|
|
107
|
+
: "";
|
|
108
|
+
|
|
109
|
+
navigationCached =
|
|
110
|
+
(rules ? `<script type="speculationrules">${jsonScript(rules)}</script>` : "") +
|
|
111
|
+
transition;
|
|
112
|
+
|
|
113
|
+
return navigationCached;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* İlk ekrandaki görselin preload'ı. Preconnect'leri layout zaten her sayfaya
|
|
118
|
+
* bastığı için burada tekrarlanmaz.
|
|
119
|
+
*
|
|
120
|
+
* @param {{ href?: string | null, imageSrcSet?: string,
|
|
121
|
+
* imageSizes?: string }} [lcpImage]
|
|
122
|
+
* @returns {string}
|
|
123
|
+
*/
|
|
124
|
+
export function headHints(lcpImage) {
|
|
125
|
+
if (!lcpImage?.href) return "";
|
|
126
|
+
|
|
127
|
+
return preloadImage({
|
|
128
|
+
href: lcpImage.href,
|
|
129
|
+
imagesrcset: lcpImage.imageSrcSet,
|
|
130
|
+
imagesizes: lcpImage.imageSizes,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ISR ikamesi: route + query anahtarlı, TTL'li LRU HTML cache.
|
|
3
|
+
*
|
|
4
|
+
* TTL dolduğunda girdi hemen atılmaz: `stale` pencerede eski HTML anında
|
|
5
|
+
* döner ve tazeleme arkada çalışır. Böylece ilk ısıtmadan sonra hiçbir istek
|
|
6
|
+
* render'ı beklemez; buna karşılık HTML'deki veri en fazla `revalidate + bir
|
|
7
|
+
* tazeleme turu` kadar geride olabilir. Fiyat gibi canlı alanlar istemcide
|
|
8
|
+
* WebSocket'ten güncellendiği için bu gecikme ekranda görünmez.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @typedef {{ html: string, status: number, expiresAt: number,
|
|
13
|
+
* staleUntil: number, encoded: Map<string, Buffer> }} HtmlEntry
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const MAX_ENTRIES = 500;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* TTL dolduktan sonra eski HTML'in kaç TTL boyunca daha servis edilebileceği.
|
|
20
|
+
* Tazeleme genelde ilk stale istekte tamamlandığı için bu pencere yalnızca
|
|
21
|
+
* yavaş upstream'lerde devreye girer.
|
|
22
|
+
*/
|
|
23
|
+
const STALE_FACTOR = 1;
|
|
24
|
+
|
|
25
|
+
/** @type {Map<string, HtmlEntry>} */
|
|
26
|
+
const store = new Map();
|
|
27
|
+
|
|
28
|
+
/** @type {Map<string, Promise<{ html: string, status: number }>>} */
|
|
29
|
+
const inflight = new Map();
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param {string} key
|
|
33
|
+
* @returns {{ html: string, status: number, encoded: Map<string, Buffer>,
|
|
34
|
+
* stale: boolean } | null}
|
|
35
|
+
*/
|
|
36
|
+
function read(key) {
|
|
37
|
+
const entry = store.get(key);
|
|
38
|
+
if (!entry) return null;
|
|
39
|
+
|
|
40
|
+
const now = Date.now();
|
|
41
|
+
if (now >= entry.staleUntil) {
|
|
42
|
+
store.delete(key);
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// LRU: erişilen girdiyi sona taşı.
|
|
47
|
+
store.delete(key);
|
|
48
|
+
store.set(key, entry);
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
html: entry.html,
|
|
52
|
+
status: entry.status,
|
|
53
|
+
encoded: entry.encoded,
|
|
54
|
+
stale: now >= entry.expiresAt,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {string} key
|
|
60
|
+
* @param {{ html: string, status: number }} value
|
|
61
|
+
* @param {number} ttlSeconds
|
|
62
|
+
*/
|
|
63
|
+
function write(key, value, ttlSeconds) {
|
|
64
|
+
const now = Date.now();
|
|
65
|
+
|
|
66
|
+
store.set(key, {
|
|
67
|
+
html: value.html,
|
|
68
|
+
status: value.status,
|
|
69
|
+
// Sıkıştırılmış gövdeler HTML ile aynı ömrü paylaşır: aynı sayfa her
|
|
70
|
+
// istekte yeniden brotli'lenmesin.
|
|
71
|
+
encoded: new Map(),
|
|
72
|
+
expiresAt: now + ttlSeconds * 1000,
|
|
73
|
+
staleUntil: now + ttlSeconds * 1000 * (1 + STALE_FACTOR),
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
while (store.size > MAX_ENTRIES) {
|
|
77
|
+
const oldest = store.keys().next().value;
|
|
78
|
+
if (oldest === undefined) break;
|
|
79
|
+
store.delete(oldest);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @param {string} key
|
|
85
|
+
* @param {number} ttlSeconds
|
|
86
|
+
* @param {() => Promise<{ html: string, status: number, degraded?: boolean }>} producer
|
|
87
|
+
* @returns {Promise<{ html: string, status: number, degraded?: boolean }>}
|
|
88
|
+
*/
|
|
89
|
+
function refresh(key, ttlSeconds, producer) {
|
|
90
|
+
const pending = inflight.get(key);
|
|
91
|
+
if (pending) return pending;
|
|
92
|
+
|
|
93
|
+
const task = producer()
|
|
94
|
+
.then((value) => {
|
|
95
|
+
// `degraded`: upstream düştüğü için eksik veriyle üretilmiş HTML.
|
|
96
|
+
// Saklanırsa eksik içerik tüm TTL boyunca servis edilir.
|
|
97
|
+
if (value.status === 200 && !value.degraded) {
|
|
98
|
+
write(key, value, ttlSeconds);
|
|
99
|
+
}
|
|
100
|
+
return value;
|
|
101
|
+
})
|
|
102
|
+
.finally(() => {
|
|
103
|
+
inflight.delete(key);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
inflight.set(key, task);
|
|
107
|
+
return task;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* @param {string} key
|
|
112
|
+
* @param {number} ttlSeconds 0 → cache yok
|
|
113
|
+
* @param {() => Promise<{ html: string, status: number }>} producer
|
|
114
|
+
* @returns {Promise<{ html: string, status: number, cached: boolean,
|
|
115
|
+
* stale?: boolean, encoded?: Map<string, Buffer> }>}
|
|
116
|
+
*/
|
|
117
|
+
export async function withHtmlCache(key, ttlSeconds, producer) {
|
|
118
|
+
if (!ttlSeconds) {
|
|
119
|
+
const fresh = await producer();
|
|
120
|
+
return { ...fresh, cached: false };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const hit = read(key);
|
|
124
|
+
|
|
125
|
+
if (hit) {
|
|
126
|
+
// Süresi geçmiş girdi anında döner; tazeleme arkada yürür ve hatası
|
|
127
|
+
// isteği etkilemez (eski HTML stale penceresi boyunca geçerli kalır).
|
|
128
|
+
if (hit.stale) {
|
|
129
|
+
void refresh(key, ttlSeconds, producer).catch((error) => {
|
|
130
|
+
console.error(`[html-cache] arka plan tazelemesi başarısız: ${key}`, error);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
return { ...hit, cached: true };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const value = await refresh(key, ttlSeconds, producer);
|
|
137
|
+
return { ...value, encoded: store.get(key)?.encoded, cached: false };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function clearHtmlCache() {
|
|
141
|
+
store.clear();
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function getHtmlCacheSize() {
|
|
145
|
+
return store.size;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Dev raporu için önbellek dökümü: hangi sayfa ne kadar HTML tutuyor, ne
|
|
150
|
+
* zaman bayatlıyor. HTML gövdesi dönmez, yalnızca boyutu.
|
|
151
|
+
*
|
|
152
|
+
* @returns {{ key: string, bytes: number, status: number, stale: boolean,
|
|
153
|
+
* expiresIn: number, encodings: string[] }[]}
|
|
154
|
+
*/
|
|
155
|
+
export function getHtmlCacheEntries() {
|
|
156
|
+
const now = Date.now();
|
|
157
|
+
|
|
158
|
+
return [...store.entries()].map(([key, entry]) => ({
|
|
159
|
+
key,
|
|
160
|
+
bytes: Buffer.byteLength(entry.html),
|
|
161
|
+
status: entry.status,
|
|
162
|
+
stale: now >= entry.expiresAt,
|
|
163
|
+
expiresIn: Math.round((entry.expiresAt - now) / 1000),
|
|
164
|
+
encodings: [...entry.encoded.keys()],
|
|
165
|
+
}));
|
|
166
|
+
}
|