@cloudexp-io/laudro-site-kit 0.0.0-stage → 0.5.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,90 @@
1
+ import { LaudroClient } from '@cloudexp-io/laudro-sdk/next';
2
+
3
+ interface RevalidateHandlerOptions {
4
+ /** `RB_WEBHOOK_SECRET`. Without it every call gets 503, so a missing env var is visible. */
5
+ secret: string | undefined;
6
+ /** `RB_SITE_ID`. When set, a payload for another site gets 403. */
7
+ siteId?: string | undefined;
8
+ /** Injected in tests. Default: Next.js `revalidateTag(tag, profile)`. */
9
+ revalidate?: (tag: string) => void;
10
+ /** Cache profile for `revalidateTag`. Default `{ expire: 0 }`: the next visit gets fresh data. */
11
+ profile?: string | {
12
+ expire?: number;
13
+ };
14
+ now?: () => Date;
15
+ }
16
+ /**
17
+ * Route handler for the backend's `content.updated` webhook. Checks the `laudro-signature` HMAC (or the legacy `rb-signature`)
18
+ * (5 minute tolerance), then revalidates each cache tag in the payload.
19
+ *
20
+ * ```ts
21
+ * // app/api/revalidate/route.ts
22
+ * export const POST = createRevalidateHandler({ secret: process.env.RB_WEBHOOK_SECRET });
23
+ * ```
24
+ */
25
+ declare function createRevalidateHandler(o: RevalidateHandlerOptions): (req: Request) => Promise<Response>;
26
+
27
+ type FormKind = "booking" | "event" | "contact";
28
+ interface FormHandlerOptions {
29
+ /** Returns the server client, or null when env vars are missing (503). */
30
+ client: () => LaudroClient | null;
31
+ kind: FormKind;
32
+ /** Max body size in bytes. Default 16 KB. */
33
+ maxBytes?: number;
34
+ }
35
+ /**
36
+ * Route handler for a site form. The browser posts JSON here; this calls the API with the site
37
+ * secret and the visitor's IP (rate limits count per IP). Never logs the body: it holds names,
38
+ * phone numbers and messages.
39
+ *
40
+ * ```ts
41
+ * // app/api/booking/route.ts
42
+ * export const POST = createFormHandler({ client: getRb, kind: "booking" });
43
+ * ```
44
+ */
45
+ declare function createFormHandler(o: FormHandlerOptions): (req: Request) => Promise<Response>;
46
+ interface TrackHandlerOptions {
47
+ client: () => LaudroClient | null;
48
+ }
49
+ /** Route handler for `/api/track`. Always 204, so a beacon never shows an error. */
50
+ declare function createTrackHandler(o: TrackHandlerOptions): (req: Request) => Promise<Response>;
51
+ interface FormTokenHandlerOptions {
52
+ /** The site secret (`RB_SITE_SECRET`). The token is an HMAC of the time with it. */
53
+ secret: string | undefined;
54
+ }
55
+ /**
56
+ * Route handler for `/api/form-token`: `{ t }`, never cached. Forms fetch it on mount because
57
+ * a cached page may be hours old, and the API drops a token older than two hours.
58
+ */
59
+ declare function createFormTokenHandler(o: FormTokenHandlerOptions): () => Promise<Response>;
60
+
61
+ declare const PREVIEW_COOKIE = "laudro_preview";
62
+ interface PreviewHandlerOptions {
63
+ client: () => LaudroClient | null;
64
+ }
65
+ /**
66
+ * Route handler for `/api/laudro-preview?token=...&path=/menu`. Checks the token with the API,
67
+ * turns on Draft Mode and keeps the token in an httpOnly cookie until it expires.
68
+ */
69
+ declare function createPreviewHandler(o: PreviewHandlerOptions): (req: Request) => Promise<Response>;
70
+ /** Route handler for `/api/laudro-preview/exit?path=/`. Turns Draft Mode off. */
71
+ declare function createPreviewExitHandler(): (req: Request) => Promise<Response>;
72
+ /**
73
+ * The client to read with on a page: the preview client while Draft Mode is on, else `base`.
74
+ * Reads cookies only in Draft Mode, so normal pages stay static.
75
+ */
76
+ declare function getPreviewAwareClient(base: LaudroClient): Promise<LaudroClient>;
77
+
78
+ /**
79
+ * The visitor's IP as the site's host saw it. `x-real-ip` first (set by Vercel and most
80
+ * proxies), then the first `x-forwarded-for` entry. Undefined when neither is there.
81
+ */
82
+ declare function visitorIp(req: Request): string | undefined;
83
+ /**
84
+ * Same-origin check for browser POSTs. A request without Origin (curl, server to server) is
85
+ * allowed; the API's form token and rate limits still apply.
86
+ */
87
+ declare function sameOrigin(req: Request): boolean;
88
+
89
+ export { PREVIEW_COOKIE, createFormHandler, createFormTokenHandler, createPreviewExitHandler, createPreviewHandler, createRevalidateHandler, createTrackHandler, getPreviewAwareClient, sameOrigin, visitorIp };
90
+ export type { FormHandlerOptions, FormKind, FormTokenHandlerOptions, PreviewHandlerOptions, RevalidateHandlerOptions, TrackHandlerOptions };
package/dist/server.js ADDED
@@ -0,0 +1,225 @@
1
+ import {
2
+ safePath
3
+ } from "./chunk-YCELGJAT.js";
4
+
5
+ // src/server.ts
6
+ import "server-only";
7
+
8
+ // src/server/revalidate.ts
9
+ import { expandCacheTags, verifyWebhook, WebhookPayload } from "@cloudexp-io/laudro-sdk/next";
10
+ import { revalidateTag } from "next/cache";
11
+
12
+ // src/server/http.ts
13
+ import { PROBLEM_CONTENT_TYPE } from "@cloudexp-io/laudro-sdk/next";
14
+ function json(body, status = 200, headers = {}) {
15
+ return new Response(JSON.stringify(body), {
16
+ status,
17
+ headers: { "content-type": "application/json", "cache-control": "no-store", ...headers }
18
+ });
19
+ }
20
+ function problem(status, title, extra = {}) {
21
+ const body = { type: "about:blank", title, status, ...extra };
22
+ return new Response(JSON.stringify(body), {
23
+ status,
24
+ headers: { "content-type": PROBLEM_CONTENT_TYPE, "cache-control": "no-store" }
25
+ });
26
+ }
27
+ function visitorIp(req) {
28
+ const real = req.headers.get("x-real-ip")?.trim();
29
+ if (real) return real.slice(0, 64);
30
+ const fwd = req.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
31
+ return fwd ? fwd.slice(0, 64) : void 0;
32
+ }
33
+ function sameOrigin(req) {
34
+ const origin = req.headers.get("origin");
35
+ if (!origin) return true;
36
+ const host = req.headers.get("x-forwarded-host") ?? req.headers.get("host");
37
+ if (!host) return false;
38
+ try {
39
+ return new URL(origin).host === host.split(",")[0]?.trim();
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
44
+ async function readLimited(req, max) {
45
+ const len = Number(req.headers.get("content-length") ?? "0");
46
+ if (len > max) return null;
47
+ const text = await req.text();
48
+ return new TextEncoder().encode(text).byteLength > max ? null : text;
49
+ }
50
+
51
+ // src/server/revalidate.ts
52
+ function createRevalidateHandler(o) {
53
+ const profile = o.profile ?? { expire: 0 };
54
+ const revalidate = o.revalidate ?? ((tag) => revalidateTag(tag, profile));
55
+ return async function POST(req) {
56
+ if (!o.secret) return json({ error: "not_configured" }, 503);
57
+ const v = await verifyWebhook(req, o.secret, o.now?.() ?? /* @__PURE__ */ new Date());
58
+ if (!v.ok) return json({ error: v.reason }, 401);
59
+ let raw;
60
+ try {
61
+ raw = JSON.parse(v.body);
62
+ } catch {
63
+ return json({ error: "bad_json" }, 400);
64
+ }
65
+ const parsed = WebhookPayload.safeParse(raw);
66
+ if (!parsed.success) {
67
+ const ev = raw?.event;
68
+ if (typeof ev === "string" && ev !== "content.updated") return json({ ignored: ev });
69
+ return json({ error: "bad_payload" }, 400);
70
+ }
71
+ if (o.siteId && parsed.data.site_id !== o.siteId) return json({ error: "wrong_site" }, 403);
72
+ const tags = expandCacheTags(parsed.data.tags);
73
+ for (const tag of tags) revalidate(tag);
74
+ return json({ revalidated: tags, id: parsed.data.id });
75
+ };
76
+ }
77
+
78
+ // src/server/forms.ts
79
+ import {
80
+ LaudroApiError,
81
+ signFormToken,
82
+ TrackEvent
83
+ } from "@cloudexp-io/laudro-sdk/next";
84
+ function isZodError(e) {
85
+ return !!e && typeof e === "object" && e.name === "ZodError" && Array.isArray(e.issues);
86
+ }
87
+ function createFormHandler(o) {
88
+ const max = o.maxBytes ?? 16 * 1024;
89
+ return async function POST(req) {
90
+ if (!sameOrigin(req)) return problem(403, "Cross-site form post");
91
+ const type = req.headers.get("content-type") ?? "";
92
+ if (!type.includes("application/json")) return problem(415, "Send JSON");
93
+ const rb = o.client();
94
+ if (!rb) return problem(503, "Site is not configured");
95
+ const text = await readLimited(req, max);
96
+ if (text === null) return problem(413, "Body too large");
97
+ let body;
98
+ try {
99
+ body = JSON.parse(text);
100
+ } catch {
101
+ return problem(400, "Invalid JSON");
102
+ }
103
+ const ip = visitorIp(req);
104
+ const opts = {
105
+ ...ip ? { ip } : {},
106
+ // Demo sites only: the API says why it dropped the form. Logged, never sent to the browser.
107
+ onResponse: (h) => {
108
+ const m = /^dropped=([a-z_]+)$/.exec(h.get("laudro-debug") ?? "");
109
+ if (m) {
110
+ console.warn(
111
+ `[laudro] request dropped by spam check: ${m[1]} (demo sites only; see https://developers.laudro.app/docs/sdk#forms)`
112
+ );
113
+ }
114
+ }
115
+ };
116
+ try {
117
+ const created = o.kind === "booking" ? await rb.bookingRequests.create(body, opts) : o.kind === "event" ? await rb.eventRequests.create(body, opts) : await rb.contact.create(body, opts);
118
+ return json({ id: created.id, status: created.status }, 201);
119
+ } catch (e) {
120
+ if (isZodError(e)) {
121
+ return problem(422, "Invalid input", {
122
+ errors: e.issues.map((i) => ({
123
+ path: i.path.map(String).join("."),
124
+ code: i.code,
125
+ message: i.message
126
+ }))
127
+ });
128
+ }
129
+ if (e instanceof LaudroApiError) {
130
+ const status = e.status >= 400 && e.status < 600 ? e.status : 502;
131
+ if (e.problem)
132
+ return json(e.problem, status, { "content-type": "application/problem+json" });
133
+ return problem(status, e.message);
134
+ }
135
+ return problem(502, "Could not reach the restaurant service");
136
+ }
137
+ };
138
+ }
139
+ function createTrackHandler(o) {
140
+ return async function POST(req) {
141
+ const done = new Response(null, { status: 204 });
142
+ if (!sameOrigin(req)) return done;
143
+ const rb = o.client();
144
+ if (!rb) return done;
145
+ const text = await readLimited(req, 2048).catch(() => null);
146
+ if (!text) return done;
147
+ let raw;
148
+ try {
149
+ raw = JSON.parse(text);
150
+ } catch {
151
+ return done;
152
+ }
153
+ const parsed = TrackEvent.safeParse(raw);
154
+ if (!parsed.success) return done;
155
+ const ip = visitorIp(req);
156
+ await rb.track(parsed.data, ip ? { ip } : {});
157
+ return done;
158
+ };
159
+ }
160
+ function createFormTokenHandler(o) {
161
+ return async function GET() {
162
+ if (!o.secret) return json({ error: "not_configured" }, 503);
163
+ const t = await signFormToken(o.secret);
164
+ return json({ t }, 200, { "cache-control": "no-store, private" });
165
+ };
166
+ }
167
+
168
+ // src/server/preview.ts
169
+ import { cookies, draftMode } from "next/headers";
170
+ import { redirect } from "next/navigation";
171
+ var PREVIEW_COOKIE = "laudro_preview";
172
+ var LEGACY_PREVIEW_COOKIE = "rb_preview";
173
+ function createPreviewHandler(o) {
174
+ return async function GET(req) {
175
+ const url = new URL(req.url);
176
+ const token = url.searchParams.get("token");
177
+ if (!token || token.length > 4096) return json({ error: "missing_token" }, 400);
178
+ const rb = o.client();
179
+ if (!rb) return json({ error: "not_configured" }, 503);
180
+ let check;
181
+ try {
182
+ check = await rb.checkPreview(token);
183
+ } catch {
184
+ return json({ error: "invalid_token" }, 401);
185
+ }
186
+ if (!check.valid) return json({ error: "invalid_token" }, 401);
187
+ (await draftMode()).enable();
188
+ (await cookies()).set(PREVIEW_COOKIE, token, {
189
+ httpOnly: true,
190
+ sameSite: "lax",
191
+ secure: process.env.NODE_ENV === "production",
192
+ path: "/",
193
+ expires: new Date(check.expires_at)
194
+ });
195
+ redirect(safePath(url.searchParams.get("path") ?? check.path));
196
+ };
197
+ }
198
+ function createPreviewExitHandler() {
199
+ return async function GET(req) {
200
+ (await draftMode()).disable();
201
+ const jar = await cookies();
202
+ jar.delete(PREVIEW_COOKIE);
203
+ jar.delete(LEGACY_PREVIEW_COOKIE);
204
+ redirect(safePath(new URL(req.url).searchParams.get("path")));
205
+ };
206
+ }
207
+ async function getPreviewAwareClient(base) {
208
+ const dm = await draftMode();
209
+ if (!dm.isEnabled) return base;
210
+ const jar = await cookies();
211
+ const token = (jar.get(PREVIEW_COOKIE) ?? jar.get(LEGACY_PREVIEW_COOKIE))?.value;
212
+ return token ? base.withPreview(token) : base;
213
+ }
214
+ export {
215
+ PREVIEW_COOKIE,
216
+ createFormHandler,
217
+ createFormTokenHandler,
218
+ createPreviewExitHandler,
219
+ createPreviewHandler,
220
+ createRevalidateHandler,
221
+ createTrackHandler,
222
+ getPreviewAwareClient,
223
+ sameOrigin,
224
+ visitorIp
225
+ };
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@cloudexp-io/laudro-site-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.5.0",
4
+ "description": "Logic and route handlers for restaurant sites on Next.js: hours, menus, lunch, pages, forms, JSON-LD, sitemap, llms.txt, revalidate. No components, no CSS.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/cloudexp-io/laudro.git",
11
+ "directory": "packages/site-kit"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ },
18
+ "./client": {
19
+ "types": "./dist/client.d.ts",
20
+ "import": "./dist/client.js"
21
+ },
22
+ "./server": {
23
+ "types": "./dist/server.d.ts",
24
+ "import": "./dist/server.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "publishConfig": {
31
+ "registry": "https://registry.npmjs.org",
32
+ "access": "public"
33
+ },
34
+ "dependencies": {
35
+ "@date-fns/tz": "^1.5.0",
36
+ "date-fns": "^4.4.0",
37
+ "server-only": "^0.0.1",
38
+ "@cloudexp-io/laudro-sdk": "0.5.0"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^22.20.5",
42
+ "@types/react": "^19.3.0",
43
+ "next": "16.4.6",
44
+ "react": "19.3.1",
45
+ "tsup": "^9.0.0",
46
+ "typescript": "~6.0.3",
47
+ "vitest": "^5.1.0",
48
+ "@cloudexp-io/laudro-contracts": "0.0.0"
49
+ },
50
+ "peerDependencies": {
51
+ "next": ">=16",
52
+ "react": ">=19"
53
+ },
54
+ "scripts": {
55
+ "build": "rm -rf dist && tsup",
56
+ "typecheck": "tsc --noEmit",
57
+ "test": "vitest run"
58
+ },
59
+ "types": "./dist/index.d.ts"
6
60
  }