noofpi 2.0.0 → 3.0.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-W5VMPOTQ.js +212 -0
  4. package/dist/chunk-A7XQWIA6.js +562 -0
  5. package/dist/chunk-GOJZ36X5.js +217 -0
  6. package/dist/{chunk-YJVMBHNL.js → chunk-JUVQEKLE.js} +43 -12
  7. package/dist/chunk-LJEKK4AK.js +51 -0
  8. package/dist/{chunk-G35DW4NA.js → chunk-PC3ZJN4D.js} +11 -1
  9. package/dist/{chunk-LL3NO5EI.js → chunk-ROMSHDCI.js} +167 -88
  10. package/dist/{chunk-IE3WF5XF.js → chunk-SUECMRBX.js} +87 -4
  11. package/dist/{chunk-MN5PVHC5.js → chunk-W7ASRDAJ.js} +229 -7
  12. package/dist/cli.js +21 -9
  13. package/dist/{dev-HTWUY27O.js → dev-2DM7VOYX.js} +7 -6
  14. package/dist/{devtools-PLUN2DYV.js → devtools-C3PFU57C.js} +1 -1
  15. package/dist/handler-BpyI3a5D.d.ts +26 -0
  16. package/dist/index.d.ts +26 -11
  17. package/dist/index.js +3 -2
  18. package/dist/payload-Cgul9YUP.d.ts +66 -0
  19. package/dist/{prepare-KKQ2AEBW.js → prepare-APN2E6PX.js} +6 -5
  20. package/dist/runtime/entry-client.js +10 -7
  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-CAP_PIlN.d.ts +272 -0
  30. package/dist/{start-AJKNZRJQ.js → start-PXOLWPL4.js} +7 -6
  31. package/dist/{types-B6rQOOxS.d.ts → types-B7xDyUbg.d.ts} +30 -5
  32. package/package.json +8 -3
  33. package/dist/build-PFCGDPPJ.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,217 @@
1
+ // src/optional.ts
2
+ async function importOptional(load, packages, feature) {
3
+ try {
4
+ return await load();
5
+ } catch (error) {
6
+ const { code, message } = error ?? {};
7
+ const missing = code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" || message?.startsWith("Could not resolve ");
8
+ if (missing && packages.some((name) => message?.includes(name)))
9
+ throw new Error(
10
+ `[noofpi] ${feature} needs ${packages.join(" and ")}: install ${packages.length > 1 ? "them" : "it"} with your package manager (for example \`bun add ${packages.join(" ")}\`)`,
11
+ { cause: error }
12
+ );
13
+ throw error;
14
+ }
15
+ }
16
+
17
+ // src/session.ts
18
+ var SESSION_SECRET_ENV = "NOOFPI_SESSION_SECRET";
19
+ var SESSION_PREVIOUS_SECRETS_ENV = "NOOFPI_SESSION_SECRET_PREVIOUS";
20
+ var DEFAULT_MAX_AGE = 7 * 24 * 60 * 60;
21
+ var MIN_SECRET_LENGTH = 32;
22
+ var COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
23
+ function resolveSession(input) {
24
+ if (input === void 0 || input === false) return void 0;
25
+ const config = input === true ? {} : input;
26
+ if (typeof config !== "object" || config === null)
27
+ throw new Error("[noofpi] session must be a boolean or an object");
28
+ const name = config.name ?? "noofpi_session";
29
+ if (!COOKIE_NAME.test(name))
30
+ throw new Error(
31
+ `[noofpi] session.name is not a valid cookie name ("${name}")`
32
+ );
33
+ const maxAge = config.maxAge ?? DEFAULT_MAX_AGE;
34
+ if (!Number.isInteger(maxAge) || maxAge <= 0)
35
+ throw new Error(
36
+ `[noofpi] session.maxAge must be a positive number of seconds (got ${String(maxAge)})`
37
+ );
38
+ const mode = config.mode ?? "encrypted";
39
+ if (mode !== "encrypted" && mode !== "signed")
40
+ throw new Error(
41
+ `[noofpi] session.mode must be "encrypted" or "signed" (got "${String(mode)}")`
42
+ );
43
+ const expose = config.expose ?? [];
44
+ if (!Array.isArray(expose) || expose.some((key) => typeof key !== "string"))
45
+ throw new Error("[noofpi] session.expose must be a list of data keys");
46
+ const cookie = config.cookie ?? {};
47
+ if (cookie.sameSite !== void 0 && !["lax", "strict", "none"].includes(cookie.sameSite))
48
+ throw new Error(
49
+ `[noofpi] session.cookie.sameSite must be lax, strict or none (got "${String(cookie.sameSite)}")`
50
+ );
51
+ return {
52
+ name,
53
+ maxAge,
54
+ mode,
55
+ expose,
56
+ cookie: {
57
+ sameSite: cookie.sameSite,
58
+ secure: cookie.secure,
59
+ domain: cookie.domain,
60
+ path: cookie.path
61
+ }
62
+ };
63
+ }
64
+ var securegeer;
65
+ function loadSecuregeer() {
66
+ securegeer ??= (async () => {
67
+ const [encryption, hmac] = await importOptional(
68
+ () => Promise.all([
69
+ import("securegeer/encryption"),
70
+ import("securegeer/hmac")
71
+ ]),
72
+ ["securegeer"],
73
+ "session"
74
+ );
75
+ return { encryption, hmac };
76
+ })();
77
+ securegeer.catch(() => securegeer = void 0);
78
+ return securegeer;
79
+ }
80
+ var readEnv = (env, name) => {
81
+ const fromBinding = env?.[name];
82
+ if (typeof fromBinding === "string" && fromBinding) return fromBinding;
83
+ const fromProcess = typeof process !== "undefined" ? process.env?.[name] : void 0;
84
+ return fromProcess || void 0;
85
+ };
86
+ var devSecret;
87
+ async function resolveSessionSecrets(env) {
88
+ const current = readEnv(env, SESSION_SECRET_ENV);
89
+ const previous = (readEnv(env, SESSION_PREVIOUS_SECRETS_ENV) ?? "").split(/[\s,]+/).filter(Boolean);
90
+ const secrets = [...current ? [current] : [], ...previous];
91
+ for (const secret of secrets)
92
+ if (secret.length < MIN_SECRET_LENGTH)
93
+ throw new Error(
94
+ `[noofpi] Session secrets must be at least ${MIN_SECRET_LENGTH} characters (generate one with \`openssl rand -base64 32\`)`
95
+ );
96
+ if (current) return secrets;
97
+ if (typeof process !== "undefined" && process.env?.NODE_ENV === "production")
98
+ throw new Error(
99
+ `[noofpi] Sessions need the ${SESSION_SECRET_ENV} environment variable (at least ${MIN_SECRET_LENGTH} characters, e.g. from \`openssl rand -base64 32\`)`
100
+ );
101
+ if (!devSecret) {
102
+ const { encryption } = await loadSecuregeer();
103
+ if (!devSecret) {
104
+ devSecret = encryption.generateSecret();
105
+ console.warn(
106
+ `[noofpi] ${SESSION_SECRET_ENV} is not set: sessions use a random secret that changes on every restart. Set it in .env.`
107
+ );
108
+ }
109
+ }
110
+ return [devSecret, ...secrets];
111
+ }
112
+ var encoder = new TextEncoder();
113
+ var decoder = new TextDecoder();
114
+ var toBase64Url = (text) => {
115
+ let binary = "";
116
+ for (const byte of encoder.encode(text)) binary += String.fromCharCode(byte);
117
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
118
+ };
119
+ var fromBase64Url = (value) => {
120
+ const binary = atob(value.replace(/-/g, "+").replace(/_/g, "/"));
121
+ return decoder.decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
122
+ };
123
+ var isEnvelope = (value) => typeof value === "object" && value !== null && typeof value.e === "number" && typeof value.d === "object" && value.d !== null && !Array.isArray(value.d);
124
+ async function seal(envelope, mode, secret) {
125
+ const { encryption, hmac } = await loadSecuregeer();
126
+ if (mode === "encrypted") return encryption.encrypt(envelope, secret);
127
+ const payload = toBase64Url(JSON.stringify(envelope));
128
+ return `${payload}.${await hmac.hmacSign(payload, secret)}`;
129
+ }
130
+ async function unseal(value, mode, secrets) {
131
+ const { encryption, hmac } = await loadSecuregeer();
132
+ for (const secret of secrets) {
133
+ try {
134
+ let parsed;
135
+ if (mode === "encrypted")
136
+ parsed = await encryption.decryptJSON(value, secret);
137
+ else {
138
+ const dot = value.lastIndexOf(".");
139
+ const payload = value.slice(0, dot);
140
+ if (dot < 1 || !await hmac.hmacVerify(payload, value.slice(dot + 1), secret))
141
+ continue;
142
+ parsed = JSON.parse(fromBase64Url(payload));
143
+ }
144
+ if (isEnvelope(parsed)) return parsed;
145
+ } catch {
146
+ }
147
+ }
148
+ return void 0;
149
+ }
150
+ async function openSession(options) {
151
+ const { config, cookies } = options;
152
+ const secrets = await options.secrets;
153
+ await loadSecuregeer();
154
+ const now = options.now ?? Date.now();
155
+ const raw = cookies.get(config.name);
156
+ let data = {};
157
+ if (raw) {
158
+ const envelope = await unseal(raw, config.mode, secrets);
159
+ if (envelope && envelope.e > now) data = envelope.d;
160
+ }
161
+ const initial = JSON.stringify(data);
162
+ let cleared = false;
163
+ const session = {
164
+ data,
165
+ update(patch) {
166
+ Object.assign(session.data, patch);
167
+ },
168
+ clear() {
169
+ cleared = true;
170
+ session.data = {};
171
+ },
172
+ get isEmpty() {
173
+ return Object.keys(session.data).length === 0;
174
+ }
175
+ };
176
+ const cookieOptions = {
177
+ ...config.cookie,
178
+ httpOnly: true
179
+ };
180
+ return {
181
+ session,
182
+ async commit() {
183
+ const changed = JSON.stringify(session.data) !== initial;
184
+ if (!changed && !cleared) return;
185
+ if (session.isEmpty) {
186
+ if (raw !== void 0)
187
+ cookies.remove(config.name, {
188
+ path: config.cookie.path,
189
+ domain: config.cookie.domain
190
+ });
191
+ return;
192
+ }
193
+ const value = await seal(
194
+ { d: session.data, e: now + config.maxAge * 1e3 },
195
+ config.mode,
196
+ secrets[0]
197
+ );
198
+ cookies.set(config.name, value, {
199
+ ...cookieOptions,
200
+ maxAge: config.maxAge
201
+ });
202
+ },
203
+ exposed() {
204
+ const visible = {};
205
+ for (const key of config.expose)
206
+ if (key in session.data) visible[key] = session.data[key];
207
+ return visible;
208
+ }
209
+ };
210
+ }
211
+
212
+ export {
213
+ importOptional,
214
+ resolveSession,
215
+ resolveSessionSecrets,
216
+ openSession
217
+ };
@@ -22,14 +22,15 @@ import {
22
22
  import {
23
23
  HEAD_ATTRS_ATTR,
24
24
  HEAD_TAG_ATTR,
25
+ SESSION_PATH,
25
26
  resolveHead
26
- } from "./chunk-G35DW4NA.js";
27
+ } from "./chunk-PC3ZJN4D.js";
27
28
  import {
28
29
  FETCH_MODES,
29
30
  isServerRendered,
30
31
  resolveFetchMode,
31
32
  usesFetchMode
32
- } from "./chunk-MN5PVHC5.js";
33
+ } from "./chunk-W7ASRDAJ.js";
33
34
 
34
35
  // src/runtime/async-data.ts
35
36
  import {
@@ -281,15 +282,15 @@ function createDoofpiClients(config, rules, ctx) {
281
282
  function createDoofpiClient(config, ctx) {
282
283
  const { server, origin } = ctx;
283
284
  const cookie = server && ctx.cookie ? { headers: { cookie: ctx.cookie } } : void 0;
284
- const track = (fetch) => ctx.log ? recordFetch(
285
- fetch ?? ((input, init) => globalThis.fetch(input, init)),
285
+ const track = (fetch2) => ctx.log ? recordFetch(
286
+ fetch2 ?? ((input, init) => globalThis.fetch(input, init)),
286
287
  ctx.log,
287
288
  {
288
289
  side: server ? "server" : "browser",
289
290
  mode: config.fetch,
290
- transport: fetch && fetch === ctx.fetch ? "in-process" : "http"
291
+ transport: fetch2 && fetch2 === ctx.fetch ? "in-process" : "http"
291
292
  }
292
- ) : fetch;
293
+ ) : fetch2;
293
294
  switch (config.fetch) {
294
295
  case "dfetch":
295
296
  return createClient({
@@ -477,12 +478,7 @@ function collectState(payload) {
477
478
  if (value.value !== void 0) state[key] = value.value;
478
479
  return state;
479
480
  }
480
- function useState(key, init) {
481
- const payload = currentPayload();
482
- if (!payload)
483
- throw new Error(
484
- "[noofpi] useState() must be called while rendering a request or in the browser"
485
- );
481
+ function stateOf(payload, key, init) {
486
482
  const registry = registryOf(payload);
487
483
  let state = registry.get(key);
488
484
  if (!state) {
@@ -493,6 +489,35 @@ function useState(key, init) {
493
489
  if (state.value === void 0 && init) state.value = init();
494
490
  return state;
495
491
  }
492
+ function seedState(payload, key, value) {
493
+ stateOf(payload, key).value = value;
494
+ }
495
+ function useState(key, init) {
496
+ const payload = currentPayload();
497
+ if (!payload)
498
+ throw new Error(
499
+ "[noofpi] useState() must be called while rendering a request or in the browser"
500
+ );
501
+ return stateOf(payload, key, init);
502
+ }
503
+
504
+ // src/runtime/session.ts
505
+ var SESSION_STATE_KEY = "noofpi:session";
506
+ async function refreshSession(state) {
507
+ if (typeof window === "undefined") return;
508
+ const response = await fetch(SESSION_PATH, {
509
+ headers: { accept: "application/json" },
510
+ credentials: "same-origin"
511
+ });
512
+ if (!response.ok)
513
+ throw new Error(`[noofpi] Could not load the session (${response.status})`);
514
+ const body = await response.json();
515
+ state.value = body.data ?? {};
516
+ }
517
+ function useSession() {
518
+ const data = useState(SESSION_STATE_KEY, () => ({}));
519
+ return { data, refresh: () => refreshSession(data) };
520
+ }
496
521
 
497
522
  // src/runtime/cookie.ts
498
523
  import { customRef, inject as inject7 } from "vue";
@@ -738,6 +763,8 @@ function createNoofpiApp(ctx) {
738
763
  ...hydrate ? readPayload() : { data: {}, errors: {} }
739
764
  };
740
765
  app.provide(PAYLOAD_KEY, payload);
766
+ if (ctx.server && ctx.session && Object.keys(ctx.session).length)
767
+ seedState(payload, SESSION_STATE_KEY, ctx.session);
741
768
  const loaders = installLoaders(router, {
742
769
  payload,
743
770
  run: (to, call) => {
@@ -752,6 +779,9 @@ function createNoofpiApp(ctx) {
752
779
  });
753
780
  app.provide(LOADER_KEY, loaders.state);
754
781
  if (!ctx.server) setBrowserState(payload);
782
+ if (!ctx.server && !hydrate && publicConfig.session)
783
+ refreshSession(stateOf(payload, SESSION_STATE_KEY)).catch(() => {
784
+ });
755
785
  if (log && payload.requests) addEntries(log, payload.requests);
756
786
  const error = ref5(payload.error ?? null);
757
787
  app.provide(ERROR_KEY, error);
@@ -799,6 +829,7 @@ export {
799
829
  setServerStateSource,
800
830
  collectState,
801
831
  useState,
832
+ useSession,
802
833
  useCookies,
803
834
  useCookie,
804
835
  defineMessages,
@@ -0,0 +1,51 @@
1
+ // src/server/cache.ts
2
+ var MAX_ENTRIES = 500;
3
+ var PageCache = class {
4
+ entries = /* @__PURE__ */ new Map();
5
+ inflight = /* @__PURE__ */ new Map();
6
+ get(key) {
7
+ return this.entries.get(key);
8
+ }
9
+ set(key, page) {
10
+ this.entries.delete(key);
11
+ this.entries.set(key, page);
12
+ if (this.entries.size > MAX_ENTRIES)
13
+ this.entries.delete(this.entries.keys().next().value);
14
+ }
15
+ clear() {
16
+ this.entries.clear();
17
+ }
18
+ /** Runs `render` for `key` unless one is running already: concurrent requests share its result instead of each rendering */
19
+ share(key, render) {
20
+ let running = this.inflight.get(key);
21
+ if (!running) {
22
+ running = render().finally(() => this.inflight.delete(key));
23
+ this.inflight.set(key, running);
24
+ }
25
+ return running;
26
+ }
27
+ isRendering(key) {
28
+ return this.inflight.has(key);
29
+ }
30
+ };
31
+ function cacheState(page, rule, now) {
32
+ const age = (now - page.storedAt) / 1e3;
33
+ if (age < rule.maxAge) return "fresh";
34
+ return age < rule.maxAge + (rule.swr ?? 0) ? "stale" : "expired";
35
+ }
36
+ function cacheControl(rule) {
37
+ const parts = ["public", `max-age=${rule.maxAge}`];
38
+ if (rule.swr) parts.push(`stale-while-revalidate=${rule.swr}`);
39
+ return parts.join(", ");
40
+ }
41
+ function cacheKey(url, request, vary = []) {
42
+ const headers = vary.map((name) => name.toLowerCase()).sort().map((name) => `${name}=${request.headers.get(name) ?? ""}`);
43
+ return [url.pathname + url.search, ...headers].join("\n");
44
+ }
45
+
46
+ export {
47
+ PageCache,
48
+ cacheState,
49
+ cacheControl,
50
+ cacheKey
51
+ };
@@ -1,3 +1,9 @@
1
+ // src/server/types.ts
2
+ var PROXY_PREFIX = "/_noofpi/proxy";
3
+ var SESSION_PATH = "/_noofpi/session";
4
+ var SSR_OUTLET = "<!--ssr-outlet-->";
5
+ var isStreamResult = (result) => "body" in result;
6
+
1
7
  // src/head.ts
2
8
  var DEFAULT_TITLE = "noofpi";
3
9
  var HEAD_TAG_ATTR = "data-noofpi-head";
@@ -125,5 +131,9 @@ export {
125
131
  HEAD_TAG_ATTR,
126
132
  HEAD_ATTRS_ATTR,
127
133
  resolveHead,
128
- applyHead
134
+ applyHead,
135
+ PROXY_PREFIX,
136
+ SESSION_PATH,
137
+ SSR_OUTLET,
138
+ isStreamResult
129
139
  };