@cmssy/next 4.7.1 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index-D-mfavEO.d.cts +46 -0
- package/dist/index-D-mfavEO.d.ts +46 -0
- package/dist/index.cjs +31 -2070
- package/dist/index.d.cts +6 -330
- package/dist/index.d.ts +6 -330
- package/dist/index.js +1 -2024
- package/dist/middleware.cjs +185 -0
- package/dist/middleware.d.cts +106 -0
- package/dist/middleware.d.ts +106 -0
- package/dist/middleware.js +156 -0
- package/dist/server.cjs +1063 -0
- package/dist/server.d.cts +206 -0
- package/dist/server.d.ts +206 -0
- package/dist/server.js +1044 -0
- package/dist/testing.cjs +7 -60
- package/dist/testing.d.cts +1 -39
- package/dist/testing.d.ts +1 -39
- package/dist/testing.js +1 -61
- package/package.json +16 -10
- package/dist/config-DNaPqq1f.d.cts +0 -63
- package/dist/config-DNaPqq1f.d.ts +0 -63
- package/dist/preset.cjs +0 -235
- package/dist/preset.d.cts +0 -81
- package/dist/preset.d.ts +0 -81
- package/dist/preset.js +0 -231
package/dist/server.cjs
ADDED
|
@@ -0,0 +1,1063 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
require('server-only');
|
|
4
|
+
var headers = require('next/headers');
|
|
5
|
+
var navigation = require('next/navigation');
|
|
6
|
+
var react = require('@cmssy/react');
|
|
7
|
+
var client = require('@cmssy/react/client');
|
|
8
|
+
var core = require('@cmssy/core');
|
|
9
|
+
var jsxRuntime = require('react/jsx-runtime');
|
|
10
|
+
|
|
11
|
+
// src/server.ts
|
|
12
|
+
async function readValidSession(config) {
|
|
13
|
+
const auth = core.assertAuthConfig(config);
|
|
14
|
+
const jar = await headers.cookies();
|
|
15
|
+
const raw = jar.get(core.CMSSY_SESSION_COOKIE)?.value;
|
|
16
|
+
if (!raw) return null;
|
|
17
|
+
const session = await core.openSession(
|
|
18
|
+
raw,
|
|
19
|
+
auth.sessionSecret,
|
|
20
|
+
config.workspaceSlug
|
|
21
|
+
);
|
|
22
|
+
if (!session || core.isAccessExpired(session)) return null;
|
|
23
|
+
return session;
|
|
24
|
+
}
|
|
25
|
+
async function getCmssyUser(config) {
|
|
26
|
+
const session = await readValidSession(config);
|
|
27
|
+
return session?.user ?? null;
|
|
28
|
+
}
|
|
29
|
+
async function getCmssyAccessToken(config) {
|
|
30
|
+
const session = await readValidSession(config);
|
|
31
|
+
return session?.accessToken ?? null;
|
|
32
|
+
}
|
|
33
|
+
function hasEditFlag(value) {
|
|
34
|
+
return Array.isArray(value) ? value.includes("1") : value === "1";
|
|
35
|
+
}
|
|
36
|
+
function firstValue(value) {
|
|
37
|
+
return Array.isArray(value) ? value[0] : value;
|
|
38
|
+
}
|
|
39
|
+
async function resolveEditorRequest(query, draftSecret) {
|
|
40
|
+
if (!hasEditFlag(query[core.CMSSY_EDIT_QUERY_PARAM])) return false;
|
|
41
|
+
const provided = firstValue(query[core.CMSSY_SECRET_QUERY_PARAM]);
|
|
42
|
+
if (!provided || !draftSecret) return false;
|
|
43
|
+
return core.cmssySecretsMatch(provided, draftSecret);
|
|
44
|
+
}
|
|
45
|
+
function createCmssyPage(config, blocks, options) {
|
|
46
|
+
return buildCmssyPageRenderer(config, blocks, options, false);
|
|
47
|
+
}
|
|
48
|
+
function createCmssyEditPage(config, blocks, options) {
|
|
49
|
+
return buildCmssyPageRenderer(config, blocks, options, true);
|
|
50
|
+
}
|
|
51
|
+
function buildCmssyPageRenderer(config, blocks, options, editRoute) {
|
|
52
|
+
if (!Array.isArray(blocks)) {
|
|
53
|
+
throw new Error(
|
|
54
|
+
"cmssy: createCmssyPage(config, blocks) requires a blocks array \u2014 pass your defineBlock(...) array"
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
const Editor = options?.editor;
|
|
58
|
+
const clientConfig = {
|
|
59
|
+
apiUrl: config.apiUrl,
|
|
60
|
+
org: config.org,
|
|
61
|
+
workspaceSlug: config.workspaceSlug
|
|
62
|
+
};
|
|
63
|
+
const client$1 = react.createCmssyClient(clientConfig);
|
|
64
|
+
const fixedPath = options?.path?.split("/").map((segment) => segment.trim()).filter(Boolean);
|
|
65
|
+
return async function CmssyCatchAllPage({
|
|
66
|
+
params,
|
|
67
|
+
searchParams
|
|
68
|
+
}) {
|
|
69
|
+
const path = fixedPath ?? (params ? (await params).path ?? void 0 : void 0);
|
|
70
|
+
const { isEnabled } = await headers.draftMode();
|
|
71
|
+
let editorActive = false;
|
|
72
|
+
if (editRoute) {
|
|
73
|
+
const query = searchParams ? await searchParams : {};
|
|
74
|
+
editorActive = await resolveEditorRequest(query, config.draftSecret);
|
|
75
|
+
if (!editorActive) {
|
|
76
|
+
navigation.notFound();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const editMode = isEnabled || editorActive;
|
|
80
|
+
const devAllowed = core.isDevelopment() && Boolean(config.devToken?.trim());
|
|
81
|
+
let locale;
|
|
82
|
+
let pagePath = path;
|
|
83
|
+
let defaultLocale;
|
|
84
|
+
let enabledLocales = config.enabledLocales;
|
|
85
|
+
if (config.resolveLocale) {
|
|
86
|
+
defaultLocale = config.defaultLocale ?? (await react.resolveSiteLocales(clientConfig)).defaultLocale;
|
|
87
|
+
locale = await config.resolveLocale();
|
|
88
|
+
} else {
|
|
89
|
+
const siteLocales = await react.resolveSiteLocales(clientConfig);
|
|
90
|
+
defaultLocale = config.defaultLocale ?? siteLocales.defaultLocale;
|
|
91
|
+
const locales = config.enabledLocales ?? siteLocales.locales;
|
|
92
|
+
enabledLocales = locales;
|
|
93
|
+
const split = react.splitLocaleFromPath(path, { defaultLocale, locales });
|
|
94
|
+
locale = split.locale;
|
|
95
|
+
pagePath = split.path;
|
|
96
|
+
}
|
|
97
|
+
const devWorkspaceId = devAllowed ? await client$1.resolveWorkspaceId() : void 0;
|
|
98
|
+
const page = await react.fetchPage(clientConfig, pagePath, {
|
|
99
|
+
previewSecret: editMode ? config.draftSecret : void 0,
|
|
100
|
+
devPreview: devAllowed || void 0,
|
|
101
|
+
devToken: devAllowed ? config.devToken : void 0,
|
|
102
|
+
workspaceId: devWorkspaceId
|
|
103
|
+
});
|
|
104
|
+
if (!page) {
|
|
105
|
+
navigation.notFound();
|
|
106
|
+
}
|
|
107
|
+
if (editorActive && !Editor) {
|
|
108
|
+
throw new Error(
|
|
109
|
+
'cmssy: edit/dev mode requires options.editor \u2014 pass a "use client" editor that imports your blocks and renders <CmssyEditablePage blocks={blocks} \u2026 />'
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
const resolvedForms = await react.resolveForms(
|
|
113
|
+
clientConfig,
|
|
114
|
+
page.blocks,
|
|
115
|
+
locale,
|
|
116
|
+
defaultLocale
|
|
117
|
+
);
|
|
118
|
+
const forms = Object.keys(resolvedForms).length > 0 ? resolvedForms : void 0;
|
|
119
|
+
const localeContext = {
|
|
120
|
+
current: locale,
|
|
121
|
+
default: defaultLocale,
|
|
122
|
+
enabled: enabledLocales && enabledLocales.length > 0 ? enabledLocales : Array.from(/* @__PURE__ */ new Set([defaultLocale, locale]))
|
|
123
|
+
};
|
|
124
|
+
if (editorActive && Editor) {
|
|
125
|
+
const bridgeOrigin = resolveBridgeOrigin(config.editorOrigin);
|
|
126
|
+
return /* @__PURE__ */ jsxRuntime.jsx(client.CmssyLocaleProvider, { value: localeContext, children: /* @__PURE__ */ jsxRuntime.jsx(
|
|
127
|
+
Editor,
|
|
128
|
+
{
|
|
129
|
+
page,
|
|
130
|
+
locale,
|
|
131
|
+
defaultLocale,
|
|
132
|
+
enabledLocales,
|
|
133
|
+
edit: { editorOrigin: bridgeOrigin },
|
|
134
|
+
forms
|
|
135
|
+
}
|
|
136
|
+
) });
|
|
137
|
+
}
|
|
138
|
+
let auth;
|
|
139
|
+
if (config.auth) {
|
|
140
|
+
try {
|
|
141
|
+
const user = await getCmssyUser(config);
|
|
142
|
+
auth = {
|
|
143
|
+
isAuthenticated: !!user,
|
|
144
|
+
member: user ? { recordId: user.recordId, email: user.email } : null
|
|
145
|
+
};
|
|
146
|
+
} catch {
|
|
147
|
+
auth = void 0;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
let workspace;
|
|
151
|
+
try {
|
|
152
|
+
workspace = {
|
|
153
|
+
id: await client$1.resolveWorkspaceId(),
|
|
154
|
+
slug: config.workspaceSlug
|
|
155
|
+
};
|
|
156
|
+
} catch {
|
|
157
|
+
workspace = void 0;
|
|
158
|
+
}
|
|
159
|
+
return /* @__PURE__ */ jsxRuntime.jsx(client.CmssyLocaleProvider, { value: localeContext, children: /* @__PURE__ */ jsxRuntime.jsx(
|
|
160
|
+
react.CmssyServerPage,
|
|
161
|
+
{
|
|
162
|
+
page,
|
|
163
|
+
blocks,
|
|
164
|
+
locale,
|
|
165
|
+
defaultLocale,
|
|
166
|
+
enabledLocales,
|
|
167
|
+
forms,
|
|
168
|
+
auth,
|
|
169
|
+
workspace
|
|
170
|
+
}
|
|
171
|
+
) });
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
function resolveBridgeOrigin(editorOrigin) {
|
|
175
|
+
const resolved = core.resolveEditorOrigin(editorOrigin);
|
|
176
|
+
const origins = (Array.isArray(resolved) ? resolved : [resolved]).map(
|
|
177
|
+
(origin) => core.toCspOrigin(origin.trim())
|
|
178
|
+
);
|
|
179
|
+
if (origins.length === 0) {
|
|
180
|
+
throw new Error("cmssy: editorOrigin must be set to frame the editor");
|
|
181
|
+
}
|
|
182
|
+
if (origins.includes("*") && !core.isDevelopment()) {
|
|
183
|
+
throw new Error(
|
|
184
|
+
"cmssy: editorOrigin '*' is only allowed in development; set a concrete editor origin (e.g. https://cmssy.io) for production"
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
return origins.length === 1 ? origins[0] : origins;
|
|
188
|
+
}
|
|
189
|
+
function DefaultNotFound() {
|
|
190
|
+
return /* @__PURE__ */ jsxRuntime.jsxs(
|
|
191
|
+
"main",
|
|
192
|
+
{
|
|
193
|
+
style: {
|
|
194
|
+
minHeight: "60vh",
|
|
195
|
+
display: "flex",
|
|
196
|
+
flexDirection: "column",
|
|
197
|
+
alignItems: "center",
|
|
198
|
+
justifyContent: "center",
|
|
199
|
+
gap: "0.5rem",
|
|
200
|
+
textAlign: "center",
|
|
201
|
+
padding: "2rem"
|
|
202
|
+
},
|
|
203
|
+
children: [
|
|
204
|
+
/* @__PURE__ */ jsxRuntime.jsx("h1", { style: { fontSize: "2rem", fontWeight: 700, margin: 0 }, children: "404" }),
|
|
205
|
+
/* @__PURE__ */ jsxRuntime.jsx("p", { style: { margin: 0, opacity: 0.7 }, children: "Page not found" })
|
|
206
|
+
]
|
|
207
|
+
}
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
function createCmssyNotFound(config, blocks, options) {
|
|
211
|
+
if (!Array.isArray(blocks)) {
|
|
212
|
+
throw new Error(
|
|
213
|
+
"cmssy: createCmssyNotFound(config, blocks) requires a blocks array \u2014 pass your defineBlock(...) array"
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
const clientConfig = {
|
|
217
|
+
apiUrl: config.apiUrl,
|
|
218
|
+
org: config.org,
|
|
219
|
+
workspaceSlug: config.workspaceSlug
|
|
220
|
+
};
|
|
221
|
+
const fallback = options?.fallback ?? /* @__PURE__ */ jsxRuntime.jsx(DefaultNotFound, {});
|
|
222
|
+
return async function CmssyNotFound() {
|
|
223
|
+
try {
|
|
224
|
+
const siteConfig = await react.fetchSiteConfig(clientConfig);
|
|
225
|
+
const notFoundPageId = siteConfig?.notFoundPageId;
|
|
226
|
+
if (!notFoundPageId) return fallback;
|
|
227
|
+
const page = await react.fetchPageById(clientConfig, notFoundPageId);
|
|
228
|
+
if (!page || page.blocks.length === 0) return fallback;
|
|
229
|
+
let locale;
|
|
230
|
+
let defaultLocale;
|
|
231
|
+
let enabledLocales = config.enabledLocales;
|
|
232
|
+
if (config.resolveLocale) {
|
|
233
|
+
defaultLocale = config.defaultLocale ?? "en";
|
|
234
|
+
locale = await config.resolveLocale();
|
|
235
|
+
} else {
|
|
236
|
+
const siteLocales = await react.resolveSiteLocales(clientConfig);
|
|
237
|
+
defaultLocale = config.defaultLocale ?? siteLocales.defaultLocale;
|
|
238
|
+
enabledLocales = config.enabledLocales ?? siteLocales.locales;
|
|
239
|
+
locale = defaultLocale;
|
|
240
|
+
}
|
|
241
|
+
const resolvedForms = await react.resolveForms(
|
|
242
|
+
clientConfig,
|
|
243
|
+
page.blocks,
|
|
244
|
+
locale,
|
|
245
|
+
defaultLocale
|
|
246
|
+
);
|
|
247
|
+
const forms = Object.keys(resolvedForms).length > 0 ? resolvedForms : void 0;
|
|
248
|
+
const localeContext = {
|
|
249
|
+
current: locale,
|
|
250
|
+
default: defaultLocale,
|
|
251
|
+
enabled: enabledLocales && enabledLocales.length > 0 ? enabledLocales : Array.from(/* @__PURE__ */ new Set([defaultLocale, locale]))
|
|
252
|
+
};
|
|
253
|
+
return /* @__PURE__ */ jsxRuntime.jsx(client.CmssyLocaleProvider, { value: localeContext, children: /* @__PURE__ */ jsxRuntime.jsx(
|
|
254
|
+
react.CmssyServerPage,
|
|
255
|
+
{
|
|
256
|
+
page,
|
|
257
|
+
blocks,
|
|
258
|
+
locale,
|
|
259
|
+
defaultLocale,
|
|
260
|
+
enabledLocales,
|
|
261
|
+
forms
|
|
262
|
+
}
|
|
263
|
+
) });
|
|
264
|
+
} catch (err) {
|
|
265
|
+
if (typeof console !== "undefined") {
|
|
266
|
+
console.warn("[cmssy] not-found page render failed", err);
|
|
267
|
+
}
|
|
268
|
+
return fallback;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
async function isCmssyEditMode() {
|
|
273
|
+
const h = await headers.headers();
|
|
274
|
+
return h.get(core.CMSSY_EDIT_HEADER) === "1";
|
|
275
|
+
}
|
|
276
|
+
async function getCmssyLocale(config, options) {
|
|
277
|
+
if (options?.path !== void 0) {
|
|
278
|
+
return core.localeForPath(config, options.path);
|
|
279
|
+
}
|
|
280
|
+
const { headers: headers2 } = await import('next/headers');
|
|
281
|
+
const headerList = await headers2();
|
|
282
|
+
const fromHeader = headerList.get(core.CMSSY_LOCALE_HEADER);
|
|
283
|
+
if (fromHeader) return fromHeader;
|
|
284
|
+
const { defaultLocale } = await core.resolveSiteLocales(config);
|
|
285
|
+
return defaultLocale;
|
|
286
|
+
}
|
|
287
|
+
async function CmssyChrome({
|
|
288
|
+
config,
|
|
289
|
+
blocks,
|
|
290
|
+
position,
|
|
291
|
+
page = "/",
|
|
292
|
+
editable
|
|
293
|
+
}) {
|
|
294
|
+
const editMode = await isCmssyEditMode();
|
|
295
|
+
const [groups, locale, siteLocales] = await Promise.all([
|
|
296
|
+
react.fetchLayouts(
|
|
297
|
+
config,
|
|
298
|
+
page,
|
|
299
|
+
editMode ? { previewSecret: config.draftSecret } : void 0
|
|
300
|
+
),
|
|
301
|
+
getCmssyLocale(config),
|
|
302
|
+
react.resolveSiteLocales(config)
|
|
303
|
+
]);
|
|
304
|
+
if (editMode && editable) {
|
|
305
|
+
const origin = core.resolveEditorOrigin(config.editorOrigin);
|
|
306
|
+
const Editable = editable;
|
|
307
|
+
return /* @__PURE__ */ jsxRuntime.jsx(
|
|
308
|
+
Editable,
|
|
309
|
+
{
|
|
310
|
+
groups,
|
|
311
|
+
position,
|
|
312
|
+
locale,
|
|
313
|
+
defaultLocale: siteLocales.defaultLocale,
|
|
314
|
+
enabledLocales: siteLocales.locales,
|
|
315
|
+
edit: {
|
|
316
|
+
editorOrigin: (Array.isArray(origin) ? origin[0] : origin) ?? ""
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
return /* @__PURE__ */ jsxRuntime.jsx(
|
|
322
|
+
react.CmssyServerLayout,
|
|
323
|
+
{
|
|
324
|
+
groups,
|
|
325
|
+
blocks,
|
|
326
|
+
position,
|
|
327
|
+
locale,
|
|
328
|
+
defaultLocale: siteLocales.defaultLocale,
|
|
329
|
+
enabledLocales: siteLocales.locales
|
|
330
|
+
}
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// src/seo-base-url.ts
|
|
335
|
+
function trimTrailingSlash(url) {
|
|
336
|
+
return url.replace(/\/+$/, "");
|
|
337
|
+
}
|
|
338
|
+
async function resolveSeoBaseUrl(config, option) {
|
|
339
|
+
if (typeof option === "function") return trimTrailingSlash(await option());
|
|
340
|
+
if (typeof option === "string" && option) return trimTrailingSlash(option);
|
|
341
|
+
if (config.siteUrl) return trimTrailingSlash(config.siteUrl);
|
|
342
|
+
const { headers: headers2 } = await import('next/headers');
|
|
343
|
+
const h = await headers2();
|
|
344
|
+
const host = h.get("host");
|
|
345
|
+
if (!host) return "";
|
|
346
|
+
const protocol = isLocalHost(host) ? "http" : "https";
|
|
347
|
+
return `${protocol}://${host}`;
|
|
348
|
+
}
|
|
349
|
+
function isLocalHost(host) {
|
|
350
|
+
const hostname = host.replace(/:\d+$/, "").replace(/^\[|\]$/g, "");
|
|
351
|
+
if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname === "::1") {
|
|
352
|
+
return true;
|
|
353
|
+
}
|
|
354
|
+
const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
|
|
355
|
+
if (!ipv4) return false;
|
|
356
|
+
const [a, b] = [Number(ipv4[1]), Number(ipv4[2])];
|
|
357
|
+
return a === 127 || a === 0 || a === 10 || a === 192 && b === 168 || a === 172 && b >= 16 && b <= 31;
|
|
358
|
+
}
|
|
359
|
+
function pick(value, locale, defaultLocale) {
|
|
360
|
+
if (!value) return "";
|
|
361
|
+
if (typeof value === "string") return value;
|
|
362
|
+
return value[locale] || value[defaultLocale] || Object.values(value)[0] || "";
|
|
363
|
+
}
|
|
364
|
+
async function buildCmssyMetadata(config, path, options = {}) {
|
|
365
|
+
const clientConfig = {
|
|
366
|
+
apiUrl: config.apiUrl,
|
|
367
|
+
org: config.org,
|
|
368
|
+
workspaceSlug: config.workspaceSlug
|
|
369
|
+
};
|
|
370
|
+
const [siteConfig, baseUrl] = await Promise.all([
|
|
371
|
+
react.fetchSiteConfig(clientConfig).catch(() => null),
|
|
372
|
+
resolveSeoBaseUrl(config, options.baseUrl)
|
|
373
|
+
]);
|
|
374
|
+
const { defaultLocale, locales: enabledLocales } = core.resolveSeoLocales(
|
|
375
|
+
config,
|
|
376
|
+
siteConfig
|
|
377
|
+
);
|
|
378
|
+
const segments = Array.isArray(path) ? path : path ? path.split("/").filter(Boolean) : void 0;
|
|
379
|
+
const fromPath = react.splitLocaleFromPath(segments, {
|
|
380
|
+
defaultLocale,
|
|
381
|
+
locales: enabledLocales
|
|
382
|
+
});
|
|
383
|
+
const locale = options.locale ?? (fromPath.locale !== defaultLocale ? fromPath.locale : await config.resolveLocale?.() ?? defaultLocale);
|
|
384
|
+
const slug = react.normalizeSlug(fromPath.path);
|
|
385
|
+
const meta = await react.fetchPageMeta(clientConfig, slug).catch(() => null);
|
|
386
|
+
const siteName = pick(siteConfig?.siteName, locale, defaultLocale) || siteConfig?.branding?.brandName || void 0;
|
|
387
|
+
const title = pick(meta?.seoTitle, locale, defaultLocale) || pick(meta?.displayName, locale, defaultLocale) || siteName || "";
|
|
388
|
+
const description = pick(meta?.seoDescription, locale, defaultLocale);
|
|
389
|
+
const keywords = meta?.seoKeywords?.length ? meta.seoKeywords : void 0;
|
|
390
|
+
const image = options.image ?? siteConfig?.branding?.ogImageUrl ?? void 0;
|
|
391
|
+
const canonical = baseUrl ? `${baseUrl}${core.localizedPath(slug, locale, defaultLocale)}` : void 0;
|
|
392
|
+
const languages = baseUrl && enabledLocales.length > 1 ? {
|
|
393
|
+
...Object.fromEntries(
|
|
394
|
+
enabledLocales.map((l) => [
|
|
395
|
+
l,
|
|
396
|
+
`${baseUrl}${core.localizedPath(slug, l, defaultLocale)}`
|
|
397
|
+
])
|
|
398
|
+
),
|
|
399
|
+
// What to serve a reader whose language none of these match.
|
|
400
|
+
"x-default": `${baseUrl}${core.localizedPath(slug, defaultLocale, defaultLocale)}`
|
|
401
|
+
} : void 0;
|
|
402
|
+
return {
|
|
403
|
+
...baseUrl ? { metadataBase: new URL(baseUrl) } : {},
|
|
404
|
+
...title ? { title } : {},
|
|
405
|
+
...description ? { description } : {},
|
|
406
|
+
...keywords ? { keywords } : {},
|
|
407
|
+
...canonical || languages ? {
|
|
408
|
+
alternates: {
|
|
409
|
+
...canonical ? { canonical } : {},
|
|
410
|
+
...languages ? { languages } : {}
|
|
411
|
+
}
|
|
412
|
+
} : {},
|
|
413
|
+
openGraph: {
|
|
414
|
+
...title ? { title } : {},
|
|
415
|
+
...description ? { description } : {},
|
|
416
|
+
...canonical ? { url: canonical } : {},
|
|
417
|
+
...siteName ? { siteName } : {},
|
|
418
|
+
type: options.ogType ?? "website",
|
|
419
|
+
locale,
|
|
420
|
+
...image ? { images: [{ url: image }] } : {}
|
|
421
|
+
},
|
|
422
|
+
twitter: {
|
|
423
|
+
card: image ? options.twitterCard ?? "summary_large_image" : "summary",
|
|
424
|
+
...title ? { title } : {},
|
|
425
|
+
...description ? { description } : {},
|
|
426
|
+
...image ? { images: [image] } : {}
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// src/create-cmssy-robots.ts
|
|
432
|
+
function createCmssyRobots(config, options = {}) {
|
|
433
|
+
return async function robots() {
|
|
434
|
+
const baseUrl = await resolveSeoBaseUrl(config, options.baseUrl);
|
|
435
|
+
const rules = options.rules ?? {
|
|
436
|
+
userAgent: "*",
|
|
437
|
+
allow: "/",
|
|
438
|
+
disallow: options.disallow ?? ["/api/"]
|
|
439
|
+
};
|
|
440
|
+
const includeSitemap = options.sitemap !== false && Boolean(baseUrl);
|
|
441
|
+
return {
|
|
442
|
+
rules,
|
|
443
|
+
...includeSitemap ? { sitemap: `${baseUrl}/sitemap.xml` } : {},
|
|
444
|
+
...options.host && baseUrl ? { host: baseUrl } : {}
|
|
445
|
+
};
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
function createCmssySitemap(config, options = {}) {
|
|
449
|
+
const clientConfig = {
|
|
450
|
+
apiUrl: config.apiUrl,
|
|
451
|
+
org: config.org,
|
|
452
|
+
workspaceSlug: config.workspaceSlug
|
|
453
|
+
};
|
|
454
|
+
return async function sitemap() {
|
|
455
|
+
let pages = [];
|
|
456
|
+
try {
|
|
457
|
+
pages = await react.fetchPages(clientConfig);
|
|
458
|
+
} catch (err) {
|
|
459
|
+
if (typeof console !== "undefined") {
|
|
460
|
+
console.warn("[cmssy] sitemap page fetch failed", err);
|
|
461
|
+
}
|
|
462
|
+
pages = [];
|
|
463
|
+
}
|
|
464
|
+
let siteConfig = null;
|
|
465
|
+
try {
|
|
466
|
+
siteConfig = await react.fetchSiteConfig(clientConfig);
|
|
467
|
+
} catch {
|
|
468
|
+
siteConfig = null;
|
|
469
|
+
}
|
|
470
|
+
const notFoundPageId = siteConfig?.notFoundPageId ?? null;
|
|
471
|
+
const baseUrl = await resolveSeoBaseUrl(config, options.baseUrl);
|
|
472
|
+
const { defaultLocale, locales } = core.resolveSeoLocales(config, siteConfig);
|
|
473
|
+
const excluded = new Set((options.excludeSlugs ?? []).map(core.normalizeSlug));
|
|
474
|
+
const languagesFor = (slug) => locales.length > 1 ? {
|
|
475
|
+
languages: {
|
|
476
|
+
...Object.fromEntries(
|
|
477
|
+
locales.map((locale) => [
|
|
478
|
+
locale,
|
|
479
|
+
`${baseUrl}${core.localizedPath(slug, locale, defaultLocale)}`
|
|
480
|
+
])
|
|
481
|
+
),
|
|
482
|
+
"x-default": `${baseUrl}${core.localizedPath(slug, defaultLocale, defaultLocale)}`
|
|
483
|
+
}
|
|
484
|
+
} : void 0;
|
|
485
|
+
const entries = pages.map((page) => ({ ...page, slug: core.normalizeSlug(page.slug) })).filter((page) => page.id !== notFoundPageId && !excluded.has(page.slug)).flatMap((page) => {
|
|
486
|
+
const lastModified = page.updatedAt ?? page.publishedAt ?? void 0;
|
|
487
|
+
const alternates = languagesFor(page.slug);
|
|
488
|
+
return locales.map((locale) => ({
|
|
489
|
+
url: `${baseUrl}${core.localizedPath(page.slug, locale, defaultLocale)}`,
|
|
490
|
+
...lastModified ? { lastModified: new Date(lastModified) } : {},
|
|
491
|
+
...alternates ? { alternates } : {}
|
|
492
|
+
}));
|
|
493
|
+
});
|
|
494
|
+
if (!options.extra) return entries;
|
|
495
|
+
const extra = typeof options.extra === "function" ? await options.extra({ baseUrl, defaultLocale, locales }) : options.extra;
|
|
496
|
+
return [...entries, ...extra];
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
var MAX_BODY_CHARS = 16 * 1024;
|
|
500
|
+
function json(body, status = 200) {
|
|
501
|
+
return new Response(JSON.stringify(body), {
|
|
502
|
+
status,
|
|
503
|
+
headers: {
|
|
504
|
+
"content-type": "application/json",
|
|
505
|
+
"cache-control": "no-store"
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
async function readBody(request) {
|
|
510
|
+
const contentType = request.headers.get("content-type") ?? "";
|
|
511
|
+
if (!contentType.toLowerCase().includes("application/json")) {
|
|
512
|
+
throw new Error("content-type must be application/json");
|
|
513
|
+
}
|
|
514
|
+
const text = await request.text();
|
|
515
|
+
if (text.length > MAX_BODY_CHARS) {
|
|
516
|
+
throw new Error("body too large");
|
|
517
|
+
}
|
|
518
|
+
if (!text) return {};
|
|
519
|
+
const parsed = JSON.parse(text);
|
|
520
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
521
|
+
throw new Error("body must be a JSON object");
|
|
522
|
+
}
|
|
523
|
+
return parsed;
|
|
524
|
+
}
|
|
525
|
+
function str(value) {
|
|
526
|
+
return typeof value === "string" ? value : "";
|
|
527
|
+
}
|
|
528
|
+
function plainObject(value) {
|
|
529
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
530
|
+
return value;
|
|
531
|
+
}
|
|
532
|
+
async function readSession(config, auth) {
|
|
533
|
+
const jar = await headers.cookies();
|
|
534
|
+
const raw = jar.get(core.CMSSY_SESSION_COOKIE)?.value;
|
|
535
|
+
if (!raw) return null;
|
|
536
|
+
return core.openSession(raw, auth.sessionSecret, config.workspaceSlug);
|
|
537
|
+
}
|
|
538
|
+
async function writeSession(config, auth, payload) {
|
|
539
|
+
const sealed = await core.sealSession(
|
|
540
|
+
payload,
|
|
541
|
+
auth.sessionSecret,
|
|
542
|
+
config.workspaceSlug
|
|
543
|
+
);
|
|
544
|
+
const jar = await headers.cookies();
|
|
545
|
+
jar.set(core.CMSSY_SESSION_COOKIE, sealed, core.sessionCookieOptions());
|
|
546
|
+
}
|
|
547
|
+
async function clearSession() {
|
|
548
|
+
const jar = await headers.cookies();
|
|
549
|
+
jar.set(core.CMSSY_SESSION_COOKIE, "", {
|
|
550
|
+
...core.sessionCookieOptions(),
|
|
551
|
+
maxAge: 0
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
async function refreshSession(config, auth, session) {
|
|
555
|
+
const result = await core.backendRefresh(config, session.refreshToken);
|
|
556
|
+
const payload = core.toSessionPayload(result);
|
|
557
|
+
if (!payload) {
|
|
558
|
+
await clearSession();
|
|
559
|
+
return null;
|
|
560
|
+
}
|
|
561
|
+
await writeSession(config, auth, payload);
|
|
562
|
+
return payload;
|
|
563
|
+
}
|
|
564
|
+
function createCmssyAuthRoute(config) {
|
|
565
|
+
const auth = core.assertAuthConfig(config);
|
|
566
|
+
async function handleSignIn(body) {
|
|
567
|
+
const identity = str(body.identity);
|
|
568
|
+
const password = str(body.password);
|
|
569
|
+
if (!identity || !password) {
|
|
570
|
+
return json({ ok: false, message: "Invalid credentials." }, 400);
|
|
571
|
+
}
|
|
572
|
+
const result = await core.backendSignIn(
|
|
573
|
+
config,
|
|
574
|
+
auth.modelSlug,
|
|
575
|
+
identity,
|
|
576
|
+
password
|
|
577
|
+
);
|
|
578
|
+
const payload = core.toSessionPayload(result);
|
|
579
|
+
if (!payload) {
|
|
580
|
+
return json({ ok: false, message: result.message }, 401);
|
|
581
|
+
}
|
|
582
|
+
await writeSession(config, auth, payload);
|
|
583
|
+
return json({ ok: true, user: payload.user });
|
|
584
|
+
}
|
|
585
|
+
async function handleRegister(body) {
|
|
586
|
+
const identity = str(body.identity);
|
|
587
|
+
const password = str(body.password);
|
|
588
|
+
if (!identity || !password) {
|
|
589
|
+
return json({ ok: false, message: "Invalid input." }, 400);
|
|
590
|
+
}
|
|
591
|
+
const result = await core.backendRegister(
|
|
592
|
+
config,
|
|
593
|
+
auth.modelSlug,
|
|
594
|
+
identity,
|
|
595
|
+
password,
|
|
596
|
+
plainObject(body.fields)
|
|
597
|
+
);
|
|
598
|
+
return json({ ok: result.success, message: result.message });
|
|
599
|
+
}
|
|
600
|
+
async function handleSignOut() {
|
|
601
|
+
const session = await readSession(config, auth);
|
|
602
|
+
if (session) {
|
|
603
|
+
await core.backendSignOut(config, session.refreshToken);
|
|
604
|
+
}
|
|
605
|
+
await clearSession();
|
|
606
|
+
return json({ ok: true });
|
|
607
|
+
}
|
|
608
|
+
async function handleSignOutEverywhere() {
|
|
609
|
+
let session = await readSession(config, auth);
|
|
610
|
+
if (session && core.isAccessExpired(session)) {
|
|
611
|
+
session = await refreshSession(config, auth, session);
|
|
612
|
+
}
|
|
613
|
+
if (session) {
|
|
614
|
+
await core.backendSignOutEverywhere(config, session.accessToken);
|
|
615
|
+
}
|
|
616
|
+
await clearSession();
|
|
617
|
+
return json({ ok: true });
|
|
618
|
+
}
|
|
619
|
+
async function handleRefresh() {
|
|
620
|
+
const session = await readSession(config, auth);
|
|
621
|
+
if (!session) {
|
|
622
|
+
return json({ ok: false, user: null }, 401);
|
|
623
|
+
}
|
|
624
|
+
const refreshed = await refreshSession(config, auth, session);
|
|
625
|
+
if (!refreshed) {
|
|
626
|
+
return json({ ok: false, user: null }, 401);
|
|
627
|
+
}
|
|
628
|
+
return json({ ok: true, user: refreshed.user });
|
|
629
|
+
}
|
|
630
|
+
async function handleMe() {
|
|
631
|
+
let session = await readSession(config, auth);
|
|
632
|
+
if (session && core.isAccessExpired(session)) {
|
|
633
|
+
session = await refreshSession(config, auth, session);
|
|
634
|
+
}
|
|
635
|
+
return json({ user: session?.user ?? null });
|
|
636
|
+
}
|
|
637
|
+
async function handleForgotPassword(body) {
|
|
638
|
+
const identity = str(body.identity);
|
|
639
|
+
if (!identity) {
|
|
640
|
+
return json({ ok: false, message: "Invalid input." }, 400);
|
|
641
|
+
}
|
|
642
|
+
const result = await core.backendForgotPassword(
|
|
643
|
+
config,
|
|
644
|
+
auth.modelSlug,
|
|
645
|
+
identity
|
|
646
|
+
);
|
|
647
|
+
return json({ ok: result.success, message: result.message });
|
|
648
|
+
}
|
|
649
|
+
async function handleResetPassword(body) {
|
|
650
|
+
const token = str(body.token);
|
|
651
|
+
const newPassword = str(body.newPassword);
|
|
652
|
+
if (!token || !newPassword) {
|
|
653
|
+
return json({ ok: false, message: "Invalid input." }, 400);
|
|
654
|
+
}
|
|
655
|
+
const result = await core.backendResetPassword(config, token, newPassword);
|
|
656
|
+
return json({ ok: result.success, message: result.message });
|
|
657
|
+
}
|
|
658
|
+
async function handleVerifyEmail(body) {
|
|
659
|
+
const token = str(body.token);
|
|
660
|
+
if (!token) {
|
|
661
|
+
return json({ ok: false, message: "Invalid input." }, 400);
|
|
662
|
+
}
|
|
663
|
+
const result = await core.backendVerifyEmail(config, token);
|
|
664
|
+
return json({ ok: result.success, message: result.message });
|
|
665
|
+
}
|
|
666
|
+
return {
|
|
667
|
+
async POST(request, context) {
|
|
668
|
+
const { action } = await context.params;
|
|
669
|
+
let body;
|
|
670
|
+
try {
|
|
671
|
+
body = await readBody(request);
|
|
672
|
+
} catch {
|
|
673
|
+
return json({ ok: false, message: "Invalid request body." }, 400);
|
|
674
|
+
}
|
|
675
|
+
try {
|
|
676
|
+
switch (action) {
|
|
677
|
+
case "sign-in":
|
|
678
|
+
return await handleSignIn(body);
|
|
679
|
+
case "register":
|
|
680
|
+
return await handleRegister(body);
|
|
681
|
+
case "sign-out":
|
|
682
|
+
return await handleSignOut();
|
|
683
|
+
case "sign-out-everywhere":
|
|
684
|
+
return await handleSignOutEverywhere();
|
|
685
|
+
case "refresh":
|
|
686
|
+
return await handleRefresh();
|
|
687
|
+
case "forgot-password":
|
|
688
|
+
return await handleForgotPassword(body);
|
|
689
|
+
case "reset-password":
|
|
690
|
+
return await handleResetPassword(body);
|
|
691
|
+
case "verify-email":
|
|
692
|
+
return await handleVerifyEmail(body);
|
|
693
|
+
default:
|
|
694
|
+
return json({ ok: false, message: "Not found." }, 404);
|
|
695
|
+
}
|
|
696
|
+
} catch {
|
|
697
|
+
return json({ ok: false, message: "Something went wrong." }, 500);
|
|
698
|
+
}
|
|
699
|
+
},
|
|
700
|
+
async GET(_request, context) {
|
|
701
|
+
const { action } = await context.params;
|
|
702
|
+
if (action !== "me") {
|
|
703
|
+
return json({ ok: false, message: "Not found." }, 404);
|
|
704
|
+
}
|
|
705
|
+
try {
|
|
706
|
+
return await handleMe();
|
|
707
|
+
} catch {
|
|
708
|
+
return json({ user: null });
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
var CMSSY_CART_COOKIE = "cmssy_cart";
|
|
714
|
+
var CART_MAX_AGE_SECONDS = 30 * 24 * 60 * 60;
|
|
715
|
+
var CART_TOKEN_BYTES = 32;
|
|
716
|
+
var MAX_BODY_CHARS2 = 16 * 1024;
|
|
717
|
+
function json2(body, status = 200) {
|
|
718
|
+
return new Response(JSON.stringify(body), {
|
|
719
|
+
status,
|
|
720
|
+
headers: {
|
|
721
|
+
"content-type": "application/json",
|
|
722
|
+
"cache-control": "no-store"
|
|
723
|
+
}
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
function cartCookieOptions() {
|
|
727
|
+
return {
|
|
728
|
+
httpOnly: true,
|
|
729
|
+
secure: process.env.NODE_ENV !== "development",
|
|
730
|
+
sameSite: "lax",
|
|
731
|
+
path: "/",
|
|
732
|
+
maxAge: CART_MAX_AGE_SECONDS
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
function mintToken() {
|
|
736
|
+
const bytes = new Uint8Array(CART_TOKEN_BYTES);
|
|
737
|
+
crypto.getRandomValues(bytes);
|
|
738
|
+
let binary = "";
|
|
739
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
740
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
741
|
+
}
|
|
742
|
+
async function readBody2(request) {
|
|
743
|
+
const contentType = request.headers.get("content-type") ?? "";
|
|
744
|
+
if (!contentType.toLowerCase().includes("application/json")) {
|
|
745
|
+
throw new Error("content-type must be application/json");
|
|
746
|
+
}
|
|
747
|
+
const text = await request.text();
|
|
748
|
+
if (text.length > MAX_BODY_CHARS2) throw new Error("body too large");
|
|
749
|
+
if (!text) return {};
|
|
750
|
+
const parsed = JSON.parse(text);
|
|
751
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
752
|
+
throw new Error("body must be a JSON object");
|
|
753
|
+
}
|
|
754
|
+
return parsed;
|
|
755
|
+
}
|
|
756
|
+
function str2(value) {
|
|
757
|
+
return typeof value === "string" ? value : "";
|
|
758
|
+
}
|
|
759
|
+
function plainObject2(value) {
|
|
760
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
761
|
+
return value;
|
|
762
|
+
}
|
|
763
|
+
function optionalStr(value) {
|
|
764
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
765
|
+
}
|
|
766
|
+
var ADDRESS_REQUIRED = [
|
|
767
|
+
"name",
|
|
768
|
+
"line1",
|
|
769
|
+
"postalCode",
|
|
770
|
+
"city",
|
|
771
|
+
"country"
|
|
772
|
+
];
|
|
773
|
+
var CmssyAddressError = class extends Error {
|
|
774
|
+
constructor(missing) {
|
|
775
|
+
super(
|
|
776
|
+
`cmssy: shippingAddress is missing required field(s): ${missing.join(
|
|
777
|
+
", "
|
|
778
|
+
)}. Expected { name, line1, postalCode, city, country } (plus optional company, line2, region, phone, vatId).`
|
|
779
|
+
);
|
|
780
|
+
this.missing = missing;
|
|
781
|
+
this.name = "CmssyAddressError";
|
|
782
|
+
}
|
|
783
|
+
missing;
|
|
784
|
+
};
|
|
785
|
+
function shippingAddress(value) {
|
|
786
|
+
if (value === void 0 || value === null) return null;
|
|
787
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
788
|
+
throw new CmssyAddressError([...ADDRESS_REQUIRED]);
|
|
789
|
+
}
|
|
790
|
+
const raw = value;
|
|
791
|
+
const missing = ADDRESS_REQUIRED.filter((key) => !optionalStr(raw[key]));
|
|
792
|
+
if (missing.length > 0) throw new CmssyAddressError(missing);
|
|
793
|
+
return {
|
|
794
|
+
name: optionalStr(raw.name),
|
|
795
|
+
company: optionalStr(raw.company),
|
|
796
|
+
line1: optionalStr(raw.line1),
|
|
797
|
+
line2: optionalStr(raw.line2),
|
|
798
|
+
postalCode: optionalStr(raw.postalCode),
|
|
799
|
+
city: optionalStr(raw.city),
|
|
800
|
+
region: optionalStr(raw.region),
|
|
801
|
+
country: optionalStr(raw.country),
|
|
802
|
+
phone: optionalStr(raw.phone),
|
|
803
|
+
vatId: optionalStr(raw.vatId)
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
function createCmssyCartRoute(config) {
|
|
807
|
+
async function ensureCartToken() {
|
|
808
|
+
const jar = await headers.cookies();
|
|
809
|
+
const existing = jar.get(CMSSY_CART_COOKIE)?.value;
|
|
810
|
+
if (existing) return existing;
|
|
811
|
+
const token = mintToken();
|
|
812
|
+
jar.set(CMSSY_CART_COOKIE, token, cartCookieOptions());
|
|
813
|
+
return token;
|
|
814
|
+
}
|
|
815
|
+
async function clearCartToken() {
|
|
816
|
+
const jar = await headers.cookies();
|
|
817
|
+
jar.set(CMSSY_CART_COOKIE, "", { ...cartCookieOptions(), maxAge: 0 });
|
|
818
|
+
}
|
|
819
|
+
async function memberAccessToken() {
|
|
820
|
+
if (!config.auth) return void 0;
|
|
821
|
+
const jar = await headers.cookies();
|
|
822
|
+
const raw = jar.get(core.CMSSY_SESSION_COOKIE)?.value;
|
|
823
|
+
if (!raw) return void 0;
|
|
824
|
+
const session = await core.openSession(
|
|
825
|
+
raw,
|
|
826
|
+
config.auth.sessionSecret,
|
|
827
|
+
config.workspaceSlug
|
|
828
|
+
);
|
|
829
|
+
if (!session || core.isAccessExpired(session)) return void 0;
|
|
830
|
+
return session.accessToken;
|
|
831
|
+
}
|
|
832
|
+
async function buildContext() {
|
|
833
|
+
const cartToken = await ensureCartToken();
|
|
834
|
+
const accessToken = await memberAccessToken();
|
|
835
|
+
return accessToken ? { cartToken, accessToken } : { cartToken };
|
|
836
|
+
}
|
|
837
|
+
return {
|
|
838
|
+
async POST(request, context) {
|
|
839
|
+
const { action } = await context.params;
|
|
840
|
+
let body;
|
|
841
|
+
try {
|
|
842
|
+
body = await readBody2(request);
|
|
843
|
+
} catch {
|
|
844
|
+
return json2({ message: "Invalid request body." }, 400);
|
|
845
|
+
}
|
|
846
|
+
try {
|
|
847
|
+
const ctx = await buildContext();
|
|
848
|
+
switch (action) {
|
|
849
|
+
case "cart":
|
|
850
|
+
return json2({ cart: await core.backendGetCart(config, ctx) });
|
|
851
|
+
case "add":
|
|
852
|
+
return json2({
|
|
853
|
+
cart: await core.backendAddToCart(config, ctx, {
|
|
854
|
+
recordId: str2(body.recordId),
|
|
855
|
+
quantity: typeof body.quantity === "number" ? body.quantity : 1,
|
|
856
|
+
variantSelections: body.variantSelections,
|
|
857
|
+
notes: typeof body.notes === "string" ? body.notes : void 0
|
|
858
|
+
})
|
|
859
|
+
});
|
|
860
|
+
case "update":
|
|
861
|
+
return json2({
|
|
862
|
+
cart: await core.backendUpdateItem(config, ctx, {
|
|
863
|
+
itemId: str2(body.itemId),
|
|
864
|
+
quantity: typeof body.quantity === "number" ? body.quantity : 0
|
|
865
|
+
})
|
|
866
|
+
});
|
|
867
|
+
case "remove":
|
|
868
|
+
return json2({
|
|
869
|
+
cart: await core.backendRemoveItem(config, ctx, str2(body.itemId))
|
|
870
|
+
});
|
|
871
|
+
case "clear":
|
|
872
|
+
return json2({ cart: await core.backendClearCart(config, ctx) });
|
|
873
|
+
case "apply-discount":
|
|
874
|
+
return json2({
|
|
875
|
+
cart: await core.backendApplyDiscount(config, ctx, str2(body.code))
|
|
876
|
+
});
|
|
877
|
+
case "remove-discount":
|
|
878
|
+
return json2({ cart: await core.backendRemoveDiscount(config, ctx) });
|
|
879
|
+
case "set-shipping":
|
|
880
|
+
return json2({
|
|
881
|
+
cart: await core.backendSetShippingMethod(
|
|
882
|
+
config,
|
|
883
|
+
ctx,
|
|
884
|
+
optionalStr(body.shippingMethodId)
|
|
885
|
+
)
|
|
886
|
+
});
|
|
887
|
+
case "merge":
|
|
888
|
+
return json2({ cart: await core.backendMergeCart(config, ctx) });
|
|
889
|
+
case "checkout": {
|
|
890
|
+
const order = await core.backendCheckout(config, ctx, {
|
|
891
|
+
customerEmail: str2(body.customerEmail),
|
|
892
|
+
poNumber: optionalStr(body.poNumber),
|
|
893
|
+
customerNote: optionalStr(body.customerNote),
|
|
894
|
+
shippingAddress: shippingAddress(body.shippingAddress)
|
|
895
|
+
});
|
|
896
|
+
await clearCartToken();
|
|
897
|
+
return json2({ order });
|
|
898
|
+
}
|
|
899
|
+
case "product":
|
|
900
|
+
return json2({
|
|
901
|
+
product: await core.backendProduct(
|
|
902
|
+
config,
|
|
903
|
+
ctx,
|
|
904
|
+
str2(body.modelSlug),
|
|
905
|
+
plainObject2(body.filter)
|
|
906
|
+
)
|
|
907
|
+
});
|
|
908
|
+
default:
|
|
909
|
+
return json2({ message: "Not found." }, 404);
|
|
910
|
+
}
|
|
911
|
+
} catch (err) {
|
|
912
|
+
if (err instanceof CmssyAddressError) {
|
|
913
|
+
return json2({ message: err.message, missing: err.missing }, 400);
|
|
914
|
+
}
|
|
915
|
+
return json2(
|
|
916
|
+
{
|
|
917
|
+
message: err instanceof Error ? err.message : "Commerce request failed"
|
|
918
|
+
},
|
|
919
|
+
502
|
|
920
|
+
);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
var DEFAULT_LIMIT = 20;
|
|
926
|
+
var MAX_LIMIT = 100;
|
|
927
|
+
function json3(body, status = 200) {
|
|
928
|
+
return new Response(JSON.stringify(body), {
|
|
929
|
+
status,
|
|
930
|
+
headers: {
|
|
931
|
+
"content-type": "application/json",
|
|
932
|
+
"cache-control": "no-store"
|
|
933
|
+
}
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
function createCmssyOrdersRoute(config) {
|
|
937
|
+
async function memberAccessToken() {
|
|
938
|
+
if (!config.auth) return void 0;
|
|
939
|
+
const jar = await headers.cookies();
|
|
940
|
+
const raw = jar.get(core.CMSSY_SESSION_COOKIE)?.value;
|
|
941
|
+
if (!raw) return void 0;
|
|
942
|
+
const session = await core.openSession(
|
|
943
|
+
raw,
|
|
944
|
+
config.auth.sessionSecret,
|
|
945
|
+
config.workspaceSlug
|
|
946
|
+
);
|
|
947
|
+
if (!session || core.isAccessExpired(session)) return void 0;
|
|
948
|
+
return session.accessToken;
|
|
949
|
+
}
|
|
950
|
+
return {
|
|
951
|
+
async GET(request) {
|
|
952
|
+
const accessToken = await memberAccessToken();
|
|
953
|
+
if (!accessToken) {
|
|
954
|
+
return json3({ message: "Not signed in." }, 401);
|
|
955
|
+
}
|
|
956
|
+
const url = new URL(request.url);
|
|
957
|
+
try {
|
|
958
|
+
const id = url.searchParams.get("id");
|
|
959
|
+
if (id) {
|
|
960
|
+
return json3({ order: await core.backendMyOrder(config, accessToken, id) });
|
|
961
|
+
}
|
|
962
|
+
const skip = Math.max(
|
|
963
|
+
0,
|
|
964
|
+
Math.floor(Number(url.searchParams.get("skip")) || 0)
|
|
965
|
+
);
|
|
966
|
+
const limitParam = Math.floor(Number(url.searchParams.get("limit")));
|
|
967
|
+
const limit = Number.isFinite(limitParam) && limitParam > 0 ? Math.min(limitParam, MAX_LIMIT) : DEFAULT_LIMIT;
|
|
968
|
+
const result = await core.backendMyOrders(config, accessToken, {
|
|
969
|
+
skip,
|
|
970
|
+
limit
|
|
971
|
+
});
|
|
972
|
+
return json3(result);
|
|
973
|
+
} catch (err) {
|
|
974
|
+
return json3(
|
|
975
|
+
{ message: err instanceof Error ? err.message : "Orders error" },
|
|
976
|
+
502
|
|
977
|
+
);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
var MIN_SECRET_LENGTH = 16;
|
|
983
|
+
function safeRedirect(redirect2, fallback) {
|
|
984
|
+
if (!redirect2 || !redirect2.startsWith("/")) return fallback;
|
|
985
|
+
if (redirect2.startsWith("//") || redirect2.includes("\\")) return fallback;
|
|
986
|
+
try {
|
|
987
|
+
if (new URL(redirect2, "https://cmssy.invalid").origin !== "https://cmssy.invalid") {
|
|
988
|
+
return fallback;
|
|
989
|
+
}
|
|
990
|
+
} catch {
|
|
991
|
+
return fallback;
|
|
992
|
+
}
|
|
993
|
+
return redirect2;
|
|
994
|
+
}
|
|
995
|
+
function createDraftRoute(config) {
|
|
996
|
+
const fallbackRedirect = config.defaultRedirect ?? "/";
|
|
997
|
+
if (safeRedirect(fallbackRedirect, "/") !== fallbackRedirect) {
|
|
998
|
+
throw new Error(
|
|
999
|
+
"cmssy: defaultRedirect must be a same-origin path starting with '/'"
|
|
1000
|
+
);
|
|
1001
|
+
}
|
|
1002
|
+
return async function GET(request) {
|
|
1003
|
+
const url = new URL(request.url);
|
|
1004
|
+
if (url.searchParams.get("disable") === "1") {
|
|
1005
|
+
const draft2 = await headers.draftMode();
|
|
1006
|
+
draft2.disable();
|
|
1007
|
+
navigation.redirect(
|
|
1008
|
+
safeRedirect(url.searchParams.get("redirect"), fallbackRedirect)
|
|
1009
|
+
);
|
|
1010
|
+
}
|
|
1011
|
+
if (config.draftSecret.length < MIN_SECRET_LENGTH) {
|
|
1012
|
+
return new Response(
|
|
1013
|
+
`cmssy: draftSecret must be at least ${MIN_SECRET_LENGTH} characters`,
|
|
1014
|
+
{ status: 500 }
|
|
1015
|
+
);
|
|
1016
|
+
}
|
|
1017
|
+
const secret = url.searchParams.get("secret");
|
|
1018
|
+
if (!secret || !await core.cmssySecretsMatch(secret, config.draftSecret)) {
|
|
1019
|
+
return new Response("Invalid draft secret", { status: 401 });
|
|
1020
|
+
}
|
|
1021
|
+
const location = safeRedirect(
|
|
1022
|
+
url.searchParams.get("redirect"),
|
|
1023
|
+
fallbackRedirect
|
|
1024
|
+
);
|
|
1025
|
+
const draft = await headers.draftMode();
|
|
1026
|
+
draft.enable();
|
|
1027
|
+
navigation.redirect(location);
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
async function requestLocale(config) {
|
|
1031
|
+
try {
|
|
1032
|
+
return await getCmssyLocale(config);
|
|
1033
|
+
} catch {
|
|
1034
|
+
return void 0;
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
async function fetchProducts(config, options) {
|
|
1038
|
+
const locale = options.locale ?? await requestLocale(config);
|
|
1039
|
+
return core.fetchProducts(config, { ...options, locale });
|
|
1040
|
+
}
|
|
1041
|
+
async function fetchProduct(config, options) {
|
|
1042
|
+
const locale = options.locale ?? await requestLocale(config);
|
|
1043
|
+
return core.fetchProduct(config, { ...options, locale });
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
exports.CMSSY_CART_COOKIE = CMSSY_CART_COOKIE;
|
|
1047
|
+
exports.CmssyChrome = CmssyChrome;
|
|
1048
|
+
exports.buildCmssyMetadata = buildCmssyMetadata;
|
|
1049
|
+
exports.createCmssyAuthRoute = createCmssyAuthRoute;
|
|
1050
|
+
exports.createCmssyCartRoute = createCmssyCartRoute;
|
|
1051
|
+
exports.createCmssyEditPage = createCmssyEditPage;
|
|
1052
|
+
exports.createCmssyNotFound = createCmssyNotFound;
|
|
1053
|
+
exports.createCmssyOrdersRoute = createCmssyOrdersRoute;
|
|
1054
|
+
exports.createCmssyPage = createCmssyPage;
|
|
1055
|
+
exports.createCmssyRobots = createCmssyRobots;
|
|
1056
|
+
exports.createCmssySitemap = createCmssySitemap;
|
|
1057
|
+
exports.createDraftRoute = createDraftRoute;
|
|
1058
|
+
exports.fetchProduct = fetchProduct;
|
|
1059
|
+
exports.fetchProducts = fetchProducts;
|
|
1060
|
+
exports.getCmssyAccessToken = getCmssyAccessToken;
|
|
1061
|
+
exports.getCmssyLocale = getCmssyLocale;
|
|
1062
|
+
exports.getCmssyUser = getCmssyUser;
|
|
1063
|
+
exports.isCmssyEditMode = isCmssyEditMode;
|