Files
ipal-kit/test/construction.test.ts
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:24:21 +01:00

160 lines
7.8 KiB
TypeScript

import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'node:os'
import path from 'node:path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { constructionNoticeHref, isPathAllowed, isPathVisibleIn, normalizePath } from '../src/modules/construction/logic.js'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
describe('under construction — path logic', () => {
test('paths compare without a trailing slash; the notice link carries the parameter', () => {
expect(normalizePath('/pl/')).toBe('/pl')
expect(normalizePath('')).toBe('/')
expect(isPathAllowed('/pl/brief/', ['/pl', '/pl/brief'])).toBe(true)
expect(isPathAllowed('/pl/o-nas', ['/pl', '/pl/brief'])).toBe(false)
expect(constructionNoticeHref('/pl')).toBe('/pl?notice=construction')
})
test('isPathVisibleIn: off → everything; on → allowed paths only', () => {
expect(isPathVisibleIn({ allowedPaths: [], enabled: false }, '/pl/o-nas')).toBe(true)
expect(isPathVisibleIn({ allowedPaths: ['/pl', '/pl/brief'], enabled: true }, '/pl/brief/')).toBe(true)
expect(isPathVisibleIn({ allowedPaths: ['/pl', '/pl/brief'], enabled: true }, '/pl/o-nas')).toBe(false)
})
})
describe('under construction — Site Settings → createPageRoute', () => {
let payload: Payload
let configPromise: Parameters<typeof getPayload>[0]['config']
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } as const
beforeAll(async () => {
configPromise = buildTestConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', index: true, localized: true }] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-construction') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [iapl({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'construction-test-secret',
telemetry: false,
})
payload = await getPayload({ config: configPromise })
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
const redirectError = (url: string): never => {
throw new Error(`REDIRECT ${url}`)
}
const route = () =>
createPageRoute(createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }), {
blocks: {},
notFound: () => {
throw new Error('NEXT_NOT_FOUND')
},
permanentRedirect: vi.fn() as unknown as (url: string) => never,
redirect: redirectError,
})
const open = (locale: string, slug?: string[]) => route().Page({ params: Promise.resolve({ slug, locale }) })
test('off: pages open normally; on: only the homepage and the chosen pages, everything else → homepage + notice', async () => {
const home = await payload.create({ collection: 'pages' as never, data: { slug: 'home', title: 'Start' } as never, locale: 'pl' as never })
const brief = await payload.create({ collection: 'pages' as never, data: { slug: 'brief', title: 'Brief' } as never, locale: 'pl' as never })
await payload.create({ collection: 'pages' as never, data: { slug: 'o-nas', title: 'O nas' } as never, locale: 'pl' as never })
await payload.update({ id: brief.id, collection: 'pages' as never, data: { slug: 'project-brief' } as never, locale: 'en' as never })
await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, siteName: 'Acme' } as never })
await expect(open('pl', ['o-nas'])).resolves.toBeTruthy()
await payload.updateGlobal({
slug: 'site-settings' as never,
data: { construction: { allowedPages: [brief.id], enabled: true, message: 'Strona w budowie', title: 'Pracujemy nad stroną' } } as never,
locale: 'pl' as never,
})
const helpers = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n })
const mode = await helpers.getConstructionMode('pl')
expect(mode).toMatchObject({ enabled: true, homePath: '/pl', locale: 'pl', texts: { message: 'Strona w budowie', title: 'Pracujemy nad stroną' } })
expect(mode.allowedPaths).toEqual(expect.arrayContaining(['/pl', '/pl/brief', '/en', '/en/project-brief']))
await expect(open('pl')).resolves.toBeTruthy()
await expect(open('pl', ['brief'])).resolves.toBeTruthy()
await expect(open('pl', ['o-nas'])).rejects.toThrow('REDIRECT /pl?notice=construction')
await expect(open('pl', ['nie-ma'])).rejects.toThrow('REDIRECT /pl?notice=construction')
})
test('on: Markdown, MCP and search hide the same pages the page route hides', async () => {
const helpers = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n })
expect((await helpers.getConstructionMode('pl')).enabled).toBe(true)
const md = (slug: string[]) => helpers.markdownRoute(new Request('https://acme.pl/md'), { params: Promise.resolve({ slug, locale: 'pl' }) })
expect((await md(['o-nas'])).status).toBe(404)
expect((await md(['brief'])).status).toBe(200)
const rpc = async (name: string, args: Record<string, unknown>) => {
const res = await helpers.mcpPOST(
new Request('https://acme.pl/api/mcp', {
body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { name, arguments: args } }),
headers: { 'content-type': 'application/json', 'x-real-ip': '198.51.100.4' },
method: 'POST',
}),
)
return ((await res.json()) as { result: { content: { text: string }[] } }).result.content[0].text
}
const list = await rpc('list_pages', { locale: 'pl' })
expect(list).toContain('/pl/brief')
expect(list).not.toContain('/pl/o-nas')
expect(await rpc('get_page', { path: '/pl/o-nas' })).toMatch(/No page found/)
expect(await rpc('search_content', { locale: 'pl', query: 'nas' })).not.toContain('/pl/o-nas')
// a whole list shares one construction-mode read (React cache doesn't dedupe in route handlers)
const readsFor = async (n: number) => {
const spy = vi.spyOn(payload, 'findGlobal')
await Promise.all(Array.from({ length: n }, (_, i) => helpers.isPathVisible(`/pl/p-${i}`, 'pl')))
const count = spy.mock.calls.length
spy.mockRestore()
return count
}
expect(await readsFor(50)).toBe(await readsFor(1))
expect(await helpers.isPathVisible('/pl/o-nas', 'pl')).toBe(false)
expect(await helpers.isPathVisible('/pl/brief', 'pl')).toBe(true)
})
})
describe('under construction — opting out per route', () => {
test('a project can pass its own isPathVisible to Markdown / MCP', async () => {
const { createMcpRoute } = await import('../src/modules/mcp/createMcpRoute.js')
const seen: string[] = []
const mcp = createMcpRoute({
config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] },
getCachedPayload: async () => ({}) as never,
isPathVisible: (path) => {
seen.push(path)
return false
},
rateLimit: false,
})
const res = await mcp.POST(
new Request('https://x/api/mcp', {
body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { name: 'get_page', arguments: { path: '/pl/o-nas' } } }),
method: 'POST',
}),
)
expect(JSON.stringify(await res.json())).toContain('No page found')
expect(seen).toEqual(['/pl/o-nas'])
})
})