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,102 +1,102 @@
1
- /**
2
- * Metadata → `<head>` etiketleri. Next.js'in Metadata API'sinin karşılığı.
3
- *
4
- * Controller `metadata` döndürür, framework onu etiketlere çevirir. Şema
5
- * bilinçli olarak küçük: title/description/canonical/robots ve OpenGraph +
6
- * Twitter kartları. Daha fazlası gerekirse `extraTags` ile ham HTML eklenir,
7
- * böylece framework her yeni meta türü için sürüm çıkarmak zorunda kalmaz.
8
- *
9
- * @typedef {object} Metadata
10
- * @property {string} [title]
11
- * @property {string} [titleTemplate] `"%s | Site"` — `title` buna gömülür.
12
- * @property {string} [description]
13
- * @property {string} [canonical] Mutlak ya da göreli URL.
14
- * @property {string} [siteUrl] Göreli canonical'ı mutlaklaştırmak için.
15
- * @property {{ index?: boolean, follow?: boolean }} [robots]
16
- * @property {string} [locale]
17
- * @property {object} [openGraph] `{ title, description, url, type, siteName, image, imageWidth, imageHeight }`
18
- * @property {object} [twitter] `{ card, site, creator, title, description, image }`
19
- * @property {string[]} [extraTags] Olduğu gibi basılacak ham etiketler.
20
- */
21
- import { attrs, esc } from "../views/helpers/html.js";
22
-
23
- /**
24
- * @param {string} name
25
- * @param {unknown} content
26
- * @returns {string}
27
- */
28
- function meta(name, content) {
29
- if (content == null || content === "") return "";
30
- return `<meta${attrs({ name, content })}>`;
31
- }
32
-
33
- /**
34
- * OpenGraph `property` kullanır, `name` değil — bazı kazıyıcılar `name` ile
35
- * yazılmış og etiketlerini görmezden geliyor.
36
- *
37
- * @param {string} property
38
- * @param {unknown} content
39
- * @returns {string}
40
- */
41
- function og(property, content) {
42
- if (content == null || content === "") return "";
43
- return `<meta${attrs({ property, content })}>`;
44
- }
45
-
46
- /**
47
- * @param {string} [canonical]
48
- * @param {string} [siteUrl]
49
- * @returns {string | undefined}
50
- */
51
- function absoluteUrl(canonical, siteUrl) {
52
- if (!canonical) return undefined;
53
- if (/^https?:\/\//.test(canonical)) return canonical;
54
- if (!siteUrl) return canonical;
55
- return new URL(canonical, siteUrl).href;
56
- }
57
-
58
- /**
59
- * @param {Metadata} [metadata]
60
- * @returns {string}
61
- */
62
- export function renderHeadMeta(metadata = {}) {
63
- const title = metadata.titleTemplate && metadata.title
64
- ? metadata.titleTemplate.replace("%s", metadata.title)
65
- : metadata.title;
66
-
67
- const url = absoluteUrl(metadata.canonical, metadata.siteUrl);
68
- const robots = metadata.robots ?? {};
69
- // Varsayılan indekslenebilir: bir sayfayı gizlemek açık bir karar olmalı.
70
- const robotsValue = [
71
- robots.index === false ? "noindex" : "index",
72
- robots.follow === false ? "nofollow" : "follow",
73
- ].join(", ");
74
-
75
- const graph = metadata.openGraph ?? {};
76
- const card = metadata.twitter ?? {};
77
-
78
- return [
79
- title ? `<title>${esc(title)}</title>` : "",
80
- meta("description", metadata.description),
81
- url ? `<link${attrs({ rel: "canonical", href: url })}>` : "",
82
- meta("robots", robotsValue),
83
- og("og:type", graph.type ?? "website"),
84
- og("og:title", graph.title ?? title),
85
- og("og:description", graph.description ?? metadata.description),
86
- og("og:url", graph.url ?? url),
87
- og("og:site_name", graph.siteName),
88
- og("og:locale", metadata.locale),
89
- og("og:image", graph.image),
90
- og("og:image:width", graph.imageWidth),
91
- og("og:image:height", graph.imageHeight),
92
- meta("twitter:card", card.card ?? (graph.image ? "summary_large_image" : "summary")),
93
- meta("twitter:site", card.site),
94
- meta("twitter:creator", card.creator),
95
- meta("twitter:title", card.title ?? graph.title ?? title),
96
- meta("twitter:description", card.description ?? metadata.description),
97
- meta("twitter:image", card.image ?? graph.image),
98
- ...(metadata.extraTags ?? []),
99
- ]
100
- .filter(Boolean)
101
- .join("");
102
- }
1
+ /**
2
+ * Metadata → `<head>` etiketleri. Next.js'in Metadata API'sinin karşılığı.
3
+ *
4
+ * Controller `metadata` döndürür, framework onu etiketlere çevirir. Şema
5
+ * bilinçli olarak küçük: title/description/canonical/robots ve OpenGraph +
6
+ * Twitter kartları. Daha fazlası gerekirse `extraTags` ile ham HTML eklenir,
7
+ * böylece framework her yeni meta türü için sürüm çıkarmak zorunda kalmaz.
8
+ *
9
+ * @typedef {object} Metadata
10
+ * @property {string} [title]
11
+ * @property {string} [titleTemplate] `"%s | Site"` — `title` buna gömülür.
12
+ * @property {string} [description]
13
+ * @property {string} [canonical] Mutlak ya da göreli URL.
14
+ * @property {string} [siteUrl] Göreli canonical'ı mutlaklaştırmak için.
15
+ * @property {{ index?: boolean, follow?: boolean }} [robots]
16
+ * @property {string} [locale]
17
+ * @property {object} [openGraph] `{ title, description, url, type, siteName, image, imageWidth, imageHeight }`
18
+ * @property {object} [twitter] `{ card, site, creator, title, description, image }`
19
+ * @property {string[]} [extraTags] Olduğu gibi basılacak ham etiketler.
20
+ */
21
+ import { attrs, esc } from "../views/helpers/html.js";
22
+
23
+ /**
24
+ * @param {string} name
25
+ * @param {unknown} content
26
+ * @returns {string}
27
+ */
28
+ function meta(name, content) {
29
+ if (content == null || content === "") return "";
30
+ return `<meta${attrs({ name, content })}>`;
31
+ }
32
+
33
+ /**
34
+ * OpenGraph `property` kullanır, `name` değil — bazı kazıyıcılar `name` ile
35
+ * yazılmış og etiketlerini görmezden geliyor.
36
+ *
37
+ * @param {string} property
38
+ * @param {unknown} content
39
+ * @returns {string}
40
+ */
41
+ function og(property, content) {
42
+ if (content == null || content === "") return "";
43
+ return `<meta${attrs({ property, content })}>`;
44
+ }
45
+
46
+ /**
47
+ * @param {string} [canonical]
48
+ * @param {string} [siteUrl]
49
+ * @returns {string | undefined}
50
+ */
51
+ function absoluteUrl(canonical, siteUrl) {
52
+ if (!canonical) return undefined;
53
+ if (/^https?:\/\//.test(canonical)) return canonical;
54
+ if (!siteUrl) return canonical;
55
+ return new URL(canonical, siteUrl).href;
56
+ }
57
+
58
+ /**
59
+ * @param {Metadata} [metadata]
60
+ * @returns {string}
61
+ */
62
+ export function renderHeadMeta(metadata = {}) {
63
+ const title = metadata.titleTemplate && metadata.title
64
+ ? metadata.titleTemplate.replace("%s", metadata.title)
65
+ : metadata.title;
66
+
67
+ const url = absoluteUrl(metadata.canonical, metadata.siteUrl);
68
+ const robots = metadata.robots ?? {};
69
+ // Varsayılan indekslenebilir: bir sayfayı gizlemek açık bir karar olmalı.
70
+ const robotsValue = [
71
+ robots.index === false ? "noindex" : "index",
72
+ robots.follow === false ? "nofollow" : "follow",
73
+ ].join(", ");
74
+
75
+ const graph = metadata.openGraph ?? {};
76
+ const card = metadata.twitter ?? {};
77
+
78
+ return [
79
+ title ? `<title>${esc(title)}</title>` : "",
80
+ meta("description", metadata.description),
81
+ url ? `<link${attrs({ rel: "canonical", href: url })}>` : "",
82
+ meta("robots", robotsValue),
83
+ og("og:type", graph.type ?? "website"),
84
+ og("og:title", graph.title ?? title),
85
+ og("og:description", graph.description ?? metadata.description),
86
+ og("og:url", graph.url ?? url),
87
+ og("og:site_name", graph.siteName),
88
+ og("og:locale", metadata.locale),
89
+ og("og:image", graph.image),
90
+ og("og:image:width", graph.imageWidth),
91
+ og("og:image:height", graph.imageHeight),
92
+ meta("twitter:card", card.card ?? (graph.image ? "summary_large_image" : "summary")),
93
+ meta("twitter:site", card.site),
94
+ meta("twitter:creator", card.creator),
95
+ meta("twitter:title", card.title ?? graph.title ?? title),
96
+ meta("twitter:description", card.description ?? metadata.description),
97
+ meta("twitter:image", card.image ?? graph.image),
98
+ ...(metadata.extraTags ?? []),
99
+ ]
100
+ .filter(Boolean)
101
+ .join("");
102
+ }
@@ -1,205 +1,205 @@
1
- /**
2
- * Yanıt sıkıştırma — Next.js'in varsayılan `compress: true` davranışının yerine.
3
- *
4
- * `compression` paketi brotli desteklemiyor ve yedi geçişli bağımlılık
5
- * getiriyor; `node:zlib` ile brotli + gzip pazarlığı yapmak yeterli.
6
- * Brotli tercih edilir: ana sayfa HTML'inde gzip'e göre ~%35 daha küçük.
7
- */
8
- import zlib from "node:zlib";
9
- import { Writable } from "node:stream";
10
-
11
- /** Bu eşiğin altındaki gövdelerde sıkıştırma kazancı yok. */
12
- const THRESHOLD_BYTES = 1024;
13
-
14
- const COMPRESSIBLE =
15
- /^(?:text\/|application\/(?:json|javascript|xml|xhtml\+xml|rss\+xml|atom\+xml|ld\+json|manifest\+json)|image\/svg\+xml)/i;
16
-
17
- const BROTLI_OPTIONS = {
18
- params: {
19
- // Metin için 5, varsayılan 11'e göre çok daha hızlı ve neredeyse aynı boyut.
20
- [zlib.constants.BROTLI_PARAM_QUALITY]: 5,
21
- [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
22
- },
23
- };
24
-
25
- /**
26
- * @param {string} header
27
- * @returns {"br" | "gzip" | null}
28
- */
29
- function negotiate(header) {
30
- if (!header) return null;
31
-
32
- /** @type {Map<string, number>} */
33
- const weights = new Map();
34
-
35
- for (const part of header.split(",")) {
36
- const [name, ...params] = part.trim().split(";");
37
- const q = params
38
- .map((p) => p.trim())
39
- .find((p) => p.startsWith("q="));
40
-
41
- weights.set(name.toLowerCase(), q ? Number(q.slice(2)) : 1);
42
- }
43
-
44
- if ((weights.get("br") ?? 0) > 0) return "br";
45
- if ((weights.get("gzip") ?? 0) > 0) return "gzip";
46
- return null;
47
- }
48
-
49
- /**
50
- * İçeriği bir kez sıkıştırıp saklamak isteyen çağıranlar için (HTML cache).
51
- *
52
- * @param {string | undefined} acceptEncoding
53
- * @returns {"br" | "gzip" | null}
54
- */
55
- export function negotiateEncoding(acceptEncoding) {
56
- return negotiate(acceptEncoding ?? "");
57
- }
58
-
59
- /**
60
- * @param {string} text
61
- * @param {"br" | "gzip"} encoding
62
- * @returns {Promise<Buffer>}
63
- */
64
- export function encodeText(text, encoding) {
65
- const input = Buffer.from(text, "utf8");
66
-
67
- return new Promise((resolve, reject) => {
68
- const done = (error, result) => (error ? reject(error) : resolve(result));
69
-
70
- if (encoding === "br") zlib.brotliCompress(input, BROTLI_OPTIONS, done);
71
- else zlib.gzip(input, done);
72
- });
73
- }
74
-
75
- /**
76
- * @param {import('http').ServerResponse} res
77
- * @returns {boolean}
78
- */
79
- function shouldCompress(res) {
80
- if (res.getHeader("content-encoding")) return false;
81
- if (res.getHeader("cache-control")?.toString().includes("no-transform")) {
82
- return false;
83
- }
84
-
85
- const type = res.getHeader("content-type")?.toString() ?? "";
86
- if (type.includes("text/event-stream")) return false;
87
- if (!COMPRESSIBLE.test(type)) return false;
88
-
89
- const length = Number(res.getHeader("content-length"));
90
- return Number.isNaN(length) || length >= THRESHOLD_BYTES;
91
- }
92
-
93
- /**
94
- * @returns {import('express').RequestHandler}
95
- */
96
- export function compression() {
97
- return (req, res, next) => {
98
- // HEAD gövdesi yok; zaten sıkışık ikili içerik boşuna CPU yakar.
99
- const encoding = req.method === "HEAD" ? null : negotiate(req.headers["accept-encoding"]);
100
-
101
- const originalWrite = res.write.bind(res);
102
- const originalEnd = res.end.bind(res);
103
-
104
- /** @type {import('zlib').Gzip | import('zlib').BrotliCompress | null} */
105
- let stream = null;
106
- let decided = false;
107
- let passthrough = false;
108
-
109
- function decide() {
110
- if (decided) return;
111
- decided = true;
112
-
113
- // SSE gibi akışlar başlıkları kendileri yazar (`writeHead`); bu noktada
114
- // başlık eklemek çökme sebebi olur, sıkıştırma da anlamsızdır.
115
- if (res.headersSent) {
116
- passthrough = true;
117
- return;
118
- }
119
-
120
- // Vary her durumda: aynı URL farklı encoding ile cache'lenebilir.
121
- res.setHeader("Vary", appendVary(res.getHeader("Vary"), "Accept-Encoding"));
122
-
123
- if (!encoding || !shouldCompress(res)) {
124
- passthrough = true;
125
- return;
126
- }
127
-
128
- res.setHeader("Content-Encoding", encoding);
129
- res.removeHeader("Content-Length");
130
-
131
- stream =
132
- encoding === "br"
133
- ? zlib.createBrotliCompress(BROTLI_OPTIONS)
134
- : zlib.createGzip({ level: 6 });
135
-
136
- // Sıkıştırılmış çıktıyı sokete geri baskıya saygı duyarak aktar.
137
- stream.pipe(
138
- new Writable({
139
- write(chunk, chunkEncoding, callback) {
140
- originalWrite(chunk, chunkEncoding, callback);
141
- },
142
- final(callback) {
143
- originalEnd();
144
- callback();
145
- },
146
- }),
147
- );
148
-
149
- // `express.static` gövdeyi `pipe` ile yazar ve `res.write()` false
150
- // dönerse `drain` bekler; zlib doldu-boşaldı sinyalini yansıtmazsak
151
- // aktarım sessizce askıda kalır.
152
- stream.on("drain", () => res.emit("drain"));
153
- stream.on("error", () => originalEnd());
154
- }
155
-
156
- res.write = function write(chunk, encodingArg, callback) {
157
- decide();
158
- if (passthrough) return originalWrite(chunk, encodingArg, callback);
159
- if (!chunk) return true;
160
-
161
- return stream.write(toBuffer(chunk, encodingArg), callback);
162
- };
163
-
164
- res.end = function end(chunk, encodingArg, callback) {
165
- decide();
166
- if (passthrough) return originalEnd(chunk, encodingArg, callback);
167
-
168
- if (chunk && typeof chunk !== "function") {
169
- stream.end(toBuffer(chunk, encodingArg), callback);
170
- } else {
171
- stream.end();
172
- }
173
-
174
- return res;
175
- };
176
-
177
- next();
178
- };
179
- }
180
-
181
- /**
182
- * @param {unknown} chunk
183
- * @param {unknown} encodingArg
184
- * @returns {Buffer}
185
- */
186
- function toBuffer(chunk, encodingArg) {
187
- if (Buffer.isBuffer(chunk)) return chunk;
188
- return Buffer.from(
189
- /** @type {string} */ (chunk),
190
- typeof encodingArg === "string" ? /** @type {BufferEncoding} */ (encodingArg) : "utf8",
191
- );
192
- }
193
-
194
- /**
195
- * @param {unknown} current
196
- * @param {string} field
197
- * @returns {string}
198
- */
199
- function appendVary(current, field) {
200
- const existing = current ? String(current) : "";
201
- if (!existing) return field;
202
-
203
- const parts = existing.split(",").map((p) => p.trim().toLowerCase());
204
- return parts.includes(field.toLowerCase()) ? existing : `${existing}, ${field}`;
205
- }
1
+ /**
2
+ * Yanıt sıkıştırma — Next.js'in varsayılan `compress: true` davranışının yerine.
3
+ *
4
+ * `compression` paketi brotli desteklemiyor ve yedi geçişli bağımlılık
5
+ * getiriyor; `node:zlib` ile brotli + gzip pazarlığı yapmak yeterli.
6
+ * Brotli tercih edilir: ana sayfa HTML'inde gzip'e göre ~%35 daha küçük.
7
+ */
8
+ import zlib from "node:zlib";
9
+ import { Writable } from "node:stream";
10
+
11
+ /** Bu eşiğin altındaki gövdelerde sıkıştırma kazancı yok. */
12
+ const THRESHOLD_BYTES = 1024;
13
+
14
+ const COMPRESSIBLE =
15
+ /^(?:text\/|application\/(?:json|javascript|xml|xhtml\+xml|rss\+xml|atom\+xml|ld\+json|manifest\+json)|image\/svg\+xml)/i;
16
+
17
+ const BROTLI_OPTIONS = {
18
+ params: {
19
+ // Metin için 5, varsayılan 11'e göre çok daha hızlı ve neredeyse aynı boyut.
20
+ [zlib.constants.BROTLI_PARAM_QUALITY]: 5,
21
+ [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
22
+ },
23
+ };
24
+
25
+ /**
26
+ * @param {string} header
27
+ * @returns {"br" | "gzip" | null}
28
+ */
29
+ function negotiate(header) {
30
+ if (!header) return null;
31
+
32
+ /** @type {Map<string, number>} */
33
+ const weights = new Map();
34
+
35
+ for (const part of header.split(",")) {
36
+ const [name, ...params] = part.trim().split(";");
37
+ const q = params
38
+ .map((p) => p.trim())
39
+ .find((p) => p.startsWith("q="));
40
+
41
+ weights.set(name.toLowerCase(), q ? Number(q.slice(2)) : 1);
42
+ }
43
+
44
+ if ((weights.get("br") ?? 0) > 0) return "br";
45
+ if ((weights.get("gzip") ?? 0) > 0) return "gzip";
46
+ return null;
47
+ }
48
+
49
+ /**
50
+ * İçeriği bir kez sıkıştırıp saklamak isteyen çağıranlar için (HTML cache).
51
+ *
52
+ * @param {string | undefined} acceptEncoding
53
+ * @returns {"br" | "gzip" | null}
54
+ */
55
+ export function negotiateEncoding(acceptEncoding) {
56
+ return negotiate(acceptEncoding ?? "");
57
+ }
58
+
59
+ /**
60
+ * @param {string} text
61
+ * @param {"br" | "gzip"} encoding
62
+ * @returns {Promise<Buffer>}
63
+ */
64
+ export function encodeText(text, encoding) {
65
+ const input = Buffer.from(text, "utf8");
66
+
67
+ return new Promise((resolve, reject) => {
68
+ const done = (error, result) => (error ? reject(error) : resolve(result));
69
+
70
+ if (encoding === "br") zlib.brotliCompress(input, BROTLI_OPTIONS, done);
71
+ else zlib.gzip(input, done);
72
+ });
73
+ }
74
+
75
+ /**
76
+ * @param {import('http').ServerResponse} res
77
+ * @returns {boolean}
78
+ */
79
+ function shouldCompress(res) {
80
+ if (res.getHeader("content-encoding")) return false;
81
+ if (res.getHeader("cache-control")?.toString().includes("no-transform")) {
82
+ return false;
83
+ }
84
+
85
+ const type = res.getHeader("content-type")?.toString() ?? "";
86
+ if (type.includes("text/event-stream")) return false;
87
+ if (!COMPRESSIBLE.test(type)) return false;
88
+
89
+ const length = Number(res.getHeader("content-length"));
90
+ return Number.isNaN(length) || length >= THRESHOLD_BYTES;
91
+ }
92
+
93
+ /**
94
+ * @returns {import('express').RequestHandler}
95
+ */
96
+ export function compression() {
97
+ return (req, res, next) => {
98
+ // HEAD gövdesi yok; zaten sıkışık ikili içerik boşuna CPU yakar.
99
+ const encoding = req.method === "HEAD" ? null : negotiate(req.headers["accept-encoding"]);
100
+
101
+ const originalWrite = res.write.bind(res);
102
+ const originalEnd = res.end.bind(res);
103
+
104
+ /** @type {import('zlib').Gzip | import('zlib').BrotliCompress | null} */
105
+ let stream = null;
106
+ let decided = false;
107
+ let passthrough = false;
108
+
109
+ function decide() {
110
+ if (decided) return;
111
+ decided = true;
112
+
113
+ // SSE gibi akışlar başlıkları kendileri yazar (`writeHead`); bu noktada
114
+ // başlık eklemek çökme sebebi olur, sıkıştırma da anlamsızdır.
115
+ if (res.headersSent) {
116
+ passthrough = true;
117
+ return;
118
+ }
119
+
120
+ // Vary her durumda: aynı URL farklı encoding ile cache'lenebilir.
121
+ res.setHeader("Vary", appendVary(res.getHeader("Vary"), "Accept-Encoding"));
122
+
123
+ if (!encoding || !shouldCompress(res)) {
124
+ passthrough = true;
125
+ return;
126
+ }
127
+
128
+ res.setHeader("Content-Encoding", encoding);
129
+ res.removeHeader("Content-Length");
130
+
131
+ stream =
132
+ encoding === "br"
133
+ ? zlib.createBrotliCompress(BROTLI_OPTIONS)
134
+ : zlib.createGzip({ level: 6 });
135
+
136
+ // Sıkıştırılmış çıktıyı sokete geri baskıya saygı duyarak aktar.
137
+ stream.pipe(
138
+ new Writable({
139
+ write(chunk, chunkEncoding, callback) {
140
+ originalWrite(chunk, chunkEncoding, callback);
141
+ },
142
+ final(callback) {
143
+ originalEnd();
144
+ callback();
145
+ },
146
+ }),
147
+ );
148
+
149
+ // `express.static` gövdeyi `pipe` ile yazar ve `res.write()` false
150
+ // dönerse `drain` bekler; zlib doldu-boşaldı sinyalini yansıtmazsak
151
+ // aktarım sessizce askıda kalır.
152
+ stream.on("drain", () => res.emit("drain"));
153
+ stream.on("error", () => originalEnd());
154
+ }
155
+
156
+ res.write = function write(chunk, encodingArg, callback) {
157
+ decide();
158
+ if (passthrough) return originalWrite(chunk, encodingArg, callback);
159
+ if (!chunk) return true;
160
+
161
+ return stream.write(toBuffer(chunk, encodingArg), callback);
162
+ };
163
+
164
+ res.end = function end(chunk, encodingArg, callback) {
165
+ decide();
166
+ if (passthrough) return originalEnd(chunk, encodingArg, callback);
167
+
168
+ if (chunk && typeof chunk !== "function") {
169
+ stream.end(toBuffer(chunk, encodingArg), callback);
170
+ } else {
171
+ stream.end();
172
+ }
173
+
174
+ return res;
175
+ };
176
+
177
+ next();
178
+ };
179
+ }
180
+
181
+ /**
182
+ * @param {unknown} chunk
183
+ * @param {unknown} encodingArg
184
+ * @returns {Buffer}
185
+ */
186
+ function toBuffer(chunk, encodingArg) {
187
+ if (Buffer.isBuffer(chunk)) return chunk;
188
+ return Buffer.from(
189
+ /** @type {string} */ (chunk),
190
+ typeof encodingArg === "string" ? /** @type {BufferEncoding} */ (encodingArg) : "utf8",
191
+ );
192
+ }
193
+
194
+ /**
195
+ * @param {unknown} current
196
+ * @param {string} field
197
+ * @returns {string}
198
+ */
199
+ function appendVary(current, field) {
200
+ const existing = current ? String(current) : "";
201
+ if (!existing) return field;
202
+
203
+ const parts = existing.split(",").map((p) => p.trim().toLowerCase());
204
+ return parts.includes(field.toLowerCase()) ? existing : `${existing}, ${field}`;
205
+ }