noofpi 2.0.1 → 3.1.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 (38) hide show
  1. package/README.md +6 -2
  2. package/client.d.ts +2 -0
  3. package/dist/build-YRW44BZG.js +212 -0
  4. package/dist/{chunk-YJVMBHNL.js → chunk-JUVQEKLE.js} +43 -12
  5. package/dist/chunk-LJEKK4AK.js +51 -0
  6. package/dist/chunk-O5JRC252.js +245 -0
  7. package/dist/{chunk-G35DW4NA.js → chunk-PC3ZJN4D.js} +11 -1
  8. package/dist/{chunk-NHBXVKEQ.js → chunk-PL3CA2JF.js} +160 -86
  9. package/dist/{chunk-MN5PVHC5.js → chunk-W7ASRDAJ.js} +229 -7
  10. package/dist/{chunk-IE3WF5XF.js → chunk-YN4TKMDX.js} +87 -4
  11. package/dist/chunk-YN64WQ2B.js +562 -0
  12. package/dist/cli.js +21 -9
  13. package/dist/{dev-OAGCOGHA.js → dev-A7VK5V4H.js} +7 -6
  14. package/dist/{devtools-PLUN2DYV.js → devtools-C3PFU57C.js} +1 -1
  15. package/dist/handler-oYl9j0Qa.d.ts +26 -0
  16. package/dist/index.d.ts +26 -11
  17. package/dist/index.js +3 -2
  18. package/dist/payload-DfhHnXAn.d.ts +66 -0
  19. package/dist/{prepare-BN7NMCVQ.js → prepare-JT2NPD5S.js} +6 -5
  20. package/dist/runtime/entry-client.js +4 -4
  21. package/dist/runtime/entry-server.d.ts +6 -4
  22. package/dist/runtime/entry-server.js +88 -25
  23. package/dist/runtime/index.d.ts +24 -6
  24. package/dist/runtime/index.js +5 -3
  25. package/dist/server/bun.d.ts +3 -3
  26. package/dist/server/index.d.ts +35 -7
  27. package/dist/server/index.js +12 -7
  28. package/dist/server/node.d.ts +3 -3
  29. package/dist/session-CLvYihOU.d.ts +275 -0
  30. package/dist/{start-ITRND3BY.js → start-J6ZIUG66.js} +7 -6
  31. package/dist/{types-B6rQOOxS.d.ts → types-Czld0vOH.d.ts} +30 -5
  32. package/package.json +12 -7
  33. package/dist/build-WPHZ7TYZ.js +0 -49
  34. package/dist/chunk-MTXQR32N.js +0 -8
  35. package/dist/chunk-X3DYEZLK.js +0 -253
  36. package/dist/handler-C6NnwBfC.d.ts +0 -17
  37. package/dist/payload-CL6tYBin.d.ts +0 -121
  38. package/dist/route-rules-COilNsVT.d.ts +0 -127
@@ -6,17 +6,24 @@ import {
6
6
  toPublicConfig,
7
7
  toServerConfig,
8
8
  variantWidths
9
- } from "./chunk-IE3WF5XF.js";
9
+ } from "./chunk-YN4TKMDX.js";
10
10
  import {
11
- SSR_OUTLET
12
- } from "./chunk-MTXQR32N.js";
11
+ cacheControl
12
+ } from "./chunk-LJEKK4AK.js";
13
+ import {
14
+ importOptional
15
+ } from "./chunk-O5JRC252.js";
13
16
  import {
14
17
  COMPRESSIBLE_EXTENSIONS
15
18
  } from "./chunk-PPUFFGCH.js";
16
19
  import {
20
+ SSR_OUTLET,
17
21
  applyHead,
18
22
  resolveHead
19
- } from "./chunk-G35DW4NA.js";
23
+ } from "./chunk-PC3ZJN4D.js";
24
+ import {
25
+ REDIRECT_STATUSES
26
+ } from "./chunk-W7ASRDAJ.js";
20
27
  import {
21
28
  filePathToRoute
22
29
  } from "./chunk-Y3NBZ6DW.js";
@@ -303,10 +310,115 @@ function htmlTemplate(entry, stylesheets = []) {
303
310
  `;
304
311
  }
305
312
 
313
+ // src/vite/layouts.ts
314
+ import { existsSync as existsSync3, readdirSync, readFileSync } from "fs";
315
+ import path7 from "path";
316
+ var USE_LAYOUT = /\buseLayout\(\s*(?:(['"`])([^'"`$\n]+)\1|(false))\s*\)/;
317
+ function extractLayout(source) {
318
+ const match = USE_LAYOUT.exec(source);
319
+ if (!match) return void 0;
320
+ return match[3] ? false : match[2];
321
+ }
322
+ function scanPages(root, extract) {
323
+ const pagesDir = path7.join(root, "app/pages");
324
+ const result = {};
325
+ const walk = (dir) => {
326
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
327
+ const full = path7.join(dir, entry.name);
328
+ if (entry.isDirectory()) walk(full);
329
+ else if (entry.name.endsWith(".vue")) {
330
+ let value;
331
+ try {
332
+ value = extract(readFileSync(full, "utf-8"));
333
+ } catch (error) {
334
+ throw new Error(
335
+ `[noofpi] ${path7.relative(root, full)}: ${error.message}`
336
+ );
337
+ }
338
+ if (value !== void 0)
339
+ result["/" + path7.relative(root, full).split(path7.sep).join("/")] = value;
340
+ }
341
+ }
342
+ };
343
+ if (existsSync3(pagesDir)) walk(pagesDir);
344
+ return result;
345
+ }
346
+ function scanPageLayouts(root) {
347
+ return scanPages(root, extractLayout);
348
+ }
349
+
350
+ // src/vite/static-files.ts
351
+ function cloudflarePaths(pattern) {
352
+ if (pattern.endsWith("/**")) {
353
+ const base = pattern.slice(0, -3);
354
+ if (base.includes("*")) return void 0;
355
+ return base ? [base, `${base}/*`] : ["/*"];
356
+ }
357
+ return pattern.includes("*") ? void 0 : [pattern];
358
+ }
359
+ function unsupportedStaticRules(config, preset) {
360
+ const unsupported = [];
361
+ for (const [pattern, rule] of Object.entries(config.routeRules)) {
362
+ const names = ["headers", "redirect", "cache"].filter(
363
+ (name) => rule[name] !== void 0 && rule[name] !== false
364
+ );
365
+ const cors = rule.cors !== void 0 && rule.cors !== false;
366
+ if (preset === "cloudflare-pages") {
367
+ if (!cloudflarePaths(pattern)) {
368
+ for (const name of cors ? [...names, "cors"] : names)
369
+ unsupported.push(`${pattern}: ${name} (pattern not supported)`);
370
+ continue;
371
+ }
372
+ if (cors) unsupported.push(`${pattern}: cors`);
373
+ } else
374
+ for (const name of cors ? [...names, "cors"] : names)
375
+ unsupported.push(`${pattern}: ${name}`);
376
+ }
377
+ return unsupported;
378
+ }
379
+ function headerBlocks(config) {
380
+ const blocks = [];
381
+ if (Object.keys(config.security.headers).length)
382
+ blocks.push({ path: "/*", headers: config.security.headers });
383
+ for (const [pattern, rule] of Object.entries(config.routeRules)) {
384
+ const paths = cloudflarePaths(pattern);
385
+ const headers = {
386
+ ...rule.cache ? { "Cache-Control": cacheControl(rule.cache) } : {},
387
+ ...rule.headers
388
+ };
389
+ if (!paths || !Object.keys(headers).length) continue;
390
+ for (const path16 of paths) blocks.push({ path: path16, headers });
391
+ }
392
+ return blocks;
393
+ }
394
+ function headersFile(config) {
395
+ return headerBlocks(config).map(
396
+ ({ path: path16, headers }) => `${path16}
397
+ ${Object.entries(headers).map(([name, value]) => ` ${name}: ${value}`).join("\n")}
398
+ `
399
+ ).join("\n");
400
+ }
401
+ function redirectsFile(config) {
402
+ const lines = [];
403
+ for (const [pattern, rule] of Object.entries(config.routeRules)) {
404
+ const redirect = rule.redirect;
405
+ const paths = redirect === void 0 ? void 0 : cloudflarePaths(pattern);
406
+ if (redirect === void 0 || !paths) continue;
407
+ const { to, status } = typeof redirect === "string" ? { to: redirect, status: 307 } : { to: redirect.to, status: redirect.status ?? 307 };
408
+ if (!REDIRECT_STATUSES.includes(status)) continue;
409
+ const splat = to.endsWith("/**");
410
+ for (const path16 of paths) {
411
+ const target = splat ? path16.endsWith("/*") ? `${to.slice(0, -3)}/:splat` : to.slice(0, -3) || "/" : to;
412
+ lines.push(`${path16} ${target} ${status}`);
413
+ }
414
+ }
415
+ return lines.length ? lines.join("\n") + "\n" : "";
416
+ }
417
+
306
418
  // src/vite/platform.ts
307
- import { existsSync as existsSync3 } from "fs";
419
+ import { existsSync as existsSync4 } from "fs";
308
420
  import { createRequire } from "module";
309
- import path7 from "path";
421
+ import path8 from "path";
310
422
  import { pathToFileURL } from "url";
311
423
  var WRANGLER_CONFIGS = [
312
424
  "wrangler.json",
@@ -317,7 +429,7 @@ async function startPlatformProxy(root, config) {
317
429
  if (!isCloudflarePreset(config.build.preset)) return void 0;
318
430
  let entry;
319
431
  try {
320
- entry = createRequire(path7.join(root, "package.json")).resolve("wrangler");
432
+ entry = createRequire(path8.join(root, "package.json")).resolve("wrangler");
321
433
  } catch {
322
434
  console.warn(
323
435
  "[noofpi] Cloudflare bindings are not available in dev: install wrangler (`wrangler` devDependency)"
@@ -325,8 +437,8 @@ async function startPlatformProxy(root, config) {
325
437
  return void 0;
326
438
  }
327
439
  const { getPlatformProxy } = await import(pathToFileURL(entry).href);
328
- const configPath = WRANGLER_CONFIGS.map((file) => path7.join(root, file)).find(
329
- existsSync3
440
+ const configPath = WRANGLER_CONFIGS.map((file) => path8.join(root, file)).find(
441
+ existsSync4
330
442
  );
331
443
  return getPlatformProxy({ configPath });
332
444
  }
@@ -338,7 +450,7 @@ import path11 from "path";
338
450
 
339
451
  // src/vite/compress.ts
340
452
  import { readdir, readFile as readFile2, writeFile as writeFile3 } from "fs/promises";
341
- import path8 from "path";
453
+ import path9 from "path";
342
454
  import { promisify } from "util";
343
455
  import { brotliCompress, constants, gzip } from "zlib";
344
456
  var brotli = promisify(brotliCompress);
@@ -347,7 +459,7 @@ var MIN_SIZE = 1024;
347
459
  async function listFiles(dir) {
348
460
  const files = [];
349
461
  for (const entry of await readdir(dir, { withFileTypes: true })) {
350
- const full = path8.join(dir, entry.name);
462
+ const full = path9.join(dir, entry.name);
351
463
  if (entry.isDirectory()) files.push(...await listFiles(full));
352
464
  else if (entry.isFile()) files.push(full);
353
465
  }
@@ -355,8 +467,8 @@ async function listFiles(dir) {
355
467
  }
356
468
  async function precompressDir(dir) {
357
469
  const files = (await listFiles(dir)).filter(
358
- (file) => COMPRESSIBLE_EXTENSIONS.has(path8.extname(file).toLowerCase()) && // The shell is inlined in the server bundle and never served as a file
359
- path8.basename(file) !== "index.html"
470
+ (file) => COMPRESSIBLE_EXTENSIONS.has(path9.extname(file).toLowerCase()) && // The shell is inlined in the server bundle and never served as a file
471
+ path9.basename(file) !== "index.html"
360
472
  );
361
473
  await Promise.all(
362
474
  files.map(async (file) => {
@@ -418,43 +530,6 @@ function dockerfile(options) {
418
530
  ].join("\n");
419
531
  }
420
532
 
421
- // src/vite/layouts.ts
422
- import { existsSync as existsSync4, readdirSync, readFileSync } from "fs";
423
- import path9 from "path";
424
- var USE_LAYOUT = /\buseLayout\(\s*(?:(['"`])([^'"`$\n]+)\1|(false))\s*\)/;
425
- function extractLayout(source) {
426
- const match = USE_LAYOUT.exec(source);
427
- if (!match) return void 0;
428
- return match[3] ? false : match[2];
429
- }
430
- function scanPages(root, extract) {
431
- const pagesDir = path9.join(root, "app/pages");
432
- const result = {};
433
- const walk = (dir) => {
434
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
435
- const full = path9.join(dir, entry.name);
436
- if (entry.isDirectory()) walk(full);
437
- else if (entry.name.endsWith(".vue")) {
438
- let value;
439
- try {
440
- value = extract(readFileSync(full, "utf-8"));
441
- } catch (error) {
442
- throw new Error(
443
- `[noofpi] ${path9.relative(root, full)}: ${error.message}`
444
- );
445
- }
446
- if (value !== void 0)
447
- result["/" + path9.relative(root, full).split(path9.sep).join("/")] = value;
448
- }
449
- }
450
- };
451
- if (existsSync4(pagesDir)) walk(pagesDir);
452
- return result;
453
- }
454
- function scanPageLayouts(root) {
455
- return scanPages(root, extractLayout);
456
- }
457
-
458
533
  // src/vite/wrangler.ts
459
534
  import { existsSync as existsSync5, readFileSync as readFileSync2 } from "fs";
460
535
  import path10 from "path";
@@ -547,6 +622,7 @@ function presetEntryCode(preset, config) {
547
622
  const { port } = config.devServer;
548
623
  switch (preset) {
549
624
  case "bun":
625
+ case "docker-bun":
550
626
  return [
551
627
  `import { fileURLToPath } from 'node:url';`,
552
628
  `import { serveBun } from 'noofpi/server/bun';`,
@@ -558,7 +634,7 @@ function presetEntryCode(preset, config) {
558
634
  case "cloudflare-worker":
559
635
  return [
560
636
  HANDLER,
561
- `export default { fetch: (request, env) => handler(request, env) };`
637
+ `export default { fetch: (request, env, ctx) => handler(request, env, ctx) };`
562
638
  ].join("\n");
563
639
  case "cloudflare-pages":
564
640
  return [
@@ -568,7 +644,7 @@ function presetEntryCode(preset, config) {
568
644
  `const apiRoot = mod.config.doofpi.root;`,
569
645
  `const isApiPath = (pathname) => pathname.startsWith('/_noofpi/') || pathname === apiRoot || pathname.startsWith(apiRoot + '.') || pathname.startsWith(apiRoot + '/');`,
570
646
  `const isFile = (request) => { const { pathname } = new URL(request.url); return (request.method === 'GET' || request.method === 'HEAD') && /\\.[a-z0-9]+$/i.test(pathname) && !isApiPath(pathname); };`,
571
- `export default { fetch: (request, env) => isFile(request) && env.ASSETS ? env.ASSETS.fetch(request) : handler(request, env) };`
647
+ `export default { fetch: (request, env, ctx) => isFile(request) && env.ASSETS ? env.ASSETS.fetch(request) : handler(request, env, ctx) };`
572
648
  ].join("\n");
573
649
  default:
574
650
  return [
@@ -671,7 +747,16 @@ async function writeSeoFiles(root, config) {
671
747
  }
672
748
  if (seo.robots) await write("robots.txt", robotsTxt(seo));
673
749
  }
674
- async function finishPresetBuild(root, config, preset) {
750
+ async function writeStaticShell(outDir, config) {
751
+ const index = path11.join(outDir, "public/index.html");
752
+ const html = applyHead(
753
+ readFileSync3(index, "utf-8"),
754
+ resolveHead(config.head)
755
+ ).replace(SSR_OUTLET, () => "");
756
+ await writeFile4(index, html);
757
+ await writeFile4(path11.join(outDir, "public/404.html"), html);
758
+ }
759
+ async function finishPresetBuild(root, config, preset, options = {}) {
675
760
  const outDir = path11.join(root, OUTPUT_DIR);
676
761
  await writeSeoFiles(root, config);
677
762
  const json = (value) => JSON.stringify(value, null, 2) + "\n";
@@ -686,6 +771,17 @@ async function finishPresetBuild(root, config, preset) {
686
771
  );
687
772
  return "deploy with `wrangler deploy -c .output/wrangler.json`";
688
773
  case "cloudflare-pages":
774
+ if (options.generated) {
775
+ await writeStaticShell(outDir, config);
776
+ await writeFile4(
777
+ path11.join(outDir, "public/_headers"),
778
+ headersFile(config)
779
+ );
780
+ const redirects = redirectsFile(config);
781
+ if (redirects)
782
+ await writeFile4(path11.join(outDir, "public/_redirects"), redirects);
783
+ return "deploy with `wrangler pages deploy .output/public`";
784
+ }
689
785
  await rm(path11.join(outDir, "public/index.html"), { force: true });
690
786
  await writeFile4(
691
787
  path11.join(outDir, "public/_routes.json"),
@@ -693,29 +789,20 @@ async function finishPresetBuild(root, config, preset) {
693
789
  );
694
790
  return "deploy with `wrangler pages deploy .output/public`";
695
791
  case "github-pages": {
696
- const index = path11.join(outDir, "public/index.html");
697
- const html = applyHead(
698
- readFileSync3(index, "utf-8"),
699
- resolveHead(config.head)
700
- ).replace(SSR_OUTLET, () => "");
701
- await writeFile4(index, html);
702
- await writeFile4(path11.join(outDir, "public/404.html"), html);
792
+ await writeStaticShell(outDir, config);
703
793
  await writeFile4(path11.join(outDir, "public/.nojekyll"), "");
704
794
  return "publish `.output/public` to GitHub Pages (set `vite.base` to `/<repo>/` for project sites)";
705
795
  }
706
- case "docker":
796
+ case "docker-node":
797
+ case "docker-bun": {
798
+ const bun = preset === "docker-bun";
707
799
  await precompressDir(path11.join(outDir, "public"));
708
800
  await mkdir3(outDir, { recursive: true });
709
801
  await writeFile4(
710
802
  path11.join(outDir, "Dockerfile"),
711
803
  dockerfile({
712
- bun: existsSync6(path11.join(root, "bun.lock")) || existsSync6(path11.join(root, "bun.lockb")),
713
- lock: existsSync6(
714
- path11.join(
715
- root,
716
- existsSync6(path11.join(root, "bun.lock")) ? "bun.lock" : "package-lock.json"
717
- )
718
- ),
804
+ bun,
805
+ lock: bun ? existsSync6(path11.join(root, "bun.lock")) || existsSync6(path11.join(root, "bun.lockb")) : existsSync6(path11.join(root, "package-lock.json")),
719
806
  port: config.devServer.port,
720
807
  ...config.build.docker
721
808
  })
@@ -725,6 +812,7 @@ async function finishPresetBuild(root, config, preset) {
725
812
  DOCKERIGNORE
726
813
  );
727
814
  return "build with `docker build -f .output/Dockerfile -t my-app .`";
815
+ }
728
816
  case "bun":
729
817
  await precompressDir(path11.join(outDir, "public"));
730
818
  return "run with `bun .output/server/start.mjs`";
@@ -1007,7 +1095,7 @@ function noofpiPlugin(options) {
1007
1095
  return [
1008
1096
  userDoofpi ? `import userDoofpi from ${imp(userDoofpi)};` : "",
1009
1097
  userProxy ? `import userProxyHook from ${imp(userProxy)};` : "",
1010
- ssr ? `export { render } from 'noofpi/runtime/entry-server';` : "",
1098
+ ssr ? `export { render, renderStream } from 'noofpi/runtime/entry-server';` : "",
1011
1099
  `export const config = ${JSON.stringify(toServerConfig(config))};`,
1012
1100
  `export const doofpi = ${userDoofpi ? "userDoofpi" : "undefined"};`,
1013
1101
  `export const proxyHook = ${userProxy ? "userProxyHook" : "undefined"};`,
@@ -1038,6 +1126,7 @@ var RUNTIME_IMPORTS = [
1038
1126
  "useError",
1039
1127
  "useCookie",
1040
1128
  "useCookies",
1129
+ "useSession",
1041
1130
  "useDoofpi",
1042
1131
  "useDoofpiFetch",
1043
1132
  "useDoofpiForm",
@@ -1089,23 +1178,6 @@ function autoImportPlugins() {
1089
1178
  import { createHash as createHash2 } from "crypto";
1090
1179
  import { readFile as readFile3 } from "fs/promises";
1091
1180
  import path14 from "path";
1092
-
1093
- // src/optional.ts
1094
- async function importOptional(load, packages, feature) {
1095
- try {
1096
- return await load();
1097
- } catch (error) {
1098
- const { code, message } = error ?? {};
1099
- if ((code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND") && packages.some((name) => message?.includes(name)))
1100
- throw new Error(
1101
- `[noofpi] ${feature} needs ${packages.join(" and ")}: install ${packages.length > 1 ? "them" : "it"} with your package manager (for example \`bun add ${packages.join(" ")}\`)`,
1102
- { cause: error }
1103
- );
1104
- throw error;
1105
- }
1106
- }
1107
-
1108
- // src/vite/images.ts
1109
1181
  var IMAGE_QUERY = /^(.+\.(?:jpe?g|png|webp|avif))\?image$/i;
1110
1182
  async function processImage(file, images, options) {
1111
1183
  const { default: sharp } = await importOptional(
@@ -1236,6 +1308,8 @@ function createViteConfig(root, config, kind, fonts = NO_FONTS) {
1236
1308
  export {
1237
1309
  resolveFonts,
1238
1310
  htmlTemplate,
1311
+ scanPages,
1312
+ unsupportedStaticRules,
1239
1313
  startPlatformProxy,
1240
1314
  OUTPUT_DIR,
1241
1315
  finishPresetBuild,
@@ -1,6 +1,119 @@
1
1
  // src/fetch-mode.ts
2
2
  var FETCH_MODES = ["dfetch", "pfetch", "lfetch", "sfetch"];
3
3
 
4
+ // src/http.ts
5
+ var HEADER_NAME = /^[A-Za-z0-9-]+$/;
6
+ var FORBIDDEN_HEADER_VALUE = /[\u0000-\u001f\u007f]/;
7
+ var isHeaderName = (name) => HEADER_NAME.test(name);
8
+ var isHeaderValue = (value) => typeof value === "string" && !FORBIDDEN_HEADER_VALUE.test(value);
9
+ function modifyHeaders(response, change) {
10
+ try {
11
+ change(response.headers);
12
+ return response;
13
+ } catch {
14
+ const headers = new Headers(response.headers);
15
+ change(headers);
16
+ return new Response(response.body, {
17
+ status: response.status,
18
+ statusText: response.statusText,
19
+ headers
20
+ });
21
+ }
22
+ }
23
+ function appendVary(headers, value) {
24
+ const current = headers.get("vary");
25
+ if (current === "*") return;
26
+ const listed = (current ?? "").split(",").map((item) => item.trim().toLowerCase());
27
+ if (listed.includes(value.toLowerCase())) return;
28
+ headers.set("vary", current ? `${current}, ${value}` : value);
29
+ }
30
+
31
+ // src/cors.ts
32
+ var DEFAULT_METHODS = ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"];
33
+ var DEFAULT_MAX_AGE = 86400;
34
+ var METHOD = /^[A-Za-z]+$/;
35
+ var optionError = (option, expected) => new Error(`cors.${option} must be ${expected}`);
36
+ function originList(origin) {
37
+ if (origin === void 0 || origin === "*") return "*";
38
+ const list = typeof origin === "string" ? [origin] : origin;
39
+ if (!Array.isArray(list))
40
+ throw optionError("origin", '"*" or a list of origins');
41
+ return list.map((entry) => {
42
+ if (entry === "*") return "*";
43
+ try {
44
+ const parsed = new URL(entry);
45
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
46
+ throw new Error();
47
+ return parsed.origin;
48
+ } catch {
49
+ throw optionError("origin", `absolute http(s) origins (got "${entry}")`);
50
+ }
51
+ });
52
+ }
53
+ var stringList = (value, option, valid) => {
54
+ if (value === void 0) return void 0;
55
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || !valid(item)))
56
+ throw optionError(option, "a list of valid names");
57
+ return value;
58
+ };
59
+ function validateCors(options) {
60
+ if (typeof options === "boolean") return;
61
+ if (typeof options !== "object" || options === null)
62
+ throw new Error("cors must be a boolean or an object");
63
+ originList(options.origin);
64
+ stringList(options.methods, "methods", (item) => METHOD.test(item));
65
+ stringList(options.allowHeaders, "allowHeaders", isHeaderName);
66
+ stringList(options.exposeHeaders, "exposeHeaders", isHeaderName);
67
+ if (options.credentials !== void 0 && typeof options.credentials !== "boolean")
68
+ throw optionError("credentials", "a boolean");
69
+ if (options.maxAge !== void 0 && (!Number.isInteger(options.maxAge) || options.maxAge < 0))
70
+ throw optionError("maxAge", "a non-negative number of seconds");
71
+ }
72
+ function isPreflight(request) {
73
+ return request.method === "OPTIONS" && request.headers.has("origin") && request.headers.has("access-control-request-method");
74
+ }
75
+ function corsHeaders(options, request, preflight = false) {
76
+ const result = new Headers();
77
+ if (options === false) return result;
78
+ const config = options === true ? {} : options;
79
+ const requestOrigin = request.headers.get("origin");
80
+ if (requestOrigin === null) return result;
81
+ const allowed = originList(config.origin);
82
+ const credentials = config.credentials === true;
83
+ const wildcard = allowed === "*" || allowed.includes("*");
84
+ if (!wildcard && !allowed.includes(requestOrigin)) {
85
+ appendVary(result, "Origin");
86
+ return result;
87
+ }
88
+ if (wildcard && !credentials) result.set("Access-Control-Allow-Origin", "*");
89
+ else {
90
+ result.set("Access-Control-Allow-Origin", requestOrigin);
91
+ appendVary(result, "Origin");
92
+ }
93
+ if (credentials) result.set("Access-Control-Allow-Credentials", "true");
94
+ if (config.exposeHeaders?.length)
95
+ result.set(
96
+ "Access-Control-Expose-Headers",
97
+ config.exposeHeaders.join(", ")
98
+ );
99
+ if (preflight) {
100
+ result.set(
101
+ "Access-Control-Allow-Methods",
102
+ (config.methods ?? DEFAULT_METHODS).join(", ")
103
+ );
104
+ const requested = request.headers.get("access-control-request-headers");
105
+ const headers = config.allowHeaders?.join(", ") ?? requested;
106
+ if (headers) result.set("Access-Control-Allow-Headers", headers);
107
+ if (!config.allowHeaders)
108
+ appendVary(result, "Access-Control-Request-Headers");
109
+ result.set(
110
+ "Access-Control-Max-Age",
111
+ String(config.maxAge ?? DEFAULT_MAX_AGE)
112
+ );
113
+ }
114
+ return result;
115
+ }
116
+
4
117
  // src/csp.ts
5
118
  var NONCE_TOKEN = "'nonce'";
6
119
  var DIRECTIVE_NAME = /^[a-z][a-z0-9-]*$/;
@@ -85,18 +198,18 @@ var DEFAULT_HEADERS = {
85
198
  "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
86
199
  [HSTS]: "max-age=15552000"
87
200
  };
88
- var HEADER_NAME = /^[A-Za-z0-9-]+$/;
89
- var FORBIDDEN_HEADER_VALUE = /[\u0000-\u001f\u007f]/;
201
+ var HEADER_NAME2 = /^[A-Za-z0-9-]+$/;
202
+ var FORBIDDEN_HEADER_VALUE2 = /[\u0000-\u001f\u007f]/;
90
203
  function overlayHeaders(base, input) {
91
204
  if (input === false) return {};
92
205
  const merged = { ...base };
93
206
  if (input && typeof input === "object") {
94
207
  for (const [name, value] of Object.entries(input)) {
95
- if (!HEADER_NAME.test(name))
208
+ if (!HEADER_NAME2.test(name))
96
209
  throw new Error(
97
210
  `[noofpi] security.headers: "${name}" is not a valid header name`
98
211
  );
99
- if (value !== false && (typeof value !== "string" || FORBIDDEN_HEADER_VALUE.test(value)))
212
+ if (value !== false && (typeof value !== "string" || FORBIDDEN_HEADER_VALUE2.test(value)))
100
213
  throw new Error(
101
214
  `[noofpi] security.headers: "${name}" must be a string without control characters, or false`
102
215
  );
@@ -260,6 +373,7 @@ function applySecurityHeaders(response, headers, https) {
260
373
  }
261
374
 
262
375
  // src/route-rules.ts
376
+ var REDIRECT_STATUSES = [301, 302, 303, 307, 308];
263
377
  function patternToRegExp(pattern) {
264
378
  const source = pattern.split("/").map(
265
379
  (segment) => segment === "**" ? ".*" : segment.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*")
@@ -306,22 +420,124 @@ function validateRouteRules(rules, ssr) {
306
420
  );
307
421
  }
308
422
  }
423
+ validateServerRule(pattern, rule, ssr);
309
424
  }
310
425
  }
426
+ var fail = (pattern, message) => {
427
+ throw new Error(`[noofpi] routeRules["${pattern}"].${message}`);
428
+ };
429
+ var isCount = (value) => Number.isInteger(value) && value >= 0;
430
+ var isRedirectTarget = (to) => {
431
+ if (typeof to !== "string") return false;
432
+ if (to.startsWith("/")) return !to.startsWith("//") && !/[\s\\]/.test(to);
433
+ try {
434
+ const { protocol } = new URL(to);
435
+ return protocol === "http:" || protocol === "https:";
436
+ } catch {
437
+ return false;
438
+ }
439
+ };
440
+ function validateServerRule(pattern, rule, ssr) {
441
+ const rendered = ssr && rule.ssr !== false;
442
+ for (const option of ["prerender", "stream"]) {
443
+ const value = rule[option];
444
+ if (value === void 0) continue;
445
+ if (typeof value !== "boolean")
446
+ fail(pattern, `${option} must be a boolean`);
447
+ if (value && !rendered)
448
+ fail(
449
+ pattern,
450
+ `${option}: true needs server rendering (ssr: true, and no ssr: false on the route)`
451
+ );
452
+ }
453
+ const { cache } = rule;
454
+ if (cache !== void 0 && cache !== false) {
455
+ if (typeof cache !== "object" || cache === null)
456
+ fail(pattern, "cache must be an object or false");
457
+ if (!isCount(cache.maxAge))
458
+ fail(pattern, "cache.maxAge must be a number of seconds (0 or more)");
459
+ if (cache.swr !== void 0 && !isCount(cache.swr))
460
+ fail(pattern, "cache.swr must be a number of seconds (0 or more)");
461
+ if (cache.vary !== void 0 && (!Array.isArray(cache.vary) || !cache.vary.every(isVaryHeader)))
462
+ fail(pattern, "cache.vary must be a list of header names");
463
+ if (cache.server !== void 0 && typeof cache.server !== "boolean")
464
+ fail(pattern, "cache.server must be a boolean");
465
+ if (!rendered)
466
+ fail(pattern, "cache only applies to server-rendered pages (needs ssr)");
467
+ }
468
+ if (rule.headers !== void 0) {
469
+ if (typeof rule.headers !== "object" || rule.headers === null)
470
+ fail(pattern, "headers must be an object");
471
+ for (const [name, value] of Object.entries(rule.headers)) {
472
+ if (!isHeaderName(name))
473
+ fail(pattern, `headers: "${name}" is not a valid header name`);
474
+ if (!isHeaderValue(value))
475
+ fail(
476
+ pattern,
477
+ `headers: "${name}" must be a string without control characters`
478
+ );
479
+ }
480
+ }
481
+ if (rule.redirect !== void 0) {
482
+ const { to, status } = normalizeRedirect(rule.redirect);
483
+ if (!isRedirectTarget(to))
484
+ fail(
485
+ pattern,
486
+ `redirect must be a path starting with "/" or an absolute http(s) URL (got "${String(to)}")`
487
+ );
488
+ if (!REDIRECT_STATUSES.includes(status))
489
+ fail(
490
+ pattern,
491
+ `redirect.status must be one of ${REDIRECT_STATUSES.join(", ")} (got ${String(status)})`
492
+ );
493
+ if (to.endsWith("/**") && !/^[^*]*\/\*\*$/.test(pattern))
494
+ fail(
495
+ pattern,
496
+ `redirect to "${to}" keeps the rest of the path, so the pattern has to end with "/**" and have no other "*"`
497
+ );
498
+ }
499
+ if (rule.cors !== void 0) {
500
+ try {
501
+ validateCors(rule.cors);
502
+ } catch (error) {
503
+ fail(pattern, error.message);
504
+ }
505
+ }
506
+ }
507
+ var isVaryHeader = (name) => typeof name === "string" && isHeaderName(name);
508
+ function normalizeRedirect(redirect) {
509
+ return typeof redirect === "string" ? { to: redirect, status: 307 } : { to: redirect?.to, status: redirect?.status ?? 307 };
510
+ }
311
511
  function matchRouteRules(rules, pathname) {
312
512
  const merged = {};
313
513
  Object.keys(rules).filter((pattern) => patternToRegExp(pattern).test(pathname)).sort((a, b) => a.length - b.length).forEach((pattern) => {
314
- const { security, ...rest } = rules[pattern];
514
+ const { security, headers, cors, ...rest } = rules[pattern];
315
515
  Object.assign(merged, rest);
316
516
  if (security) merged.security = { ...merged.security, ...security };
517
+ if (headers) merged.headers = { ...merged.headers, ...headers };
518
+ if (cors !== void 0)
519
+ merged.cors = typeof cors === "object" && typeof merged.cors === "object" ? { ...merged.cors, ...cors } : cors;
317
520
  });
318
521
  return merged;
319
522
  }
523
+ function matchRedirect(rules, pathname) {
524
+ const pattern = Object.keys(rules).filter(
525
+ (candidate) => rules[candidate].redirect !== void 0 && patternToRegExp(candidate).test(pathname)
526
+ ).sort((a, b) => b.length - a.length)[0];
527
+ if (pattern === void 0) return void 0;
528
+ const { to, status } = normalizeRedirect(rules[pattern].redirect);
529
+ if (!to.endsWith("/**")) return { to, status };
530
+ const rest = pathname.slice(pattern.length - "/**".length);
531
+ return { to: to.slice(0, -3) + rest, status };
532
+ }
320
533
  function toPublicRouteRules(rules) {
321
534
  return Object.fromEntries(
322
- Object.entries(rules).map(([pattern, { security: _security, ...rule }]) => [
535
+ Object.entries(rules).map(([pattern, { ssr, fetch }]) => [
323
536
  pattern,
324
- rule
537
+ {
538
+ ...ssr !== void 0 ? { ssr } : {},
539
+ ...fetch !== void 0 ? { fetch } : {}
540
+ }
325
541
  ])
326
542
  );
327
543
  }
@@ -337,6 +553,10 @@ function isServerRendered(ssr, rules, pathname) {
337
553
 
338
554
  export {
339
555
  FETCH_MODES,
556
+ modifyHeaders,
557
+ appendVary,
558
+ isPreflight,
559
+ corsHeaders,
340
560
  usesNonce,
341
561
  generateNonce,
342
562
  buildCspHeader,
@@ -347,9 +567,11 @@ export {
347
567
  limitRequestBody,
348
568
  isCrossSiteWrite,
349
569
  applySecurityHeaders,
570
+ REDIRECT_STATUSES,
350
571
  matchesRoutePattern,
351
572
  validateRouteRules,
352
573
  matchRouteRules,
574
+ matchRedirect,
353
575
  toPublicRouteRules,
354
576
  resolveFetchMode,
355
577
  usesFetchMode,