@zappie/sdk 0.11.1 → 0.13.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.
- package/CHANGELOG.md +22 -0
- package/README.md +102 -4
- package/dist/config/index.d.ts +5 -1
- package/dist/debug.js +1 -1
- package/dist/index.js +1 -1
- package/dist/server/chosen-branch.js +24 -2
- package/dist/server/chosen-branch.js.map +1 -1
- package/dist/server/edge-cache.js +392 -0
- package/dist/server/edge-cache.js.map +6 -0
- package/dist/server/index.d.ts +160 -7
- package/dist/server/index.js +24 -0
- package/dist/server/index.js.map +1 -1
- package/dist/site-closed/index.d.ts +44 -0
- package/dist/site-closed/index.js +39 -0
- package/dist/site-closed/index.js.map +6 -0
- package/dist/site-config/validate.js +8 -11
- package/dist/site-config/validate.js.map +1 -1
- package/dist/vite/index.d.ts +39 -4
- package/dist/vite/index.js +112 -7
- package/package.json +6 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# @zappie/sdk
|
|
2
2
|
|
|
3
|
+
## 0.13.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 846083d: A site Worker now answers from its own cache. `cachedApiFetch({ ctx })` from `@zappie/sdk/server` is a fetch for `createZappie` that keeps `GET /store` and `GET /menus` for as long as the API's `Cache-Control` says, answers a stale read at once and refreshes it after the response through `ctx.waitUntil`. Its key holds a hash of the publishable key, never the key. `cachePage(request, render, { ctx, deployId, branchCookie })` keeps anonymous documents, their `.data`, robots and the sitemap, keyed by URL, branch cookie, deploy and site. It renders afresh for drafts, reviews, previews, the closed state, any `Authorization` header or session cookie and anything but a `GET`, keeps only a cookie-free `200`, and gives each cached HTML page a new CSP nonce. `x-zappie-edge-cache` says how each response was answered. `openEdgeCache()` opens the Worker's own cache, because Workers for Platforms disables `caches.default`.
|
|
8
|
+
|
|
9
|
+
`loadStoreAndMenu` starts the menu read beside the store read for a branch named by slug once a store read in the same isolate has given that slug's ID, and its `cookie` option is now optional.
|
|
10
|
+
|
|
11
|
+
`@zappie/sdk/vite` adds `zappieWorker()`, which minifies the Worker, renders it with React's streaming renderer alone and sets `import.meta.env.ZAPPIE_DEPLOY_ID` for each build. `zappieSource` now pre-bundles every browser entry of `@zappie/sdk` and `@zappie/foundations` and scans `app/` on every dev server, so a new page never re-bundles and reloads a Studio preview.
|
|
12
|
+
|
|
13
|
+
`prerender` in `zappie.config.ts` did nothing, because Zappie hosting prerenders no page. `validateConfig` now warns `unused_setting` when it is set, and the type marks it deprecated.
|
|
14
|
+
|
|
15
|
+
The starter caches its pages and API reads in the Worker, reads the store and menu side by side, answers robots and the sitemap with a 5-minute shared lifetime, builds with `zappieWorker()` and drops `prerender`. Its server build is 214 KB instead of 715 KB. Set `ZAPPIE_EDGE_CACHE=off` to turn the cache off.
|
|
16
|
+
|
|
17
|
+
## 0.12.0
|
|
18
|
+
|
|
19
|
+
### Minor Changes
|
|
20
|
+
|
|
21
|
+
- e2058df: New `@zappie/sdk/site-closed` entry for a storefront's own closed page while the merchant has switched it off. `siteClosed(request)` reads the site host's closed state and the merchant's message, decoded safely and cut to 280 characters, and returns `null` while the store is open. `siteClosedCopy(closed, copy)` gives the heading and message: the merchant's message, then your words, then "Closed for now" and "We're closed for now. Please check back soon." `markClosedPage(response)` marks the page so the site host serves it. The host serves Zappie's own closed page for anything unmarked.
|
|
22
|
+
|
|
23
|
+
The starter draws its own closed page with the store's name, logo and each branch's contact details and hours, with no bag, menu or checkout link and no scripts. Its root loader now reloads the store and menu only when the query, which names the branch, changes, so going home or closing an item makes no request to the Worker.
|
|
24
|
+
|
|
3
25
|
## 0.11.1
|
|
4
26
|
|
|
5
27
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -69,6 +69,7 @@ Prices always come from Zappie. The cart shows a local estimate while it waits,
|
|
|
69
69
|
| `@zappie/sdk/template` and `/template/react` | Template settings and responsive images for template authors |
|
|
70
70
|
| `@zappie/sdk/error-pages` and `/error-pages/react` | Zappie's page not found and something went wrong pages, for the site host's fallback |
|
|
71
71
|
| `@zappie/sdk/site-error` and `/site-error/react` | Your own 404 and error pages: which page, safe words, Try again and the home link |
|
|
72
|
+
| `@zappie/sdk/site-closed` | Your own closed page while the merchant has switched the storefront off |
|
|
72
73
|
| `@zappie/sdk/receipts` | Receipt PDFs as files, and whether the device can share them |
|
|
73
74
|
| `@zappie/sdk/testing` | A mock client for your tests |
|
|
74
75
|
| `@zappie/sdk/url` | Storefront URL parsing and canonical redirects |
|
|
@@ -134,6 +135,41 @@ Zappie's own pages in `@zappie/sdk/error-pages` are for the site host, which
|
|
|
134
135
|
answers with them when a site can't answer at all. A Worker you host yourself
|
|
135
136
|
can return `platformErrorResponse("went-wrong")` when its handler throws.
|
|
136
137
|
|
|
138
|
+
When the merchant switches the storefront off, the site host asks your Worker
|
|
139
|
+
for each page with the closed state. Draw your own closed page in your header
|
|
140
|
+
and footer, with no bag, menu or checkout link. `siteClosed(request)` from
|
|
141
|
+
`@zappie/sdk/site-closed` returns `{ closed: true, message }`, or `null` while
|
|
142
|
+
the store is open. `message` is the merchant's own words as plain text, or
|
|
143
|
+
`null`. `siteClosedCopy(closed, copy)` gives the heading and message to show:
|
|
144
|
+
the merchant's message when they set one, then your words from `copy`, then
|
|
145
|
+
"Closed for now" and "We're closed for now. Please check back soon." Mark the
|
|
146
|
+
page with `markClosedPage(response)`. The host serves only a marked 2xx HTML
|
|
147
|
+
page, and it sets the status and cache headers itself. Anything else, such as
|
|
148
|
+
a page you didn't mark, gets Zappie's own closed page, so a shopper never sees
|
|
149
|
+
your full shop while it is off.
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
import { markClosedPage, siteClosed } from "@zappie/sdk/site-closed";
|
|
153
|
+
|
|
154
|
+
export default {
|
|
155
|
+
async fetch(request: Request, env: Env) {
|
|
156
|
+
if (siteClosed(request)) {
|
|
157
|
+
// Render / for every address, so no shop route runs.
|
|
158
|
+
const response = await handle(
|
|
159
|
+
new Request(new URL("/", request.url), request),
|
|
160
|
+
siteContext(env),
|
|
161
|
+
);
|
|
162
|
+
return response.ok ? markClosedPage(response) : response;
|
|
163
|
+
}
|
|
164
|
+
return handle(request, siteContext(env));
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Your root loader reads the same `siteClosed(request)` and draws the closed
|
|
170
|
+
page instead of the shop. The host asks only for GET and HEAD pages and waits
|
|
171
|
+
5 seconds for an answer.
|
|
172
|
+
|
|
137
173
|
Receipts come as PDF files. `customer.receipt(orderId)` reads an online order's
|
|
138
174
|
receipt, and `receiptFile(url)` from `@zappie/sdk/receipts` reads any receipt
|
|
139
175
|
address, such as a table bill's `inVenue.receiptUrl(orderId)`. Hand the file to
|
|
@@ -286,10 +322,72 @@ When the link, the cookie or the fallback names the branch by ID (`br_…`),
|
|
|
286
322
|
the menu read starts alongside the store read, so the page waits for one round
|
|
287
323
|
trip instead of two. You get the menu once the store confirms that branch,
|
|
288
324
|
with the same errors as `store.get` followed by `menu.get`. A branch named by
|
|
289
|
-
slug
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
325
|
+
slug starts early too once a store read in the same Worker isolate has given
|
|
326
|
+
that slug's ID. The first such request reads the menu after the store, because
|
|
327
|
+
the API takes branch IDs only. `cookie` is optional for a site that keeps no
|
|
328
|
+
branch cookie. `requestedBranch(request, options)` returns the raw value a
|
|
329
|
+
request names, link first, before you have the store.
|
|
330
|
+
|
|
331
|
+
### Edge cache in a site Worker
|
|
332
|
+
|
|
333
|
+
On Zappie hosting each site runs as a Worker in a Workers for Platforms
|
|
334
|
+
dispatch namespace. There `caches.default` is disabled, and each Worker's
|
|
335
|
+
`caches.open()` cache is its own. `@zappie/sdk/server` keeps two kinds of
|
|
336
|
+
response in that cache, through `openEdgeCache()`.
|
|
337
|
+
|
|
338
|
+
`cachedApiFetch({ ctx })` is a fetch for `createZappie` on the server. It keeps
|
|
339
|
+
`GET /store` and `GET /menus` for as long as the API's own `Cache-Control`
|
|
340
|
+
says (`s-maxage`, then `stale-while-revalidate`). A stale read answers at once
|
|
341
|
+
and refreshes after the response through `ctx.waitUntil`, with the menu's ETag.
|
|
342
|
+
Its key is the URL, the API version and a hash of the publishable key, never
|
|
343
|
+
the key itself. A customer's, cart's, order's or quote's call, and any call
|
|
344
|
+
signed in as a shopper or carrying a cookie, goes straight to the API.
|
|
345
|
+
|
|
346
|
+
`cachePage(request, render, { ctx, deployId, branchCookie })` answers a site
|
|
347
|
+
Worker's anonymous pages from the cache: documents, their `.data`, robots and
|
|
348
|
+
the sitemap, for as long as each response's `Cache-Control` says. Its key is
|
|
349
|
+
the full URL, the branch cookie's value, the deploy, and the site the host
|
|
350
|
+
names. It renders afresh for a request that isn't a `GET`, a draft, review or
|
|
351
|
+
preview, the closed state, an `Authorization` header and a session or sign-in
|
|
352
|
+
cookie. It keeps only a `200` that sets no cookie and isn't the closed page. A
|
|
353
|
+
cached HTML page gets a new CSP nonce in its policy and its markup for each
|
|
354
|
+
shopper. `x-zappie-edge-cache` says how each response was answered: `HIT`,
|
|
355
|
+
`STALE`, `MISS` or `BYPASS`.
|
|
356
|
+
|
|
357
|
+
```ts
|
|
358
|
+
import { cachePage, cachedApiFetch } from "@zappie/sdk/server";
|
|
359
|
+
|
|
360
|
+
const client = createZappie({
|
|
361
|
+
store,
|
|
362
|
+
key,
|
|
363
|
+
baseUrl,
|
|
364
|
+
fetch: cachedApiFetch({ ctx }),
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
export default {
|
|
368
|
+
fetch: (request, env, ctx) =>
|
|
369
|
+
cachePage(request, (fresh) => handle(fresh, siteContext(env, ctx)), {
|
|
370
|
+
ctx,
|
|
371
|
+
deployId: import.meta.env.ZAPPIE_DEPLOY_ID,
|
|
372
|
+
branchCookie: "site_branch",
|
|
373
|
+
}),
|
|
374
|
+
};
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
### Vite plugins
|
|
378
|
+
|
|
379
|
+
`@zappie/sdk/vite` holds the build and dev plugins a site uses.
|
|
380
|
+
|
|
381
|
+
- `zappieSource({ previewHost })` marks elements with their source on the
|
|
382
|
+
Studio dev server. On every dev server it also pre-bundles each browser
|
|
383
|
+
entry of the installed `@zappie/sdk` and `@zappie/foundations`, and scans
|
|
384
|
+
every module under `app/`, so opening a page that imports an entry the
|
|
385
|
+
session hasn't seen never re-bundles and reloads the preview.
|
|
386
|
+
- `zappieWorker()` minifies the site's Worker, renders it with React's
|
|
387
|
+
streaming renderer alone, and sets `import.meta.env.ZAPPIE_DEPLOY_ID` to a
|
|
388
|
+
new id for each build. The browser's code is unchanged.
|
|
389
|
+
- `zappieHoistImports()` lists each route's chunks in its own file.
|
|
390
|
+
- `zappieUploads({ host })` serves the site's uploads on a local dev server.
|
|
293
391
|
|
|
294
392
|
### Checkout defaults
|
|
295
393
|
|
package/dist/config/index.d.ts
CHANGED
|
@@ -18,6 +18,10 @@ type ZappieSiteConfig = {
|
|
|
18
18
|
store: string;
|
|
19
19
|
branches?: string[];
|
|
20
20
|
theme: string;
|
|
21
|
+
/**
|
|
22
|
+
* @deprecated Zappie hosting prerenders no page: every page renders in your Worker, and its page cache keeps the
|
|
23
|
+
* anonymous ones. `validateConfig` warns when it is set. Remove it.
|
|
24
|
+
*/
|
|
21
25
|
prerender?: string[];
|
|
22
26
|
menu?: {
|
|
23
27
|
hiddenCategories?: string[];
|
|
@@ -96,7 +100,7 @@ type ZappieSiteConfig = {
|
|
|
96
100
|
*/
|
|
97
101
|
type ConfigIssue = {
|
|
98
102
|
path: string;
|
|
99
|
-
code: "invalid_type" | "missing_required" | "unknown_key" | "invalid_format" | "duplicate" | "redundant_allowlist" | "budget_override";
|
|
103
|
+
code: "invalid_type" | "missing_required" | "unknown_key" | "invalid_format" | "duplicate" | "redundant_allowlist" | "budget_override" | "unused_setting";
|
|
100
104
|
message: string;
|
|
101
105
|
severity: "error" | "warning";
|
|
102
106
|
};
|
package/dist/debug.js
CHANGED
package/dist/index.js
CHANGED
|
@@ -11,7 +11,7 @@ import { ZappieError, isZappieError } from "./errors.js";
|
|
|
11
11
|
export * from "./models.js";
|
|
12
12
|
import { format, money } from "./money.js";
|
|
13
13
|
import { RestTransport } from "./transport/rest.js";
|
|
14
|
-
var VERSION = true ? "0.
|
|
14
|
+
var VERSION = true ? "0.13.0" : "0.0.0-development";
|
|
15
15
|
export {
|
|
16
16
|
API_VERSION,
|
|
17
17
|
RestTransport,
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
// src/server/chosen-branch.ts
|
|
2
2
|
var find = (store, wanted) => wanted ? store.branches.find((b) => b.id === wanted || b.slug === wanted) : void 0;
|
|
3
3
|
function readCookie(request, name) {
|
|
4
|
+
if (!name) {
|
|
5
|
+
return void 0;
|
|
6
|
+
}
|
|
4
7
|
for (const part of (request.headers.get("cookie") ?? "").split(";")) {
|
|
5
8
|
const index = part.indexOf("=");
|
|
6
9
|
if (index > 0 && part.slice(0, index).trim() === name) {
|
|
@@ -29,17 +32,36 @@ var ignore = () => {
|
|
|
29
32
|
};
|
|
30
33
|
async function loadStoreAndMenu(client, request, options) {
|
|
31
34
|
const named = requestedBranch(request, options);
|
|
32
|
-
const
|
|
35
|
+
const learned = slugs(client);
|
|
36
|
+
const guess = named?.startsWith("br_") ? named : named && learned.get(named);
|
|
37
|
+
const early = guess && !client.store.peek() ? client._internal.readMenu(guess, {}) : void 0;
|
|
33
38
|
early?.catch(ignore);
|
|
34
39
|
const store = await client.store.get();
|
|
40
|
+
for (const entry of store.branches) {
|
|
41
|
+
learned.set(entry.slug, entry.id);
|
|
42
|
+
}
|
|
35
43
|
const resolved = resolveBranch(store, request, options);
|
|
36
44
|
const { branch } = resolved;
|
|
37
45
|
if (!branch) {
|
|
38
46
|
return { store, ...resolved, menu: void 0 };
|
|
39
47
|
}
|
|
40
|
-
const menu = await (early && branch.id ===
|
|
48
|
+
const menu = await (early && branch.id === guess ? early : client.menu.get({ branch: branch.id }));
|
|
41
49
|
return { store, ...resolved, menu };
|
|
42
50
|
}
|
|
51
|
+
var learnedSlugs = /* @__PURE__ */ new Map();
|
|
52
|
+
function slugs(client) {
|
|
53
|
+
const { config } = client;
|
|
54
|
+
const id = JSON.stringify([config.baseUrl ?? "", config.store, config.key]);
|
|
55
|
+
let found = learnedSlugs.get(id);
|
|
56
|
+
if (!found) {
|
|
57
|
+
if (learnedSlugs.size >= 100) {
|
|
58
|
+
learnedSlugs.clear();
|
|
59
|
+
}
|
|
60
|
+
found = /* @__PURE__ */ new Map();
|
|
61
|
+
learnedSlugs.set(id, found);
|
|
62
|
+
}
|
|
63
|
+
return found;
|
|
64
|
+
}
|
|
43
65
|
export {
|
|
44
66
|
loadStoreAndMenu,
|
|
45
67
|
requestedBranch,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/server/chosen-branch.ts"],
|
|
4
|
-
"mappings": ";AA0BA,IAAM,OAAO,CAAC,OAAc,WAC1B,SACI,MAAM,SAAS,KAAK,CAAC,MAAM,EAAE,OAAO,UAAU,EAAE,SAAS,MAAM,IAC/D;AAEN,SAAS,WAAW,SAAkB,
|
|
4
|
+
"mappings": ";AA0BA,IAAM,OAAO,CAAC,OAAc,WAC1B,SACI,MAAM,SAAS,KAAK,CAAC,MAAM,EAAE,OAAO,UAAU,EAAE,SAAS,MAAM,IAC/D;AAEN,SAAS,WAAW,SAAkB,MAA0B;AAC9D,MAAI,CAAC,MAAM;AACT,WAAO;AAAA,EACT;AACA,aAAW,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KAAK,IAAI,MAAM,GAAG,GAAG;AACnE,UAAM,QAAQ,KAAK,QAAQ,GAAG;AAC9B,QAAI,QAAQ,KAAK,KAAK,MAAM,GAAG,KAAK,EAAE,KAAK,MAAM,MAAM;AACrD,UAAI;AACF,eAAO,mBAAmB,KAAK,MAAM,QAAQ,CAAC,EAAE,KAAK,CAAC;AAAA,MACxD,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAaO,SAAS,cACd,OACA,SACA,EAAE,QAAQ,UAAU,QAAQ,SAAS,GACrB;AAChB,QAAM,SACJ,KAAK,OAAO,IAAI,IAAI,QAAQ,GAAG,EAAE,aAAa,IAAI,KAAK,CAAC,KACxD,KAAK,OAAO,WAAW,SAAS,MAAM,CAAC;AACzC,QAAM,SACJ,UACA,KAAK,OAAO,QAAQ,KACpB,MAAM,SAAS,KAAK,CAAC,MAAM,EAAE,SAAS,KACtC,MAAM,SAAS,CAAC;AAClB,SAAO;AAAA,IACL;AAAA,IACA,QAAQ,QAAQ,MAAM;AAAA,IACtB,YAAY,CAAC,UAAU,MAAM,SAAS,SAAS;AAAA,EACjD;AACF;AAaO,SAAS,gBACd,SACA,EAAE,QAAQ,UAAU,QAAQ,SAAS,GACjB;AACpB,SACE,IAAI,IAAI,QAAQ,GAAG,EAAE,aAAa,IAAI,KAAK,KAC3C,WAAW,SAAS,MAAM,KAC1B,YACA;AAEJ;AASA,IAAM,SAAS,MAAM;AAAC;AAwBtB,eAAsB,iBACpB,QACA,SACA,SACuB;AACvB,QAAM,QAAQ,gBAAgB,SAAS,OAAO;AAC9C,QAAM,UAAU,MAAM,MAAM;AAG5B,QAAM,QAAQ,OAAO,WAAW,KAAK,IAAI,QAAQ,SAAS,QAAQ,IAAI,KAAK;AAC3E,QAAM,QACJ,SAAS,CAAC,OAAO,MAAM,KAAK,IACxB,OAAO,UAAU,SAAS,OAAO,CAAC,CAAC,IACnC;AACN,SAAO,MAAM,MAAM;AACnB,QAAM,QAAQ,MAAM,OAAO,MAAM,IAAI;AACrC,aAAW,SAAS,MAAM,UAAU;AAClC,YAAQ,IAAI,MAAM,MAAM,MAAM,EAAE;AAAA,EAClC;AACA,QAAM,WAAW,cAAc,OAAO,SAAS,OAAO;AACtD,QAAM,EAAE,OAAO,IAAI;AACnB,MAAI,CAAC,QAAQ;AACX,WAAO,EAAE,OAAO,GAAG,UAAU,MAAM,OAAU;AAAA,EAC/C;AACA,QAAM,OAAO,OAAO,SAAS,OAAO,OAAO,QACvC,QACA,OAAO,KAAK,IAAI,EAAE,QAAQ,OAAO,GAAG,CAAC;AACzC,SAAO,EAAE,OAAO,GAAG,UAAU,KAAK;AACpC;AAIA,IAAM,eAAe,oBAAI,IAAiC;AAE1D,SAAS,MAAM,QAAgB;AAC7B,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,KAAK,KAAK,UAAU,CAAC,OAAO,WAAW,IAAI,OAAO,OAAO,OAAO,GAAG,CAAC;AAC1E,MAAI,QAAQ,aAAa,IAAI,EAAE;AAC/B,MAAI,CAAC,OAAO;AAEV,QAAI,aAAa,QAAQ,KAAK;AAC5B,mBAAa,MAAM;AAAA,IACrB;AACA,YAAQ,oBAAI,IAAI;AAChB,iBAAa,IAAI,IAAI,KAAK;AAAA,EAC5B;AACA,SAAO;AACT;",
|
|
5
5
|
"names": []
|
|
6
6
|
}
|
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
// src/server/edge-cache.ts
|
|
2
|
+
import { createSecurityNonce } from "./security.js";
|
|
3
|
+
var EDGE_CACHE_HEADER = "x-zappie-edge-cache";
|
|
4
|
+
var STORED_AT = "x-zappie-stored-at";
|
|
5
|
+
var FRESH_FOR = "x-zappie-fresh-for";
|
|
6
|
+
var STALE_FOR = "x-zappie-stale-for";
|
|
7
|
+
var ORIGIN_CACHE_CONTROL = "x-zappie-origin-cache-control";
|
|
8
|
+
var CACHE_NAME = "zappie";
|
|
9
|
+
var opened;
|
|
10
|
+
function openEdgeCache() {
|
|
11
|
+
opened ?? (opened = (async () => {
|
|
12
|
+
try {
|
|
13
|
+
return typeof caches === "undefined" ? void 0 : await caches.open(CACHE_NAME);
|
|
14
|
+
} catch {
|
|
15
|
+
return void 0;
|
|
16
|
+
}
|
|
17
|
+
})());
|
|
18
|
+
return opened;
|
|
19
|
+
}
|
|
20
|
+
async function sha256(value) {
|
|
21
|
+
const digest = await crypto.subtle.digest(
|
|
22
|
+
"SHA-256",
|
|
23
|
+
new TextEncoder().encode(value)
|
|
24
|
+
);
|
|
25
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
26
|
+
}
|
|
27
|
+
function sharedFreshness(cacheControl) {
|
|
28
|
+
if (!cacheControl || /\b(?:private|no-store|no-cache)\b/i.test(cacheControl)) {
|
|
29
|
+
return void 0;
|
|
30
|
+
}
|
|
31
|
+
const seconds = (name) => {
|
|
32
|
+
const match = new RegExp(`(?:^|[,\\s])${name}=(\\d+)`, "i").exec(
|
|
33
|
+
cacheControl
|
|
34
|
+
);
|
|
35
|
+
return match ? Number(match[1]) : void 0;
|
|
36
|
+
};
|
|
37
|
+
const fresh = seconds("s-maxage") ?? seconds("max-age") ?? 0;
|
|
38
|
+
if (fresh <= 0) {
|
|
39
|
+
return void 0;
|
|
40
|
+
}
|
|
41
|
+
return { fresh, stale: seconds("stale-while-revalidate") ?? 0 };
|
|
42
|
+
}
|
|
43
|
+
function storable(response, life, now) {
|
|
44
|
+
const headers = new Headers(response.headers);
|
|
45
|
+
headers.delete("set-cookie");
|
|
46
|
+
headers.delete(EDGE_CACHE_HEADER);
|
|
47
|
+
const origin = response.headers.get("cache-control");
|
|
48
|
+
if (origin) {
|
|
49
|
+
headers.set(ORIGIN_CACHE_CONTROL, origin);
|
|
50
|
+
}
|
|
51
|
+
headers.set(STORED_AT, String(now));
|
|
52
|
+
headers.set(FRESH_FOR, String(life.fresh));
|
|
53
|
+
headers.set(STALE_FOR, String(life.stale));
|
|
54
|
+
headers.set("cache-control", `public, max-age=${life.fresh + life.stale}`);
|
|
55
|
+
return new Response(response.body, { status: response.status, headers });
|
|
56
|
+
}
|
|
57
|
+
function served(cached, status, age) {
|
|
58
|
+
const headers = new Headers(cached.headers);
|
|
59
|
+
const origin = headers.get(ORIGIN_CACHE_CONTROL);
|
|
60
|
+
if (origin) {
|
|
61
|
+
headers.set("cache-control", origin);
|
|
62
|
+
} else {
|
|
63
|
+
headers.delete("cache-control");
|
|
64
|
+
}
|
|
65
|
+
for (const name of [STORED_AT, FRESH_FOR, STALE_FOR, ORIGIN_CACHE_CONTROL]) {
|
|
66
|
+
headers.delete(name);
|
|
67
|
+
}
|
|
68
|
+
headers.set("age", String(Math.max(0, Math.floor(age))));
|
|
69
|
+
headers.set(EDGE_CACHE_HEADER, status);
|
|
70
|
+
return new Response(cached.body, { status: cached.status, headers });
|
|
71
|
+
}
|
|
72
|
+
function discard(response) {
|
|
73
|
+
response.body?.cancel().catch(() => {
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
function marked(response, status) {
|
|
77
|
+
const out = new Response(response.body, response);
|
|
78
|
+
out.headers.set(EDGE_CACHE_HEADER, status);
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
async function lookup(cache, key, now) {
|
|
82
|
+
const cached = await cache.match(key);
|
|
83
|
+
if (!cached) {
|
|
84
|
+
return void 0;
|
|
85
|
+
}
|
|
86
|
+
const storedAt = Number(cached.headers.get(STORED_AT));
|
|
87
|
+
const life = {
|
|
88
|
+
fresh: Number(cached.headers.get(FRESH_FOR)),
|
|
89
|
+
stale: Number(cached.headers.get(STALE_FOR))
|
|
90
|
+
};
|
|
91
|
+
if (!Number.isFinite(storedAt) || !Number.isFinite(life.fresh) || !Number.isFinite(life.stale)) {
|
|
92
|
+
discard(cached);
|
|
93
|
+
return void 0;
|
|
94
|
+
}
|
|
95
|
+
return { response: cached, age: (now - storedAt) / 1e3, life };
|
|
96
|
+
}
|
|
97
|
+
var refreshing = /* @__PURE__ */ new Map();
|
|
98
|
+
function refreshOnce(ctx, key, refresh) {
|
|
99
|
+
if (refreshing.has(key.url)) {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const running = refresh().catch(() => {
|
|
103
|
+
}).finally(() => refreshing.delete(key.url));
|
|
104
|
+
refreshing.set(key.url, running);
|
|
105
|
+
ctx.waitUntil(running);
|
|
106
|
+
}
|
|
107
|
+
var SHARED_READS = /\/(?:store|menus)$/;
|
|
108
|
+
function apiCacheBypass(request) {
|
|
109
|
+
if (request.method !== "GET") {
|
|
110
|
+
return "method";
|
|
111
|
+
}
|
|
112
|
+
if (!SHARED_READS.test(new URL(request.url).pathname)) {
|
|
113
|
+
return "path";
|
|
114
|
+
}
|
|
115
|
+
if (!/^Bearer pk_(?:test|live)_/.test(
|
|
116
|
+
request.headers.get("authorization") ?? ""
|
|
117
|
+
)) {
|
|
118
|
+
return "credentials";
|
|
119
|
+
}
|
|
120
|
+
if (request.headers.has("cookie")) {
|
|
121
|
+
return "cookie";
|
|
122
|
+
}
|
|
123
|
+
if (request.headers.has("if-none-match")) {
|
|
124
|
+
return "conditional";
|
|
125
|
+
}
|
|
126
|
+
return void 0;
|
|
127
|
+
}
|
|
128
|
+
async function apiCacheKey(request) {
|
|
129
|
+
const key = (request.headers.get("authorization") ?? "").replace(
|
|
130
|
+
/^Bearer\s+/,
|
|
131
|
+
""
|
|
132
|
+
);
|
|
133
|
+
const url = new URL(request.url);
|
|
134
|
+
const identity = await sha256(
|
|
135
|
+
JSON.stringify([key, request.headers.get("zappie-version") ?? ""])
|
|
136
|
+
);
|
|
137
|
+
return new Request(
|
|
138
|
+
`https://zappie-api-cache.internal/${identity.slice(0, 40)}/${url.host}${url.pathname}${url.search}`
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
function cachedApiFetch(options = {}) {
|
|
142
|
+
const upstream = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
143
|
+
const now = options.now ?? Date.now;
|
|
144
|
+
const source = () => options.cache ?? openEdgeCache();
|
|
145
|
+
return async (input, init) => {
|
|
146
|
+
const request = new Request(input, init);
|
|
147
|
+
if (apiCacheBypass(request)) {
|
|
148
|
+
return upstream(request);
|
|
149
|
+
}
|
|
150
|
+
let cache;
|
|
151
|
+
let key;
|
|
152
|
+
let hit;
|
|
153
|
+
try {
|
|
154
|
+
cache = await source();
|
|
155
|
+
if (cache) {
|
|
156
|
+
key = await apiCacheKey(request);
|
|
157
|
+
hit = await lookup(cache, key, now());
|
|
158
|
+
}
|
|
159
|
+
} catch {
|
|
160
|
+
cache = void 0;
|
|
161
|
+
}
|
|
162
|
+
if (!cache) {
|
|
163
|
+
return upstream(request);
|
|
164
|
+
}
|
|
165
|
+
const store = async (response) => {
|
|
166
|
+
const life = sharedFreshness(response.headers.get("cache-control"));
|
|
167
|
+
if (response.status !== 200 || !life || response.headers.has("set-cookie")) {
|
|
168
|
+
return response;
|
|
169
|
+
}
|
|
170
|
+
const copy = response.clone();
|
|
171
|
+
const put = cache.put(key, storable(copy, life, now())).catch(() => {
|
|
172
|
+
});
|
|
173
|
+
if (options.ctx) {
|
|
174
|
+
options.ctx.waitUntil(put);
|
|
175
|
+
} else {
|
|
176
|
+
await put;
|
|
177
|
+
}
|
|
178
|
+
return response;
|
|
179
|
+
};
|
|
180
|
+
if (hit && hit.age < hit.life.fresh) {
|
|
181
|
+
return served(hit.response, "HIT", hit.age);
|
|
182
|
+
}
|
|
183
|
+
if (hit && options.ctx && hit.age < hit.life.fresh + hit.life.stale) {
|
|
184
|
+
const etag = hit.response.headers.get("etag");
|
|
185
|
+
const kept = hit.response.clone();
|
|
186
|
+
refreshOnce(options.ctx, key, async () => {
|
|
187
|
+
const headers = new Headers(request.headers);
|
|
188
|
+
if (etag) {
|
|
189
|
+
headers.set("if-none-match", etag);
|
|
190
|
+
}
|
|
191
|
+
const response = await upstream(
|
|
192
|
+
new Request(request.url, {
|
|
193
|
+
method: "GET",
|
|
194
|
+
headers,
|
|
195
|
+
redirect: "manual"
|
|
196
|
+
})
|
|
197
|
+
);
|
|
198
|
+
if (response.status === 304) {
|
|
199
|
+
discard(response);
|
|
200
|
+
const life2 = sharedFreshness(response.headers.get("cache-control")) ?? hit.life;
|
|
201
|
+
const restamped = served(kept, "HIT", 0);
|
|
202
|
+
restamped.headers.delete("age");
|
|
203
|
+
restamped.headers.delete(EDGE_CACHE_HEADER);
|
|
204
|
+
await cache.put(key, storable(restamped, life2, now()));
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const life = sharedFreshness(response.headers.get("cache-control"));
|
|
208
|
+
if (response.status === 200 && life && !response.headers.has("set-cookie")) {
|
|
209
|
+
await cache.put(key, storable(response, life, now()));
|
|
210
|
+
} else {
|
|
211
|
+
discard(response);
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
return served(hit.response, "STALE", hit.age);
|
|
215
|
+
}
|
|
216
|
+
if (hit) {
|
|
217
|
+
discard(hit.response);
|
|
218
|
+
}
|
|
219
|
+
return store(await upstream(request));
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
var SESSION_COOKIE = /^(?:__Host-zappie_|__Host-zp_)|(?:^|[_-])(?:session|sess|sid|auth|token|jwt)(?:$|[_-])/i;
|
|
223
|
+
function cookieNames(request) {
|
|
224
|
+
return (request.headers.get("cookie") ?? "").split(";").map((part) => part.slice(0, part.indexOf("=") >>> 0).trim()).filter(Boolean);
|
|
225
|
+
}
|
|
226
|
+
function cookieValue(request, name) {
|
|
227
|
+
for (const part of (request.headers.get("cookie") ?? "").split(";")) {
|
|
228
|
+
const index = part.indexOf("=");
|
|
229
|
+
if (index > 0 && part.slice(0, index).trim() === name) {
|
|
230
|
+
return part.slice(index + 1).trim();
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return "";
|
|
234
|
+
}
|
|
235
|
+
function pageCacheBypass(request, options = {}) {
|
|
236
|
+
if (request.method !== "GET") {
|
|
237
|
+
return "method";
|
|
238
|
+
}
|
|
239
|
+
if (["x-zappie-draft", "x-zappie-review", "x-zappie-preview"].some(
|
|
240
|
+
(name) => request.headers.has(name)
|
|
241
|
+
) || new URL(request.url).searchParams.has("preview")) {
|
|
242
|
+
return "preview";
|
|
243
|
+
}
|
|
244
|
+
if (request.headers.has("x-zappie-site-state")) {
|
|
245
|
+
return "closed";
|
|
246
|
+
}
|
|
247
|
+
if (request.headers.has("authorization")) {
|
|
248
|
+
return "authorization";
|
|
249
|
+
}
|
|
250
|
+
const own = new Set(options.privateCookies ?? []);
|
|
251
|
+
if (cookieNames(request).some(
|
|
252
|
+
(name) => own.has(name) || SESSION_COOKIE.test(name)
|
|
253
|
+
)) {
|
|
254
|
+
return "session";
|
|
255
|
+
}
|
|
256
|
+
return void 0;
|
|
257
|
+
}
|
|
258
|
+
async function pageCacheKey(request, options) {
|
|
259
|
+
const identity = await sha256(
|
|
260
|
+
JSON.stringify([
|
|
261
|
+
request.url,
|
|
262
|
+
options.branchCookie ? cookieValue(request, options.branchCookie) : "",
|
|
263
|
+
options.deployId,
|
|
264
|
+
request.headers.get("x-zappie-site") ?? "",
|
|
265
|
+
request.headers.get("x-zappie-key") ?? ""
|
|
266
|
+
])
|
|
267
|
+
);
|
|
268
|
+
return new Request(`https://zappie-page-cache.internal/${identity}`);
|
|
269
|
+
}
|
|
270
|
+
function pageStoreBypass(response, fallback) {
|
|
271
|
+
if (response.status !== 200) {
|
|
272
|
+
return "status";
|
|
273
|
+
}
|
|
274
|
+
if (response.headers.has("set-cookie")) {
|
|
275
|
+
return "set-cookie";
|
|
276
|
+
}
|
|
277
|
+
if (response.headers.has("x-zappie-closed-page")) {
|
|
278
|
+
return "closed";
|
|
279
|
+
}
|
|
280
|
+
if (/(?:^|,)\s*\*\s*(?:,|$)/.test(response.headers.get("vary") ?? "")) {
|
|
281
|
+
return "vary";
|
|
282
|
+
}
|
|
283
|
+
if (!sharedFreshness(response.headers.get("cache-control") ?? fallback ?? null)) {
|
|
284
|
+
return "cache-control";
|
|
285
|
+
}
|
|
286
|
+
return void 0;
|
|
287
|
+
}
|
|
288
|
+
var NONCE = /'nonce-([A-Za-z0-9_+/=-]+)'/;
|
|
289
|
+
var POLICY_HEADERS = [
|
|
290
|
+
"content-security-policy",
|
|
291
|
+
"content-security-policy-report-only"
|
|
292
|
+
];
|
|
293
|
+
async function rotatePageNonce(response, nonce = createSecurityNonce()) {
|
|
294
|
+
const old = POLICY_HEADERS.map(
|
|
295
|
+
(name) => NONCE.exec(response.headers.get(name) ?? "")?.[1]
|
|
296
|
+
).find(Boolean);
|
|
297
|
+
if (!old || !/^text\/html/i.test(response.headers.get("content-type") ?? "")) {
|
|
298
|
+
return response;
|
|
299
|
+
}
|
|
300
|
+
const headers = new Headers(response.headers);
|
|
301
|
+
for (const name of POLICY_HEADERS) {
|
|
302
|
+
const value = headers.get(name);
|
|
303
|
+
if (value) {
|
|
304
|
+
headers.set(name, value.replaceAll(`'nonce-${old}'`, `'nonce-${nonce}'`));
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
headers.delete("content-length");
|
|
308
|
+
const body = (await response.text()).replaceAll(`nonce="${old}"`, `nonce="${nonce}"`).replaceAll(`nonce=${old}`, `nonce=${nonce}`);
|
|
309
|
+
return new Response(body, { status: response.status, headers });
|
|
310
|
+
}
|
|
311
|
+
async function cachePage(request, render, options) {
|
|
312
|
+
if (pageCacheBypass(request, options)) {
|
|
313
|
+
return marked(await render(request), "BYPASS");
|
|
314
|
+
}
|
|
315
|
+
const now = options.now ?? Date.now;
|
|
316
|
+
let cache;
|
|
317
|
+
let key;
|
|
318
|
+
let hit;
|
|
319
|
+
try {
|
|
320
|
+
cache = await (options.cache ?? openEdgeCache());
|
|
321
|
+
if (cache) {
|
|
322
|
+
key = await pageCacheKey(request, options);
|
|
323
|
+
hit = await lookup(cache, key, now());
|
|
324
|
+
}
|
|
325
|
+
} catch {
|
|
326
|
+
cache = void 0;
|
|
327
|
+
}
|
|
328
|
+
if (!cache || !key) {
|
|
329
|
+
return marked(await render(request), "BYPASS");
|
|
330
|
+
}
|
|
331
|
+
const fallback = () => options.cacheControl?.(new URL(request.url));
|
|
332
|
+
const keep = async (response) => {
|
|
333
|
+
const control = response.headers.get("cache-control") ?? fallback();
|
|
334
|
+
if (pageStoreBypass(response, control)) {
|
|
335
|
+
return void 0;
|
|
336
|
+
}
|
|
337
|
+
const life = sharedFreshness(control ?? null);
|
|
338
|
+
const shared = new Response(response.body, response);
|
|
339
|
+
if (control && !shared.headers.has("cache-control")) {
|
|
340
|
+
shared.headers.set("cache-control", control);
|
|
341
|
+
}
|
|
342
|
+
return { shared, life };
|
|
343
|
+
};
|
|
344
|
+
if (hit && hit.age < hit.life.fresh) {
|
|
345
|
+
return rotatePageNonce(served(hit.response, "HIT", hit.age));
|
|
346
|
+
}
|
|
347
|
+
if (hit && options.ctx && hit.age < hit.life.fresh + hit.life.stale) {
|
|
348
|
+
refreshOnce(options.ctx, key, async () => {
|
|
349
|
+
const kept2 = await keep(
|
|
350
|
+
await render(
|
|
351
|
+
new Request(request.url, { method: "GET", headers: request.headers })
|
|
352
|
+
)
|
|
353
|
+
);
|
|
354
|
+
if (kept2) {
|
|
355
|
+
await cache.put(key, storable(kept2.shared, kept2.life, now()));
|
|
356
|
+
} else {
|
|
357
|
+
await cache.delete(key);
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
return rotatePageNonce(served(hit.response, "STALE", hit.age));
|
|
361
|
+
}
|
|
362
|
+
if (hit) {
|
|
363
|
+
discard(hit.response);
|
|
364
|
+
}
|
|
365
|
+
const rendered = await render(request);
|
|
366
|
+
const kept = await keep(rendered);
|
|
367
|
+
if (!kept) {
|
|
368
|
+
return marked(rendered, "MISS");
|
|
369
|
+
}
|
|
370
|
+
const put = cache.put(key, storable(kept.shared.clone(), kept.life, now())).catch(() => {
|
|
371
|
+
});
|
|
372
|
+
if (options.ctx) {
|
|
373
|
+
options.ctx.waitUntil(put);
|
|
374
|
+
} else {
|
|
375
|
+
await put;
|
|
376
|
+
}
|
|
377
|
+
return marked(kept.shared, "MISS");
|
|
378
|
+
}
|
|
379
|
+
export {
|
|
380
|
+
EDGE_CACHE_HEADER,
|
|
381
|
+
apiCacheBypass,
|
|
382
|
+
apiCacheKey,
|
|
383
|
+
cachePage,
|
|
384
|
+
cachedApiFetch,
|
|
385
|
+
openEdgeCache,
|
|
386
|
+
pageCacheBypass,
|
|
387
|
+
pageCacheKey,
|
|
388
|
+
pageStoreBypass,
|
|
389
|
+
rotatePageNonce,
|
|
390
|
+
sharedFreshness
|
|
391
|
+
};
|
|
392
|
+
//# sourceMappingURL=edge-cache.js.map
|