@amboras-dev/storefront-core 2026.11.11 → 2026.11.12
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 +133 -0
- package/README.md +29 -3
- package/bin/amboras-check.mjs +2 -1
- package/bin/checks/check-market-routes.mjs +187 -0
- package/bin/checks/check-redirect-boundaries.mjs +10 -2
- package/core-manifest.json +6 -1
- package/dist/edge/hosted-checkout.d.ts +5 -2
- package/dist/edge/hosted-checkout.d.ts.map +1 -1
- package/dist/edge/hosted-checkout.js +11 -7
- package/dist/edge/hosted-checkout.js.map +1 -1
- package/dist/edge/market.d.ts +45 -0
- package/dist/edge/market.d.ts.map +1 -0
- package/dist/edge/market.js +74 -0
- package/dist/edge/market.js.map +1 -0
- package/dist/edge/proxy.d.ts +27 -2
- package/dist/edge/proxy.d.ts.map +1 -1
- package/dist/edge/proxy.js +206 -56
- package/dist/edge/proxy.js.map +1 -1
- package/dist/edge/url-map.d.ts +57 -0
- package/dist/edge/url-map.d.ts.map +1 -0
- package/dist/edge/url-map.js +140 -0
- package/dist/edge/url-map.js.map +1 -0
- package/dist/hooks/use-auth.d.ts.map +1 -1
- package/dist/hooks/use-auth.js +5 -2
- package/dist/hooks/use-auth.js.map +1 -1
- package/dist/lib/market.d.ts +176 -0
- package/dist/lib/market.d.ts.map +1 -0
- package/dist/lib/market.js +228 -0
- package/dist/lib/market.js.map +1 -0
- package/dist/lib/medusa-client.d.ts.map +1 -1
- package/dist/lib/medusa-client.js +30 -1
- package/dist/lib/medusa-client.js.map +1 -1
- package/dist/lib/redirects.d.ts +14 -6
- package/dist/lib/redirects.d.ts.map +1 -1
- package/dist/lib/redirects.js +68 -9
- package/dist/lib/redirects.js.map +1 -1
- package/dist/lib/seo.d.ts +20 -7
- package/dist/lib/seo.d.ts.map +1 -1
- package/dist/lib/seo.js +185 -33
- package/dist/lib/seo.js.map +1 -1
- package/dist/lib/site-url.d.ts +24 -0
- package/dist/lib/site-url.d.ts.map +1 -1
- package/dist/lib/site-url.js +35 -0
- package/dist/lib/site-url.js.map +1 -1
- package/dist/lib/visitor-free-routes.d.ts +18 -0
- package/dist/lib/visitor-free-routes.d.ts.map +1 -0
- package/dist/lib/visitor-free-routes.js +33 -0
- package/dist/lib/visitor-free-routes.js.map +1 -0
- package/dist/next-config/index.d.ts +31 -0
- package/dist/next-config/index.d.ts.map +1 -1
- package/dist/next-config/index.js +32 -1
- package/dist/next-config/index.js.map +1 -1
- package/dist/shell/market-link.d.ts +18 -0
- package/dist/shell/market-link.d.ts.map +1 -0
- package/dist/shell/market-link.js +39 -0
- package/dist/shell/market-link.js.map +1 -0
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,139 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 2026.11.12
|
|
6
|
+
|
|
7
|
+
### Rollout
|
|
8
|
+
|
|
9
|
+
- Deploy order: Medusa first (it serves `GET /store/url-map` and `GET /store/market-exclusions`), then this core, then
|
|
10
|
+
the orchestrator, then the template. A Medusa without the URL map (404) means no market URL: today's storefront and
|
|
11
|
+
sitemaps. A Medusa with the URL map but without `/store/market-exclusions` (404) makes every product child that
|
|
12
|
+
names market alternates answer 5xx (crawlers retry) until it ships, never alternates it cannot check.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- Market URLs (AMB-2174, Shopify's market web presences): a market can have a subfolder (`store.com/en-ca`), a subdomain
|
|
17
|
+
(`ca.store.com`) or its own domain (`store.ca`). Medusa owns the link and serves it as `GET /store/url-map`.
|
|
18
|
+
- `/edge`: `marketProxy`, for a store whose routes live under `app/[m]/`. It resolves the market from the host or the
|
|
19
|
+
first path segment and rewrites every page to `/{key}{path}` (`_` root, `en-ca` subfolder, `_<marketId>` host).
|
|
20
|
+
The host is the request's Host header through the one read of it, `requestHostOf` in `lib/site-url` (`host`,
|
|
21
|
+
lowercase, port dropped), which the sitemaps, robots and the hosted checkout read too, so routing and canonicals
|
|
22
|
+
never see two hosts; the URL's hostname only without one (under `next start` it is the listen host). Never
|
|
23
|
+
`x-forwarded-host`: under `next start` and `next dev` a client's copy reaches the app, the orchestrator's preview
|
|
24
|
+
proxy passes one on, and on Vercel it equals `host`.
|
|
25
|
+
A previous path (the map's `previousPaths`) and a former default language's path (`languagePaths`: `/de-ca`, and
|
|
26
|
+
`/en-can` after en→de and can→ca, each computed by Medusa) 301 to the current URL only while that URL is
|
|
27
|
+
announced (active and turned on); to a pending host, an inactive market or a passive URL they 302 to the root
|
|
28
|
+
instead (`unserved`), so no indexed link is moved for good to a URL that does not serve. A language that is only
|
|
29
|
+
enabled is never a redirect (`/fr-ca` is the root's), and an older map without `languagePaths` has none. An
|
|
30
|
+
inactive presence 302s to the root when Medusa
|
|
31
|
+
says so in `inactiveRedirect` (`temporary`: a draft market, market URLs off, a market now the primary; null or an
|
|
32
|
+
unknown value: no redirect); `/en-ca/checkout*` 302s to the root checkout. Every market redirect is `no-store`. A
|
|
33
|
+
copy of the map older than 10 minutes routes but never redirects, except to the root checkout.
|
|
34
|
+
- Paths in `OUTSIDE_MARKET_TREE` are never rewritten: files (`public/`, `/llms.txt`, `/pinterest/feed.xml`, robots,
|
|
35
|
+
sitemaps, the manifest), `/api`, `.well-known` and the root metadata images. A file path that no file or route
|
|
36
|
+
answers goes to `/_/<path>` through `marketFallbackRewrites()` (`/next-config`, a store's `afterFiles` rewrites,
|
|
37
|
+
one rule), so the catch-all answers the merchant's redirect for it, as on the old tree. A subfolder's file keeps
|
|
38
|
+
its market: `marketProxy` names the market key in `x-amb-market-key` (`MARKET_KEY_HEADER`), and the catch-all's
|
|
39
|
+
lookup accepts a subfolder key that the URL map holds as an active market and that is the path's own prefix, so
|
|
40
|
+
`/en-ca/catalog.pdf` inherits the root's `/catalog.pdf` redirect, prefixed (308 `/en-ca/new`). Any other key is
|
|
41
|
+
the root's lookup. The key comes from a copy of the map younger than 10 minutes only; on a cold instance the read
|
|
42
|
+
starts in the background, so a later request has it. A file never waits for the map, never 503s, never redirects
|
|
43
|
+
and sends no beacon. A real file in `public/` is served first. A dotted path on a market host
|
|
44
|
+
(`ca.store.com/products/a.b`) is the root's: Medusa's product handles carry no `.`.
|
|
45
|
+
- Market URLs exist only on a build that opted in (`marketTreeEnv()`, `isMarketTreeBuild()`): without it neither
|
|
46
|
+
`proxy` nor `marketProxy` reads the URL map, and `proxy` (a store on the old route tree) sets no `x-amb-market`,
|
|
47
|
+
sends no market redirect and adds no market canonical, exactly as before. Both delete client copies of
|
|
48
|
+
`x-amb-market`, `x-amb-market-hop` and `x-amb-market-key`. With the opt-in, `marketProxy` sets `x-amb-market` to the
|
|
49
|
+
resolved market (none on the root); `proxy` never rewrites a path.
|
|
50
|
+
- A/B on the `app/[m]/` tree: the control signs the internal path it resolved into `x-amb-market-hop`
|
|
51
|
+
(`MARKET_HOP_HEADER`, the `amb_theme` HMAC, valid 60 s), and the variant's `marketProxy` serves that path as it is.
|
|
52
|
+
A variant that cannot verify it (no secret yet, an old one) still serves an internal key the map holds (`/_/x`, a
|
|
53
|
+
market host's `/_<marketId>/x`) as it is on a host that is not the store's, without a market header, and counts
|
|
54
|
+
`hop_unverified` (as for any hop header that fails verification). On such a host a subfolder resolves as on the primary (draft 302, previous-suffix 301 included),
|
|
55
|
+
so subfolder pages keep rendering there with or without a verified hop.
|
|
56
|
+
- The edge keeps the map in memory: refreshed every 30 s with `If-None-Match`, in the background once a copy exists,
|
|
57
|
+
one fetch in flight, a 1.5 s timeout, the last good copy when Medusa fails. A 404 or 410 before any good copy (an
|
|
58
|
+
older Medusa) means no map: the root everywhere, retried in 30 s; any other 4xx, or a 4xx after a good copy, keeps
|
|
59
|
+
the copy, marked stale. A cold instance (its first page request) waits for that read, up to 1.5 s, even on a store
|
|
60
|
+
with no market URL: the map is how it knows there is none. One that cannot read it tries
|
|
61
|
+
again after 5 s and, on the primary host, answers a first segment that starts like a market URL (a language subtag
|
|
62
|
+
and a hyphen, `en-ca`; not a template page such as `/kit-gallery`) with a 503 (`Retry-After: 5`, `no-store`) that
|
|
63
|
+
crawlers retry, where a 404 would drop the page; every other path is the
|
|
64
|
+
root's; after 10 minutes without a map (a revoked key, a WAF block) it stops answering 503 and serves the root,
|
|
65
|
+
still retrying. A change to a market URL reaches the edge within about 90 s (Medusa's 30 s memo, 30 s at
|
|
66
|
+
CloudFront, the copy's 30 s refresh) and a page's canonical and the sitemaps 30 s after that (the data cache). Market redirects run only on the store's own hosts: a preview or variant deployment keeps its
|
|
67
|
+
password gate first and never sends a visitor to the live checkout. It counts `map_stale`, `map_unavailable`, `inactive_redirect` and `hop_unverified` through
|
|
68
|
+
`POST /store/market-signals` (kind only), at most once a minute per kind.
|
|
69
|
+
- `lib/market` (new shim `lib/market.ts`): `StoreUrlMap`, `parseStoreUrlMap` (a presence of an unknown kind or status
|
|
70
|
+
is left out, not the whole map), `MARKET_HEADER`, `OUTSIDE_MARKET_TREE`, `isOutsideMarketTree`, `prefixOfKey`,
|
|
71
|
+
`isMarketKey` (an internal key, or one safe lowercase segment the proxy rewrites; a segment of
|
|
72
|
+
`OUTSIDE_MARKET_TREE` such as `api` is not one), `assertMarketKey(m, notFound)` (the `[m]` layout's guard),
|
|
73
|
+
`marketHref`, `getStoreUrlMap` (null only on a 404 or 410, a store API without the map; any other answer that is
|
|
74
|
+
not a map throws `StoreUrlMapUnavailableError`, as the edge copy reads it). The `m` param is request input: a key or
|
|
75
|
+
prefix that is not one safe lowercase segment (`isMarketPrefix`: no slash, backslash, `_` or `.`) prefixes nothing,
|
|
76
|
+
and a redirect lookup given one answers none. Core never re-checks the market URL rule itself (language and
|
|
77
|
+
suffix): that is Medusa's alone, and the map carries only what it allowed.
|
|
78
|
+
- `/visitor-free-routes`: `VISITOR_FREE_ROUTES`, the store routes whose GET/HEAD answer never depends on the visitor
|
|
79
|
+
(`/store/content/blogs/:blog/articles`, …). The server fetch shim reads it, and Medusa's mirror spec imports it, so
|
|
80
|
+
the list has one owner.
|
|
81
|
+
- `shell/market-link`: `useMarketHref`, `MarketLink`, `useMarketPathname` (the public path on the server and in the
|
|
82
|
+
browser alike). `useAuth().logout` goes to the market's home.
|
|
83
|
+
- `lib/site-url`: `requestHostOf(headers, { port })`, the request host (above); a store's unmatched-path page passes
|
|
84
|
+
`requestHostOf(await headers())` as `resolveUnmatchedPathRedirect`'s `requestHost`. `marketMetadataBase(key, map)`, the `metadataBase` of an `app/[m]/` page (`https://store.com/en-ca`,
|
|
85
|
+
`https://store.ca`); the root origin for a passive (backfilled, not turned on) presence.
|
|
86
|
+
- `lib/seo`: the sitemap index lists the root plus each announced subfolder on the primary host, and a market's own
|
|
87
|
+
host lists its market; child ids are `slot * 100000 + page`, the slot being Medusa's stable presence `ordinal`
|
|
88
|
+
(the root's slot is 0, so its ids are unchanged). Every URL carries hreflang alternates (`en-CA`, …, `x-default`) when the store's
|
|
89
|
+
hreflang setting is on and a market URL is announced. A market's sitemap (a subfolder's slot, or its own host's)
|
|
90
|
+
lists what its region sells (`/store/products?region_id=`, the map's `regionId`; a market without one lists no
|
|
91
|
+
product), and a product URL names as alternates only the markets that sell it: the slot's own market sells all it
|
|
92
|
+
lists, another market every product its region does not exclude. The exclusions are ONE read per product child,
|
|
93
|
+
`GET /store/market-exclusions` (`{ markets: [{ marketId, productIds }], regions: [{ regionId, marketIds }] }`: a
|
|
94
|
+
region excludes the union of its markets' ids, Medusa's own exclusion rule and lineage; a region not listed
|
|
95
|
+
excludes nothing), cached
|
|
96
|
+
like the child and shared by every child; none without hreflang or when no other market has a region. A failed,
|
|
97
|
+
missing (an older Medusa's 404) or malformed answer rejects the child (crawlers retry): it never lists alternates
|
|
98
|
+
without it. Deploy Medusa with that route before this core. The sitemap is the only place
|
|
99
|
+
hreflang is written: no page `<head>` carries it, so the two can never disagree. `robots.txt` names a market host's own sitemap there and
|
|
100
|
+
disallows the private pages under each announced subfolder too. All of it only on the `app/[m]/` tree
|
|
101
|
+
(`marketTreeEnv()`, `isMarketTreeBuild()`): a store on the old route tree never reads the map there and gets
|
|
102
|
+
byte-for-byte today's sitemaps and robots, as does a store with no announced market URL.
|
|
103
|
+
- `lib/redirects`: `resolveRedirect`, `resolveHandleRedirect` and `resolveUnmatchedPathRedirect` take a
|
|
104
|
+
`marketPrefix` (`prefixOfKey(params.m)`). Under a prefix the full path is tried first (`/en-ca/old-page`), then
|
|
105
|
+
the inner path, whose relative target stays in the market. With no prefix, on the `app/[m]/` tree,
|
|
106
|
+
`resolveUnmatchedPathRedirect` takes a market file path's prefix from `x-amb-market-key` as above (it reads
|
|
107
|
+
`headers()`; a map that cannot be read is the root's lookup, never a 500, logged as `redirect_lookup_failed`).
|
|
108
|
+
- `amboras-check market-routes`: on a store with `app/[m]/` or a `marketProxy` export, fails a route file on the wrong
|
|
109
|
+
side of `OUTSIDE_MARKET_TREE` (and a metadata image anywhere but the app root) with the move to make, an
|
|
110
|
+
`app/[m]/layout` without `assertMarketKey`, and a `next.config` that does not spread `marketTreeEnv()` into its
|
|
111
|
+
`env` or return `marketFallbackRewrites()` in its `rewrites()` `afterFiles` (alone, or spread anywhere in an array).
|
|
112
|
+
`amboras-check redirect-boundaries` guards the same folders under
|
|
113
|
+
`app/[m]/`, and `app/[m]/loading.*`.
|
|
114
|
+
|
|
115
|
+
### Fixed
|
|
116
|
+
|
|
117
|
+
- Static rendering, on a store that opts in (`env: { ...marketTreeEnv() }` in next.config, `/next-config`: the
|
|
118
|
+
`app/[m]/` template): the server fetch shim (`lib/medusa-client`) read `cookies()` / `headers()` for every request to
|
|
119
|
+
Medusa, so a statically rendered page (`/about`, `/checkout`, `/account`) threw "static to dynamic" on every
|
|
120
|
+
revalidation and stayed stale, and an `app/[m]/` page's first render under a market key answered 500. With the
|
|
121
|
+
opt-in it skips that read for a GET of the exact store routes core calls that Medusa answers the same for every
|
|
122
|
+
visitor: `/store/url-map`, `/store/url-redirects`, `/store/content/blogs`, `/store/content/blogs/:blog/articles`,
|
|
123
|
+
`/store/content/blogs/:blog/articles/:handle`, `/store/content/blogs/:blog/articles/:handle/comments`,
|
|
124
|
+
`/store/metaobjects/:type`, `/store/metaobjects/:type/:handle`, `/store/config`, `/store/brand`,
|
|
125
|
+
`/store/integrations/active`, `/store/policies`, `/store/checkout-settings`, `/store/market-exclusions` (matched on
|
|
126
|
+
the normalised path).
|
|
127
|
+
Every other route keeps the visitor's `x-amb-vid` / `x-amb-country`, and a store without the opt-in (every store on
|
|
128
|
+
the old tree) is exactly as before.
|
|
129
|
+
- The hosted checkout's store token names the request's Host header (`requestHostOf`, port kept) as the store's host,
|
|
130
|
+
never a client's `x-forwarded-host` (which reached it under `next start` and through the preview proxy). Same value on
|
|
131
|
+
Vercel, where the two are equal.
|
|
132
|
+
- `edge/proxy.ts` no longer claims to be generated from the orchestrator's `middleware-template.ts`: core stores run
|
|
133
|
+
this file, legacy stores run the template.
|
|
134
|
+
- `amboras-check market-routes` requires `app/[m]/layout.*` to call `assertMarketKey(`, read with comments stripped
|
|
135
|
+
(the sibling gate's `stripComments`). It accepted any layout that named it, so one that kept the import but dropped
|
|
136
|
+
the call passed, and every page then rendered under a first segment no market owns (`/api/about` answered 200).
|
|
137
|
+
|
|
5
138
|
## 2026.11.11
|
|
6
139
|
|
|
7
140
|
### Added
|
package/README.md
CHANGED
|
@@ -57,7 +57,7 @@ from it and its version-floor check makes sure each shim exists.
|
|
|
57
57
|
| `types/index.ts` | `@amboras-dev/storefront-core/types` |
|
|
58
58
|
| `components/ClientPluginSlot.tsx` | `@amboras-dev/storefront-core/shell/client-plugin-slot` |
|
|
59
59
|
| `components/PluginSlot.tsx` | `createPluginSlot` from `@amboras-dev/storefront-core/server/plugin-slot` |
|
|
60
|
-
| `proxy.ts` | `proxy` from `@amboras-dev/storefront-core/edge`
|
|
60
|
+
| `proxy.ts` | `proxy` (or `marketProxy`) from `@amboras-dev/storefront-core/edge` |
|
|
61
61
|
|
|
62
62
|
### 3. The registry and payment UI are injected
|
|
63
63
|
|
|
@@ -184,6 +184,31 @@ export const config = {
|
|
|
184
184
|
|
|
185
185
|
`amboras-check proxy-matcher` fails when the copy differs from the installed core's matcher.
|
|
186
186
|
|
|
187
|
+
**Market URLs (AMB-2174).** A store whose routes live under `app/[m]/` exports `marketProxy as proxy` instead. It
|
|
188
|
+
reads the store's URL map (`GET /store/url-map`), resolves the market from the host (`ca.store.com`, `store.ca`) or the
|
|
189
|
+
first path segment (`/en-ca`), rewrites every page to `/{market key}{path}` and sets the `x-amb-market` request header
|
|
190
|
+
(any client copy is deleted first). A store on the old tree keeps `proxy`, which reads no URL map and never rewrites
|
|
191
|
+
a path, so it is unchanged by a core bump. Links go through `MarketLink` / `useMarketHref` (`/shell/market-link`) or
|
|
192
|
+
`marketHref` (`/lib/market`); the current path through `useMarketPathname` (never `usePathname`, which differs between
|
|
193
|
+
the server and the browser on a rewritten page). The `[m]` layout guards its key with `assertMarketKey(m, notFound)`
|
|
194
|
+
and sets `metadataBase` with `marketMetadataBase(m, map)`. `next.config` (both from `/next-config`) spreads
|
|
195
|
+
`...marketTreeEnv()` into its `env`, the opt-in that lets the visitor-independent store reads skip the visitor
|
|
196
|
+
cookies so static pages stay static (without it the store is an old tree: no market URL anywhere), and returns
|
|
197
|
+
`afterFiles: marketFallbackRewrites()` from `rewrites()`: a file path no file or route answered goes to `/_/<path>`,
|
|
198
|
+
where the catch-all answers the merchant's redirect, as on the old tree (`/en-ca/old.pdf` in the `en-ca` market, from
|
|
199
|
+
the key `marketProxy` names in `x-amb-market-key`). `OUTSIDE_MARKET_TREE`
|
|
200
|
+
(`/lib/market`, `/edge`) is the one list of paths served outside `app/[m]/`: files, `/api`, `.well-known`, the sitemaps
|
|
201
|
+
and the root metadata images. `amboras-check market-routes` fails a route file on the wrong side of it, a layout
|
|
202
|
+
without `assertMarketKey` and a `next.config` without either of the two.
|
|
203
|
+
|
|
204
|
+
What a market URL is (its language and suffix) is Medusa's rule alone: the map holds only what it allowed, with each
|
|
205
|
+
moved URL's old paths (`previousPaths`, and `languagePaths` for a former default language). An old path 301s only to
|
|
206
|
+
an announced URL; to one that is not serving yet it 302s to the root. The edge keeps the map in memory, so a page
|
|
207
|
+
request makes no Medusa call except on a cold instance's first request, which waits up to 1.5 s for it (even on a
|
|
208
|
+
store without market URLs). With no map at all, a path that starts like a market URL (`/en-ca`) answers 503 for up
|
|
209
|
+
to 10 minutes, which crawlers retry. A change reaches the edge within about 90 s and a page's canonical and the
|
|
210
|
+
sitemaps about 30 s after that.
|
|
211
|
+
|
|
187
212
|
### 6. Feature switches: unknown is not off
|
|
188
213
|
|
|
189
214
|
`useStoreConfig()` (client) and `getStoreConfig()` (server) read Medusa's `GET /store/config`. Each
|
|
@@ -197,7 +222,7 @@ then falls back to `/store/checkout-settings`.
|
|
|
197
222
|
### 7. Build gates
|
|
198
223
|
|
|
199
224
|
```bash
|
|
200
|
-
npx amboras-check # plugin slots, store quirks, redirect boundaries, consent scroll, proxy matcher
|
|
225
|
+
npx amboras-check # plugin slots, store quirks, redirect boundaries, consent scroll, proxy matcher, market routes
|
|
201
226
|
npx amboras-check slots # one gate
|
|
202
227
|
```
|
|
203
228
|
|
|
@@ -209,7 +234,8 @@ npx amboras-check slots # one gate
|
|
|
209
234
|
| `/client/<hook>` | one hook file, same exports as the template's | per file |
|
|
210
235
|
| `/server` | `createPluginSlot`, `PluginSlot`, `getPluginConfigs`, `medusaFetch`, `getStoreConfig`, config | no |
|
|
211
236
|
| `/lib/<path>` | logic modules (checkout, cart, payment providers, analytics, consent…) | per file |
|
|
212
|
-
| `/edge` | `proxy`, `proxyConfig`
|
|
237
|
+
| `/edge` | `proxy`, `marketProxy`, `proxyConfig`, `OUTSIDE_MARKET_TREE`, `MARKET_HOP_HEADER` | no |
|
|
238
|
+
| `/visitor-free-routes` | `VISITOR_FREE_ROUTES`, the store routes that never vary by visitor (Medusa's spec imports it) | no |
|
|
213
239
|
| `/next-config` | `withAmborasCore`, `resolveAmborasImageHosts` | no |
|
|
214
240
|
| `/config` | `configureCore`, `getCoreConfig` | no |
|
|
215
241
|
| `/types`, `/types/plugins` | shared types, slot types | no |
|
package/bin/amboras-check.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
//
|
|
4
4
|
// amboras-check [gate…] [--root <dir>]
|
|
5
5
|
//
|
|
6
|
-
// Gates: slots, quirks, redirect-boundaries, consent-scroll, proxy-matcher (default: all).
|
|
6
|
+
// Gates: slots, quirks, redirect-boundaries, consent-scroll, proxy-matcher, market-routes (default: all).
|
|
7
7
|
// The store root defaults to the current directory. Each gate is a separate
|
|
8
8
|
// node process, so a failing gate's exit code and output are its own.
|
|
9
9
|
import { spawnSync } from 'node:child_process'
|
|
@@ -17,6 +17,7 @@ const GATES = {
|
|
|
17
17
|
'redirect-boundaries': 'check-redirect-boundaries.mjs',
|
|
18
18
|
'consent-scroll': 'check-consent-scroll.mjs',
|
|
19
19
|
'proxy-matcher': 'check-proxy-matcher.mjs',
|
|
20
|
+
'market-routes': 'check-market-routes.mjs',
|
|
20
21
|
}
|
|
21
22
|
|
|
22
23
|
const args = process.argv.slice(2)
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Guard: on a store with the `app/[m]/` tree (AMB-2174), every route file sits where `marketProxy` serves it.
|
|
4
|
+
*
|
|
5
|
+
* WHY. `marketProxy` rewrites every page request to `/{market key}{path}` (`/products/x` → `/_/products/x`), so a
|
|
6
|
+
* page, route handler or metadata route anywhere else under `app/` is never reached: it 404s at the root and under
|
|
7
|
+
* every market prefix. The other way round, a URL in core's `OUTSIDE_MARKET_TREE` (the API, `.well-known`, a file
|
|
8
|
+
* such as `/llms.txt` or `/pinterest/feed.xml`, robots, sitemaps, the manifest) is never rewritten, so its route file
|
|
9
|
+
* must stay at the top of `app/`. Metadata images (`icon`, `apple-icon`, `opengraph-image`, `twitter-image`) live at the
|
|
10
|
+
* app root only. The rule is core's own `isOutsideMarketTree`, loaded from the installed `dist/lib/market.js`, so the
|
|
11
|
+
* gate and the proxy cannot drift.
|
|
12
|
+
*
|
|
13
|
+
* Active when the store has an `app/[m]/` folder or its proxy file exports `marketProxy`; then `app/[m]/layout.*`
|
|
14
|
+
* must exist and guard its key with `assertMarketKey`, and `next.config.*` must spread `marketTreeEnv()` into its
|
|
15
|
+
* `env` and return `marketFallbackRewrites()` in its `rewrites()` `afterFiles`, alone or spread anywhere in an array
|
|
16
|
+
* (else a missing file path, `/old.pdf`, 404s instead of answering its merchant redirect; a config writer such as the
|
|
17
|
+
* Shopify cloner can drop them). A store on the old tree runs `proxy` and passes untouched.
|
|
18
|
+
*
|
|
19
|
+
* Usage: `node check-market-routes.mjs` from the store root (or AMBORAS_STORE_ROOT). One FAIL line per problem with
|
|
20
|
+
* the move to make, exit 1; `[check-market-routes] EXIT_OK` as the last line otherwise.
|
|
21
|
+
*/
|
|
22
|
+
import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
|
|
23
|
+
import { dirname, join, relative, sep } from 'node:path'
|
|
24
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
25
|
+
// The sibling gate's comment stripper (inert on import: it runs its main() only as process.argv[1]).
|
|
26
|
+
import { stripComments } from './check-store-quirks.mjs'
|
|
27
|
+
|
|
28
|
+
const TAG = '[check-market-routes]'
|
|
29
|
+
const SCRIPT_EXT = '(?:tsx?|jsx?)'
|
|
30
|
+
const PAGE_RE = new RegExp(`^(?:page|route)\\.${SCRIPT_EXT}$`)
|
|
31
|
+
/** Metadata images: served from the app root only on the market tree (nested under `[m]` their URL doubles the prefix). */
|
|
32
|
+
const METADATA_IMAGE_RE = /^(?:icon|apple-icon|opengraph-image|twitter-image)\d*\..+$/
|
|
33
|
+
/** The other metadata routes and the URL Next serves each at. */
|
|
34
|
+
const METADATA_URL = { robots: 'robots.txt', manifest: 'manifest.webmanifest', sitemap: 'sitemap.xml' }
|
|
35
|
+
const METADATA_RE = /^(robots|manifest|sitemap)\..+$/
|
|
36
|
+
const LAYOUT_RE = new RegExp(`^layout\\.${SCRIPT_EXT}$`)
|
|
37
|
+
const PROXY_FILES = ['proxy.ts', 'proxy.js', 'src/proxy.ts']
|
|
38
|
+
|
|
39
|
+
/** True when the store is on the `app/[m]/` tree: the folder exists, or its proxy file exports `marketProxy`. */
|
|
40
|
+
export function isMarketTree(root) {
|
|
41
|
+
if (existsSync(join(root, 'app', '[m]'))) return true
|
|
42
|
+
return PROXY_FILES.some((file) => {
|
|
43
|
+
try {
|
|
44
|
+
return /\bmarketProxy\b/.test(readFileSync(join(root, file), 'utf8'))
|
|
45
|
+
} catch {
|
|
46
|
+
return false
|
|
47
|
+
}
|
|
48
|
+
})
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** What is wrong with `app/[m]/layout.*`, or null: it must exist and call `assertMarketKey`. */
|
|
52
|
+
export function layoutProblem(root) {
|
|
53
|
+
const dir = join(root, 'app', '[m]')
|
|
54
|
+
const layout = existsSync(dir) ? readdirSync(dir).find((name) => LAYOUT_RE.test(name)) : undefined
|
|
55
|
+
if (!layout) return 'app/[m]/layout.tsx is missing: it sets the market metadataBase and answers a bad key with assertMarketKey.'
|
|
56
|
+
// A call, not the name: the import line alone (or a call left in a comment) guards nothing.
|
|
57
|
+
if (!/\bassertMarketKey\s*\(/.test(stripComments(readFileSync(join(dir, layout), 'utf8')))) {
|
|
58
|
+
return `app/[m]/${layout} does not call assertMarketKey(m, notFound): a path no rewrite reaches (/api/missing.json) would render a page under any first segment.`
|
|
59
|
+
}
|
|
60
|
+
return null
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const NEXT_CONFIGS = ['next.config.mjs', 'next.config.js', 'next.config.ts', 'next.config.mts', 'next.config.cjs']
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The source of the `{ … }` (or the `[ … ]` with `open` `[`) that starts at or after `from`, by bracket count (strings
|
|
67
|
+
* and comments are not special).
|
|
68
|
+
*/
|
|
69
|
+
function blockFrom(src, from, open = '{') {
|
|
70
|
+
const close = open === '[' ? ']' : '}'
|
|
71
|
+
const start = src.indexOf(open, from)
|
|
72
|
+
if (start < 0) return ''
|
|
73
|
+
let depth = 0
|
|
74
|
+
for (let i = start; i < src.length; i++) {
|
|
75
|
+
if (src[i] === open) depth++
|
|
76
|
+
if (src[i] === close && --depth === 0) return src.slice(start, i + 1)
|
|
77
|
+
}
|
|
78
|
+
return src.slice(start)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Whether the `afterFiles` of a `rewrites()` body is `marketFallbackRewrites()` or an array that spreads it anywhere. */
|
|
82
|
+
function afterFilesHasFallback(body) {
|
|
83
|
+
const afterFiles = /\bafterFiles\s*:\s*/.exec(body)
|
|
84
|
+
if (!afterFiles) return false
|
|
85
|
+
const value = body.slice(afterFiles.index + afterFiles[0].length)
|
|
86
|
+
if (/^marketFallbackRewrites\s*\(/.test(value)) return true
|
|
87
|
+
return value.startsWith('[') && /\.\.\.\s*marketFallbackRewrites\s*\(/.test(blockFrom(value, 0, '['))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The first match of `re` (global) that is not on a `//` comment line, or null. */
|
|
91
|
+
function declaration(src, re) {
|
|
92
|
+
for (const match of src.matchAll(re)) {
|
|
93
|
+
const lineStart = src.lastIndexOf('\n', match.index) + 1
|
|
94
|
+
if (!src.slice(lineStart, match.index).includes('//')) return match
|
|
95
|
+
}
|
|
96
|
+
return null
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* What is wrong with the store's next.config, or null: its `env` must spread `marketTreeEnv()` (the opt-in of the
|
|
101
|
+
* market tree), its `rewrites()` must return `marketFallbackRewrites()` in `afterFiles` (after the public files and
|
|
102
|
+
* static routes, before `app/[m]`; alone or spread anywhere in an array).
|
|
103
|
+
*/
|
|
104
|
+
export function nextConfigProblem(root) {
|
|
105
|
+
const file = NEXT_CONFIGS.find((name) => existsSync(join(root, name)))
|
|
106
|
+
if (!file) return `no next.config (${NEXT_CONFIGS.join(', ')}): it must set env: { ...marketTreeEnv() } and rewrites() afterFiles: marketFallbackRewrites().`
|
|
107
|
+
const src = readFileSync(join(root, file), 'utf8')
|
|
108
|
+
// The declarations themselves (`env: {`, `rewrites() {`, `rewrites: async () =>`), never a comment that names them.
|
|
109
|
+
const env = declaration(src, /\benv\s*:\s*\{/g)
|
|
110
|
+
if (!env || !/\.\.\.\s*marketTreeEnv\s*\(\s*\)/.test(blockFrom(src, env.index))) {
|
|
111
|
+
return `${file} does not spread marketTreeEnv() into its env: the market tree's static pages would read cookies on every store read and render per request.`
|
|
112
|
+
}
|
|
113
|
+
const rewrites = declaration(src, /\brewrites\s*(?:\(\s*\)\s*\{|:\s*(?:async\s*)?(?:\(\s*\)\s*=>|function\s*\())/g)
|
|
114
|
+
if (!rewrites || !afterFilesHasFallback(blockFrom(src, rewrites.index))) {
|
|
115
|
+
return `${file} does not return marketFallbackRewrites() in its rewrites() afterFiles: a missing file path (/old.pdf) would 404 instead of answering its merchant redirect.`
|
|
116
|
+
}
|
|
117
|
+
return null
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function walk(dir) {
|
|
121
|
+
return readdirSync(dir, { withFileTypes: true }).flatMap((d) => (d.isDirectory() ? walk(join(dir, d.name)) : [join(dir, d.name)]))
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The URL a route file serves, from its segments under `app/` (groups and `[m]` already dropped). */
|
|
125
|
+
function urlOf(dirs, name) {
|
|
126
|
+
const metadata = METADATA_RE.exec(name)?.[1]
|
|
127
|
+
return `/${[...dirs, ...(metadata ? [METADATA_URL[metadata]] : [])].join('/')}`
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Misplaced route files of `root` as `{ file, move, reason }` (store-relative, `/`-separated). `isOutside` is core's
|
|
132
|
+
* `isOutsideMarketTree`. Files in private folders (`_x`) are not routes; route groups (`(x)`) are not in the URL.
|
|
133
|
+
*/
|
|
134
|
+
export function findMarketRouteViolations(root, isOutside) {
|
|
135
|
+
const appDir = join(root, 'app')
|
|
136
|
+
if (!existsSync(appDir)) return []
|
|
137
|
+
const found = []
|
|
138
|
+
for (const file of walk(appDir).map((f) => relative(root, f).split(sep).join('/')).sort()) {
|
|
139
|
+
const segments = file.split('/').slice(1)
|
|
140
|
+
const name = segments.pop()
|
|
141
|
+
if (segments.some((s) => s.startsWith('_'))) continue
|
|
142
|
+
const isImage = METADATA_IMAGE_RE.test(name)
|
|
143
|
+
if (!isImage && !PAGE_RE.test(name) && !METADATA_RE.test(name)) continue
|
|
144
|
+
const dirs = segments.filter((s) => !/^\(.*\)$/.test(s))
|
|
145
|
+
const inTree = dirs[0] === '[m]'
|
|
146
|
+
const urlDirs = inTree ? dirs.slice(1) : dirs
|
|
147
|
+
const raw = segments.filter((s) => s !== '[m]')
|
|
148
|
+
const top = `app/${[...raw, name].join('/')}`
|
|
149
|
+
if (isImage) {
|
|
150
|
+
if (dirs.length) found.push({ file, move: `app/${name}`, reason: 'a metadata image is served from the app root only' })
|
|
151
|
+
continue
|
|
152
|
+
}
|
|
153
|
+
const outside = isOutside(PAGE_RE.test(name) ? `/${urlDirs.join('/')}` : urlOf(urlDirs, name))
|
|
154
|
+
if (outside && inTree) found.push({ file, move: top, reason: 'its URL is outside app/[m]/ (OUTSIDE_MARKET_TREE), marketProxy never rewrites it' })
|
|
155
|
+
if (!outside && !inTree) found.push({ file, move: `app/[m]/${[...raw, name].join('/')}`, reason: 'a route outside app/[m]/ is never served by marketProxy' })
|
|
156
|
+
}
|
|
157
|
+
return found
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function main() {
|
|
161
|
+
const root = process.env.AMBORAS_STORE_ROOT ?? process.cwd()
|
|
162
|
+
if (!isMarketTree(root)) {
|
|
163
|
+
console.log(`${TAG} OK: no app/[m]/ and no marketProxy, the store is on the old route tree (proxy), nothing to check.`)
|
|
164
|
+
console.log(`${TAG} EXIT_OK`)
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
// core's own rule, from the installed build (the same code the proxy runs).
|
|
168
|
+
const coreMarket = pathToFileURL(join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'dist', 'lib', 'market.js')).href
|
|
169
|
+
const { isOutsideMarketTree } = await import(coreMarket)
|
|
170
|
+
const problems = [
|
|
171
|
+
...[layoutProblem(root), nextConfigProblem(root)].filter(Boolean),
|
|
172
|
+
...findMarketRouteViolations(root, isOutsideMarketTree).map(({ file, move, reason }) => `${file} → ${move} (${reason})`),
|
|
173
|
+
]
|
|
174
|
+
if (problems.length) {
|
|
175
|
+
for (const problem of problems) console.error(`${TAG} FAIL: ${problem}`)
|
|
176
|
+
process.exit(1)
|
|
177
|
+
}
|
|
178
|
+
console.log(`${TAG} OK: every route file is where marketProxy serves it, and app/[m]/layout guards its key.`)
|
|
179
|
+
console.log(`${TAG} EXIT_OK`)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
|
|
183
|
+
main().catch((err) => {
|
|
184
|
+
console.error(`${TAG} FAIL: check crashed — ${err?.message ?? err}`)
|
|
185
|
+
process.exit(1)
|
|
186
|
+
})
|
|
187
|
+
}
|
|
@@ -19,12 +19,16 @@
|
|
|
19
19
|
* The same holds for the catch-all `app/[...slug]/page.tsx` (a merchant URL redirect for any path):
|
|
20
20
|
* a `loading.tsx` next to it would turn its 308 into a 200 with a client redirect.
|
|
21
21
|
*
|
|
22
|
+
* On the `app/[m]/` tree (AMB-2174) the same folders sit under `app/[m]/`, and a `loading.tsx` in `app/[m]/` itself
|
|
23
|
+
* wraps every one of them, so it fails too.
|
|
24
|
+
*
|
|
22
25
|
* Usage: `node scripts/check-redirect-boundaries.mjs [storefrontRoot]`.
|
|
23
26
|
* Exit 1 with the offending paths, exit 0 otherwise.
|
|
24
27
|
*/
|
|
25
28
|
import { existsSync, readFileSync } from 'node:fs'
|
|
26
29
|
import { join, resolve } from 'node:path'
|
|
27
30
|
import { fileURLToPath } from 'node:url'
|
|
31
|
+
import { isMarketTree } from './check-market-routes.mjs'
|
|
28
32
|
|
|
29
33
|
// app/pages: a metaobject entry's web page (app/pages/[handle]/[entry]) 308s to a merchant URL redirect when
|
|
30
34
|
// the entry is gone, so a loading.tsx in either parent would turn that into a 200 (content module).
|
|
@@ -36,10 +40,13 @@ export const CORE_BLOG_DIRS = ['app/blogs', 'app/blogs/[blog]']
|
|
|
36
40
|
const CORE_BLOG_MARKER = '@/lib/store-blog'
|
|
37
41
|
const LOADING_FILES = ['loading.tsx', 'loading.ts', 'loading.jsx', 'loading.js']
|
|
38
42
|
|
|
43
|
+
/** `app/x` → `app/[m]/x` on the market tree. */
|
|
44
|
+
const inTree = (root, dir) => (isMarketTree(root) ? dir.replace(/^app\//, 'app/[m]/') : dir)
|
|
45
|
+
|
|
39
46
|
function hasCoreBlogPages(root) {
|
|
40
47
|
return ['app/blogs/[blog]/page.tsx', 'app/blogs/[blog]/[article]/page.tsx'].some((file) => {
|
|
41
48
|
try {
|
|
42
|
-
return readFileSync(join(root, file), 'utf8').includes(CORE_BLOG_MARKER)
|
|
49
|
+
return readFileSync(join(root, inTree(root, file)), 'utf8').includes(CORE_BLOG_MARKER)
|
|
43
50
|
} catch {
|
|
44
51
|
return false
|
|
45
52
|
}
|
|
@@ -49,7 +56,8 @@ function hasCoreBlogPages(root) {
|
|
|
49
56
|
/** Offending files (relative paths) under `root`. */
|
|
50
57
|
export function findRedirectBoundaryViolations(root) {
|
|
51
58
|
const found = []
|
|
52
|
-
|
|
59
|
+
const dirs = (hasCoreBlogPages(root) ? [...GUARDED_DIRS, ...CORE_BLOG_DIRS] : GUARDED_DIRS).map((dir) => inTree(root, dir))
|
|
60
|
+
for (const dir of isMarketTree(root) ? ['app/[m]', ...dirs] : dirs) {
|
|
53
61
|
for (const file of LOADING_FILES) {
|
|
54
62
|
if (existsSync(join(root, dir, file))) found.push(`${dir}/${file}`)
|
|
55
63
|
}
|
package/core-manifest.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$comment": "Generated by scripts/build-manifest.mjs. Paths are relative to the storefront app root.",
|
|
3
3
|
"package": "@amboras-dev/storefront-core",
|
|
4
|
-
"version": "2026.11.
|
|
4
|
+
"version": "2026.11.12",
|
|
5
5
|
"shims": [
|
|
6
6
|
{
|
|
7
7
|
"path": "hooks/use-auth.ts",
|
|
@@ -383,6 +383,11 @@
|
|
|
383
383
|
"import": "@amboras-dev/storefront-core/lib/logger",
|
|
384
384
|
"kind": "reexport"
|
|
385
385
|
},
|
|
386
|
+
{
|
|
387
|
+
"path": "lib/market.ts",
|
|
388
|
+
"import": "@amboras-dev/storefront-core/lib/market",
|
|
389
|
+
"kind": "reexport"
|
|
390
|
+
},
|
|
386
391
|
{
|
|
387
392
|
"path": "lib/medusa-client.ts",
|
|
388
393
|
"import": "@amboras-dev/storefront-core/lib/medusa-client",
|
|
@@ -50,8 +50,11 @@ export interface HostedCheckoutEnv {
|
|
|
50
50
|
preview?: boolean;
|
|
51
51
|
}
|
|
52
52
|
export declare function hostedCheckoutEnv(): HostedCheckoutEnv;
|
|
53
|
-
/**
|
|
54
|
-
|
|
53
|
+
/**
|
|
54
|
+
* The rewrite to the hosted checkout, or null to let the store serve /checkout itself. `requestHeaders` are the
|
|
55
|
+
* headers forwarded to the checkout app (the proxy's, with the client's `x-amb-market` already replaced).
|
|
56
|
+
*/
|
|
57
|
+
export declare function hostedCheckout(req: NextRequest, env?: HostedCheckoutEnv, now?: number, requestHeaders?: Headers): Promise<NextResponse | null>;
|
|
55
58
|
/** True for a rewrite to the hosted app: its own security headers must reach the browser untouched. */
|
|
56
59
|
export declare function isHostedCheckoutResponse(res: Response): boolean;
|
|
57
60
|
/** Test seam: forget the cached health document. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hosted-checkout.d.ts","sourceRoot":"","sources":["../../src/edge/hosted-checkout.ts"],"names":[],"mappings":"AAAA,OAAO,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aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,OAAO,CAAC,EAAE,OAAO,CAAA;CAClB;AAED,wBAAgB,iBAAiB,IAAI,iBAAiB,CAarD;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,WAAW,EAChB,GAAG,GAAE,iBAAuC,EAC5C,GAAG,GAAE,MAAmB,EACxB,cAAc,GAAE,OAAqB,GACpC,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAqC9B;AAID,uGAAuG;AACvG,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAE/D;AAED,oDAAoD;AACpD,wBAAgB,yBAAyB,SAExC"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { NextResponse } from 'next/server';
|
|
2
|
+
import { requestHostOf } from '../lib/site-url.js';
|
|
3
|
+
import { edgeStoreEnv } from './url-map.js';
|
|
2
4
|
/**
|
|
3
5
|
* Hosted checkout: /checkout on the store's own domain is served by the platform's checkout app
|
|
4
6
|
* (amboras-checkout) through a rewrite, so the shopper never leaves the store's origin.
|
|
@@ -69,9 +71,7 @@ export function hostedCheckoutEnv() {
|
|
|
69
71
|
checkoutKey: process.env.AMBORAS_CHECKOUT_KEY,
|
|
70
72
|
checkoutKeyId: process.env.AMBORAS_CHECKOUT_KEY_ID,
|
|
71
73
|
healthUrl: process.env.AMBORAS_CHECKOUT_HEALTH_URL,
|
|
72
|
-
|
|
73
|
-
medusaUrl: process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL,
|
|
74
|
-
publishableKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
|
|
74
|
+
...edgeStoreEnv(),
|
|
75
75
|
analyticsEndpoint: process.env.NEXT_PUBLIC_ANALYTICS_ENDPOINT,
|
|
76
76
|
analyticsIngestUrl: process.env.NEXT_PUBLIC_ANALYTICS_INGEST_URL,
|
|
77
77
|
analyticsKey: process.env.NEXT_PUBLIC_ANALYTICS_KEY,
|
|
@@ -79,8 +79,11 @@ export function hostedCheckoutEnv() {
|
|
|
79
79
|
preview: process.env.VERCEL_ENV !== undefined && process.env.VERCEL_ENV !== 'production',
|
|
80
80
|
};
|
|
81
81
|
}
|
|
82
|
-
/**
|
|
83
|
-
|
|
82
|
+
/**
|
|
83
|
+
* The rewrite to the hosted checkout, or null to let the store serve /checkout itself. `requestHeaders` are the
|
|
84
|
+
* headers forwarded to the checkout app (the proxy's, with the client's `x-amb-market` already replaced).
|
|
85
|
+
*/
|
|
86
|
+
export async function hostedCheckout(req, env = hostedCheckoutEnv(), now = Date.now(), requestHeaders = req.headers) {
|
|
84
87
|
const { pathname: requested, search } = req.nextUrl;
|
|
85
88
|
const pathname = requested === STORE_PAYMENT_RELAY_PATH ? HOSTED_PAYMENT_RELAY_PATH : requested;
|
|
86
89
|
if (!isCheckoutPath(pathname))
|
|
@@ -95,7 +98,8 @@ export async function hostedCheckout(req, env = hostedCheckoutEnv(), now = Date.
|
|
|
95
98
|
const from = req.headers.get('next-url');
|
|
96
99
|
if (from !== null && !isCheckoutPath(from.split('?')[0]))
|
|
97
100
|
return new NextResponse(null, { status: 204, headers: { 'cache-control': 'no-store', vary: 'rsc' } });
|
|
98
|
-
|
|
101
|
+
// The shopper-facing host the checkout links back to, port included (`localhost:3000` in development).
|
|
102
|
+
const host = requestHostOf(req.headers, { port: true }) ?? req.nextUrl.host;
|
|
99
103
|
const ip = req.headers.get('x-real-ip') ?? req.headers.get('x-forwarded-for')?.split(',')[0]?.trim();
|
|
100
104
|
const payload = {
|
|
101
105
|
v: 1,
|
|
@@ -112,7 +116,7 @@ export async function hostedCheckout(req, env = hostedCheckoutEnv(), now = Date.
|
|
|
112
116
|
...(env.analyticsKey ? { ak: env.analyticsKey } : {}),
|
|
113
117
|
...(env.googleMapsApiKey ? { g: env.googleMapsApiKey } : {}),
|
|
114
118
|
};
|
|
115
|
-
const headers = new Headers(
|
|
119
|
+
const headers = new Headers(requestHeaders);
|
|
116
120
|
headers.set(STORE_TOKEN_HEADER, await signStoreToken(checkoutKey, payload));
|
|
117
121
|
const target = new URL(`${pathname}${search}`, checkoutUrl);
|
|
118
122
|
const res = NextResponse.rewrite(target, { request: { headers } });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hosted-checkout.js","sourceRoot":"","sources":["../../src/edge/hosted-checkout.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAoB,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"hosted-checkout.js","sourceRoot":"","sources":["../../src/edge/hosted-checkout.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAoB,MAAM,aAAa,CAAA;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAE3C;;;;;;;;;GASG;AAEH,MAAM,CAAC,MAAM,kBAAkB,GAAG,iBAAiB,CAAA;AAoBnD,MAAM,GAAG,GAAG,IAAI,WAAW,EAAE,CAAA;AAE7B,SAAS,MAAM,CAAC,KAAiB;IAC/B,IAAI,CAAC,GAAG,EAAE,CAAA;IACV,KAAK,MAAM,CAAC,IAAI,KAAK;QAAE,CAAC,IAAI,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAA;IAClD,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,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AO,EAAE,EAAE,OAAO,EAAE,EAAE,CAAC,CAAA;IAClE,eAAe,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;IACxB,OAAO,GAAG,CAAA;AACZ,CAAC;AAED,MAAM,eAAe,GAAG,IAAI,OAAO,EAAY,CAAA;AAE/C,uGAAuG;AACvG,MAAM,UAAU,wBAAwB,CAAC,GAAa;IACpD,OAAO,eAAe,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;AACjC,CAAC;AAED,oDAAoD;AACpD,MAAM,UAAU,yBAAyB;IACvC,WAAW,GAAG,IAAI,CAAA;AACpB,CAAC"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { UrlMapCopy } from './url-map.js';
|
|
2
|
+
/**
|
|
3
|
+
* Which market a request URL names (AMB-2174). Pure: no I/O, the same answer for a crawler and a human.
|
|
4
|
+
*
|
|
5
|
+
* First match wins:
|
|
6
|
+
* 1. the host is a subdomain or domain presence: active → that market; inactive → its `inactiveRedirect` to the
|
|
7
|
+
* primary, else the root; pending → the root (`domain_pending`);
|
|
8
|
+
* 2. on the primary host, the first path segment is a subfolder presence's `path`: active → that market (a
|
|
9
|
+
* `/checkout*` inner path → 302 to the root checkout); inactive → its `inactiveRedirect` to the root, else the root;
|
|
10
|
+
* 2a. a previous path (`previousPaths`) → 301 to the current URL; 2b. a former default language's path
|
|
11
|
+
* (`languagePaths`) → 301 to the current URL; either only while that URL is announced (active and turned on),
|
|
12
|
+
* else a 302 to the root (`unserved`: a pending host, an inactive market or a passive URL is no place to move
|
|
13
|
+
* an indexed link to for good);
|
|
14
|
+
* 3. anything else → the root, today's behaviour.
|
|
15
|
+
*
|
|
16
|
+
* An inactive presence redirects as Medusa says (`inactiveRedirect`: `temporary` 302, null none; it can always come
|
|
17
|
+
* back), a moved URL 301s; the proxy sends
|
|
18
|
+
* every one with `no-store`, so a browser never replays an old one after a suffix is reverted. Redirect targets are
|
|
19
|
+
* built on a map origin (a presence host or the primary), never resolved against the request, so none can become an
|
|
20
|
+
* open redirect.
|
|
21
|
+
*/
|
|
22
|
+
export interface MarketResolution {
|
|
23
|
+
source: 'host' | 'subfolder' | 'root';
|
|
24
|
+
/** null on the root. */
|
|
25
|
+
marketId: string | null;
|
|
26
|
+
/** '/en-ca' on a subfolder, '' otherwise. */
|
|
27
|
+
publicPrefix: string;
|
|
28
|
+
/** The `[m]` segment: '_' root, 'en-ca' subfolder, '_<marketId>' subdomain or domain. */
|
|
29
|
+
internalKey: string;
|
|
30
|
+
/** The path without publicPrefix. */
|
|
31
|
+
innerPath: string;
|
|
32
|
+
redirect?: {
|
|
33
|
+
location: URL;
|
|
34
|
+
status: 301 | 302;
|
|
35
|
+
kind: 'previous_path' | 'language' | 'unserved' | 'inactive' | 'root_checkout';
|
|
36
|
+
};
|
|
37
|
+
fallback?: 'map_stale' | 'map_unavailable' | 'domain_pending';
|
|
38
|
+
}
|
|
39
|
+
/** The root: today's behaviour, no market. */
|
|
40
|
+
export declare function rootResolution(url: URL): MarketResolution;
|
|
41
|
+
/** `options.subfolders: false` resolves hosts only (the `proxy` export, for a store tree without `app/[m]/`). */
|
|
42
|
+
export declare function resolveMarket(url: URL, host: string, map: UrlMapCopy | null, primaryHost: string | null, { subfolders: withSubfolders }?: {
|
|
43
|
+
subfolders?: boolean;
|
|
44
|
+
}): MarketResolution;
|
|
45
|
+
//# sourceMappingURL=market.d.ts.map
|