@justanarthur/payload-www 0.3.5 → 1.2.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.
Files changed (63) hide show
  1. package/README.md +317 -307
  2. package/dist/access.d.ts +2 -2
  3. package/dist/access.js +3 -17
  4. package/dist/blocks.d.ts +7 -12
  5. package/dist/blocks.js +24 -43
  6. package/dist/cli.js +201 -0
  7. package/dist/collections.d.ts +33 -225
  8. package/dist/collections.js +185 -639
  9. package/dist/config.d.ts +19 -105
  10. package/dist/config.js +257 -855
  11. package/dist/fields.d.ts +4 -46
  12. package/dist/fields.js +177 -53
  13. package/dist/imagehash.js +0 -15
  14. package/dist/import-map-provider.d.ts +0 -16
  15. package/dist/import-map-provider.js +0 -15
  16. package/dist/metadata.d.ts +24 -89
  17. package/dist/metadata.js +123 -255
  18. package/dist/pages.d.ts +37 -319
  19. package/dist/pages.js +349 -964
  20. package/dist/render-pages.d.ts +70 -565
  21. package/dist/render-pages.js +464 -1477
  22. package/dist/sitemap.d.ts +10 -0
  23. package/dist/sitemap.js +337 -0
  24. package/dist/translator.js +0 -15
  25. package/dist/utils.d.ts +10 -12
  26. package/dist/utils.js +18 -41
  27. package/package.json +81 -178
  28. package/dist/components.d.ts +0 -6
  29. package/dist/components.js +0 -39
  30. package/dist/core-access.d.ts +0 -11
  31. package/dist/core-access.js +0 -34
  32. package/dist/core-blocks.d.ts +0 -24
  33. package/dist/core-blocks.js +0 -79
  34. package/dist/core-fields.d.ts +0 -73
  35. package/dist/core-fields.js +0 -167
  36. package/dist/core-utils.d.ts +0 -16
  37. package/dist/core-utils.js +0 -63
  38. package/dist/data-collections.d.ts +0 -229
  39. package/dist/data-collections.js +0 -676
  40. package/dist/data-seed.d.ts +0 -76
  41. package/dist/data-seed.js +0 -212
  42. package/dist/data-test.d.ts +0 -30
  43. package/dist/data-test.js +0 -1110
  44. package/dist/globals.d.ts +0 -69
  45. package/dist/globals.js +0 -251
  46. package/dist/hooks.d.ts +0 -108
  47. package/dist/hooks.js +0 -228
  48. package/dist/index.d.ts +0 -6
  49. package/dist/index.js +0 -39
  50. package/dist/render-components.d.ts +0 -42
  51. package/dist/render-components.js +0 -154
  52. package/dist/render-metadata.d.ts +0 -122
  53. package/dist/render-metadata.js +0 -390
  54. package/dist/render-utils.d.ts +0 -166
  55. package/dist/render-utils.js +0 -398
  56. package/dist/seed.d.ts +0 -76
  57. package/dist/seed.js +0 -212
  58. package/dist/server.d.ts +0 -980
  59. package/dist/server.js +0 -2231
  60. package/dist/test.d.ts +0 -30
  61. package/dist/test.js +0 -1110
  62. package/dist/with-www-config.d.ts +0 -108
  63. package/dist/with-www-config.js +0 -1006
package/dist/server.js DELETED
@@ -1,2231 +0,0 @@
1
-
2
- var __defProp = Object.defineProperty;
3
- var __returnValue = (v) => v;
4
- function __exportSetter(name, newValue) {
5
- this[name] = __returnValue.bind(null, newValue);
6
- }
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, {
10
- get: all[name],
11
- enumerable: true,
12
- configurable: true,
13
- set: __exportSetter.bind(all, name)
14
- });
15
- };
16
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
-
18
- // src/render/components/PageShowcase.tsx
19
- var exports_PageShowcase = {};
20
- __export(exports_PageShowcase, {
21
- PageShowcase: () => PageShowcase
22
- });
23
- import * as React from "react";
24
- import { jsx as jsx5, jsxs } from "react/jsx-runtime";
25
- function PageShowcase({
26
- children,
27
- metadata,
28
- jsonLd,
29
- localeSwitcher,
30
- metadataHeading = "Page metadata",
31
- jsonLdHeading = "JSON-LD"
32
- }) {
33
- console.log("[WWW] render/components:PageShowcase jsonLdEntries=", jsonLd.length, "hasOg=", Boolean(metadata.openGraph), "hasTwitter=", Boolean(metadata.twitter), "canonical=", metadata.alternates?.canonical);
34
- const og = metadata.openGraph;
35
- const twitter = metadata.twitter;
36
- const rows = [
37
- ["Title", resolveTitle(metadata.title)],
38
- ["Description", metadata.description],
39
- ["Canonical", metadata.alternates?.canonical],
40
- [
41
- "Languages",
42
- metadata.alternates?.languages ? Object.entries(metadata.alternates.languages).map(([locale, url]) => `${locale}: ${url}`).join(`
43
- `) : undefined
44
- ],
45
- ["Open Graph title", og?.title],
46
- ["Open Graph description", og?.description],
47
- ["Open Graph type", og?.type],
48
- ["Open Graph url", og?.url],
49
- ["Open Graph site name", og?.siteName],
50
- ["Twitter card", twitter?.card],
51
- ["Twitter title", twitter?.title],
52
- ["Twitter description", twitter?.description],
53
- ["Twitter site", twitter?.site],
54
- ["Twitter creator", twitter?.creator]
55
- ];
56
- return /* @__PURE__ */ jsxs("div", {
57
- className: "page-showcase grid gap-8 lg:grid-cols-[1fr_320px]",
58
- children: [
59
- /* @__PURE__ */ jsx5("main", {
60
- className: "page-showcase__main",
61
- children
62
- }),
63
- /* @__PURE__ */ jsxs("aside", {
64
- className: "page-showcase__sidebar flex flex-col gap-6 text-sm",
65
- children: [
66
- /* @__PURE__ */ jsxs("section", {
67
- className: "page-showcase__locale",
68
- children: [
69
- /* @__PURE__ */ jsx5("h2", {
70
- className: "m-0 mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",
71
- children: "Language"
72
- }),
73
- localeSwitcher
74
- ]
75
- }),
76
- /* @__PURE__ */ jsxs("section", {
77
- className: "page-showcase__metadata",
78
- children: [
79
- /* @__PURE__ */ jsx5("h2", {
80
- className: "m-0 mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",
81
- children: metadataHeading
82
- }),
83
- /* @__PURE__ */ jsx5("dl", {
84
- className: "m-0 grid grid-cols-[max-content_1fr] gap-x-3 gap-y-1.5",
85
- children: rows.filter(([, value]) => value !== undefined && value !== "").map(([label, value]) => /* @__PURE__ */ jsxs(React.Fragment, {
86
- children: [
87
- /* @__PURE__ */ jsx5("dt", {
88
- className: "font-medium text-muted-foreground",
89
- children: label
90
- }),
91
- /* @__PURE__ */ jsx5("dd", {
92
- className: "m-0 whitespace-pre-wrap break-words font-mono text-xs",
93
- children: value
94
- })
95
- ]
96
- }, label))
97
- })
98
- ]
99
- }),
100
- jsonLd.length > 0 ? /* @__PURE__ */ jsxs("section", {
101
- className: "page-showcase__jsonld",
102
- children: [
103
- /* @__PURE__ */ jsx5("h2", {
104
- className: "m-0 mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",
105
- children: jsonLdHeading
106
- }),
107
- jsonLd.map(({ id, schema }) => /* @__PURE__ */ jsxs("details", {
108
- className: "mb-2 rounded border border-border bg-muted/30 p-2",
109
- children: [
110
- /* @__PURE__ */ jsx5("summary", {
111
- className: "cursor-pointer font-mono text-xs",
112
- children: id
113
- }),
114
- /* @__PURE__ */ jsx5("pre", {
115
- className: "mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-[10px] leading-snug",
116
- children: JSON.stringify(schema, null, 2)
117
- })
118
- ]
119
- }, id))
120
- ]
121
- }) : null
122
- ]
123
- })
124
- ]
125
- });
126
- }
127
- function resolveTitle(title) {
128
- if (!title)
129
- return;
130
- if (typeof title === "string")
131
- return title;
132
- if (title === null)
133
- return;
134
- const t = title;
135
- return t.absolute ?? t.template ?? t.default;
136
- }
137
- var init_PageShowcase = () => {};
138
-
139
- // src/render/components/LocaleSwitcher.tsx
140
- var exports_LocaleSwitcher = {};
141
- __export(exports_LocaleSwitcher, {
142
- LocaleSwitcher: () => LocaleSwitcher
143
- });
144
- import { jsx as jsx6, jsxs as jsxs2 } from "react/jsx-runtime";
145
- function LocaleSwitcher({
146
- currentLocale,
147
- hreflangAlternates,
148
- labels
149
- }) {
150
- const locales = Object.keys(hreflangAlternates).filter((k) => k !== "x-default");
151
- console.log("[WWW] render/components:LocaleSwitcher currentLocale=", currentLocale, "locales=", JSON.stringify(locales), "hasXDefault=", Boolean(hreflangAlternates["x-default"]));
152
- return /* @__PURE__ */ jsx6("nav", {
153
- "aria-label": "Language",
154
- className: "locale-switcher",
155
- children: /* @__PURE__ */ jsxs2("ul", {
156
- className: "flex flex-wrap gap-2 list-none p-0 m-0",
157
- children: [
158
- locales.map((locale) => {
159
- const href = hreflangAlternates[locale];
160
- if (!href)
161
- return null;
162
- const isCurrent = locale === currentLocale;
163
- return /* @__PURE__ */ jsx6("li", {
164
- children: /* @__PURE__ */ jsx6("a", {
165
- href,
166
- "aria-current": isCurrent ? "true" : undefined,
167
- hrefLang: locale,
168
- className: "locale-switcher__link",
169
- "data-locale": locale,
170
- children: labels?.[locale] ?? locale.toUpperCase()
171
- })
172
- }, locale);
173
- }),
174
- hreflangAlternates["x-default"] ? /* @__PURE__ */ jsx6("li", {
175
- children: /* @__PURE__ */ jsx6("a", {
176
- href: hreflangAlternates["x-default"],
177
- hrefLang: "x-default",
178
- className: "locale-switcher__link",
179
- "data-locale": "x-default",
180
- children: labels?.["x-default"] ?? "Default"
181
- })
182
- }, "x-default") : null
183
- ]
184
- })
185
- });
186
- }
187
- var init_LocaleSwitcher = () => {};
188
-
189
- // src/core/access/index.ts
190
- var anyone = () => true;
191
- var authenticated = ({ req: { user } }) => Boolean(user);
192
- var authenticatedOrPublished = ({ req: { user } }) => {
193
- if (user)
194
- return true;
195
- return { _status: { equals: "published" } };
196
- };
197
-
198
- // src/core/fields/slug.ts
199
- var FLAT_PATTERN = /^[a-z0-9-]+$/;
200
- var NESTED_PATTERN = /^[a-z0-9_-]+$/;
201
- var slugField = (options = {}) => {
202
- const { name = "slug", nested = false, localized = true } = options;
203
- const pattern = nested ? NESTED_PATTERN : FLAT_PATTERN;
204
- const invalidMessage = nested ? "Slug must be lowercase, with hyphens or the `_` nesting divider (no spaces or other special characters)" : "Slug must be lowercase, with hyphens (no spaces or special characters)";
205
- return {
206
- name,
207
- type: "text",
208
- required: true,
209
- unique: true,
210
- index: true,
211
- localized,
212
- admin: {
213
- position: "sidebar",
214
- ...nested ? { description: "Lowercase, hyphens for words. Use the `_` divider for nesting, e.g. `about_us` → `/about/us`." } : {}
215
- },
216
- validate: (value) => {
217
- if (typeof value !== "string")
218
- return "Slug must be a string";
219
- if (value !== "" && !pattern.test(value))
220
- return invalidMessage;
221
- return true;
222
- }
223
- };
224
- };
225
-
226
- // src/render/_locale.ts
227
- function prefixFor(locale, defaultLocale, mode) {
228
- let result;
229
- if (mode === "never")
230
- result = "";
231
- else if (mode === "as-needed" && locale === defaultLocale)
232
- result = "";
233
- else
234
- result = `/${locale}`;
235
- console.log("[WWW] render/_locale:prefixFor locale=", locale, "default=", defaultLocale, "mode=", mode, "->", JSON.stringify(result));
236
- return result;
237
- }
238
- function resolveLocale(req) {
239
- if (!req || typeof req !== "object") {
240
- console.log('[WWW] render/_locale:resolveLocale -> "" (no req)');
241
- return "";
242
- }
243
- const r = req;
244
- if (typeof r.locale === "string" && r.locale.length > 0) {
245
- console.log("[WWW] render/_locale:resolveLocale ->", r.locale, "(from req.locale)");
246
- return r.locale;
247
- }
248
- const fallback = r.payload?.config?.localization?.defaultLocale;
249
- if (typeof fallback === "string" && fallback.length > 0) {
250
- console.log("[WWW] render/_locale:resolveLocale ->", fallback, "(from config.localization.defaultLocale)");
251
- return fallback;
252
- }
253
- console.log('[WWW] render/_locale:resolveLocale -> "" (no locale anywhere)');
254
- return "";
255
- }
256
- function allLocales(req) {
257
- if (!req || typeof req !== "object") {
258
- console.log("[WWW] render/_locale:allLocales -> [] (no req)");
259
- return [];
260
- }
261
- const r = req;
262
- const list = r.payload?.config?.localization?.locales;
263
- if (!Array.isArray(list) || list.length === 0) {
264
- console.log("[WWW] render/_locale:allLocales -> [] (no locales declared)");
265
- return [];
266
- }
267
- const out = [];
268
- for (const entry of list) {
269
- if (typeof entry === "string" && entry.length > 0) {
270
- out.push(entry);
271
- } else if (entry && typeof entry === "object" && "code" in entry) {
272
- const code = entry.code;
273
- if (typeof code === "string" && code.length > 0)
274
- out.push(code);
275
- }
276
- }
277
- console.log("[WWW] render/_locale:allLocales ->", JSON.stringify(out));
278
- return out;
279
- }
280
-
281
- // src/render/hooks/_shared.ts
282
- var cachePromise = null;
283
- function nextCacheImport() {
284
- return cachePromise ??= import("next/cache");
285
- }
286
- function shouldSkipRevalidate(context) {
287
- const skip = Boolean(context?.disableRevalidate);
288
- if (skip)
289
- console.log("[WWW] render/hooks:_shared:shouldSkipRevalidate -> skip");
290
- return skip;
291
- }
292
- async function safeRevalidatePath(payload, path) {
293
- console.log("[WWW] render/hooks:_shared:safeRevalidatePath path=", path);
294
- try {
295
- const { revalidatePath } = await nextCacheImport();
296
- revalidatePath(path);
297
- } catch (error) {
298
- console.error("[WWW] render/hooks:_shared:safeRevalidatePath failed path=", path, "err=", String(error));
299
- payload.logger.error(`revalidatePath("${path}") failed: ${String(error)}`);
300
- }
301
- }
302
- async function safeRevalidateTag(payload, tag, profile = "max") {
303
- console.log("[WWW] render/hooks:_shared:safeRevalidateTag tag=", tag, "profile=", profile);
304
- try {
305
- const { revalidateTag } = await nextCacheImport();
306
- revalidateTag(tag, profile);
307
- } catch (error) {
308
- console.error("[WWW] render/hooks:_shared:safeRevalidateTag failed tag=", tag, "err=", String(error));
309
- payload.logger.error(`revalidateTag("${tag}") failed: ${String(error)}`);
310
- }
311
- }
312
-
313
- // src/render/hooks/revalidateCollection.ts
314
- function createRevalidateCollectionHook(options) {
315
- const {
316
- collectionSlug,
317
- urlPathPrefix = "",
318
- sitemapTag,
319
- localePrefix: modeOption,
320
- defaultLocale: defaultLocaleOption,
321
- pathMode = "url"
322
- } = options;
323
- const resolvedSitemapTag = sitemapTag === false ? false : sitemapTag ?? `${collectionSlug}-sitemap`;
324
- console.log("[WWW] render/hooks:createRevalidateCollectionHook collectionSlug=", collectionSlug, "urlPathPrefix=", urlPathPrefix, "sitemapTag=", resolvedSitemapTag, "pathMode=", pathMode);
325
- const resolveDefaults = (req) => {
326
- const mode = modeOption ?? "always";
327
- const defaultLocale = defaultLocaleOption ?? req?.payload?.config?.localization?.defaultLocale ?? "";
328
- return { mode, defaultLocale };
329
- };
330
- const localesToFanOut = (req) => {
331
- const all = allLocales(req);
332
- if (all.length > 0)
333
- return all;
334
- const single = resolveLocale(req);
335
- return single ? [single] : [];
336
- };
337
- const collectionPath = (slug, locale, mode, defaultLocale) => {
338
- const prefix = prefixFor(locale, defaultLocale, mode);
339
- if (!slug)
340
- return `${prefix}${urlPathPrefix}` || "/";
341
- return `${prefix}${urlPathPrefix}/${slug}`;
342
- };
343
- const fanOutPaths = async (payload, req, slug, label) => {
344
- const { mode, defaultLocale } = resolveDefaults(req);
345
- const locales = localesToFanOut(req);
346
- for (const locale of locales) {
347
- const path = collectionPath(slug, locale, mode, defaultLocale);
348
- payload.logger.info?.(`${label} ${path}`);
349
- await safeRevalidatePath(payload, path);
350
- }
351
- };
352
- const fireCollectionTags = async (payload, docId, req) => {
353
- console.log("[WWW] render/hooks:fireCollectionTags collectionSlug=", collectionSlug, "docId=", docId);
354
- if (typeof docId === "string" || typeof docId === "number") {
355
- await safeRevalidateTag(payload, `collection_${collectionSlug}_${docId}`);
356
- }
357
- if (resolvedSitemapTag !== false) {
358
- await safeRevalidateTag(payload, resolvedSitemapTag);
359
- }
360
- };
361
- const afterChange = async ({ doc, previousDoc, req }) => {
362
- if (shouldSkipRevalidate(req.context))
363
- return doc;
364
- const { payload } = req;
365
- const typed = doc;
366
- const prev = previousDoc;
367
- console.log("[WWW] render/hooks:afterChange collectionSlug=", collectionSlug, "id=", typed.id, "slug=", typed.slug, "prevSlug=", prev?.slug);
368
- const isPublished = typed._status === "published";
369
- const wasPublished = prev?._status === "published";
370
- const prevSlugIsString = typeof prev?.slug === "string";
371
- const slugChanged = prevSlugIsString && prev?.slug !== typed.slug;
372
- if (isPublished) {
373
- if (pathMode !== "tag-only") {
374
- await fanOutPaths(payload, req, typed.slug, `Revalidating ${collectionSlug} at path:`);
375
- }
376
- await fireCollectionTags(payload, typed.id, req);
377
- }
378
- if (wasPublished && (!isPublished || slugChanged)) {
379
- if (pathMode !== "tag-only") {
380
- await fanOutPaths(payload, req, prev?.slug, `Revalidating old ${collectionSlug} at path:`);
381
- }
382
- await fireCollectionTags(payload, typed.id, req);
383
- }
384
- return doc;
385
- };
386
- const afterDelete = async ({ doc, req }) => {
387
- if (shouldSkipRevalidate(req.context))
388
- return doc ?? null;
389
- const { payload } = req;
390
- const typed = doc;
391
- console.log("[WWW] render/hooks:afterDelete collectionSlug=", collectionSlug, "id=", typed?.id, "slug=", typed?.slug);
392
- if (pathMode !== "tag-only") {
393
- await fanOutPaths(payload, req, typed?.slug, `Revalidating deleted ${collectionSlug} at path:`);
394
- }
395
- await fireCollectionTags(payload, typed?.id, req);
396
- return doc ?? null;
397
- };
398
- return { afterChange, afterDelete };
399
- }
400
- var createRevalidatePageHooks = (opts = {}) => {
401
- console.log("[WWW] render/hooks:createRevalidatePageHooks (deprecated alias) opts=", JSON.stringify(opts));
402
- return createRevalidateCollectionHook({
403
- collectionSlug: "pages",
404
- urlPathPrefix: "",
405
- ...opts
406
- });
407
- };
408
-
409
- // src/config/constants.ts
410
- var PAGES_RENDER_PATH = "@justanarthur/payload-www/render-pages#PagesPage";
411
- var POSTS_RENDER_PATH = "@justanarthur/payload-www/render-pages#PostsPage";
412
- var HEADER_RENDER_PATH = "@justanarthur/payload-www/render-pages#HeaderPage";
413
- var FOOTER_RENDER_PATH = "@justanarthur/payload-www/render-pages#FooterPage";
414
- var LIVE_PREVIEW_LISTENER_PATH = "@justanarthur/payload-www/render-components#LivePreviewListener";
415
- var PAGES_SLUG = "pages";
416
- var POSTS_SLUG = "posts";
417
- var STATIC_PAGES_SLUG = "staticPages";
418
-
419
- // src/data/collections/Pages/index.ts
420
- var HOME_PAGE_SLUG = "";
421
- var PAGES_SLUG2 = PAGES_SLUG;
422
- var createPagesCollection = (blocks, options = {}) => {
423
- const {
424
- renderPath = PAGES_RENDER_PATH,
425
- slug: collectionSlug = PAGES_SLUG2,
426
- localePrefix,
427
- defaultLocale,
428
- nested = false
429
- } = options;
430
- const baseFields = [
431
- {
432
- name: "title",
433
- type: "text",
434
- required: true,
435
- localized: true
436
- },
437
- {
438
- type: "tabs",
439
- tabs: [
440
- {
441
- fields: [
442
- {
443
- name: "blocks",
444
- type: "blocks",
445
- blocks,
446
- required: true,
447
- admin: { initCollapsed: true }
448
- }
449
- ],
450
- label: "Content"
451
- }
452
- ]
453
- },
454
- {
455
- name: "publishedAt",
456
- type: "date",
457
- admin: { position: "sidebar" }
458
- },
459
- slugField({ nested })
460
- ];
461
- const { afterChange: revalidateAfterChange, afterDelete: revalidateAfterDelete } = createRevalidateCollectionHook({
462
- collectionSlug,
463
- urlPathPrefix: "",
464
- localePrefix,
465
- defaultLocale
466
- });
467
- return {
468
- slug: collectionSlug,
469
- custom: { path: renderPath },
470
- access: {
471
- create: authenticated,
472
- delete: authenticated,
473
- read: authenticatedOrPublished,
474
- update: authenticated
475
- },
476
- fields: baseFields,
477
- hooks: {
478
- afterChange: [revalidateAfterChange],
479
- afterDelete: [revalidateAfterDelete]
480
- },
481
- versions: { drafts: { autosave: { interval: 1000 } } }
482
- };
483
- };
484
-
485
- // src/data/collections/Posts/index.ts
486
- var POSTS_SLUG2 = "posts";
487
- var createPostsCollection = (options = {}) => {
488
- const {
489
- renderPath = POSTS_RENDER_PATH,
490
- slug: collectionSlug = POSTS_SLUG2,
491
- localePrefix,
492
- defaultLocale
493
- } = options;
494
- const baseFields = [
495
- {
496
- name: "title",
497
- type: "text",
498
- required: true,
499
- localized: true
500
- },
501
- {
502
- name: "excerpt",
503
- type: "text",
504
- required: false,
505
- localized: true
506
- },
507
- {
508
- name: "content",
509
- type: "richText",
510
- required: false,
511
- localized: true
512
- },
513
- {
514
- name: "publishedAt",
515
- type: "date",
516
- admin: { position: "sidebar" }
517
- },
518
- slugField()
519
- ];
520
- const { afterChange, afterDelete } = createRevalidateCollectionHook({
521
- collectionSlug,
522
- urlPathPrefix: "/posts",
523
- localePrefix,
524
- defaultLocale
525
- });
526
- return {
527
- slug: collectionSlug,
528
- custom: { path: renderPath },
529
- access: {
530
- create: authenticated,
531
- delete: authenticated,
532
- read: authenticatedOrPublished,
533
- update: authenticated
534
- },
535
- fields: baseFields,
536
- hooks: {
537
- afterChange: [afterChange],
538
- afterDelete: [afterDelete]
539
- },
540
- versions: { drafts: { autosave: { interval: 1000 } } }
541
- };
542
- };
543
-
544
- // src/data/collections/StaticPages/index.ts
545
- var createStaticPagesCollection = (blocks) => {
546
- const { afterChange, afterDelete } = createRevalidateCollectionHook({
547
- collectionSlug: STATIC_PAGES_SLUG,
548
- pathMode: "tag-only",
549
- sitemapTag: "static-pages"
550
- });
551
- return {
552
- slug: STATIC_PAGES_SLUG,
553
- dbName: "sp",
554
- admin: { group: "System", useAsTitle: "title" },
555
- access: {
556
- create: authenticated,
557
- delete: authenticated,
558
- read: authenticatedOrPublished,
559
- update: authenticated
560
- },
561
- fields: [
562
- {
563
- name: "kind",
564
- type: "select",
565
- required: true,
566
- unique: true,
567
- index: true,
568
- options: [
569
- { label: "Not found (404)", value: "not-found" },
570
- { label: "Server error (500)", value: "server-error" },
571
- { label: "Search empty", value: "search-empty" },
572
- { label: "Offline", value: "offline" }
573
- ],
574
- admin: {
575
- position: "sidebar",
576
- description: "Which system page this row powers. One row per kind."
577
- }
578
- },
579
- {
580
- name: "title",
581
- type: "text",
582
- required: true,
583
- localized: true,
584
- admin: { description: "Admin-only label. Not rendered." }
585
- },
586
- {
587
- type: "tabs",
588
- tabs: [
589
- {
590
- fields: [
591
- {
592
- name: "blocks",
593
- type: "blocks",
594
- localized: true,
595
- blocks,
596
- admin: { initCollapsed: true },
597
- dbName: "b"
598
- }
599
- ],
600
- label: "Content"
601
- }
602
- ]
603
- },
604
- {
605
- name: "publishedAt",
606
- type: "date",
607
- admin: { position: "sidebar" }
608
- }
609
- ],
610
- hooks: {
611
- afterChange: [afterChange],
612
- afterDelete: [afterDelete]
613
- },
614
- versions: { drafts: { autosave: { interval: 1000 } } }
615
- };
616
- };
617
-
618
- // src/core/fields/link.ts
619
- var appearanceOptions = {
620
- default: { label: "Default", value: "default" },
621
- outline: { label: "Outline", value: "outline" }
622
- };
623
- var link = (options = {}) => {
624
- const {
625
- appearances,
626
- disableLabel = false,
627
- relationTo = [PAGES_SLUG],
628
- localized = false,
629
- overrides = {},
630
- extraFields = []
631
- } = options;
632
- const result = {
633
- name: "link",
634
- type: "group",
635
- admin: { hideGutter: true },
636
- fields: [
637
- {
638
- type: "row",
639
- fields: [
640
- {
641
- name: "type",
642
- type: "radio",
643
- admin: { layout: "horizontal", width: "50%" },
644
- defaultValue: "reference",
645
- options: [
646
- { label: "Internal link", value: "reference" },
647
- { label: "Custom URL", value: "custom" }
648
- ]
649
- },
650
- {
651
- name: "newTab",
652
- type: "checkbox",
653
- admin: { style: { alignSelf: "flex-end" }, width: "50%" },
654
- label: "Open in new tab"
655
- }
656
- ]
657
- }
658
- ]
659
- };
660
- const linkTypes = [
661
- {
662
- name: "reference",
663
- type: "relationship",
664
- admin: { condition: (_, siblingData) => siblingData?.type === "reference" },
665
- label: "Document to link to",
666
- relationTo,
667
- required: true,
668
- localized
669
- },
670
- {
671
- name: "url",
672
- type: "text",
673
- admin: { condition: (_, siblingData) => siblingData?.type === "custom" },
674
- label: "Custom URL",
675
- required: true,
676
- localized
677
- }
678
- ];
679
- if (!disableLabel) {
680
- result.fields.push({
681
- type: "row",
682
- fields: [
683
- ...linkTypes,
684
- {
685
- name: "label",
686
- type: "text",
687
- admin: { width: "50%" },
688
- label: "Label",
689
- required: true,
690
- localized
691
- }
692
- ]
693
- });
694
- } else {
695
- result.fields = [...result.fields, ...linkTypes];
696
- }
697
- if (appearances !== false) {
698
- const opts = appearances ? appearances.map((a) => appearanceOptions[a]) : [appearanceOptions.default, appearanceOptions.outline];
699
- result.fields.push({
700
- name: "appearance",
701
- type: "select",
702
- admin: { description: "Choose how the link should be rendered." },
703
- defaultValue: "default",
704
- options: opts
705
- });
706
- }
707
- if (extraFields.length) {
708
- result.fields.push(...extraFields);
709
- }
710
- return { ...result, ...overrides };
711
- };
712
-
713
- // src/render/hooks/revalidateGlobal.ts
714
- function createRevalidateGlobalHook(slug) {
715
- console.log("[WWW] render/hooks:createRevalidateGlobalHook slug=", slug);
716
- return async ({ doc, req: { payload, context, locale } }) => {
717
- if (shouldSkipRevalidate(context))
718
- return doc;
719
- const tags = [`global_${slug}`, `global_${slug}_${locale}`];
720
- console.log("[WWW] render/hooks:revalidateGlobal slug=", slug, "locale=", locale, "tags=", JSON.stringify(tags));
721
- payload.logger.info?.(`Revalidating global: ${tags.join(", ")}`);
722
- for (const tag of tags) {
723
- await safeRevalidateTag(payload, tag);
724
- }
725
- return doc;
726
- };
727
- }
728
-
729
- // src/data/collections/globals/Header/config.ts
730
- var createHeaderGlobal = (options = {}) => {
731
- const {
732
- renderPath = HEADER_RENDER_PATH,
733
- linkRelationTo = [PAGES_SLUG],
734
- navColumnLinkFields = [],
735
- navItemLinkFields = []
736
- } = options;
737
- const navColumnBlock = {
738
- slug: "navColumn",
739
- fields: [
740
- { name: "title", type: "text", required: true, localized: true },
741
- { name: "links", type: "array", fields: [link({ appearances: false, localized: true, relationTo: linkRelationTo, extraFields: navColumnLinkFields })] }
742
- ]
743
- };
744
- const navItemBlock = {
745
- slug: "navItem",
746
- fields: [link({ appearances: false, localized: true, relationTo: linkRelationTo, extraFields: navItemLinkFields })]
747
- };
748
- return {
749
- slug: "header",
750
- custom: { path: renderPath },
751
- access: { read: () => true },
752
- fields: [
753
- {
754
- name: "nav",
755
- type: "blocks",
756
- required: true,
757
- blocks: [navColumnBlock, navItemBlock]
758
- }
759
- ],
760
- hooks: {
761
- afterChange: [createRevalidateGlobalHook("header")]
762
- }
763
- };
764
- };
765
-
766
- // src/data/collections/globals/Footer/config.ts
767
- var createFooterGlobal = (options = {}) => {
768
- const {
769
- renderPath = FOOTER_RENDER_PATH,
770
- linkRelationTo = [PAGES_SLUG],
771
- navColumnLinkFields = [],
772
- navItemLinkFields = []
773
- } = options;
774
- const navColumnBlock = {
775
- slug: "navColumn",
776
- fields: [
777
- { name: "title", type: "text", required: true, localized: true },
778
- { name: "links", type: "array", fields: [link({ appearances: false, localized: true, relationTo: linkRelationTo, extraFields: navColumnLinkFields })] }
779
- ]
780
- };
781
- const navItemBlock = {
782
- slug: "navItem",
783
- fields: [link({ appearances: false, localized: true, relationTo: linkRelationTo, extraFields: navItemLinkFields })]
784
- };
785
- return {
786
- slug: "footer",
787
- custom: { path: renderPath },
788
- access: { read: () => true },
789
- fields: [
790
- {
791
- name: "nav",
792
- type: "blocks",
793
- required: true,
794
- blocks: [navColumnBlock, navItemBlock]
795
- }
796
- ],
797
- hooks: {
798
- afterChange: [createRevalidateGlobalHook("footer")]
799
- }
800
- };
801
- };
802
-
803
- // src/config/createWWWConfig.ts
804
- import openAIResolver from "@justanarthur/payload-plugin-translator/resolvers/openAI";
805
-
806
- // src/render/preview/createPreviewHandler.ts
807
- function createPreviewHandler(options) {
808
- const { getServerSideURL: _getServerSideURL, secret, enableDraftMode = true } = options;
809
- return async function GET(req) {
810
- const { draftMode } = await import("next/headers");
811
- const { redirect } = await import("next/navigation");
812
- const url = new URL(req.url);
813
- const path = url.searchParams.get("path") ?? "/";
814
- const previewSecret = url.searchParams.get("previewSecret");
815
- console.log("[WWW] render/preview:createPreviewHandler:GET path=", path, "hasSecret=", Boolean(previewSecret), "enableDraftMode=", enableDraftMode);
816
- if (!previewSecret || previewSecret !== secret) {
817
- console.warn("[WWW] render/preview:createPreviewHandler:GET invalid preview secret (401)");
818
- return new Response("Invalid preview secret", { status: 401 });
819
- }
820
- if (enableDraftMode) {
821
- (await draftMode()).enable();
822
- console.log("[WWW] render/preview:createPreviewHandler:GET draftMode enabled");
823
- }
824
- redirect(path);
825
- return new Response(null, { status: 204 });
826
- };
827
- }
828
- // src/render/metadata/hreflang.ts
829
- async function buildHreflangAlternates({
830
- siteUrl,
831
- locale,
832
- urlPrefix,
833
- storedSlug,
834
- queryAllLocaleSlugs,
835
- nested,
836
- homeSlug,
837
- defaultLocale,
838
- locales,
839
- localePrefix = "always"
840
- }) {
841
- const allLocaleSlugs = await queryAllLocaleSlugs(storedSlug, locale);
842
- console.log("[WWW] render/metadata:buildHreflangAlternates storedSlug=", storedSlug, "locale=", locale, "allLocaleSlugs=", JSON.stringify(allLocaleSlugs));
843
- const languages = {};
844
- const urlFor = (l, slug) => {
845
- const trimmedPrefix = urlPrefix.replace(/^\/|\/$/g, "");
846
- const prefixSegment = trimmedPrefix ? `/${trimmedPrefix}` : "";
847
- const urlPath = slug === homeSlug ? "/" : nested ? "/" + slug.replaceAll("_", "/") : "/" + slug;
848
- const localeSegment = localePrefix === "never" ? "" : localePrefix === "as-needed" && l === defaultLocale ? "" : `/${l}`;
849
- return `${siteUrl}${localeSegment}${prefixSegment}${urlPath}`;
850
- };
851
- for (const l of locales) {
852
- const slugForLocale = allLocaleSlugs?.[l];
853
- if (!slugForLocale)
854
- continue;
855
- languages[l] = urlFor(l, slugForLocale);
856
- }
857
- if (allLocaleSlugs?.[defaultLocale]) {
858
- languages["x-default"] = urlFor(defaultLocale, allLocaleSlugs[defaultLocale]);
859
- }
860
- console.log("[WWW] render/metadata:buildHreflangAlternates ->", JSON.stringify(languages));
861
- return languages;
862
- }
863
-
864
- // src/render/metadata/query.ts
865
- import { getPayload } from "payload";
866
- import { cache } from "react";
867
-
868
- // src/core/utils/getFromImportMap.ts
869
- function getFromImportMap(key, importMap) {
870
- return importMap[key.includes("#") ? key : key + "#default"];
871
- }
872
-
873
- // src/render/metadata/query.ts
874
- var queryDocBySlug = cache(async function queryDocBySlug2({
875
- collectionSlug,
876
- slug,
877
- slugField: slugField2 = "slug",
878
- locale,
879
- draft = false,
880
- config
881
- }) {
882
- console.log("[WWW] render/metadata:queryDocBySlug collection=", collectionSlug, "slug=", slug, "slugField=", slugField2, "locale=", locale, "draft=", draft);
883
- const payload = await getPayload({ config });
884
- const result = await payload.find({
885
- collection: collectionSlug,
886
- draft,
887
- limit: 1,
888
- pagination: false,
889
- overrideAccess: draft,
890
- where: { [slugField2]: { equals: slug } },
891
- locale
892
- });
893
- const doc = result.docs?.[0] ?? null;
894
- console.log("[WWW] render/metadata:queryDocBySlug ->", doc ? "hit" : "miss");
895
- return doc;
896
- });
897
- var queryAllDocs = cache(async function queryAllDocs2({
898
- collectionSlug,
899
- slugField: slugField2 = "slug",
900
- locale,
901
- config
902
- }) {
903
- console.log("[WWW] render/metadata:queryAllDocs collection=", collectionSlug, "locale=", locale);
904
- const payload = await getPayload({ config });
905
- const result = await payload.find({
906
- collection: collectionSlug,
907
- draft: false,
908
- limit: 1000,
909
- pagination: false,
910
- overrideAccess: false,
911
- select: { [slugField2]: true },
912
- locale
913
- });
914
- const docs = result.docs ?? [];
915
- console.log("[WWW] render/metadata:queryAllDocs -> count=", docs.length);
916
- return docs;
917
- });
918
- var queryAllLocaleSlugs = cache(async function queryAllLocaleSlugs2({
919
- collectionSlug,
920
- slug,
921
- slugField: slugField2 = "slug",
922
- locale,
923
- config
924
- }) {
925
- console.log("[WWW] render/metadata:queryAllLocaleSlugs collection=", collectionSlug, "slug=", slug, "locale=", locale);
926
- const payload = await getPayload({ config });
927
- const result = await payload.find({
928
- collection: collectionSlug,
929
- draft: false,
930
- limit: 1,
931
- pagination: false,
932
- overrideAccess: false,
933
- locale,
934
- where: { [slugField2]: { equals: slug } },
935
- select: { [slugField2]: true }
936
- });
937
- const doc = result.docs?.[0];
938
- if (!doc) {
939
- console.log("[WWW] render/metadata:queryAllLocaleSlugs -> undefined (no doc)");
940
- return;
941
- }
942
- let fieldValue = doc[slugField2];
943
- if (doc.id != null) {
944
- const allLocales2 = await payload.findByID({
945
- collection: collectionSlug,
946
- id: doc.id,
947
- locale: "all",
948
- draft: false,
949
- overrideAccess: false,
950
- select: { [slugField2]: true }
951
- }).catch(() => null);
952
- if (allLocales2)
953
- fieldValue = allLocales2[slugField2];
954
- }
955
- if (fieldValue && typeof fieldValue === "object") {
956
- console.log("[WWW] render/metadata:queryAllLocaleSlugs -> localized map=", JSON.stringify(fieldValue));
957
- return fieldValue;
958
- }
959
- const resolved = await config;
960
- const rawLocales = Array.isArray(resolved?.localization?.localeCodes) ? resolved.localization.localeCodes : resolved?.localization?.locales?.map((l) => l.code) ?? [];
961
- const out = {};
962
- for (const l of rawLocales)
963
- out[l] = String(fieldValue ?? slug);
964
- console.log("[WWW] render/metadata:queryAllLocaleSlugs -> flat-fanout locales=", rawLocales.length, "slug=", JSON.stringify(fieldValue ?? slug));
965
- return out;
966
- });
967
- var queryGlobal = cache(async function queryGlobal2({
968
- globalSlug,
969
- locale,
970
- depth = 0,
971
- draft = false,
972
- config
973
- }) {
974
- console.log("[WWW] render/metadata:queryGlobal global=", globalSlug, "locale=", locale, "depth=", depth, "draft=", draft);
975
- const payload = await getPayload({ config });
976
- try {
977
- const global = await payload.findGlobal({
978
- slug: globalSlug,
979
- depth,
980
- draft,
981
- locale
982
- });
983
- console.log("[WWW] render/metadata:queryGlobal -> hit");
984
- return global;
985
- } catch (error) {
986
- console.warn("[WWW] render/metadata:queryGlobal failed for slug=", globalSlug, "err=", String(error));
987
- return null;
988
- }
989
- });
990
- function getRenderModuleExports(exportName, collection, importMap) {
991
- const path = collection?.custom?.path;
992
- if (!path) {
993
- console.log("[WWW] render/metadata:getRenderModuleExports no custom.path exportName=", exportName);
994
- return;
995
- }
996
- const mod = getFromImportMap(path, importMap);
997
- const value = mod?.[exportName];
998
- console.log("[WWW] render/metadata:getRenderModuleExports exportName=", exportName, "path=", path, "hit=", Boolean(value));
999
- return value;
1000
- }
1001
-
1002
- // src/render/sitemap/createSitemapFile.ts
1003
- function createSitemapFile(options) {
1004
- const { collections } = options;
1005
- return async function sitemap() {
1006
- console.log("[WWW] render/sitemap:createSitemapFile:sitemap collections=", JSON.stringify(options.collections), "localePrefix=", options.localePrefix ?? "always");
1007
- const cfg = await options.config;
1008
- const allLocales2 = Array.isArray(cfg.localization?.locales) ? cfg.localization.locales.map((l) => typeof l === "string" ? l : l.code) : [cfg.localization?.defaultLocale ?? "en"];
1009
- const defaultLocale = cfg.localization?.defaultLocale ?? allLocales2[0];
1010
- const activeLocales = Array.isArray(options.locales) && options.locales.length > 0 ? options.locales.filter((l) => allLocales2.includes(l)) : allLocales2;
1011
- console.log("[WWW] render/sitemap:createSitemapFile:sitemap allLocales=", JSON.stringify(allLocales2), "default=", defaultLocale, "active=", JSON.stringify(activeLocales));
1012
- const entries = [];
1013
- const seen = new Set;
1014
- for (const collectionSlug of collections) {
1015
- const collectionDefaults = options.perCollection?.[collectionSlug] ?? {};
1016
- const urlPrefix = (options.urlPrefixes?.[collectionSlug] ?? "").replace(/\/$/, "");
1017
- const siteUrl = options.getServerSideURL().replace(/\/$/, "");
1018
- const isNested = options.nested?.[collectionSlug] ?? false;
1019
- for (const locale of activeLocales) {
1020
- const docs = await queryAllDocs({
1021
- collectionSlug,
1022
- slugField: "slug",
1023
- locale,
1024
- config: options.config
1025
- });
1026
- for (const doc of docs) {
1027
- const storedSlug = doc.slug;
1028
- if (typeof storedSlug !== "string" || storedSlug === "")
1029
- continue;
1030
- const dedupeKey = `${collectionSlug}:${locale}:${storedSlug}`;
1031
- if (seen.has(dedupeKey))
1032
- continue;
1033
- seen.add(dedupeKey);
1034
- const slugPath = isNested ? storedSlug.replaceAll("_", "/") : storedSlug;
1035
- const url = `${siteUrl}${prefixFor(locale, defaultLocale, options.localePrefix ?? "always")}${urlPrefix}/${slugPath}`;
1036
- const languages = await buildHreflangAlternates({
1037
- siteUrl,
1038
- locale,
1039
- urlPrefix,
1040
- storedSlug,
1041
- nested: isNested,
1042
- homeSlug: "",
1043
- defaultLocale,
1044
- locales: activeLocales,
1045
- localePrefix: options.localePrefix,
1046
- queryAllLocaleSlugs: async (s, l) => {
1047
- const result = await queryAllLocaleSlugs({
1048
- collectionSlug,
1049
- slug: s,
1050
- slugField: "slug",
1051
- locale: l,
1052
- config: options.config
1053
- });
1054
- return result ?? undefined;
1055
- }
1056
- });
1057
- entries.push({
1058
- url,
1059
- lastModified: doc.updatedAt ? new Date(doc.updatedAt) : undefined,
1060
- changeFrequency: collectionDefaults.changefreq ?? "weekly",
1061
- priority: collectionDefaults.priority ?? 0.5,
1062
- alternates: { languages }
1063
- });
1064
- }
1065
- }
1066
- }
1067
- console.log("[WWW] render/sitemap:createSitemapFile:sitemap -> entries=", entries.length);
1068
- return entries;
1069
- };
1070
- }
1071
- // src/config/createWWWConfig.ts
1072
- function createWWWConfig(options) {
1073
- const { locales, routing, blocks, linkRelationTo, registerPosts = true, nested = false, defaultPlugins } = options;
1074
- const defaultLocale = routing?.defaultLocale ?? locales[0] ?? "";
1075
- const localePrefixMode = (() => {
1076
- const raw = routing?.localePrefix;
1077
- if (typeof raw === "string")
1078
- return raw;
1079
- return raw?.mode ?? "always";
1080
- })();
1081
- if (locales.length === 0) {
1082
- throw new Error("createWWWConfig: `locales` must contain at least one entry.");
1083
- }
1084
- const buildPagesCollection = () => createPagesCollection(blocks, {
1085
- localePrefix: localePrefixMode,
1086
- defaultLocale,
1087
- nested
1088
- });
1089
- const buildPostsCollection = () => createPostsCollection({
1090
- localePrefix: localePrefixMode,
1091
- defaultLocale
1092
- });
1093
- const buildStaticPagesCollection = () => createStaticPagesCollection(blocks);
1094
- const buildHeaderGlobal = () => createHeaderGlobal({ linkRelationTo });
1095
- const buildFooterGlobal = () => createFooterGlobal({ linkRelationTo });
1096
- async function withWWWConfig(config) {
1097
- const baseDefaults = [
1098
- buildPagesCollection(),
1099
- buildStaticPagesCollection()
1100
- ];
1101
- if (registerPosts)
1102
- baseDefaults.push(buildPostsCollection());
1103
- const defaultCollections = baseDefaults;
1104
- const collections = typeof config.collections === "function" ? config.collections({ defaultCollections }) : [...defaultCollections, ...config.collections || []];
1105
- const defaultGlobals = [buildHeaderGlobal(), buildFooterGlobal()];
1106
- const globals = typeof config.globals === "function" ? config.globals({ defaultGlobals }) : [...defaultGlobals, ...config.globals || []];
1107
- const renderDependencies = {
1108
- [PAGES_RENDER_PATH]: { path: PAGES_RENDER_PATH, type: "component" },
1109
- [POSTS_RENDER_PATH]: { path: POSTS_RENDER_PATH, type: "component" },
1110
- [HEADER_RENDER_PATH]: { path: HEADER_RENDER_PATH, type: "component" },
1111
- [FOOTER_RENDER_PATH]: { path: FOOTER_RENDER_PATH, type: "component" },
1112
- [LIVE_PREVIEW_LISTENER_PATH]: {
1113
- path: LIVE_PREVIEW_LISTENER_PATH,
1114
- type: "component"
1115
- }
1116
- };
1117
- for (const { slug, custom, admin } of blocks) {
1118
- const path = custom?.path ?? admin?.custom?.path;
1119
- if (typeof path === "string" && slug)
1120
- renderDependencies[slug] = { path, type: "component" };
1121
- }
1122
- for (const entry of [...collections, ...globals]) {
1123
- const path = entry.custom?.path;
1124
- if (typeof path === "string")
1125
- renderDependencies[path] = { path, type: "component" };
1126
- }
1127
- const [
1128
- { seoPlugin },
1129
- { imageHashPlugin },
1130
- { translator }
1131
- ] = await Promise.all([
1132
- import("@justanarthur/payload-plugin-seo"),
1133
- import("@justanarthur/payload-imagehash-plugin"),
1134
- import("@justanarthur/payload-plugin-translator")
1135
- ]);
1136
- const defaultPluginList = [
1137
- seoPlugin({
1138
- collections: ["pages", "posts", "static-pages"],
1139
- autoGenerate: { mode: "onCreate", deriveFrom: "allScalars" }
1140
- }),
1141
- imageHashPlugin({ algorithm: "lqip-modern" }),
1142
- translator({
1143
- collections: ["pages", "posts", "static-pages"],
1144
- globals: ["header", "footer"],
1145
- resolvers: [
1146
- openAIResolver({
1147
- apiKey: process.env.OPENAI_API_KEY,
1148
- chunkLength: 31,
1149
- model: "gpt-5-mini"
1150
- })
1151
- ]
1152
- })
1153
- ];
1154
- const mergedPlugins = defaultPlugins ? defaultPlugins(defaultPluginList) : defaultPluginList;
1155
- return {
1156
- ...config,
1157
- collections,
1158
- globals,
1159
- plugins: mergedPlugins,
1160
- admin: {
1161
- ...config.admin ?? {},
1162
- dependencies: {
1163
- ...renderDependencies,
1164
- ...config.admin?.dependencies ?? {}
1165
- }
1166
- }
1167
- };
1168
- }
1169
- return { withWWWConfig };
1170
- }
1171
-
1172
- // src/core/fields/linkGroup.ts
1173
- var linkGroup = (options = {}) => ({
1174
- name: "links",
1175
- type: "array",
1176
- fields: [link(options)],
1177
- admin: { initCollapsed: true }
1178
- });
1179
-
1180
- // src/core/utils/generateImportName.ts
1181
- function generateImportName(type, slug) {
1182
- switch (type) {
1183
- case "block":
1184
- return `Block${slug.replace(/(^\w|-\w)/g, (m) => m.replace("-", "").toUpperCase())}#default`;
1185
- case "page":
1186
- return `Page${slug.replace(/(^\w|-\w)/g, (m) => m.replace("-", "").toUpperCase())}#default`;
1187
- default:
1188
- throw new Error(`Unknown type: ${type}`);
1189
- }
1190
- }
1191
-
1192
- // src/render/utils/renderCollectionModule.tsx
1193
- import { jsx } from "react/jsx-runtime";
1194
- function renderCollectionModule(collection = [], slug, importMap, props) {
1195
- const renderPath = collection?.find((c) => c.slug === slug)?.custom?.path;
1196
- if (!renderPath) {
1197
- console.log("[WWW] render/utils:renderCollectionModule no custom.path slug=", slug);
1198
- return null;
1199
- }
1200
- const CollectionRenderModule = getFromImportMap(renderPath, importMap);
1201
- if (!CollectionRenderModule) {
1202
- console.error("[WWW] render/utils:renderCollectionModule not found slug=", slug, "path=", renderPath);
1203
- if (false) {}
1204
- return null;
1205
- }
1206
- console.log("[WWW] render/utils:renderCollectionModule rendering slug=", slug, "path=", renderPath);
1207
- return /* @__PURE__ */ jsx(CollectionRenderModule, {
1208
- importMap,
1209
- ...props
1210
- });
1211
- }
1212
-
1213
- // src/render/utils/renderGlobalModule.tsx
1214
- import { jsx as jsx2 } from "react/jsx-runtime";
1215
- function renderGlobalModule(globals = [], slug, importMap, props) {
1216
- const renderPath = globals?.find((g) => g.slug === slug)?.custom?.path;
1217
- if (!renderPath) {
1218
- console.log("[WWW] render/utils:renderGlobalModule no custom.path slug=", slug);
1219
- return null;
1220
- }
1221
- const GlobalRenderModule = getFromImportMap(renderPath, importMap);
1222
- if (!GlobalRenderModule) {
1223
- console.error("[WWW] render/utils:renderGlobalModule not found slug=", slug, "path=", renderPath);
1224
- if (false) {}
1225
- return null;
1226
- }
1227
- console.log("[WWW] render/utils:renderGlobalModule rendering slug=", slug, "path=", renderPath);
1228
- return /* @__PURE__ */ jsx2(GlobalRenderModule, {
1229
- importMap,
1230
- ...props
1231
- });
1232
- }
1233
-
1234
- // src/render/utils/getCachedGlobal.ts
1235
- import { unstable_cache } from "next/cache";
1236
- var getCachedGlobal = (config, slug, depth = 0) => {
1237
- console.log("[WWW] render/utils:getCachedGlobal slug=", slug, "depth=", depth);
1238
- return unstable_cache(async () => queryGlobal({
1239
- globalSlug: slug,
1240
- locale: "__ALL__",
1241
- depth,
1242
- config
1243
- }), [slug], { tags: [`global_${slug}`] });
1244
- };
1245
-
1246
- // src/render/metadata/jsonld.ts
1247
- function getImageUrl(doc, siteUrl) {
1248
- const img = doc?.meta?.image ?? doc?.heroImage ?? doc?.image;
1249
- if (!img)
1250
- return null;
1251
- if (typeof img === "string")
1252
- return img;
1253
- if (img?.url)
1254
- return img.url.startsWith("http") ? img.url : `${siteUrl}${img.url}`;
1255
- return null;
1256
- }
1257
- function getImageUrlWithLog(doc, siteUrl) {
1258
- const result = getImageUrl(doc, siteUrl);
1259
- console.log("[WWW] render/metadata:jsonld:getImageUrl ->", result);
1260
- return result;
1261
- }
1262
- function resolveLocalizedField(value, locale) {
1263
- if (value == null)
1264
- return "";
1265
- if (typeof value === "string") {
1266
- if (!value.startsWith("{"))
1267
- return value;
1268
- try {
1269
- const parsed = JSON.parse(value);
1270
- return resolveLocalizedField(parsed, locale);
1271
- } catch {
1272
- return value;
1273
- }
1274
- }
1275
- if (typeof value !== "object")
1276
- return "";
1277
- const obj = value;
1278
- if (typeof obj[locale] === "string" && obj[locale].length > 0) {
1279
- return obj[locale];
1280
- }
1281
- return Object.values(obj).filter((v) => typeof v === "string" && v.length > 0).join(" / ");
1282
- }
1283
- function resolveLocalizedFieldWithLog(value, locale) {
1284
- const result = resolveLocalizedField(value, locale);
1285
- if (value && typeof value === "object") {
1286
- console.log("[WWW] render/metadata:jsonld:resolveLocalizedField locale=", locale, "->", JSON.stringify(result));
1287
- }
1288
- return result;
1289
- }
1290
- function buildArticleLd({
1291
- doc,
1292
- url,
1293
- locale,
1294
- siteUrl,
1295
- type = "BlogPosting",
1296
- publisherName,
1297
- publisherLogo
1298
- }) {
1299
- const name = publisherName ?? new URL(siteUrl).hostname;
1300
- console.log("[WWW] render/metadata:buildArticleLd url=", url, "locale=", locale, "type=", type, "publisherName=", name);
1301
- const ld = {
1302
- "@context": "https://schema.org",
1303
- "@type": type,
1304
- "@id": `${url}#article`,
1305
- headline: resolveLocalizedFieldWithLog(doc.title, locale),
1306
- description: resolveLocalizedFieldWithLog(doc.meta?.description ?? doc.description ?? doc.excerpt, locale),
1307
- inLanguage: locale,
1308
- url,
1309
- dateModified: doc.updatedAt ? new Date(doc.updatedAt).toISOString() : undefined
1310
- };
1311
- const datePublished = doc.publishedAt ?? doc.createdAt;
1312
- if (datePublished)
1313
- ld.datePublished = new Date(datePublished).toISOString();
1314
- const imgUrl = getImageUrlWithLog(doc, siteUrl);
1315
- if (imgUrl)
1316
- ld.image = imgUrl;
1317
- ld.author = { "@type": "Organization", name, url: siteUrl };
1318
- const publisher = { "@type": "Organization", name };
1319
- if (publisherLogo !== undefined) {
1320
- if (publisherLogo !== null)
1321
- publisher.logo = { "@type": "ImageObject", url: publisherLogo };
1322
- }
1323
- ld.publisher = publisher;
1324
- return ld;
1325
- }
1326
- function buildBreadcrumbsLd({
1327
- items,
1328
- currentUrl
1329
- }) {
1330
- console.log("[WWW] render/metadata:buildBreadcrumbsLd items=", items.length, "currentUrl=", currentUrl);
1331
- return {
1332
- "@context": "https://schema.org",
1333
- "@type": "BreadcrumbList",
1334
- itemListElement: items.map((item, index) => ({
1335
- "@type": "ListItem",
1336
- position: index + 1,
1337
- name: item.label,
1338
- item: index === items.length - 1 ? currentUrl : item.url
1339
- }))
1340
- };
1341
- }
1342
- function buildOrganizationLd({
1343
- siteUrl,
1344
- name,
1345
- logo,
1346
- sameAs
1347
- }) {
1348
- console.log("[WWW] render/metadata:buildOrganizationLd siteUrl=", siteUrl, "name=", name, "logo?", Boolean(logo), "sameAs?", Boolean(sameAs));
1349
- const org = {
1350
- "@context": "https://schema.org",
1351
- "@type": "Organization",
1352
- "@id": `${siteUrl}#organization`,
1353
- url: siteUrl,
1354
- ...name && { name },
1355
- ...logo && { logo: { "@type": "ImageObject", url: logo } },
1356
- ...sameAs && sameAs.length > 0 && { sameAs }
1357
- };
1358
- return org;
1359
- }
1360
-
1361
- // src/render/metadata/slug.ts
1362
- var SLUG_NESTED_DIVIDER = "_";
1363
- function segmentsToStoredSlug(segments, nested) {
1364
- if (!Array.isArray(segments)) {
1365
- console.log("[WWW] render/metadata:segmentsToStoredSlug string passthrough:", JSON.stringify(segments));
1366
- return segments;
1367
- }
1368
- const result = nested ? segments.join(SLUG_NESTED_DIVIDER) : segments[0] ?? "";
1369
- console.log("[WWW] render/metadata:segmentsToStoredSlug nested=", nested, "segments=", JSON.stringify(segments), "->", result);
1370
- return result;
1371
- }
1372
- function segmentsToUrlPath(segments, nested) {
1373
- let result;
1374
- if (!Array.isArray(segments))
1375
- result = "/" + segments;
1376
- else if (nested)
1377
- result = "/" + segments.join("/");
1378
- else
1379
- result = "/" + (segments[0] ?? "");
1380
- console.log("[WWW] render/metadata:segmentsToUrlPath nested=", nested, "segments=", JSON.stringify(segments), "->", result);
1381
- return result;
1382
- }
1383
- function storedSlugToSegments(storedSlug, nested) {
1384
- const result = nested ? storedSlug.split(SLUG_NESTED_DIVIDER) : storedSlug;
1385
- console.log("[WWW] render/metadata:storedSlugToSegments nested=", nested, "storedSlug=", storedSlug, "->", JSON.stringify(result));
1386
- return result;
1387
- }
1388
- function buildCanonicalUrl({
1389
- siteUrl,
1390
- locale,
1391
- urlPrefix,
1392
- urlPath
1393
- }) {
1394
- const trimmedPrefix = urlPrefix.replace(/^\/|\/$/g, "");
1395
- const prefixSegment = trimmedPrefix ? `/${trimmedPrefix}` : "";
1396
- const result = `${siteUrl}/${locale}${prefixSegment}${urlPath}`;
1397
- console.log("[WWW] render/metadata:buildCanonicalUrl siteUrl=", siteUrl, "locale=", locale, "urlPrefix=", urlPrefix, "urlPath=", urlPath, "->", result);
1398
- return result;
1399
- }
1400
- function getUrlPath(segments, nested, homeSlug) {
1401
- const urlPath = segmentsToUrlPath(segments, nested);
1402
- if (nested && !Array.isArray(segments)) {
1403
- if (segments === homeSlug)
1404
- return "/";
1405
- } else if (nested && Array.isArray(segments)) {
1406
- const stored = segments.join(SLUG_NESTED_DIVIDER);
1407
- if (stored === homeSlug)
1408
- return "/";
1409
- }
1410
- return urlPath;
1411
- }
1412
-
1413
- // src/render/blocks/renderBlocks.tsx
1414
- import { jsx as jsx3, Fragment } from "react/jsx-runtime";
1415
- var RenderBlocks = ({
1416
- blocks,
1417
- blockProps,
1418
- config,
1419
- importMap,
1420
- locale,
1421
- searchParams
1422
- }) => {
1423
- if (!blocks || !Array.isArray(blocks) || blocks.length === 0) {
1424
- console.log("[WWW] render/blocks:RenderBlocks no blocks (locale=", locale, ")");
1425
- return null;
1426
- }
1427
- console.log("[WWW] render/blocks:RenderBlocks rendering count=", blocks.length, "locale=", locale);
1428
- const rendered = [];
1429
- for (let i = 0;i < blocks.length; i++) {
1430
- const block = blocks[i];
1431
- const { blockType } = block;
1432
- const importMapPath = config.admin?.dependencies?.[blockType]?.path ?? generateImportName("block", blockType);
1433
- const Block = getFromImportMap(importMapPath, importMap);
1434
- if (!Block) {
1435
- console.warn(`[WWW] render/blocks:RenderBlocks no block for type=${blockType} importMapPath=${importMapPath} (locale=${locale})`);
1436
- continue;
1437
- }
1438
- console.log("[WWW] render/blocks:RenderBlocks [", i, "] blockType=", blockType, "importMapPath=", importMapPath);
1439
- rendered.push(/* @__PURE__ */ jsx3(Block, {
1440
- index: i,
1441
- ...blockProps,
1442
- ...block,
1443
- locale,
1444
- searchParams
1445
- }, i));
1446
- }
1447
- return /* @__PURE__ */ jsx3(Fragment, {
1448
- children: rendered
1449
- });
1450
- };
1451
-
1452
- // src/data/seed/createBaseSeed.ts
1453
- var simpleRichText = (text) => ({
1454
- root: {
1455
- type: "root",
1456
- format: "",
1457
- indent: 0,
1458
- version: 1,
1459
- direction: "ltr",
1460
- children: [
1461
- {
1462
- type: "paragraph",
1463
- format: "",
1464
- indent: 0,
1465
- version: 1,
1466
- direction: "ltr",
1467
- textFormat: 0,
1468
- children: [
1469
- { mode: "normal", text, type: "text", style: "", detail: 0, format: 0, version: 1 }
1470
- ]
1471
- }
1472
- ]
1473
- }
1474
- });
1475
- async function createBaseSeed(payload, options = {}) {
1476
- const localization = payload.config.localization;
1477
- const defaultLocale = options.defaultLocale ?? (typeof localization === "object" && localization ? typeof localization.defaultLocale === "string" ? localization.defaultLocale : "en" : "en");
1478
- const configLocales = typeof localization === "object" && localization ? (localization.locales ?? []).map((l) => typeof l === "string" ? l : l.code) : [];
1479
- const locales = options.locales ?? (configLocales.length > 0 ? configLocales : [defaultLocale]);
1480
- const result = { users: [], categories: [], pages: [], posts: [] };
1481
- const pagesCollection = payload.collections["pages"];
1482
- if (!pagesCollection) {
1483
- throw new Error("createBaseSeed: no `pages` collection registered with this payload instance");
1484
- }
1485
- const findBlocksField = (fields) => {
1486
- for (const f of fields) {
1487
- if (f.name === "blocks" && Array.isArray(f.blocks))
1488
- return f;
1489
- if (Array.isArray(f.fields)) {
1490
- const found = findBlocksField(f.fields);
1491
- if (found)
1492
- return found;
1493
- }
1494
- if (Array.isArray(f.tabs)) {
1495
- for (const t of f.tabs) {
1496
- if (Array.isArray(t.fields)) {
1497
- const found = findBlocksField(t.fields);
1498
- if (found)
1499
- return found;
1500
- }
1501
- }
1502
- }
1503
- }
1504
- return;
1505
- };
1506
- const layoutField = findBlocksField(pagesCollection.config.fields);
1507
- const validBlockSlugs = new Set((layoutField?.blocks ?? []).map((b) => b.slug));
1508
- for (const page of options.pages ?? []) {
1509
- for (const block of page.blocks ?? []) {
1510
- const slug = block.blockType;
1511
- if (!slug) {
1512
- throw new Error(`createBaseSeed: page "${page.slug}" has a block without blockType`);
1513
- }
1514
- if (!validBlockSlugs.has(slug)) {
1515
- throw new Error(`createBaseSeed: page "${page.slug}" references unknown block slug "${slug}". Allowed: ${[...validBlockSlugs].join(", ")}`);
1516
- }
1517
- }
1518
- }
1519
- if (options.dryRun)
1520
- return result;
1521
- for (const user of options.users ?? [{ email: "dev@payloadcms.com", password: "test", name: "Dev User" }]) {
1522
- const existing = await payload.find({
1523
- collection: "users",
1524
- where: { email: { equals: user.email } },
1525
- limit: 1,
1526
- overrideAccess: true
1527
- });
1528
- let id;
1529
- if (existing.docs.length > 0) {
1530
- id = existing.docs[0].id;
1531
- } else {
1532
- const created = await payload.create({
1533
- collection: "users",
1534
- data: { email: user.email, password: user.password ?? "test", name: user.name ?? "" },
1535
- overrideAccess: true
1536
- });
1537
- id = created.id;
1538
- }
1539
- result.users.push({ id, email: user.email });
1540
- }
1541
- for (const cat of options.categories ?? []) {
1542
- const slug = cat.slug ?? cat.title.toLowerCase().replace(/\s+/g, "-");
1543
- const existing = await payload.find({
1544
- collection: "categories",
1545
- where: { title: { equals: cat.title } },
1546
- limit: 1,
1547
- overrideAccess: true
1548
- });
1549
- let id;
1550
- if (existing.docs.length > 0) {
1551
- id = existing.docs[0].id;
1552
- } else {
1553
- const created = await payload.create({
1554
- collection: "categories",
1555
- data: { title: cat.title, slug },
1556
- overrideAccess: true
1557
- });
1558
- id = created.id;
1559
- }
1560
- result.categories.push({ id, title: cat.title, slug });
1561
- }
1562
- for (const page of options.pages ?? []) {
1563
- const existing = await payload.find({
1564
- collection: "pages",
1565
- where: { slug: { equals: page.slug } },
1566
- limit: 1,
1567
- overrideAccess: true
1568
- });
1569
- const data = {
1570
- slug: page.slug,
1571
- title: { ...page.title },
1572
- blocks: page.blocks ?? [],
1573
- publishedAt: page.publishedAt ?? new Date().toISOString(),
1574
- _status: page.status === "draft" ? "draft" : "published"
1575
- };
1576
- if (page.meta)
1577
- data.meta = { ...page.meta };
1578
- let id;
1579
- if (existing.docs.length === 0) {
1580
- const created = await payload.create({
1581
- collection: "pages",
1582
- data,
1583
- overrideAccess: true,
1584
- draft: page.status === "draft"
1585
- });
1586
- id = created.id;
1587
- } else {
1588
- id = existing.docs[0].id;
1589
- await payload.update({
1590
- collection: "pages",
1591
- id,
1592
- data,
1593
- overrideAccess: true,
1594
- draft: page.status === "draft"
1595
- });
1596
- }
1597
- for (const locale of locales)
1598
- result.pages.push({ id, slug: page.slug, locale });
1599
- }
1600
- for (const post of options.posts ?? []) {
1601
- const existing = await payload.find({
1602
- collection: "posts",
1603
- where: { slug: { equals: post.slug } },
1604
- limit: 1,
1605
- overrideAccess: true
1606
- });
1607
- const data = {
1608
- slug: post.slug,
1609
- title: { ...post.title },
1610
- ...post.excerpt ? { excerpt: { ...post.excerpt } } : {},
1611
- content: post.content ?? simpleRichText("Hello world"),
1612
- publishedAt: post.publishedAt ?? new Date().toISOString(),
1613
- authors: result.users.length > 0 ? [result.users[0].id] : [],
1614
- _status: post.status === "draft" ? "draft" : "published"
1615
- };
1616
- let id;
1617
- if (existing.docs.length === 0) {
1618
- const created = await payload.create({
1619
- collection: "posts",
1620
- data,
1621
- overrideAccess: true,
1622
- draft: post.status === "draft"
1623
- });
1624
- id = created.id;
1625
- } else {
1626
- id = existing.docs[0].id;
1627
- await payload.update({
1628
- collection: "posts",
1629
- id,
1630
- data,
1631
- overrideAccess: true,
1632
- draft: post.status === "draft"
1633
- });
1634
- }
1635
- for (const locale of locales)
1636
- result.posts.push({ id, slug: post.slug, locale });
1637
- }
1638
- return result;
1639
- }
1640
-
1641
- // src/data/test/createTestPayload.ts
1642
- import { sqliteAdapter } from "@payloadcms/db-sqlite";
1643
- import { flattenAllFields, getPayload as getPayload2, inMemoryKVAdapter } from "payload";
1644
- import path from "node:path";
1645
- import { fileURLToPath } from "node:url";
1646
- async function createTestPayload(options = {}) {
1647
- const filename = fileURLToPath(import.meta.url);
1648
- const dirname = path.dirname(filename);
1649
- const databaseFile = options.databaseFile ?? path.join(dirname, `.test-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
1650
- const locales = options.locales ?? ["en", "uk"];
1651
- const defaultLocale = locales[0] ?? "en";
1652
- const blocks = options.blocks ?? [];
1653
- const { withWWWConfig } = createWWWConfig({ locales: [...locales], blocks });
1654
- const config = await withWWWConfig({
1655
- admin: { user: "users" },
1656
- blocks: [],
1657
- collections: [
1658
- {
1659
- slug: "posts",
1660
- access: { read: () => true },
1661
- fields: [{ name: "title", type: "text" }]
1662
- }
1663
- ],
1664
- globals: [],
1665
- db: sqliteAdapter({
1666
- client: { url: `file:${databaseFile}` },
1667
- push: false
1668
- }),
1669
- secret: "test-secret-do-not-use-in-prod",
1670
- sharp: (await import("sharp")).default,
1671
- editor: {},
1672
- localization: { locales: [...locales], defaultLocale },
1673
- kv: inMemoryKVAdapter(),
1674
- typescript: { outputFile: "./payload-types.ts" }
1675
- });
1676
- const registered = new Set([
1677
- ...(config.collections ?? []).map((c) => c.slug),
1678
- ...(config.globals ?? []).map((g) => g.slug)
1679
- ]);
1680
- const findMissing = (fields) => {
1681
- const out = [];
1682
- const walk = (f) => {
1683
- if (Array.isArray(f)) {
1684
- for (const child of f)
1685
- walk(child);
1686
- return;
1687
- }
1688
- if (f.relationTo) {
1689
- const rels = Array.isArray(f.relationTo) ? f.relationTo : [f.relationTo];
1690
- for (const r of rels) {
1691
- if (typeof r === "string" && !registered.has(r))
1692
- out.push(r);
1693
- }
1694
- }
1695
- if (Array.isArray(f.fields))
1696
- walk(f.fields);
1697
- };
1698
- for (const f of fields)
1699
- walk(f);
1700
- return out;
1701
- };
1702
- for (const c of config.collections ?? []) {
1703
- const missing = findMissing(c.fields ?? []);
1704
- if (missing.length)
1705
- console.log("collection", c.slug, "missing relations:", missing);
1706
- }
1707
- for (const g of config.globals ?? []) {
1708
- const missing = findMissing(g.fields ?? []);
1709
- if (missing.length)
1710
- console.log("global", g.slug, "missing relations:", missing);
1711
- }
1712
- for (const c of config.collections ?? []) {
1713
- if (c.fields) {
1714
- c.flattenedFields = flattenAllFields({ fields: c.fields });
1715
- }
1716
- if (c.upload === undefined)
1717
- c.upload = false;
1718
- c.sanitizedIndexes = c.sanitizedIndexes ?? [];
1719
- c.polymorphicJoins = c.polymorphicJoins ?? [];
1720
- if (options.overridePagesVersions && c.slug === "pages") {
1721
- c.versions = false;
1722
- }
1723
- }
1724
- for (const g of config.globals ?? []) {
1725
- if (g.fields) {
1726
- g.flattenedFields = flattenAllFields({ fields: g.fields });
1727
- }
1728
- g.sanitizedIndexes = g.sanitizedIndexes ?? [];
1729
- }
1730
- const payload = await getPayload2({ config });
1731
- let destroyed = false;
1732
- const destroy = async () => {
1733
- if (destroyed)
1734
- return;
1735
- destroyed = true;
1736
- try {
1737
- await payload.destroy();
1738
- } catch {}
1739
- };
1740
- return { payload, databaseFile, destroy };
1741
- }
1742
-
1743
- // src/render/pages/createCollectionPageExports.tsx
1744
- import"server-only";
1745
- import { Suspense } from "react";
1746
- import { RichText } from "@payloadcms/richtext-lexical/react";
1747
-
1748
- // src/render/pages/PagesPage.tsx
1749
- import { jsx as jsx4, Fragment as Fragment2 } from "react/jsx-runtime";
1750
- async function PagesPage({ doc, ...props }) {
1751
- if (!doc) {
1752
- console.log("[WWW] render/pages:PagesPage no doc");
1753
- return /* @__PURE__ */ jsx4(Fragment2, {});
1754
- }
1755
- const blocks = doc.blocks ?? [];
1756
- console.log("[WWW] render/pages:PagesPage blocks=", blocks.length, "locale=", props.locale);
1757
- return /* @__PURE__ */ jsx4(Fragment2, {
1758
- children: /* @__PURE__ */ jsx4(RenderBlocks, {
1759
- blocks,
1760
- ...props
1761
- })
1762
- });
1763
- }
1764
-
1765
- // src/render/pages/createCollectionPageExports.tsx
1766
- import { jsx as jsx7, jsxs as jsxs3, Fragment as Fragment4 } from "react/jsx-runtime";
1767
- var HOME_SLUG = "";
1768
- function createCollectionPageExports({
1769
- slug = "pages",
1770
- config: configPromise,
1771
- routing,
1772
- importMap: importMapArg,
1773
- renderPath,
1774
- nested = false
1775
- }, deps, options = {}) {
1776
- const importMap = importMapArg ?? {};
1777
- const { jsonLd: jsonLdOption = true, changefreq = "weekly", priority = 0.5, websiteName } = options;
1778
- const {
1779
- getServerSideURL,
1780
- generateMeta,
1781
- metadataType: metadataTypeOverride,
1782
- showcase: showcaseOption,
1783
- homeExtras
1784
- } = deps;
1785
- const showcaseEnabled = showcaseOption?.enabled === true;
1786
- const { metadataHeading, jsonLdHeading } = showcaseOption ?? {};
1787
- const locales = routing.locales;
1788
- const defaultLocale = routing.defaultLocale;
1789
- const metadataType = metadataTypeOverride ?? (slug === POSTS_SLUG ? "article" : "website");
1790
- const defaultRenderPath = slug === POSTS_SLUG ? POSTS_RENDER_PATH : PAGES_RENDER_PATH;
1791
- const localePrefixMode = typeof routing.localePrefix === "string" ? routing.localePrefix : routing.localePrefix?.mode ?? "always";
1792
- const buildLocalePath = (locale, storedSlug) => {
1793
- const urlPath = getUrlPath(storedSlugToSegments(storedSlug, nested), nested, HOME_SLUG);
1794
- let result;
1795
- if (localePrefixMode === "never")
1796
- result = urlPath;
1797
- else if (localePrefixMode === "as-needed" && locale === defaultLocale)
1798
- result = urlPath;
1799
- else
1800
- result = `/${locale}${urlPath}`;
1801
- console.log("[WWW] render/pages:createCollectionPageExports:buildLocalePath locale=", locale, "storedSlug=", storedSlug, "->", result);
1802
- return result;
1803
- };
1804
- async function fetchDoc(locale, storedSlug, draft = false) {
1805
- return queryDocBySlug({
1806
- collectionSlug: slug,
1807
- slug: storedSlug,
1808
- locale,
1809
- draft,
1810
- config: configPromise
1811
- });
1812
- }
1813
- async function resolveHreflangAlternates(locale, storedSlug) {
1814
- const siteUrl = getServerSideURL();
1815
- const urlPath = buildLocalePath(locale, storedSlug);
1816
- const canonical = `${siteUrl}${urlPath}`;
1817
- const languages = await buildHreflangAlternates({
1818
- siteUrl,
1819
- locale,
1820
- urlPrefix: "",
1821
- storedSlug,
1822
- nested,
1823
- homeSlug: HOME_SLUG,
1824
- defaultLocale,
1825
- locales,
1826
- localePrefix: localePrefixMode,
1827
- queryAllLocaleSlugs: (s, l) => queryAllLocaleSlugs({ collectionSlug: slug, slug: s, slugField: "slug", locale: l, config: configPromise })
1828
- });
1829
- const alternates = {};
1830
- for (const [key, url] of Object.entries(languages)) {
1831
- alternates[key] = url;
1832
- }
1833
- console.log("[WWW] render/pages:createCollectionPageExports:resolveHreflangAlternates canonical=", canonical, "alts=", JSON.stringify(alternates));
1834
- return { alternates, canonical };
1835
- }
1836
- const default_ = async (props) => {
1837
- const { slug: rawSlugSegments, locale: incomingLocale } = await props.params ?? {};
1838
- const slugSegments = Array.isArray(rawSlugSegments) ? rawSlugSegments : [];
1839
- const locale = typeof incomingLocale === "string" ? incomingLocale : defaultLocale;
1840
- console.log("[WWW] render/pages:createCollectionPageExports:default_ collectionSlug=", slug, "locale=", locale, "segments=", JSON.stringify(slugSegments), "showcase=", showcaseEnabled);
1841
- if (!locales.includes(locale)) {
1842
- console.error(`[WWW] render/pages:createCollectionPageExports:default_ notFound invalid-locale collection=${slug} locale=${locale} segments=${JSON.stringify(slugSegments)}`);
1843
- const { notFound } = await import("next/navigation");
1844
- notFound();
1845
- }
1846
- const { setRequestLocale } = await import("next-intl/server");
1847
- setRequestLocale(locale);
1848
- const { draftMode } = await import("next/headers");
1849
- const { isEnabled: draft } = await draftMode();
1850
- console.log("[WWW] render/pages:createCollectionPageExports:default_ draftMode=", draft);
1851
- const storedSlug = segmentsToStoredSlug(slugSegments, nested);
1852
- const doc = await fetchDoc(locale, storedSlug, draft);
1853
- if (!doc) {
1854
- console.error(`[WWW] render/pages:createCollectionPageExports:default_ notFound no-doc collection=${slug} locale=${locale} storedSlug="${storedSlug}" segments=${JSON.stringify(slugSegments)} draft=${draft}`);
1855
- const { notFound } = await import("next/navigation");
1856
- notFound();
1857
- }
1858
- const cfg = await configPromise;
1859
- const collectionCustomPath = cfg.collections.find((c) => c.slug === slug)?.custom?.path;
1860
- const effectivePath = renderPath ?? collectionCustomPath ?? defaultRenderPath;
1861
- console.log("[WWW] render/pages:createCollectionPageExports:default_ effectivePath=", effectivePath);
1862
- const render = effectivePath === PAGES_RENDER_PATH ? /* @__PURE__ */ jsx7(PagesPage, {
1863
- doc,
1864
- importMap,
1865
- config: cfg,
1866
- locale
1867
- }) : effectivePath === POSTS_RENDER_PATH ? doc ? await renderPostBody(doc, locale) : null : renderCollectionModule(cfg.collections, slug, importMap, {
1868
- ...props,
1869
- config: cfg,
1870
- locale,
1871
- searchParams: props.searchParams,
1872
- doc
1873
- });
1874
- const jsonLdNodes = doc ? await generateJsonLd(slugSegments, doc, locale) : [];
1875
- const { alternates: hreflangAlternates, canonical } = await resolveHreflangAlternates(locale, storedSlug);
1876
- const inner = /* @__PURE__ */ jsxs3(Fragment4, {
1877
- children: [
1878
- jsonLdNodes.map(({ id, schema }) => /* @__PURE__ */ jsx7("script", {
1879
- type: "application/ld+json",
1880
- dangerouslySetInnerHTML: { __html: JSON.stringify(schema) }
1881
- }, id)),
1882
- render,
1883
- draft ? (() => {
1884
- const ResolvedListener = importMap?.[LIVE_PREVIEW_LISTENER_PATH];
1885
- if (!ResolvedListener)
1886
- return null;
1887
- return /* @__PURE__ */ jsx7(Suspense, {
1888
- fallback: null,
1889
- children: /* @__PURE__ */ jsx7(ResolvedListener, {})
1890
- });
1891
- })() : null,
1892
- storedSlug === HOME_SLUG && homeExtras ? await homeExtras({ locale, doc }) : null
1893
- ]
1894
- });
1895
- if (!showcaseEnabled || !doc)
1896
- return inner;
1897
- const { PageShowcase: PageShowcase2 } = await Promise.resolve().then(() => (init_PageShowcase(), exports_PageShowcase));
1898
- const { LocaleSwitcher: LocaleSwitcher2 } = await Promise.resolve().then(() => (init_LocaleSwitcher(), exports_LocaleSwitcher));
1899
- const meta = await generateMeta({
1900
- doc,
1901
- url: canonical,
1902
- type: metadataType,
1903
- locale
1904
- });
1905
- return /* @__PURE__ */ jsx7(PageShowcase2, {
1906
- metadata: meta,
1907
- metadataHeading,
1908
- jsonLdHeading,
1909
- jsonLd: jsonLdNodes,
1910
- localeSwitcher: /* @__PURE__ */ jsx7(LocaleSwitcher2, {
1911
- currentLocale: locale,
1912
- hreflangAlternates,
1913
- labels: routing.labels
1914
- }),
1915
- children: inner
1916
- });
1917
- };
1918
- async function generateMetadata(props) {
1919
- const cfg = await configPromise;
1920
- const { slug: rawSlugSegments, locale: incomingLocale } = await props.params ?? {};
1921
- const slugSegments = Array.isArray(rawSlugSegments) ? rawSlugSegments : [];
1922
- const locale = typeof incomingLocale === "string" ? incomingLocale : defaultLocale;
1923
- console.log("[WWW] render/pages:createCollectionPageExports:generateMetadata collectionSlug=", slug, "locale=", locale, "segments=", JSON.stringify(slugSegments));
1924
- if (!locales.includes(locale)) {
1925
- console.log("[WWW] render/pages:createCollectionPageExports:generateMetadata invalid locale -> not found meta");
1926
- return { title: "Not found", robots: { index: false, follow: false } };
1927
- }
1928
- const storedSlug = segmentsToStoredSlug(slugSegments, nested);
1929
- const doc = await fetchDoc(locale, storedSlug);
1930
- if (!doc) {
1931
- console.log("[WWW] render/pages:createCollectionPageExports:generateMetadata no doc -> not found meta");
1932
- return { title: "Not found", robots: { index: false, follow: false } };
1933
- }
1934
- const collection = cfg.collections.find((c) => c.slug === slug);
1935
- if (!collection) {
1936
- console.warn("[WWW] render/pages:createCollectionPageExports:generateMetadata collection not in config slug=", slug);
1937
- return {};
1938
- }
1939
- const { canonical, alternates } = await resolveHreflangAlternates(locale, storedSlug);
1940
- const meta = await generateMeta({
1941
- doc,
1942
- url: canonical,
1943
- type: metadataType,
1944
- locale
1945
- });
1946
- meta.alternates = {
1947
- canonical,
1948
- languages: Object.keys(alternates).length ? alternates : undefined
1949
- };
1950
- return meta;
1951
- }
1952
- async function generateJsonLd(slugSegments, doc, locale) {
1953
- if (jsonLdOption === false || !doc)
1954
- return [];
1955
- const siteUrl = getServerSideURL();
1956
- const storedSlug = segmentsToStoredSlug(slugSegments, nested);
1957
- const urlPath = buildLocalePath(locale, storedSlug);
1958
- const canonical = `${siteUrl}${urlPath}`;
1959
- const entries = Array.isArray(jsonLdOption) ? jsonLdOption : metadataType === "article" ? [{ type: "article" }] : [{ type: "website" }];
1960
- console.log("[WWW] render/pages:createCollectionPageExports:generateJsonLd collection=", slug, "locale=", locale, "entries=", entries.map((e) => e.type).join(","));
1961
- const outputs = [];
1962
- for (const entry of entries) {
1963
- const id = entry.id ?? `jsonld-${entry.type}-${outputs.length}`;
1964
- let schema = null;
1965
- switch (entry.type) {
1966
- case "article": {
1967
- const articleOpts = {
1968
- doc,
1969
- url: canonical,
1970
- locale,
1971
- siteUrl,
1972
- type: entry.schemaType ?? "BlogPosting"
1973
- };
1974
- if (entry.publisherName !== undefined)
1975
- articleOpts.publisherName = entry.publisherName;
1976
- if (entry.publisherLogo !== undefined)
1977
- articleOpts.publisherLogo = entry.publisherLogo;
1978
- schema = buildArticleLd(articleOpts);
1979
- break;
1980
- }
1981
- case "website": {
1982
- schema = {
1983
- "@context": "https://schema.org",
1984
- "@type": "WebSite",
1985
- "@id": `${siteUrl}#website`,
1986
- url: siteUrl,
1987
- name: entry.name ?? websiteName ?? new URL(siteUrl).hostname,
1988
- ...entry.alternateName ? { alternateName: entry.alternateName } : {},
1989
- inLanguage: locale
1990
- };
1991
- break;
1992
- }
1993
- case "organization": {
1994
- schema = buildOrganizationLd({
1995
- siteUrl,
1996
- name: entry.name,
1997
- logo: entry.logo,
1998
- sameAs: entry.sameAs
1999
- });
2000
- break;
2001
- }
2002
- case "breadcrumbs": {
2003
- let items = entry.items ?? [];
2004
- if (!items.length && entry.buildItems)
2005
- items = entry.buildItems(doc, canonical);
2006
- if (items.length > 0)
2007
- schema = buildBreadcrumbsLd({ items, currentUrl: canonical });
2008
- break;
2009
- }
2010
- case "custom": {
2011
- schema = entry.build({ doc, url: canonical, locale, siteUrl });
2012
- break;
2013
- }
2014
- }
2015
- if (schema)
2016
- outputs.push({ id, schema });
2017
- }
2018
- return outputs;
2019
- }
2020
- async function generateStaticParams() {
2021
- console.log("[WWW] render/pages:createCollectionPageExports:generateStaticParams collection=", slug, "locales=", JSON.stringify(locales));
2022
- const params = [];
2023
- for (const locale of locales) {
2024
- const docs = await queryAllDocs({ collectionSlug: slug, slugField: "slug", locale, config: configPromise });
2025
- for (const doc of docs) {
2026
- const slugVal = doc.slug;
2027
- if (typeof slugVal !== "string" || slugVal === "")
2028
- continue;
2029
- const segments = storedSlugToSegments(slugVal, nested);
2030
- params.push({ slug: Array.isArray(segments) ? segments : [segments], locale });
2031
- }
2032
- }
2033
- console.log("[WWW] render/pages:createCollectionPageExports:generateStaticParams -> count=", params.length);
2034
- return params;
2035
- }
2036
- async function generateSitemap() {
2037
- console.log("[WWW] render/pages:createCollectionPageExports:generateSitemap collection=", slug, "locales=", JSON.stringify(locales));
2038
- const docs = await queryAllDocs({
2039
- collectionSlug: slug,
2040
- slugField: "slug",
2041
- locale: defaultLocale,
2042
- config: configPromise
2043
- });
2044
- const siteUrl = getServerSideURL().replace(/\/$/, "");
2045
- const urls = [];
2046
- for (const doc of docs) {
2047
- const slugVal = doc.slug;
2048
- if (typeof slugVal !== "string" || slugVal === "")
2049
- continue;
2050
- for (const locale of locales) {
2051
- const urlPath = buildLocalePath(locale, slugVal);
2052
- const updatedAt = doc.updatedAt;
2053
- const lastmod = typeof updatedAt === "string" ? new Date(updatedAt).toISOString() : undefined;
2054
- urls.push({ url: `${siteUrl}${urlPath}`, lastModified: lastmod, changeFrequency: changefreq, priority });
2055
- }
2056
- }
2057
- console.log("[WWW] render/pages:createCollectionPageExports:generateSitemap -> urls=", urls.length);
2058
- return urls;
2059
- }
2060
- return {
2061
- default: default_,
2062
- generateMetadata,
2063
- generateStaticParams,
2064
- generateSitemap,
2065
- generateJsonLd
2066
- };
2067
- }
2068
- function addCollectionsToSitemap(exports) {
2069
- async function buildSitemap() {
2070
- const all = await Promise.all(exports.map((e) => e.generateSitemap()));
2071
- return all.flat();
2072
- }
2073
- return { default: buildSitemap, generateSitemap: buildSitemap };
2074
- }
2075
- async function renderPostBody(doc, locale) {
2076
- const typedDoc = doc;
2077
- const title = typedDoc.title ?? "";
2078
- const excerpt = typedDoc.excerpt ?? null;
2079
- const content = typedDoc.content;
2080
- return /* @__PURE__ */ jsxs3("article", {
2081
- className: "posts-page prose prose-neutral dark:prose-invert mx-auto max-w-3xl py-10",
2082
- children: [
2083
- /* @__PURE__ */ jsxs3("header", {
2084
- className: "posts-page__header not-prose mb-8",
2085
- children: [
2086
- /* @__PURE__ */ jsx7("h1", {
2087
- className: "posts-page__title text-4xl font-semibold tracking-tight",
2088
- children: title
2089
- }),
2090
- excerpt ? /* @__PURE__ */ jsx7("p", {
2091
- className: "posts-page__excerpt mt-3 text-lg text-muted-foreground",
2092
- children: excerpt
2093
- }) : null
2094
- ]
2095
- }),
2096
- content ? /* @__PURE__ */ jsx7("div", {
2097
- className: "posts-page__content",
2098
- children: /* @__PURE__ */ jsx7(RichText, {
2099
- data: content
2100
- })
2101
- }) : null
2102
- ]
2103
- });
2104
- }
2105
-
2106
- // src/render/pages/createStaticPageExports.tsx
2107
- import"server-only";
2108
- import { jsx as jsx8 } from "react/jsx-runtime";
2109
- function createStaticPageExports({
2110
- kind = "not-found",
2111
- config: configPromise,
2112
- importMap: importMapArg
2113
- }) {
2114
- const importMap = importMapArg ?? {};
2115
- let dbgRenderCount = 0;
2116
- const default_ = async () => {
2117
- const { getLocale } = await import("next-intl/server");
2118
- const locale = await getLocale();
2119
- console.log("[WWW] render/pages:createStaticPageExports:default_ kind=", kind, "locale=", locale);
2120
- dbgRenderCount++;
2121
- {
2122
- let reqUrl = "?";
2123
- try {
2124
- const { headers } = await import("next/headers");
2125
- const h = await headers();
2126
- reqUrl = h.get("x-invoke-path") || h.get("x-matched-path") || h.get("x-next-url") || h.get("next-url") || h.get("referer") || "?";
2127
- } catch {}
2128
- console.error(`[WWW-DBG static-render #${dbgRenderCount}] kind=${kind} locale=${locale} url=${reqUrl}`);
2129
- if (dbgRenderCount <= 5) {
2130
- console.error(`[WWW-DBG static-render #${dbgRenderCount}] stack:
2131
- ` + (new Error("static-render").stack?.split(`
2132
- `).slice(2, 12).join(`
2133
- `) ?? ""));
2134
- }
2135
- }
2136
- const doc = await queryDocBySlug({
2137
- collectionSlug: STATIC_PAGES_SLUG,
2138
- slug: kind,
2139
- slugField: "kind",
2140
- locale,
2141
- config: configPromise
2142
- });
2143
- if (!doc) {
2144
- console.warn("[createStaticPageExports] !doc: STATIC_PAGES_SLUG=", STATIC_PAGES_SLUG, "slug:" + kind);
2145
- return /* @__PURE__ */ jsx8("section", {
2146
- children: /* @__PURE__ */ jsx8("h1", {
2147
- children: "404"
2148
- })
2149
- });
2150
- }
2151
- const cfg = await configPromise;
2152
- console.log("[WWW] render/pages:createStaticPageExports:default_ -> rendering via PagesPage kind=", kind, "locale=", locale);
2153
- return /* @__PURE__ */ jsx8(PagesPage, {
2154
- doc,
2155
- locale,
2156
- importMap,
2157
- config: cfg
2158
- });
2159
- };
2160
- return { default: default_ };
2161
- }
2162
-
2163
- // src/data/collections/previewPath.ts
2164
- var collectionPrefixMap = {
2165
- posts: "/posts",
2166
- pages: ""
2167
- };
2168
- function generatePreviewPath({
2169
- collection,
2170
- slug
2171
- }) {
2172
- if (slug === undefined || slug === null)
2173
- return null;
2174
- const encodedSlug = encodeURIComponent(slug);
2175
- const params = new URLSearchParams({
2176
- path: `${collectionPrefixMap[collection] ?? ""}/${encodedSlug}`,
2177
- previewSecret: process.env.PREVIEW_SECRET || ""
2178
- });
2179
- return `/next/preview?${params.toString()}`;
2180
- }
2181
-
2182
- // src/exports/server.ts
2183
- var server_default = createWWWConfig;
2184
- export {
2185
- storedSlugToSegments,
2186
- segmentsToUrlPath,
2187
- segmentsToStoredSlug,
2188
- renderGlobalModule,
2189
- renderCollectionModule,
2190
- queryGlobal,
2191
- queryDocBySlug,
2192
- queryAllLocaleSlugs,
2193
- queryAllDocs,
2194
- linkGroup,
2195
- link,
2196
- getUrlPath,
2197
- getRenderModuleExports,
2198
- getFromImportMap,
2199
- getCachedGlobal,
2200
- generatePreviewPath,
2201
- generateImportName,
2202
- server_default as default,
2203
- createWWWConfig,
2204
- createTestPayload,
2205
- createStaticPagesCollection,
2206
- createStaticPageExports,
2207
- createRevalidatePageHooks,
2208
- createRevalidateGlobalHook,
2209
- createRevalidateCollectionHook,
2210
- createPostsCollection,
2211
- createPagesCollection,
2212
- createHeaderGlobal,
2213
- createFooterGlobal,
2214
- createCollectionPageExports,
2215
- createBaseSeed,
2216
- buildOrganizationLd,
2217
- buildHreflangAlternates,
2218
- buildCanonicalUrl,
2219
- buildBreadcrumbsLd,
2220
- buildArticleLd,
2221
- authenticatedOrPublished,
2222
- authenticated,
2223
- appearanceOptions,
2224
- anyone,
2225
- addCollectionsToSitemap,
2226
- STATIC_PAGES_SLUG,
2227
- RenderBlocks,
2228
- POSTS_SLUG2 as POSTS_SLUG,
2229
- PAGES_SLUG2 as PAGES_SLUG,
2230
- HOME_PAGE_SLUG
2231
- };