Files
ipal-kit/src/modules/seed/values.ts
T
Radosław SmolińskiandClaude Opus 5.5 3645e61f7d Fixes from the reference site: 404 page unlisted, own-origin media, fillGlobal defaults, switcher docs
- sitemap, llms.txt and the site index leave out the page assigned as the 404
  page (unlistedPageIds, exported); it stays when it is also the homepage
- buildImagesConfig: in production with R2_PUBLIC_URL empty, allow the site's
  own /api/media/file/** so next/image no longer answers 400
- fillGlobal: a choice field (select, radio, checkbox, number, date) still at its
  defaultValue counts as empty; text is never overwritten
- docs: LanguageSwitcher renderLabel needs a 'use client' wrapper (i18n.md,
  ipal-site, ipal-setup, api.md)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:29:07 +01:00

199 lines
8.7 KiB
TypeScript

import type { BasePayload } from 'payload'
import { createHash } from 'node:crypto'
/**
* Seed values — content written once, every language side by side:
*
* heading: { pl: 'Nasze usługi', en: 'Our services' } → localized: one value per locale
* heading: 'Nasze usługi' → the same value in every locale
*
* An object counts as localized when every key is one of the config's locale
* codes. A locale missing from it is left untouched in that locale.
*/
export type SeedValue = { [key: string]: SeedValue } | boolean | null | number | SeedValue[] | string
/** Locale codes and the default locale of a Payload config ([] / undefined without localization). */
export function localesOf(payload: BasePayload): { codes: string[]; defaultLocale: string | undefined } {
const loc = payload.config.localization
return loc ? { codes: loc.localeCodes, defaultLocale: loc.defaultLocale } : { codes: [], defaultLocale: undefined }
}
const isPlainObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
export function isLocalizedValue(v: unknown, codes: string[]): v is Record<string, unknown> {
return isPlainObject(v) && Object.keys(v).length > 0 && Object.keys(v).every((k) => codes.includes(k))
}
/**
* The value for one locale. Arrays (array fields, blocks) keep the ids of the
* rows already stored at the same index — new ids would wipe the other
* locales' texts. A block row keeps its id only when its blockType matches.
* undefined = leave the field out.
*/
export function localize(value: unknown, locale: string | undefined, existing: unknown, codes: string[]): unknown {
if (isLocalizedValue(value, codes)) {return locale ? value[locale] : undefined}
if (Array.isArray(value)) {
const rows = Array.isArray(existing) ? (existing as unknown[]) : []
return value.map((item, i) => {
const row = rows[i] as Record<string, unknown> | undefined
const out = localize(item, locale, row, codes)
if (!isPlainObject(out) || !row?.id) {return out ?? null}
if (out.blockType !== undefined && row.blockType !== undefined && out.blockType !== row.blockType) {return out}
return { ...out, id: row.id }
})
}
if (isPlainObject(value)) {
const ex = isPlainObject(existing) ? existing : {}
const out: Record<string, unknown> = {}
for (const [k, v] of Object.entries(value)) {
const r = localize(v, locale, ex[k], codes)
if (r !== undefined) {out[k] = r}
}
return out
}
return value
}
/** JSON with sorted keys, no row ids, null = missing — equal content gives equal text. */
function stable(v: unknown): string {
if (Array.isArray(v)) {return `[${v.map(stable).join(',')}]`}
if (isPlainObject(v)) {
return `{${Object.keys(v)
.filter((k) => k !== 'id' && v[k] != null)
.sort()
.map((k) => `${JSON.stringify(k)}:${stable(v[k])}`)
.join(',')}}`
}
return JSON.stringify(v ?? null)
}
/** Hash of seeded values: key order, row ids and nulls don't change it. */
export function seedHash(value: unknown): string {
return createHash('sha256').update(stable(value)).digest('hex').slice(0, 32)
}
/** The current values at the keys the seed writes — everything else in the record is ignored. */
export function projectOnto(seed: unknown, current: unknown): unknown {
if (Array.isArray(seed)) {
return Array.isArray(current) && current.length === seed.length ? seed.map((s, i) => projectOnto(s, current[i])) : current
}
if (isPlainObject(seed)) {
if (!isPlainObject(current)) {return current}
return Object.fromEntries(Object.keys(seed).map((k) => [k, projectOnto(seed[k], current[k])]))
}
return current
}
export type EditedSinceSeedArgs = {
/**
* Hash of the record's CURRENT values at the seeded keys (seedHash of
* projectOnto per locale). Needed only when the record stores a hash.
*/
currentHash?: string
/** The stored record (default locale) — reads createdAt, updatedAt and the hash field. */
doc: Record<string, unknown>
/** Hash field name. Default SEED_HASH_FIELD or 'seedHash'; false = timestamps only. */
hashField?: false | string
/** "Untouched" window for the timestamp method. Default SEED_UNTOUCHED_SECONDS or 120. */
untouchedSeconds?: number
}
export const defaultHashField = (): false | string => {
const v = process.env.SEED_HASH_FIELD
return v === undefined ? 'seedHash' : v || false
}
export const defaultUntouchedSeconds = (): number => {
const n = Number(process.env.SEED_UNTOUCHED_SECONDS ?? 120)
return Number.isFinite(n) ? n : 120
}
/**
* null when nobody edited the record since seeding; otherwise why it counts
* as edited. A stored hash decides when present; else updatedAt must be at
* most `untouchedSeconds` after createdAt.
*/
export function editedSinceSeed({
currentHash,
doc,
hashField = defaultHashField(),
untouchedSeconds = defaultUntouchedSeconds(),
}: EditedSinceSeedArgs): null | string {
const stored = hashField ? doc[hashField] : undefined
if (typeof stored === 'string' && stored) {
return currentHash === stored ? null : `${hashField as string} differs`
}
const c = Date.parse(String(doc.createdAt))
const u = Date.parse(String(doc.updatedAt))
if (!Number.isFinite(c) || !Number.isFinite(u)) {return 'no createdAt/updatedAt'}
const s = Math.round((u - c) / 1000)
return s <= untouchedSeconds ? null : `updated ${s}s after creation`
}
export type SeedTarget = { collection: string; id: number | string } | { global: string }
export type WriteLocalesOptions = {
/** Passed to every write — see docs/seeding.md § Context flags. */
context?: Record<string, unknown>
/** Read the latest draft for row ids (collections with drafts). */
draft?: boolean
}
/** Reads a record in one locale, never filling gaps from the fallback locale. */
export function readSeedTarget(payload: BasePayload, target: SeedTarget, locale: string | undefined, draft = false) {
const loc = locale ? { fallbackLocale: false as never, locale: locale as never } : {}
return ('global' in target
? payload.findGlobal({ slug: target.global as never, depth: 0, ...loc })
: payload.findByID({ id: target.id, collection: target.collection as never, depth: 0, ...(draft ? { draft } : {}), ...loc })) as Promise<
Record<string, unknown>
>
}
/**
* Writes seed values to an existing record in every locale: the default locale
* first (it creates the rows), then each other locale with
* `fallbackLocale: false` onto the same row ids.
*/
export async function writeLocales(
payload: BasePayload,
target: SeedTarget,
data: Record<string, unknown>,
{ context = {}, draft = false }: WriteLocalesOptions = {},
): Promise<void> {
const { codes, defaultLocale } = localesOf(payload)
const write = (value: unknown, locale: string | undefined) => {
const loc = locale ? { fallbackLocale: false as never, locale: locale as never } : {}
return 'global' in target
? payload.updateGlobal({ slug: target.global as never, context, data: value as never, depth: 0, ...loc })
: payload.update({ id: target.id, collection: target.collection as never, context, data: value as never, depth: 0, ...loc })
}
await write(localize(data, defaultLocale, await readSeedTarget(payload, target, defaultLocale, draft), codes), defaultLocale)
const others = codes.filter((c) => c !== defaultLocale)
if (!others.length) {return}
const rows = await readSeedTarget(payload, target, defaultLocale, draft)
for (const locale of others) {await write(localize(data, locale, rows, codes), locale)}
}
/** True when a value has content (non-empty text, a number, true, or a nested one). */
/** Field types whose stored value is a choice, not text an editor wrote. */
const CHOICE_TYPES = new Set(['checkbox', 'date', 'number', 'point', 'radio', 'select'])
/**
* A global field nobody has set yet: empty, or — for a choice (select, radio, checkbox, number, date) —
* still holding the field's own `defaultValue`, which Payload stores on the first save of the global.
* Text an editor wrote is never "unset", even when it equals a default.
*/
export function isUnsetValue(value: unknown, field?: { defaultValue?: unknown; type?: string }): boolean {
if (!hasContent(value)) {return true}
if (!field || !CHOICE_TYPES.has(field.type ?? '') || field.defaultValue === undefined || typeof field.defaultValue === 'function') {return false}
return JSON.stringify(value) === JSON.stringify(field.defaultValue)
}
export function hasContent(v: unknown): boolean {
if (typeof v === 'string') {return v.trim() !== ''}
if (typeof v === 'number' || v === true) {return true}
if (Array.isArray(v)) {return v.some(hasContent)}
if (isPlainObject(v)) {return Object.entries(v).some(([k, x]) => k !== 'id' && hasContent(x))}
return false
}