@klnap/payload-redirect 0.2.0 → 0.3.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 (60) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +204 -72
  3. package/dist/core/redirects/auto/create-redirect.d.ts +8 -3
  4. package/dist/core/redirects/auto/create-redirect.js +20 -61
  5. package/dist/core/redirects/auto/match-existing-rule.js +1 -1
  6. package/dist/core/redirects/auto/persist-auto-rule.d.ts +3 -2
  7. package/dist/core/redirects/auto/persist-auto-rule.js +2 -2
  8. package/dist/core/redirects/auto/publication/get-publication-transition.d.ts +2 -2
  9. package/dist/core/redirects/auto/publication/get-publication-transition.js +20 -36
  10. package/dist/core/redirects/auto/publication/locales.d.ts +7 -5
  11. package/dist/core/redirects/auto/publication/locales.js +32 -28
  12. package/dist/core/redirects/auto/publication/publish-intent.d.ts +1 -3
  13. package/dist/core/redirects/auto/publication/publish-intent.js +2 -26
  14. package/dist/core/redirects/auto/publication/versions/document-locale.d.ts +4 -6
  15. package/dist/core/redirects/auto/publication/versions/document-locale.js +9 -18
  16. package/dist/core/redirects/auto/publication/versions/version-pages.d.ts +2 -10
  17. package/dist/core/redirects/auto/publication/versions/version-pages.js +4 -30
  18. package/dist/core/redirects/auto/publication/versions/version-rows.d.ts +1 -7
  19. package/dist/core/redirects/auto/publication/versions/version-rows.js +4 -28
  20. package/dist/core/redirects/auto/types.d.ts +27 -8
  21. package/dist/core/redirects/collection/collection.js +1 -1
  22. package/dist/core/redirects/collection/duplicate-guard.js +1 -1
  23. package/dist/core/redirects/collection/fields.js +4 -4
  24. package/dist/core/redirects/model/status-code.js +1 -1
  25. package/dist/core/redirects/queries.d.ts +1 -10
  26. package/dist/core/redirects/queries.js +2 -2
  27. package/dist/core/url/published-path.d.ts +4 -16
  28. package/dist/core/url/published-path.js +38 -120
  29. package/dist/core/url/route-params.d.ts +3 -11
  30. package/dist/core/url/route-params.js +31 -99
  31. package/dist/exports/index.d.ts +1 -1
  32. package/dist/plugin/payload-plugin.d.ts +0 -1
  33. package/dist/plugin/payload-plugin.js +83 -81
  34. package/dist/plugin/types.d.ts +8 -34
  35. package/docs/FAILURE_SEMANTICS.md +15 -11
  36. package/package.json +10 -9
  37. package/dist/core/redirects/auto/publication/identifier-snapshot.d.ts +0 -2
  38. package/dist/core/redirects/auto/publication/identifier-snapshot.js +0 -27
  39. package/dist/core/redirects/auto/publication/identifier-transitions.d.ts +0 -18
  40. package/dist/core/redirects/auto/publication/identifier-transitions.js +0 -36
  41. package/dist/core/redirects/auto/publication/transition-for-locale.d.ts +0 -12
  42. package/dist/core/redirects/auto/publication/transition-for-locale.js +0 -167
  43. package/dist/core/redirects/auto/publication/transitions-to-pairs.d.ts +0 -9
  44. package/dist/core/redirects/auto/publication/transitions-to-pairs.js +0 -22
  45. package/dist/core/redirects/auto/published-link-config.d.ts +0 -6
  46. package/dist/core/redirects/auto/published-link-config.js +0 -53
  47. package/dist/core/redirects/auto/published-path.d.ts +0 -6
  48. package/dist/core/redirects/auto/published-path.js +0 -28
  49. package/dist/core/redirects/auto/redirect-custom.d.ts +0 -7
  50. package/dist/core/redirects/auto/redirect-custom.js +0 -19
  51. package/dist/core/redirects/identifier-field-path.d.ts +0 -14
  52. package/dist/core/redirects/identifier-field-path.js +0 -94
  53. package/dist/core/redirects/runtime.d.ts +0 -9
  54. package/dist/core/redirects/runtime.js +0 -13
  55. package/dist/core/url/preview-path.d.ts +0 -1
  56. package/dist/core/url/preview-path.js +0 -9
  57. package/dist/core/url/preview-routes.d.ts +0 -3
  58. package/dist/core/url/preview-routes.js +0 -31
  59. package/docs/RELEASING.md +0 -41
  60. package/docs/adr/0002-database-indexes.md +0 -44
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 0.3.0
4
+
5
+ - Simplify automatic redirect configuration to `path`, `paths`, and `getPath`.
6
+ - Compare complete published paths with native Payload localization and no locale fallback.
7
+ - Register the redirects collection automatically and use `statusCode` as its status field.
package/README.md CHANGED
@@ -1,139 +1,271 @@
1
1
  # @klnap/payload-redirect
2
2
 
3
- Payload plugin for manual and publication-generated redirects.
3
+ Redirect management for Payload CMS.
4
4
 
5
- ## Install
5
+ Manage redirects directly in Payload and automatically preserve existing URLs when published content paths change.
6
+
7
+ Define your public URL structure, enable automatic redirects for selected collections, and let your application's routing layer handle redirect responses.
8
+
9
+ ## Overview
10
+
11
+ The plugin owns its Payload collection, so manual redirects need no collection stub or automatic-generation setup. Automatic generation is optional and compares complete published paths.
12
+
13
+ ## Installation
6
14
 
7
15
  ```sh
8
- npm install @klnap/payload-redirect
16
+ bun add @klnap/payload-redirect
17
+ ```
18
+
19
+ Requires Payload `>=3.94.1 <4`. PostgreSQL is the supported database adapter.
20
+
21
+ ## Manual redirects
22
+
23
+ Register the plugin with no options:
24
+
25
+ ```ts
26
+ import { buildConfig } from 'payload'
27
+ import { postgresAdapter } from '@payloadcms/db-postgres'
28
+ import { redirects } from '@klnap/payload-redirect'
29
+
30
+ export default buildConfig({
31
+ secret: process.env.PAYLOAD_SECRET!,
32
+ db: postgresAdapter({ pool: { connectionString: process.env.DATABASE_URI! } }),
33
+ plugins: [redirects()],
34
+ })
9
35
  ```
10
36
 
11
- Requires Payload `>=3.94.1 <4`. PostgreSQL is the supported adapter for transaction-safe
12
- duplicate and redirect-chain checks.
37
+ The plugin adds the `redirects` collection. Add, edit, enable, or disable rules in Payload Admin. Manual rules work without automatic redirect configuration.
13
38
 
14
- ## Configure
39
+ ## Automatic redirects
40
+
41
+ Automatic generation is enabled for each collection configured in `redirects({ collections })`. Those collections must use Payload drafts so the plugin can compare published snapshots.
15
42
 
16
43
  ```ts
17
44
  import { buildConfig } from 'payload'
45
+ import { postgresAdapter } from '@payloadcms/db-postgres'
18
46
  import { redirects } from '@klnap/payload-redirect'
19
47
 
20
48
  export default buildConfig({
49
+ secret: process.env.PAYLOAD_SECRET!,
50
+ db: postgresAdapter({ pool: { connectionString: process.env.DATABASE_URI! } }),
51
+ localization: {
52
+ locales: ['pl', 'en', 'de'],
53
+ defaultLocale: 'pl',
54
+ },
21
55
  collections: [
22
56
  {
23
57
  slug: 'articles',
24
58
  versions: { drafts: true },
25
- fields: [{ name: 'slug', type: 'text', required: true }],
26
- custom: {
27
- redirect: {
28
- identifier: 'slug',
29
- publishedLink: { path: '/articles/[slug]' },
30
- },
31
- },
59
+ fields: [
60
+ { name: 'title', type: 'text', required: true },
61
+ { name: 'slug', type: 'text', required: true, localized: true },
62
+ ],
63
+ },
64
+ {
65
+ slug: 'projects',
66
+ versions: { drafts: true },
67
+ fields: [{ name: 'slug', type: 'text', required: true, localized: true }],
32
68
  },
33
69
  ],
34
70
  plugins: [
35
71
  redirects({
36
- localePrefix: { en: '', pl: '/pl' },
72
+ localePrefixes: {
73
+ pl: '',
74
+ en: '/en',
75
+ de: '/de',
76
+ },
77
+ collections: {
78
+ articles: { path: '/[slug]' },
79
+ projects: {
80
+ paths: {
81
+ pl: '/realizacje/[slug]',
82
+ en: '/work/[slug]',
83
+ de: '/projekte/[slug]',
84
+ },
85
+ },
86
+ },
37
87
  }),
38
88
  ],
39
89
  })
40
90
  ```
41
91
 
42
- `redirects()` adds the plugin-owned `redirects` collection and wires publication hooks for
43
- collections with `custom.redirect.identifier`. It preserves existing hooks. Do not register a
44
- second redirects collection or add manual publication hooks.
92
+ ### Reading the configuration
45
93
 
46
- The plugin creates a rule when a published identifier changes. Draft saves, first publications,
47
- unpublishes, and unchanged identifiers do not create rules. A manual rule on the same source path
48
- always wins over an automatic rule.
94
+ > When the published path of a document in this collection changes, redirect the previous path to the new one.
49
95
 
50
- ## Published paths
96
+ - Articles use one path template. `localePrefixes` adds each locale's explicit prefix.
97
+ - Projects use a separate public path template for each Payload locale.
98
+ - Collections without redirect configuration remain unaffected.
99
+
100
+ For a Polish project, a slug change creates this rule:
101
+
102
+ ```text
103
+ Previous published path: /realizacje/stary-projekt
104
+ Current published path: /realizacje/nowy-projekt
105
+ Generated redirect: /realizacje/stary-projekt → /realizacje/nowy-projekt
106
+ ```
107
+
108
+ The plugin tracks the resolved public URL, not a particular slug field. A change to any field used by the path template can create a redirect.
51
109
 
52
- Put collection-specific settings in `custom.redirect.publishedLink`. `custom.draft.publishedLink`
53
- is also read when `custom.redirect.publishedLink` is absent.
110
+ ### Collection-level configuration
54
111
 
55
- Use `path` for a shared template, `paths` for locale-specific templates, or `getPath` for custom
56
- logic. Template parameters match top-level collection fields; localized fields resolve for the
57
- published locale. Dynamic values are URL-encoded as single path segments.
112
+ Use the same options directly on a collection when central configuration is not convenient:
58
113
 
59
114
  ```ts
60
- custom: {
61
- redirect: {
62
- identifier: 'slug',
63
- publishedLink: {
64
- paths: {
65
- en: '/articles/[slug]',
66
- pl: '/artykuly/[slug]',
67
- },
68
- },
115
+ import type { CollectionConfig } from 'payload'
116
+ import type { RedirectCollectionOptions } from '@klnap/payload-redirect'
117
+
118
+ const projectRedirect = {
119
+ paths: {
120
+ pl: '/realizacje/[slug]',
121
+ en: '/work/[slug]',
122
+ de: '/projekte/[slug]',
123
+ },
124
+ } satisfies RedirectCollectionOptions<'projects'>
125
+
126
+ export const Projects: CollectionConfig = {
127
+ slug: 'projects',
128
+ versions: { drafts: true },
129
+ custom: {
130
+ redirect: projectRedirect,
69
131
  },
132
+ fields: [{ name: 'slug', type: 'text', required: true, localized: true }],
133
+ }
134
+ ```
135
+
136
+ Central configuration replaces collection-level configuration for that collection. The plugin does not merge path strategies.
137
+
138
+ Set `custom.redirect.enabled` to `false` to disable automatic generation for that collection. Manual redirect management remains enabled.
139
+
140
+ ## Published paths
141
+
142
+ Choose exactly one path strategy for each configured collection.
143
+
144
+ ### Shared templates
145
+
146
+ Use `path` when every locale has the same route shape:
147
+
148
+ ```ts
149
+ articles: {
150
+ path: '/articles/[slug]'
70
151
  }
71
152
  ```
72
153
 
73
- `getPath` receives the published document snapshot and locale. Return a site path or `null` to skip
74
- that transition:
154
+ Templates use top-level field names in brackets. Use multiple fields when the public route depends on multiple values:
75
155
 
76
156
  ```ts
77
- publishedLink: {
78
- getPath: ({ doc, locale }) =>
79
- `/articles/${String(doc.category)}/${String(doc.slug)}-${locale}`,
157
+ projects: {
158
+ path: '/[category]/[slug]'
80
159
  }
81
160
  ```
82
161
 
83
- Centralized path rules can be set in `redirects()`; collection `publishedLink` settings take precedence:
162
+ Each value is encoded as one URL path segment. Missing, invalid, or unsafe values prevent that transition from creating a redirect.
163
+
164
+ ### Localized templates
165
+
166
+ Use `paths` to give each Payload locale a complete template:
84
167
 
85
168
  ```ts
86
- redirects({
87
- localePrefix: { en: '', pl: '/pl' },
88
- collections: {
89
- articles: {
90
- identifier: 'slug',
91
- path: '/articles/[slug]',
92
- },
169
+ projects: {
170
+ paths: {
171
+ pl: '/realizacje/[slug]',
172
+ en: '/work/[slug]',
173
+ de: '/projekte/[slug]',
93
174
  },
94
- })
175
+ }
176
+ ```
177
+
178
+ The map must include every locale configured in Payload. The plugin does not use fallback locale values to resolve a published path.
179
+
180
+ ### Locale prefixes
181
+
182
+ `localePrefixes` maps Payload locale codes to explicit prefixes. An empty string means no prefix. The map must include every Payload locale when provided.
183
+
184
+ Prefixes apply to `path` and `paths`. If `localePrefixes` is omitted, the plugin adds no prefix and does not infer one from the locale code.
185
+
186
+ ### Custom path resolution
187
+
188
+ Use `getPath` when templates cannot express the public route:
189
+
190
+ ```ts
191
+ projects: {
192
+ getPath: ({ doc, locale }) =>
193
+ doc.slug && doc.category
194
+ ? `${locale ? `/${locale}` : ''}/${String(doc.category)}/${String(doc.slug)}`
195
+ : null,
196
+ }
95
197
  ```
96
198
 
97
- Payload localization defines the available locales. If you set a prefix map, include every locale.
98
- An empty prefix means no locale segment. Without a prefix map, the builder uses the locale code.
199
+ Payload generated types infer `doc` from the configured collection. The callback receives the locale-specific published snapshot and locale; locale is `undefined` when Payload localization is off. Return a complete site-relative path or `null`. The plugin does not add `localePrefixes` to callback results.
99
200
 
100
201
  ## Redirect collection
101
202
 
102
- The plugin owns the collection and its required fields: `from`, `to`, `StatusCode`, `enabled`, and
103
- `origin`. `from` is unique. Redirect writes normalize paths and reject duplicate sources and
104
- enabled loops. Manual rules are not overwritten by publication hooks.
203
+ The plugin owns these fields:
204
+
205
+ - `from`: unique source path.
206
+ - `to`: site-relative destination path.
207
+ - `statusCode`: `301` or `302`.
208
+ - `enabled`: whether the rule is active.
209
+ - `origin`: `manual` or `auto`.
105
210
 
106
- Pass native Payload collection settings through `overrides`:
211
+ The schema uses the camelCase field `statusCode`.
212
+
213
+ ### Collection overrides
214
+
215
+ Pass native Payload collection options through `overrides`:
107
216
 
108
217
  ```ts
109
218
  redirects({
110
219
  overrides: {
111
220
  slug: 'url-rules',
112
221
  labels: { singular: 'URL rule', plural: 'URL rules' },
113
- admin: { group: 'Content' },
222
+ admin: { group: 'Settings' },
223
+ trash: true,
114
224
  },
115
225
  })
116
226
  ```
117
227
 
118
- Use `overrides.fields` to customize the plugin fields. It receives `defaultFields`; required fields,
119
- validators, uniqueness, and indexes remain enforced.
228
+ Use `overrides.fields` to customize the plugin fields. Required fields, validation, uniqueness, and indexes remain enforced.
120
229
 
121
- `enabled: false` disables automatic generation only. The manual redirects collection remains
122
- available.
230
+ ## Automatic redirect behavior
123
231
 
124
- ## Checks and limits
232
+ - Draft saves, autosaves, first publications, unpublishes, and unchanged paths create no rules.
233
+ - The plugin compares the current published path with the latest earlier published path.
234
+ - A missing or unsafe path on either side skips that locale's redirect.
235
+ - A manual rule that owns the previous path is never overwritten.
236
+ - Automatic writes run through Payload Local API with the active request and transaction.
237
+ - Deleting a document does not create a redirect; configure removal behavior in your application if needed.
125
238
 
126
- - PostgreSQL is required for transaction-scoped advisory locking and race-safe graph validation.
127
- - Other database adapters are not claimed to provide equivalent concurrency guarantees.
128
- - The plugin stores redirect rules; the host application serves them from its routing layer.
129
- - The package does not expose a redirect resolver or HTTP middleware.
239
+ Automatic generation requires `versions.drafts`. It reads published versions with fallback disabled so localized paths never borrow values from another locale.
130
240
 
131
- Run package checks:
241
+ ## Application integration
132
242
 
133
- ```sh
134
- bun run typecheck
135
- bun run typecheck:consumer
136
- bun test src tests/unit
137
- bun run test:int
138
- bun run check:release
243
+ The package stores rules. Your application retrieves enabled rules, caches them, matches incoming paths, and returns HTTP redirect responses.
244
+
245
+ ```ts
246
+ const { docs } = await payload.find({
247
+ collection: 'redirects',
248
+ where: { enabled: { equals: true } },
249
+ depth: 0,
250
+ })
251
+
252
+ // Match the incoming path and return the selected rule's statusCode and to.
139
253
  ```
254
+
255
+ The package does not include a resolver, cache, middleware, proxy, or framework adapter.
256
+
257
+ ## Security and reliability
258
+
259
+ The collection validates site-relative sources, rejects unsafe destinations, prevents duplicate sources, and checks enabled redirect chains for loops. Manual rules are protected from automatic writes.
260
+
261
+ PostgreSQL provides the transaction-scoped advisory lock used to serialize graph validation. This package does not claim equivalent concurrent-write guarantees for other adapters.
262
+
263
+ ## Requirements
264
+
265
+ - Payload: `>=3.94.1 <4`.
266
+ - PostgreSQL: supported adapter for transaction-scoped graph locking.
267
+ - Other adapters: no equivalent concurrency guarantee is claimed.
268
+
269
+ ## License
270
+
271
+ MIT
@@ -1,5 +1,10 @@
1
1
  import type { CollectionAfterChangeHook } from 'payload';
2
- export type CreateRedirectOptions = {
3
- identifier: string;
2
+ import { type LocalePrefixes } from '../../url/published-path.js';
3
+ import type { RedirectPathOptions } from './types.js';
4
+ type CreateRedirectOptions = {
5
+ collectionSlug: string;
6
+ pathOptions: RedirectPathOptions;
7
+ localePrefixes?: LocalePrefixes;
4
8
  };
5
- export declare const createRedirect: (options: CreateRedirectOptions) => CollectionAfterChangeHook;
9
+ export declare const createRedirect: ({ collectionSlug, pathOptions, localePrefixes, }: CreateRedirectOptions) => CollectionAfterChangeHook;
10
+ export {};
@@ -1,77 +1,36 @@
1
1
  import { ensureAutoRedirect } from './persist-auto-rule.js';
2
2
  import { getPublicationTransition } from './publication/get-publication-transition.js';
3
- import { publicationTransitionsToPairs } from './publication/transitions-to-pairs.js';
4
- import { identifierValueForPath, resolveCollectionPublishedPathConfig, } from './published-path.js';
5
3
  import { REDIRECT_CONTEXT_KEYS } from '../context-keys.js';
6
- import { paramKeyFromIdentifierPath } from '../identifier-field-path.js';
7
4
  import { normalizePathOrUrl } from '../normalize-path.js';
8
- import { getRedirectRuntime } from '../runtime.js';
9
5
  import { buildPublishedPath } from '../../url/published-path.js';
10
- const publishedDataForLocale = (doc, collection, locale) => {
11
- const data = { ...doc };
12
- for (const field of collection.fields) {
13
- if (!('name' in field) || typeof field.name !== 'string' || !('localized' in field))
14
- continue;
15
- const value = data[field.name];
16
- if (field.localized === true && value && typeof value === 'object' && !Array.isArray(value)) {
17
- data[field.name] = value[locale];
18
- }
19
- }
20
- return data;
21
- };
22
- export const createRedirect = (options) => async (args) => {
23
- const { req, collection } = args;
24
- if (req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto]) {
6
+ export const createRedirect = ({ collectionSlug, pathOptions, localePrefixes, }) => async (args) => {
7
+ if (pathOptions.enabled === false)
25
8
  return args.doc;
26
- }
27
- const transitions = await getPublicationTransition(args, options);
28
- const pairs = publicationTransitionsToPairs(transitions);
29
- if (pairs.length === 0) {
9
+ if (args.req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto])
30
10
  return args.doc;
31
- }
32
- const { collectionSlug, localePrefix } = getRedirectRuntime(req.payload.config);
33
- const pathConfig = resolveCollectionPublishedPathConfig(collection, localePrefix);
34
- for (const { previous, current, locale, previousDoc, currentDoc } of pairs) {
35
- const resolvePath = (identifierValue, publishedDoc) => {
36
- if (!pathConfig || !locale)
37
- return identifierValue;
38
- const paramKey = paramKeyFromIdentifierPath(options.identifier);
39
- const mapping = pathConfig.params?.[paramKey];
40
- const data = publishedDataForLocale(publishedDoc, collection, locale);
41
- if (data[paramKey] === undefined) {
42
- data[paramKey] =
43
- mapping &&
44
- typeof mapping === 'object' &&
45
- 'localized' in mapping &&
46
- mapping.localized === true
47
- ? { [locale]: identifierValue }
48
- : identifierValueForPath(options.identifier, identifierValue)[paramKey];
49
- }
50
- const built = buildPublishedPath(pathConfig, data, locale);
51
- return built;
52
- };
53
- const fromRaw = resolvePath(previous, previousDoc);
54
- const toRaw = resolvePath(current, currentDoc);
55
- if (!fromRaw || !toRaw) {
11
+ const transitions = await getPublicationTransition(args);
12
+ for (const { currentDoc, publishedDocs, locale } of transitions) {
13
+ const currentPath = buildPublishedPath(pathOptions, currentDoc, locale, localePrefixes);
14
+ if (!currentPath)
15
+ continue;
16
+ const to = normalizePathOrUrl(currentPath);
17
+ const previousPublishedDoc = publishedDocs.find((publishedDoc) => {
18
+ const path = buildPublishedPath(pathOptions, publishedDoc, locale, localePrefixes);
19
+ return !path || normalizePathOrUrl(path) !== to;
20
+ });
21
+ if (!previousPublishedDoc)
56
22
  continue;
57
- }
58
- let from;
59
- let to;
60
- try {
61
- from = normalizePathOrUrl(fromRaw);
62
- to = normalizePathOrUrl(toRaw);
63
- }
64
- catch {
23
+ const previousPath = buildPublishedPath(pathOptions, previousPublishedDoc, locale, localePrefixes);
24
+ if (!previousPath)
65
25
  continue;
66
- }
67
- if (from === to) {
26
+ const from = normalizePathOrUrl(previousPath);
27
+ if (from === to)
68
28
  continue;
69
- }
70
29
  await ensureAutoRedirect({
71
- req,
30
+ req: args.req,
72
31
  collectionSlug,
73
32
  rule: { from, to },
74
- context: req.context,
33
+ context: args.req.context,
75
34
  });
76
35
  }
77
36
  return args.doc;
@@ -1,7 +1,7 @@
1
1
  import { assertRedirectStatusCode, DEFAULT_REDIRECT_STATUS_CODE, } from '../model/status-code.js';
2
2
  export const isIdenticalAutoRule = (doc, rule) => doc.from === rule.from &&
3
3
  doc.to === rule.to &&
4
- assertRedirectStatusCode(doc.StatusCode ?? DEFAULT_REDIRECT_STATUS_CODE) ===
4
+ assertRedirectStatusCode(doc.statusCode ?? DEFAULT_REDIRECT_STATUS_CODE) ===
5
5
  DEFAULT_REDIRECT_STATUS_CODE &&
6
6
  doc.enabled !== false &&
7
7
  doc.origin === 'auto';
@@ -1,9 +1,9 @@
1
1
  import type { PayloadRequest } from 'payload';
2
- export type AutoRedirectRule = {
2
+ type AutoRedirectRule = {
3
3
  from: string;
4
4
  to: string;
5
5
  };
6
- export type EnsureAutoRedirectArgs = {
6
+ type EnsureAutoRedirectArgs = {
7
7
  req: PayloadRequest;
8
8
  collectionSlug: string;
9
9
  rule: AutoRedirectRule;
@@ -13,3 +13,4 @@ export type EnsureAutoRedirectArgs = {
13
13
  * Idempotent create for auto 301 rules. One lookup by unique `from`.
14
14
  */
15
15
  export declare const ensureAutoRedirect: ({ req, collectionSlug, rule, context, }: EnsureAutoRedirectArgs) => Promise<'created' | 'skipped' | 'updated'>;
16
+ export {};
@@ -13,7 +13,7 @@ export const ensureAutoRedirect = async ({ req, collectionSlug, rule, context, }
13
13
  const data = {
14
14
  from: rule.from,
15
15
  to: rule.to,
16
- StatusCode: '301',
16
+ statusCode: '301',
17
17
  enabled: true,
18
18
  origin: 'auto',
19
19
  };
@@ -36,7 +36,7 @@ export const ensureAutoRedirect = async ({ req, collectionSlug, rule, context, }
36
36
  id: doc.id,
37
37
  data: {
38
38
  to: rule.to,
39
- StatusCode: '301',
39
+ statusCode: '301',
40
40
  enabled: true,
41
41
  },
42
42
  context: internalContext,
@@ -1,3 +1,3 @@
1
1
  import type { CollectionAfterChangeHook } from 'payload';
2
- import type { GetPublicationTransitionOptions, PublicationTransition } from '../types.js';
3
- export declare const getPublicationTransition: (args: Parameters<CollectionAfterChangeHook>[0], options: GetPublicationTransitionOptions) => Promise<PublicationTransition[]>;
2
+ import type { PublicationTransition } from '../types.js';
3
+ export declare const getPublicationTransition: (args: Parameters<CollectionAfterChangeHook>[0]) => Promise<PublicationTransition[]>;
@@ -1,49 +1,33 @@
1
1
  import { REDIRECT_CONTEXT_KEYS } from '../../context-keys.js';
2
- import { getRequestLocales, hasLocalizedDraftStatus, isIdentifierLocalized, listLocales, } from './locales.js';
3
- import { isDraftSave, isPublishIntent, isUnpublishedStatus } from './publish-intent.js';
4
- import { transitionForLocale } from './transition-for-locale.js';
5
- export const getPublicationTransition = async (args, options) => {
6
- const { req, doc, collection, data } = args;
7
- const publishIntent = isPublishIntent(data);
2
+ import { getRequestLocales, hasLocalizedDraftStatus, resolveDefaultLocale } from './locales.js';
3
+ import { isDraftSave, isLocalePublished } from './publish-intent.js';
4
+ import { fetchLocalePublishedDoc } from './versions/document-locale.js';
5
+ import { fetchPublishedVersionPages } from './versions/version-pages.js';
6
+ export const getPublicationTransition = async (args) => {
7
+ const { req, doc, collection } = args;
8
8
  if (!collection.versions?.drafts)
9
9
  return [];
10
- if (isDraftSave(req))
10
+ if (isDraftSave(req) || req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto])
11
11
  return [];
12
- if (req.context?.[REDIRECT_CONTEXT_KEYS.skipAuto])
13
- return [];
14
- const docRecord = doc;
15
- if (isUnpublishedStatus(docRecord._status) && !hasLocalizedDraftStatus(collection)) {
16
- return [];
17
- }
18
- let locales = getRequestLocales(req);
19
- const localizedField = isIdentifierLocalized(collection, options.identifier);
20
12
  const docId = doc.id;
21
- const publishAllLocales = req.query?.publishAllLocales === 'true' || req.query?.publishAllLocales === true;
22
- if (locales.length === 0 && publishAllLocales) {
23
- locales = listLocales(req);
24
- }
25
- if (locales.length === 0 &&
26
- localizedField &&
27
- hasLocalizedDraftStatus(collection) &&
28
- docRecord._status &&
29
- typeof docRecord._status === 'object') {
30
- locales = Object.entries(docRecord._status)
31
- .filter(([, value]) => value === 'published')
32
- .map(([code]) => code);
33
- }
13
+ const locales = getRequestLocales(req, doc._status);
14
+ const localizeStatus = hasLocalizedDraftStatus(collection);
15
+ const defaultLocale = resolveDefaultLocale(req);
34
16
  const transitions = [];
35
17
  for (const locale of locales) {
36
- const t = await transitionForLocale({
18
+ const currentDoc = await fetchLocalePublishedDoc({ req, collection, docId, locale });
19
+ if (!currentDoc || !isLocalePublished(currentDoc._status, locale ?? ''))
20
+ continue;
21
+ const publishedDocs = (await fetchPublishedVersionPages({
37
22
  req,
38
- collection,
23
+ collectionSlug: collection.slug,
39
24
  docId,
40
25
  locale,
41
- identifier: options.identifier,
42
- localizedField,
43
- hookDoc: docRecord,
44
- publishIntent,
45
- });
46
- transitions.push(t);
26
+ versionFilter: { localizeStatus, defaultLocale },
27
+ }))
28
+ .map((row) => row.version)
29
+ .filter((version) => Boolean(version));
30
+ transitions.push({ locale, currentDoc, publishedDocs });
47
31
  }
48
32
  return transitions;
49
33
  };
@@ -1,6 +1,8 @@
1
- import type { CollectionConfig, PayloadRequest } from 'payload';
2
- export declare const listLocales: (req: PayloadRequest) => string[];
3
- export declare const getRequestLocales: (req: PayloadRequest) => string[];
4
- export declare const hasLocalizedDraftStatus: (collection: CollectionConfig) => boolean;
5
- export declare const isIdentifierLocalized: (collection: CollectionConfig, identifier: string) => boolean;
1
+ import type { PayloadRequest } from 'payload';
2
+ export declare const getRequestLocales: (req: PayloadRequest, status: unknown) => Array<string | undefined>;
3
+ export declare const hasLocalizedDraftStatus: (collection: {
4
+ versions?: {
5
+ drafts?: unknown;
6
+ } | false;
7
+ }) => boolean;
6
8
  export declare const resolveDefaultLocale: (req: PayloadRequest) => string | undefined;