Stable admin import map without R2 env, read-only media, Cookie Settings save-button migration
buildR2Storage registered nothing without R2_* env, so `pnpm dev` / generate:importmap in dev
wrote an importMap.js without S3ClientUploadHandler — committed, the production admin (R2 on)
rendered a blank page with no console error (hit vanstev.pl). The injected s3Storage is now
always registered (enabled: false without R2 → local disk); storage-s3 still adds its client
handler, so the import map is identical in every environment. ipal-audit flags an import map
without the handler.
R2_PUBLIC_URL alone (absolute, outside production) = read-only media: URLs from the media
domain, upload/delete refused with 403 — local dev against a production database without
bucket keys. ipalEnvRules allows it in development.
Cookie Settings (MongoDB): the 1.11.1 rename buttons.save → savePreferences lost the texts on
the first save; onInit copies the old value (all locales) when the new field is missing.
getConsentTexts read the old field as a string, Mongo returns the raw { pl, en } map.
Also: context.ipalSkipAutoFill (SKIP_AUTO_FILL) — save without meta / aiSummary auto-fill;
createPageRoute redirects the homepage under its own slug (homeAlias, default 'redirect');
ipal-audit: multi-line tsconfig exclude, numeronyms (a11y) not "numbered fields",
`${prefix}/${slug}` links and slugs typed into links detected, clearer panel-language message.
Docs: fallback-on-save in i18n.md, `pnpm up --latest` and the stale-token 401 in PROGRAMISTA §1.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
2c3195c4e1
commit
e1431a7c49
@@ -0,0 +1,39 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
type MongoGlobals = {
|
||||
collection?: {
|
||||
updateOne: (
|
||||
filter: Record<string, unknown>,
|
||||
update: Record<string, unknown>[],
|
||||
) => Promise<{ modifiedCount?: number }>
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1.11.1 renamed Cookie Settings `buttons.save` → `buttons.savePreferences` (Mongoose
|
||||
* reserves `save`). MongoDB keeps the old key, but the first save of the global — panel
|
||||
* or script — rewrites the document without it, and the button text silently falls back
|
||||
* to "Save preferences" in every language. Runs once per start: copies the old value
|
||||
* (all locales at once) into the new field when the new one is still missing.
|
||||
* SQL adapters: the column rename happens in the migration (`migrate:create` → rename).
|
||||
*/
|
||||
export async function migrateCookieSettingsSaveButton(payload: BasePayload): Promise<void> {
|
||||
if (payload.db.name !== 'mongoose') {return}
|
||||
const globals = (payload.db as unknown as { globals?: MongoGlobals }).globals
|
||||
if (!globals?.collection) {return}
|
||||
try {
|
||||
const result = await globals.collection.updateOne(
|
||||
{
|
||||
'buttons.save': { $exists: true },
|
||||
'buttons.savePreferences': { $exists: false },
|
||||
globalType: 'cookie-settings',
|
||||
},
|
||||
[{ $set: { 'buttons.savePreferences': '$buttons.save' } }],
|
||||
)
|
||||
if (result.modifiedCount) {
|
||||
payload.logger.info('[ipal] Cookie Settings: buttons.save copied to buttons.savePreferences (1.11.1 rename).')
|
||||
}
|
||||
} catch (error) {
|
||||
payload.logger.error({ err: error, msg: '[ipal] Cookie Settings: could not migrate buttons.save → buttons.savePreferences' })
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -216,7 +216,7 @@ export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler }
|
||||
export { buildIconsMetadata, buildOrganizationJsonLd, sameAsUrls, validateFaviconField } from './modules/seo/index.js'
|
||||
export { buildNoindexField } from './modules/seo/index.js'
|
||||
export { buildSpeakableJsonLd } from './modules/seo/index.js'
|
||||
export { buildSummaryField } from './modules/seo/index.js'
|
||||
export { buildSummaryField, SKIP_AUTO_FILL } from './modules/seo/index.js'
|
||||
export { buildBreadcrumbJsonLd, buildNavigationJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'
|
||||
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
|
||||
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
|
||||
|
||||
@@ -40,8 +40,11 @@ const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
|
||||
type CookieSettingsData = {
|
||||
alwaysActiveLabel?: null | string
|
||||
buttons?: ({
|
||||
/** Before 1.11.1 the field was `save` — still read, so old MongoDB data keeps working until re-saved. */
|
||||
save?: null | string
|
||||
/**
|
||||
* Before 1.11.1 the field was `save` — still read for old MongoDB data. Not in the schema any
|
||||
* more, so Payload doesn't flatten it: it comes back as the raw `{ pl, en }` map.
|
||||
*/
|
||||
save?: null | Record<string, string> | string
|
||||
savePreferences?: null | string
|
||||
} & Partial<Omit<ConsentTexts['buttons'], 'save'>>) | null
|
||||
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
|
||||
@@ -146,7 +149,7 @@ export async function getConsentTexts({
|
||||
back: g.buttons?.back || FALLBACK.buttons.back,
|
||||
close: g.buttons?.close || FALLBACK.buttons.close,
|
||||
reject: g.buttons?.reject || FALLBACK.buttons.reject,
|
||||
save: g.buttons?.savePreferences || g.buttons?.save || FALLBACK.buttons.save,
|
||||
save: g.buttons?.savePreferences || resolveLocalized(g.buttons?.save, locale ?? '') || FALLBACK.buttons.save,
|
||||
settings: g.buttons?.settings || FALLBACK.buttons.settings,
|
||||
},
|
||||
categories,
|
||||
|
||||
Vendored
+5
-3
@@ -74,9 +74,11 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
|
||||
]
|
||||
|
||||
if (storage) {
|
||||
const r2Vars = ['R2_BUCKET', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_ENDPOINT', 'R2_PUBLIC_URL']
|
||||
// Production: always. Development: only once any R2_* is set (all or nothing).
|
||||
const r2Required = process.env.NODE_ENV === 'production' || r2Vars.some((name) => Boolean(process.env[name]))
|
||||
const r2Credentials = ['R2_BUCKET', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_ENDPOINT']
|
||||
// Production: always. Development: once any credential is set (all or nothing).
|
||||
// R2_PUBLIC_URL alone is the read-only media mode (buildR2Storage) — allowed in dev.
|
||||
const r2Required =
|
||||
process.env.NODE_ENV === 'production' || r2Credentials.some((name) => Boolean(process.env[name]))
|
||||
rules.push(
|
||||
{ name: 'R2_BUCKET', description: 'R2 bucket name', required: r2Required },
|
||||
{ name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id', required: r2Required },
|
||||
|
||||
@@ -10,7 +10,7 @@ import { LocaleView } from '../pages/LocaleView.js'
|
||||
import { NotFoundLoader } from '../pages/NotFoundLoader.js'
|
||||
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
|
||||
|
||||
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode' | 'getSystemLinks'>> & Pick<
|
||||
type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode' | 'getHomeSlug' | 'getSystemLinks'>> & Pick<
|
||||
ContentHelpers,
|
||||
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
|
||||
>
|
||||
@@ -26,6 +26,12 @@ export type PageRouteOptions = {
|
||||
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
|
||||
/** blockType → component (the project's registry). */
|
||||
blocks: BlockComponentMap
|
||||
/**
|
||||
* The homepage opened under its own slug (/pl/home): 'redirect' (default) — 308 to the
|
||||
* locale root, one URL per page (canonical already points there; Search Console reports
|
||||
* the alias as a duplicate otherwise). `false` — render it like any page.
|
||||
*/
|
||||
homeAlias?: 'redirect' | false
|
||||
/** Per-page JSON-LD (WebPage, breadcrumbs, FAQ…). Default true; options as getPageJsonLd. */
|
||||
jsonLd?: boolean | PageJsonLdOptions
|
||||
/** Field with the blocks. Default 'layout'. */
|
||||
@@ -76,7 +82,7 @@ type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
|
||||
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
|
||||
*/
|
||||
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, onMissing = 'notFound', permanentRedirect, redirect, render } = options
|
||||
const { blockProps, blocks, homeAlias = 'redirect', jsonLd = true, layoutField = 'layout', notFound, onMissing = 'notFound', permanentRedirect, redirect, render } = options
|
||||
if (onMissing === 'redirectHome' && !redirect) {
|
||||
throw new Error("[ipal] createPageRoute: onMissing: 'redirectHome' needs `redirect` from 'next/navigation'.")
|
||||
}
|
||||
@@ -118,6 +124,14 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
if (target) {return permanentRedirect(target)}
|
||||
return missing(locale, segments)
|
||||
}
|
||||
if (homeAlias === 'redirect' && route.type !== 'home' && segments.length && helpers.getHomeSlug) {
|
||||
const homeSlug = await helpers.getHomeSlug(locale)
|
||||
if (homeSlug && segments.join('/') === homeSlug) {
|
||||
const [home] = helpers.getSystemLinks ? await helpers.getSystemLinks(locale, ['homepage']) : []
|
||||
const multilingual = (helpers.i18n?.locales.length ?? 0) > 1
|
||||
return permanentRedirect(home?.href ?? (multilingual ? `/${locale}` : '/'))
|
||||
}
|
||||
}
|
||||
const doc = route.doc
|
||||
const extra = blockProps ? await blockProps({ doc, locale }) : {}
|
||||
const rendered = (
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { CollectionBeforeChangeHook } from 'payload'
|
||||
|
||||
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
|
||||
import { describeFromMarkdown } from './plainText.js'
|
||||
import { isAutoFillSkipped } from './skipAutoFill.js'
|
||||
|
||||
/**
|
||||
* Maps document fields to SEO meta fields for auto-fill.
|
||||
@@ -51,8 +52,8 @@ export function buildAutoFillMetaHook(mapping: AutoFillMapping = {}): Collection
|
||||
const contentField = mapping.content === undefined ? 'layout' : mapping.content
|
||||
const descriptionLength = mapping.descriptionLength ?? 155
|
||||
|
||||
return ({ data, originalDoc }) => {
|
||||
if (!data) {return data}
|
||||
return ({ context, data, originalDoc }) => {
|
||||
if (!data || isAutoFillSkipped(context)) {return data}
|
||||
|
||||
// plugin-seo stores meta as a group under `meta`
|
||||
const meta = (data.meta as Record<string, unknown> | undefined) ?? {}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Field, FieldHook, TextareaField } from 'payload'
|
||||
|
||||
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
|
||||
import { mdToPlain, truncate } from './plainText.js'
|
||||
import { isAutoFillSkipped } from './skipAutoFill.js'
|
||||
|
||||
type BuildSummaryFieldArgs = {
|
||||
/** Auto-fill from page content when the editor leaves it empty. Default true. */
|
||||
@@ -50,7 +51,8 @@ export function buildSummaryField(args: BuildSummaryFieldArgs = {}): Field {
|
||||
overrides = {},
|
||||
} = args
|
||||
|
||||
const autofillHook: FieldHook = ({ data, value }) => {
|
||||
const autofillHook: FieldHook = ({ context, data, value }) => {
|
||||
if (isAutoFillSkipped(context)) {return value}
|
||||
if (typeof value === 'string' && value.trim()) {return value} // never clobber a manual summary
|
||||
if (!data || typeof data !== 'object') {return value}
|
||||
const layout = (data as Record<string, unknown>)[layoutField]
|
||||
|
||||
@@ -49,6 +49,7 @@ export { collectSiteIndex } from './siteIndex.js'
|
||||
export type { CollectSiteIndexArgs, SiteIndexEntry } from './siteIndex.js'
|
||||
export { buildSitemapCss, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './sitemapStyle.js'
|
||||
export type { SitemapStyleOptions } from './sitemapStyle.js'
|
||||
export { SKIP_AUTO_FILL } from './skipAutoFill.js'
|
||||
export { slugsAcrossLocales } from './slugsAcrossLocales.js'
|
||||
export type { SeoMeta, SeoOption } from './types.js'
|
||||
export { validateFaviconField } from './validateFavicon.js'
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* `payload.update({ …, context: { ipalSkipAutoFill: true } })` — the save fills nothing
|
||||
* automatically (meta title/description, AI summary). For data migrations and scripts that
|
||||
* must write exactly what they set, nothing generated on top. Same idea as Payload's
|
||||
* `context.disableRevalidate`.
|
||||
*/
|
||||
export const SKIP_AUTO_FILL = 'ipalSkipAutoFill'
|
||||
|
||||
export function isAutoFillSkipped(context: unknown): boolean {
|
||||
return Boolean(context && typeof context === 'object' && (context as Record<string, unknown>)[SKIP_AUTO_FILL])
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { Plugin } from 'payload'
|
||||
import type { CollectionConfig, Plugin } from 'payload'
|
||||
|
||||
import { APIError } from 'payload'
|
||||
|
||||
type GenerateFileURL = (args: { filename: string; prefix?: string }) => string
|
||||
|
||||
@@ -16,6 +18,8 @@ export type S3StorageFactory = (options: {
|
||||
forcePathStyle: boolean
|
||||
region: string
|
||||
}
|
||||
/** false = registered but inactive: no S3 client, local disk, admin import map unchanged. */
|
||||
enabled?: boolean
|
||||
}) => Plugin
|
||||
|
||||
export type BuildR2StorageDeps = {
|
||||
@@ -58,17 +62,43 @@ export const buildR2Storage = (
|
||||
const accessKeyId = process.env.R2_ACCESS_KEY_ID
|
||||
const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY
|
||||
|
||||
// Any missing → skip R2, fall back to local disk. Warn so it's not silent.
|
||||
const { s3Storage } = deps
|
||||
|
||||
// Any missing → local disk. The adapter is still REGISTERED (enabled: false) when the
|
||||
// project injects it: storage-s3 adds its admin client handler to the import map even
|
||||
// when disabled, so `pnpm dev` / `generate:importmap` without R2 env writes the same
|
||||
// importMap.js as production. Before 1.12.2 a no-op was returned here — an import map
|
||||
// generated in dev lacked S3ClientUploadHandler and the production admin rendered blank.
|
||||
if (!bucket || !endpoint || !accessKeyId || !secretAccessKey) {
|
||||
const readOnly = readOnlyPublicUrl({ accessKeyId, bucket, endpoint, secretAccessKey })
|
||||
const disabled: Plugin | undefined = s3Storage
|
||||
? s3Storage({
|
||||
bucket: bucket ?? '',
|
||||
collections: Object.fromEntries(collections.map((slug) => [slug, true as const])),
|
||||
config: {
|
||||
credentials: { accessKeyId: accessKeyId ?? '', secretAccessKey: secretAccessKey ?? '' },
|
||||
endpoint: endpoint ?? '',
|
||||
forcePathStyle: true,
|
||||
region: 'auto',
|
||||
},
|
||||
enabled: false,
|
||||
})
|
||||
: undefined
|
||||
return (config) => {
|
||||
// Only warn when SOME vars are set (partial config = likely a mistake).
|
||||
if (bucket || endpoint || accessKeyId || secretAccessKey) {
|
||||
if (readOnly) {
|
||||
console.warn(
|
||||
`[ipal] R2 storage: read-only media from ${readOnly} (R2_PUBLIC_URL without credentials) — ` +
|
||||
'uploads are disabled. Set all R2_* to upload, or none for local disk.',
|
||||
)
|
||||
} else if (bucket || endpoint || accessKeyId || secretAccessKey) {
|
||||
// Only warn when SOME vars are set (partial config = likely a mistake).
|
||||
console.warn(
|
||||
'[ipal] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' +
|
||||
'R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). Falling back to local disk.',
|
||||
)
|
||||
}
|
||||
return config
|
||||
const next = disabled ? disabled(config) : config
|
||||
return readOnly ? withReadOnlyMedia(next as Parameters<Plugin>[0], collections, readOnly) : next
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,7 +125,6 @@ export const buildR2Storage = (
|
||||
|
||||
// R2 env is complete → the adapter is required. Fail loudly at boot rather
|
||||
// than silently storing media on the container disk (lost on redeploy).
|
||||
const { s3Storage } = deps
|
||||
if (!s3Storage) {
|
||||
throw new Error(
|
||||
'[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' +
|
||||
@@ -121,3 +150,76 @@ export const buildR2Storage = (
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only media: outside production, R2_PUBLIC_URL (absolute) with none of the
|
||||
* credentials → files are read from the public domain. For a local dev pointed at
|
||||
* a production database: images show, nothing can be uploaded to (or deleted from)
|
||||
* the real bucket. Returns the base URL, or null when the mode doesn't apply.
|
||||
*/
|
||||
function readOnlyPublicUrl(env: {
|
||||
accessKeyId?: string
|
||||
bucket?: string
|
||||
endpoint?: string
|
||||
secretAccessKey?: string
|
||||
}): null | string {
|
||||
if (process.env.NODE_ENV === 'production') {return null}
|
||||
if (env.accessKeyId || env.bucket || env.endpoint || env.secretAccessKey) {return null}
|
||||
const url = process.env.R2_PUBLIC_URL?.trim().replace(/\/$/, '')
|
||||
return url && /^https?:\/\/[^/\s]+/i.test(url) ? url : null
|
||||
}
|
||||
|
||||
type UploadDoc = {
|
||||
filename?: null | string
|
||||
sizes?: Record<string, { filename?: null | string; url?: null | string } | null>
|
||||
thumbnailURL?: null | string
|
||||
url?: null | string
|
||||
}
|
||||
|
||||
function withReadOnlyMedia(
|
||||
config: Parameters<Plugin>[0],
|
||||
collections: string[],
|
||||
publicUrl: string,
|
||||
): Parameters<Plugin>[0] {
|
||||
const fileUrl = (filename: string) => `${publicUrl}/${encodeURIComponent(filename)}`
|
||||
return {
|
||||
...config,
|
||||
collections: (config.collections ?? []).map((collection): CollectionConfig => {
|
||||
if (!collections.includes(collection.slug)) {return collection}
|
||||
return {
|
||||
...collection,
|
||||
hooks: {
|
||||
...collection.hooks,
|
||||
afterRead: [
|
||||
...(collection.hooks?.afterRead ?? []),
|
||||
({ doc }: { doc: UploadDoc }) => {
|
||||
if (!doc?.filename) {return doc}
|
||||
doc.url = fileUrl(doc.filename)
|
||||
if (doc.thumbnailURL) {
|
||||
const thumb = doc.sizes?.thumbnail?.filename
|
||||
doc.thumbnailURL = thumb ? fileUrl(thumb) : doc.url
|
||||
}
|
||||
for (const size of Object.values(doc.sizes ?? {})) {
|
||||
if (size?.filename) {size.url = fileUrl(size.filename)}
|
||||
}
|
||||
return doc
|
||||
},
|
||||
],
|
||||
beforeOperation: [
|
||||
...(collection.hooks?.beforeOperation ?? []),
|
||||
({ args, operation }) => {
|
||||
const req = (args as { req?: { file?: unknown } }).req
|
||||
if (operation === 'delete' || ((operation === 'create' || operation === 'update') && req?.file)) {
|
||||
throw new APIError(
|
||||
'Media is read-only here (R2_PUBLIC_URL without R2 credentials). Set all R2_* to upload or delete files.',
|
||||
403,
|
||||
)
|
||||
}
|
||||
return args
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Config, Plugin } from 'payload'
|
||||
import type { IpalOptions, TotpPluginFactory } from './types.js'
|
||||
|
||||
import { buildCookieSettings } from './globals/CookieSettings/index.js'
|
||||
import { migrateCookieSettingsSaveButton } from './globals/CookieSettings/migrateSaveButton.js'
|
||||
import { buildNotifications } from './globals/Notifications/index.js'
|
||||
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
|
||||
import { buildSiteSettings } from './globals/SiteSettings/index.js'
|
||||
@@ -303,6 +304,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
const incomingOnInit = config.onInit
|
||||
config.onInit = async (payload) => {
|
||||
if (incomingOnInit) {await incomingOnInit(payload)}
|
||||
await migrateCookieSettingsSaveButton(payload)
|
||||
payload.logger.info('[ipal] Plugin initialized.')
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user