@ogygia/postrender 0.12.0 → 0.14.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.
@@ -1,4 +1,5 @@
1
- import { normalize_prefix, subtree_prefix } from "./key.js";
1
+ import { in_subtree, normalize_prefix } from "./key.js";
2
+ import { clock } from "@ogygia/machine";
2
3
  import { SizedLru } from "@ogygia/core/plugin/utils";
3
4
  // src/memory-store.ts
4
5
  /** Resident budget for stored pages (a stored page can be multi-MB; a count alone bounds nothing). */
@@ -6,41 +7,42 @@ const DEFAULT_MAX_BYTES = 67108864;
6
7
  const DEFAULT_MAX_ENTRIES = 1e3;
7
8
  /** What an entry costs to keep: a page is its HTML; a redirect is a few dozen bytes. */
8
9
  const entry_bytes = (entry) => entry.kind === "page" ? entry.html.length : 64;
9
- function memory_store(max_entries = DEFAULT_MAX_ENTRIES, max_bytes = DEFAULT_MAX_BYTES) {
10
- const entries = new SizedLru(max_bytes, max_entries);
11
- const tag_index = /* @__PURE__ */ new Map();
12
- return {
13
- async get(key) {
14
- return entries.get(key, Date.now());
15
- },
16
- async put(key, entry, options) {
17
- entries.set(key, entry, entry_bytes(entry), Date.now() + options.ttl * 1e3);
18
- for (const tag of options.tags ?? []) {
19
- let set = tag_index.get(tag);
20
- if (!set) tag_index.set(tag, set = /* @__PURE__ */ new Set());
21
- set.add(key);
22
- }
23
- },
24
- async evict(key) {
25
- entries.delete(key);
26
- },
27
- async evictWhere({ prefix }) {
28
- const p = normalize_prefix(prefix);
29
- const subtree = subtree_prefix(p);
30
- for (const key of entries.keys()) if (key === p || key.startsWith(subtree)) entries.delete(key);
31
- },
32
- async evictByTag(tag) {
33
- const set = tag_index.get(tag);
34
- if (!set) return [];
35
- tag_index.delete(tag);
36
- const evicted = [];
37
- for (const key of set) if (entries.delete(key)) evicted.push(key);
38
- return evicted;
39
- },
40
- async size() {
41
- entries.sweep(Date.now());
42
- return entries.size;
10
+ var MemoryStore = class {
11
+ #entries;
12
+ #tag_index = /* @__PURE__ */ new Map();
13
+ constructor(max_entries = DEFAULT_MAX_ENTRIES, max_bytes = DEFAULT_MAX_BYTES) {
14
+ this.#entries = new SizedLru(max_bytes, max_entries);
15
+ }
16
+ async get(key) {
17
+ return this.#entries.get(key, clock.mono());
18
+ }
19
+ async put(key, entry, options) {
20
+ this.#entries.set(key, entry, entry_bytes(entry), clock.mono() + options.ttl * 1e3);
21
+ for (const tag of options.tags ?? []) {
22
+ let set = this.#tag_index.get(tag);
23
+ if (!set) this.#tag_index.set(tag, set = /* @__PURE__ */ new Set());
24
+ set.add(key);
43
25
  }
44
- };
45
- }
46
- export { memory_store };
26
+ }
27
+ async evict(key) {
28
+ this.#entries.delete(key);
29
+ }
30
+ async evictWhere({ prefix }) {
31
+ const p = normalize_prefix(prefix);
32
+ const entries = this.#entries;
33
+ for (const key of entries.keys()) if (in_subtree(key, p)) entries.delete(key);
34
+ }
35
+ async evictByTag(tag) {
36
+ const set = this.#tag_index.get(tag);
37
+ if (!set) return [];
38
+ this.#tag_index.delete(tag);
39
+ const evicted = [];
40
+ for (const key of set) if (this.#entries.delete(key)) evicted.push(key);
41
+ return evicted;
42
+ }
43
+ async size() {
44
+ this.#entries.sweep(clock.mono());
45
+ return this.#entries.size;
46
+ }
47
+ };
48
+ export { MemoryStore };
@@ -0,0 +1,78 @@
1
+ import { MessagesOf } from "@ogygia/core/internal/messages";
2
+ /** The errors: `throw new OgygiaError(code, args)`. */
3
+ export declare const POSTRENDER_ERRORS: {
4
+ postrender_invalidate_not_source: {
5
+ text: () => string;
6
+ details: () => string;
7
+ };
8
+ postrender_adapter_request_failed: {
9
+ text: (a: {
10
+ what: string;
11
+ status: number;
12
+ body: string;
13
+ }) => string;
14
+ details: () => string;
15
+ };
16
+ postrender_store_client_missing: {
17
+ text: (a: {
18
+ client: string;
19
+ commands: string;
20
+ }) => string;
21
+ details: () => string;
22
+ };
23
+ };
24
+ /** The warnings: `warn(code, args, ...rest)`. */
25
+ export declare const POSTRENDER_WARNINGS: {
26
+ postrender_edges_without_shared_store: {
27
+ text: () => string;
28
+ details: () => string;
29
+ };
30
+ postrender_store_no_evict_by_tag: {
31
+ text: () => string;
32
+ details: () => string;
33
+ };
34
+ postrender_tag_evict_failed: {
35
+ text: (a: {
36
+ tag: string;
37
+ }) => string;
38
+ details: () => string;
39
+ };
40
+ postrender_store_failed: {
41
+ text: (a: {
42
+ op: string;
43
+ key: string;
44
+ }) => string;
45
+ details: () => string;
46
+ };
47
+ postrender_capture_failed: {
48
+ text: (a: {
49
+ path: string;
50
+ }) => string;
51
+ details: () => string;
52
+ };
53
+ postrender_fanout_failed: {
54
+ text: (a: {
55
+ label: string;
56
+ what: string;
57
+ }) => string;
58
+ details: () => string;
59
+ };
60
+ postrender_stays_per_request: {
61
+ text: (a: {
62
+ path: string;
63
+ refusal: string;
64
+ }) => string;
65
+ details: () => string;
66
+ };
67
+ postrender_handle_unlisted: {
68
+ text: () => string;
69
+ details: () => string;
70
+ };
71
+ };
72
+ type Own = MessagesOf<typeof POSTRENDER_ERRORS, typeof POSTRENDER_WARNINGS>;
73
+ /** `throw new OgygiaError(code, args)`; `warn(code, args, ...rest)` logs; `line(code, args)` is the
74
+ * line as a string. Wording and link in dev and while prerendering, the link alone otherwise. */
75
+ export declare const OgygiaError: Own["OgygiaError"];
76
+ export declare const warn: Own["warn"];
77
+ export declare const line: Own["line"];
78
+ export {};
@@ -0,0 +1,150 @@
1
+ import { define_messages, dev_or_prerender, prose } from "@ogygia/core/internal/messages";
2
+ // src/messages.ts
3
+ /** The errors: `throw new OgygiaError(code, args)`. */
4
+ const POSTRENDER_ERRORS = {
5
+ postrender_invalidate_not_source: {
6
+ text: () => prose`
7
+ postrender.invalidate(fn, args): the function is not a declared source — wrap its
8
+ definition: \`export const fn = import.meta.og.source(async (…) => …)\`.
9
+ `,
10
+ details: () => prose`
11
+ \`invalidate(fn, args)\` evicts the stored pages that read a data source with those
12
+ arguments. It only knows the functions declared as sources: this one is not.
13
+
14
+ Wrap the function's definition in \`import.meta.og.source(…)\`. Or evict by URL with
15
+ \`invalidate(url)\`.
16
+ `
17
+ },
18
+ postrender_adapter_request_failed: {
19
+ text: (a) => `${a.what} failed: ${a.status} ${a.body}`,
20
+ details: () => prose`
21
+ A store or edge adapter called its service's HTTP API (to purge a URL, or to run a store
22
+ command) and the service answered with an error status. \`status\` and \`body\` are its
23
+ answer.
24
+
25
+ A 401 or 403 is usually the adapter's credentials (a token, a key) or their permissions.
26
+ `
27
+ },
28
+ postrender_store_client_missing: {
29
+ text: (a) => `${a.client} client has no ${a.commands} — og.source tags need it`,
30
+ details: () => prose`
31
+ The client handed to the store adapter has no set commands, which the adapter needs to
32
+ file each stored page under the sources it read (\`import.meta.og.source\`). Pass a
33
+ client that has them.
34
+ `
35
+ }
36
+ };
37
+ /** The warnings: `warn(code, args, ...rest)`. */
38
+ const POSTRENDER_WARNINGS = {
39
+ postrender_edges_without_shared_store: {
40
+ text: () => prose`
41
+ postrender: edge adapters are configured but the store is the per-instance memory default
42
+ — invalidations cannot reach other replicas. Use a shared store (ValkeyStore / UpstashStore /
43
+ CloudflareKvStore) in multi-instance deploys.
44
+ `,
45
+ details: () => prose`
46
+ \`postrender.handle()\` was given edge adapters but no \`store\`, so each server instance
47
+ keeps its own memory store. An invalidation evicts the page on the instance that runs it
48
+ and purges the edge, but the other instances keep their stale copy and serve it to the
49
+ edge again.
50
+
51
+ Give \`postrender.handle()\` a shared \`store\` when the app runs on more than one
52
+ instance.
53
+ `
54
+ },
55
+ postrender_store_no_evict_by_tag: {
56
+ text: () => prose`
57
+ postrender: the configured store has no evictByTag — tag invalidation needs it
58
+ (MemoryStore/ValkeyStore/UpstashStore/CloudflareKvStore all provide it).
59
+ `,
60
+ details: () => prose`
61
+ An invalidation by source or tag needs the store to evict every page filed under a tag,
62
+ through \`evictByTag\`. The configured store has none, so nothing was evicted. Add
63
+ \`evictByTag\` to the custom store, or use one of the built-in stores.
64
+ `
65
+ },
66
+ postrender_tag_evict_failed: {
67
+ text: (a) => prose`
68
+ postrender.invalidate(tags): the store failed to evict tag ${a.tag} (evictByTag); its
69
+ pages stay stored until they expire —
70
+ `,
71
+ details: () => prose`
72
+ The store's \`evictByTag\` threw for one tag (the error follows the message). The other
73
+ tags were still evicted and purged at the edges; this tag's pages stay stored until
74
+ they expire.
75
+ `
76
+ },
77
+ postrender_store_failed: {
78
+ text: (a) => prose`
79
+ postrender: the store failed (${a.op} ${a.key}); pages render fresh and are not kept
80
+ while it does —
81
+ `,
82
+ details: () => prose`
83
+ A call to the store given to \`postrender.handle({ store })\` threw (the error follows the
84
+ message). A store that is down never fails a render: a read is a miss, a write or an
85
+ evict is skipped. So every page renders fresh, nothing is kept, and an evict may leave a
86
+ page stored until it expires. Said once, then again only after a store call worked: a
87
+ store that stays down does not fill the log.
88
+
89
+ Check the store's connection and credentials.
90
+ `
91
+ },
92
+ postrender_capture_failed: {
93
+ text: (a) => prose`
94
+ postrender: storing ${a.path} failed; the page went out as rendered, not stored —
95
+ `,
96
+ details: () => prose`
97
+ Postrender reads each storable page to store it (its stitched holes rewritten, its
98
+ headers made). That step threw for this page (the error follows the message). The
99
+ visitor got the page as the app rendered it, marked \`no-store\`, and nothing was
100
+ stored: the next request renders it again. Said once per page.
101
+
102
+ The error names what failed: often a stitched hole whose \`endpoint\` is not a URL, or
103
+ an edge adapter that threw.
104
+ `
105
+ },
106
+ postrender_fanout_failed: {
107
+ text: (a) => `postrender.${a.label}: ${a.what} —`,
108
+ details: () => prose`
109
+ An invalidation reaches the store and every edge adapter at once. One of those calls
110
+ failed (\`what\` names it; the error follows the message); the others still ran. The
111
+ page may stay stored, or cached at that edge, until it expires.
112
+ `
113
+ },
114
+ postrender_stays_per_request: {
115
+ text: (a) => prose`
116
+ postrender: ${a.path} stays per-request — the render read ${a.refusal}. Personalize inside
117
+ a render:'deferred' hole to make the shell storable.
118
+ `,
119
+ details: () => prose`
120
+ Dev only. The page's render read something personal (a cookie, a header, the visitor) or
121
+ answered in a way that cannot be shared (a status other than 200, a \`set-cookie\`
122
+ header, streamed load promises), so it is rendered per request and never stored.
123
+ \`refusal\` names what.
124
+
125
+ Move the personal part into a \`render: 'deferred'\` hole: the rest of the page is then
126
+ stored, and the hole fills in per visitor.
127
+ `
128
+ },
129
+ postrender_handle_unlisted: {
130
+ text: () => prose`
131
+ postrender.handle() runs, but \`postrender()\` is not listed in vite.config, so no page is
132
+ stored. Add it: \`plugins: [ogygia(), postrender(), sveltekit()]\`
133
+ (from '@ogygia/postrender/vite').
134
+ `,
135
+ details: () => prose`
136
+ \`postrender.handle()\` is in the hooks, but the plugin's server half never started, so
137
+ nothing is ever stored.
138
+
139
+ List \`postrender()\` (from \`@ogygia/postrender/vite\`) in the \`plugins\` of vite.config,
140
+ beside \`ogygia()\`.
141
+ `
142
+ }
143
+ };
144
+ const own = /* @__PURE__ */ define_messages(import.meta.env?.DEV || import.meta.env?.SSR ? POSTRENDER_ERRORS : null, import.meta.env?.DEV || import.meta.env?.SSR ? POSTRENDER_WARNINGS : null, dev_or_prerender);
145
+ /** `throw new OgygiaError(code, args)`; `warn(code, args, ...rest)` logs; `line(code, args)` is the
146
+ * line as a string. Wording and link in dev and while prerendering, the link alone otherwise. */
147
+ const OgygiaError = own.OgygiaError;
148
+ const warn = own.warn;
149
+ const line = own.line;
150
+ export { OgygiaError, POSTRENDER_ERRORS, POSTRENDER_WARNINGS, line, warn };
package/dist/observe.d.ts CHANGED
@@ -1,17 +1,13 @@
1
- import { RequestEvent } from "@sveltejs/kit";
1
+ import { RequestContext } from "@ogygia/core/plugin";
2
2
  export interface Observation {
3
- /** First personalization read that returned a NON-default value, or null — the verdict input.
4
- * Named (`cookie:consent`, `header:accept-language`, `locals.user`) for the dev note. It IS the
5
- * request's `perVisitor` fact: a flag read or a streamed promise lands there too. */
3
+ /** The first per-visitor read, or null — the verdict input. Named (`cookie:consent`,
4
+ * `header:accept-language`, `locals.user`, `flag:hero`) for the dev note. */
6
5
  readonly disqualified_by: string | null;
7
6
  /** The render (or the app) wrote a cookie — always per-request. */
8
7
  wrote_cookie: boolean;
9
8
  }
10
9
  /**
11
- * Patch `event.cookies` / `event.locals` / `event.request.headers` in place, recording reads.
12
- * Returns the live observation the verdict reads after the render. Patching is per-request
13
- * (the event dies with the request) — nothing to restore.
10
+ * Note the event's personal reads from now on, and record its cookie writes (patched in place, per
11
+ * request: the event dies with it). Returns the live observation the verdict reads after the render.
14
12
  */
15
- export declare function observe_event(event: RequestEvent, facts?: {
16
- perVisitor: string | null;
17
- }): Observation;
13
+ export declare function observe_event(ctx: Pick<RequestContext<unknown, unknown>, "event" | "facts" | "app">): Observation;
package/dist/observe.js CHANGED
@@ -1,77 +1,28 @@
1
1
  // src/observe.ts
2
- /** Personalization-bearing request headers: reading one during an eligible render disqualifies
3
- * the page. Everything else (host, sec-fetch-*, accept-encoding, …) is delivery plumbing. */
4
- const DISQUALIFYING_HEADERS = /* @__PURE__ */ new Set([
5
- "cookie",
6
- "authorization",
7
- "accept-language",
8
- "user-agent",
9
- "referer",
10
- "x-user",
11
- "x-user-id",
12
- "x-session",
13
- "x-session-id"
14
- ]);
15
- /** Default-valued reads still store: undefined/null/''/false, empty plain object, empty array. */
16
- function is_default_value(value) {
17
- if (value === void 0 || value === null || value === "" || value === false) return true;
18
- if (Array.isArray(value)) return value.length === 0;
19
- if (typeof value === "object") {
20
- const proto = Object.getPrototypeOf(value);
21
- if (proto === Object.prototype || proto === null) return Object.keys(value).length === 0;
22
- }
23
- return false;
24
- }
25
2
  /**
26
- * Patch `event.cookies` / `event.locals` / `event.request.headers` in place, recording reads.
27
- * Returns the live observation the verdict reads after the render. Patching is per-request
28
- * (the event dies with the request) — nothing to restore.
3
+ * Note the event's personal reads from now on, and record its cookie writes (patched in place, per
4
+ * request: the event dies with it). Returns the live observation the verdict reads after the render.
29
5
  */
30
- function observe_event(event, facts = { perVisitor: null }) {
6
+ function observe_event(ctx) {
7
+ const { event, facts } = ctx;
8
+ ctx.app.observeReads(event);
31
9
  const obs = {
32
10
  get disqualified_by() {
33
- return facts.perVisitor;
11
+ return facts.reads.perVisitor;
34
12
  },
35
13
  wrote_cookie: false
36
14
  };
37
- const disqualify = (label) => {
38
- if (facts.perVisitor === null) facts.perVisitor = label;
39
- };
40
15
  const cookies = event.cookies;
41
- const orig_get = cookies.get.bind(cookies);
42
- const orig_get_all = cookies.getAll.bind(cookies);
43
- const orig_set = cookies.set.bind(cookies);
44
- const orig_delete = cookies.delete.bind(cookies);
45
- cookies.get = ((name, opts) => {
46
- const value = orig_get(name, opts);
47
- if (!is_default_value(value)) disqualify(`cookie:${name}`);
48
- return value;
49
- });
50
- cookies.getAll = ((opts) => {
51
- const all = orig_get_all(opts);
52
- if (all.length > 0) disqualify("cookies.getAll");
53
- return all;
54
- });
16
+ const set = cookies.set.bind(cookies);
17
+ const drop = cookies.delete.bind(cookies);
55
18
  cookies.set = ((...args) => {
56
19
  obs.wrote_cookie = true;
57
- return orig_set(...args);
20
+ return set(...args);
58
21
  });
59
22
  cookies.delete = ((...args) => {
60
23
  obs.wrote_cookie = true;
61
- return orig_delete(...args);
62
- });
63
- const headers = event.request.headers;
64
- const orig_header_get = headers.get.bind(headers);
65
- headers.get = ((name) => {
66
- const value = orig_header_get(name);
67
- if (value !== null && DISQUALIFYING_HEADERS.has(name.toLowerCase())) disqualify(`header:${name.toLowerCase()}`);
68
- return value;
24
+ return drop(...args);
69
25
  });
70
- event.locals = new Proxy(event.locals, { get(target, prop, receiver) {
71
- const value = Reflect.get(target, prop, receiver);
72
- if (typeof prop === "string" && !is_default_value(value) && typeof value !== "function") disqualify(`locals.${prop}`);
73
- return value;
74
- } });
75
26
  return obs;
76
27
  }
77
28
  export { observe_event };
@@ -1,4 +1,5 @@
1
1
  import { EdgeAdapter, PostrenderEntry, PostrenderHandleOptions, PostrenderPutOptions, PostrenderStore } from "./types.js";
2
+ import { Stale } from "@ogygia/machine";
2
3
  import { RequestEvent } from "@sveltejs/kit";
3
4
  /** One server's live settings: what its `postrender.handle({ store, edge })` was given. */
4
5
  export interface Runtime {
@@ -20,13 +21,59 @@ export declare function reset_for_tests(): void;
20
21
  /** Evict every stored page carrying ANY of `tags` (origin + every edge). The receiving half of a
21
22
  * thaw notice; also what `invalidate(fn, args)` does for one receipt tag. */
22
23
  export declare function invalidate_tags(tags: readonly string[], runtime?: Runtime): Promise<string[]>;
24
+ /** `invalidate_tags`, with what the store failed to evict: the shared hook (a peer's thaw) must not
25
+ * answer "done" for a tag that is still stored (#287). */
26
+ export declare function evict_tags(tags: readonly string[], runtime?: Runtime): Promise<{
27
+ keys: string[];
28
+ failed: unknown[];
29
+ }>;
30
+ /** `work` against the store: its failure is said, then thrown (for a caller that tries again). */
31
+ export declare function store_call<T>(op: string, key: string, work: () => Promise<T>): Promise<T>;
23
32
  export declare function store_get(runtime: Runtime, key: string): Promise<PostrenderEntry | null>;
24
33
  export declare function store_put(runtime: Runtime, key: string, entry: PostrenderEntry, options: PostrenderPutOptions): Promise<void>;
34
+ /**
35
+ * Store a render's page. An invalidation that starts while the write is out ends the render's
36
+ * flight (it may have read what the invalidation changes), and its evict may run before the write
37
+ * lands: the page is then taken back out, through the same tried-again evict a post waits for.
38
+ * True when it stays stored.
39
+ *
40
+ * From the moment its flight goes stale until that evict ends, the page is RETRACTING: what the
41
+ * store holds for it may be the page from before the invalidation, so no hit is served from it
42
+ * (#332).
43
+ */
44
+ export declare function store_render(runtime: Runtime, key: string, entry: PostrenderEntry, options: PostrenderPutOptions, flight: Flight): Promise<boolean>;
45
+ /** A stale render's page is being taken back out of the store: a hit for it is a miss. */
46
+ export declare function retracting(key: string): boolean;
25
47
  export type FlightOutcome = {
26
48
  stored: PostrenderEntry | null;
27
49
  };
28
- export declare function join_flight(key: string): Promise<FlightOutcome> | null;
29
- export declare function begin_flight(key: string): (outcome: FlightOutcome) => void;
50
+ /**
51
+ * One page's render, opened by the request that renders it: that request settles it exactly once,
52
+ * however it ends (the plugin's `done` settles one nothing else did), with what it stored, or null.
53
+ * An invalidation that would have evicted its page ends it while it renders (`stale`: what it read
54
+ * may be the page from before the publish): it is not stored, and the requests that joined it are
55
+ * let go at once to ask again (#194).
56
+ */
57
+ export declare class Flight {
58
+ #private;
59
+ readonly key: string;
60
+ readonly outcome: Promise<FlightOutcome>;
61
+ constructor(key: string);
62
+ /** An invalidation ended it while it rendered. */
63
+ get stale(): boolean;
64
+ /** Settle it (once: a second settle does nothing). */
65
+ settle(outcome: FlightOutcome): void;
66
+ /** The flight's work: its outcome, once its request settles it. */
67
+ _fly(signal: AbortSignal): Promise<FlightOutcome>;
68
+ }
69
+ /** The render of `key` in progress: join it (its outcome, `STALE` when an invalidation ended it),
70
+ * or, with none out, open it (`opened`: this request renders the page, and settles it however it
71
+ * ends). */
72
+ export declare function enter_flight(key: string): {
73
+ opened: Flight;
74
+ } | {
75
+ joined: Promise<FlightOutcome | Stale>;
76
+ };
30
77
  /** A function stamped by the `import.meta.og.source` macro (core's data sources). */
31
78
  type SourceFn = (...args: never[]) => unknown;
32
79
  /**
@@ -44,7 +91,9 @@ export declare function invalidate(target: string | SourceFn, args?: unknown[]):
44
91
  export declare function invalidateWhere(filter: {
45
92
  prefix: string;
46
93
  }): Promise<void>;
47
- /** Action self-evict: a successful non-GET on a page URL evicts that URL (origin only — the
48
- * edge copy follows via its s-maxage or the app's explicit invalidate; fire-and-forget). */
49
- export declare function self_evict(runtime: Runtime, pathname: string): void;
94
+ /** Action self-evict: a successful non-GET on a page URL evicts that URL (origin only — the edge
95
+ * copy follows via its s-maxage or the app's explicit invalidate). Settles once the store took it
96
+ * out, or gave up (it never rejects): the response waits for it, so the redirect's GET right after
97
+ * cannot be answered with the page from before the post (#283). */
98
+ export declare function self_evict(runtime: Runtime, pathname: string): Promise<void>;
50
99
  export {};