@reblu/site-next 1.13.0 → 1.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.
@@ -0,0 +1,106 @@
1
+ import { ShopProductsParams, ListResult, RebluClient } from '@reblu/site-client';
2
+ import { ShopProductListItem, ShopFacets } from '@reblu/site-contracts';
3
+
4
+ /**
5
+ * Parse a `URLSearchParams` (or anything with that shape — `ReadonlyURLSearchParams`
6
+ * from `next/navigation`, or a plain `new URLSearchParams(record)`) into
7
+ * `ShopProductsParams`. Hostile/unknown params are dropped: only the known
8
+ * scalar keys and the two bracket groups are ever read.
9
+ */
10
+ declare function parseShopSearchParams(searchParams: URLSearchParams): ShopProductsParams;
11
+ /**
12
+ * Serialize `ShopProductsParams` into a `URLSearchParams` — the inverse of
13
+ * {@link parseShopSearchParams}. Falsy/empty/undefined fields are omitted, so
14
+ * `parseShopSearchParams(serializeShopParams(params))` round-trips to `params`
15
+ * for any already-canonical (non-empty-string, in-range) input — that is the
16
+ * property the round-trip tests pin.
17
+ */
18
+ declare function serializeShopParams(params: ShopProductsParams): URLSearchParams;
19
+ /**
20
+ * Convert Next's `searchParams` route prop —
21
+ * `Record<string, string | string[] | undefined>`, already URL-decoded, with
22
+ * a repeated query key grouped into an array — into a `URLSearchParams` for
23
+ * {@link parseShopSearchParams}.
24
+ *
25
+ * NOT the same as `new URLSearchParams(searchParams)`: the native
26
+ * `URLSearchParams` constructor only accepts `Record<string, string>` —
27
+ * handed an array value (`{ 'attr[color]': ['red', 'blue'] }`), it calls
28
+ * `String()` on it, producing ONE entry `attr[color]=red,blue` instead of two
29
+ * repeated `attr[color]=red` / `attr[color]=blue` entries. That silently
30
+ * breaks `parseShopSearchParams`'s repeat-count-based array/scalar
31
+ * distinction (see its own module doc) for every multi-value `attr[<key>]`
32
+ * filter — this helper is what actually preserves the repeat.
33
+ */
34
+ declare function toURLSearchParams(searchParams: Record<string, string | string[] | undefined>): URLSearchParams;
35
+ /**
36
+ * The navigation seam `@reblu/site-blocks`'s `ShopFilters` calls `hrefs` — kept
37
+ * structurally identical to its `ShopFiltersHrefs` type WITHOUT a package
38
+ * dependency on `@reblu/site-blocks` (this package has none today, and this
39
+ * one shape does not warrant adding one). Any object matching this shape is
40
+ * assignable to `ShopFiltersHrefs` by structural typing.
41
+ */
42
+ interface ShopFilterHrefs {
43
+ taxonomy: (axisKey: string, value: string | undefined) => string;
44
+ attr: (fieldKey: string, value: string) => string;
45
+ price: (min: number | undefined, max: number | undefined) => string;
46
+ onSale: (nextActive: boolean) => string;
47
+ clearAll: () => string;
48
+ }
49
+ /**
50
+ * Build `ShopFilters`' href set from the CURRENT params and pathname. Every
51
+ * href preserves every OTHER current param (category, q, sort, every other
52
+ * taxonomy/attr filter) and resets pagination (`page`) — a filter change is
53
+ * never silently stuck on page 4 of a now-smaller result set.
54
+ *
55
+ * Pure and framework-agnostic (no `next/navigation`): a Server Component calls
56
+ * it directly with its own `searchParams` prop and route pathname — no
57
+ * `'use client'` boundary required. See `./use-shop-filter-links` for the
58
+ * client-side hook that wraps this with `usePathname`/`useSearchParams`.
59
+ */
60
+ declare function buildShopFilterHrefs(current: ShopProductsParams, pathname: string): ShopFilterHrefs;
61
+
62
+ /**
63
+ * `getShopCollection` (REB-809) — fetches the product list AND its facets with
64
+ * the EXACT SAME params in one call. This is the seam that keeps a shop
65
+ * collection page correct: facet counts must reflect the same filter context
66
+ * the product list is showing, and a hand-rolled page that calls
67
+ * `client.shop.products(params)` and `client.shop.facets(someOtherParams)`
68
+ * separately is exactly how they drift apart.
69
+ *
70
+ * Server-safe (no `'use client'`, no React) — call it directly from an async
71
+ * Server Component (route `page.tsx`) with the params parsed via
72
+ * {@link parseShopSearchParams} from that page's `searchParams` prop.
73
+ */
74
+ interface ShopCollection {
75
+ products: ListResult<ShopProductListItem>;
76
+ facets: ShopFacets;
77
+ /**
78
+ * R3-002: `'ok'` when `client.shop.facets(...)` actually succeeded;
79
+ * `'unavailable'` when it failed and `facets` above is the degraded
80
+ * {@link EMPTY_FACETS} fallback. NOT silent — check this before treating an
81
+ * empty `facets` as "this tenant configured no filterable axes" when it may
82
+ * really mean "the facets endpoint is down right now". A logged
83
+ * `console.warn` (see below) covers the case nobody checks this field.
84
+ */
85
+ facetsStatus: 'ok' | 'unavailable';
86
+ }
87
+ /**
88
+ * R4-facets-failure-takes-down-listing: `products` and `facets` are NOT
89
+ * equally critical. A product listing with no products is not a listing —
90
+ * that failure must propagate so the caller's own error handling (or a
91
+ * thrown-away `try/catch` degrading the whole page) sees it. A product
92
+ * listing with no FACETS is still a perfectly good listing, just without
93
+ * filter UI — degrading `facets` to {@link EMPTY_FACETS} on failure, instead
94
+ * of letting one upstream endpoint's outage take the other down too, is what
95
+ * `Promise.allSettled` (rather than `Promise.all`) buys here.
96
+ *
97
+ * R3-002: that degradation must not be SILENT. `console.warn`, bracket-tagged
98
+ * `[getShopCollection]` — the same convention `@reblu/site-next` already uses
99
+ * elsewhere (`route-handlers.ts`'s `[createProxyRoute]`,
100
+ * `set-password.tsx`'s `[SetPassword]`) — fires once per failed call, and the
101
+ * returned `facetsStatus: 'unavailable'` lets a caller that wants to act on
102
+ * it (retry, surface a banner, alert) do so without parsing a log line.
103
+ */
104
+ declare function getShopCollection(client: RebluClient, params?: ShopProductsParams): Promise<ShopCollection>;
105
+
106
+ export { type ShopFilterHrefs as S, type ShopCollection as a, buildShopFilterHrefs as b, getShopCollection as g, parseShopSearchParams as p, serializeShopParams as s, toURLSearchParams as t };
@@ -0,0 +1,106 @@
1
+ import { ShopProductsParams, ListResult, RebluClient } from '@reblu/site-client';
2
+ import { ShopProductListItem, ShopFacets } from '@reblu/site-contracts';
3
+
4
+ /**
5
+ * Parse a `URLSearchParams` (or anything with that shape — `ReadonlyURLSearchParams`
6
+ * from `next/navigation`, or a plain `new URLSearchParams(record)`) into
7
+ * `ShopProductsParams`. Hostile/unknown params are dropped: only the known
8
+ * scalar keys and the two bracket groups are ever read.
9
+ */
10
+ declare function parseShopSearchParams(searchParams: URLSearchParams): ShopProductsParams;
11
+ /**
12
+ * Serialize `ShopProductsParams` into a `URLSearchParams` — the inverse of
13
+ * {@link parseShopSearchParams}. Falsy/empty/undefined fields are omitted, so
14
+ * `parseShopSearchParams(serializeShopParams(params))` round-trips to `params`
15
+ * for any already-canonical (non-empty-string, in-range) input — that is the
16
+ * property the round-trip tests pin.
17
+ */
18
+ declare function serializeShopParams(params: ShopProductsParams): URLSearchParams;
19
+ /**
20
+ * Convert Next's `searchParams` route prop —
21
+ * `Record<string, string | string[] | undefined>`, already URL-decoded, with
22
+ * a repeated query key grouped into an array — into a `URLSearchParams` for
23
+ * {@link parseShopSearchParams}.
24
+ *
25
+ * NOT the same as `new URLSearchParams(searchParams)`: the native
26
+ * `URLSearchParams` constructor only accepts `Record<string, string>` —
27
+ * handed an array value (`{ 'attr[color]': ['red', 'blue'] }`), it calls
28
+ * `String()` on it, producing ONE entry `attr[color]=red,blue` instead of two
29
+ * repeated `attr[color]=red` / `attr[color]=blue` entries. That silently
30
+ * breaks `parseShopSearchParams`'s repeat-count-based array/scalar
31
+ * distinction (see its own module doc) for every multi-value `attr[<key>]`
32
+ * filter — this helper is what actually preserves the repeat.
33
+ */
34
+ declare function toURLSearchParams(searchParams: Record<string, string | string[] | undefined>): URLSearchParams;
35
+ /**
36
+ * The navigation seam `@reblu/site-blocks`'s `ShopFilters` calls `hrefs` — kept
37
+ * structurally identical to its `ShopFiltersHrefs` type WITHOUT a package
38
+ * dependency on `@reblu/site-blocks` (this package has none today, and this
39
+ * one shape does not warrant adding one). Any object matching this shape is
40
+ * assignable to `ShopFiltersHrefs` by structural typing.
41
+ */
42
+ interface ShopFilterHrefs {
43
+ taxonomy: (axisKey: string, value: string | undefined) => string;
44
+ attr: (fieldKey: string, value: string) => string;
45
+ price: (min: number | undefined, max: number | undefined) => string;
46
+ onSale: (nextActive: boolean) => string;
47
+ clearAll: () => string;
48
+ }
49
+ /**
50
+ * Build `ShopFilters`' href set from the CURRENT params and pathname. Every
51
+ * href preserves every OTHER current param (category, q, sort, every other
52
+ * taxonomy/attr filter) and resets pagination (`page`) — a filter change is
53
+ * never silently stuck on page 4 of a now-smaller result set.
54
+ *
55
+ * Pure and framework-agnostic (no `next/navigation`): a Server Component calls
56
+ * it directly with its own `searchParams` prop and route pathname — no
57
+ * `'use client'` boundary required. See `./use-shop-filter-links` for the
58
+ * client-side hook that wraps this with `usePathname`/`useSearchParams`.
59
+ */
60
+ declare function buildShopFilterHrefs(current: ShopProductsParams, pathname: string): ShopFilterHrefs;
61
+
62
+ /**
63
+ * `getShopCollection` (REB-809) — fetches the product list AND its facets with
64
+ * the EXACT SAME params in one call. This is the seam that keeps a shop
65
+ * collection page correct: facet counts must reflect the same filter context
66
+ * the product list is showing, and a hand-rolled page that calls
67
+ * `client.shop.products(params)` and `client.shop.facets(someOtherParams)`
68
+ * separately is exactly how they drift apart.
69
+ *
70
+ * Server-safe (no `'use client'`, no React) — call it directly from an async
71
+ * Server Component (route `page.tsx`) with the params parsed via
72
+ * {@link parseShopSearchParams} from that page's `searchParams` prop.
73
+ */
74
+ interface ShopCollection {
75
+ products: ListResult<ShopProductListItem>;
76
+ facets: ShopFacets;
77
+ /**
78
+ * R3-002: `'ok'` when `client.shop.facets(...)` actually succeeded;
79
+ * `'unavailable'` when it failed and `facets` above is the degraded
80
+ * {@link EMPTY_FACETS} fallback. NOT silent — check this before treating an
81
+ * empty `facets` as "this tenant configured no filterable axes" when it may
82
+ * really mean "the facets endpoint is down right now". A logged
83
+ * `console.warn` (see below) covers the case nobody checks this field.
84
+ */
85
+ facetsStatus: 'ok' | 'unavailable';
86
+ }
87
+ /**
88
+ * R4-facets-failure-takes-down-listing: `products` and `facets` are NOT
89
+ * equally critical. A product listing with no products is not a listing —
90
+ * that failure must propagate so the caller's own error handling (or a
91
+ * thrown-away `try/catch` degrading the whole page) sees it. A product
92
+ * listing with no FACETS is still a perfectly good listing, just without
93
+ * filter UI — degrading `facets` to {@link EMPTY_FACETS} on failure, instead
94
+ * of letting one upstream endpoint's outage take the other down too, is what
95
+ * `Promise.allSettled` (rather than `Promise.all`) buys here.
96
+ *
97
+ * R3-002: that degradation must not be SILENT. `console.warn`, bracket-tagged
98
+ * `[getShopCollection]` — the same convention `@reblu/site-next` already uses
99
+ * elsewhere (`route-handlers.ts`'s `[createProxyRoute]`,
100
+ * `set-password.tsx`'s `[SetPassword]`) — fires once per failed call, and the
101
+ * returned `facetsStatus: 'unavailable'` lets a caller that wants to act on
102
+ * it (retry, surface a banner, alert) do so without parsing a log line.
103
+ */
104
+ declare function getShopCollection(client: RebluClient, params?: ShopProductsParams): Promise<ShopCollection>;
105
+
106
+ export { type ShopFilterHrefs as S, type ShopCollection as a, buildShopFilterHrefs as b, getShopCollection as g, parseShopSearchParams as p, serializeShopParams as s, toURLSearchParams as t };
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/shop/route-handlers.ts
21
+ var route_handlers_exports = {};
22
+ __export(route_handlers_exports, {
23
+ createShopApplyDiscountRoute: () => createShopApplyDiscountRoute,
24
+ createShopCheckEmailRoute: () => createShopCheckEmailRoute,
25
+ createShopCheckoutRoute: () => createShopCheckoutRoute,
26
+ createShopOrderRoute: () => createShopOrderRoute,
27
+ createShopValidateCartRoute: () => createShopValidateCartRoute
28
+ });
29
+ module.exports = __toCommonJS(route_handlers_exports);
30
+
31
+ // src/route-handlers.ts
32
+ function jsonErrorResponse(status, error, message) {
33
+ return new Response(
34
+ JSON.stringify({ error, message, correlation_id: crypto.randomUUID() }),
35
+ { status, headers: { "Content-Type": "application/json; charset=utf-8" } }
36
+ );
37
+ }
38
+ function createProxyRoute(targetPath, opts = {}) {
39
+ const {
40
+ method = "POST",
41
+ forwardSetCookie = false,
42
+ requireJson = false,
43
+ invalidRequestMessage = "Solicitud no v\xE1lida",
44
+ timeoutMs = 8e3,
45
+ configurationErrorMessage = "Error de configuraci\xF3n del servidor.",
46
+ timeoutMessage = "La solicitud ha superado el tiempo de espera.",
47
+ proxyErrorMessage = "Error de conexi\xF3n con el servidor."
48
+ } = opts;
49
+ return async function handler(request) {
50
+ if (requireJson) {
51
+ const contentType = request.headers.get("content-type") ?? "";
52
+ if (!contentType.includes("application/json")) {
53
+ return jsonErrorResponse(400, "invalid_request", invalidRequestMessage);
54
+ }
55
+ }
56
+ const baseUrl = opts.baseUrl ?? process.env.REBLU_API_BASE_URL ?? "";
57
+ const apiKey = opts.apiKey ?? process.env.REBLU_API_KEY ?? "";
58
+ if (!baseUrl || !apiKey) {
59
+ console.error(
60
+ `[createProxyRoute] Missing configuration for ${targetPath}: ` + `${!baseUrl ? "baseUrl/REBLU_API_BASE_URL " : ""}${!apiKey ? "apiKey/REBLU_API_KEY" : ""}`.trim()
61
+ );
62
+ return jsonErrorResponse(500, "missing_configuration", configurationErrorMessage);
63
+ }
64
+ const forwardedHeaders = {};
65
+ const ua = request.headers.get("user-agent");
66
+ if (ua) forwardedHeaders["user-agent"] = ua;
67
+ const xff = request.headers.get("x-forwarded-for");
68
+ if (xff) forwardedHeaders["x-forwarded-for"] = xff;
69
+ const xri = request.headers.get("x-real-ip");
70
+ if (xri) forwardedHeaders["x-real-ip"] = xri;
71
+ const upperMethod = method.toUpperCase();
72
+ const body = upperMethod === "GET" || upperMethod === "HEAD" ? void 0 : await request.text();
73
+ const search = request.nextUrl?.search ?? "";
74
+ const controller = new AbortController();
75
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
76
+ try {
77
+ const res = await fetch(`${baseUrl}${targetPath}${search}`, {
78
+ method,
79
+ headers: {
80
+ "Content-Type": "application/json",
81
+ "X-Reblu-Api-Key": apiKey,
82
+ ...forwardedHeaders
83
+ },
84
+ ...body ? { body } : {},
85
+ cache: "no-store",
86
+ signal: controller.signal
87
+ });
88
+ const data = await res.text();
89
+ const responseHeaders = new Headers({
90
+ "Content-Type": res.headers.get("Content-Type") ?? "application/json"
91
+ });
92
+ if (forwardSetCookie) {
93
+ for (const cookie of res.headers.getSetCookie()) {
94
+ responseHeaders.append("set-cookie", cookie);
95
+ }
96
+ }
97
+ return new Response(data, { status: res.status, headers: responseHeaders });
98
+ } catch (err) {
99
+ if (err instanceof Error && err.name === "AbortError") {
100
+ console.error(`[createProxyRoute] Timed out forwarding to ${targetPath} after ${timeoutMs}ms`);
101
+ return jsonErrorResponse(502, "upstream_timeout", timeoutMessage);
102
+ }
103
+ console.error(`[createProxyRoute] Error forwarding to ${targetPath}:`, err);
104
+ return jsonErrorResponse(502, "proxy_error", proxyErrorMessage);
105
+ } finally {
106
+ clearTimeout(timer);
107
+ }
108
+ };
109
+ }
110
+
111
+ // src/shop/route-handlers.ts
112
+ var DEFAULT_WRITE_OPTS = { requireJson: true };
113
+ function createShopCheckoutRoute(opts = {}) {
114
+ return createProxyRoute("/api/site/shop/checkout", { ...DEFAULT_WRITE_OPTS, ...opts });
115
+ }
116
+ function createShopValidateCartRoute(opts = {}) {
117
+ return createProxyRoute("/api/site/shop/validate-cart", { ...DEFAULT_WRITE_OPTS, ...opts });
118
+ }
119
+ function createShopApplyDiscountRoute(opts = {}) {
120
+ return createProxyRoute("/api/site/shop/apply-discount", { ...DEFAULT_WRITE_OPTS, ...opts });
121
+ }
122
+ function createShopCheckEmailRoute(opts = {}) {
123
+ return createProxyRoute("/api/site/shop/check-email", { ...DEFAULT_WRITE_OPTS, ...opts });
124
+ }
125
+ function createShopOrderRoute(opts = {}) {
126
+ return async function handler(request, context) {
127
+ const { sessionId } = await context.params;
128
+ const targetPath = `/api/site/shop/order/${encodeURIComponent(sessionId)}`;
129
+ return createProxyRoute(targetPath, { ...opts, method: "GET" })(request);
130
+ };
131
+ }
132
+ // Annotate the CommonJS export names for ESM import in node:
133
+ 0 && (module.exports = {
134
+ createShopApplyDiscountRoute,
135
+ createShopCheckEmailRoute,
136
+ createShopCheckoutRoute,
137
+ createShopOrderRoute,
138
+ createShopValidateCartRoute
139
+ });
140
+ //# sourceMappingURL=shop-route-handlers.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shop/route-handlers.ts","../src/route-handlers.ts"],"sourcesContent":["/**\n * `@reblu/site-next/shop-route-handlers` (REB-829) — Route Handler factories\n * for the cart/checkout write flow (`/api/site/shop/{checkout, validate-cart,\n * apply-discount, check-email, order/[sessionId]}`). Every demo-site route\n * these replace (`app/api/shop/*`) either hand-rolled the SAME proxy\n * boilerplate `./route-handlers`'s `createProxyRoute` already generalizes\n * (checkout/validate-cart/apply-discount/check-email), or called\n * `proxyToBaseApi` directly for the one dynamic-path route (`order/\n * [sessionId]`) that `createProxyRoute` deliberately does not cover (its own\n * docblock: \"a per-request DYNAMIC targetPath... is genuinely out of scope\").\n * This module is the dynamic-path extension `createProxyRoute` named as a\n * gap, kept as its own file (not folded into `./server`, REB-809's filters/\n * collection glue) because it is a distinct concern — a page that only reads\n * shop data never needs these factories, and a cart/checkout integration\n * never needs the filters glue.\n *\n * Server-only, dependency-free (only `createProxyRoute` + the `next/server`\n * type) — same isolation direction as `./route-handlers`/`./shop/server.ts`:\n * this entry must NEVER carry `'use client'` (see `tsup.config.ts`).\n *\n * Mirrors `createProxyRoute`'s own API-key/server-only handling verbatim —\n * `REBLU_API_KEY` is read lazily, server-side, and injected as\n * `X-Reblu-Api-Key` on the upstream fetch only; it never reaches the\n * Response these handlers return to the browser.\n *\n * // app/api/shop/checkout/route.ts\n * export const POST = createShopCheckoutRoute()\n *\n * // app/api/shop/order/[sessionId]/route.ts\n * export const GET = createShopOrderRoute()\n */\nimport type { NextRequest } from 'next/server'\nimport { createProxyRoute, type CreateProxyRouteOptions } from '../route-handlers'\n\n/** Options for a fixed-path write route. `method` is always `'POST'` here. */\nexport type ShopWriteRouteOptions = Omit<CreateProxyRouteOptions, 'method'>\n\n/**\n * `requireJson: true` by default for every write route below: the browser\n * clients these proxy for (the cart/checkout UI) always set\n * `Content-Type: application/json`, and rejecting anything else with a 400\n * BEFORE the upstream fetch is strictly safer than forwarding an\n * unparseable body to base-api. A SITE with a non-JSON caller can still pass\n * `{ requireJson: false }`.\n */\nconst DEFAULT_WRITE_OPTS: ShopWriteRouteOptions = { requireJson: true }\n\n/** `POST /api/site/shop/checkout` — starts a hosted Stripe Checkout session. */\nexport function createShopCheckoutRoute(opts: ShopWriteRouteOptions = {}) {\n return createProxyRoute('/api/site/shop/checkout', { ...DEFAULT_WRITE_OPTS, ...opts })\n}\n\n/** `POST /api/site/shop/validate-cart` — live stock/price re-check before checkout. */\nexport function createShopValidateCartRoute(opts: ShopWriteRouteOptions = {}) {\n return createProxyRoute('/api/site/shop/validate-cart', { ...DEFAULT_WRITE_OPTS, ...opts })\n}\n\n/** `POST /api/site/shop/apply-discount` — validates a discount code against the cart. */\nexport function createShopApplyDiscountRoute(opts: ShopWriteRouteOptions = {}) {\n return createProxyRoute('/api/site/shop/apply-discount', { ...DEFAULT_WRITE_OPTS, ...opts })\n}\n\n/** `POST /api/site/shop/check-email` — whether a guest's email already has an account. */\nexport function createShopCheckEmailRoute(opts: ShopWriteRouteOptions = {}) {\n return createProxyRoute('/api/site/shop/check-email', { ...DEFAULT_WRITE_OPTS, ...opts })\n}\n\n/** Options for the dynamic order-lookup route. `method` is always `'GET'`. */\nexport type ShopOrderRouteOptions = Omit<CreateProxyRouteOptions, 'method'>\n\n/**\n * `GET /api/site/shop/order/[sessionId]` — the one route in this file with a\n * per-request dynamic target path, so it can't be a one-line\n * `createProxyRoute(...)` call like the others: it reads Next's route\n * `params`, builds `/api/site/shop/order/{sessionId}` per request, and\n * delegates everything else (env, timeout, forwarding, error shaping) to\n * `createProxyRoute`.\n */\nexport function createShopOrderRoute(opts: ShopOrderRouteOptions = {}) {\n return async function handler(\n request: NextRequest,\n context: { params: Promise<{ sessionId: string }> },\n ): Promise<Response> {\n const { sessionId } = await context.params\n const targetPath = `/api/site/shop/order/${encodeURIComponent(sessionId)}`\n return createProxyRoute(targetPath, { ...opts, method: 'GET' })(request)\n }\n}\n","/**\n * `@reblu/site-next/route-handlers` — server-only, dependency-free Route\n * Handler factory (REB-510 / design doc \"site-auth-package\").\n *\n * This module MUST stay dependency-free (no `@reblu/site-ui`, no React): it is\n * imported directly by `app/api/*` Route Handler files, and its own tsup entry\n * carries NO `'use client'` directive (mirrors the `cache` subpath's R4\n * precedent for the opposite direction — see `tsup.config.ts`).\n *\n * Scope: this factory covers the `/api/site/auth/*` proxy shape specifically\n * (fixed target path, JSON body passthrough, optional `Set-Cookie` forward) —\n * the same shape as every one of demo-site's 8 auth Route Handlers. It is\n * modeled on `apps/demo-site/src/lib/api/proxy.ts` (`proxyToBaseApi`) but is\n * NOT a drop-in replacement for every one of that helper's call sites: it\n * does not support a per-request DYNAMIC `targetPath` (e.g.\n * `api/shop/order/[sessionId]/route.ts`'s `` `/api/site/shop/order/${id}` ``)\n * or an arbitrary extra-`headers` passthrough — both are genuinely out of\n * scope for REB-510 (auth only). demo-site's non-auth proxy routes keep using\n * `proxyToBaseApi` directly; only the 8 auth routes are candidates to adopt\n * this factory.\n *\n * export const POST = createProxyRoute('/api/site/auth/login')\n *\n * Deliberate behavior change vs the original (R6): `proxy.ts` reads\n * `REBLU_API_BASE_URL`/`REBLU_API_KEY` at MODULE LOAD. This factory reads them\n * LAZILY, inside the returned handler, on every request — `opts.baseUrl` /\n * `opts.apiKey` still take priority when provided.\n *\n * Why this factory reads `process.env` at all, unlike `@reblu/site-client`\n * (whose own docblock states \"the SDK never reads `process.env` itself\"):\n * `site-client` is instantiated ONCE by the consuming SITE, which already\n * owns and injects its env at that single call site. `createProxyRoute` is\n * the opposite shape on purpose — a ZERO-CONFIG one-liner meant to be called\n * once per Route Handler FILE (8+ files in a typical SITE), so requiring\n * every file to re-thread `baseUrl`/`apiKey` would defeat the \"one line\"\n * value proposition documented in the README. The env fallback is this\n * factory's deliberate ergonomic default; `opts.baseUrl`/`opts.apiKey` remain\n * available for a SITE that wants explicit, non-`process.env` control.\n *\n * Trust note on header forwarding: `X-Forwarded-For`/`X-Real-IP` are copied\n * from the incoming request VERBATIM (same as the original `proxy.ts`). On\n * Vercel the platform itself sets/overwrites these ahead of the Route\n * Handler, so they're trustworthy there — but this is a distributable SDK a\n * SITE can deploy anywhere. On a host where nothing strips inbound spoofed\n * values, a client can forge the IP base-api rate-limits on. Deploy this\n * factory only behind a platform that normalizes/overwrites these headers,\n * or in front of infra that strips client-supplied ones.\n */\nimport type { NextRequest } from 'next/server'\n\nexport interface CreateProxyRouteOptions {\n /** Overrides `REBLU_API_BASE_URL`. Read lazily per-request when omitted. */\n baseUrl?: string\n /** Overrides `REBLU_API_KEY`. Read lazily per-request when omitted. */\n apiKey?: string\n /** @default 'POST' */\n method?: string\n /** Forward upstream `Set-Cookie` headers to the browser. @default false */\n forwardSetCookie?: boolean\n /**\n * Reject non-`application/json` requests with a Spanish 400 before ever\n * reaching the network — mirrors `magic-link-exchange/route.ts`'s guard.\n * @default false\n */\n requireJson?: boolean\n /**\n * Overrides the Spanish `message` field of the `requireJson` 400 body, for\n * a non-Spanish-default SITE. The `error` code (`invalid_request`) and\n * shape stay fixed — only the human-facing text is overridable.\n * @default 'Solicitud no válida'\n */\n invalidRequestMessage?: string\n /**\n * Hard timeout (ms) for the upstream fetch, enforced via `AbortController`\n * — mirrors `@reblu/site-client`'s own `timeoutMs` (default `8000`, same\n * value). Without this, a hung base-api response would hang the SITE's\n * Route Handler indefinitely instead of degrading.\n * @default 8000\n */\n timeoutMs?: number\n /**\n * Overrides the `message` field of the 500 body returned when neither\n * `opts.baseUrl`/`opts.apiKey` nor `REBLU_API_BASE_URL`/`REBLU_API_KEY`\n * resolve to a non-empty value.\n * @default 'Error de configuración del servidor.'\n */\n configurationErrorMessage?: string\n /**\n * Overrides the `message` field of the 502 body returned when the\n * upstream fetch times out.\n * @default 'La solicitud ha superado el tiempo de espera.'\n */\n timeoutMessage?: string\n /**\n * Overrides the `message` field of the 502 body returned when the\n * upstream fetch fails for any other reason (DNS, connection refused,\n * etc.).\n * @default 'Error de conexión con el servidor.'\n */\n proxyErrorMessage?: string\n}\n\nfunction jsonErrorResponse(status: number, error: string, message: string): Response {\n return new Response(\n JSON.stringify({ error, message, correlation_id: crypto.randomUUID() }),\n { status, headers: { 'Content-Type': 'application/json; charset=utf-8' } },\n )\n}\n\n/**\n * Creates a Next.js Route Handler that proxies `request` to\n * `${baseUrl}${targetPath}` at base-api, injecting the `X-Reblu-Api-Key`\n * server-side so it never reaches the browser.\n */\nexport function createProxyRoute(targetPath: string, opts: CreateProxyRouteOptions = {}) {\n const {\n method = 'POST',\n forwardSetCookie = false,\n requireJson = false,\n invalidRequestMessage = 'Solicitud no válida',\n timeoutMs = 8000,\n configurationErrorMessage = 'Error de configuración del servidor.',\n timeoutMessage = 'La solicitud ha superado el tiempo de espera.',\n proxyErrorMessage = 'Error de conexión con el servidor.',\n } = opts\n\n return async function handler(request: NextRequest): Promise<Response> {\n if (requireJson) {\n const contentType = request.headers.get('content-type') ?? ''\n if (!contentType.includes('application/json')) {\n return jsonErrorResponse(400, 'invalid_request', invalidRequestMessage)\n }\n }\n\n // Lazy, per-request env read (R6) — opts win when provided.\n const baseUrl = opts.baseUrl ?? process.env.REBLU_API_BASE_URL ?? ''\n const apiKey = opts.apiKey ?? process.env.REBLU_API_KEY ?? ''\n\n if (!baseUrl || !apiKey) {\n console.error(\n `[createProxyRoute] Missing configuration for ${targetPath}: ` +\n `${!baseUrl ? 'baseUrl/REBLU_API_BASE_URL ' : ''}${!apiKey ? 'apiKey/REBLU_API_KEY' : ''}`.trim(),\n )\n return jsonErrorResponse(500, 'missing_configuration', configurationErrorMessage)\n }\n\n const forwardedHeaders: Record<string, string> = {}\n const ua = request.headers.get('user-agent')\n if (ua) forwardedHeaders['user-agent'] = ua\n const xff = request.headers.get('x-forwarded-for')\n if (xff) forwardedHeaders['x-forwarded-for'] = xff\n const xri = request.headers.get('x-real-ip')\n if (xri) forwardedHeaders['x-real-ip'] = xri\n\n const upperMethod = method.toUpperCase()\n const body =\n upperMethod === 'GET' || upperMethod === 'HEAD' ? undefined : await request.text()\n // Forward the original query string (e.g. `?slug=x`) regardless of\n // method — `targetPath` is fixed at factory-call time, so without this a\n // GET route configured via `{ method: 'GET' }` would silently drop it.\n const search = request.nextUrl?.search ?? ''\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n\n try {\n const res = await fetch(`${baseUrl}${targetPath}${search}`, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Reblu-Api-Key': apiKey,\n ...forwardedHeaders,\n },\n ...(body ? { body } : {}),\n cache: 'no-store',\n signal: controller.signal,\n })\n\n const data = await res.text()\n const responseHeaders = new Headers({\n 'Content-Type': res.headers.get('Content-Type') ?? 'application/json',\n })\n\n if (forwardSetCookie) {\n for (const cookie of res.headers.getSetCookie()) {\n responseHeaders.append('set-cookie', cookie)\n }\n }\n\n return new Response(data, { status: res.status, headers: responseHeaders })\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') {\n console.error(`[createProxyRoute] Timed out forwarding to ${targetPath} after ${timeoutMs}ms`)\n return jsonErrorResponse(502, 'upstream_timeout', timeoutMessage)\n }\n console.error(`[createProxyRoute] Error forwarding to ${targetPath}:`, err)\n return jsonErrorResponse(502, 'proxy_error', proxyErrorMessage)\n } finally {\n clearTimeout(timer)\n }\n }\n}\n"],"mappings":"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","names":[]}
@@ -0,0 +1,62 @@
1
+ import { NextRequest } from 'next/server';
2
+ import { CreateProxyRouteOptions } from './route-handlers.cjs';
3
+
4
+ /**
5
+ * `@reblu/site-next/shop-route-handlers` (REB-829) — Route Handler factories
6
+ * for the cart/checkout write flow (`/api/site/shop/{checkout, validate-cart,
7
+ * apply-discount, check-email, order/[sessionId]}`). Every demo-site route
8
+ * these replace (`app/api/shop/*`) either hand-rolled the SAME proxy
9
+ * boilerplate `./route-handlers`'s `createProxyRoute` already generalizes
10
+ * (checkout/validate-cart/apply-discount/check-email), or called
11
+ * `proxyToBaseApi` directly for the one dynamic-path route (`order/
12
+ * [sessionId]`) that `createProxyRoute` deliberately does not cover (its own
13
+ * docblock: "a per-request DYNAMIC targetPath... is genuinely out of scope").
14
+ * This module is the dynamic-path extension `createProxyRoute` named as a
15
+ * gap, kept as its own file (not folded into `./server`, REB-809's filters/
16
+ * collection glue) because it is a distinct concern — a page that only reads
17
+ * shop data never needs these factories, and a cart/checkout integration
18
+ * never needs the filters glue.
19
+ *
20
+ * Server-only, dependency-free (only `createProxyRoute` + the `next/server`
21
+ * type) — same isolation direction as `./route-handlers`/`./shop/server.ts`:
22
+ * this entry must NEVER carry `'use client'` (see `tsup.config.ts`).
23
+ *
24
+ * Mirrors `createProxyRoute`'s own API-key/server-only handling verbatim —
25
+ * `REBLU_API_KEY` is read lazily, server-side, and injected as
26
+ * `X-Reblu-Api-Key` on the upstream fetch only; it never reaches the
27
+ * Response these handlers return to the browser.
28
+ *
29
+ * // app/api/shop/checkout/route.ts
30
+ * export const POST = createShopCheckoutRoute()
31
+ *
32
+ * // app/api/shop/order/[sessionId]/route.ts
33
+ * export const GET = createShopOrderRoute()
34
+ */
35
+
36
+ /** Options for a fixed-path write route. `method` is always `'POST'` here. */
37
+ type ShopWriteRouteOptions = Omit<CreateProxyRouteOptions, 'method'>;
38
+ /** `POST /api/site/shop/checkout` — starts a hosted Stripe Checkout session. */
39
+ declare function createShopCheckoutRoute(opts?: ShopWriteRouteOptions): (request: NextRequest) => Promise<Response>;
40
+ /** `POST /api/site/shop/validate-cart` — live stock/price re-check before checkout. */
41
+ declare function createShopValidateCartRoute(opts?: ShopWriteRouteOptions): (request: NextRequest) => Promise<Response>;
42
+ /** `POST /api/site/shop/apply-discount` — validates a discount code against the cart. */
43
+ declare function createShopApplyDiscountRoute(opts?: ShopWriteRouteOptions): (request: NextRequest) => Promise<Response>;
44
+ /** `POST /api/site/shop/check-email` — whether a guest's email already has an account. */
45
+ declare function createShopCheckEmailRoute(opts?: ShopWriteRouteOptions): (request: NextRequest) => Promise<Response>;
46
+ /** Options for the dynamic order-lookup route. `method` is always `'GET'`. */
47
+ type ShopOrderRouteOptions = Omit<CreateProxyRouteOptions, 'method'>;
48
+ /**
49
+ * `GET /api/site/shop/order/[sessionId]` — the one route in this file with a
50
+ * per-request dynamic target path, so it can't be a one-line
51
+ * `createProxyRoute(...)` call like the others: it reads Next's route
52
+ * `params`, builds `/api/site/shop/order/{sessionId}` per request, and
53
+ * delegates everything else (env, timeout, forwarding, error shaping) to
54
+ * `createProxyRoute`.
55
+ */
56
+ declare function createShopOrderRoute(opts?: ShopOrderRouteOptions): (request: NextRequest, context: {
57
+ params: Promise<{
58
+ sessionId: string;
59
+ }>;
60
+ }) => Promise<Response>;
61
+
62
+ export { type ShopOrderRouteOptions, type ShopWriteRouteOptions, createShopApplyDiscountRoute, createShopCheckEmailRoute, createShopCheckoutRoute, createShopOrderRoute, createShopValidateCartRoute };
@@ -0,0 +1,62 @@
1
+ import { NextRequest } from 'next/server';
2
+ import { CreateProxyRouteOptions } from './route-handlers.js';
3
+
4
+ /**
5
+ * `@reblu/site-next/shop-route-handlers` (REB-829) — Route Handler factories
6
+ * for the cart/checkout write flow (`/api/site/shop/{checkout, validate-cart,
7
+ * apply-discount, check-email, order/[sessionId]}`). Every demo-site route
8
+ * these replace (`app/api/shop/*`) either hand-rolled the SAME proxy
9
+ * boilerplate `./route-handlers`'s `createProxyRoute` already generalizes
10
+ * (checkout/validate-cart/apply-discount/check-email), or called
11
+ * `proxyToBaseApi` directly for the one dynamic-path route (`order/
12
+ * [sessionId]`) that `createProxyRoute` deliberately does not cover (its own
13
+ * docblock: "a per-request DYNAMIC targetPath... is genuinely out of scope").
14
+ * This module is the dynamic-path extension `createProxyRoute` named as a
15
+ * gap, kept as its own file (not folded into `./server`, REB-809's filters/
16
+ * collection glue) because it is a distinct concern — a page that only reads
17
+ * shop data never needs these factories, and a cart/checkout integration
18
+ * never needs the filters glue.
19
+ *
20
+ * Server-only, dependency-free (only `createProxyRoute` + the `next/server`
21
+ * type) — same isolation direction as `./route-handlers`/`./shop/server.ts`:
22
+ * this entry must NEVER carry `'use client'` (see `tsup.config.ts`).
23
+ *
24
+ * Mirrors `createProxyRoute`'s own API-key/server-only handling verbatim —
25
+ * `REBLU_API_KEY` is read lazily, server-side, and injected as
26
+ * `X-Reblu-Api-Key` on the upstream fetch only; it never reaches the
27
+ * Response these handlers return to the browser.
28
+ *
29
+ * // app/api/shop/checkout/route.ts
30
+ * export const POST = createShopCheckoutRoute()
31
+ *
32
+ * // app/api/shop/order/[sessionId]/route.ts
33
+ * export const GET = createShopOrderRoute()
34
+ */
35
+
36
+ /** Options for a fixed-path write route. `method` is always `'POST'` here. */
37
+ type ShopWriteRouteOptions = Omit<CreateProxyRouteOptions, 'method'>;
38
+ /** `POST /api/site/shop/checkout` — starts a hosted Stripe Checkout session. */
39
+ declare function createShopCheckoutRoute(opts?: ShopWriteRouteOptions): (request: NextRequest) => Promise<Response>;
40
+ /** `POST /api/site/shop/validate-cart` — live stock/price re-check before checkout. */
41
+ declare function createShopValidateCartRoute(opts?: ShopWriteRouteOptions): (request: NextRequest) => Promise<Response>;
42
+ /** `POST /api/site/shop/apply-discount` — validates a discount code against the cart. */
43
+ declare function createShopApplyDiscountRoute(opts?: ShopWriteRouteOptions): (request: NextRequest) => Promise<Response>;
44
+ /** `POST /api/site/shop/check-email` — whether a guest's email already has an account. */
45
+ declare function createShopCheckEmailRoute(opts?: ShopWriteRouteOptions): (request: NextRequest) => Promise<Response>;
46
+ /** Options for the dynamic order-lookup route. `method` is always `'GET'`. */
47
+ type ShopOrderRouteOptions = Omit<CreateProxyRouteOptions, 'method'>;
48
+ /**
49
+ * `GET /api/site/shop/order/[sessionId]` — the one route in this file with a
50
+ * per-request dynamic target path, so it can't be a one-line
51
+ * `createProxyRoute(...)` call like the others: it reads Next's route
52
+ * `params`, builds `/api/site/shop/order/{sessionId}` per request, and
53
+ * delegates everything else (env, timeout, forwarding, error shaping) to
54
+ * `createProxyRoute`.
55
+ */
56
+ declare function createShopOrderRoute(opts?: ShopOrderRouteOptions): (request: NextRequest, context: {
57
+ params: Promise<{
58
+ sessionId: string;
59
+ }>;
60
+ }) => Promise<Response>;
61
+
62
+ export { type ShopOrderRouteOptions, type ShopWriteRouteOptions, createShopApplyDiscountRoute, createShopCheckEmailRoute, createShopCheckoutRoute, createShopOrderRoute, createShopValidateCartRoute };
@@ -0,0 +1,109 @@
1
+ // src/route-handlers.ts
2
+ function jsonErrorResponse(status, error, message) {
3
+ return new Response(
4
+ JSON.stringify({ error, message, correlation_id: crypto.randomUUID() }),
5
+ { status, headers: { "Content-Type": "application/json; charset=utf-8" } }
6
+ );
7
+ }
8
+ function createProxyRoute(targetPath, opts = {}) {
9
+ const {
10
+ method = "POST",
11
+ forwardSetCookie = false,
12
+ requireJson = false,
13
+ invalidRequestMessage = "Solicitud no v\xE1lida",
14
+ timeoutMs = 8e3,
15
+ configurationErrorMessage = "Error de configuraci\xF3n del servidor.",
16
+ timeoutMessage = "La solicitud ha superado el tiempo de espera.",
17
+ proxyErrorMessage = "Error de conexi\xF3n con el servidor."
18
+ } = opts;
19
+ return async function handler(request) {
20
+ if (requireJson) {
21
+ const contentType = request.headers.get("content-type") ?? "";
22
+ if (!contentType.includes("application/json")) {
23
+ return jsonErrorResponse(400, "invalid_request", invalidRequestMessage);
24
+ }
25
+ }
26
+ const baseUrl = opts.baseUrl ?? process.env.REBLU_API_BASE_URL ?? "";
27
+ const apiKey = opts.apiKey ?? process.env.REBLU_API_KEY ?? "";
28
+ if (!baseUrl || !apiKey) {
29
+ console.error(
30
+ `[createProxyRoute] Missing configuration for ${targetPath}: ` + `${!baseUrl ? "baseUrl/REBLU_API_BASE_URL " : ""}${!apiKey ? "apiKey/REBLU_API_KEY" : ""}`.trim()
31
+ );
32
+ return jsonErrorResponse(500, "missing_configuration", configurationErrorMessage);
33
+ }
34
+ const forwardedHeaders = {};
35
+ const ua = request.headers.get("user-agent");
36
+ if (ua) forwardedHeaders["user-agent"] = ua;
37
+ const xff = request.headers.get("x-forwarded-for");
38
+ if (xff) forwardedHeaders["x-forwarded-for"] = xff;
39
+ const xri = request.headers.get("x-real-ip");
40
+ if (xri) forwardedHeaders["x-real-ip"] = xri;
41
+ const upperMethod = method.toUpperCase();
42
+ const body = upperMethod === "GET" || upperMethod === "HEAD" ? void 0 : await request.text();
43
+ const search = request.nextUrl?.search ?? "";
44
+ const controller = new AbortController();
45
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
46
+ try {
47
+ const res = await fetch(`${baseUrl}${targetPath}${search}`, {
48
+ method,
49
+ headers: {
50
+ "Content-Type": "application/json",
51
+ "X-Reblu-Api-Key": apiKey,
52
+ ...forwardedHeaders
53
+ },
54
+ ...body ? { body } : {},
55
+ cache: "no-store",
56
+ signal: controller.signal
57
+ });
58
+ const data = await res.text();
59
+ const responseHeaders = new Headers({
60
+ "Content-Type": res.headers.get("Content-Type") ?? "application/json"
61
+ });
62
+ if (forwardSetCookie) {
63
+ for (const cookie of res.headers.getSetCookie()) {
64
+ responseHeaders.append("set-cookie", cookie);
65
+ }
66
+ }
67
+ return new Response(data, { status: res.status, headers: responseHeaders });
68
+ } catch (err) {
69
+ if (err instanceof Error && err.name === "AbortError") {
70
+ console.error(`[createProxyRoute] Timed out forwarding to ${targetPath} after ${timeoutMs}ms`);
71
+ return jsonErrorResponse(502, "upstream_timeout", timeoutMessage);
72
+ }
73
+ console.error(`[createProxyRoute] Error forwarding to ${targetPath}:`, err);
74
+ return jsonErrorResponse(502, "proxy_error", proxyErrorMessage);
75
+ } finally {
76
+ clearTimeout(timer);
77
+ }
78
+ };
79
+ }
80
+
81
+ // src/shop/route-handlers.ts
82
+ var DEFAULT_WRITE_OPTS = { requireJson: true };
83
+ function createShopCheckoutRoute(opts = {}) {
84
+ return createProxyRoute("/api/site/shop/checkout", { ...DEFAULT_WRITE_OPTS, ...opts });
85
+ }
86
+ function createShopValidateCartRoute(opts = {}) {
87
+ return createProxyRoute("/api/site/shop/validate-cart", { ...DEFAULT_WRITE_OPTS, ...opts });
88
+ }
89
+ function createShopApplyDiscountRoute(opts = {}) {
90
+ return createProxyRoute("/api/site/shop/apply-discount", { ...DEFAULT_WRITE_OPTS, ...opts });
91
+ }
92
+ function createShopCheckEmailRoute(opts = {}) {
93
+ return createProxyRoute("/api/site/shop/check-email", { ...DEFAULT_WRITE_OPTS, ...opts });
94
+ }
95
+ function createShopOrderRoute(opts = {}) {
96
+ return async function handler(request, context) {
97
+ const { sessionId } = await context.params;
98
+ const targetPath = `/api/site/shop/order/${encodeURIComponent(sessionId)}`;
99
+ return createProxyRoute(targetPath, { ...opts, method: "GET" })(request);
100
+ };
101
+ }
102
+ export {
103
+ createShopApplyDiscountRoute,
104
+ createShopCheckEmailRoute,
105
+ createShopCheckoutRoute,
106
+ createShopOrderRoute,
107
+ createShopValidateCartRoute
108
+ };
109
+ //# sourceMappingURL=shop-route-handlers.js.map