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.
Files changed (72) hide show
  1. package/AGENTS.md +127 -0
  2. package/CHANGELOG.md +40 -0
  3. package/LICENSE +21 -0
  4. package/README.md +342 -0
  5. package/bin/jskelet.mjs +104 -0
  6. package/docs/01-baslangic.md +285 -0
  7. package/docs/02-mimari.md +287 -0
  8. package/docs/03-routing.md +437 -0
  9. package/docs/04-render-ve-sablonlar.md +490 -0
  10. package/docs/05-islands.md +429 -0
  11. package/docs/06-cache.md +409 -0
  12. package/docs/07-yapilandirma.md +673 -0
  13. package/docs/08-build.md +366 -0
  14. package/docs/09-dev-araclari.md +302 -0
  15. package/docs/10-dagitim.md +329 -0
  16. package/docs/11-tasima.md +352 -0
  17. package/docs/README.md +82 -0
  18. package/package.json +97 -0
  19. package/src/build/build.mjs +138 -0
  20. package/src/build/ensure-build.mjs +15 -0
  21. package/src/build/paths.mjs +118 -0
  22. package/src/build/resolve-peer.mjs +36 -0
  23. package/src/build/tasks/client.mjs +268 -0
  24. package/src/build/tasks/css.mjs +124 -0
  25. package/src/build/tasks/fonts.mjs +146 -0
  26. package/src/build/tasks/icons.mjs +224 -0
  27. package/src/build/tasks/images.mjs +244 -0
  28. package/src/build/tasks/precompress.mjs +78 -0
  29. package/src/client/devtools/overlay.js +1763 -0
  30. package/src/client/devtools/report.html +185 -0
  31. package/src/client/devtools/report.js +712 -0
  32. package/src/client/dom.js +95 -0
  33. package/src/client/index.js +26 -0
  34. package/src/client/registry.js +223 -0
  35. package/src/client/safe-image.js +91 -0
  36. package/src/client/store.js +36 -0
  37. package/src/config/defaults.js +102 -0
  38. package/src/config/index.js +433 -0
  39. package/src/config/pattern.js +107 -0
  40. package/src/dev-server.mjs +383 -0
  41. package/src/http/control-flow.js +56 -0
  42. package/src/http/request-cache.js +46 -0
  43. package/src/index.js +35 -0
  44. package/src/init.mjs +220 -0
  45. package/src/log.mjs +332 -0
  46. package/src/logo.png +0 -0
  47. package/src/runtime/alias-hooks.mjs +119 -0
  48. package/src/runtime/register.mjs +4 -0
  49. package/src/server/assets.js +119 -0
  50. package/src/server/create-app.js +167 -0
  51. package/src/server/dev/devtools.js +383 -0
  52. package/src/server/dev/report.js +351 -0
  53. package/src/server/head-hints.js +132 -0
  54. package/src/server/html-cache.js +166 -0
  55. package/src/server/metadata.js +102 -0
  56. package/src/server/middleware/compression.js +205 -0
  57. package/src/server/middleware/dev-gate.js +62 -0
  58. package/src/server/middleware/headers.js +37 -0
  59. package/src/server/middleware/redirects.js +32 -0
  60. package/src/server/middleware/static-precompressed.js +100 -0
  61. package/src/server/middleware/upstream-proxy.js +141 -0
  62. package/src/server/prewarm.js +283 -0
  63. package/src/server/render.js +356 -0
  64. package/src/server/router.js +121 -0
  65. package/src/server/status-page.js +164 -0
  66. package/src/server/upstream-tracking.js +51 -0
  67. package/src/start.mjs +7 -0
  68. package/src/templates/layout.ejs +44 -0
  69. package/src/version.mjs +17 -0
  70. package/src/views/components/loader.js +85 -0
  71. package/src/views/helpers/html.js +102 -0
  72. package/src/views/helpers/tags.js +193 -0
@@ -0,0 +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
+ }
@@ -0,0 +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
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Yayına açılmamış bir ortamı gizler: `DEV_TOKEN` ayarlıyken token taşımayan
3
+ * her isteğe 404 döner. 403 değil 404 — 403 ortamın var olduğunu doğrular,
4
+ * 404 hiç yokmuş gibi davranır.
5
+ *
6
+ * Token bir kez `?dev_token=…` ile gelirse çereze yazılır, böylece link
7
+ * paylaşımı yeterli olur. `DEV_TOKEN` yoksa middleware tamamen devre dışıdır
8
+ * ve üretimde hiçbir maliyeti olmaz.
9
+ */
10
+ import process from "node:process";
11
+ import { getConfig } from "../../config/index.js";
12
+
13
+ const COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 14;
14
+
15
+ /**
16
+ * @param {import('http').IncomingMessage} req
17
+ * @param {string} name
18
+ * @returns {string | undefined}
19
+ */
20
+ function readCookie(req, name) {
21
+ const header = req.headers.cookie;
22
+ if (!header) return undefined;
23
+
24
+ for (const part of header.split(";")) {
25
+ const eq = part.indexOf("=");
26
+ if (eq === -1) continue;
27
+ if (part.slice(0, eq).trim() !== name) continue;
28
+ return decodeURIComponent(part.slice(eq + 1).trim());
29
+ }
30
+ return undefined;
31
+ }
32
+
33
+ /** @returns {import('express').RequestHandler} */
34
+ export function devGate() {
35
+ const { devGateBypass, brand } = getConfig();
36
+ const bypass = new Set(devGateBypass);
37
+ const cookieName = brand.devTokenCookie;
38
+
39
+ return (req, res, next) => {
40
+ const devToken = process.env.DEV_TOKEN;
41
+ if (!devToken) return next();
42
+ if (bypass.has(req.path)) return next();
43
+
44
+ const fromQuery = req.query?.[cookieName];
45
+ const tokenFromQuery = Array.isArray(fromQuery) ? fromQuery[0] : fromQuery;
46
+ const tokenFromCookie = readCookie(req, cookieName);
47
+
48
+ if (tokenFromQuery !== devToken && tokenFromCookie !== devToken) {
49
+ res.status(404).type("text/plain").send("Not Found");
50
+ return;
51
+ }
52
+
53
+ if (tokenFromQuery === devToken) {
54
+ res.setHeader(
55
+ "Set-Cookie",
56
+ `${cookieName}=${encodeURIComponent(devToken)}; Max-Age=${COOKIE_MAX_AGE_SECONDS}; Path=/; SameSite=Lax`,
57
+ );
58
+ }
59
+
60
+ next();
61
+ };
62
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * `jskelet.config.mjs` → `headers()` uygulayıcısı.
3
+ *
4
+ * İki katman var. Framework yalnızca statik dosyalara uzun ömürlü cache
5
+ * yazar — bu, hash'li çıktı için her projede doğru olan tek varsayılan.
6
+ * Bunun dışındaki her başlık (CSP, COOP, HSTS, X-Frame-Options…) config'ten
7
+ * gelir ve varsayılanların üstüne biner: aynı başlığı yeniden tanımlarsan
8
+ * config kazanır.
9
+ */
10
+ import { getConfig } from "../../config/index.js";
11
+ import { matchPattern } from "../../config/pattern.js";
12
+ import { IMMUTABLE_CACHE } from "../../config/defaults.js";
13
+
14
+ /** @returns {import('express').RequestHandler} */
15
+ export function headersMiddleware() {
16
+ const { static: staticRules, headers: rules } = getConfig();
17
+
18
+ return (req, res, next) => {
19
+ const pathname = req.path ?? "";
20
+ const dot = pathname.lastIndexOf(".");
21
+ const ext = dot === -1 ? "" : pathname.slice(dot).toLowerCase();
22
+
23
+ if (
24
+ staticRules.extensions.has(ext) ||
25
+ staticRules.prefixes.some((prefix) => pathname.startsWith(prefix))
26
+ ) {
27
+ res.setHeader("Cache-Control", IMMUTABLE_CACHE);
28
+ }
29
+
30
+ for (const rule of rules) {
31
+ if (!matchPattern(rule.pattern, pathname)) continue;
32
+ for (const { key, value } of rule.headers) res.setHeader(key, value);
33
+ }
34
+
35
+ next();
36
+ };
37
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `jskelet.config.mjs` → `redirects()` uygulayıcısı.
3
+ *
4
+ * İlk eşleşen kural kazanır, sonrası denenmez — sıralama config'teki yazım
5
+ * sırasıdır. Query string korunur: `/eski?utm=x` → `/yeni?utm=x`, çünkü
6
+ * yönlendirme kampanya parametrelerini düşürürse trafik kaynağı kaybolur.
7
+ */
8
+ import { getConfig } from "../../config/index.js";
9
+ import { fillDestination, matchPattern } from "../../config/pattern.js";
10
+
11
+ /** @returns {import('express').RequestHandler} */
12
+ export function redirects() {
13
+ const rules = getConfig().redirects;
14
+ if (!rules.length) return (req, res, next) => next();
15
+
16
+ return (req, res, next) => {
17
+ const query = req.originalUrl.slice(req.path.length);
18
+
19
+ for (const rule of rules) {
20
+ const params = matchPattern(rule.pattern, req.path);
21
+ if (!params) continue;
22
+
23
+ res.redirect(
24
+ rule.statusCode,
25
+ `${fillDestination(rule.destination, params)}${query}`,
26
+ );
27
+ return;
28
+ }
29
+
30
+ next();
31
+ };
32
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Build'de üretilmiş `.br` / `.gz` kopyalarını servis eder.
3
+ *
4
+ * `express.static`ten önce çalışır: istemcinin kabul ettiği bir kopya varsa
5
+ * istek yolunu ona çevirir ve doğru `Content-Type` / `Content-Encoding`
6
+ * başlıklarını kendisi kurar. Böylece hash'li varlıklar istek başına yeniden
7
+ * sıkıştırılmaz ve build'deki kalite 11 brotli kullanılır.
8
+ *
9
+ * Kopya yoksa istek olduğu gibi `express.static`e devredilir.
10
+ */
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import { negotiateEncoding } from "./compression.js";
14
+ import { IMMUTABLE_CACHE } from "../../config/defaults.js";
15
+
16
+ /** @type {Record<string, string>} */
17
+ const CONTENT_TYPES = {
18
+ ".css": "text/css; charset=utf-8",
19
+ ".js": "text/javascript; charset=utf-8",
20
+ ".mjs": "text/javascript; charset=utf-8",
21
+ ".svg": "image/svg+xml",
22
+ ".json": "application/json; charset=utf-8",
23
+ ".xml": "application/xml; charset=utf-8",
24
+ ".txt": "text/plain; charset=utf-8",
25
+ ".map": "application/json; charset=utf-8",
26
+ };
27
+
28
+ /**
29
+ * @param {string} publicDir
30
+ * @returns {import('express').RequestHandler}
31
+ */
32
+ export function staticPrecompressed(publicDir) {
33
+ const root = path.resolve(publicDir);
34
+
35
+ return (req, res, next) => {
36
+ if (req.method !== "GET" && req.method !== "HEAD") {
37
+ next();
38
+ return;
39
+ }
40
+
41
+ const type = CONTENT_TYPES[path.extname(req.path).toLowerCase()];
42
+ if (!type) {
43
+ next();
44
+ return;
45
+ }
46
+
47
+ const encoding = negotiateEncoding(req.headers["accept-encoding"]);
48
+ if (!encoding) {
49
+ next();
50
+ return;
51
+ }
52
+
53
+ let decoded;
54
+ try {
55
+ decoded = decodeURIComponent(req.path);
56
+ } catch {
57
+ next();
58
+ return;
59
+ }
60
+
61
+ const target = path.resolve(root, `.${decoded}`);
62
+
63
+ // Path traversal koruması: çözülen yol public/ dışına çıkamaz.
64
+ if (target !== root && !target.startsWith(root + path.sep)) {
65
+ next();
66
+ return;
67
+ }
68
+
69
+ const file = `${target}${encoding === "br" ? ".br" : ".gz"}`;
70
+
71
+ let stat;
72
+ try {
73
+ stat = fs.statSync(file);
74
+ } catch {
75
+ next();
76
+ return;
77
+ }
78
+
79
+ if (!stat.isFile()) {
80
+ next();
81
+ return;
82
+ }
83
+
84
+ res.setHeader("Content-Type", type);
85
+ res.setHeader("Content-Encoding", encoding);
86
+ res.setHeader("Content-Length", String(stat.size));
87
+ res.setHeader("Vary", "Accept-Encoding");
88
+
89
+ if (req.path.startsWith("/assets/")) {
90
+ res.setHeader("Cache-Control", IMMUTABLE_CACHE);
91
+ }
92
+
93
+ if (req.method === "HEAD") {
94
+ res.end();
95
+ return;
96
+ }
97
+
98
+ fs.createReadStream(file).on("error", () => res.end()).pipe(res);
99
+ };
100
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * `jskelet.config.mjs` → `rewrites()` uygulayıcısı ve yeniden kullanılabilir
3
+ * reverse proxy.
4
+ *
5
+ * Harici paket yok; native `fetch` ile stream eden ince bir proxy. `duplex:
6
+ * "half"` gövdeli isteklerde şart, `redirect: "manual"` olmadan upstream'in
7
+ * 302'si burada tüketilir ve tarayıcı hiç görmez.
8
+ *
9
+ * Tipik kullanım: `/api/*` yolunu backend'e taşımak. Bunu tarayıcı
10
+ * same-origin çağırdığı için CORS ve third-party cookie sorunları oluşmaz.
11
+ */
12
+ import { Readable } from "node:stream";
13
+ import { getConfig } from "../../config/index.js";
14
+ import { fillDestination, matchPattern } from "../../config/pattern.js";
15
+
16
+ /** Hop-by-hop header'lar proxy edilmez. */
17
+ const STRIPPED_REQUEST_HEADERS = new Set([
18
+ "host",
19
+ "connection",
20
+ "content-length",
21
+ "accept-encoding",
22
+ ]);
23
+
24
+ const STRIPPED_RESPONSE_HEADERS = new Set([
25
+ "content-encoding",
26
+ "content-length",
27
+ "transfer-encoding",
28
+ "connection",
29
+ ]);
30
+
31
+ /**
32
+ * Rewrite hedefini istek nesnesinde taşımak için; string bir alan adı
33
+ * uygulamanın kendi alanlarıyla çakışabilir.
34
+ */
35
+ const REWRITE_TARGET = Symbol("jskelet.rewriteTarget");
36
+
37
+ /**
38
+ * @param {import('express').Request} req
39
+ * @returns {Record<string, string>}
40
+ */
41
+ function forwardHeaders(req) {
42
+ /** @type {Record<string, string>} */
43
+ const out = {};
44
+ for (const [key, value] of Object.entries(req.headers)) {
45
+ if (STRIPPED_REQUEST_HEADERS.has(key)) continue;
46
+ if (value === undefined) continue;
47
+ out[key] = Array.isArray(value) ? value.join(", ") : String(value);
48
+ }
49
+ return out;
50
+ }
51
+
52
+ /**
53
+ * Hedefi isteğe göre hesaplayan proxy üretir. `resolveTarget` fırlatırsa
54
+ * istek proxy'lenmez ve zincire devam eder — hedef origin yapılandırılmamış
55
+ * bir kurulumda 500 yerine normal 404 almak daha doğru.
56
+ *
57
+ * @param {(req: import('express').Request) => string} resolveTarget
58
+ * @returns {import('express').RequestHandler}
59
+ */
60
+ export function createProxy(resolveTarget) {
61
+ return async (req, res, next) => {
62
+ let target;
63
+ try {
64
+ target = resolveTarget(req);
65
+ } catch {
66
+ next();
67
+ return;
68
+ }
69
+
70
+ if (!target) {
71
+ next();
72
+ return;
73
+ }
74
+
75
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
76
+
77
+ try {
78
+ const upstream = await fetch(target, {
79
+ method: req.method,
80
+ headers: forwardHeaders(req),
81
+ body: hasBody ? Readable.toWeb(req) : undefined,
82
+ duplex: hasBody ? "half" : undefined,
83
+ redirect: "manual",
84
+ });
85
+
86
+ res.status(upstream.status);
87
+ upstream.headers.forEach((value, key) => {
88
+ if (STRIPPED_RESPONSE_HEADERS.has(key.toLowerCase())) return;
89
+ res.setHeader(key, value);
90
+ });
91
+
92
+ if (!upstream.body) {
93
+ res.end();
94
+ return;
95
+ }
96
+
97
+ Readable.fromWeb(upstream.body).pipe(res);
98
+ } catch (error) {
99
+ next(error);
100
+ }
101
+ };
102
+ }
103
+
104
+ /**
105
+ * Config'teki `rewrites()` kuralları.
106
+ *
107
+ * Hedef mutlaksa (http/https) istek proxy ile dışa taşınır; göreliyse
108
+ * yalnızca `req.url` değiştirilir ve istek kendi route tablosunda devam eder.
109
+ * İki faz var: `beforeFiles` statik dosyalardan önce, `afterFiles` statik
110
+ * denendikten sonra sayfalardan önce.
111
+ *
112
+ * @param {"beforeFiles" | "afterFiles"} phase
113
+ * @returns {import('express').RequestHandler}
114
+ */
115
+ export function configRewrites(phase) {
116
+ const rules = getConfig().rewrites.filter((rule) => rule.phase === phase);
117
+ if (!rules.length) return (req, res, next) => next();
118
+
119
+ const proxy = createProxy((req) => req[REWRITE_TARGET]);
120
+
121
+ return (req, res, next) => {
122
+ for (const rule of rules) {
123
+ const params = matchPattern(rule.pattern, req.path);
124
+ if (!params) continue;
125
+
126
+ const query = req.originalUrl.slice(req.path.length);
127
+ const destination = fillDestination(rule.destination, params);
128
+
129
+ if (/^https?:\/\//.test(destination)) {
130
+ req[REWRITE_TARGET] = `${destination}${query}`;
131
+ proxy(req, res, next);
132
+ return;
133
+ }
134
+
135
+ req.url = `${destination}${query}`;
136
+ break;
137
+ }
138
+
139
+ next();
140
+ };
141
+ }