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
@@ -0,0 +1,26 @@
1
+ import { f as ServerModule } from './types-Czld0vOH.js';
2
+
3
+ interface HandlerOptions {
4
+ /** Returns the generated server module (`virtual:noofpi/server`, or the built bundle in production) */
5
+ load: () => Promise<ServerModule>;
6
+ /** Returns the HTML shell for a page URL */
7
+ getTemplate: (url: string) => Promise<string>;
8
+ onError?: (error: unknown) => void;
9
+ /**
10
+ * Rendering pages into files (`noofpi generate`): no streaming, no server cache, no visitor session and no CSP
11
+ * nonces, because the HTML is written once and served to everybody
12
+ */
13
+ prerender?: boolean;
14
+ }
15
+ /** What a runtime that kills the request's work when the response is sent (Workers) offers to keep it alive */
16
+ interface HandlerContext {
17
+ waitUntil(promise: Promise<unknown>): void;
18
+ }
19
+ type Handler = (request: Request, env?: unknown, ctx?: HandlerContext) => Promise<Response>;
20
+ /**: one web-standard `fetch(Request) -> Response` handler.
21
+ * Order: redirects and CORS preflights -> middleware -> proxy (pfetch) -> local doofpi API -> HTML (SSR render or SPA shell).
22
+ */
23
+ declare function createHandler(options: HandlerOptions): Handler;
24
+
25
+ export { createHandler as c };
26
+ export type { Handler as H, HandlerContext as a, HandlerOptions as b };
package/dist/index.d.ts CHANGED
@@ -1,17 +1,19 @@
1
1
  import { UserConfig } from 'vite';
2
- import { R as RouteRules, H as HeadConfig, S as SecurityConfig, F as FetchMode } from './route-rules-COilNsVT.js';
3
- export { C as CspConfig, a as CspDirectiveName, b as CspDirectiveValue, c as CsrfConfig, d as FETCH_MODES, e as HeadInput, f as HeadTag, g as RouteRule } from './route-rules-COilNsVT.js';
2
+ import { R as RouteRules, S as SessionConfig, H as HeadConfig, a as SecurityConfig, F as FetchMode } from './session-CLvYihOU.js';
3
+ export { C as CacheRule, b as CorsOptions, c as CspConfig, d as CspDirectiveName, e as CspDirectiveValue, f as CsrfConfig, g as FETCH_MODES, h as HeadInput, i as HeadTag, j as RedirectRule, k as RouteRule, l as Session, m as SessionData } from './session-CLvYihOU.js';
4
4
  import { I as ImagesConfig, a as I18nConfig } from './images-BNwTAi50.js';
5
5
  export { b as ImageFormat } from './images-BNwTAi50.js';
6
6
 
7
- declare const BUILD_PRESETS: readonly ["node", "bun", "docker", "cloudflare-worker", "cloudflare-pages", "github-pages"];
7
+ declare const BUILD_PRESETS: readonly ["node", "bun", "docker-node", "docker-bun", "cloudflare-worker", "cloudflare-pages", "github-pages"];
8
8
  /**
9
9
  * - `node`: `.output/` runs with `noofpi start` or `node .output/server/start.mjs`
10
10
  * - `bun`: like `node`, served with `Bun.serve` (`bun .output/server/start.mjs`)
11
- * - `docker`: like `node`, plus `.output/Dockerfile`
11
+ * - `docker-node`: like `node`, plus `.output/Dockerfile` for a Node image
12
+ * - `docker-bun`: like `bun`, plus `.output/Dockerfile` for a Bun image
12
13
  * - `cloudflare-worker`: one bundled Worker (`server/index.mjs`) with static assets, plus `wrangler.json`
13
14
  * - `cloudflare-pages`: `public/` with a bundled `_worker.js`, deployable with `wrangler pages deploy`
14
- * - `github-pages`: static client-only SPA in `public/` (no server): `index.html`, a `404.html` fallback and `.nojekyll`
15
+ * - `github-pages`: static files in `public/` (no server): `index.html`, a `404.html` client-router fallback and `.nojekyll`. A client-only SPA, or with `routeRules` `prerender` (`noofpi generate`) real HTML for the marked pages
16
+ * - `cloudflare-pages` also takes `noofpi generate`: static files with `_headers` and `_redirects` instead of a Worker
15
17
  */
16
18
  type BuildPreset = (typeof BUILD_PRESETS)[number];
17
19
 
@@ -67,6 +69,13 @@ interface FontsConfig {
67
69
  families: FontFamily[];
68
70
  }
69
71
 
72
+ interface PrerenderConfig {
73
+ /** Pages to prerender besides the ones `routeRules` marks: URLs of dynamic pages that nothing links to (`/users/42`) */
74
+ routes?: string[];
75
+ /** Also prerender the pages that prerendered pages link to, when they are marked for prerendering. Default: `true` */
76
+ crawlLinks?: boolean;
77
+ }
78
+
70
79
  interface SeoConfig {
71
80
  /** Public URL of the site (`https://example.com`, or with a path for project sites). Needed for the sitemap, whose URLs are absolute */
72
81
  siteUrl?: string;
@@ -81,8 +90,14 @@ interface SeoConfig {
81
90
  interface NoofpiConfig {
82
91
  /** Render pages on the server (`true`, default) or ship a client-only SPA (`false`) */
83
92
  ssr?: boolean;
84
- /** Per-route overrides keyed by URL pattern (`/admin/**`, `/users/*`, `/about`), e.g. `{ "/admin/**": { ssr: false, fetch: "pfetch" } }` */
93
+ /** Stream server-rendered pages: the HTML shell is sent as soon as the route is resolved and the page follows while data loads. Default: `false`. `routeRules[...].stream` overrides it per route */
94
+ streaming?: boolean;
95
+ /** Per-route overrides keyed by URL pattern (`/admin/**`, `/users/*`, `/about`), e.g. `{ "/admin/**": { ssr: false, fetch: "pfetch" }, "/blog/**": { prerender: true, cache: { maxAge: 60, swr: 600 } } }` */
85
96
  routeRules?: RouteRules;
97
+ /** What `noofpi generate` prerenders besides the pages `routeRules` marks with `prerender: true` */
98
+ prerender?: PrerenderConfig;
99
+ /** Signed or encrypted cookie sessions: `getSession(request)` on the server, `useSession()` in components, `sessionGuard()` for a server middleware. Needs the `NOOFPI_SESSION_SECRET` environment variable. `true` for the defaults. Off unless set */
100
+ session?: boolean | SessionConfig;
86
101
  /** Default `<head>` of every page: `title` (put `%s` where a page's `useHead({ title })` goes), `meta`, `link`, `htmlAttrs`, `bodyAttrs` */
87
102
  head?: HeadConfig;
88
103
  /** Enable the built-in Tailwind CSS (v4) vite plugin */
@@ -114,11 +129,11 @@ interface NoofpiConfig {
114
129
  host?: string;
115
130
  };
116
131
  build?: {
117
- /** Deploy target of `noofpi build`: `node` (default), `bun`, `docker`, `cloudflare-worker`, `cloudflare-pages` or `github-pages` (static SPA). `--preset` overrides it */
132
+ /** Deploy target of `noofpi build`: `node` (default), `bun`, `docker-node`, `docker-bun`, `cloudflare-worker`, `cloudflare-pages` or `github-pages` (static SPA). `--preset` overrides it */
118
133
  preset?: BuildPreset;
119
- /** Options of the generated `.output/Dockerfile` (`docker` preset) */
134
+ /** Options of the generated `.output/Dockerfile` (`docker-node` and `docker-bun` presets) */
120
135
  docker?: {
121
- /** Base image of both build stages. Default: `node:22-alpine` (`oven/bun:1` when the project uses bun) */
136
+ /** Base image of both build stages. Default: `node:22-alpine` (`oven/bun:1` with `docker-bun`) */
122
137
  image?: string;
123
138
  /** Path the image `HEALTHCHECK` requests (any status below 500 is healthy), or `false` for no healthcheck. Default: `/` */
124
139
  healthcheck?: string | false;
@@ -131,5 +146,5 @@ interface NoofpiConfig {
131
146
  }
132
147
  declare function defineNoofpiConfig(config: NoofpiConfig): NoofpiConfig;
133
148
 
134
- export { BUILD_PRESETS, FONT_PROVIDERS, FetchMode, HeadConfig, I18nConfig, ImagesConfig, RouteRules, SecurityConfig, defineNoofpiConfig };
135
- export type { BuildPreset, FontDisplay, FontFamily, FontProviderName, FontStyle, FontWeight, FontsConfig, GoogleFontFamily, LocalFontFamily, LocalFontFile, NoofpiConfig, SeoConfig };
149
+ export { BUILD_PRESETS, FONT_PROVIDERS, FetchMode, HeadConfig, I18nConfig, ImagesConfig, RouteRules, SecurityConfig, SessionConfig, defineNoofpiConfig };
150
+ export type { BuildPreset, FontDisplay, FontFamily, FontProviderName, FontStyle, FontWeight, FontsConfig, GoogleFontFamily, LocalFontFamily, LocalFontFile, NoofpiConfig, PrerenderConfig, SeoConfig };
package/dist/index.js CHANGED
@@ -2,11 +2,12 @@ import {
2
2
  BUILD_PRESETS,
3
3
  FONT_PROVIDERS,
4
4
  defineNoofpiConfig
5
- } from "./chunk-IE3WF5XF.js";
5
+ } from "./chunk-YN4TKMDX.js";
6
+ import "./chunk-O5JRC252.js";
6
7
  import "./chunk-ELXCFUA4.js";
7
8
  import {
8
9
  FETCH_MODES
9
- } from "./chunk-MN5PVHC5.js";
10
+ } from "./chunk-W7ASRDAJ.js";
10
11
  export {
11
12
  BUILD_PRESETS,
12
13
  FETCH_MODES,
@@ -0,0 +1,66 @@
1
+ import { F as FetchMode } from './session-CLvYihOU.js';
2
+
3
+ /** The error shown by `app/error.vue`: what the page receives in its `error` prop */
4
+ interface NoofpiErrorData {
5
+ statusCode: number;
6
+ statusMessage: string;
7
+ message: string;
8
+ /** The URL that was being rendered */
9
+ url?: string;
10
+ }
11
+ interface CreateErrorInput {
12
+ statusCode?: number;
13
+ statusMessage?: string;
14
+ message?: string;
15
+ }
16
+ /** Marks errors made by `createError()`, which stay recognizable when the module is loaded twice */
17
+ declare const BRAND = "__noofpiError";
18
+ declare class NoofpiError extends Error implements NoofpiErrorData {
19
+ readonly [BRAND] = true;
20
+ statusCode: number;
21
+ statusMessage: string;
22
+ url?: string;
23
+ constructor(input?: CreateErrorInput);
24
+ }
25
+ /**
26
+ * Creates an error to `throw` from a page's setup, a route middleware (or pass it to
27
+ * `showError()`): when the project has an `app/error.vue`, it is rendered with this error and the response gets its status.
28
+ */
29
+ declare function createError(input: string | CreateErrorInput): NoofpiError;
30
+
31
+ /** A doofpi request seen by the dev request inspector */
32
+ interface RequestEntry {
33
+ /** Where the request was made: while rendering on the server or in the browser */
34
+ side: "server" | "browser";
35
+ mode: FetchMode;
36
+ /** `in-process` never touches the network (SSR `lfetch` / `pfetch` call the noofpi server directly) */
37
+ transport: "in-process" | "http";
38
+ method: string;
39
+ url: string;
40
+ /** `undefined` while the request is pending or when it failed before a response */
41
+ status?: number;
42
+ /** Milliseconds until the response headers arrived (or the request failed) */
43
+ ms?: number;
44
+ error?: string;
45
+ }
46
+
47
+ /** Data collected during SSR and handed to the browser so it does not fetch again */
48
+ interface PayloadData {
49
+ data: Record<string, unknown>;
50
+ errors: Record<string, AsyncDataError>;
51
+ /** Values of `useState` by key */
52
+ state?: Record<string, unknown>;
53
+ /** Set when the server rendered the error page, so the browser hydrates the same one */
54
+ error?: NoofpiErrorData;
55
+ /** The locale the server rendered in (only with `i18n`), so the browser hydrates in the same one */
56
+ locale?: string;
57
+ /** Dev only: the doofpi requests the server made while rendering, for the dev request inspector */
58
+ requests?: RequestEntry[];
59
+ }
60
+ interface AsyncDataError {
61
+ message: string;
62
+ status?: number;
63
+ }
64
+
65
+ export { NoofpiError as a, createError as c };
66
+ export type { AsyncDataError as A, CreateErrorInput as C, NoofpiErrorData as N, PayloadData as P, RequestEntry as R };
@@ -1,12 +1,13 @@
1
1
  import {
2
2
  createViteConfig
3
- } from "./chunk-NHBXVKEQ.js";
4
- import "./chunk-IE3WF5XF.js";
5
- import "./chunk-MTXQR32N.js";
3
+ } from "./chunk-PL3CA2JF.js";
4
+ import "./chunk-YN4TKMDX.js";
5
+ import "./chunk-LJEKK4AK.js";
6
+ import "./chunk-O5JRC252.js";
6
7
  import "./chunk-PPUFFGCH.js";
7
8
  import "./chunk-ELXCFUA4.js";
8
- import "./chunk-G35DW4NA.js";
9
- import "./chunk-MN5PVHC5.js";
9
+ import "./chunk-PC3ZJN4D.js";
10
+ import "./chunk-W7ASRDAJ.js";
10
11
  import "./chunk-Y3NBZ6DW.js";
11
12
 
12
13
  // src/vite/prepare.ts
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  createNoofpiApp
3
- } from "../chunk-YJVMBHNL.js";
3
+ } from "../chunk-JUVQEKLE.js";
4
4
  import "../chunk-6OWKWAIW.js";
5
5
  import "../chunk-ELXCFUA4.js";
6
6
  import "../chunk-EZPJF4D4.js";
7
- import "../chunk-G35DW4NA.js";
8
- import "../chunk-MN5PVHC5.js";
7
+ import "../chunk-PC3ZJN4D.js";
8
+ import "../chunk-W7ASRDAJ.js";
9
9
 
10
10
  // src/runtime/entry-client.ts
11
11
  import { publicConfig } from "virtual:noofpi/config";
@@ -53,7 +53,7 @@ async function mount() {
53
53
  );
54
54
  await i18n?.ready;
55
55
  if (import.meta.env.DEV && publicConfig.devtools) {
56
- const { mountDevtools } = await import("../devtools-PLUN2DYV.js");
56
+ const { mountDevtools } = await import("../devtools-C3PFU57C.js");
57
57
  mountDevtools({
58
58
  router,
59
59
  config: publicConfig,
@@ -1,8 +1,10 @@
1
- import { RenderContext, RenderResult } from '../server/index.js';
1
+ import { RenderContext, RenderResult, StreamRenderResult } from '../server/index.js';
2
2
  import 'doofpi';
3
- import '../route-rules-COilNsVT.js';
4
- import '../payload-CL6tYBin.js';
3
+ import '../session-CLvYihOU.js';
4
+ import '../payload-DfhHnXAn.js';
5
5
 
6
6
  declare function render(url: string, ctx: RenderContext): Promise<RenderResult>;
7
+ /** Like `render`, but the page markup is returned as a stream (see `renderRouteStream`) */
8
+ declare function renderStream(url: string, ctx: RenderContext): Promise<RenderResult | StreamRenderResult>;
7
9
 
8
- export { render };
10
+ export { render, renderStream };
@@ -4,67 +4,119 @@ import {
4
4
  notFoundError,
5
5
  setServerStateSource,
6
6
  snapshotEntries
7
- } from "../chunk-YJVMBHNL.js";
7
+ } from "../chunk-JUVQEKLE.js";
8
8
  import "../chunk-6OWKWAIW.js";
9
9
  import "../chunk-ELXCFUA4.js";
10
10
  import {
11
11
  isNoofpiError,
12
12
  toErrorData
13
13
  } from "../chunk-EZPJF4D4.js";
14
- import "../chunk-G35DW4NA.js";
15
- import "../chunk-MN5PVHC5.js";
14
+ import "../chunk-PC3ZJN4D.js";
15
+ import "../chunk-W7ASRDAJ.js";
16
16
 
17
17
  // src/runtime/entry-server.ts
18
18
  import { AsyncLocalStorage } from "async_hooks";
19
- import { renderToString } from "vue/server-renderer";
19
+ import { renderToString, renderToWebStream } from "vue/server-renderer";
20
20
  import ErrorPage from "virtual:noofpi/error";
21
21
  var requestScope = new AsyncLocalStorage();
22
22
  setServerStateSource(() => requestScope.getStore()?.payload);
23
- async function renderRoute(url, ctx) {
24
- const { app, router, payload, head, error, log, i18n } = createNoofpiApp({
25
- server: true,
26
- ...ctx
27
- });
23
+ async function prepareRoute(url, ctx) {
24
+ const created = createNoofpiApp({ server: true, ...ctx });
25
+ const { app, router, payload, error } = created;
28
26
  requestScope.getStore().payload = payload;
29
27
  const failure = await router.push(url);
30
28
  await router.isReady();
31
29
  if (failure) {
32
- if (!ErrorPage) return { html: "", status: 404 };
30
+ if (!ErrorPage) return { early: { html: "", status: 404 } };
33
31
  error.value = notFoundError(url);
34
32
  } else {
35
33
  const requested = router.resolve(url).fullPath;
36
34
  const current = router.currentRoute.value.fullPath;
37
35
  if (current !== requested) {
38
36
  return {
39
- html: "",
40
- status: 302,
41
- // One leading slash only, so a redirect can never turn into a protocol-relative (external) URL
42
- redirect: "/" + current.replace(/^\/+/, "")
37
+ early: {
38
+ html: "",
39
+ status: 302,
40
+ // One leading slash only, so a redirect can never turn into a protocol-relative (external) URL
41
+ redirect: "/" + current.replace(/^\/+/, "")
42
+ }
43
43
  };
44
44
  }
45
45
  if (ErrorPage && !router.currentRoute.value.matched.length)
46
46
  error.value = notFoundError(url);
47
47
  }
48
+ return { prepared: created };
49
+ }
50
+ var statusOf = ({ router, error }) => error.value ? error.value.statusCode : router.currentRoute.value.matched.length ? 200 : 404;
51
+ function payloadOf({ payload, error, log, i18n }) {
52
+ return {
53
+ data: payload.data,
54
+ errors: payload.errors,
55
+ state: collectState(payload),
56
+ ...error.value ? { error: error.value } : {},
57
+ ...i18n ? { locale: i18n.locale.value } : {},
58
+ ...log ? { requests: snapshotEntries(log) } : {}
59
+ };
60
+ }
61
+ async function renderRoute(url, ctx) {
62
+ const route = await prepareRoute(url, ctx);
63
+ if ("early" in route) return route.early;
64
+ const prepared = route.prepared;
65
+ const { app, head } = prepared;
48
66
  const failures = [];
49
67
  if (ErrorPage)
50
- app.config.errorHandler = (failure2) => void failures.push(failure2);
68
+ app.config.errorHandler = (failure) => void failures.push(failure);
51
69
  const html = await renderToString(app);
52
70
  if (failures.length) throw failures[0];
53
71
  return {
54
72
  html,
55
- status: error.value ? error.value.statusCode : router.currentRoute.value.matched.length ? 200 : 404,
56
- payload: {
57
- data: payload.data,
58
- errors: payload.errors,
59
- state: collectState(payload),
60
- ...error.value ? { error: error.value } : {},
61
- ...i18n ? { locale: i18n.locale.value } : {},
62
- ...log ? { requests: snapshotEntries(log) } : {}
63
- },
73
+ status: statusOf(prepared),
74
+ payload: payloadOf(prepared),
64
75
  // Resolved after rendering, so titles that depend on fetched data are included
65
76
  head: head.resolve()
66
77
  };
67
78
  }
79
+ async function renderRouteStream(url, ctx) {
80
+ const route = await prepareRoute(url, ctx);
81
+ if ("early" in route) return route.early;
82
+ const prepared = route.prepared;
83
+ const { app, head } = prepared;
84
+ const failures = [];
85
+ if (ErrorPage)
86
+ app.config.errorHandler = (failure) => void failures.push(failure);
87
+ const stream = renderToWebStream(app);
88
+ const reader = stream.getReader();
89
+ const first = await reader.read();
90
+ if (failures.length) {
91
+ await reader.cancel().catch(() => {
92
+ });
93
+ throw failures[0];
94
+ }
95
+ let queued = first.done ? void 0 : first.value;
96
+ const body = new ReadableStream({
97
+ async pull(controller) {
98
+ if (queued) {
99
+ controller.enqueue(queued);
100
+ queued = void 0;
101
+ return;
102
+ }
103
+ const { done, value } = await reader.read();
104
+ if (done) controller.close();
105
+ else controller.enqueue(value);
106
+ },
107
+ cancel: (reason) => reader.cancel(reason)
108
+ });
109
+ return {
110
+ status: statusOf(prepared),
111
+ head: head.resolve(),
112
+ body,
113
+ finish: () => ({
114
+ payload: payloadOf(prepared),
115
+ head: head.resolve(),
116
+ ...failures.length ? { error: failures[0] } : {}
117
+ })
118
+ };
119
+ }
68
120
  async function renderErrorPage(url, ctx, failure) {
69
121
  const { app, payload, head, error, log, i18n } = createNoofpiApp({
70
122
  server: true,
@@ -102,6 +154,17 @@ function render(url, ctx) {
102
154
  }
103
155
  });
104
156
  }
157
+ function renderStream(url, ctx) {
158
+ return requestScope.run({}, async () => {
159
+ try {
160
+ return await renderRouteStream(url, ctx);
161
+ } catch (failure) {
162
+ if (!ErrorPage) throw failure;
163
+ return await renderErrorPage(url, ctx, failure);
164
+ }
165
+ });
166
+ }
105
167
  export {
106
- render
168
+ render,
169
+ renderStream
107
170
  };
@@ -2,14 +2,14 @@ import * as vue from 'vue';
2
2
  import { Ref, ComputedRef, ShallowRef, MaybeRefOrGetter, App, PropType, VNode } from 'vue';
3
3
  import * as vue_router from 'vue-router';
4
4
  import { RouteLocationNormalized, RouteParams, LocationQuery, Router, NavigationGuardReturn, LocationQueryRaw, NavigationFailure, RouteLocationRaw } from 'vue-router';
5
- import { A as AsyncDataError, R as RequestEntry, N as NoofpiErrorData, C as CreateErrorInput, a as NoofpiError, b as CookieJar, c as CookieOptions, d as CookieCodec, e as CookieDefinition } from '../payload-CL6tYBin.js';
5
+ import { A as AsyncDataError, R as RequestEntry, N as NoofpiErrorData, C as CreateErrorInput, a as NoofpiError } from '../payload-DfhHnXAn.js';
6
6
  import { PayloadData } from '../server/index.js';
7
- export { f as booleanCodec, g as createError, h as defineCookie, i as enumCodec, j as jsonCodec, n as numberCodec, s as stringCodec } from '../payload-CL6tYBin.js';
7
+ export { c as createError } from '../payload-DfhHnXAn.js';
8
8
  import Doofpi, { createClient, ClientFetch } from 'doofpi';
9
- import { e as HeadInput } from '../route-rules-COilNsVT.js';
9
+ import { h as HeadInput, o as CookieJar, m as SessionData, p as CookieOptions, q as CookieCodec, r as CookieDefinition } from '../session-CLvYihOU.js';
10
10
  import { FetchMode } from '../index.js';
11
11
  import { ResolvedHead } from '../server/index.js';
12
- export { H as HeadConfig, f as HeadTag, g as RouteRule, R as RouteRules } from '../route-rules-COilNsVT.js';
12
+ export { C as CacheRule, b as CorsOptions, H as HeadConfig, i as HeadTag, j as RedirectRule, k as RouteRule, R as RouteRules, s as booleanCodec, t as defineCookie, u as enumCodec, v as jsonCodec, w as numberCodec, x as stringCodec } from '../session-CLvYihOU.js';
13
13
  import { M as Messages, c as MessageParamValue, d as ImageSource } from '../images-BNwTAi50.js';
14
14
  import { F as FormErrors, a as FormSchema } from '../validation-Dwpex2JZ.js';
15
15
  export { b as FORM_ERROR_KEY, I as InferSchema, V as ValidationIssue, c as ValidationResult, e as errorsFromFailure, i as issuesToErrors, v as validate } from '../validation-Dwpex2JZ.js';
@@ -269,6 +269,8 @@ interface NoofpiAppContext extends Omit<DoofpiClientContext, "origin"> {
269
269
  acceptLanguage?: string;
270
270
  /** The server's jar for the request; without it the server builds one from `cookie` and the browser uses `document.cookie` */
271
271
  cookies?: CookieJar;
272
+ /** The part of the session the browser may see (server only), shown by `useSession()` */
273
+ session?: SessionData;
272
274
  }
273
275
  declare function createNoofpiApp(ctx: NoofpiAppContext): {
274
276
  app: App;
@@ -329,6 +331,22 @@ declare function useCookie<T>(cookie: CookieDefinition<T>, options: UseCookieOpt
329
331
  }): Ref<T>;
330
332
  declare function useCookie<T>(cookie: CookieDefinition<T>, options?: UseCookieOptions<T>): Ref<T | undefined>;
331
333
 
334
+ interface UseSession<T extends SessionData = SessionData> {
335
+ /**
336
+ * The part of the session the `session.expose` option lists: set by the server while it renders, so SSR and hydration
337
+ * agree. Read-only here; change the session on the server (a doofpi endpoint, a server middleware)
338
+ */
339
+ data: Readonly<Ref<Readonly<T>>>;
340
+ /** Fetches the session again, e.g. after logging in or out through the API. It does nothing on the server */
341
+ refresh(): Promise<void>;
342
+ }
343
+ /**
344
+ * The visitor's session as far as the browser may see it (the keys of `session.expose`), on the server and in the
345
+ * browser. The full session, with what must stay private, is only reachable on the server with `getSession(request)`
346
+ * from `noofpi/server`. Call it inside `setup()`, a route middleware or any code that runs while rendering.
347
+ */
348
+ declare function useSession<T extends SessionData = SessionData>(): UseSession<T>;
349
+
332
350
  /**
333
351
  * `useAsyncData` with the doofpi client handed to the handler: fetched on the server, transferred to the browser,
334
352
  * not fetched again while hydrating. The client is typed by the `Register` routes of its mode (`localRoutes` for
@@ -556,5 +574,5 @@ declare function navigateTo<T extends RouteLocationRaw>(to: T extends keyof Regi
556
574
  params?: Record<string, RouteParamValue>;
557
575
  }): Promise<NavigationFailure | void | undefined>;
558
576
 
559
- export { AsyncDataError, ClientOnly, CookieCodec, CookieDefinition, CookieJar, CookieOptions, CreateErrorInput, FormErrors, FormSchema, HeadInput, ImageSource, MessageParamValue, Messages, NoofpiError, NoofpiErrorData, NoofpiImage, NoofpiLayout, NoofpiLink, NoofpiPage, RequestEntry, clearError, createDoofpiClient, createNoofpiApp, defineMessages, defineNoofpiPlugin, definePage, defineRouteMiddleware, navigateTo, showError, useAsyncData, useCookie, useCookies, useDoofpi, useDoofpiFetch, useDoofpiForm, useError, useHead, useI18n, useLayout, useLoaderData, useMiddleware, useState };
560
- export type { AsyncData, DoofpiClient, DoofpiClientConfig, DoofpiClientContext, DoofpiForm, I18n, LoaderContext, LoaderData, Locale, LocaleMessages, MessageArgs, MessageKey, NavigateToOptions, NoofpiPlugin, NoofpiPluginContext, PageDefinition, PageLoader, Register, RegisteredLocalRoutes, RegisteredMessages, RegisteredPages, RegisteredRemoteRoutes, RegisteredRoutes, RouteMiddleware, RouteParamValue, RoutesForMode, SubmitResult, TranslateFunction, UseAsyncDataOptions, UseCookieCodecOptions, UseCookieOptions, UseDoofpiFormOptions, UseDoofpiOptions };
577
+ export { AsyncDataError, ClientOnly, CookieCodec, CookieDefinition, CookieJar, CookieOptions, CreateErrorInput, FormErrors, FormSchema, HeadInput, ImageSource, MessageParamValue, Messages, NoofpiError, NoofpiErrorData, NoofpiImage, NoofpiLayout, NoofpiLink, NoofpiPage, RequestEntry, SessionData, clearError, createDoofpiClient, createNoofpiApp, defineMessages, defineNoofpiPlugin, definePage, defineRouteMiddleware, navigateTo, showError, useAsyncData, useCookie, useCookies, useDoofpi, useDoofpiFetch, useDoofpiForm, useError, useHead, useI18n, useLayout, useLoaderData, useMiddleware, useSession, useState };
578
+ export type { AsyncData, DoofpiClient, DoofpiClientConfig, DoofpiClientContext, DoofpiForm, I18n, LoaderContext, LoaderData, Locale, LocaleMessages, MessageArgs, MessageKey, NavigateToOptions, NoofpiPlugin, NoofpiPluginContext, PageDefinition, PageLoader, Register, RegisteredLocalRoutes, RegisteredMessages, RegisteredPages, RegisteredRemoteRoutes, RegisteredRoutes, RouteMiddleware, RouteParamValue, RoutesForMode, SubmitResult, TranslateFunction, UseAsyncDataOptions, UseCookieCodecOptions, UseCookieOptions, UseDoofpiFormOptions, UseDoofpiOptions, UseSession };
@@ -15,8 +15,9 @@ import {
15
15
  useHead,
16
16
  useI18n,
17
17
  useLoaderData,
18
+ useSession,
18
19
  useState
19
- } from "../chunk-YJVMBHNL.js";
20
+ } from "../chunk-JUVQEKLE.js";
20
21
  import {
21
22
  defineRouteMiddleware,
22
23
  useMiddleware
@@ -37,8 +38,8 @@ import {
37
38
  numberCodec,
38
39
  stringCodec
39
40
  } from "../chunk-EZPJF4D4.js";
40
- import "../chunk-G35DW4NA.js";
41
- import "../chunk-MN5PVHC5.js";
41
+ import "../chunk-PC3ZJN4D.js";
42
+ import "../chunk-W7ASRDAJ.js";
42
43
  import {
43
44
  NoofpiLayout,
44
45
  NoofpiLink,
@@ -219,6 +220,7 @@ export {
219
220
  useLayout,
220
221
  useLoaderData,
221
222
  useMiddleware,
223
+ useSession,
222
224
  useState,
223
225
  validate
224
226
  };
@@ -1,8 +1,8 @@
1
1
  import { Handler } from './index.js';
2
- import '../types-B6rQOOxS.js';
2
+ import '../types-Czld0vOH.js';
3
3
  import 'doofpi';
4
- import '../route-rules-COilNsVT.js';
5
- import '../payload-CL6tYBin.js';
4
+ import '../session-CLvYihOU.js';
5
+ import '../payload-DfhHnXAn.js';
6
6
 
7
7
  /** Serves a handler with `Bun.serve`: static files of `publicDir` first, then the handler. */
8
8
  declare function serveBun(options: {
@@ -1,10 +1,10 @@
1
- export { H as Handler, a as HandlerOptions, c as createHandler } from '../handler-C6NnwBfC.js';
2
- import { P as ProxyHook, S as ServerMiddleware } from '../types-B6rQOOxS.js';
3
- export { b as PROXY_PREFIX, R as RenderContext, a as RenderResult, c as ServerConfig, d as ServerMiddlewareContext, e as ServerModule } from '../types-B6rQOOxS.js';
4
- import { b as CookieJar } from '../payload-CL6tYBin.js';
5
- export { d as CookieCodec, e as CookieDefinition, c as CookieOptions, P as PayloadData, f as booleanCodec, h as defineCookie, i as enumCodec, j as jsonCodec, n as numberCodec, s as stringCodec } from '../payload-CL6tYBin.js';
1
+ export { H as Handler, a as HandlerContext, b as HandlerOptions, c as createHandler } from '../handler-oYl9j0Qa.js';
2
+ import { P as ProxyHook, b as ServerMiddleware } from '../types-Czld0vOH.js';
3
+ export { c as PROXY_PREFIX, R as RenderContext, a as RenderResult, d as ServerConfig, e as ServerMiddlewareContext, f as ServerModule, S as StreamRenderResult } from '../types-Czld0vOH.js';
4
+ import { o as CookieJar, l as Session, m as SessionData } from '../session-CLvYihOU.js';
5
+ export { C as CacheRule, q as CookieCodec, r as CookieDefinition, p as CookieOptions, b as CorsOptions, j as RedirectRule, n as ResolvedHead, y as ResolvedSecurity, k as RouteRule, S as SessionConfig, s as booleanCodec, t as defineCookie, u as enumCodec, v as jsonCodec, w as numberCodec, x as stringCodec } from '../session-CLvYihOU.js';
6
6
  export { b as FORM_ERROR_KEY, F as FormErrors, a as FormSchema, I as InferSchema, V as ValidationIssue, c as ValidationResult, e as errorsFromFailure, i as issuesToErrors, v as validate } from '../validation-Dwpex2JZ.js';
7
- export { h as ResolvedHead, i as ResolvedSecurity } from '../route-rules-COilNsVT.js';
7
+ export { P as PayloadData } from '../payload-DfhHnXAn.js';
8
8
  import 'doofpi';
9
9
 
10
10
  /** Resolves a proxied path to a URL on the remote API, or `null` when it is not allowed */
@@ -13,6 +13,8 @@ declare function proxyRequest(request: Request, options: {
13
13
  base: string;
14
14
  root: string;
15
15
  hook?: ProxyHook;
16
+ /** Name of a cookie (the session's) that is not forwarded */
17
+ omitCookie?: string;
16
18
  }): Promise<Response>;
17
19
 
18
20
  /**
@@ -22,7 +24,33 @@ declare function proxyRequest(request: Request, options: {
22
24
  */
23
25
  declare function getRequestCookies(request: Request): CookieJar;
24
26
 
27
+ /**
28
+ * The session of a request the noofpi server is handling (needs the `session` option). Pass the `Request` you were
29
+ * given (a doofpi endpoint's `req`, a server middleware's `request`, a `server/proxy.ts` hook's `request`); a copy of
30
+ * it is not known to the server. Changes are saved with the response.
31
+ */
32
+ declare function getSession<T extends SessionData = SessionData>(request: Request): Session<T>;
33
+ interface SessionGuardOptions {
34
+ /** Path patterns (`/admin/**`, `/account`, like `routeRules`) the guard protects. Default: every path */
35
+ match?: string | string[];
36
+ /** Patterns that stay open although they match, e.g. `/login` and the API that logs in */
37
+ exclude?: string | string[];
38
+ /** Whether the session may pass. Default: it has data */
39
+ allow?: (session: Session) => boolean | Promise<boolean>;
40
+ /** Where a browser asking for a page is sent instead of getting a 401, with the page it wanted in `?redirect=` */
41
+ redirect?: string;
42
+ /** Name of that query parameter. Default: `redirect` */
43
+ redirectParam?: string;
44
+ }
45
+ /**
46
+ * A `server/middleware/*.ts` that only lets requests with an allowed session through. Others get a `401` JSON answer,
47
+ * or, for pages, a redirect to `redirect`. Because it runs around every request, it also protects the doofpi API and the
48
+ * pfetch proxy under the patterns it matches.
49
+ */
50
+ declare function sessionGuard(options?: SessionGuardOptions): ServerMiddleware;
51
+
25
52
  /** Typing helper for `server/middleware/*.ts` */
26
53
  declare function defineServerMiddleware(middleware: ServerMiddleware): ServerMiddleware;
27
54
 
28
- export { CookieJar, ProxyHook, ServerMiddleware, defineServerMiddleware, getRequestCookies, proxyRequest, resolveProxyTarget };
55
+ export { CookieJar, ProxyHook, ServerMiddleware, Session, SessionData, defineServerMiddleware, getRequestCookies, getSession, proxyRequest, resolveProxyTarget, sessionGuard };
56
+ export type { SessionGuardOptions };
@@ -1,12 +1,13 @@
1
1
  import {
2
2
  createHandler,
3
3
  getRequestCookies,
4
+ getSession,
4
5
  proxyRequest,
5
- resolveProxyTarget
6
- } from "../chunk-X3DYEZLK.js";
7
- import {
8
- PROXY_PREFIX
9
- } from "../chunk-MTXQR32N.js";
6
+ resolveProxyTarget,
7
+ sessionGuard
8
+ } from "../chunk-YN64WQ2B.js";
9
+ import "../chunk-LJEKK4AK.js";
10
+ import "../chunk-O5JRC252.js";
10
11
  import {
11
12
  FORM_ERROR_KEY,
12
13
  errorsFromFailure,
@@ -21,8 +22,10 @@ import {
21
22
  numberCodec,
22
23
  stringCodec
23
24
  } from "../chunk-EZPJF4D4.js";
24
- import "../chunk-G35DW4NA.js";
25
- import "../chunk-MN5PVHC5.js";
25
+ import {
26
+ PROXY_PREFIX
27
+ } from "../chunk-PC3ZJN4D.js";
28
+ import "../chunk-W7ASRDAJ.js";
26
29
 
27
30
  // src/server/index.ts
28
31
  function defineServerMiddleware(middleware) {
@@ -38,11 +41,13 @@ export {
38
41
  enumCodec,
39
42
  errorsFromFailure,
40
43
  getRequestCookies,
44
+ getSession,
41
45
  issuesToErrors,
42
46
  jsonCodec,
43
47
  numberCodec,
44
48
  proxyRequest,
45
49
  resolveProxyTarget,
50
+ sessionGuard,
46
51
  stringCodec,
47
52
  validate
48
53
  };
@@ -1,9 +1,9 @@
1
1
  import { Server, ServerResponse, IncomingMessage } from 'node:http';
2
2
  import { Handler } from './index.js';
3
- import '../types-B6rQOOxS.js';
3
+ import '../types-Czld0vOH.js';
4
4
  import 'doofpi';
5
- import '../route-rules-COilNsVT.js';
6
- import '../payload-CL6tYBin.js';
5
+ import '../session-CLvYihOU.js';
6
+ import '../payload-DfhHnXAn.js';
7
7
 
8
8
  declare function toWebRequest(req: IncomingMessage): Request;
9
9
  declare function sendWebResponse(res: ServerResponse, response: Response): Promise<void>;