@klnap/payload-redirect 0.4.0 → 0.4.1

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 4adb5e9: Fix automatic redirect ownership races. Automatic rule generation and rule updates now take the redirect graph lock before reading existing rules, so a manual edit committed during the decision is no longer overwritten. Graph validation now reads the stored rule after the lock is acquired. The README's Next.js example now matches the stored source exactly, including the query string, and no longer decodes the request path.
8
+
3
9
  ## 0.4.0
4
10
 
5
11
  ### Minor Changes
package/README.md CHANGED
@@ -147,23 +147,15 @@ function normalizeRequestPath(pathname: string): string {
147
147
  return collapsed.length > 1 && collapsed.endsWith("/") ? collapsed.slice(0, -1) : collapsed;
148
148
  }
149
149
 
150
- function decodeSafely(value: string): string {
151
- try {
152
- return decodeURI(value);
153
- } catch {
154
- return value;
155
- }
156
- }
157
-
158
150
  export async function proxy(request: NextRequest) {
159
- const pathname = normalizeRequestPath(request.nextUrl.pathname);
160
- const candidates = [...new Set([pathname, decodeSafely(pathname)])];
151
+ const { search } = request.nextUrl;
152
+ const from = normalizeRequestPath(request.nextUrl.pathname) + search;
161
153
 
162
154
  const payload = await getPayload({ config: payloadConfig });
163
155
  const { docs } = await payload.find({
164
156
  collection: "redirects",
165
157
  where: {
166
- and: [{ from: { in: candidates } }, { enabled: { equals: true } }],
158
+ and: [{ from: { equals: from } }, { enabled: { equals: true } }],
167
159
  },
168
160
  limit: 1,
169
161
  pagination: false,
@@ -174,7 +166,11 @@ export async function proxy(request: NextRequest) {
174
166
  const rule = docs[0];
175
167
  if (!rule) return NextResponse.next();
176
168
 
177
- return NextResponse.redirect(new URL(rule.to, request.url), Number(rule.statusCode) as 301 | 302);
169
+ const target = new URL(rule.to, request.url);
170
+ // A rule that points at the current path and query would redirect forever. Fragments are not sent to the server.
171
+ if (target.pathname + target.search === from) return NextResponse.next();
172
+
173
+ return NextResponse.redirect(target, Number(rule.statusCode) as 301 | 302);
178
174
  }
179
175
 
180
176
  export const config = {
@@ -337,13 +333,33 @@ redirects({
337
333
  - `statusCode` is `301` (default) or `302`.
338
334
  - `enabled` defaults to `true`. `origin` is `manual` for rules you create and `auto` for generated ones.
339
335
 
336
+ ### Campaign links
337
+
338
+ Share short, readable URLs in SMS campaigns, newsletters, or promotional materials. A manual rule redirects visitors to the landing page with campaign parameters:
339
+
340
+ | Field | Value |
341
+ | ------------ | --------------------------------------------------------------------- |
342
+ | `from` | `/summer-2027` |
343
+ | `to` | `/summer-2027?utm_source=sms&utm_medium=sms&utm_campaign=summer_2027` |
344
+ | `statusCode` | `302` |
345
+ | `enabled` | `true` |
346
+
347
+ Rules for query strings:
348
+
349
+ - Sources and destinations may contain a query string. Source matching is exact, so `/campaign?ref=sms` is distinct from `/campaign` and from `/campaign?ref=email`.
350
+ - A source and destination may share a pathname when their query strings differ. The lookup in [Serving redirects](#serving-redirects) includes `search`, so the landing request does not match the campaign rule again.
351
+ - The plugin does not forward or merge incoming query parameters. The destination is the stored `to`.
352
+ - Automatic content paths have no query strings. Campaign rules are ordinary manual rules.
353
+
354
+ The plugin stores these rules only. It does not collect attribution data or integrate with analytics or advertising tools.
355
+
340
356
  Register `redirects()` once. A second registration throws. The collection slug defaults to `redirects`. Change it with `overrides.slug` if that slug is taken.
341
357
 
342
358
  ## Serving redirects
343
359
 
344
360
  The plugin stores rules and does not send responses. The [complete example](#complete-example) shows `src/proxy.ts`, which looks up the rule and returns the redirect with its stored status.
345
361
 
346
- Stored rules use the plugin's normalization, and `URL.pathname` alone does not match it. The lookup in `proxy.ts` applies the same rules to the request path:
362
+ Stored rules use the plugin's normalization. The lookup in `proxy.ts` applies the same path rules to `request.nextUrl.pathname` and appends `request.nextUrl.search`, so a query-specific rule matches only the same query string:
347
363
 
348
364
  | Input | Stored source |
349
365
  | ------------------------ | ------------------------------------ |
@@ -355,7 +371,9 @@ Stored rules use the plugin's normalization, and `URL.pathname` alone does not m
355
371
 
356
372
  Normalization trims whitespace, adds a leading slash, collapses repeated slashes, resolves `.` and `..` segments (including percent-encoded forms), and removes a trailing slash except at `/`. It preserves Unicode, percent encoding, and query strings. Fragments are rejected.
357
373
 
358
- The example looks up the pathname only, so rules with a query string never match. If you need them, add the query string to the lookup yourself. Lookup compares the stored value exactly, so case and encoding matter.
374
+ Lookup is exact. The request path is not decoded, so a browser request for `/caf%C3%A9` matches only a rule stored as `/caf%C3%A9`, and a rule stored as `/café` never matches a browser request. Store the percent-encoded form for paths that browsers request. Query parameters are not reordered, merged, or forwarded: the destination is the stored `to`.
375
+
376
+ A pathname-only rule does not match a request that has extra query parameters. Add a second rule with the exact query string if needed. Automatic rules use paths without query strings.
359
377
 
360
378
  ## Overrides and access
361
379
 
@@ -1,4 +1,5 @@
1
1
  import { isIdenticalAutoRule } from "./match-existing-rule.js";
2
+ import { lockRedirectRuleGraph } from "../collection/graph-lock.js";
2
3
  import { REDIRECT_CONTEXT_KEYS } from "../context-keys.js";
3
4
  import { findRedirectByFrom } from "../queries.js";
4
5
  /**
@@ -18,6 +19,8 @@ export const ensureAutoRedirect = async ({ req, collectionSlug, rule, context, }
18
19
  origin: "auto",
19
20
  };
20
21
  const payload = req.payload;
22
+ // Lock before the lookup: the ownership decision must read rows committed before this write.
23
+ await lockRedirectRuleGraph(req);
21
24
  const existing = await findRedirectByFrom(req.payload, {
22
25
  collectionSlug,
23
26
  from: rule.from,
@@ -1 +1 @@
1
- {"version":3,"file":"persist-auto-rule.js","sourceRoot":"","sources":["../../../../src/core/redirects/auto/persist-auto-rule.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mDAAmD,CAAC;AACxF,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,EAAE,kBAAkB,EAA0B,MAAM,kCAAkC,CAAC;AAc9F;;GAEG;AACH,MAAM,CAAC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AC;QACnB,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,MAAM,OAAO,CAAC,MAAM,CAAC;QACnB,UAAU,EAAE,cAAc;QAC1B,IAAI;QACJ,OAAO,EAAE,eAAe;QACxB,cAAc,EAAE,IAAI;QACpB,GAAG;KACJ,CAAC,CAAC;IAEH,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import type { PayloadRequest } from \"payload\";\nimport { isIdenticalAutoRule } from \"#redirect/core/redirects/auto/match-existing-rule\";\nimport { REDIRECT_CONTEXT_KEYS } from \"#redirect/core/redirects/context-keys\";\nimport { findRedirectByFrom, type RedirectLookupDoc } from \"#redirect/core/redirects/queries\";\n\ntype AutoRedirectRule = {\n from: string;\n to: string;\n};\n\ntype EnsureAutoRedirectArgs = {\n req: PayloadRequest;\n collectionSlug: string;\n rule: AutoRedirectRule;\n context?: Record<string, unknown>;\n};\n\n/**\n * Idempotent create for auto 301 rules. Plugin-owned integrity operations use trusted Local API access.\n */\nexport const ensureAutoRedirect = async ({\n req,\n collectionSlug,\n rule,\n context,\n}: EnsureAutoRedirectArgs): Promise<\"created\" | \"skipped\" | \"updated\"> => {\n const internalContext = {\n ...context,\n [REDIRECT_CONTEXT_KEYS.autoWrite]: true,\n [REDIRECT_CONTEXT_KEYS.skipAuto]: true,\n };\n\n const data = {\n from: rule.from,\n to: rule.to,\n statusCode: \"301\",\n enabled: true,\n origin: \"auto\" as const,\n };\n const payload = req.payload as unknown as {\n create: (args: Record<string, unknown>) => Promise<unknown>;\n update: (args: Record<string, unknown>) => Promise<unknown>;\n };\n\n const existing = await findRedirectByFrom(req.payload, {\n collectionSlug,\n from: rule.from,\n req,\n overrideAccess: true,\n context: internalContext,\n });\n\n const doc = existing.docs[0] as RedirectLookupDoc | undefined;\n if (doc) {\n if (isIdenticalAutoRule(doc, rule)) {\n return \"skipped\";\n }\n if (doc.origin === \"auto\") {\n await payload.update({\n collection: collectionSlug,\n id: doc.id,\n data: {\n to: rule.to,\n statusCode: \"301\",\n enabled: true,\n },\n context: internalContext,\n overrideAccess: true,\n req,\n });\n return \"updated\";\n }\n return \"skipped\";\n }\n\n await payload.create({\n collection: collectionSlug,\n data,\n context: internalContext,\n overrideAccess: true,\n req,\n });\n\n return \"created\";\n};\n"]}
1
+ {"version":3,"file":"persist-auto-rule.js","sourceRoot":"","sources":["../../../../src/core/redirects/auto/persist-auto-rule.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mDAAmD,CAAC;AACxF,OAAO,EAAE,qBAAqB,EAAE,MAAM,gDAAgD,CAAC;AACvF,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,EAAE,kBAAkB,EAA0B,MAAM,kCAAkC,CAAC;AAc9F;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,KAAK,EAAE,EACvC,GAAG,EACH,cAAc,EACd,IAAI,EACJ,OAAO,GACgB,EAA8C,EAAE;IACvE,MAAM,eAAe,GAAG;QACtB,GAAG,OAAO;QACV,CAAC,qBAAqB,CAAC,SAAS,CAAC,EAAE,IAAI;QACvC,CAAC,qBAAqB,CAAC,QAAQ,CAAC,EAAE,IAAI;KACvC,CAAC;IAEF,MAAM,IAAI,GAAG;QACX,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,EAAE,EAAE,IAAI,CAAC,EAAE;QACX,UAAU,EAAE,KAAK;QACjB,OAAO,EAAE,IAAI;QACb,MAAM,EAAE,MAAe;KACxB,CAAC;IACF,MAAM,OAAO,GAAG,GAAG,CAAC,OAGnB,CAAC;IAEF,6FAA6F;IAC7F,MAAM,qBAAqB,CAAC,GAAG,CAAC,CAAC;IACjC,MAAM,QAAQ,GAAG,MAAM,kBAAkB,CAAC,GAAG,CAAC,OAAO,EAAE;QACrD,cAAc;QACd,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,GAAG;QACH,cAAc,EAAE,IAAI;QACpB,OAAO,EAAE,eAAe;KACzB,CAAC,CAAC;IAEH,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAkC,CAAC;IAC9D,IAAI,GAAG,EAAE,CAAC;QACR,IAAI,mBAAmB,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,CAAC;YACnC,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,IAAI,GAAG,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;YAC1B,MAAM,OAAO,CAAC,MAAM,CAAC;gBACnB,UAAU,EAAE,cAAc;gBAC1B,EAAE,EAAE,GAAG,CAAC,EAAE;gBACV,IAAI,EAAE;oBACJ,EAAE,EAAE,IAAI,CAAC,EAAE;oBACX,UAAU,EAAE,KAAK;oBACjB,OAAO,EAAE,IAAI;iBACd;gBACD,OAAO,EAAE,eAAe;gBACxB,cAAc,EAAE,IAAI;gBACpB,GAAG;aACJ,CAAC,CAAC;YACH,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,MAAM,OAAO,CAAC,MAAM,CAAC;QACnB,UAAU,EAAE,cAAc;QAC1B,IAAI;QACJ,OAAO,EAAE,eAAe;QACxB,cAAc,EAAE,IAAI;QACpB,GAAG;KACJ,CAAC,CAAC;IAEH,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import type { PayloadRequest } from \"payload\";\nimport { isIdenticalAutoRule } from \"#redirect/core/redirects/auto/match-existing-rule\";\nimport { lockRedirectRuleGraph } from \"#redirect/core/redirects/collection/graph-lock\";\nimport { REDIRECT_CONTEXT_KEYS } from \"#redirect/core/redirects/context-keys\";\nimport { findRedirectByFrom, type RedirectLookupDoc } from \"#redirect/core/redirects/queries\";\n\ntype AutoRedirectRule = {\n from: string;\n to: string;\n};\n\ntype EnsureAutoRedirectArgs = {\n req: PayloadRequest;\n collectionSlug: string;\n rule: AutoRedirectRule;\n context?: Record<string, unknown>;\n};\n\n/**\n * Idempotent create for auto 301 rules. Plugin-owned integrity operations use trusted Local API access.\n */\nexport const ensureAutoRedirect = async ({\n req,\n collectionSlug,\n rule,\n context,\n}: EnsureAutoRedirectArgs): Promise<\"created\" | \"skipped\" | \"updated\"> => {\n const internalContext = {\n ...context,\n [REDIRECT_CONTEXT_KEYS.autoWrite]: true,\n [REDIRECT_CONTEXT_KEYS.skipAuto]: true,\n };\n\n const data = {\n from: rule.from,\n to: rule.to,\n statusCode: \"301\",\n enabled: true,\n origin: \"auto\" as const,\n };\n const payload = req.payload as unknown as {\n create: (args: Record<string, unknown>) => Promise<unknown>;\n update: (args: Record<string, unknown>) => Promise<unknown>;\n };\n\n // Lock before the lookup: the ownership decision must read rows committed before this write.\n await lockRedirectRuleGraph(req);\n const existing = await findRedirectByFrom(req.payload, {\n collectionSlug,\n from: rule.from,\n req,\n overrideAccess: true,\n context: internalContext,\n });\n\n const doc = existing.docs[0] as RedirectLookupDoc | undefined;\n if (doc) {\n if (isIdenticalAutoRule(doc, rule)) {\n return \"skipped\";\n }\n if (doc.origin === \"auto\") {\n await payload.update({\n collection: collectionSlug,\n id: doc.id,\n data: {\n to: rule.to,\n statusCode: \"301\",\n enabled: true,\n },\n context: internalContext,\n overrideAccess: true,\n req,\n });\n return \"updated\";\n }\n return \"skipped\";\n }\n\n await payload.create({\n collection: collectionSlug,\n data,\n context: internalContext,\n overrideAccess: true,\n req,\n });\n\n return \"created\";\n};\n"]}
@@ -1,4 +1,5 @@
1
1
  import { createDuplicateBeforeChange } from "./duplicate-guard.js";
2
+ import { createRedirectGraphLockBeforeOperation } from "./graph-lock.js";
2
3
  import { assertRedirectFields, buildRedirectFields, mergeRedirectFields } from "./fields.js";
3
4
  import { createRedirectOriginBeforeChange } from "./origin-hook.js";
4
5
  const DEFAULT_SLUG = "redirects";
@@ -26,6 +27,10 @@ export const createRedirectsCollection = (overrides = {}) => {
26
27
  fields,
27
28
  hooks: {
28
29
  ...existingHooks,
30
+ beforeOperation: [
31
+ ...(existingHooks.beforeOperation ?? []),
32
+ createRedirectGraphLockBeforeOperation(),
33
+ ],
29
34
  beforeChange: [
30
35
  ...(existingHooks.beforeChange ?? []),
31
36
  createRedirectOriginBeforeChange(),
@@ -1 +1 @@
1
- {"version":3,"file":"collection.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/collection.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,2BAA2B,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAC7F,OAAO,EAAE,gCAAgC,EAAE,MAAM,kBAAkB,CAAC;AAGpE,MAAM,YAAY,GAAG,WAAW,CAAC;AAEjC,MAAM,CAAC,MAAM,yBAAyB,GAAG,CACvC,SAAS,GAAgC,EAAE,EACzB,EAAE;IACpB,MAAM,aAAa,GAAG,mBAAmB,EAAE,CAAC;IAC5C,MAAM,MAAM,GAAY,SAAS,CAAC,MAAM;QACtC,CAAC,CAAC,mBAAmB,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC;QAC1D,CAAC,CAAC,aAAa,CAAC;IAElB,oBAAoB,CAAC,MAAM,CAAC,CAAC;IAE7B,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,IAAI,YAAY,CAAC;IAC5C,MAAM,aAAa,GAAG,SAAS,CAAC,KAAK,IAAI,EAAE,CAAC;IAE5C,OAAO;QACL,GAAG,SAAS;QACZ,IAAI;QACJ,KAAK,EAAE,SAAS,CAAC,KAAK,IAAI,IAAI;QAC9B,QAAQ,EAAE,SAAS,CAAC,QAAQ,IAAI,KAAK;QACrC,UAAU,EAAE,SAAS,CAAC,UAAU,IAAI,IAAI;QACxC,KAAK,EAAE;YACL,UAAU,EAAE,MAAM;YAClB,cAAc,EAAE,CAAC,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,CAAC;YAC9E,oBAAoB,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC;YACpC,GAAG,SAAS,CAAC,KAAK;SACnB;QACD,WAAW,EAAE,SAAS,CAAC,WAAW,IAAI,MAAM;QAC5C,MAAM;QACN,KAAK,EAAE;YACL,GAAG,aAAa;YAChB,YAAY,EAAE;gBACZ,GAAG,CAAC,aAAa,CAAC,YAAY,IAAI,EAAE,CAAC;gBACrC,gCAAgC,EAAE;gBAClC,2BAA2B,CAAC,IAAI,CAAC;aAClC;SACF;KACF,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import type { CollectionConfig, Field } from \"payload\";\nimport { createDuplicateBeforeChange } from \"./duplicate-guard.js\";\nimport { assertRedirectFields, buildRedirectFields, mergeRedirectFields } from \"./fields.js\";\nimport { createRedirectOriginBeforeChange } from \"./origin-hook.js\";\nimport type { RedirectCollectionOverrides } from \"./types.js\";\n\nconst DEFAULT_SLUG = \"redirects\";\n\nexport const createRedirectsCollection = (\n overrides: RedirectCollectionOverrides = {},\n): CollectionConfig => {\n const defaultFields = buildRedirectFields();\n const fields: Field[] = overrides.fields\n ? mergeRedirectFields(overrides.fields({ defaultFields }))\n : defaultFields;\n\n assertRedirectFields(fields);\n\n const slug = overrides.slug ?? DEFAULT_SLUG;\n const existingHooks = overrides.hooks ?? {};\n\n return {\n ...overrides,\n slug,\n trash: overrides.trash ?? true,\n versions: overrides.versions ?? false,\n timestamps: overrides.timestamps ?? true,\n admin: {\n useAsTitle: \"from\",\n defaultColumns: [\"from\", \"to\", \"statusCode\", \"origin\", \"enabled\", \"updatedAt\"],\n listSearchableFields: [\"from\", \"to\"],\n ...overrides.admin,\n },\n defaultSort: overrides.defaultSort ?? \"from\",\n fields,\n hooks: {\n ...existingHooks,\n beforeChange: [\n ...(existingHooks.beforeChange ?? []),\n createRedirectOriginBeforeChange(),\n createDuplicateBeforeChange(slug),\n ],\n },\n };\n};\n"]}
1
+ {"version":3,"file":"collection.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/collection.ts"],"names":[],"mappings":"AACA,OAAO,EAAE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gBACf,GAAG,CAAC,aAAa,CAAC,eAAe,IAAI,EAAE,CAAC;gBACxC,sCAAsC,EAAE;aACzC;YACD,YAAY,EAAE;gBACZ,GAAG,CAAC,aAAa,CAAC,YAAY,IAAI,EAAE,CAAC;gBACrC,gCAAgC,EAAE;gBAClC,2BAA2B,CAAC,IAAI,CAAC;aAClC;SACF;KACF,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import type { CollectionConfig, Field } from \"payload\";\nimport { createDuplicateBeforeChange } from \"./duplicate-guard.js\";\nimport { createRedirectGraphLockBeforeOperation } from \"./graph-lock.js\";\nimport { assertRedirectFields, buildRedirectFields, mergeRedirectFields } from \"./fields.js\";\nimport { createRedirectOriginBeforeChange } from \"./origin-hook.js\";\nimport type { RedirectCollectionOverrides } from \"./types.js\";\n\nconst DEFAULT_SLUG = \"redirects\";\n\nexport const createRedirectsCollection = (\n overrides: RedirectCollectionOverrides = {},\n): CollectionConfig => {\n const defaultFields = buildRedirectFields();\n const fields: Field[] = overrides.fields\n ? mergeRedirectFields(overrides.fields({ defaultFields }))\n : defaultFields;\n\n assertRedirectFields(fields);\n\n const slug = overrides.slug ?? DEFAULT_SLUG;\n const existingHooks = overrides.hooks ?? {};\n\n return {\n ...overrides,\n slug,\n trash: overrides.trash ?? true,\n versions: overrides.versions ?? false,\n timestamps: overrides.timestamps ?? true,\n admin: {\n useAsTitle: \"from\",\n defaultColumns: [\"from\", \"to\", \"statusCode\", \"origin\", \"enabled\", \"updatedAt\"],\n listSearchableFields: [\"from\", \"to\"],\n ...overrides.admin,\n },\n defaultSort: overrides.defaultSort ?? \"from\",\n fields,\n hooks: {\n ...existingHooks,\n beforeOperation: [\n ...(existingHooks.beforeOperation ?? []),\n createRedirectGraphLockBeforeOperation(),\n ],\n beforeChange: [\n ...(existingHooks.beforeChange ?? []),\n createRedirectOriginBeforeChange(),\n createDuplicateBeforeChange(slug),\n ],\n },\n };\n};\n"]}
@@ -1,5 +1,4 @@
1
1
  import { ValidationError } from "payload";
2
- import { lockRedirectRuleGraph } from "./graph-lock.js";
3
2
  import { assertRedirectStatusCode, DEFAULT_REDIRECT_STATUS_CODE, validateDestinationForStatus, } from "../model/status-code.js";
4
3
  import { normalizeRedirectSourcePath, normalizeRelativeRedirectPath, } from "../normalize-path.js";
5
4
  import { findRedirectByFrom } from "../queries.js";
@@ -162,9 +161,6 @@ export const effectiveRuleData = (operation, data, originalDoc) => {
162
161
  export const createDuplicateBeforeChange = (collectionSlug = "redirects") => {
163
162
  return async (args) => {
164
163
  const { data, req, operation, originalDoc } = args;
165
- if (operation === "create" || operation === "update") {
166
- await lockRedirectRuleGraph(req);
167
- }
168
164
  const effective = effectiveRuleData(operation, data, originalDoc);
169
165
  if (effective && (operation === "create" || operation === "update")) {
170
166
  normalizeRulePaths(effective);
@@ -1 +1 @@
1
- {"version":3,"file":"duplicate-guard.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/duplicate-guard.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAC1C,OAAO,EAAE,qBAAqB,EAAE,MAAM,gDAAgD,CAAC;AACvF,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,4BAA4B,GAC7B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,2BAA2B,EAC3B,6BAA6B,GAC9B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AAEtE,gHAAgH;AAChH,MAAM,CAAC,MAAM,uBAAuB,GAAG,IAAI,CAAC;AAE5C,MAAM,iBAAiB,GAAG,qDAAqD,CAAC;AAChF,MAAM,YAAY,GAChB,oFAAoF,CAAC;AACvF,MAAM,kBAAkB,GAAG,qEAAqE,CAAC;AACjG,MAAM,sBAAsB,GAAG,kEAAkE,uBAAuB,OAAO,CAAC;AAEhI,MAAM,oBAAoB,GAAG,CAAC,GAAY,EAAsB,EAAE;IAChE,IAAI,OAAO,GAAG,KAAK,QAAQ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port { lockRedirectRuleGraph } from \"#redirect/core/redirects/collection/graph-lock\";\nimport {\n assertRedirectStatusCode,\n DEFAULT_REDIRECT_STATUS_CODE,\n validateDestinationForStatus,\n} from \"#redirect/core/redirects/model/status-code\";\nimport {\n normalizeRedirectSourcePath,\n normalizeRelativeRedirectPath,\n} from \"#redirect/core/redirects/normalize-path\";\nimport { findRedirectByFrom } from \"#redirect/core/redirects/queries\";\n\n/** Enabled rules followed from `to` before a write is refused as unverifiable. Bounds the lookups per write. */\nexport const MAX_REDIRECT_CHAIN_HOPS = 1000;\n\nconst DUPLICATE_MESSAGE = \"A redirect rule already exists for this source path\";\nconst LOOP_MESSAGE =\n \"Enabled redirect rules already lead from this destination back to this source path\";\nconst CHAIN_LOOP_MESSAGE = \"Enabled redirect rules from this destination already contain a loop\";\nconst CHAIN_TOO_LONG_MESSAGE = `Enabled redirect rules from this destination chain longer than ${MAX_REDIRECT_CHAIN_HOPS} hops`;\n\nconst normalizeOrUndefined = (raw: unknown): string | undefined => {\n if (typeof raw !== \"string\" || raw.trim().length === 0) return undefined;\n try {\n return normalizeRelativeRedirectPath(raw).split(\"#\", 1)[0];\n } catch {\n return undefined;\n }\n};\n\nexport const resolveNormalizedFrom = (data: Record<string, unknown>): string | undefined => {\n if (typeof data.from !== \"string\" || data.from.trim().length === 0) return undefined;\n try {\n return normalizeRedirectSourcePath(data.from);\n } catch {\n return undefined;\n }\n};\n\nexport const findDuplicateFrom = async ({\n req,\n collectionSlug,\n normalizedFrom,\n excludeId,\n}: {\n req: PayloadRequest;\n collectionSlug: string;\n normalizedFrom: string;\n excludeId?: string | number;\n}): Promise<boolean> => {\n // Integrity lookup: it must see every rule, whatever the requester can read. It returns only a boolean.\n const result = await findRedirectByFrom(req.payload, {\n collectionSlug,\n from: normalizedFrom,\n excludeId,\n req,\n overrideAccess: true,\n select: { id: true },\n });\n\n return result.docs.length > 0;\n};\n\ntype HookOperationArgs = {\n data: Record<string, unknown> | undefined;\n req: PayloadRequest;\n operation: string;\n originalDoc?: { id?: string | number } | null;\n};\n\n/** Payload collection `beforeChange` passes `originalDoc`, not top-level `id` (see Payload 3 update op). */\nexport const resolveDuplicateGuardExcludeId = (\n operation: string,\n originalDoc?: { id?: string | number } | null,\n): string | number | undefined => {\n if (operation !== \"update\" || !originalDoc) return undefined;\n const { id } = originalDoc;\n if (typeof id === \"string\" || typeof id === \"number\") return id;\n return undefined;\n};\n\nconst resolveExcludeId = (args: HookOperationArgs): string | number | undefined =>\n resolveDuplicateGuardExcludeId(args.operation, args.originalDoc);\n\n/**\n * Rejects a write whose enabled chain from `to` returns to `from`, of any length. A chain that\n * repeats a hop without reaching `from` predates this write, so it is accepted. Runs past\n * MAX_REDIRECT_CHAIN_HOPS are refused as unverifiable. One indexed lookup on `from` per hop.\n */\nconst assertNoLoop = async (\n args: HookOperationArgs,\n normalizedFrom: string,\n collectionSlug: string,\n): Promise<void> => {\n const { data, req } = args;\n if (!data || data.enabled === false) return;\n\n const normalizedTo = normalizeOrUndefined(data.to);\n if (!normalizedTo) return;\n if (normalizedTo === normalizedFrom) {\n throw new ValidationError({ errors: [{ message: LOOP_MESSAGE, path: \"to\" }] });\n }\n\n const excludeId = resolveExcludeId(args);\n const visited = new Set<string>();\n let current = normalizedTo;\n for (let hop = 0; hop <= MAX_REDIRECT_CHAIN_HOPS; hop++) {\n if (visited.has(current)) {\n throw new ValidationError({ errors: [{ message: CHAIN_LOOP_MESSAGE, path: \"to\" }] });\n }\n visited.add(current);\n // Integrity lookup: a requester without read access must not hide a rule from the cycle walk.\n const { docs } = await findRedirectByFrom(req.payload, {\n collectionSlug,\n from: current,\n excludeId,\n req,\n overrideAccess: true,\n });\n\n const rule = docs[0];\n if (!rule?.enabled) return;\n const next = normalizeOrUndefined(rule.to);\n if (!next) return;\n if (next === normalizedFrom) {\n throw new ValidationError({ errors: [{ message: LOOP_MESSAGE, path: \"to\" }] });\n }\n current = next;\n }\n\n throw new ValidationError({ errors: [{ message: CHAIN_TOO_LONG_MESSAGE, path: \"to\" }] });\n};\n\nconst assertNoDuplicateFrom = async (\n args: HookOperationArgs,\n collectionSlug: string,\n): Promise<string | undefined> => {\n const { data, req } = args;\n if (!data) return undefined;\n\n const normalizedFrom = resolveNormalizedFrom(data);\n if (!normalizedFrom) return undefined;\n\n const duplicate = await findDuplicateFrom({\n req,\n collectionSlug,\n normalizedFrom,\n excludeId: resolveExcludeId(args),\n });\n\n if (duplicate) {\n throw new ValidationError({ errors: [{ message: DUPLICATE_MESSAGE, path: \"from\" }] });\n }\n\n await assertNoLoop(args, normalizedFrom, collectionSlug);\n\n return normalizedFrom;\n};\n\nconst normalizeRulePaths = (data: Record<string, unknown>): void => {\n const normalize = (value: unknown, path: \"from\" | \"to\"): string => {\n if (typeof value !== \"string\") {\n throw new ValidationError({ errors: [{ message: `${path} is required`, path }] });\n }\n try {\n return normalizeRelativeRedirectPath(value);\n } catch (error) {\n const message = error instanceof Error ? error.message : `Invalid ${path} path`;\n throw new ValidationError({ errors: [{ message, path }] });\n }\n };\n\n if (typeof data.from !== \"string\") {\n throw new ValidationError({ errors: [{ message: \"from is required\", path: \"from\" }] });\n }\n try {\n data.from = normalizeRedirectSourcePath(data.from);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Invalid from path\";\n throw new ValidationError({ errors: [{ message, path: \"from\" }] });\n }\n data.to = normalize(data.to, \"to\");\n\n try {\n const statusCode = assertRedirectStatusCode(data.statusCode ?? DEFAULT_REDIRECT_STATUS_CODE);\n validateDestinationForStatus(statusCode, data.to);\n } catch (error) {\n const message =\n error instanceof Error ? error.message : \"Invalid redirect status or destination\";\n throw new ValidationError({ errors: [{ message, path: \"to\" }] });\n }\n};\n\n/**\n * The rule as it will be stored: on update, the stored document overlaid with the incoming change.\n * Payload passes only the incoming fields to beforeChange, so checking `data` alone would skip the\n * loop walk for any update that omits `from` or `to`.\n */\nexport const effectiveRuleData = (\n operation: string,\n data: Record<string, unknown> | undefined,\n originalDoc: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | undefined => {\n if (!data) return undefined;\n if (operation !== \"update\" || !originalDoc) return data;\n return { ...originalDoc, ...data };\n};\n\nexport const createDuplicateBeforeChange = (\n collectionSlug = \"redirects\",\n): CollectionBeforeChangeHook => {\n return async (args) => {\n const { data, req, operation, originalDoc } = args;\n if (operation === \"create\" || operation === \"update\") {\n await lockRedirectRuleGraph(req);\n }\n const effective = effectiveRuleData(\n operation,\n data as Record<string, unknown> | undefined,\n originalDoc as Record<string, unknown> | null | undefined,\n );\n if (effective && (operation === \"create\" || operation === \"update\")) {\n normalizeRulePaths(effective);\n if (data) {\n if (typeof data.from === \"string\") data.from = effective.from;\n if (typeof data.to === \"string\") data.to = effective.to;\n }\n }\n const normalizedFrom = await assertNoDuplicateFrom(\n {\n data: effective,\n req,\n operation,\n originalDoc: args.originalDoc,\n },\n collectionSlug,\n );\n\n if (data && normalizedFrom && typeof data.from === \"string\") {\n data.from = normalizedFrom;\n }\n\n return data;\n };\n};\n"]}
1
+ {"version":3,"file":"duplicate-guard.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/duplicate-guard.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAC1C,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,4BAA4B,GAC7B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,2BAA2B,EAC3B,6BAA6B,GAC9B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AAEtE,gHAAgH;AAChH,MAAM,CAAC,MAAM,uBAAuB,GAAG,IAAI,CAAC;AAE5C,MAAM,iBAAiB,GAAG,qDAAqD,CAAC;AAChF,MAAM,YAAY,GAChB,oFAAoF,CAAC;AACvF,MAAM,kBAAkB,GAAG,qEAAqE,CAAC;AACjG,MAAM,sBAAsB,GAAG,kEAAkE,uBAAuB,OAAO,CAAC;AAEhI,MAAM,oBAAoB,GAAG,CAAC,GAAY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W,EAAE,GAAG,IAAI,EAAE,CAAC;AACrC,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,2BAA2B,GAAG,CACzC,cAAc,GAAG,WAAW,EACA,EAAE;IAC9B,OAAO,KAAK,EAAE,IAAI,EAAE,EAAE;QACpB,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;QACnD,MAAM,SAAS,GAAG,iBAAiB,CACjC,SAAS,EACT,IAA2C,EAC3C,WAAyD,CAC1D,CAAC;QACF,IAAI,SAAS,IAAI,CAAC,SAAS,KAAK,QAAQ,IAAI,SAAS,KAAK,QAAQ,CAAC,EAAE,CAAC;YACpE,kBAAkB,CAAC,SAAS,CAAC,CAAC;YAC9B,IAAI,IAAI,EAAE,CAAC;gBACT,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ;oBAAE,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC;gBAC9D,IAAI,OAAO,IAAI,CAAC,EAAE,KAAK,QAAQ;oBAAE,IAAI,CAAC,EAAE,GAAG,SAAS,CAAC,EAAE,CAAC;YAC1D,CAAC;QACH,CAAC;QACD,MAAM,cAAc,GAAG,MAAM,qBAAqB,CAChD;YACE,IAAI,EAAE,SAAS;YACf,GAAG;YACH,SAAS;YACT,WAAW,EAAE,IAAI,CAAC,WAAW;SAC9B,EACD,cAAc,CACf,CAAC;QAEF,IAAI,IAAI,IAAI,cAAc,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC5D,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;QAC7B,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import type { CollectionBeforeChangeHook, PayloadRequest } from \"payload\";\nimport { ValidationError } from \"payload\";\nimport {\n assertRedirectStatusCode,\n DEFAULT_REDIRECT_STATUS_CODE,\n validateDestinationForStatus,\n} from \"#redirect/core/redirects/model/status-code\";\nimport {\n normalizeRedirectSourcePath,\n normalizeRelativeRedirectPath,\n} from \"#redirect/core/redirects/normalize-path\";\nimport { findRedirectByFrom } from \"#redirect/core/redirects/queries\";\n\n/** Enabled rules followed from `to` before a write is refused as unverifiable. Bounds the lookups per write. */\nexport const MAX_REDIRECT_CHAIN_HOPS = 1000;\n\nconst DUPLICATE_MESSAGE = \"A redirect rule already exists for this source path\";\nconst LOOP_MESSAGE =\n \"Enabled redirect rules already lead from this destination back to this source path\";\nconst CHAIN_LOOP_MESSAGE = \"Enabled redirect rules from this destination already contain a loop\";\nconst CHAIN_TOO_LONG_MESSAGE = `Enabled redirect rules from this destination chain longer than ${MAX_REDIRECT_CHAIN_HOPS} hops`;\n\nconst normalizeOrUndefined = (raw: unknown): string | undefined => {\n if (typeof raw !== \"string\" || raw.trim().length === 0) return undefined;\n try {\n return normalizeRelativeRedirectPath(raw).split(\"#\", 1)[0];\n } catch {\n return undefined;\n }\n};\n\nexport const resolveNormalizedFrom = (data: Record<string, unknown>): string | undefined => {\n if (typeof data.from !== \"string\" || data.from.trim().length === 0) return undefined;\n try {\n return normalizeRedirectSourcePath(data.from);\n } catch {\n return undefined;\n }\n};\n\nexport const findDuplicateFrom = async ({\n req,\n collectionSlug,\n normalizedFrom,\n excludeId,\n}: {\n req: PayloadRequest;\n collectionSlug: string;\n normalizedFrom: string;\n excludeId?: string | number;\n}): Promise<boolean> => {\n // Integrity lookup: it must see every rule, whatever the requester can read. It returns only a boolean.\n const result = await findRedirectByFrom(req.payload, {\n collectionSlug,\n from: normalizedFrom,\n excludeId,\n req,\n overrideAccess: true,\n select: { id: true },\n });\n\n return result.docs.length > 0;\n};\n\ntype HookOperationArgs = {\n data: Record<string, unknown> | undefined;\n req: PayloadRequest;\n operation: string;\n originalDoc?: { id?: string | number } | null;\n};\n\n/** Payload collection `beforeChange` passes `originalDoc`, not top-level `id` (see Payload 3 update op). */\nexport const resolveDuplicateGuardExcludeId = (\n operation: string,\n originalDoc?: { id?: string | number } | null,\n): string | number | undefined => {\n if (operation !== \"update\" || !originalDoc) return undefined;\n const { id } = originalDoc;\n if (typeof id === \"string\" || typeof id === \"number\") return id;\n return undefined;\n};\n\nconst resolveExcludeId = (args: HookOperationArgs): string | number | undefined =>\n resolveDuplicateGuardExcludeId(args.operation, args.originalDoc);\n\n/**\n * Rejects a write whose enabled chain from `to` returns to `from`, of any length. A chain that\n * repeats a hop without reaching `from` predates this write, so it is accepted. Runs past\n * MAX_REDIRECT_CHAIN_HOPS are refused as unverifiable. One indexed lookup on `from` per hop.\n */\nconst assertNoLoop = async (\n args: HookOperationArgs,\n normalizedFrom: string,\n collectionSlug: string,\n): Promise<void> => {\n const { data, req } = args;\n if (!data || data.enabled === false) return;\n\n const normalizedTo = normalizeOrUndefined(data.to);\n if (!normalizedTo) return;\n if (normalizedTo === normalizedFrom) {\n throw new ValidationError({ errors: [{ message: LOOP_MESSAGE, path: \"to\" }] });\n }\n\n const excludeId = resolveExcludeId(args);\n const visited = new Set<string>();\n let current = normalizedTo;\n for (let hop = 0; hop <= MAX_REDIRECT_CHAIN_HOPS; hop++) {\n if (visited.has(current)) {\n throw new ValidationError({ errors: [{ message: CHAIN_LOOP_MESSAGE, path: \"to\" }] });\n }\n visited.add(current);\n // Integrity lookup: a requester without read access must not hide a rule from the cycle walk.\n const { docs } = await findRedirectByFrom(req.payload, {\n collectionSlug,\n from: current,\n excludeId,\n req,\n overrideAccess: true,\n });\n\n const rule = docs[0];\n if (!rule?.enabled) return;\n const next = normalizeOrUndefined(rule.to);\n if (!next) return;\n if (next === normalizedFrom) {\n throw new ValidationError({ errors: [{ message: LOOP_MESSAGE, path: \"to\" }] });\n }\n current = next;\n }\n\n throw new ValidationError({ errors: [{ message: CHAIN_TOO_LONG_MESSAGE, path: \"to\" }] });\n};\n\nconst assertNoDuplicateFrom = async (\n args: HookOperationArgs,\n collectionSlug: string,\n): Promise<string | undefined> => {\n const { data, req } = args;\n if (!data) return undefined;\n\n const normalizedFrom = resolveNormalizedFrom(data);\n if (!normalizedFrom) return undefined;\n\n const duplicate = await findDuplicateFrom({\n req,\n collectionSlug,\n normalizedFrom,\n excludeId: resolveExcludeId(args),\n });\n\n if (duplicate) {\n throw new ValidationError({ errors: [{ message: DUPLICATE_MESSAGE, path: \"from\" }] });\n }\n\n await assertNoLoop(args, normalizedFrom, collectionSlug);\n\n return normalizedFrom;\n};\n\nconst normalizeRulePaths = (data: Record<string, unknown>): void => {\n const normalize = (value: unknown, path: \"from\" | \"to\"): string => {\n if (typeof value !== \"string\") {\n throw new ValidationError({ errors: [{ message: `${path} is required`, path }] });\n }\n try {\n return normalizeRelativeRedirectPath(value);\n } catch (error) {\n const message = error instanceof Error ? error.message : `Invalid ${path} path`;\n throw new ValidationError({ errors: [{ message, path }] });\n }\n };\n\n if (typeof data.from !== \"string\") {\n throw new ValidationError({ errors: [{ message: \"from is required\", path: \"from\" }] });\n }\n try {\n data.from = normalizeRedirectSourcePath(data.from);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Invalid from path\";\n throw new ValidationError({ errors: [{ message, path: \"from\" }] });\n }\n data.to = normalize(data.to, \"to\");\n\n try {\n const statusCode = assertRedirectStatusCode(data.statusCode ?? DEFAULT_REDIRECT_STATUS_CODE);\n validateDestinationForStatus(statusCode, data.to);\n } catch (error) {\n const message =\n error instanceof Error ? error.message : \"Invalid redirect status or destination\";\n throw new ValidationError({ errors: [{ message, path: \"to\" }] });\n }\n};\n\n/**\n * The rule as it will be stored: on update, the stored document overlaid with the incoming change.\n * Payload passes only the incoming fields to beforeChange, so checking `data` alone would skip the\n * loop walk for any update that omits `from` or `to`.\n */\nexport const effectiveRuleData = (\n operation: string,\n data: Record<string, unknown> | undefined,\n originalDoc: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | undefined => {\n if (!data) return undefined;\n if (operation !== \"update\" || !originalDoc) return data;\n return { ...originalDoc, ...data };\n};\n\nexport const createDuplicateBeforeChange = (\n collectionSlug = \"redirects\",\n): CollectionBeforeChangeHook => {\n return async (args) => {\n const { data, req, operation, originalDoc } = args;\n const effective = effectiveRuleData(\n operation,\n data as Record<string, unknown> | undefined,\n originalDoc as Record<string, unknown> | null | undefined,\n );\n if (effective && (operation === \"create\" || operation === \"update\")) {\n normalizeRulePaths(effective);\n if (data) {\n if (typeof data.from === \"string\") data.from = effective.from;\n if (typeof data.to === \"string\") data.to = effective.to;\n }\n }\n const normalizedFrom = await assertNoDuplicateFrom(\n {\n data: effective,\n req,\n operation,\n originalDoc: args.originalDoc,\n },\n collectionSlug,\n );\n\n if (data && normalizedFrom && typeof data.from === \"string\") {\n data.from = normalizedFrom;\n }\n\n return data;\n };\n};\n"]}
@@ -1,2 +1,7 @@
1
- import type { PayloadRequest } from "payload";
1
+ import type { CollectionBeforeOperationHook, PayloadRequest } from "payload";
2
2
  export declare function lockRedirectRuleGraph(req: PayloadRequest): Promise<void>;
3
+ /**
4
+ * Takes the graph lock in `beforeOperation`, before Payload reads `originalDoc` and before any ownership
5
+ * or graph decision. A lock taken in `beforeChange` would let a stale `originalDoc` drive the loop walk.
6
+ */
7
+ export declare const createRedirectGraphLockBeforeOperation: () => CollectionBeforeOperationHook;
@@ -29,4 +29,15 @@ export async function lockRedirectRuleGraph(req) {
29
29
  throw new Error("Redirect rule lock requires READ COMMITTED transactions.");
30
30
  }
31
31
  }
32
+ /**
33
+ * Takes the graph lock in `beforeOperation`, before Payload reads `originalDoc` and before any ownership
34
+ * or graph decision. A lock taken in `beforeChange` would let a stale `originalDoc` drive the loop walk.
35
+ */
36
+ export const createRedirectGraphLockBeforeOperation = () => {
37
+ return async ({ operation, req }) => {
38
+ if (operation === "create" || operation === "update") {
39
+ await lockRedirectRuleGraph(req);
40
+ }
41
+ };
42
+ };
32
43
  //# sourceMappingURL=graph-lock.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"graph-lock.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/graph-lock.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AACH,MAAM,QAAQ,GAAG,6BAA6B,CAAC;AAC/C,MAAM,wBAAwB,GAAG,UAAU,CAAC;AAW5C,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,GAAmB;IAC7D,MAAM,EAAE,GAAG,GAAG,CAAC,OAAO,EAAE,EAA2C,CAAC;IACpE,gFAAgF;IAChF,IAAI,EAAE,IAAI,IAAI;QAAE,OAAO;IACvB,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,EAAE,CAAC,WAAW,IAAI,EAAE,CAAC;QAAE,OAAO;IAEjE,MAAM,aAAa,GAAG,MAAM,GAAG,CAAC,aAAa,CAAC;IAC9C,MAAM,OAAO,GAAG,aAAa,IAAI,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC;IACzF,MAAM,EAAE,GAAG,OAAO,EAAE,EAAsC,CAAC;IAC3D,IAAI,EAAE,IAAI,IAAI,IAAI,OAAO,EAAE,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACnD,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;IAC5F,CAAC;IAED,oEAAoE;IACpE,MAAM,EAAE,CAAC,OAAO,CAAC,0CAA0C,QAAQ,KAAK,CAAC,CAAC;IAE1E,MAAM,SAAS,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,4BAA4B,CAAC,CAAC;IACjE,IAAI,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,qBAAqB,KAAK,gBAAgB,EAAE,CAAC;QAClE,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;AACH,CAAC","sourcesContent":["import type { PayloadRequest } from \"payload\";\n\n/**\n * Serializes writes to the redirect rule graph. The loop and duplicate checks read committed rows,\n * so two concurrent writes that each close a cycle could both pass unless the second waits for the\n * first to commit. The lock is transaction-scoped and released at commit or rollback.\n *\n * Postgres is the supported adapter: the lock needs the request transaction and READ COMMITTED\n * isolation, and the function throws when either is missing rather than checking without it.\n * Adapters without advisory locks return without locking.\n */\nconst LOCK_KEY = \"payload-redirect:rule-graph\";\nconst POSTGRES_ADAPTER_PATTERN = /postgres/;\n\ntype TransactionQueryable = {\n execute: (query: string) => Promise<{ rows: Array<Record<string, unknown>> }>;\n};\n\ntype DbWithSessions = {\n packageName?: string;\n sessions?: Record<string, { db?: unknown } | undefined>;\n};\n\nexport async function lockRedirectRuleGraph(req: PayloadRequest): Promise<void> {\n const db = req.payload?.db as unknown as DbWithSessions | undefined;\n // No database adapter means there is no transaction graph to serialize against.\n if (db == null) return;\n if (!POSTGRES_ADAPTER_PATTERN.test(db.packageName ?? \"\")) return;\n\n const transactionID = await req.transactionID;\n const session = transactionID == null ? undefined : db.sessions?.[String(transactionID)];\n const tx = session?.db as TransactionQueryable | undefined;\n if (tx == null || typeof tx.execute !== \"function\") {\n throw new Error(\"Redirect rule lock needs the request transaction; refusing without it.\");\n }\n\n // LOCK_KEY is a constant, so inlining it into the SQL text is safe.\n await tx.execute(`select pg_advisory_xact_lock(hashtext('${LOCK_KEY}'))`);\n\n const isolation = await tx.execute(\"show transaction_isolation\");\n if (isolation.rows[0]?.transaction_isolation !== \"read committed\") {\n throw new Error(\"Redirect rule lock requires READ COMMITTED transactions.\");\n }\n}\n"]}
1
+ {"version":3,"file":"graph-lock.js","sourceRoot":"","sources":["../../../../src/core/redirects/collection/graph-lock.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AACH,MAAM,QAAQ,GAAG,6BAA6B,CAAC;AAC/C,MAAM,wBAAwB,GAAG,UAAU,CAAC;AAW5C,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,GAAmB;IAC7D,MAAM,EAAE,GAAG,GAAG,CAAC,OAAO,EAAE,EAA2C,CAAC;IACpE,gFAAgF;IAChF,IAAI,EAAE,IAAI,IAAI;QAAE,OAAO;IACvB,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,EAAE,CAAC,WAAW,IAAI,EAAE,CAAC;QAAE,OAAO;IAEjE,MAAM,aAAa,GAAG,MAAM,GAAG,CAAC,aAAa,CAAC;IAC9C,MAAM,OAAO,GAAG,aAAa,IAAI,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC;IACzF,MAAM,EAAE,GAAG,OAAO,EAAE,EAAsC,CAAC;IAC3D,IAAI,EAAE,IAAI,IAAI,IAAI,OAAO,EAAE,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACnD,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;IAC5F,CAAC;IAED,oEAAoE;IACpE,MAAM,EAAE,CAAC,OAAO,CAAC,0CAA0C,QAAQ,KAAK,CAAC,CAAC;IAE1E,MAAM,SAAS,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,4BAA4B,CAAC,CAAC;IACjE,IAAI,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,qBAAqB,KAAK,gBAAgB,EAAE,CAAC;QAClE,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,sCAAsC,GAAG,GAAkC,EAAE;IACxF,OAAO,KAAK,EAAE,EAAE,SAAS,EAAE,GAAG,EAAE,EAAE,EAAE;QAClC,IAAI,SAAS,KAAK,QAAQ,IAAI,SAAS,KAAK,QAAQ,EAAE,CAAC;YACrD,MAAM,qBAAqB,CAAC,GAAG,CAAC,CAAC;QACnC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import type { CollectionBeforeOperationHook, PayloadRequest } from \"payload\";\n\n/**\n * Serializes writes to the redirect rule graph. The loop and duplicate checks read committed rows,\n * so two concurrent writes that each close a cycle could both pass unless the second waits for the\n * first to commit. The lock is transaction-scoped and released at commit or rollback.\n *\n * Postgres is the supported adapter: the lock needs the request transaction and READ COMMITTED\n * isolation, and the function throws when either is missing rather than checking without it.\n * Adapters without advisory locks return without locking.\n */\nconst LOCK_KEY = \"payload-redirect:rule-graph\";\nconst POSTGRES_ADAPTER_PATTERN = /postgres/;\n\ntype TransactionQueryable = {\n execute: (query: string) => Promise<{ rows: Array<Record<string, unknown>> }>;\n};\n\ntype DbWithSessions = {\n packageName?: string;\n sessions?: Record<string, { db?: unknown } | undefined>;\n};\n\nexport async function lockRedirectRuleGraph(req: PayloadRequest): Promise<void> {\n const db = req.payload?.db as unknown as DbWithSessions | undefined;\n // No database adapter means there is no transaction graph to serialize against.\n if (db == null) return;\n if (!POSTGRES_ADAPTER_PATTERN.test(db.packageName ?? \"\")) return;\n\n const transactionID = await req.transactionID;\n const session = transactionID == null ? undefined : db.sessions?.[String(transactionID)];\n const tx = session?.db as TransactionQueryable | undefined;\n if (tx == null || typeof tx.execute !== \"function\") {\n throw new Error(\"Redirect rule lock needs the request transaction; refusing without it.\");\n }\n\n // LOCK_KEY is a constant, so inlining it into the SQL text is safe.\n await tx.execute(`select pg_advisory_xact_lock(hashtext('${LOCK_KEY}'))`);\n\n const isolation = await tx.execute(\"show transaction_isolation\");\n if (isolation.rows[0]?.transaction_isolation !== \"read committed\") {\n throw new Error(\"Redirect rule lock requires READ COMMITTED transactions.\");\n }\n}\n\n/**\n * Takes the graph lock in `beforeOperation`, before Payload reads `originalDoc` and before any ownership\n * or graph decision. A lock taken in `beforeChange` would let a stale `originalDoc` drive the loop walk.\n */\nexport const createRedirectGraphLockBeforeOperation = (): CollectionBeforeOperationHook => {\n return async ({ operation, req }) => {\n if (operation === \"create\" || operation === \"update\") {\n await lockRedirectRuleGraph(req);\n }\n };\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@klnap/payload-redirect",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Redirect management for Payload CMS.",
5
5
  "homepage": "https://github.com/klnap/payload-redirect#readme",
6
6
  "bugs": {