@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
@@ -1,38 +1,42 @@
1
- import { isIdentifierPathLocalized } from '../../identifier-field-path.js';
2
- export const listLocales = (req) => {
1
+ const listLocales = (req) => {
3
2
  const localization = req.payload.config.localization;
4
- if (!localization)
3
+ if (localization === false || !localization)
5
4
  return [];
6
- return localization.locales.map((l) => (typeof l === 'string' ? l : l.code));
5
+ return localization.locales.map((locale) => (typeof locale === 'string' ? locale : locale.code));
7
6
  };
8
- export const getRequestLocales = (req) => {
9
- if (req.query?.publishAllLocales === 'true' || req.query?.publishAllLocales === true) {
10
- return listLocales(req);
7
+ export const getRequestLocales = (req, status) => {
8
+ const localization = listLocales(req);
9
+ if (localization.length === 0)
10
+ return [undefined];
11
+ const specificLocale = typeof req.query?.publishSpecificLocale === 'string'
12
+ ? req.query.publishSpecificLocale
13
+ : undefined;
14
+ if (specificLocale && specificLocale !== 'all')
15
+ return [specificLocale];
16
+ if (specificLocale === 'all' ||
17
+ req.query?.publishAllLocales === 'true' ||
18
+ req.query?.publishAllLocales === true) {
19
+ return localization;
11
20
  }
12
- const locale = (typeof req.query?.publishSpecificLocale === 'string' && req.query.publishSpecificLocale) ||
13
- (typeof req.query?.locale === 'string' && req.query.locale) ||
14
- (typeof req.locale === 'string' ? req.locale : undefined);
15
- if (locale && locale !== 'all')
16
- return [locale];
17
- const all = listLocales(req);
18
- if (all.length === 0)
19
- return ['en'];
20
- return [];
21
+ const requestedLocale = typeof req.query?.locale === 'string' ? req.query.locale : undefined;
22
+ if (requestedLocale && requestedLocale !== 'all')
23
+ return [requestedLocale];
24
+ if (requestedLocale === 'all')
25
+ return localization;
26
+ if (status && typeof status === 'object' && !Array.isArray(status)) {
27
+ return Object.entries(status)
28
+ .filter(([, value]) => value === 'published')
29
+ .map(([locale]) => locale);
30
+ }
31
+ if (typeof req.locale === 'string')
32
+ return [req.locale];
33
+ return status === 'published' ? localization : [];
21
34
  };
22
35
  export const hasLocalizedDraftStatus = (collection) => {
23
- const versions = collection.versions;
24
- if (!versions || typeof versions !== 'object' || !('drafts' in versions))
25
- return false;
26
- const drafts = versions.drafts;
27
- return typeof drafts === 'object' && drafts !== null && drafts.localizeStatus === true;
28
- };
29
- export const isIdentifierLocalized = (collection, identifier) => {
30
- return isIdentifierPathLocalized(collection.fields, identifier);
36
+ const drafts = collection.versions === false ? undefined : collection.versions?.drafts;
37
+ return Boolean(drafts && typeof drafts === 'object' && 'localizeStatus' in drafts && drafts.localizeStatus);
31
38
  };
32
39
  export const resolveDefaultLocale = (req) => {
33
40
  const localization = req.payload.config.localization;
34
- if (typeof localization === 'object' && localization && 'defaultLocale' in localization) {
35
- return String(localization.defaultLocale);
36
- }
37
- return undefined;
41
+ return localization ? localization.defaultLocale : undefined;
38
42
  };
@@ -1,5 +1,3 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  export declare const isDraftSave: (req: PayloadRequest) => boolean;
3
- export declare const isUnpublishedStatus: (status: unknown) => boolean;
4
- export declare const isPublishIntent: (data: unknown) => boolean;
5
- export declare const isLocalePublished: (status: unknown, locale: string, localizeStatus: boolean) => boolean;
3
+ export declare const isLocalePublished: (status: unknown, locale: string) => boolean;
@@ -1,31 +1,7 @@
1
1
  export const isDraftSave = (req) => req.query?.draft === 'true' || req.query?.draft === true;
2
- export const isUnpublishedStatus = (status) => {
3
- if (status === 'published')
4
- return false;
5
- if (status === 'draft' || status == null)
6
- return true;
7
- if (typeof status === 'object') {
8
- return !Object.values(status).includes('published');
9
- }
10
- return true;
11
- };
12
- export const isPublishIntent = (data) => {
13
- if (!data || typeof data !== 'object')
14
- return false;
15
- const status = data._status;
16
- if (status === 'published')
17
- return true;
18
- if (status && typeof status === 'object') {
19
- return Object.values(status).includes('published');
20
- }
21
- return false;
22
- };
23
- export const isLocalePublished = (status, locale, localizeStatus) => {
2
+ export const isLocalePublished = (status, locale) => {
24
3
  if (typeof status === 'object' && status !== null) {
25
4
  return status[locale] === 'published';
26
5
  }
27
- if (status === 'published') {
28
- return !localizeStatus;
29
- }
30
- return false;
6
+ return status === 'published';
31
7
  };
@@ -1,9 +1,7 @@
1
- import type { CollectionConfig, PayloadRequest, TypedLocale } from 'payload';
2
- export declare const toTypedLocale: (locale: string) => TypedLocale;
3
- export declare const fetchLocalePublishedDoc: ({ req, collection, docId, locale, draft, }: {
1
+ import type { CollectionConfig, PayloadRequest } from 'payload';
2
+ export declare const fetchLocalePublishedDoc: ({ req, collection, docId, locale, }: {
4
3
  req: PayloadRequest;
5
4
  collection: CollectionConfig;
6
5
  docId: string | number;
7
- locale: string;
8
- draft?: boolean;
9
- }) => Promise<Record<string, unknown> | undefined>;
6
+ locale?: string;
7
+ }) => Promise<Record<string, unknown>>;
@@ -1,18 +1,9 @@
1
- export const toTypedLocale = (locale) => locale;
2
- export const fetchLocalePublishedDoc = async ({ req, collection, docId, locale, draft = false, }) => {
3
- try {
4
- return (await req.payload.findByID({
5
- collection: collection.slug,
6
- id: docId,
7
- locale: toTypedLocale(locale),
8
- fallbackLocale: false,
9
- depth: 0,
10
- draft,
11
- overrideAccess: true,
12
- req,
13
- }));
14
- }
15
- catch {
16
- return undefined;
17
- }
18
- };
1
+ export const fetchLocalePublishedDoc = async ({ req, collection, docId, locale, }) => (await req.payload.findByID({
2
+ collection: collection.slug,
3
+ id: docId,
4
+ ...(locale ? { locale: locale } : {}),
5
+ fallbackLocale: false,
6
+ depth: 0,
7
+ overrideAccess: true,
8
+ req,
9
+ }));
@@ -1,20 +1,12 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import { type VersionRow } from './version-rows.js';
3
- export declare const fetchPublishedVersionPages: ({ req, collectionSlug, docId, locale, versionLocale, versionFilter, }: {
3
+ export declare const fetchPublishedVersionPages: ({ req, collectionSlug, docId, locale, versionFilter, }: {
4
4
  req: PayloadRequest;
5
5
  collectionSlug: string;
6
6
  docId: string | number;
7
- locale: string;
8
- versionLocale?: string;
7
+ locale?: string;
9
8
  versionFilter?: {
10
9
  localizeStatus?: boolean;
11
10
  defaultLocale?: string;
12
- identifier?: string;
13
11
  };
14
12
  }) => Promise<VersionRow[]>;
15
- export declare const fetchVersionHistoryPages: ({ req, collectionSlug, docId, versionLocale, }: {
16
- req: PayloadRequest;
17
- collectionSlug: string;
18
- docId: string | number;
19
- versionLocale?: string;
20
- }) => Promise<VersionRow[]>;
@@ -1,10 +1,8 @@
1
- import { toTypedLocale } from './document-locale.js';
2
1
  import { isPublishedVersionRow } from './version-rows.js';
3
- export const fetchPublishedVersionPages = async ({ req, collectionSlug, docId, locale, versionLocale, versionFilter, }) => {
2
+ export const fetchPublishedVersionPages = async ({ req, collectionSlug, docId, locale, versionFilter, }) => {
4
3
  const published = [];
5
4
  let page = 1;
6
5
  const limit = 50;
7
- const queryLocale = versionLocale ?? locale;
8
6
  while (true) {
9
7
  const result = await req.payload.findVersions({
10
8
  collection: collectionSlug,
@@ -13,39 +11,15 @@ export const fetchPublishedVersionPages = async ({ req, collectionSlug, docId, l
13
11
  depth: 0,
14
12
  page,
15
13
  limit,
16
- ...(versionLocale === undefined ? undefined : { locale: toTypedLocale(queryLocale) }),
14
+ ...(locale ? { locale: locale } : {}),
15
+ fallbackLocale: false,
17
16
  overrideAccess: true,
18
17
  req,
19
18
  });
20
- const rows = result.docs.filter((row) => isPublishedVersionRow(row, locale, versionFilter));
21
- published.push(...rows);
19
+ published.push(...result.docs.filter((row) => isPublishedVersionRow(row, locale, versionFilter)));
22
20
  if (!result.hasNextPage)
23
21
  break;
24
22
  page += 1;
25
23
  }
26
24
  return published;
27
25
  };
28
- export const fetchVersionHistoryPages = async ({ req, collectionSlug, docId, versionLocale, }) => {
29
- const rows = [];
30
- let page = 1;
31
- const limit = 50;
32
- while (true) {
33
- const result = await req.payload.findVersions({
34
- collection: collectionSlug,
35
- where: { parent: { equals: docId } },
36
- sort: '-updatedAt',
37
- depth: 0,
38
- page,
39
- limit,
40
- ...(versionLocale === undefined ? undefined : { locale: toTypedLocale(versionLocale) }),
41
- overrideAccess: true,
42
- req,
43
- });
44
- const docs = result.docs.filter((row) => !row.snapshot && !row.autosave);
45
- rows.push(...docs);
46
- if (!result.hasNextPage)
47
- break;
48
- page += 1;
49
- }
50
- return rows;
51
- };
@@ -7,13 +7,7 @@ export type VersionRow = {
7
7
  published_locale?: string;
8
8
  version?: Record<string, unknown>;
9
9
  };
10
- export declare const isPublishedVersionRow: (row: VersionRow, locale: string, options?: {
10
+ export declare const isPublishedVersionRow: (row: VersionRow, locale: string | undefined, options?: {
11
11
  localizeStatus?: boolean;
12
12
  defaultLocale?: string;
13
- identifier?: string;
14
13
  }) => boolean;
15
- export declare const pickPublishedVersions: (rows: VersionRow[], locale: string, options?: {
16
- localizeStatus?: boolean;
17
- defaultLocale?: string;
18
- identifier?: string;
19
- }) => VersionRow[];
@@ -2,40 +2,16 @@ export const isPublishedVersionRow = (row, locale, options) => {
2
2
  if (row.snapshot || row.autosave)
3
3
  return false;
4
4
  const publishedLocale = row.publishedLocale ?? row.published_locale;
5
- if (publishedLocale) {
5
+ if (publishedLocale)
6
6
  return publishedLocale === locale;
7
- }
8
7
  const status = row.version?._status;
9
8
  if (status === 'draft')
10
9
  return false;
11
- if (options?.localizeStatus && options.identifier) {
12
- const field = row.version?.[options.identifier];
13
- if (typeof field === 'string') {
14
- if (typeof status === 'object' && status !== null) {
15
- return status[locale] === 'published';
16
- }
17
- return status === 'published';
18
- }
19
- if (field && typeof field === 'object' && !Array.isArray(field)) {
20
- if (!(locale in field))
21
- return false;
22
- if (typeof status === 'object' && status !== null) {
23
- return status[locale] === 'published';
24
- }
25
- if (status === 'published')
26
- return true;
27
- return false;
28
- }
29
- }
30
- if (status && typeof status === 'object') {
31
- return status[locale] === 'published';
10
+ if (status && typeof status === 'object' && !Array.isArray(status)) {
11
+ return locale !== undefined && status[locale] === 'published';
32
12
  }
33
13
  if (status === 'published') {
34
- if (options?.localizeStatus && options.defaultLocale) {
35
- return locale === options.defaultLocale;
36
- }
37
- return true;
14
+ return !options?.localizeStatus || locale !== undefined;
38
15
  }
39
16
  return false;
40
17
  };
41
- export const pickPublishedVersions = (rows, locale, options) => rows.filter((row) => isPublishedVersionRow(row, locale, options));
@@ -1,11 +1,30 @@
1
+ import type { CollectionSlug, DataFromCollectionSlug, TypedLocale } from 'payload';
2
+ export type RedirectPathOptions<TSlug extends CollectionSlug = CollectionSlug> = {
3
+ enabled?: true;
4
+ path: string;
5
+ paths?: never;
6
+ getPath?: never;
7
+ } | {
8
+ enabled?: true;
9
+ path?: never;
10
+ paths: string extends Extract<TypedLocale, string> ? Record<string, string> : Record<Extract<TypedLocale, string>, string>;
11
+ getPath?: never;
12
+ } | {
13
+ enabled?: true;
14
+ path?: never;
15
+ paths?: never;
16
+ getPath: (args: {
17
+ doc: DataFromCollectionSlug<TSlug>;
18
+ locale: TypedLocale | undefined;
19
+ }) => string | null;
20
+ } | {
21
+ enabled: false;
22
+ path?: never;
23
+ paths?: never;
24
+ getPath?: never;
25
+ };
1
26
  export type PublicationTransition = {
2
- published: boolean;
3
27
  locale?: string;
4
- previous?: string;
5
- current?: string;
6
- previousDoc?: Record<string, unknown>;
7
- currentDoc?: Record<string, unknown>;
8
- };
9
- export type GetPublicationTransitionOptions = {
10
- identifier: string;
28
+ currentDoc: Record<string, unknown>;
29
+ publishedDocs: Record<string, unknown>[];
11
30
  };
@@ -20,7 +20,7 @@ export const createRedirectsCollection = (overrides = {}) => {
20
20
  timestamps: overrides.timestamps ?? true,
21
21
  admin: {
22
22
  useAsTitle: 'from',
23
- defaultColumns: ['from', 'to', 'StatusCode', 'origin', 'enabled', 'updatedAt'],
23
+ defaultColumns: ['from', 'to', 'statusCode', 'origin', 'enabled', 'updatedAt'],
24
24
  listSearchableFields: ['from', 'to'],
25
25
  ...overrides.admin,
26
26
  },
@@ -139,7 +139,7 @@ const normalizeRulePaths = (data) => {
139
139
  }
140
140
  data.to = normalize(data.to, 'to');
141
141
  try {
142
- const statusCode = assertRedirectStatusCode(data.StatusCode ?? DEFAULT_REDIRECT_STATUS_CODE);
142
+ const statusCode = assertRedirectStatusCode(data.statusCode ?? DEFAULT_REDIRECT_STATUS_CODE);
143
143
  validateDestinationForStatus(statusCode, data.to);
144
144
  }
145
145
  catch (error) {
@@ -40,7 +40,7 @@ export const buildRedirectFields = () => [
40
40
  access: publicFieldRead,
41
41
  validate: (value, { siblingData }) => {
42
42
  try {
43
- const statusCode = assertRedirectStatusCode(siblingData?.StatusCode ?? DEFAULT_REDIRECT_STATUS_CODE);
43
+ const statusCode = assertRedirectStatusCode(siblingData?.statusCode ?? DEFAULT_REDIRECT_STATUS_CODE);
44
44
  validateDestinationForStatus(statusCode, value);
45
45
  if (typeof value === 'string' &&
46
46
  normalizeRelativeRedirectPath(value) === normalizeSiblingFrom(siblingData?.from)) {
@@ -54,7 +54,7 @@ export const buildRedirectFields = () => [
54
54
  },
55
55
  },
56
56
  {
57
- name: 'StatusCode',
57
+ name: 'statusCode',
58
58
  type: 'select',
59
59
  label: 'Type',
60
60
  defaultValue: String(DEFAULT_REDIRECT_STATUS_CODE),
@@ -70,7 +70,7 @@ export const buildRedirectFields = () => [
70
70
  return true;
71
71
  }
72
72
  catch (error) {
73
- return error instanceof Error ? error.message : 'Invalid StatusCode';
73
+ return error instanceof Error ? error.message : 'Invalid statusCode';
74
74
  }
75
75
  },
76
76
  admin: { position: 'sidebar' },
@@ -140,7 +140,7 @@ export const assertRedirectFields = (fields) => {
140
140
  const expected = new Map([
141
141
  ['from', 'text'],
142
142
  ['to', 'text'],
143
- ['StatusCode', 'select'],
143
+ ['statusCode', 'select'],
144
144
  ['enabled', 'checkbox'],
145
145
  ['origin', 'select'],
146
146
  ]);
@@ -11,7 +11,7 @@ export const isRedirectStatusCode = (value) => normalizeStatusCode(value) !== un
11
11
  export const assertRedirectStatusCode = (value) => {
12
12
  const code = normalizeStatusCode(value);
13
13
  if (code === undefined) {
14
- throw new RedirectValidationError(`StatusCode must be one of ${SUPPORTED.join(', ')}`);
14
+ throw new RedirectValidationError(`statusCode must be one of ${SUPPORTED.join(', ')}`);
15
15
  }
16
16
  return code;
17
17
  };
@@ -1,19 +1,10 @@
1
1
  import type { Payload, PayloadRequest, SelectType } from 'payload';
2
2
  import type { RedirectStatusCode } from './model/status-code.js';
3
- /** Lookup hooks / idempotent writes (includes `id`). */
4
- export declare const redirectLookupSelect: {
5
- readonly id: true;
6
- readonly from: true;
7
- readonly to: true;
8
- readonly StatusCode: true;
9
- readonly enabled: true;
10
- readonly origin: true;
11
- };
12
3
  export type RedirectLookupDoc = {
13
4
  id: string | number;
14
5
  from?: string | null;
15
6
  to?: string | null;
16
- StatusCode?: RedirectStatusCode | null;
7
+ statusCode?: RedirectStatusCode | null;
17
8
  enabled?: boolean | null;
18
9
  origin?: string | null;
19
10
  };
@@ -1,9 +1,9 @@
1
1
  /** Lookup hooks / idempotent writes (includes `id`). */
2
- export const redirectLookupSelect = {
2
+ const redirectLookupSelect = {
3
3
  id: true,
4
4
  from: true,
5
5
  to: true,
6
- StatusCode: true,
6
+ statusCode: true,
7
7
  enabled: true,
8
8
  origin: true,
9
9
  };
@@ -1,20 +1,8 @@
1
- import { type PreviewRoutes } from './preview-routes.js';
2
- import { type RouteParamsConfig } from './route-params.js';
3
- export type LocalePrefix = Record<string, string>;
4
- export type PublishedLinkPathTemplate = {
1
+ export type LocalePrefixes = Record<string, string>;
2
+ export type PublishedPathConfiguration = {
5
3
  path?: string;
6
4
  paths?: Record<string, string>;
7
- routes?: PreviewRoutes;
8
- params?: RouteParamsConfig;
9
5
  getPath?: unknown;
10
6
  };
11
- export type ResolvedPublishedPathConfig = PublishedLinkPathTemplate & {
12
- localePrefix: LocalePrefix;
13
- };
14
- export declare function mergeLocalePrefix(plugin?: LocalePrefix, schema?: LocalePrefix): LocalePrefix;
15
- export declare function resolveLocaleRoutePrefix(localePrefix: LocalePrefix, code: string): string | null;
16
- export declare function resolvePathTemplate(config: Pick<PublishedLinkPathTemplate, 'path' | 'paths' | 'routes'>, locale: unknown): string | null;
17
- export declare function buildPublishedPath(config: ResolvedPublishedPathConfig, data: Record<string, unknown>, locale: unknown): string | null;
18
- export declare function resolvePublishedPathConfig(pluginLocalePrefix?: LocalePrefix, link?: PublishedLinkPathTemplate & {
19
- localePrefix?: LocalePrefix;
20
- }): ResolvedPublishedPathConfig | null;
7
+ export declare const isValidLocalePrefix: (prefix: string) => boolean;
8
+ export declare const buildPublishedPath: (config: PublishedPathConfiguration, doc: Record<string, unknown>, locale: unknown, localePrefixes?: LocalePrefixes) => string | null;
@@ -1,131 +1,49 @@
1
- import { localeCode } from './preview-path.js';
2
- import { buildPreviewPath } from './preview-routes.js';
3
- import { applyDynamicSegments } from './route-params.js';
4
- export function mergeLocalePrefix(plugin, schema) {
5
- return Object.assign({}, plugin, schema);
6
- }
7
- function normalizeLocalePrefix(prefix) {
8
- const trimmed = prefix.trim();
9
- if (!trimmed || trimmed === '/')
10
- return '';
11
- const withLeading = trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
12
- return withLeading.replace(/\/+$/, '');
13
- }
14
- export function resolveLocaleRoutePrefix(localePrefix, code) {
15
- if (Object.keys(localePrefix).length === 0) {
16
- return `/${code}`;
1
+ import { applyDynamicSegments, hasControlCharacter, isValidPathTemplate } from './route-params.js';
2
+ const localeCode = (locale) => {
3
+ if (typeof locale === 'string')
4
+ return locale || undefined;
5
+ if (locale && typeof locale === 'object' && 'code' in locale) {
6
+ const code = locale.code;
7
+ return typeof code === 'string' && code ? code : undefined;
17
8
  }
18
- const explicit = localePrefix[code];
19
- if (explicit === undefined) {
20
- return null;
21
- }
22
- return normalizeLocalePrefix(explicit);
23
- }
24
- function patternForLocale(previewRoutes, locale) {
25
- const entries = Object.entries(previewRoutes);
26
- if (entries.length === 0)
27
- return null;
28
- const first = entries[0];
29
- if (!first)
30
- return null;
31
- const [, template] = first;
32
- const code = localeCode(locale);
33
- if (!code)
34
- return null;
35
- if (typeof template === 'string')
36
- return template;
37
- return template[code] ?? null;
38
- }
39
- export function resolvePathTemplate(config, locale) {
40
- const code = localeCode(locale);
41
- if (!code)
42
- return null;
43
- const localized = config.paths?.[code];
44
- if (localized)
45
- return localized;
46
- if (config.path)
47
- return config.path;
48
- if (config.routes)
49
- return patternForLocale(config.routes, locale);
50
- return null;
51
- }
52
- function joinPrefixAndPath(prefix, pathname) {
53
- if (pathname === '/' || pathname === '') {
54
- return prefix || '/';
55
- }
56
- const normalized = pathname.startsWith('/') ? pathname : `/${pathname}`;
57
- return `${prefix}${normalized}`;
58
- }
59
- function isSiteRelativePath(path) {
60
- return (path.startsWith('/') &&
61
- !path.startsWith('//') &&
62
- !path.includes('?') &&
63
- !path.includes('#') &&
64
- !path.includes('\\') &&
65
- ![...path].some((character) => {
66
- const code = character.charCodeAt(0);
67
- return code < 32 || code === 127;
68
- }));
69
- }
70
- function usesLegacyPreviewPathBuilder(config) {
71
- const hasNewTemplate = Boolean(config.path) || Boolean(config.paths && Object.keys(config.paths).length > 0);
72
- if (hasNewTemplate)
73
- return false;
74
- if (!config.routes || Object.keys(config.routes).length === 0)
75
- return false;
76
- return Object.keys(config.localePrefix).length === 0;
77
- }
78
- export function buildPublishedPath(config, data, locale) {
9
+ return undefined;
10
+ };
11
+ export const isValidLocalePrefix = (prefix) => prefix === '' ||
12
+ (prefix.startsWith('/') &&
13
+ !prefix.startsWith('//') &&
14
+ !prefix.includes('?') &&
15
+ !prefix.includes('#') &&
16
+ !prefix.includes('\\') &&
17
+ !hasControlCharacter(prefix));
18
+ const withPrefix = (prefix, path) => path === '/' ? prefix || '/' : `${prefix}${path}`;
19
+ const isSiteRelativePath = (path) => path.startsWith('/') &&
20
+ !path.startsWith('//') &&
21
+ !path.includes('?') &&
22
+ !path.includes('#') &&
23
+ !path.includes('\\') &&
24
+ !hasControlCharacter(path);
25
+ export const buildPublishedPath = (config, doc, locale, localePrefixes) => {
79
26
  if (typeof config.getPath === 'function') {
80
- const path = config.getPath({ doc: data, locale });
27
+ const path = config.getPath({
28
+ doc,
29
+ locale,
30
+ });
81
31
  if (path === null)
82
32
  return null;
83
- if (typeof path !== 'string') {
84
- throw new Error('getPath must return a path or null');
85
- }
86
- const code = localeCode(locale);
87
- if (!code)
33
+ if (typeof path !== 'string')
88
34
  return null;
89
- const prefix = resolveLocaleRoutePrefix(config.localePrefix, code);
90
- if (prefix === null)
91
- return null;
92
- const result = joinPrefixAndPath(prefix, path);
93
- return isSiteRelativePath(result) ? result : null;
94
- }
95
- if (usesLegacyPreviewPathBuilder(config)) {
96
- if (!config.routes)
97
- throw new Error('Legacy preview path requires locale routes');
98
- return buildPreviewPath(config.routes, data, locale, config.params);
35
+ return isSiteRelativePath(path) ? path : null;
99
36
  }
100
37
  const code = localeCode(locale);
101
- if (!code)
38
+ const template = config.paths !== undefined ? (code ? config.paths[code] : undefined) : config.path;
39
+ if (typeof template !== 'string' || !isValidPathTemplate(template))
102
40
  return null;
103
- const pattern = resolvePathTemplate(config, locale);
104
- if (!pattern)
105
- return null;
106
- const resolved = applyDynamicSegments(pattern, data, locale, config.params);
41
+ const resolved = applyDynamicSegments(template, doc, code);
107
42
  if (resolved === null)
108
43
  return null;
109
- const prefix = resolveLocaleRoutePrefix(config.localePrefix, code);
110
- if (prefix === null)
111
- return null;
112
- const result = joinPrefixAndPath(prefix, resolved);
113
- return isSiteRelativePath(result) ? result : null;
114
- }
115
- export function resolvePublishedPathConfig(pluginLocalePrefix, link) {
116
- if (!link)
117
- return null;
118
- const hasRoutes = link.routes && typeof link.routes === 'object' && Object.keys(link.routes).length > 0;
119
- const hasPath = typeof link.path === 'string' && link.path.length > 0;
120
- const hasPaths = link.paths && Object.keys(link.paths).length > 0;
121
- if (!hasRoutes && !hasPath && !hasPaths && typeof link.getPath !== 'function')
44
+ if (localePrefixes === undefined)
45
+ return resolved;
46
+ if (!code || !Object.hasOwn(localePrefixes, code))
122
47
  return null;
123
- return {
124
- localePrefix: mergeLocalePrefix(pluginLocalePrefix, link.localePrefix),
125
- path: link.path,
126
- paths: link.paths,
127
- routes: hasRoutes ? link.routes : undefined,
128
- params: link.params,
129
- getPath: link.getPath,
130
- };
131
- }
48
+ return withPrefix(localePrefixes[code], resolved);
49
+ };
@@ -1,11 +1,3 @@
1
- export type RouteParamFieldSpec = {
2
- field: string;
3
- localized?: boolean;
4
- };
5
- export type RouteParamMapping = string | RouteParamFieldSpec;
6
- export type RouteParamsConfig = Record<string, RouteParamMapping>;
7
- export declare function templateHasUnsupportedDynamicSyntax(template: string): boolean;
8
- export declare function extractDynamicSegments(template: string): string[];
9
- export declare function readValueAtPath(data: Record<string, unknown>, fieldPath: string): unknown;
10
- export declare function resolveRouteParam(paramName: string, data: Record<string, unknown>, locale: unknown, routeParams: RouteParamsConfig | undefined): string | null;
11
- export declare function applyDynamicSegments(pattern: string, data: Record<string, unknown>, locale: unknown, routeParams: RouteParamsConfig | undefined): string | null;
1
+ export declare const hasControlCharacter: (value: string) => boolean;
2
+ export declare const isValidPathTemplate: (template: string) => boolean;
3
+ export declare const applyDynamicSegments: (template: string, doc: Record<string, unknown>, locale: string | undefined) => string | null;