payload-nested-docs-page-tree 1.4.4 → 1.5.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 (32) hide show
  1. package/README.md +169 -257
  2. package/dist/components/PageTreeListView.client.d.ts +3 -2
  3. package/dist/components/PageTreeListView.client.js +11 -31
  4. package/dist/components/PageTreeListView.client.js.map +1 -1
  5. package/dist/components/PageTreeListView.module.css +63 -0
  6. package/dist/components/PageTreeListView.server.js +62 -15
  7. package/dist/components/PageTreeListView.server.js.map +1 -1
  8. package/dist/components/PageTreeStatusBadge.d.ts +6 -0
  9. package/dist/components/PageTreeStatusBadge.js +77 -0
  10. package/dist/components/PageTreeStatusBadge.js.map +1 -0
  11. package/dist/components/PageTreeTitleCell.js +3 -2
  12. package/dist/components/PageTreeTitleCell.js.map +1 -1
  13. package/dist/endpoints/createMovePageEndpoint.js +13 -14
  14. package/dist/endpoints/createMovePageEndpoint.js.map +1 -1
  15. package/dist/endpoints/createReorderPageEndpoint.js +3 -4
  16. package/dist/endpoints/createReorderPageEndpoint.js.map +1 -1
  17. package/dist/endpoints/shared.d.ts +1 -14
  18. package/dist/endpoints/shared.js +3 -6
  19. package/dist/endpoints/shared.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +3 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/types.d.ts +15 -1
  24. package/dist/types.js.map +1 -1
  25. package/dist/utilities/badgeLinks.d.ts +29 -0
  26. package/dist/utilities/badgeLinks.js +47 -0
  27. package/dist/utilities/badgeLinks.js.map +1 -0
  28. package/dist/utilities/diagnostics.js +1 -1
  29. package/dist/utilities/diagnostics.js.map +1 -1
  30. package/dist/utilities/pageTreeConfig.js +1 -0
  31. package/dist/utilities/pageTreeConfig.js.map +1 -1
  32. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/endpoints/createMovePageEndpoint.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest } from 'payload'\n\nimport {\n DIAGNOSTICS_FLOW_CONTEXT_KEY,\n type Diagnostics,\n createFlowID,\n readMainRowSnapshot,\n} from '../utilities/diagnostics.js'\nimport { CANCEL_DRAG_MESSAGE } from '../utilities/moveValidation.js'\nimport {\n buildChildrenByParentID,\n collectDescendantIDs,\n getDocParentID,\n stringifyDocID,\n} from '../utilities/pageTree.js'\nimport {\n pageTreeMoveContextKey,\n type PageTreeSourceDoc,\n pageTreeWriteContextKey,\n} from '../types.js'\nimport {\n assertUpdateAccess,\n collectionHasAutosaveDrafts,\n collectionHasDrafts,\n getRequestedLocale,\n normalizeID,\n respond,\n toCollectionID,\n} from './shared.js'\n\nconst SNAPSHOT_FIELDS = ['_status'] as const\n\ntype MoveDocumentRequestBody = {\n parentID: null | string\n}\n\nfunction hasOwnProperty(value: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(value, key)\n}\n\nfunction normalizeMoveDocumentBody(value: unknown): MoveDocumentRequestBody | null {\n const incomingData =\n typeof value === 'string'\n ? (() => {\n try {\n return JSON.parse(value) as unknown\n } catch {\n return null\n }\n })()\n : value\n\n if (!incomingData || typeof incomingData !== 'object' || Array.isArray(incomingData)) {\n return null\n }\n\n if (!hasOwnProperty(incomingData, 'parentID')) {\n return null\n }\n\n const parentID = normalizeID((incomingData as { parentID?: unknown }).parentID)\n\n if (\n (incomingData as { parentID?: unknown }).parentID !== null &&\n (incomingData as { parentID?: unknown }).parentID !== undefined &&\n parentID === null\n ) {\n return null\n }\n\n return {\n parentID,\n }\n}\n\ntype RawBodyAttempt = {\n raw: unknown\n source: 'req.data' | 'req.json' | 'req.text'\n}\n\nasync function readBodyFromRequest(\n req: PayloadRequest,\n): Promise<{ body: MoveDocumentRequestBody | null; lastAttempt: null | RawBodyAttempt }> {\n let lastAttempt: null | RawBodyAttempt = null\n\n if (req.data !== undefined && req.data !== null) {\n lastAttempt = { raw: req.data, source: 'req.data' }\n const directBody = normalizeMoveDocumentBody(req.data)\n\n if (directBody) {\n return { body: directBody, lastAttempt }\n }\n }\n\n if (typeof req.json === 'function') {\n try {\n const raw = await req.json()\n lastAttempt = { raw, source: 'req.json' }\n const jsonBody = normalizeMoveDocumentBody(raw)\n\n if (jsonBody) {\n return { body: jsonBody, lastAttempt }\n }\n } catch {\n // Fall through to the text-based fallback when the runtime does not hydrate req.data.\n }\n }\n\n if (typeof req.text === 'function') {\n try {\n const raw = await req.text()\n lastAttempt = { raw, source: 'req.text' }\n const textBody = normalizeMoveDocumentBody(raw)\n\n if (textBody) {\n return { body: textBody, lastAttempt }\n }\n } catch {\n return { body: null, lastAttempt }\n }\n }\n\n return { body: null, lastAttempt }\n}\n\nexport function createMovePageEndpoint(args: {\n collectionSlug: string\n diagnostics: Diagnostics\n parentFieldSlug: string\n publishOnMove?: boolean\n}): Endpoint {\n const { collectionSlug, diagnostics, parentFieldSlug, publishOnMove = false } = args\n const snapshotFields = [...SNAPSHOT_FIELDS, parentFieldSlug]\n\n return {\n handler: async (req) => {\n const movedIDFromRoute = normalizeID(req.routeParams?.id)\n\n if (!movedIDFromRoute) {\n return respond(400, {\n message: 'Document ID was not specified.',\n })\n }\n\n const { body, lastAttempt } = await readBodyFromRequest(req)\n\n if (!body) {\n if (diagnostics.enabled) {\n diagnostics.log({\n collection: collectionSlug,\n data: {\n movedID: movedIDFromRoute,\n rawBody: lastAttempt?.raw ?? null,\n rawBodySource: lastAttempt?.source ?? null,\n },\n flow: createFlowID('move-endpoint'),\n level: 'warn',\n message: 'move endpoint rejected request body: parentID was missing or malformed',\n source: 'move-endpoint:body-rejected',\n })\n }\n\n return respond(400, {\n message: 'A valid parentID is required.',\n })\n }\n\n const movedID = toCollectionID({\n collectionSlug,\n id: movedIDFromRoute,\n req,\n })\n const nextParentID =\n body.parentID === null\n ? null\n : toCollectionID({\n collectionSlug,\n id: body.parentID,\n req,\n })\n const accessError = await assertUpdateAccess({\n collectionSlug,\n data: { [parentFieldSlug]: nextParentID },\n id: movedID,\n req,\n })\n\n if (accessError) {\n return accessError\n }\n\n const docsResult = await req.payload.find({\n collection: collectionSlug as never,\n depth: 0,\n draft: collectionHasDrafts({ collectionSlug, req }) ? true : undefined,\n fallbackLocale: false as never,\n limit: 0,\n locale: getRequestedLocale(req) as never,\n overrideAccess: true,\n req,\n } as never)\n const docs = docsResult.docs as unknown as PageTreeSourceDoc[]\n const docsByID = new Map(docs.map((doc) => [stringifyDocID(doc.id), doc]))\n const movedDoc = docsByID.get(movedIDFromRoute)\n\n if (!movedDoc) {\n return respond(404, {\n message: 'Document not found.',\n })\n }\n\n if (body.parentID !== null && !docsByID.has(body.parentID)) {\n return respond(400, {\n message: 'Parent document not found.',\n })\n }\n\n const currentParentID = getDocParentID(movedDoc, parentFieldSlug)\n\n if (currentParentID === body.parentID) {\n return respond(400, {\n message: 'Document already has that parent.',\n })\n }\n\n if (body.parentID === movedIDFromRoute) {\n return respond(400, {\n message: CANCEL_DRAG_MESSAGE,\n })\n }\n\n const childrenByParentID = buildChildrenByParentID({\n docs,\n parentFieldSlug,\n })\n const descendantIDs = collectDescendantIDs(movedIDFromRoute, childrenByParentID)\n\n if (body.parentID !== null && descendantIDs.includes(body.parentID)) {\n return respond(400, {\n message: 'A document cannot be moved under one of its descendants.',\n })\n }\n\n const flow = createFlowID('move-endpoint')\n const moveStart = Date.now()\n const hasDrafts = collectionHasDrafts({ collectionSlug, req })\n const hasAutosave = hasDrafts && collectionHasAutosaveDrafts({ collectionSlug, req })\n // With `publishOnMove`, publish the reparent right away instead of staging\n // it — but ONLY when the moved doc had nothing staged before the move (its\n // latest version, read above with `draft: true`, is already published). A\n // doc with pending draft edits stays staged, so those in-progress edits are\n // never published as a side effect of the move.\n const publishMove = publishOnMove && hasDrafts && movedDoc._status === 'published'\n const updateData = {\n [parentFieldSlug]:\n body.parentID === null\n ? null\n : toCollectionID({\n collectionSlug,\n id: body.parentID,\n req,\n }),\n ...(publishMove ? { _status: 'published' } : {}),\n }\n const updateArgs = {\n collection: collectionSlug as never,\n context: {\n // A published move changes the live URL of this page and of every\n // descendant nested-docs resaves on this request, so the deploy\n // opt-out flag is withheld and consumer rebuild hooks fire normally.\n // A staged move changes nothing live and keeps the flag.\n ...(publishMove ? {} : { [pageTreeMoveContextKey]: true }),\n [pageTreeWriteContextKey]: true,\n } as Record<string, unknown>,\n autosave: hasAutosave && !publishMove ? true : undefined,\n data: updateData as never,\n depth: 0,\n draft: hasDrafts && !publishMove ? true : undefined,\n id: movedID as never,\n locale: getRequestedLocale(req) as never,\n overrideAccess: true,\n req,\n }\n\n if (diagnostics.enabled) {\n if (!req.context) {\n req.context = {}\n }\n\n ;(req.context as Record<string, unknown>)[DIAGNOSTICS_FLOW_CONTEXT_KEY] = flow\n\n const beforeSnapshot = await readMainRowSnapshot({\n collectionSlug,\n fields: snapshotFields,\n id: movedID,\n req,\n })\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n autosave: updateArgs.autosave ?? null,\n currentParentID,\n draft: updateArgs.draft,\n hasTransaction: Boolean((req as { transactionID?: unknown }).transactionID),\n locale: updateArgs.locale ?? null,\n movedDocStatus: movedDoc._status ?? null,\n movedID: String(movedID),\n nextParentID: body.parentID,\n publishedMainRowBefore: beforeSnapshot,\n publishMove,\n updateData,\n },\n flow,\n level: 'info',\n message: 'move endpoint entering: parent move only',\n source: 'move-endpoint:enter',\n })\n }\n\n try {\n const result = (await req.payload.update(updateArgs as never)) as\n | (Record<string, unknown> & { _status?: string })\n | undefined\n\n if (diagnostics.enabled) {\n const afterSnapshot = await readMainRowSnapshot({\n collectionSlug,\n fields: snapshotFields,\n id: movedID,\n req,\n })\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n durMs: Date.now() - moveStart,\n movedID: String(movedID),\n publishedMainRowAfter: afterSnapshot,\n resultStatus: result?._status ?? null,\n },\n flow,\n level: 'info',\n message: 'move endpoint payload.update succeeded',\n source: 'move-endpoint:ok',\n })\n }\n } catch (err) {\n const error = err as { data?: unknown; message?: string; name?: string } & Error\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n data: error?.data ?? null,\n durMs: Date.now() - moveStart,\n message: error?.message,\n movedID: String(movedID),\n name: error?.name,\n },\n flow,\n level: 'error',\n message: `move endpoint payload.update failed: ${error?.message ?? 'unknown error'}`,\n source: 'move-endpoint:error',\n })\n\n throw err\n }\n\n return respond(200, {\n movedID: movedIDFromRoute,\n ok: true,\n parentID: body.parentID,\n })\n },\n method: 'post',\n path: '/:id/move',\n }\n}\n"],"names":["DIAGNOSTICS_FLOW_CONTEXT_KEY","createFlowID","readMainRowSnapshot","CANCEL_DRAG_MESSAGE","buildChildrenByParentID","collectDescendantIDs","getDocParentID","stringifyDocID","pageTreeMoveContextKey","pageTreeWriteContextKey","assertUpdateAccess","collectionHasAutosaveDrafts","collectionHasDrafts","getRequestedLocale","normalizeID","respond","toCollectionID","SNAPSHOT_FIELDS","hasOwnProperty","value","key","Object","prototype","call","normalizeMoveDocumentBody","incomingData","JSON","parse","Array","isArray","parentID","undefined","readBodyFromRequest","req","lastAttempt","data","raw","source","directBody","body","json","jsonBody","text","textBody","createMovePageEndpoint","args","collectionSlug","diagnostics","parentFieldSlug","publishOnMove","snapshotFields","handler","movedIDFromRoute","routeParams","id","message","enabled","log","collection","movedID","rawBody","rawBodySource","flow","level","nextParentID","accessError","docsResult","payload","find","depth","draft","fallbackLocale","limit","locale","overrideAccess","docs","docsByID","Map","map","doc","movedDoc","get","has","currentParentID","childrenByParentID","descendantIDs","includes","moveStart","Date","now","hasDrafts","hasAutosave","publishMove","_status","updateData","updateArgs","context","autosave","beforeSnapshot","fields","hasTransaction","Boolean","transactionID","movedDocStatus","String","publishedMainRowBefore","result","update","afterSnapshot","durMs","publishedMainRowAfter","resultStatus","err","error","name","ok","method","path"],"mappings":"AAEA,SACEA,4BAA4B,EAE5BC,YAAY,EACZC,mBAAmB,QACd,8BAA6B;AACpC,SAASC,mBAAmB,QAAQ,iCAAgC;AACpE,SACEC,uBAAuB,EACvBC,oBAAoB,EACpBC,cAAc,EACd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GAAG,CAAC;oBACdC,YAAYZ;oBACZX,MAAM;wBACJA,MAAM8E,OAAO9E,QAAQ;wBACrB0E,OAAOrB,KAAKC,GAAG,KAAKF;wBACpBhC,SAAS0D,OAAO1D;wBAChBI,SAAS6C,OAAO7C;wBAChBuD,MAAMD,OAAOC;oBACf;oBACApD;oBACAC,OAAO;oBACPR,SAAS,CAAC,qCAAqC,EAAE0D,OAAO1D,WAAW,iBAAiB;oBACpFlB,QAAQ;gBACV;gBAEA,MAAM2E;YACR;YAEA,OAAOjG,QAAQ,KAAK;gBAClB4C,SAASP;gBACT+D,IAAI;gBACJrF,UAAUS,KAAKT,QAAQ;YACzB;QACF;QACAsF,QAAQ;QACRC,MAAM;IACR;AACF"}
1
+ {"version":3,"sources":["../../src/endpoints/createMovePageEndpoint.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest } from 'payload'\n\nimport {\n pageTreeMoveContextKey,\n type PageTreeSourceDoc,\n pageTreeWriteContextKey,\n} from '../types.js'\nimport {\n createFlowID,\n type Diagnostics,\n DIAGNOSTICS_FLOW_CONTEXT_KEY,\n readMainRowSnapshot,\n} from '../utilities/diagnostics.js'\nimport { CANCEL_DRAG_MESSAGE } from '../utilities/moveValidation.js'\nimport {\n buildChildrenByParentID,\n collectDescendantIDs,\n getDocParentID,\n stringifyDocID,\n} from '../utilities/pageTree.js'\nimport {\n assertUpdateAccess,\n collectionHasAutosaveDrafts,\n collectionHasDrafts,\n getRequestedLocale,\n normalizeID,\n respond,\n toCollectionID,\n} from './shared.js'\n\nconst SNAPSHOT_FIELDS = ['_status'] as const\n\ntype MoveDocumentRequestBody = {\n parentID: null | string\n}\n\nfunction hasOwnProperty(value: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(value, key)\n}\n\nfunction normalizeMoveDocumentBody(value: unknown): MoveDocumentRequestBody | null {\n const incomingData =\n typeof value === 'string'\n ? (() => {\n try {\n return JSON.parse(value) as unknown\n } catch {\n return null\n }\n })()\n : value\n\n if (!incomingData || typeof incomingData !== 'object' || Array.isArray(incomingData)) {\n return null\n }\n\n if (!hasOwnProperty(incomingData, 'parentID')) {\n return null\n }\n\n const parentID = normalizeID((incomingData as { parentID?: unknown }).parentID)\n\n if (\n (incomingData as { parentID?: unknown }).parentID !== null &&\n (incomingData as { parentID?: unknown }).parentID !== undefined &&\n parentID === null\n ) {\n return null\n }\n\n return {\n parentID,\n }\n}\n\ntype RawBodyAttempt = {\n raw: unknown\n source: 'req.data' | 'req.json' | 'req.text'\n}\n\nasync function readBodyFromRequest(\n req: PayloadRequest,\n): Promise<{ body: MoveDocumentRequestBody | null; lastAttempt: null | RawBodyAttempt }> {\n let lastAttempt: null | RawBodyAttempt = null\n\n if (req.data !== undefined && req.data !== null) {\n lastAttempt = { raw: req.data, source: 'req.data' }\n const directBody = normalizeMoveDocumentBody(req.data)\n\n if (directBody) {\n return { body: directBody, lastAttempt }\n }\n }\n\n if (typeof req.json === 'function') {\n try {\n const raw = await req.json()\n lastAttempt = { raw, source: 'req.json' }\n const jsonBody = normalizeMoveDocumentBody(raw)\n\n if (jsonBody) {\n return { body: jsonBody, lastAttempt }\n }\n } catch {\n // Fall through to the text-based fallback when the runtime does not hydrate req.data.\n }\n }\n\n if (typeof req.text === 'function') {\n try {\n const raw = await req.text()\n lastAttempt = { raw, source: 'req.text' }\n const textBody = normalizeMoveDocumentBody(raw)\n\n if (textBody) {\n return { body: textBody, lastAttempt }\n }\n } catch {\n return { body: null, lastAttempt }\n }\n }\n\n return { body: null, lastAttempt }\n}\n\nexport function createMovePageEndpoint(args: {\n collectionSlug: string\n diagnostics: Diagnostics\n parentFieldSlug: string\n publishOnMove?: boolean\n}): Endpoint {\n const { collectionSlug, diagnostics, parentFieldSlug, publishOnMove = false } = args\n const snapshotFields = [...SNAPSHOT_FIELDS, parentFieldSlug]\n\n return {\n handler: async (req) => {\n const movedIDFromRoute = normalizeID(req.routeParams?.id)\n\n if (!movedIDFromRoute) {\n return respond(400, {\n message: 'Document ID was not specified.',\n })\n }\n\n const { body, lastAttempt } = await readBodyFromRequest(req)\n\n if (!body) {\n if (diagnostics.enabled) {\n diagnostics.log({\n collection: collectionSlug,\n data: {\n movedID: movedIDFromRoute,\n rawBody: lastAttempt?.raw ?? null,\n rawBodySource: lastAttempt?.source ?? null,\n },\n flow: createFlowID('move-endpoint'),\n level: 'warn',\n message: 'move endpoint rejected request body: parentID was missing or malformed',\n source: 'move-endpoint:body-rejected',\n })\n }\n\n return respond(400, {\n message: 'A valid parentID is required.',\n })\n }\n\n const movedID = toCollectionID({\n id: movedIDFromRoute,\n collectionSlug,\n req,\n })\n const nextParentID =\n body.parentID === null\n ? null\n : toCollectionID({\n id: body.parentID,\n collectionSlug,\n req,\n })\n const accessError = await assertUpdateAccess({\n id: movedID,\n collectionSlug,\n data: { [parentFieldSlug]: nextParentID },\n req,\n })\n\n if (accessError) {\n return accessError\n }\n\n const docsResult = await req.payload.find({\n collection: collectionSlug,\n depth: 0,\n draft: collectionHasDrafts({ collectionSlug, req }) ? true : undefined,\n fallbackLocale: false,\n limit: 0,\n locale: getRequestedLocale(req),\n overrideAccess: true,\n req,\n })\n const docs = docsResult.docs as unknown as PageTreeSourceDoc[]\n const docsByID = new Map(docs.map((doc) => [stringifyDocID(doc.id), doc]))\n const movedDoc = docsByID.get(movedIDFromRoute)\n\n if (!movedDoc) {\n return respond(404, {\n message: 'Document not found.',\n })\n }\n\n if (body.parentID !== null && !docsByID.has(body.parentID)) {\n return respond(400, {\n message: 'Parent document not found.',\n })\n }\n\n const currentParentID = getDocParentID(movedDoc, parentFieldSlug)\n\n if (currentParentID === body.parentID) {\n return respond(400, {\n message: 'Document already has that parent.',\n })\n }\n\n if (body.parentID === movedIDFromRoute) {\n return respond(400, {\n message: CANCEL_DRAG_MESSAGE,\n })\n }\n\n const childrenByParentID = buildChildrenByParentID({\n docs,\n parentFieldSlug,\n })\n const descendantIDs = collectDescendantIDs(movedIDFromRoute, childrenByParentID)\n\n if (body.parentID !== null && descendantIDs.includes(body.parentID)) {\n return respond(400, {\n message: 'A document cannot be moved under one of its descendants.',\n })\n }\n\n const flow = createFlowID('move-endpoint')\n const moveStart = Date.now()\n const hasDrafts = collectionHasDrafts({ collectionSlug, req })\n const hasAutosave = hasDrafts && collectionHasAutosaveDrafts({ collectionSlug, req })\n // With `publishOnMove`, publish the reparent right away instead of staging\n // it - but ONLY when the moved doc had nothing staged before the move (its\n // latest version, read above with `draft: true`, is already published). A\n // doc with pending draft edits stays staged, so those in-progress edits are\n // never published as a side effect of the move.\n const publishMove = publishOnMove && hasDrafts && movedDoc._status === 'published'\n const updateData = {\n [parentFieldSlug]:\n body.parentID === null\n ? null\n : toCollectionID({\n id: body.parentID,\n collectionSlug,\n req,\n }),\n ...(publishMove ? { _status: 'published' } : {}),\n }\n const updateArgs = {\n id: movedID,\n autosave: hasAutosave && !publishMove ? true : undefined,\n collection: collectionSlug,\n context: {\n // A published move changes the live URL of this page and of every\n // descendant nested-docs resaves on this request, so the deploy\n // opt-out flag is withheld and consumer rebuild hooks fire normally.\n // A staged move changes nothing live and keeps the flag.\n ...(publishMove ? {} : { [pageTreeMoveContextKey]: true }),\n [pageTreeWriteContextKey]: true,\n } as Record<string, unknown>,\n data: updateData,\n depth: 0,\n draft: hasDrafts && !publishMove ? true : undefined,\n locale: getRequestedLocale(req),\n overrideAccess: true,\n req,\n }\n\n if (diagnostics.enabled) {\n if (!req.context) {\n req.context = {}\n }\n\n req.context[DIAGNOSTICS_FLOW_CONTEXT_KEY] = flow\n\n const beforeSnapshot = await readMainRowSnapshot({\n id: movedID,\n collectionSlug,\n fields: snapshotFields,\n req,\n })\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n autosave: updateArgs.autosave ?? null,\n currentParentID,\n draft: updateArgs.draft,\n hasTransaction: Boolean((req as { transactionID?: unknown }).transactionID),\n locale: updateArgs.locale ?? null,\n movedDocStatus: movedDoc._status ?? null,\n movedID: String(movedID),\n nextParentID: body.parentID,\n publishedMainRowBefore: beforeSnapshot,\n publishMove,\n updateData,\n },\n flow,\n level: 'info',\n message: 'move endpoint entering: parent move only',\n source: 'move-endpoint:enter',\n })\n }\n\n try {\n const result = (await req.payload.update(updateArgs)) as\n | ({ _status?: string } & Record<string, unknown>)\n | undefined\n\n if (diagnostics.enabled) {\n const afterSnapshot = await readMainRowSnapshot({\n id: movedID,\n collectionSlug,\n fields: snapshotFields,\n req,\n })\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n durMs: Date.now() - moveStart,\n movedID: String(movedID),\n publishedMainRowAfter: afterSnapshot,\n resultStatus: result?._status ?? null,\n },\n flow,\n level: 'info',\n message: 'move endpoint payload.update succeeded',\n source: 'move-endpoint:ok',\n })\n }\n } catch (err) {\n const error = err as { data?: unknown; message?: string; name?: string } & Error\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n name: error?.name,\n data: error?.data ?? null,\n durMs: Date.now() - moveStart,\n message: error?.message,\n movedID: String(movedID),\n },\n flow,\n level: 'error',\n message: `move endpoint payload.update failed: ${error?.message ?? 'unknown error'}`,\n source: 'move-endpoint:error',\n })\n\n throw err\n }\n\n return respond(200, {\n movedID: movedIDFromRoute,\n ok: true,\n parentID: body.parentID,\n })\n },\n method: 'post',\n path: '/:id/move',\n }\n}\n"],"names":["pageTreeMoveContextKey","pageTreeWriteContextKey","createFlowID","DIAGNOSTICS_FLOW_CONTEXT_KEY","readMainRowSnapshot","CANCEL_DRAG_MESSAGE","buildChildrenByParentID","collectDescendantIDs","getDocParentID","stringifyDocID","assertUpdateAccess","collectionHasAutosaveDrafts","collectionHasDrafts","getRequestedLocale","normalizeID","respond","toCollectionID","SNAPSHOT_FIELDS","hasOwnProperty","value","key","Object","prototype","call","normalizeMoveDocumentBody","incomingData","JSON","parse","Array","isArray","parentID","undefined","readBodyFromRequest","req","lastAttempt","data","raw","source","directBody","body","json","jsonBody","text","textBody","createMovePageEndpoint","args","collectionSlug","diagnostics","parentFieldSlug","publishOnMove","snapshotFields","handler","movedIDFromRoute","routeParams","id","message","enabled","log","collection","movedID","rawBody","rawBodySource","flow","level","nextParentID","accessError","docsResult","payload","find","depth","draft","fallbackLocale","limit","locale","overrideAccess","docs","docsByID","Map","map","doc","movedDoc","get","has","currentParentID","childrenByParentID","descendantIDs","includes","moveStart","Date","now","hasDrafts","hasAutosave","publishMove","_status","updateData","updateArgs","autosave","context","beforeSnapshot","fields","hasTransaction","Boolean","transactionID","movedDocStatus","String","publishedMainRowBefore","result","update","afterSnapshot","durMs","publishedMainRowAfter","resultStatus","err","error","name","ok","method","path"],"mappings":"AAEA,SACEA,sBAAsB,EAEtBC,uBAAuB,QAClB,cAAa;AACpB,SACEC,YAAY,EAEZC,4BAA4B,EAC5BC,mBAAmB,QACd,8BAA6B;AACpC,SAASC,mBAAmB,QAAQ,iCAAgC;AACpE,SACEC,uBAAuB,EACvBC,oBAAoB,EACpBC,cAAc,EACdC,cAAc,QACT,2BAA0B;AACjC,SACEC,kBAAkB,EAClBC,2BAA2B,EAC3BC,mBAAmB,EACnBC,kBAAkB,EAClBC,WAAW,EACXC,OAAO,EACPC,cAAc,QACT,cAAa;AAEpB,MAAMC,kBAAkB;IAAC;CAAU;AAMnC,SAASC,eAAeC,KAAa,EAAEC,GAAgB;IACrD,OAAOC,OAAOC,SAAS,CAACJ,cAAc,CAACK,IAAI,CAACJ,OAAOC;AACrD;AAEA,SAASI,0BAA0BL,KAAc;IAC/C,MAAMM,eACJ,OAAON,UAAU,WACb,AAAC,CAAA;QACC,IAAI;YACF,OAAOO,KAAKC,KAAK,CAACR;QACpB,EAAE,OAAM;YACN,OAAO;QACT;IACF,CAAA,MACAA;IAEN,IAAI,CAACM,gBAAgB,OAAOA,iBAAiB,YAAYG,MAAMC,OAAO,CAACJ,eAAe;QACpF,OAAO;IACT;IAEA,IAAI,CAACP,eAAeO,cAAc,aAAa;QAC7C,OAAO;IACT;IAEA,MAAMK,WAAWhB,YAAY,AAACW,aAAwCK,QAAQ;IAE9E,IACE,AAACL,aAAwCK,QAAQ,KA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,MAAMzE,IAAIkC,OAAO,CAACwC,MAAM,CAACZ;gBAIzC,IAAIhD,YAAYS,OAAO,EAAE;oBACvB,MAAMoD,gBAAgB,MAAMxG,oBAAoB;wBAC9CkD,IAAIK;wBACJb;wBACAqD,QAAQjD;wBACRjB;oBACF;oBAEAc,YAAYU,GAAG,CAAC;wBACdC,YAAYZ;wBACZX,MAAM;4BACJ0E,OAAOrB,KAAKC,GAAG,KAAKF;4BACpB5B,SAAS6C,OAAO7C;4BAChBmD,uBAAuBF;4BACvBG,cAAcL,QAAQb,WAAW;wBACnC;wBACA/B;wBACAC,OAAO;wBACPR,SAAS;wBACTlB,QAAQ;oBACV;gBACF;YACF,EAAE,OAAO2E,KAAK;gBACZ,MAAMC,QAAQD;gBAEdjE,YAAYU,GAAG,CAAC;oBACdC,YAAYZ;oBACZX,MAAM;wBACJ+E,MAAMD,OAAOC;wBACb/E,MAAM8E,OAAO9E,QAAQ;wBACrB0E,OAAOrB,KAAKC,GAAG,KAAKF;wBACpBhC,SAAS0D,OAAO1D;wBAChBI,SAAS6C,OAAO7C;oBAClB;oBACAG;oBACAC,OAAO;oBACPR,SAAS,CAAC,qCAAqC,EAAE0D,OAAO1D,WAAW,iBAAiB;oBACpFlB,QAAQ;gBACV;gBAEA,MAAM2E;YACR;YAEA,OAAOjG,QAAQ,KAAK;gBAClB4C,SAASP;gBACT+D,IAAI;gBACJrF,UAAUS,KAAKT,QAAQ;YACzB;QACF;QACAsF,QAAQ;QACRC,MAAM;IACR;AACF"}
@@ -204,9 +204,9 @@ async function readBackendSiblingOrder(args) {
204
204
  const result = await req.payload.find({
205
205
  collection: collectionSlug,
206
206
  depth: 0,
207
- draft: draft,
207
+ draft,
208
208
  limit: 250,
209
- locale: locale,
209
+ locale,
210
210
  overrideAccess: true,
211
211
  pagination: false,
212
212
  req,
@@ -305,7 +305,7 @@ async function updateLatestVersionOrder(args) {
305
305
  async function updateOrderValueSilently(args) {
306
306
  const { id, collectionSlug, hasDrafts, orderableFieldName, orderValue, req } = args;
307
307
  await req.payload.db.updateOne({
308
- id: id,
308
+ id,
309
309
  collection: collectionSlug,
310
310
  data: {
311
311
  [orderableFieldName]: orderValue,
@@ -473,7 +473,6 @@ export function createReorderPageEndpoint(args) {
473
473
  }
474
474
  // A reorder only writes the order key, never publishing state, so it
475
475
  // always carries the deploy opt-out flag.
476
- ;
477
476
  req.context[pageTreeMoveContextKey] = true;
478
477
  req.context[pageTreeWriteContextKey] = true;
479
478
  req.context[DIAGNOSTICS_FLOW_CONTEXT_KEY] = flow;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/endpoints/createReorderPageEndpoint.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest, Where } from 'payload'\n\nimport { combineWhereConstraints, generateNKeysBetween } from 'payload/shared'\n\nimport {\n pageTreeMoveContextKey,\n type PageTreeSourceDoc,\n pageTreeWriteContextKey,\n} from '../types.js'\nimport {\n createFlowID,\n type Diagnostics,\n DIAGNOSTICS_FLOW_CONTEXT_KEY,\n readMainRowSnapshot,\n} from '../utilities/diagnostics.js'\nimport { getDocParentID, stringifyDocID } from '../utilities/pageTree.js'\nimport {\n assertUpdateAccess,\n collectionHasDrafts,\n getRequestedLocale,\n normalizeID,\n respond,\n toCollectionID,\n} from './shared.js'\n\ntype ReorderDocumentRequestBody = {\n docsToMove: string[]\n frontendOrder?: ReorderFrontendOrderDiagnostic\n newKeyWillBe: 'greater' | 'less'\n orderableFieldName: string\n target: {\n id: string\n key: null | string\n }\n}\n\ntype ReorderFrontendOrderDiagnostic = {\n activeSlug: null | string\n after: ReorderFrontendOrderEntry[]\n before: ReorderFrontendOrderEntry[]\n moveFromIndex: number\n moveToIndex: number\n newAfterRowSlug: null | string\n newBeforeRowSlug: null | string\n sort: null | string\n targetSlug: null | string\n}\n\ntype ReorderFrontendOrderEntry = {\n index: number\n orderKey: null | string\n slug: null | string\n}\n\ntype ReorderBackendOrderEntry = {\n index: number\n orderKey: null | string\n slug: null | string\n status: null | string\n}\n\ntype RawBodyAttempt = {\n raw: unknown\n source: 'req.data' | 'req.json' | 'req.text'\n}\n\ntype VersionRecord = {\n createdAt?: string\n id?: number | string\n latest?: boolean\n parent?: number | string\n publishedLocale?: string\n updatedAt?: string\n version?: Record<string, unknown>\n} & Record<string, unknown>\n\nconst SNAPSHOT_FIELDS = ['_status'] as const\n\nfunction hasOwnProperty(value: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(value, key)\n}\n\nfunction normalizeOptionalString(value: unknown): null | string {\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction normalizeFrontendOrderEntry(\n value: unknown,\n fallbackIndex: number,\n): null | ReorderFrontendOrderEntry {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return null\n }\n\n const data = value as Record<string, unknown>\n\n return {\n slug: normalizeOptionalString(data.slug),\n index: typeof data.index === 'number' && Number.isFinite(data.index) ? data.index : fallbackIndex,\n orderKey: normalizeOptionalString(data.orderKey),\n }\n}\n\nfunction normalizeFrontendOrder(value: unknown): ReorderFrontendOrderDiagnostic | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return undefined\n }\n\n const data = value as Record<string, unknown>\n\n if (!Array.isArray(data.before) || !Array.isArray(data.after)) {\n return undefined\n }\n\n const before = data.before\n .slice(0, 250)\n .map((entry, index) => normalizeFrontendOrderEntry(entry, index))\n .filter((entry): entry is ReorderFrontendOrderEntry => Boolean(entry))\n const after = data.after\n .slice(0, 250)\n .map((entry, index) => normalizeFrontendOrderEntry(entry, index))\n .filter((entry): entry is ReorderFrontendOrderEntry => Boolean(entry))\n\n return {\n activeSlug: normalizeOptionalString(data.activeSlug),\n after,\n before,\n moveFromIndex:\n typeof data.moveFromIndex === 'number' && Number.isFinite(data.moveFromIndex)\n ? data.moveFromIndex\n : -1,\n moveToIndex:\n typeof data.moveToIndex === 'number' && Number.isFinite(data.moveToIndex)\n ? data.moveToIndex\n : -1,\n newAfterRowSlug: normalizeOptionalString(data.newAfterRowSlug),\n newBeforeRowSlug: normalizeOptionalString(data.newBeforeRowSlug),\n sort: normalizeOptionalString(data.sort),\n targetSlug: normalizeOptionalString(data.targetSlug),\n }\n}\n\nfunction normalizeReorderDocumentBody(value: unknown): null | ReorderDocumentRequestBody {\n const incomingData =\n typeof value === 'string'\n ? (() => {\n try {\n return JSON.parse(value) as unknown\n } catch {\n return null\n }\n })()\n : value\n\n if (!incomingData || typeof incomingData !== 'object' || Array.isArray(incomingData)) {\n return null\n }\n\n const data = incomingData as Record<string, unknown>\n const target = data.target\n\n if (!Array.isArray(data.docsToMove) || data.docsToMove.length !== 1) {\n return null\n }\n\n if (data.newKeyWillBe !== 'greater' && data.newKeyWillBe !== 'less') {\n return null\n }\n\n if (typeof data.orderableFieldName !== 'string' || data.orderableFieldName.length === 0) {\n return null\n }\n\n if (!target || typeof target !== 'object' || Array.isArray(target)) {\n return null\n }\n\n const targetData = target as Record<string, unknown>\n const movedID = normalizeID(data.docsToMove[0])\n const targetID = normalizeID(targetData.id)\n\n if (!movedID || !targetID) {\n return null\n }\n\n const key = hasOwnProperty(targetData, 'key') ? targetData.key : null\n\n if (key !== null && key !== undefined && typeof key !== 'string') {\n return null\n }\n\n return {\n docsToMove: [movedID],\n frontendOrder: normalizeFrontendOrder(data.frontendOrder),\n newKeyWillBe: data.newKeyWillBe,\n orderableFieldName: data.orderableFieldName,\n target: {\n id: targetID,\n key: key || null,\n },\n }\n}\n\nasync function readBodyFromRequest(\n req: PayloadRequest,\n): Promise<{ body: null | ReorderDocumentRequestBody; lastAttempt: null | RawBodyAttempt }> {\n let lastAttempt: null | RawBodyAttempt = null\n\n if (req.data !== undefined && req.data !== null) {\n lastAttempt = { raw: req.data, source: 'req.data' }\n const directBody = normalizeReorderDocumentBody(req.data)\n\n if (directBody) {\n return { body: directBody, lastAttempt }\n }\n }\n\n if (typeof req.json === 'function') {\n try {\n const raw = await req.json()\n lastAttempt = { raw, source: 'req.json' }\n const jsonBody = normalizeReorderDocumentBody(raw)\n\n if (jsonBody) {\n return { body: jsonBody, lastAttempt }\n }\n } catch {\n // Fall through to the text-based fallback when the runtime does not hydrate req.data.\n }\n }\n\n if (typeof req.text === 'function') {\n try {\n const raw = await req.text()\n lastAttempt = { raw, source: 'req.text' }\n const textBody = normalizeReorderDocumentBody(raw)\n\n if (textBody) {\n return { body: textBody, lastAttempt }\n }\n } catch {\n return { body: null, lastAttempt }\n }\n }\n\n return { body: null, lastAttempt }\n}\n\nfunction getParentScopeWhere(args: {\n parentFieldSlug: string\n parentID: null | number | string\n}): Where {\n const { parentFieldSlug, parentID } = args\n\n return {\n [parentFieldSlug]: {\n equals: parentID,\n },\n } as Where\n}\n\nfunction getOrderableKey(doc: PageTreeSourceDoc | undefined, orderableFieldName: string) {\n const value = doc?.[orderableFieldName]\n\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction getDiagnosticDocString(value: unknown, locale?: string): null | string {\n if (typeof value === 'string' && value.length > 0) {\n return value\n }\n\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return null\n }\n\n const localizedValue = value as Record<string, unknown>\n const localeValue = locale ? localizedValue[locale] : undefined\n\n if (typeof localeValue === 'string' && localeValue.length > 0) {\n return localeValue\n }\n\n const firstString = Object.values(localizedValue).find(\n (entry): entry is string => typeof entry === 'string' && entry.length > 0,\n )\n\n return firstString ?? null\n}\n\nfunction getBackendOrderEntry(args: {\n doc: PageTreeSourceDoc\n index: number\n locale?: string\n orderableFieldName: string\n}): ReorderBackendOrderEntry {\n const { doc, index, locale, orderableFieldName } = args\n\n return {\n slug: getDiagnosticDocString(doc.slug, locale),\n index,\n orderKey: getOrderableKey(doc, orderableFieldName),\n status: getDiagnosticDocString(doc._status, locale),\n }\n}\n\nfunction getMainRowOrderSnapshot(\n snapshot: null | Record<string, unknown>,\n orderableFieldName: string,\n): { orderKey: null | string; status: null | string } | null {\n if (!snapshot) {\n return null\n }\n\n return {\n orderKey: normalizeOptionalString(snapshot[orderableFieldName]),\n status: normalizeOptionalString(snapshot._status),\n }\n}\n\nasync function readBackendSiblingOrder(args: {\n collectionSlug: string\n draft?: boolean\n orderableFieldName: string\n parentScopeWhere: Where\n req: PayloadRequest\n}): Promise<ReorderBackendOrderEntry[]> {\n const { collectionSlug, draft, orderableFieldName, parentScopeWhere, req } = args\n const locale = getRequestedLocale(req)\n\n try {\n const result = await req.payload.find({\n collection: collectionSlug as never,\n depth: 0,\n draft: draft as never,\n limit: 250,\n locale: locale as never,\n overrideAccess: true,\n pagination: false,\n req,\n sort: orderableFieldName,\n where: parentScopeWhere as never,\n } as never)\n\n return (result.docs as unknown as PageTreeSourceDoc[]).map((doc, index) =>\n getBackendOrderEntry({\n doc,\n index,\n locale,\n orderableFieldName,\n }),\n )\n } catch {\n return []\n }\n}\n\nfunction getOrderValuesBetween(args: {\n adjacentDocKey: null | string\n docsToMoveLength: number\n movedBoundaryKey: null | string\n newKeyWillBe: ReorderDocumentRequestBody['newKeyWillBe']\n targetKey: string\n}): { orderValues: string[]; usedMovedKeyBoundary: boolean } {\n const { adjacentDocKey, docsToMoveLength, movedBoundaryKey, newKeyWillBe, targetKey } = args\n const orderValues =\n newKeyWillBe === 'greater'\n ? generateNKeysBetween(targetKey, adjacentDocKey, docsToMoveLength)\n : generateNKeysBetween(adjacentDocKey, targetKey, docsToMoveLength)\n\n if (orderValues[0] !== movedBoundaryKey) {\n return { orderValues, usedMovedKeyBoundary: false }\n }\n\n if (newKeyWillBe === 'greater' && movedBoundaryKey && movedBoundaryKey > targetKey) {\n return {\n orderValues: generateNKeysBetween(targetKey, movedBoundaryKey, docsToMoveLength),\n usedMovedKeyBoundary: true,\n }\n }\n\n if (newKeyWillBe === 'less' && movedBoundaryKey && movedBoundaryKey < targetKey) {\n return {\n orderValues: generateNKeysBetween(movedBoundaryKey, targetKey, docsToMoveLength),\n usedMovedKeyBoundary: true,\n }\n }\n\n return { orderValues, usedMovedKeyBoundary: false }\n}\n\nasync function readLatestVersion(args: {\n collectionSlug: string\n id: number | string\n req: PayloadRequest\n}): Promise<null | VersionRecord> {\n const { id, collectionSlug, req } = args\n const versions = await req.payload.db.findVersions({\n collection: collectionSlug as never,\n limit: 1,\n pagination: false,\n req,\n sort: '-updatedAt',\n where: {\n latest: {\n equals: true,\n },\n parent: {\n equals: id,\n },\n },\n } as never)\n const latestVersion = versions.docs[0] as undefined | VersionRecord\n\n if (!latestVersion?.version) {\n return null\n }\n\n return latestVersion\n}\n\nasync function updateLatestVersionOrder(args: {\n collectionSlug: string\n id: number | string\n orderableFieldName: string\n orderValue: string\n req: PayloadRequest\n}): Promise<boolean> {\n const { id, collectionSlug, orderableFieldName, orderValue, req } = args\n const latestVersion = await readLatestVersion({\n id,\n collectionSlug,\n req,\n })\n\n if (!latestVersion?.id || !latestVersion.version) {\n return false\n }\n\n await req.payload.db.updateVersion({\n id: latestVersion.id as never,\n collection: collectionSlug as never,\n locale: getRequestedLocale(req) as never,\n req,\n returning: false,\n versionData: {\n createdAt: latestVersion.createdAt,\n latest: latestVersion.latest,\n parent: id,\n publishedLocale: latestVersion.publishedLocale,\n updatedAt: latestVersion.updatedAt,\n version: {\n ...latestVersion.version,\n [orderableFieldName]: orderValue,\n },\n },\n } as never)\n\n return true\n}\n\nasync function updateOrderValueSilently(args: {\n collectionSlug: string\n hasDrafts: boolean\n id: number | string\n orderableFieldName: string\n orderValue: string\n req: PayloadRequest\n}): Promise<{ updatedDraftVersion: boolean }> {\n const { id, collectionSlug, hasDrafts, orderableFieldName, orderValue, req } = args\n\n await req.payload.db.updateOne({\n id: id as never,\n collection: collectionSlug as never,\n data: {\n [orderableFieldName]: orderValue,\n updatedAt: null,\n },\n locale: getRequestedLocale(req) as never,\n req,\n returning: false,\n } as never)\n\n const updatedDraftVersion = hasDrafts\n ? await updateLatestVersionOrder({\n id,\n collectionSlug,\n orderableFieldName,\n orderValue,\n req,\n })\n : false\n\n return {\n updatedDraftVersion,\n }\n}\n\nasync function initializeMissingOrderKeys(args: {\n collectionSlug: string\n diagnostics: Diagnostics\n flow: string\n hasDrafts: boolean\n orderableFieldName: string\n parentScopeWhere: Where\n req: PayloadRequest\n}): Promise<Response> {\n const { collectionSlug, diagnostics, flow, hasDrafts, orderableFieldName, parentScopeWhere, req } =\n args\n const existingOrderedDocs = await req.payload.find({\n collection: collectionSlug as never,\n depth: 0,\n draft: hasDrafts ? true : undefined,\n limit: 1,\n locale: getRequestedLocale(req) as never,\n overrideAccess: true,\n pagination: false,\n req,\n select: { [orderableFieldName]: true } as never,\n sort: `-${orderableFieldName}`,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n exists: true,\n },\n },\n parentScopeWhere,\n ]) as never,\n } as never)\n const missingOrderDocs = await req.payload.find({\n collection: collectionSlug as never,\n depth: 0,\n draft: hasDrafts ? true : undefined,\n limit: 0,\n locale: getRequestedLocale(req) as never,\n overrideAccess: true,\n pagination: false,\n req,\n select: { [orderableFieldName]: true } as never,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n exists: false,\n },\n },\n parentScopeWhere,\n ]) as never,\n } as never)\n const lastOrderValue = getOrderableKey(\n existingOrderedDocs.docs[0] as unknown as PageTreeSourceDoc | undefined,\n orderableFieldName,\n )\n const orderValues = generateNKeysBetween(lastOrderValue, null, missingOrderDocs.docs.length)\n\n for (const [index, doc] of (missingOrderDocs.docs as unknown as PageTreeSourceDoc[]).entries()) {\n const docID = doc.id\n const orderValue = orderValues[index]\n\n if (\n orderValue &&\n (typeof docID === 'number' || typeof docID === 'string')\n ) {\n await updateOrderValueSilently({\n id: docID,\n collectionSlug,\n hasDrafts,\n orderableFieldName,\n orderValue,\n req,\n })\n }\n }\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n initializedCount: missingOrderDocs.docs.length,\n orderableFieldName,\n },\n flow,\n level: 'info',\n message: 'reorder endpoint initialized missing order keys',\n source: 'reorder-endpoint:initial-migration',\n })\n\n return respond(200, {\n message: 'initial migration',\n success: true,\n })\n}\n\nexport function createReorderPageEndpoint(args: {\n collectionSlug: string\n diagnostics: Diagnostics\n orderableFieldName: string\n parentFieldSlug: string\n}): Endpoint {\n const { collectionSlug, diagnostics, orderableFieldName, parentFieldSlug } = args\n const snapshotFields = [...SNAPSHOT_FIELDS, parentFieldSlug, orderableFieldName]\n\n return {\n handler: async (req) => {\n const movedIDFromRoute = normalizeID(req.routeParams?.id)\n\n if (!movedIDFromRoute) {\n return respond(400, {\n message: 'Document ID was not specified.',\n })\n }\n\n const { body, lastAttempt } = await readBodyFromRequest(req)\n\n if (\n !body ||\n body.orderableFieldName !== orderableFieldName ||\n body.docsToMove[0] !== movedIDFromRoute\n ) {\n if (diagnostics.enabled) {\n diagnostics.log({\n collection: collectionSlug,\n data: {\n movedID: movedIDFromRoute,\n rawBody: lastAttempt?.raw ?? null,\n rawBodySource: lastAttempt?.source ?? null,\n },\n flow: createFlowID('reorder-endpoint'),\n level: 'warn',\n message: 'reorder endpoint rejected request body',\n source: 'reorder-endpoint:body-rejected',\n })\n }\n\n return respond(400, {\n message: 'A valid reorder request is required.',\n })\n }\n\n if (body.target.id === movedIDFromRoute) {\n return respond(400, {\n message: 'Document is already in that position.',\n })\n }\n\n const movedID = toCollectionID({\n id: movedIDFromRoute,\n collectionSlug,\n req,\n })\n const targetID = toCollectionID({\n id: body.target.id,\n collectionSlug,\n req,\n })\n const accessError = await assertUpdateAccess({\n id: movedID,\n collectionSlug,\n data: {},\n req,\n })\n\n if (accessError) {\n return accessError\n }\n\n const flow = createFlowID('reorder-endpoint')\n const reorderStart = Date.now()\n const hasDrafts = collectionHasDrafts({ collectionSlug, req })\n\n if (!req.context) {\n req.context = {}\n }\n\n // A reorder only writes the order key, never publishing state, so it\n // always carries the deploy opt-out flag.\n ;(req.context as Record<string, unknown>)[pageTreeMoveContextKey] = true\n ;(req.context as Record<string, unknown>)[pageTreeWriteContextKey] = true\n ;(req.context as Record<string, unknown>)[DIAGNOSTICS_FLOW_CONTEXT_KEY] = flow\n\n const relatedDocsResult = await req.payload.find({\n collection: collectionSlug as never,\n depth: 0,\n draft: hasDrafts ? true : undefined,\n limit: 2,\n locale: getRequestedLocale(req) as never,\n overrideAccess: true,\n req,\n where: {\n id: {\n in: [movedID, targetID],\n },\n },\n } as never)\n const docsByID = new Map(\n (relatedDocsResult.docs as unknown as PageTreeSourceDoc[]).map((doc) => [\n stringifyDocID(doc.id),\n doc,\n ]),\n )\n const movedDoc = docsByID.get(movedIDFromRoute)\n const targetDoc = docsByID.get(body.target.id)\n\n if (!movedDoc) {\n return respond(404, {\n message: 'Document not found.',\n })\n }\n\n if (!targetDoc) {\n return respond(400, {\n message: 'Target document not found.',\n })\n }\n\n const movedParentID = getDocParentID(movedDoc, parentFieldSlug)\n const targetParentID = getDocParentID(targetDoc, parentFieldSlug)\n\n if (movedParentID !== targetParentID) {\n return respond(400, {\n message: 'Documents can only be reordered within the same parent.',\n })\n }\n\n const parentScopeWhere = getParentScopeWhere({\n parentFieldSlug,\n parentID:\n movedParentID === null\n ? null\n : toCollectionID({\n id: movedParentID,\n collectionSlug,\n req,\n }),\n })\n\n if (!body.target.key) {\n return initializeMissingOrderKeys({\n collectionSlug,\n diagnostics,\n flow,\n hasDrafts,\n orderableFieldName,\n parentScopeWhere,\n req,\n })\n }\n\n const beforeSnapshot = await readMainRowSnapshot({\n id: movedID,\n collectionSlug,\n fields: snapshotFields,\n req,\n })\n const backendDraftOrderBefore = diagnostics.enabled\n ? await readBackendSiblingOrder({\n collectionSlug,\n draft: hasDrafts ? true : undefined,\n orderableFieldName,\n parentScopeWhere,\n req,\n })\n : null\n const backendMainOrderBefore = diagnostics.enabled\n ? await readBackendSiblingOrder({\n collectionSlug,\n draft: false,\n orderableFieldName,\n parentScopeWhere,\n req,\n })\n : null\n const adjacentDoc = await req.payload.find({\n collection: collectionSlug as never,\n depth: 0,\n draft: hasDrafts ? true : undefined,\n limit: 1,\n locale: getRequestedLocale(req) as never,\n overrideAccess: true,\n pagination: false,\n req,\n select: { [orderableFieldName]: true } as never,\n sort: body.newKeyWillBe === 'greater' ? orderableFieldName : `-${orderableFieldName}`,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n [body.newKeyWillBe === 'greater' ? 'greater_than' : 'less_than']: body.target.key,\n },\n },\n parentScopeWhere,\n ]) as never,\n } as never)\n const adjacentDocKey = getOrderableKey(\n adjacentDoc.docs[0] as unknown as PageTreeSourceDoc | undefined,\n orderableFieldName,\n )\n const movedDocKey = getOrderableKey(movedDoc, orderableFieldName)\n const movedSlug = getDiagnosticDocString(movedDoc.slug, getRequestedLocale(req))\n const targetSlug = getDiagnosticDocString(targetDoc.slug, getRequestedLocale(req))\n const movedMainRowKey =\n typeof beforeSnapshot?.[orderableFieldName] === 'string' &&\n beforeSnapshot[orderableFieldName].length > 0\n ? beforeSnapshot[orderableFieldName]\n : movedDocKey\n const { orderValues, usedMovedKeyBoundary } = getOrderValuesBetween({\n adjacentDocKey,\n docsToMoveLength: body.docsToMove.length,\n movedBoundaryKey: movedMainRowKey,\n newKeyWillBe: body.newKeyWillBe,\n targetKey: body.target.key,\n })\n const orderValue = orderValues[0]\n\n if (!orderValue) {\n return respond(500, {\n message: 'Could not generate a new order key.',\n })\n }\n\n if (diagnostics.enabled) {\n diagnostics.log({\n collection: collectionSlug,\n data: {\n adjacentDocKey,\n backendOrderBefore: {\n draft: backendDraftOrderBefore,\n main: backendMainOrderBefore,\n },\n frontendOrder: body.frontendOrder ?? null,\n mainRowBefore: getMainRowOrderSnapshot(beforeSnapshot, orderableFieldName),\n movedDocKey,\n movedMainRowKey,\n movedSlug,\n newKeyWillBe: body.newKeyWillBe,\n orderableFieldName,\n orderValue,\n target: {\n slug: targetSlug,\n key: body.target.key,\n },\n usedMovedKeyBoundary,\n },\n flow,\n level: 'info',\n message: 'reorder endpoint entering: order key update only',\n source: 'reorder-endpoint:enter',\n })\n }\n\n try {\n const updateResult = await updateOrderValueSilently({\n id: movedID,\n collectionSlug,\n hasDrafts,\n orderableFieldName,\n orderValue,\n req,\n })\n\n if (diagnostics.enabled) {\n const afterSnapshot = await readMainRowSnapshot({\n id: movedID,\n collectionSlug,\n fields: snapshotFields,\n req,\n })\n const backendDraftOrderAfter = await readBackendSiblingOrder({\n collectionSlug,\n draft: hasDrafts ? true : undefined,\n orderableFieldName,\n parentScopeWhere,\n req,\n })\n const backendMainOrderAfter = await readBackendSiblingOrder({\n collectionSlug,\n draft: false,\n orderableFieldName,\n parentScopeWhere,\n req,\n })\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n backendOrderAfter: {\n draft: backendDraftOrderAfter,\n main: backendMainOrderAfter,\n },\n durMs: Date.now() - reorderStart,\n mainRowAfter: getMainRowOrderSnapshot(afterSnapshot, orderableFieldName),\n movedSlug,\n orderValue,\n updatedDraftVersion: updateResult.updatedDraftVersion,\n },\n flow,\n level: 'info',\n message: 'reorder endpoint order key update succeeded',\n source: 'reorder-endpoint:ok',\n })\n }\n } catch (err) {\n const error = err as { data?: unknown; message?: string; name?: string } & Error\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n name: error?.name,\n data: error?.data ?? null,\n durMs: Date.now() - reorderStart,\n message: error?.message,\n movedSlug,\n },\n flow,\n level: 'error',\n message: `reorder endpoint order key update failed: ${error?.message ?? 'unknown error'}`,\n source: 'reorder-endpoint:error',\n })\n\n throw err\n }\n\n return respond(200, {\n movedID: movedIDFromRoute,\n orderValues,\n success: true,\n })\n },\n method: 'post',\n path: '/:id/reorder',\n }\n}\n"],"names":["combineWhereConstraints","generateNKeysBetween","pageTreeMoveContextKey","pageTreeWriteContextKey","createFlowID","DIAGNOSTICS_FLOW_CONTEXT_KEY","readMainRowSnapshot","getDocParentID","stringifyDocID","assertUpdateAccess","collectionHasDrafts","getRequestedLocale","normalizeID","respond","toCollectionID","SNAPSHOT_FIELDS","hasOwnProperty","value","key","Object","prototype","call","normalizeOptionalString","length","normalizeFrontendOrderEntry","fallbackIndex","Array","isArray","data","slug","index","Number","isFinite","orderKey","normalizeFrontendOrder","undefined","before","after","slice","map","entry","filter","Boolean","activeSlug","moveFromIndex","moveToIndex","newAfterRowSlug","newBeforeRowSlug","sort","targetSlug","normalizeReorderDocumentBody","incomingData","JSON","parse","target","docsToMove","newKeyWillBe","orderableFieldName","targetData","movedID","targetID","id","frontendOrder","readBodyFromRequest","req","lastAttempt","raw","source","directBody","body","json","jsonBody","text","textBody","getParentScopeWhere","args","parentFieldSlug","parentID","equals","getOrderableKey","doc","getDiagnosticDocString","locale","localizedValue","localeValue","firstString","values","find","getBackendOrderEntry","status","_status","getMainRowOrderSnapshot","snapshot","readBackendSiblingOrder","collectionSlug","draft","parentScopeWhere","result","payload","collection","depth","limit","overrideAccess","pagination","where","docs","getOrderValuesBetween","adjacentDocKey","docsToMoveLength","movedBoundaryKey","targetKey","orderValues","usedMovedKeyBoundary","readLatestVersion","versions","db","findVersions","latest","parent","latestVersion","version","updateLatestVersionOrder","orderValue","updateVersion","returning","versionData","createdAt","publishedLocale","updatedAt","updateOrderValueSilently","hasDrafts","updateOne","updatedDraftVersion","initializeMissingOrderKeys","diagnostics","flow","existingOrderedDocs","select","exists","missingOrderDocs","lastOrderValue","entries","docID","log","initializedCount","level","message","success","createReorderPageEndpoint","snapshotFields","handler","movedIDFromRoute","routeParams","enabled","rawBody","rawBodySource","accessError","reorderStart","Date","now","context","relatedDocsResult","in","docsByID","Map","movedDoc","get","targetDoc","movedParentID","targetParentID","beforeSnapshot","fields","backendDraftOrderBefore","backendMainOrderBefore","adjacentDoc","movedDocKey","movedSlug","movedMainRowKey","backendOrderBefore","main","mainRowBefore","updateResult","afterSnapshot","backendDraftOrderAfter","backendMainOrderAfter","backendOrderAfter","durMs","mainRowAfter","err","error","name","method","path"],"mappings":"AAEA,SAASA,uBAAuB,EAAEC,oBAAoB,QAAQ,iBAAgB;AAE9E,SACEC,sBAAsB,EAEtBC,uBAAuB,QAClB,cAAa;AACpB,SACEC,YAAY,EAEZC,4BAA4B,EAC5BC,mBAAmB,QACd,8BAA6B;AACpC,SAASC,cAAc,EAAEC,cAAc,QAAQ,2BAA0B;AACzE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MuH,yBAAyB,MAAM1F,wBAAwB;wBAC3DC;wBACAC,OAAOmC,YAAY,OAAO/F;wBAC1BsB;wBACAuC;wBACAhC;oBACF;oBACA,MAAMwH,wBAAwB,MAAM3F,wBAAwB;wBAC1DC;wBACAC,OAAO;wBACPtC;wBACAuC;wBACAhC;oBACF;oBAEAsE,YAAYS,GAAG,CAAC;wBACd5C,YAAYL;wBACZlE,MAAM;4BACJ6J,mBAAmB;gCACjB1F,OAAOwF;gCACPJ,MAAMK;4BACR;4BACAE,OAAO5B,KAAKC,GAAG,KAAKF;4BACpB8B,cAAchG,wBAAwB2F,eAAe7H;4BACrDuH;4BACAtD;4BACAU,qBAAqBiD,aAAajD,mBAAmB;wBACvD;wBACAG;wBACAU,OAAO;wBACPC,SAAS;wBACT/E,QAAQ;oBACV;gBACF;YACF,EAAE,OAAOyH,KAAK;gBACZ,MAAMC,QAAQD;gBAEdtD,YAAYS,GAAG,CAAC;oBACd5C,YAAYL;oBACVlE,MAAM;wBACJkK,MAAMD,OAAOC;wBACblK,MAAMiK,OAAOjK,QAAQ;wBACrB8J,OAAO5B,KAAKC,GAAG,KAAKF;wBACpBX,SAAS2C,OAAO3C;wBAChB8B;oBACF;oBACFzC;oBACAU,OAAO;oBACPC,SAAS,CAAC,0CAA0C,EAAE2C,OAAO3C,WAAW,iBAAiB;oBACzF/E,QAAQ;gBACV;gBAEA,MAAMyH;YACR;YAEA,OAAO/K,QAAQ,KAAK;gBAClB8C,SAAS4F;gBACTxC;gBACAoC,SAAS;YACX;QACF;QACA4C,QAAQ;QACRC,MAAM;IACR;AACF"}
1
+ {"version":3,"sources":["../../src/endpoints/createReorderPageEndpoint.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest, Where } from 'payload'\n\nimport { combineWhereConstraints, generateNKeysBetween } from 'payload/shared'\n\nimport {\n pageTreeMoveContextKey,\n type PageTreeSourceDoc,\n pageTreeWriteContextKey,\n} from '../types.js'\nimport {\n createFlowID,\n type Diagnostics,\n DIAGNOSTICS_FLOW_CONTEXT_KEY,\n readMainRowSnapshot,\n} from '../utilities/diagnostics.js'\nimport { getDocParentID, stringifyDocID } from '../utilities/pageTree.js'\nimport {\n assertUpdateAccess,\n collectionHasDrafts,\n getRequestedLocale,\n normalizeID,\n respond,\n toCollectionID,\n} from './shared.js'\n\ntype ReorderDocumentRequestBody = {\n docsToMove: string[]\n frontendOrder?: ReorderFrontendOrderDiagnostic\n newKeyWillBe: 'greater' | 'less'\n orderableFieldName: string\n target: {\n id: string\n key: null | string\n }\n}\n\ntype ReorderFrontendOrderDiagnostic = {\n activeSlug: null | string\n after: ReorderFrontendOrderEntry[]\n before: ReorderFrontendOrderEntry[]\n moveFromIndex: number\n moveToIndex: number\n newAfterRowSlug: null | string\n newBeforeRowSlug: null | string\n sort: null | string\n targetSlug: null | string\n}\n\ntype ReorderFrontendOrderEntry = {\n index: number\n orderKey: null | string\n slug: null | string\n}\n\ntype ReorderBackendOrderEntry = {\n index: number\n orderKey: null | string\n slug: null | string\n status: null | string\n}\n\ntype RawBodyAttempt = {\n raw: unknown\n source: 'req.data' | 'req.json' | 'req.text'\n}\n\ntype VersionRecord = {\n createdAt?: string\n id?: number | string\n latest?: boolean\n parent?: number | string\n publishedLocale?: string\n updatedAt?: string\n version?: Record<string, unknown>\n} & Record<string, unknown>\n\nconst SNAPSHOT_FIELDS = ['_status'] as const\n\nfunction hasOwnProperty(value: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(value, key)\n}\n\nfunction normalizeOptionalString(value: unknown): null | string {\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction normalizeFrontendOrderEntry(\n value: unknown,\n fallbackIndex: number,\n): null | ReorderFrontendOrderEntry {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return null\n }\n\n const data = value as Record<string, unknown>\n\n return {\n slug: normalizeOptionalString(data.slug),\n index: typeof data.index === 'number' && Number.isFinite(data.index) ? data.index : fallbackIndex,\n orderKey: normalizeOptionalString(data.orderKey),\n }\n}\n\nfunction normalizeFrontendOrder(value: unknown): ReorderFrontendOrderDiagnostic | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return undefined\n }\n\n const data = value as Record<string, unknown>\n\n if (!Array.isArray(data.before) || !Array.isArray(data.after)) {\n return undefined\n }\n\n const before = data.before\n .slice(0, 250)\n .map((entry, index) => normalizeFrontendOrderEntry(entry, index))\n .filter((entry): entry is ReorderFrontendOrderEntry => Boolean(entry))\n const after = data.after\n .slice(0, 250)\n .map((entry, index) => normalizeFrontendOrderEntry(entry, index))\n .filter((entry): entry is ReorderFrontendOrderEntry => Boolean(entry))\n\n return {\n activeSlug: normalizeOptionalString(data.activeSlug),\n after,\n before,\n moveFromIndex:\n typeof data.moveFromIndex === 'number' && Number.isFinite(data.moveFromIndex)\n ? data.moveFromIndex\n : -1,\n moveToIndex:\n typeof data.moveToIndex === 'number' && Number.isFinite(data.moveToIndex)\n ? data.moveToIndex\n : -1,\n newAfterRowSlug: normalizeOptionalString(data.newAfterRowSlug),\n newBeforeRowSlug: normalizeOptionalString(data.newBeforeRowSlug),\n sort: normalizeOptionalString(data.sort),\n targetSlug: normalizeOptionalString(data.targetSlug),\n }\n}\n\nfunction normalizeReorderDocumentBody(value: unknown): null | ReorderDocumentRequestBody {\n const incomingData =\n typeof value === 'string'\n ? (() => {\n try {\n return JSON.parse(value) as unknown\n } catch {\n return null\n }\n })()\n : value\n\n if (!incomingData || typeof incomingData !== 'object' || Array.isArray(incomingData)) {\n return null\n }\n\n const data = incomingData as Record<string, unknown>\n const target = data.target\n\n if (!Array.isArray(data.docsToMove) || data.docsToMove.length !== 1) {\n return null\n }\n\n if (data.newKeyWillBe !== 'greater' && data.newKeyWillBe !== 'less') {\n return null\n }\n\n if (typeof data.orderableFieldName !== 'string' || data.orderableFieldName.length === 0) {\n return null\n }\n\n if (!target || typeof target !== 'object' || Array.isArray(target)) {\n return null\n }\n\n const targetData = target as Record<string, unknown>\n const movedID = normalizeID(data.docsToMove[0])\n const targetID = normalizeID(targetData.id)\n\n if (!movedID || !targetID) {\n return null\n }\n\n const key = hasOwnProperty(targetData, 'key') ? targetData.key : null\n\n if (key !== null && key !== undefined && typeof key !== 'string') {\n return null\n }\n\n return {\n docsToMove: [movedID],\n frontendOrder: normalizeFrontendOrder(data.frontendOrder),\n newKeyWillBe: data.newKeyWillBe,\n orderableFieldName: data.orderableFieldName,\n target: {\n id: targetID,\n key: key || null,\n },\n }\n}\n\nasync function readBodyFromRequest(\n req: PayloadRequest,\n): Promise<{ body: null | ReorderDocumentRequestBody; lastAttempt: null | RawBodyAttempt }> {\n let lastAttempt: null | RawBodyAttempt = null\n\n if (req.data !== undefined && req.data !== null) {\n lastAttempt = { raw: req.data, source: 'req.data' }\n const directBody = normalizeReorderDocumentBody(req.data)\n\n if (directBody) {\n return { body: directBody, lastAttempt }\n }\n }\n\n if (typeof req.json === 'function') {\n try {\n const raw = await req.json()\n lastAttempt = { raw, source: 'req.json' }\n const jsonBody = normalizeReorderDocumentBody(raw)\n\n if (jsonBody) {\n return { body: jsonBody, lastAttempt }\n }\n } catch {\n // Fall through to the text-based fallback when the runtime does not hydrate req.data.\n }\n }\n\n if (typeof req.text === 'function') {\n try {\n const raw = await req.text()\n lastAttempt = { raw, source: 'req.text' }\n const textBody = normalizeReorderDocumentBody(raw)\n\n if (textBody) {\n return { body: textBody, lastAttempt }\n }\n } catch {\n return { body: null, lastAttempt }\n }\n }\n\n return { body: null, lastAttempt }\n}\n\nfunction getParentScopeWhere(args: {\n parentFieldSlug: string\n parentID: null | number | string\n}): Where {\n const { parentFieldSlug, parentID } = args\n\n return {\n [parentFieldSlug]: {\n equals: parentID,\n },\n } as Where\n}\n\nfunction getOrderableKey(doc: PageTreeSourceDoc | undefined, orderableFieldName: string) {\n const value = doc?.[orderableFieldName]\n\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction getDiagnosticDocString(value: unknown, locale?: string): null | string {\n if (typeof value === 'string' && value.length > 0) {\n return value\n }\n\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return null\n }\n\n const localizedValue = value as Record<string, unknown>\n const localeValue = locale ? localizedValue[locale] : undefined\n\n if (typeof localeValue === 'string' && localeValue.length > 0) {\n return localeValue\n }\n\n const firstString = Object.values(localizedValue).find(\n (entry): entry is string => typeof entry === 'string' && entry.length > 0,\n )\n\n return firstString ?? null\n}\n\nfunction getBackendOrderEntry(args: {\n doc: PageTreeSourceDoc\n index: number\n locale?: string\n orderableFieldName: string\n}): ReorderBackendOrderEntry {\n const { doc, index, locale, orderableFieldName } = args\n\n return {\n slug: getDiagnosticDocString(doc.slug, locale),\n index,\n orderKey: getOrderableKey(doc, orderableFieldName),\n status: getDiagnosticDocString(doc._status, locale),\n }\n}\n\nfunction getMainRowOrderSnapshot(\n snapshot: null | Record<string, unknown>,\n orderableFieldName: string,\n): { orderKey: null | string; status: null | string } | null {\n if (!snapshot) {\n return null\n }\n\n return {\n orderKey: normalizeOptionalString(snapshot[orderableFieldName]),\n status: normalizeOptionalString(snapshot._status),\n }\n}\n\nasync function readBackendSiblingOrder(args: {\n collectionSlug: string\n draft?: boolean\n orderableFieldName: string\n parentScopeWhere: Where\n req: PayloadRequest\n}): Promise<ReorderBackendOrderEntry[]> {\n const { collectionSlug, draft, orderableFieldName, parentScopeWhere, req } = args\n const locale = getRequestedLocale(req)\n\n try {\n const result = await req.payload.find({\n collection: collectionSlug,\n depth: 0,\n draft,\n limit: 250,\n locale,\n overrideAccess: true,\n pagination: false,\n req,\n sort: orderableFieldName,\n where: parentScopeWhere,\n })\n\n return (result.docs as unknown as PageTreeSourceDoc[]).map((doc, index) =>\n getBackendOrderEntry({\n doc,\n index,\n locale,\n orderableFieldName,\n }),\n )\n } catch {\n return []\n }\n}\n\nfunction getOrderValuesBetween(args: {\n adjacentDocKey: null | string\n docsToMoveLength: number\n movedBoundaryKey: null | string\n newKeyWillBe: ReorderDocumentRequestBody['newKeyWillBe']\n targetKey: string\n}): { orderValues: string[]; usedMovedKeyBoundary: boolean } {\n const { adjacentDocKey, docsToMoveLength, movedBoundaryKey, newKeyWillBe, targetKey } = args\n const orderValues =\n newKeyWillBe === 'greater'\n ? generateNKeysBetween(targetKey, adjacentDocKey, docsToMoveLength)\n : generateNKeysBetween(adjacentDocKey, targetKey, docsToMoveLength)\n\n if (orderValues[0] !== movedBoundaryKey) {\n return { orderValues, usedMovedKeyBoundary: false }\n }\n\n if (newKeyWillBe === 'greater' && movedBoundaryKey && movedBoundaryKey > targetKey) {\n return {\n orderValues: generateNKeysBetween(targetKey, movedBoundaryKey, docsToMoveLength),\n usedMovedKeyBoundary: true,\n }\n }\n\n if (newKeyWillBe === 'less' && movedBoundaryKey && movedBoundaryKey < targetKey) {\n return {\n orderValues: generateNKeysBetween(movedBoundaryKey, targetKey, docsToMoveLength),\n usedMovedKeyBoundary: true,\n }\n }\n\n return { orderValues, usedMovedKeyBoundary: false }\n}\n\nasync function readLatestVersion(args: {\n collectionSlug: string\n id: number | string\n req: PayloadRequest\n}): Promise<null | VersionRecord> {\n const { id, collectionSlug, req } = args\n const versions = await req.payload.db.findVersions({\n collection: collectionSlug,\n limit: 1,\n pagination: false,\n req,\n sort: '-updatedAt',\n where: {\n latest: {\n equals: true,\n },\n parent: {\n equals: id,\n },\n },\n })\n const latestVersion = versions.docs[0] as undefined | VersionRecord\n\n if (!latestVersion?.version) {\n return null\n }\n\n return latestVersion\n}\n\nasync function updateLatestVersionOrder(args: {\n collectionSlug: string\n id: number | string\n orderableFieldName: string\n orderValue: string\n req: PayloadRequest\n}): Promise<boolean> {\n const { id, collectionSlug, orderableFieldName, orderValue, req } = args\n const latestVersion = await readLatestVersion({\n id,\n collectionSlug,\n req,\n })\n\n if (!latestVersion?.id || !latestVersion.version) {\n return false\n }\n\n await req.payload.db.updateVersion({\n id: latestVersion.id,\n collection: collectionSlug,\n locale: getRequestedLocale(req),\n req,\n returning: false,\n versionData: {\n createdAt: latestVersion.createdAt,\n latest: latestVersion.latest,\n parent: id,\n publishedLocale: latestVersion.publishedLocale,\n updatedAt: latestVersion.updatedAt,\n version: {\n ...latestVersion.version,\n [orderableFieldName]: orderValue,\n },\n },\n })\n\n return true\n}\n\nasync function updateOrderValueSilently(args: {\n collectionSlug: string\n hasDrafts: boolean\n id: number | string\n orderableFieldName: string\n orderValue: string\n req: PayloadRequest\n}): Promise<{ updatedDraftVersion: boolean }> {\n const { id, collectionSlug, hasDrafts, orderableFieldName, orderValue, req } = args\n\n await req.payload.db.updateOne({\n id,\n collection: collectionSlug,\n data: {\n [orderableFieldName]: orderValue,\n updatedAt: null,\n },\n locale: getRequestedLocale(req),\n req,\n returning: false,\n })\n\n const updatedDraftVersion = hasDrafts\n ? await updateLatestVersionOrder({\n id,\n collectionSlug,\n orderableFieldName,\n orderValue,\n req,\n })\n : false\n\n return {\n updatedDraftVersion,\n }\n}\n\nasync function initializeMissingOrderKeys(args: {\n collectionSlug: string\n diagnostics: Diagnostics\n flow: string\n hasDrafts: boolean\n orderableFieldName: string\n parentScopeWhere: Where\n req: PayloadRequest\n}): Promise<Response> {\n const { collectionSlug, diagnostics, flow, hasDrafts, orderableFieldName, parentScopeWhere, req } =\n args\n const existingOrderedDocs = await req.payload.find({\n collection: collectionSlug,\n depth: 0,\n draft: hasDrafts ? true : undefined,\n limit: 1,\n locale: getRequestedLocale(req),\n overrideAccess: true,\n pagination: false,\n req,\n select: { [orderableFieldName]: true },\n sort: `-${orderableFieldName}`,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n exists: true,\n },\n },\n parentScopeWhere,\n ]),\n })\n const missingOrderDocs = await req.payload.find({\n collection: collectionSlug,\n depth: 0,\n draft: hasDrafts ? true : undefined,\n limit: 0,\n locale: getRequestedLocale(req),\n overrideAccess: true,\n pagination: false,\n req,\n select: { [orderableFieldName]: true },\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n exists: false,\n },\n },\n parentScopeWhere,\n ]),\n })\n const lastOrderValue = getOrderableKey(\n existingOrderedDocs.docs[0] as unknown as PageTreeSourceDoc | undefined,\n orderableFieldName,\n )\n const orderValues = generateNKeysBetween(lastOrderValue, null, missingOrderDocs.docs.length)\n\n for (const [index, doc] of (missingOrderDocs.docs as unknown as PageTreeSourceDoc[]).entries()) {\n const docID = doc.id\n const orderValue = orderValues[index]\n\n if (\n orderValue &&\n (typeof docID === 'number' || typeof docID === 'string')\n ) {\n await updateOrderValueSilently({\n id: docID,\n collectionSlug,\n hasDrafts,\n orderableFieldName,\n orderValue,\n req,\n })\n }\n }\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n initializedCount: missingOrderDocs.docs.length,\n orderableFieldName,\n },\n flow,\n level: 'info',\n message: 'reorder endpoint initialized missing order keys',\n source: 'reorder-endpoint:initial-migration',\n })\n\n return respond(200, {\n message: 'initial migration',\n success: true,\n })\n}\n\nexport function createReorderPageEndpoint(args: {\n collectionSlug: string\n diagnostics: Diagnostics\n orderableFieldName: string\n parentFieldSlug: string\n}): Endpoint {\n const { collectionSlug, diagnostics, orderableFieldName, parentFieldSlug } = args\n const snapshotFields = [...SNAPSHOT_FIELDS, parentFieldSlug, orderableFieldName]\n\n return {\n handler: async (req) => {\n const movedIDFromRoute = normalizeID(req.routeParams?.id)\n\n if (!movedIDFromRoute) {\n return respond(400, {\n message: 'Document ID was not specified.',\n })\n }\n\n const { body, lastAttempt } = await readBodyFromRequest(req)\n\n if (\n !body ||\n body.orderableFieldName !== orderableFieldName ||\n body.docsToMove[0] !== movedIDFromRoute\n ) {\n if (diagnostics.enabled) {\n diagnostics.log({\n collection: collectionSlug,\n data: {\n movedID: movedIDFromRoute,\n rawBody: lastAttempt?.raw ?? null,\n rawBodySource: lastAttempt?.source ?? null,\n },\n flow: createFlowID('reorder-endpoint'),\n level: 'warn',\n message: 'reorder endpoint rejected request body',\n source: 'reorder-endpoint:body-rejected',\n })\n }\n\n return respond(400, {\n message: 'A valid reorder request is required.',\n })\n }\n\n if (body.target.id === movedIDFromRoute) {\n return respond(400, {\n message: 'Document is already in that position.',\n })\n }\n\n const movedID = toCollectionID({\n id: movedIDFromRoute,\n collectionSlug,\n req,\n })\n const targetID = toCollectionID({\n id: body.target.id,\n collectionSlug,\n req,\n })\n const accessError = await assertUpdateAccess({\n id: movedID,\n collectionSlug,\n data: {},\n req,\n })\n\n if (accessError) {\n return accessError\n }\n\n const flow = createFlowID('reorder-endpoint')\n const reorderStart = Date.now()\n const hasDrafts = collectionHasDrafts({ collectionSlug, req })\n\n if (!req.context) {\n req.context = {}\n }\n\n // A reorder only writes the order key, never publishing state, so it\n // always carries the deploy opt-out flag.\n req.context[pageTreeMoveContextKey] = true\n req.context[pageTreeWriteContextKey] = true\n req.context[DIAGNOSTICS_FLOW_CONTEXT_KEY] = flow\n\n const relatedDocsResult = await req.payload.find({\n collection: collectionSlug,\n depth: 0,\n draft: hasDrafts ? true : undefined,\n limit: 2,\n locale: getRequestedLocale(req),\n overrideAccess: true,\n req,\n where: {\n id: {\n in: [movedID, targetID],\n },\n },\n })\n const docsByID = new Map(\n (relatedDocsResult.docs as unknown as PageTreeSourceDoc[]).map((doc) => [\n stringifyDocID(doc.id),\n doc,\n ]),\n )\n const movedDoc = docsByID.get(movedIDFromRoute)\n const targetDoc = docsByID.get(body.target.id)\n\n if (!movedDoc) {\n return respond(404, {\n message: 'Document not found.',\n })\n }\n\n if (!targetDoc) {\n return respond(400, {\n message: 'Target document not found.',\n })\n }\n\n const movedParentID = getDocParentID(movedDoc, parentFieldSlug)\n const targetParentID = getDocParentID(targetDoc, parentFieldSlug)\n\n if (movedParentID !== targetParentID) {\n return respond(400, {\n message: 'Documents can only be reordered within the same parent.',\n })\n }\n\n const parentScopeWhere = getParentScopeWhere({\n parentFieldSlug,\n parentID:\n movedParentID === null\n ? null\n : toCollectionID({\n id: movedParentID,\n collectionSlug,\n req,\n }),\n })\n\n if (!body.target.key) {\n return initializeMissingOrderKeys({\n collectionSlug,\n diagnostics,\n flow,\n hasDrafts,\n orderableFieldName,\n parentScopeWhere,\n req,\n })\n }\n\n const beforeSnapshot = await readMainRowSnapshot({\n id: movedID,\n collectionSlug,\n fields: snapshotFields,\n req,\n })\n const backendDraftOrderBefore = diagnostics.enabled\n ? await readBackendSiblingOrder({\n collectionSlug,\n draft: hasDrafts ? true : undefined,\n orderableFieldName,\n parentScopeWhere,\n req,\n })\n : null\n const backendMainOrderBefore = diagnostics.enabled\n ? await readBackendSiblingOrder({\n collectionSlug,\n draft: false,\n orderableFieldName,\n parentScopeWhere,\n req,\n })\n : null\n const adjacentDoc = await req.payload.find({\n collection: collectionSlug,\n depth: 0,\n draft: hasDrafts ? true : undefined,\n limit: 1,\n locale: getRequestedLocale(req),\n overrideAccess: true,\n pagination: false,\n req,\n select: { [orderableFieldName]: true },\n sort: body.newKeyWillBe === 'greater' ? orderableFieldName : `-${orderableFieldName}`,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n [body.newKeyWillBe === 'greater' ? 'greater_than' : 'less_than']: body.target.key,\n },\n },\n parentScopeWhere,\n ]),\n })\n const adjacentDocKey = getOrderableKey(\n adjacentDoc.docs[0] as unknown as PageTreeSourceDoc | undefined,\n orderableFieldName,\n )\n const movedDocKey = getOrderableKey(movedDoc, orderableFieldName)\n const movedSlug = getDiagnosticDocString(movedDoc.slug, getRequestedLocale(req))\n const targetSlug = getDiagnosticDocString(targetDoc.slug, getRequestedLocale(req))\n const movedMainRowKey =\n typeof beforeSnapshot?.[orderableFieldName] === 'string' &&\n beforeSnapshot[orderableFieldName].length > 0\n ? beforeSnapshot[orderableFieldName]\n : movedDocKey\n const { orderValues, usedMovedKeyBoundary } = getOrderValuesBetween({\n adjacentDocKey,\n docsToMoveLength: body.docsToMove.length,\n movedBoundaryKey: movedMainRowKey,\n newKeyWillBe: body.newKeyWillBe,\n targetKey: body.target.key,\n })\n const orderValue = orderValues[0]\n\n if (!orderValue) {\n return respond(500, {\n message: 'Could not generate a new order key.',\n })\n }\n\n if (diagnostics.enabled) {\n diagnostics.log({\n collection: collectionSlug,\n data: {\n adjacentDocKey,\n backendOrderBefore: {\n draft: backendDraftOrderBefore,\n main: backendMainOrderBefore,\n },\n frontendOrder: body.frontendOrder ?? null,\n mainRowBefore: getMainRowOrderSnapshot(beforeSnapshot, orderableFieldName),\n movedDocKey,\n movedMainRowKey,\n movedSlug,\n newKeyWillBe: body.newKeyWillBe,\n orderableFieldName,\n orderValue,\n target: {\n slug: targetSlug,\n key: body.target.key,\n },\n usedMovedKeyBoundary,\n },\n flow,\n level: 'info',\n message: 'reorder endpoint entering: order key update only',\n source: 'reorder-endpoint:enter',\n })\n }\n\n try {\n const updateResult = await updateOrderValueSilently({\n id: movedID,\n collectionSlug,\n hasDrafts,\n orderableFieldName,\n orderValue,\n req,\n })\n\n if (diagnostics.enabled) {\n const afterSnapshot = await readMainRowSnapshot({\n id: movedID,\n collectionSlug,\n fields: snapshotFields,\n req,\n })\n const backendDraftOrderAfter = await readBackendSiblingOrder({\n collectionSlug,\n draft: hasDrafts ? true : undefined,\n orderableFieldName,\n parentScopeWhere,\n req,\n })\n const backendMainOrderAfter = await readBackendSiblingOrder({\n collectionSlug,\n draft: false,\n orderableFieldName,\n parentScopeWhere,\n req,\n })\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n backendOrderAfter: {\n draft: backendDraftOrderAfter,\n main: backendMainOrderAfter,\n },\n durMs: Date.now() - reorderStart,\n mainRowAfter: getMainRowOrderSnapshot(afterSnapshot, orderableFieldName),\n movedSlug,\n orderValue,\n updatedDraftVersion: updateResult.updatedDraftVersion,\n },\n flow,\n level: 'info',\n message: 'reorder endpoint order key update succeeded',\n source: 'reorder-endpoint:ok',\n })\n }\n } catch (err) {\n const error = err as { data?: unknown; message?: string; name?: string } & Error\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n name: error?.name,\n data: error?.data ?? null,\n durMs: Date.now() - reorderStart,\n message: error?.message,\n movedSlug,\n },\n flow,\n level: 'error',\n message: `reorder endpoint order key update failed: ${error?.message ?? 'unknown error'}`,\n source: 'reorder-endpoint:error',\n })\n\n throw err\n }\n\n return respond(200, {\n movedID: movedIDFromRoute,\n orderValues,\n success: true,\n })\n },\n method: 'post',\n path: '/:id/reorder',\n }\n}\n"],"names":["combineWhereConstraints","generateNKeysBetween","pageTreeMoveContextKey","pageTreeWriteContextKey","createFlowID","DIAGNOSTICS_FLOW_CONTEXT_KEY","readMainRowSnapshot","getDocParentID","stringifyDocID","assertUpdateAccess","collectionHasDrafts","getRequestedLocale","normalizeID","respond","toCollectionID","SNAPSHOT_FIELDS","hasOwnProperty","value","key","Object","prototype","call","normalizeOptionalString","length","normalizeFrontendOrderEntry","fallbackIndex","Array","isArray","data","slug","index","Number","isFinite","orderKey","normalizeFrontendOrder","undefined","before","after","slice","map","entry","filter","Boolean","activeSlug","moveFromIndex","moveToIndex","newAfterRowSlug","newBeforeRowSlug","sort","targetSlug","normalizeReorderDocumentBody","incomingData","JSON","parse","target","docsToMove","newKeyWillBe","orderableFieldName","targetData","movedID","targetID","id","frontendOrder","readBodyFromRequest","req","lastAttempt","raw","source","directBody","body","json","jsonBody","text","textBody","getParentScopeWhere","args","parentFieldSlug","parentID","equals","getOrderableKey","doc","getDiagnosticDocString","locale","localizedValue","localeValue","firstString","values","find","getBackendOrderEntry","status","_status","getMainRowOrderSnapshot","snapshot","readBackendSiblingOrder","collectionSlug","draft","parentScopeWhere","result","payload","collection","depth","limit","overrideAccess","pagination","where","docs","getOrderValuesBetween","adjacentDocKey","docsToMoveLength","movedBoundaryKey","targetKey","orderValues","usedMovedKeyBoundary","readLatestVersion","versions","db","findVersions","latest","parent","latestVersion","version","updateLatestVersionOrder","orderValue","updateVersion","returning","versionData","createdAt","publishedLocale","updatedAt","updateOrderValueSilently","hasDrafts","updateOne","updatedDraftVersion","initializeMissingOrderKeys","diagnostics","flow","existingOrderedDocs","select","exists","missingOrderDocs","lastOrderValue","entries","docID","log","initializedCount","level","message","success","createReorderPageEndpoint","snapshotFields","handler","movedIDFromRoute","routeParams","enabled","rawBody","rawBodySource","accessError","reorderStart","Date","now","context","relatedDocsResult","in","docsByID","Map","movedDoc","get","targetDoc","movedParentID","targetParentID","beforeSnapshot","fields","backendDraftOrderBefore","backendMainOrderBefore","adjacentDoc","movedDocKey","movedSlug","movedMainRowKey","backendOrderBefore","main","mainRowBefore","updateResult","afterSnapshot","backendDraftOrderAfter","backendMainOrderAfter","backendOrderAfter","durMs","mainRowAfter","err","error","name","method","path"],"mappings":"AAEA,SAASA,uBAAuB,EAAEC,oBAAoB,QAAQ,iBAAgB;AAE9E,SACEC,sBAAsB,EAEtBC,uBAAuB,QAClB,cAAa;AACpB,SACEC,YAAY,EAEZC,4BAA4B,EAC5BC,mBAAmB,QACd,8BAA6B;AACpC,SAASC,cAAc,EAAEC,cAAc,QAAQ,2BAA0B;AACzE,SACEC,kBAAkB,EAClBC,mBAAmB,EACnBC,kBAAkB,EAClBC,WAAW,EACXC,OAAO,EACPC,cAAc,QACT,cAAa;AAqDpB,MAAMC,kBAAkB;IAAC;CAAU;AAEnC,SAASC,eAAeC,KAAa,EAAEC,GAAgB;IACrD,OAAOC,OAAOC,SAAS,CAACJ,cAAc,CAACK,IAAI,CAACJ,OAAOC;AACrD;AAEA,SAASI,wBAAwBL,KAAc;IAC7C,OAAO,OAAOA,UAAU,YAAYA,MAAMM,MAAM,GAAG,IAAIN,QAAQ;AACjE;AAEA,SAASO,4BACPP,KAAc,EACdQ,aAAqB;IAErB,IAAI,CAACR,SAAS,OAAOA,UAAU,YAAYS,MAAMC,OAAO,CAACV,QAAQ;QAC/D,OAAO;IACT;IAEA,MAAMW,OAAOX;IAEb,OAAO;QACLY,MAAMP,wBAAwBM,KAAKC,IAAI;QACvCC,OAAO,OAAOF,KAAKE,KAAK,KAAK,YAAYC,OAAOC,QAAQ,CAACJ,KAAKE,KAAK,IAAIF,KAAKE,KAAK,GAAGL;QACpFQ,UAAUX,wBAAwBM,KAAKK,QAAQ;IACjD;AACF;AAEA,SAASC,uBAAuBjB,KAAc;IAC5C,IAAI,CAACA,SAAS,OAA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,OAAO3C,WAAW,iBAAiB;oBACzF/E,QAAQ;gBACV;gBAEA,MAAMyH;YACR;YAEA,OAAO/K,QAAQ,KAAK;gBAClB8C,SAAS4F;gBACTxC;gBACAoC,SAAS;YACX;QACF;QACA4C,QAAQ;QACRC,MAAM;IACR;AACF"}
@@ -1,21 +1,8 @@
1
1
  import type { PayloadRequest } from 'payload';
2
- export type PayloadCollectionLike = {
3
- config?: {
4
- access?: {
5
- update?: ((args: Record<string, unknown>) => boolean | Promise<boolean | Record<string, unknown>> | Record<string, unknown>) | undefined;
6
- };
7
- versions?: {
8
- drafts?: {
9
- autosave?: boolean | Record<string, unknown>;
10
- } | boolean;
11
- };
12
- };
13
- customIDType?: string;
14
- };
15
2
  export declare function getPayloadCollection({ collectionSlug, req, }: {
16
3
  collectionSlug: string;
17
4
  req: PayloadRequest;
18
- }): PayloadCollectionLike | undefined;
5
+ }): import("payload").Collection;
19
6
  export declare function getRequestedLocale(req: PayloadRequest): string | undefined;
20
7
  export declare function collectionHasDrafts(args: {
21
8
  collectionSlug: string;
@@ -10,10 +10,7 @@ export function collectionHasDrafts(args) {
10
10
  }
11
11
  export function collectionHasAutosaveDrafts(args) {
12
12
  const drafts = getPayloadCollection(args)?.config?.versions?.drafts;
13
- if (!drafts || drafts === true) {
14
- return false;
15
- }
16
- return Boolean(drafts.autosave);
13
+ return Boolean(drafts && drafts.autosave);
17
14
  }
18
15
  export function normalizeID(value) {
19
16
  if (value === null || value === undefined || value === '') {
@@ -49,8 +46,8 @@ export async function assertUpdateAccess(args) {
49
46
  return null;
50
47
  }
51
48
  const accessResult = await updateAccess({
52
- id: id,
53
- data: data,
49
+ id,
50
+ data,
54
51
  req
55
52
  });
56
53
  if (accessResult === false) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/endpoints/shared.ts"],"sourcesContent":["import type { PayloadRequest, Where } from 'payload'\n\nimport { stringifyDocID } from '../utilities/pageTree.js'\n\nexport type PayloadCollectionLike = {\n config?: {\n access?: {\n update?:\n | ((\n args: Record<string, unknown>,\n ) => boolean | Promise<boolean | Record<string, unknown>> | Record<string, unknown>)\n | undefined\n }\n versions?: {\n drafts?:\n | {\n autosave?: boolean | Record<string, unknown>\n }\n | boolean\n }\n }\n customIDType?: string\n}\n\nexport function getPayloadCollection({\n collectionSlug,\n req,\n}: {\n collectionSlug: string\n req: PayloadRequest\n}): PayloadCollectionLike | undefined {\n return (req.payload.collections as unknown as Record<string, PayloadCollectionLike | undefined>)[\n collectionSlug\n ]\n}\n\nexport function getRequestedLocale(req: PayloadRequest): string | undefined {\n return req.locale && req.locale !== 'all' ? req.locale : undefined\n}\n\nexport function collectionHasDrafts(args: {\n collectionSlug: string\n req: PayloadRequest\n}): boolean {\n return Boolean(getPayloadCollection(args)?.config?.versions?.drafts)\n}\n\nexport function collectionHasAutosaveDrafts(args: {\n collectionSlug: string\n req: PayloadRequest\n}): boolean {\n const drafts = getPayloadCollection(args)?.config?.versions?.drafts\n\n if (!drafts || drafts === true) {\n return false\n }\n\n return Boolean(drafts.autosave)\n}\n\nexport function normalizeID(value: unknown): null | string {\n if (value === null || value === undefined || value === '') {\n return null\n }\n\n if (typeof value === 'number' || typeof value === 'string') {\n return stringifyDocID(value)\n }\n\n return null\n}\n\nexport function respond(status: number, body: Record<string, unknown>) {\n return Response.json(body, { status })\n}\n\nexport function toCollectionID(args: {\n collectionSlug: string\n id: string\n req: PayloadRequest\n}): number | string {\n const { id, collectionSlug, req } = args\n const collection = getPayloadCollection({ collectionSlug, req })\n const idType = collection?.customIDType ?? req.payload.db.defaultIDType\n\n return idType === 'number' ? Number(id) : id\n}\n\nexport async function assertUpdateAccess(args: {\n collectionSlug: string\n data: Record<string, unknown>\n id: number | string\n req: PayloadRequest\n}): Promise<null | Response> {\n const { id, collectionSlug, data, req } = args\n const collection = getPayloadCollection({ collectionSlug, req })\n const updateAccess = collection?.config?.access?.update\n\n if (!updateAccess) {\n return null\n }\n\n const accessResult = await updateAccess({\n id: id as never,\n data: data as never,\n req,\n })\n\n if (accessResult === false) {\n return respond(403, {\n message: req.i18n.t('error:unauthorized'),\n })\n }\n\n if (accessResult && typeof accessResult === 'object') {\n const matchingDocs = await req.payload.find({\n collection: collectionSlug as never,\n depth: 0,\n draft: collectionHasDrafts({ collectionSlug, req }) ? true : undefined,\n limit: 1,\n locale: getRequestedLocale(req) as never,\n overrideAccess: true,\n req,\n where: {\n and: [\n {\n id: {\n equals: id,\n },\n },\n accessResult as Where,\n ],\n } as never,\n } as never)\n\n if (matchingDocs.docs.length === 0) {\n return respond(403, {\n message: req.i18n.t('error:unauthorized'),\n })\n }\n }\n\n return null\n}\n"],"names":["stringifyDocID","getPayloadCollection","collectionSlug","req","payload","collections","getRequestedLocale","locale","undefined","collectionHasDrafts","args","Boolean","config","versions","drafts","collectionHasAutosaveDrafts","autosave","normalizeID","value","respond","status","body","Response","json","toCollectionID","id","collection","idType","customIDType","db","defaultIDType","Number","assertUpdateAccess","data","updateAccess","access","update","accessResult","message","i18n","t","matchingDocs","find","depth","draft","limit","overrideAccess","where","and","equals","docs","length"],"mappings":"AAEA,SAASA,cAAc,QAAQ,2BAA0B;AAsBzD,OAAO,SAASC,qBAAqB,EACnCC,cAAc,EACdC,GAAG,EAIJ;IACC,OAAO,AAACA,IAAIC,OAAO,CAACC,WAAW,AAAiE,CAC9FH,eACD;AACH;AAEA,OAAO,SAASI,mBAAmBH,GAAmB;IACpD,OAAOA,IAAII,MAAM,IAAIJ,IAAII,MAAM,KAAK,QAAQJ,IAAII,MAAM,GAAGC;AAC3D;AAEA,OAAO,SAASC,oBAAoBC,IAGnC;IACC,OAAOC,QAAQV,qBAAqBS,OAAOE,QAAQC,UAAUC;AAC/D;AAEA,OAAO,SAASC,4BAA4BL,IAG3C;IACC,MAAMI,SAASb,qBAAqBS,OAAOE,QAAQC,UAAUC;IAE7D,IAAI,CAACA,UAAUA,WAAW,MAAM;QAC9B,OAAO;IACT;IAEA,OAAOH,QAAQG,OAAOE,QAAQ;AAChC;AAEA,OAA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AQD,mBAAmBH;YAC3B2C,gBAAgB;YAChB3C;YACA4C,OAAO;gBACLC,KAAK;oBACH;wBACEvB,IAAI;4BACFwB,QAAQxB;wBACV;oBACF;oBACAY;iBACD;YACH;QACF;QAEA,IAAII,aAAaS,IAAI,CAACC,MAAM,KAAK,GAAG;YAClC,OAAOhC,QAAQ,KAAK;gBAClBmB,SAASnC,IAAIoC,IAAI,CAACC,CAAC,CAAC;YACtB;QACF;IACF;IAEA,OAAO;AACT"}
1
+ {"version":3,"sources":["../../src/endpoints/shared.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { stringifyDocID } from '../utilities/pageTree.js'\n\nexport function getPayloadCollection({\n collectionSlug,\n req,\n}: {\n collectionSlug: string\n req: PayloadRequest\n}) {\n return req.payload.collections[collectionSlug]\n}\n\nexport function getRequestedLocale(req: PayloadRequest): string | undefined {\n return req.locale && req.locale !== 'all' ? req.locale : undefined\n}\n\nexport function collectionHasDrafts(args: {\n collectionSlug: string\n req: PayloadRequest\n}): boolean {\n return Boolean(getPayloadCollection(args)?.config?.versions?.drafts)\n}\n\nexport function collectionHasAutosaveDrafts(args: {\n collectionSlug: string\n req: PayloadRequest\n}): boolean {\n const drafts = getPayloadCollection(args)?.config?.versions?.drafts\n\n return Boolean(drafts && drafts.autosave)\n}\n\nexport function normalizeID(value: unknown): null | string {\n if (value === null || value === undefined || value === '') {\n return null\n }\n\n if (typeof value === 'number' || typeof value === 'string') {\n return stringifyDocID(value)\n }\n\n return null\n}\n\nexport function respond(status: number, body: Record<string, unknown>) {\n return Response.json(body, { status })\n}\n\nexport function toCollectionID(args: {\n collectionSlug: string\n id: string\n req: PayloadRequest\n}): number | string {\n const { id, collectionSlug, req } = args\n const collection = getPayloadCollection({ collectionSlug, req })\n const idType = collection?.customIDType ?? req.payload.db.defaultIDType\n\n return idType === 'number' ? Number(id) : id\n}\n\nexport async function assertUpdateAccess(args: {\n collectionSlug: string\n data: Record<string, unknown>\n id: number | string\n req: PayloadRequest\n}): Promise<null | Response> {\n const { id, collectionSlug, data, req } = args\n const collection = getPayloadCollection({ collectionSlug, req })\n const updateAccess = collection?.config?.access?.update\n\n if (!updateAccess) {\n return null\n }\n\n const accessResult = await updateAccess({\n id,\n data,\n req,\n })\n\n if (accessResult === false) {\n return respond(403, {\n message: req.i18n.t('error:unauthorized'),\n })\n }\n\n if (accessResult && typeof accessResult === 'object') {\n const matchingDocs = await req.payload.find({\n collection: collectionSlug,\n depth: 0,\n draft: collectionHasDrafts({ collectionSlug, req }) ? true : undefined,\n limit: 1,\n locale: getRequestedLocale(req),\n overrideAccess: true,\n req,\n where: {\n and: [\n {\n id: {\n equals: id,\n },\n },\n accessResult,\n ],\n },\n })\n\n if (matchingDocs.docs.length === 0) {\n return respond(403, {\n message: req.i18n.t('error:unauthorized'),\n })\n }\n }\n\n return null\n}\n"],"names":["stringifyDocID","getPayloadCollection","collectionSlug","req","payload","collections","getRequestedLocale","locale","undefined","collectionHasDrafts","args","Boolean","config","versions","drafts","collectionHasAutosaveDrafts","autosave","normalizeID","value","respond","status","body","Response","json","toCollectionID","id","collection","idType","customIDType","db","defaultIDType","Number","assertUpdateAccess","data","updateAccess","access","update","accessResult","message","i18n","t","matchingDocs","find","depth","draft","limit","overrideAccess","where","and","equals","docs","length"],"mappings":"AAEA,SAASA,cAAc,QAAQ,2BAA0B;AAEzD,OAAO,SAASC,qBAAqB,EACnCC,cAAc,EACdC,GAAG,EAIJ;IACC,OAAOA,IAAIC,OAAO,CAACC,WAAW,CAACH,eAAe;AAChD;AAEA,OAAO,SAASI,mBAAmBH,GAAmB;IACpD,OAAOA,IAAII,MAAM,IAAIJ,IAAII,MAAM,KAAK,QAAQJ,IAAII,MAAM,GAAGC;AAC3D;AAEA,OAAO,SAASC,oBAAoBC,IAGnC;IACC,OAAOC,QAAQV,qBAAqBS,OAAOE,QAAQC,UAAUC;AAC/D;AAEA,OAAO,SAASC,4BAA4BL,IAG3C;IACC,MAAMI,SAASb,qBAAqBS,OAA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;gBAAEP;gBAAgBC;YAAI,KAAK,OAAOK;YAC7DqC,OAAO;YACPtC,QAAQD,mBAAmBH;YAC3B2C,gBAAgB;YAChB3C;YACA4C,OAAO;gBACLC,KAAK;oBACH;wBACEvB,IAAI;4BACFwB,QAAQxB;wBACV;oBACF;oBACAY;iBACD;YACH;QACF;QAEA,IAAII,aAAaS,IAAI,CAACC,MAAM,KAAK,GAAG;YAClC,OAAOhC,QAAQ,KAAK;gBAClBmB,SAASnC,IAAIoC,IAAI,CAACC,CAAC,CAAC;YACtB;QACF;IACF;IAEA,OAAO;AACT"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Config } from 'payload';
2
2
  import type { NestedDocsPageTreePluginConfig } from './types.js';
3
- export type { NestedDocsPageTreePluginBadgeConfig, NestedDocsPageTreePluginBadgeMap, NestedDocsPageTreePluginBadgeStatus, NestedDocsPageTreePluginConfig, NestedDocsPageTreePluginHomeIndicatorConfig, PageTreeMoveContext, } from './types.js';
3
+ export type { NestedDocsPageTreePluginBadgeConfig, NestedDocsPageTreePluginBadgeMap, NestedDocsPageTreePluginBadgesLinks, NestedDocsPageTreePluginBadgeStatus, NestedDocsPageTreePluginConfig, NestedDocsPageTreePluginHomeIndicatorConfig, PageTreeMoveContext, } from './types.js';
4
4
  export { pageTreeMoveContextKey } from './types.js';
5
5
  export declare const nestedDocsPageTreePlugin: (pluginOptions: NestedDocsPageTreePluginConfig) => (config: Config) => Config;
package/dist/index.js CHANGED
@@ -132,9 +132,10 @@ function validateTargetCollection(args) {
132
132
  }
133
133
  }
134
134
  function buildCollectionCustom(args) {
135
- const { badges, breadcrumbsFieldSlug, defaultLimit, hideBreadcrumbs, homeIndicator, parentFieldSlug } = args;
135
+ const { badges, badgesLinks, breadcrumbsFieldSlug, defaultLimit, hideBreadcrumbs, homeIndicator, parentFieldSlug } = args;
136
136
  return {
137
137
  badges,
138
+ badgesLinks,
138
139
  breadcrumbsFieldSlug,
139
140
  defaultLimit,
140
141
  hideBreadcrumbs,
@@ -209,6 +210,7 @@ export const nestedDocsPageTreePlugin = (pluginOptions)=>(config)=>{
209
210
  ...collection.custom ?? {},
210
211
  [nestedDocsPageTreePluginCustomKey]: buildCollectionCustom({
211
212
  badges,
213
+ badgesLinks: pluginOptions.badgesLinks,
212
214
  breadcrumbsFieldSlug,
213
215
  defaultLimit,
214
216
  hideBreadcrumbs,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n CollectionAfterChangeHook,\n CollectionConfig,\n Config,\n} from 'payload'\n\nimport { createMovePageEndpoint } from './endpoints/createMovePageEndpoint.js'\nimport { createReorderPageEndpoint } from './endpoints/createReorderPageEndpoint.js'\nimport type {\n NestedDocsPageTreePluginCollectionCustom,\n NestedDocsPageTreePluginConfig,\n} from './types.js'\nimport { nestedDocsPageTreePluginCustomKey, pageTreeWriteContextKey } from './types.js'\nimport { normalizeNestedDocsPageTreePluginBadgeConfig } from './utilities/badgeConfig.js'\nimport {\n DIAGNOSTICS_FLOW_CONTEXT_KEY,\n type Diagnostics,\n createFlowID,\n projectField,\n resolveDiagnostics,\n} from './utilities/diagnostics.js'\nimport { findTopLevelField, mapTopLevelFields } from './utilities/fields.js'\n\nconst DEFAULT_BREADCRUMBS_FIELD_SLUG = 'breadcrumbs'\nconst DEFAULT_HOME_INDICATOR_COLLECTIONS = ['pages']\nconst DEFAULT_LIMIT = 100\nconst DEFAULT_PARENT_FIELD_SLUG = 'parent'\nconst PAGE_TREE_LIST_VIEW_PATH =\n 'payload-nested-docs-page-tree/rsc#NestedDocsPageTreeListView'\ntype CollectionEndpoint = NonNullable<Exclude<CollectionConfig['endpoints'], false>>[number]\n\n/**\n * When diagnostics are enabled this hook emits a structured event for each\n * page-tree-tagged create/update, including a small before/after diff of the\n * fields most relevant to tree publish/draft regressions.\n */\nfunction createDiagnosticsAfterChangeHook(args: {\n collectionSlug: string\n diagnostics: Diagnostics\n orderableFieldName: null | string\n parentFieldSlug: string\n}): CollectionAfterChangeHook {\n const { collectionSlug, diagnostics, orderableFieldName, parentFieldSlug } = args\n const snapshotFields: string[] = ['_status', parentFieldSlug]\n\n if (orderableFieldName) {\n snapshotFields.push(orderableFieldName)\n }\n\n return async ({ doc, operation, previousDoc, req }) => {\n if (!diagnostics.enabled) {\n return doc\n }\n\n if (operation !== 'update' && operation !== 'create') {\n return doc\n }\n\n // Gated on the write flag, not the deploy opt-out flag: a published move\n // withholds the latter, and that is the case most worth tracing.\n if (!req.context?.[pageTreeWriteContextKey]) {\n return doc\n }\n\n const docID = (doc as Record<string, unknown>)?.id\n\n if (typeof docID !== 'string' && typeof docID !== 'number') {\n return doc\n }\n\n const flow =\n (req.context?.[DIAGNOSTICS_FLOW_CONTEXT_KEY] as string | undefined) ??\n createFlowID('page-tree-change')\n const before: Record<string, unknown> = {}\n const after: Record<string, unknown> = {}\n const changed: string[] = []\n\n for (const field of snapshotFields) {\n const beforeValue = projectField((previousDoc as Record<string, unknown> | undefined)?.[field])\n const afterValue = projectField((doc as Record<string, unknown>)?.[field])\n\n before[field] = beforeValue\n after[field] = afterValue\n\n if (JSON.stringify(beforeValue) !== JSON.stringify(afterValue)) {\n changed.push(field)\n }\n }\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n after,\n before,\n changed,\n docID: String(docID),\n operation,\n },\n flow,\n level: 'info',\n message: `${operation} on ${collectionSlug}#${String(docID)}`,\n source: 'page-tree-change:after',\n })\n\n const beforeStatus = (previousDoc as Record<string, unknown> | undefined)?._status\n const afterStatus = (doc as Record<string, unknown>)?._status\n\n if (beforeStatus === 'published' && afterStatus !== 'published') {\n diagnostics.log({\n collection: collectionSlug,\n data: {\n afterStatus,\n beforeStatus,\n docID: String(docID),\n },\n flow,\n level: 'warn',\n message: `Published doc was demoted to \"${String(afterStatus ?? 'missing')}\" by a page-tree operation. Inspect the move-endpoint:enter/ok snapshots in flow ${flow} to confirm whether the main row was touched.`,\n source: 'page-tree-change:status-flip',\n })\n }\n\n return doc\n }\n}\n\nfunction getCollectionEndpoints(collection: CollectionConfig): CollectionEndpoint[] {\n return Array.isArray(collection.endpoints) ? [...collection.endpoints] : []\n}\n\nfunction patchBreadcrumbField<TField extends CollectionConfig['fields'][number]>(args: {\n breadcrumbsFieldSlug: string\n field: TField\n hideBreadcrumbs: boolean\n}): TField {\n const { breadcrumbsFieldSlug, field, hideBreadcrumbs } = args\n\n if (!('name' in field) || field.name !== breadcrumbsFieldSlug) {\n return field\n }\n\n return {\n ...field,\n admin: {\n ...(field.admin ?? {}),\n hidden: hideBreadcrumbs,\n },\n } as TField\n}\n\nfunction validateTargetCollection(args: {\n breadcrumbsFieldSlug: string\n collection: CollectionConfig\n parentFieldSlug: string\n}) {\n const { breadcrumbsFieldSlug, collection, parentFieldSlug } = args\n\n if (typeof collection.admin?.useAsTitle !== 'string' || collection.admin.useAsTitle.includes('.')) {\n throw new Error(\n `payload-nested-docs-page-tree requires \"${collection.slug}\" to define a top-level admin.useAsTitle field.`,\n )\n }\n\n if (!findTopLevelField(collection.fields, collection.admin.useAsTitle)) {\n throw new Error(\n `payload-nested-docs-page-tree could not find the useAsTitle field \"${collection.admin.useAsTitle}\" on \"${collection.slug}\". Fields inside tabs, rows, collapsibles, and unnamed groups are supported; fields inside a named tab or named group are not top-level.`,\n )\n }\n\n if (!findTopLevelField(collection.fields, parentFieldSlug)) {\n throw new Error(\n `payload-nested-docs-page-tree requires \"${collection.slug}\" to already define the nested docs parent field \"${parentFieldSlug}\". Register @payloadcms/plugin-nested-docs before payload-nested-docs-page-tree.`,\n )\n }\n\n if (!findTopLevelField(collection.fields, breadcrumbsFieldSlug)) {\n throw new Error(\n `payload-nested-docs-page-tree requires \"${collection.slug}\" to already define the nested docs breadcrumbs field \"${breadcrumbsFieldSlug}\". Register @payloadcms/plugin-nested-docs before payload-nested-docs-page-tree.`,\n )\n }\n\n const existingListView = collection.admin?.components?.views?.list?.Component\n\n if (existingListView && existingListView !== PAGE_TREE_LIST_VIEW_PATH) {\n throw new Error(\n `payload-nested-docs-page-tree cannot own the \"${collection.slug}\" list view because the collection already defines a custom admin.components.views.list.Component.`,\n )\n }\n\n const existingMoveEndpoint = getCollectionEndpoints(collection).find(\n (endpoint) => endpoint.path === '/:id/move',\n )\n const existingReorderEndpoint = getCollectionEndpoints(collection).find(\n (endpoint) => endpoint.path === '/:id/reorder',\n )\n\n if (existingMoveEndpoint) {\n throw new Error(\n `payload-nested-docs-page-tree cannot add the move endpoint to \"${collection.slug}\" because the collection already defines POST /:id/move.`,\n )\n }\n\n if (existingReorderEndpoint) {\n throw new Error(\n `payload-nested-docs-page-tree cannot add the reorder endpoint to \"${collection.slug}\" because the collection already defines POST /:id/reorder.`,\n )\n }\n}\n\nfunction buildCollectionCustom(args: {\n badges: NestedDocsPageTreePluginCollectionCustom['badges']\n breadcrumbsFieldSlug: string\n defaultLimit: number\n hideBreadcrumbs: boolean\n homeIndicator: NestedDocsPageTreePluginCollectionCustom['homeIndicator']\n parentFieldSlug: string\n}): NestedDocsPageTreePluginCollectionCustom {\n const {\n badges,\n breadcrumbsFieldSlug,\n defaultLimit,\n hideBreadcrumbs,\n homeIndicator,\n parentFieldSlug,\n } = args\n\n return {\n badges,\n breadcrumbsFieldSlug,\n defaultLimit,\n hideBreadcrumbs,\n homeIndicator,\n parentFieldSlug,\n }\n}\n\nfunction getHomeIndicatorCollectionSlugs(\n homeIndicator: NestedDocsPageTreePluginConfig['homeIndicator'],\n): Set<string> {\n if (homeIndicator === false) {\n return new Set()\n }\n\n return new Set(homeIndicator?.collections ?? DEFAULT_HOME_INDICATOR_COLLECTIONS)\n}\n\nexport type {\n NestedDocsPageTreePluginBadgeConfig,\n NestedDocsPageTreePluginBadgeMap,\n NestedDocsPageTreePluginBadgeStatus,\n NestedDocsPageTreePluginConfig,\n NestedDocsPageTreePluginHomeIndicatorConfig,\n PageTreeMoveContext,\n} from './types.js'\n\nexport { pageTreeMoveContextKey } from './types.js'\n\nexport const nestedDocsPageTreePlugin =\n (pluginOptions: NestedDocsPageTreePluginConfig) =>\n (config: Config): Config => {\n if (!pluginOptions.collections?.length) {\n throw new Error('payload-nested-docs-page-tree requires at least one collection slug.')\n }\n\n if (pluginOptions.disabled) {\n return config\n }\n\n const breadcrumbsFieldSlug =\n pluginOptions.breadcrumbsFieldSlug ?? DEFAULT_BREADCRUMBS_FIELD_SLUG\n const defaultLimit = pluginOptions.defaultLimit ?? DEFAULT_LIMIT\n const hideBreadcrumbs = pluginOptions.hideBreadcrumbs ?? true\n const parentFieldSlug = pluginOptions.parentFieldSlug ?? DEFAULT_PARENT_FIELD_SLUG\n const publishOnMove = pluginOptions.publishOnMove ?? false\n const badges = normalizeNestedDocsPageTreePluginBadgeConfig(pluginOptions.badges)\n const diagnostics = resolveDiagnostics(pluginOptions.diagnostics)\n const homeIndicatorCollectionSlugs = getHomeIndicatorCollectionSlugs(\n pluginOptions.homeIndicator,\n )\n const targetedCollectionSlugs = new Set<string>(pluginOptions.collections)\n\n if (!config.collections?.length) {\n throw new Error('payload-nested-docs-page-tree could not find any collections to patch.')\n }\n\n const foundCollectionSlugs = new Set<string>()\n const nextCollections = config.collections.map((collection) => {\n if (!targetedCollectionSlugs.has(collection.slug)) {\n return collection\n }\n\n foundCollectionSlugs.add(collection.slug)\n validateTargetCollection({\n breadcrumbsFieldSlug,\n collection,\n parentFieldSlug,\n })\n const orderableFieldName =\n typeof collection.orderable === 'string'\n ? collection.orderable\n : collection.orderable\n ? '_order'\n : null\n const diagnosticsAfterChangeHook = diagnostics.enabled\n ? createDiagnosticsAfterChangeHook({\n collectionSlug: collection.slug,\n diagnostics,\n orderableFieldName,\n parentFieldSlug,\n })\n : null\n\n return {\n ...collection,\n admin: {\n ...(collection.admin ?? {}),\n components: {\n ...(collection.admin?.components ?? {}),\n views: {\n ...(collection.admin?.components?.views ?? {}),\n list: {\n ...(collection.admin?.components?.views?.list ?? {}),\n Component: PAGE_TREE_LIST_VIEW_PATH,\n },\n },\n },\n pagination: {\n ...(collection.admin?.pagination ?? {}),\n defaultLimit:\n collection.admin?.pagination?.defaultLimit === undefined\n ? defaultLimit\n : collection.admin.pagination.defaultLimit,\n },\n },\n custom: {\n ...(collection.custom ?? {}),\n [nestedDocsPageTreePluginCustomKey]: buildCollectionCustom({\n badges,\n breadcrumbsFieldSlug,\n defaultLimit,\n hideBreadcrumbs,\n homeIndicator: {\n enabled: homeIndicatorCollectionSlugs.has(collection.slug),\n },\n parentFieldSlug,\n }),\n },\n endpoints: [\n ...getCollectionEndpoints(collection),\n createMovePageEndpoint({\n collectionSlug: collection.slug,\n diagnostics,\n parentFieldSlug,\n publishOnMove,\n }),\n ...(orderableFieldName\n ? [\n createReorderPageEndpoint({\n collectionSlug: collection.slug,\n diagnostics,\n orderableFieldName,\n parentFieldSlug,\n }),\n ]\n : []),\n ],\n fields: mapTopLevelFields(collection.fields, (field) =>\n patchBreadcrumbField({\n breadcrumbsFieldSlug,\n field,\n hideBreadcrumbs,\n }),\n ),\n hooks: {\n ...(collection.hooks ?? {}),\n ...(diagnosticsAfterChangeHook\n ? {\n afterChange: [\n ...(collection.hooks?.afterChange ?? []),\n diagnosticsAfterChangeHook,\n ],\n }\n : {}),\n },\n }\n })\n\n const missingCollections = pluginOptions.collections.filter(\n (collectionSlug) => !foundCollectionSlugs.has(collectionSlug),\n )\n\n if (missingCollections.length > 0) {\n throw new Error(\n `payload-nested-docs-page-tree could not find the following collections: ${missingCollections.join(', ')}`,\n )\n }\n\n return {\n ...config,\n collections: nextCollections as CollectionConfig[],\n }\n }\n"],"names":["createMovePageEndpoint","createReorderPageEndpoint","nestedDocsPageTreePluginCustomKey","pageTreeWriteContextKey","normalizeNestedDocsPageTreePluginBadgeConfig","DIAGNOSTICS_FLOW_CONTEXT_KEY","createFlowID","projectField","resolveDiagnostics","findTopLevelField","mapTopLevelFields","DEFAULT_BREADCRUMBS_FIELD_SLUG","DEFAULT_HOME_INDICATOR_COLLECTIONS","DEFAULT_LIMIT","DEFAULT_PARENT_FIELD_SLUG","PAGE_TREE_LIST_VIEW_PATH","createDiagnosticsAfterChangeHook","args","collectionSlug","diagnostics","orderableFieldName","parentFieldSlug","snapshotFields","push","doc","operation","previousDoc","req","enabled","context","docID","id","flow","before","after","changed","field","beforeValue","afterValue","JSON","stringify","log","collection","data","String","level","message","source","beforeStatus","_status","afterStatus","getCollectionEndpoints","Array","isArray","endpoints","patchBreadcrumbField","breadcrumbsFieldSlug","hideBreadcrumbs","name","admin","hidden","validateTargetCollection","useAsTitle","includes","Error","slug","fields","existingListView","components","views","list","Component","existingMoveEndpoint","find","endpoint","path","existingReorderEndpoint","buildCollectionCustom","badges","defaultLimit","homeIndicator","getHomeIndicatorCollectionSlugs","Set","collections","pageTreeMoveContextKey","nestedDocsPageTreePlugin","pluginOptions","config","length","disabled","publishOnMove","homeIndicatorCollectionSlugs","targetedCollectionSlugs","foundCollectionSlugs","nextCollections","map","has","add","orderable","diagnosticsAfterChangeHook","pagination","undefined","custom","hooks","afterChange","missingCollections","filter","join"],"mappings":"AAMA,SAASA,sBAAsB,QAAQ,wCAAuC;AAC9E,SAASC,yBAAyB,QAAQ,2CAA0C;AAKpF,SAASC,iCAAiC,EAAEC,uBAAuB,QAAQ,aAAY;AACvF,SAASC,4CAA4C,QAAQ,6BAA4B;AACzF,SACEC,4BAA4B,EAE5BC,YAAY,EACZC,YAAY,EACZC,kBAAkB,QACb,6BAA4B;AACnC,SAASC,iBAAiB,EAAEC,iBAAiB,QAAQ,wBAAuB;AAE5E,MAAMC,iCAAiC;AACvC,MAAMC,qCAAqC;IAAC;CAAQ;AACpD,MAAMC,gBAAgB;AACtB,MAAMC,4BAA4B;AAClC,MAAMC,2BACJ;AAGF;;;;CAIC,GACD,SAASC,iCAAiCC,IAKzC;IACC,MAAM,EAAEC,cAAc,EAAEC,WAAW,EAAEC,kBAAkB,EAAEC,eAAe,EAAE,GAAGJ;IAC7E,MAAMK,iBAA2B;QAAC;QAAWD;KAAgB;IAE7D,IAAID,oBAAoB;Q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,6BACA;wBACEK,aAAa;+BACP9D,WAAW6D,KAAK,EAAEC,eAAe,EAAE;4BACvCL;yBACD;oBACH,IACA,CAAC,CAAC;gBACR;YACF;QACF;QAEA,MAAMM,qBAAqBnB,cAAcH,WAAW,CAACuB,MAAM,CACzD,CAACxF,iBAAmB,CAAC2E,qBAAqBG,GAAG,CAAC9E;QAGhD,IAAIuF,mBAAmBjB,MAAM,GAAG,GAAG;YACjC,MAAM,IAAIxB,MACR,CAAC,wEAAwE,EAAEyC,mBAAmBE,IAAI,CAAC,OAAO;QAE9G;QAEA,OAAO;YACL,GAAGpB,MAAM;YACTJ,aAAaW;QACf;IACF,EAAC"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n CollectionAfterChangeHook,\n CollectionConfig,\n Config,\n} from 'payload'\n\nimport { createMovePageEndpoint } from './endpoints/createMovePageEndpoint.js'\nimport { createReorderPageEndpoint } from './endpoints/createReorderPageEndpoint.js'\nimport type {\n NestedDocsPageTreePluginCollectionCustom,\n NestedDocsPageTreePluginConfig,\n} from './types.js'\nimport { nestedDocsPageTreePluginCustomKey, pageTreeWriteContextKey } from './types.js'\nimport { normalizeNestedDocsPageTreePluginBadgeConfig } from './utilities/badgeConfig.js'\nimport {\n DIAGNOSTICS_FLOW_CONTEXT_KEY,\n type Diagnostics,\n createFlowID,\n projectField,\n resolveDiagnostics,\n} from './utilities/diagnostics.js'\nimport { findTopLevelField, mapTopLevelFields } from './utilities/fields.js'\n\nconst DEFAULT_BREADCRUMBS_FIELD_SLUG = 'breadcrumbs'\nconst DEFAULT_HOME_INDICATOR_COLLECTIONS = ['pages']\nconst DEFAULT_LIMIT = 100\nconst DEFAULT_PARENT_FIELD_SLUG = 'parent'\nconst PAGE_TREE_LIST_VIEW_PATH =\n 'payload-nested-docs-page-tree/rsc#NestedDocsPageTreeListView'\ntype CollectionEndpoint = NonNullable<Exclude<CollectionConfig['endpoints'], false>>[number]\n\n/**\n * When diagnostics are enabled this hook emits a structured event for each\n * page-tree-tagged create/update, including a small before/after diff of the\n * fields most relevant to tree publish/draft regressions.\n */\nfunction createDiagnosticsAfterChangeHook(args: {\n collectionSlug: string\n diagnostics: Diagnostics\n orderableFieldName: null | string\n parentFieldSlug: string\n}): CollectionAfterChangeHook {\n const { collectionSlug, diagnostics, orderableFieldName, parentFieldSlug } = args\n const snapshotFields: string[] = ['_status', parentFieldSlug]\n\n if (orderableFieldName) {\n snapshotFields.push(orderableFieldName)\n }\n\n return async ({ doc, operation, previousDoc, req }) => {\n if (!diagnostics.enabled) {\n return doc\n }\n\n if (operation !== 'update' && operation !== 'create') {\n return doc\n }\n\n // Gated on the write flag, not the deploy opt-out flag: a published move\n // withholds the latter, and that is the case most worth tracing.\n if (!req.context?.[pageTreeWriteContextKey]) {\n return doc\n }\n\n const docID = (doc as Record<string, unknown>)?.id\n\n if (typeof docID !== 'string' && typeof docID !== 'number') {\n return doc\n }\n\n const flow =\n (req.context?.[DIAGNOSTICS_FLOW_CONTEXT_KEY] as string | undefined) ??\n createFlowID('page-tree-change')\n const before: Record<string, unknown> = {}\n const after: Record<string, unknown> = {}\n const changed: string[] = []\n\n for (const field of snapshotFields) {\n const beforeValue = projectField((previousDoc as Record<string, unknown> | undefined)?.[field])\n const afterValue = projectField((doc as Record<string, unknown>)?.[field])\n\n before[field] = beforeValue\n after[field] = afterValue\n\n if (JSON.stringify(beforeValue) !== JSON.stringify(afterValue)) {\n changed.push(field)\n }\n }\n\n diagnostics.log({\n collection: collectionSlug,\n data: {\n after,\n before,\n changed,\n docID: String(docID),\n operation,\n },\n flow,\n level: 'info',\n message: `${operation} on ${collectionSlug}#${String(docID)}`,\n source: 'page-tree-change:after',\n })\n\n const beforeStatus = (previousDoc as Record<string, unknown> | undefined)?._status\n const afterStatus = (doc as Record<string, unknown>)?._status\n\n if (beforeStatus === 'published' && afterStatus !== 'published') {\n diagnostics.log({\n collection: collectionSlug,\n data: {\n afterStatus,\n beforeStatus,\n docID: String(docID),\n },\n flow,\n level: 'warn',\n message: `Published doc was demoted to \"${String(afterStatus ?? 'missing')}\" by a page-tree operation. Inspect the move-endpoint:enter/ok snapshots in flow ${flow} to confirm whether the main row was touched.`,\n source: 'page-tree-change:status-flip',\n })\n }\n\n return doc\n }\n}\n\nfunction getCollectionEndpoints(collection: CollectionConfig): CollectionEndpoint[] {\n return Array.isArray(collection.endpoints) ? [...collection.endpoints] : []\n}\n\nfunction patchBreadcrumbField<TField extends CollectionConfig['fields'][number]>(args: {\n breadcrumbsFieldSlug: string\n field: TField\n hideBreadcrumbs: boolean\n}): TField {\n const { breadcrumbsFieldSlug, field, hideBreadcrumbs } = args\n\n if (!('name' in field) || field.name !== breadcrumbsFieldSlug) {\n return field\n }\n\n return {\n ...field,\n admin: {\n ...(field.admin ?? {}),\n hidden: hideBreadcrumbs,\n },\n } as TField\n}\n\nfunction validateTargetCollection(args: {\n breadcrumbsFieldSlug: string\n collection: CollectionConfig\n parentFieldSlug: string\n}) {\n const { breadcrumbsFieldSlug, collection, parentFieldSlug } = args\n\n if (typeof collection.admin?.useAsTitle !== 'string' || collection.admin.useAsTitle.includes('.')) {\n throw new Error(\n `payload-nested-docs-page-tree requires \"${collection.slug}\" to define a top-level admin.useAsTitle field.`,\n )\n }\n\n if (!findTopLevelField(collection.fields, collection.admin.useAsTitle)) {\n throw new Error(\n `payload-nested-docs-page-tree could not find the useAsTitle field \"${collection.admin.useAsTitle}\" on \"${collection.slug}\". Fields inside tabs, rows, collapsibles, and unnamed groups are supported; fields inside a named tab or named group are not top-level.`,\n )\n }\n\n if (!findTopLevelField(collection.fields, parentFieldSlug)) {\n throw new Error(\n `payload-nested-docs-page-tree requires \"${collection.slug}\" to already define the nested docs parent field \"${parentFieldSlug}\". Register @payloadcms/plugin-nested-docs before payload-nested-docs-page-tree.`,\n )\n }\n\n if (!findTopLevelField(collection.fields, breadcrumbsFieldSlug)) {\n throw new Error(\n `payload-nested-docs-page-tree requires \"${collection.slug}\" to already define the nested docs breadcrumbs field \"${breadcrumbsFieldSlug}\". Register @payloadcms/plugin-nested-docs before payload-nested-docs-page-tree.`,\n )\n }\n\n const existingListView = collection.admin?.components?.views?.list?.Component\n\n if (existingListView && existingListView !== PAGE_TREE_LIST_VIEW_PATH) {\n throw new Error(\n `payload-nested-docs-page-tree cannot own the \"${collection.slug}\" list view because the collection already defines a custom admin.components.views.list.Component.`,\n )\n }\n\n const existingMoveEndpoint = getCollectionEndpoints(collection).find(\n (endpoint) => endpoint.path === '/:id/move',\n )\n const existingReorderEndpoint = getCollectionEndpoints(collection).find(\n (endpoint) => endpoint.path === '/:id/reorder',\n )\n\n if (existingMoveEndpoint) {\n throw new Error(\n `payload-nested-docs-page-tree cannot add the move endpoint to \"${collection.slug}\" because the collection already defines POST /:id/move.`,\n )\n }\n\n if (existingReorderEndpoint) {\n throw new Error(\n `payload-nested-docs-page-tree cannot add the reorder endpoint to \"${collection.slug}\" because the collection already defines POST /:id/reorder.`,\n )\n }\n}\n\nfunction buildCollectionCustom(args: {\n badges: NestedDocsPageTreePluginCollectionCustom['badges']\n badgesLinks?: NestedDocsPageTreePluginConfig['badgesLinks']\n breadcrumbsFieldSlug: string\n defaultLimit: number\n hideBreadcrumbs: boolean\n homeIndicator: NestedDocsPageTreePluginCollectionCustom['homeIndicator']\n parentFieldSlug: string\n}): NestedDocsPageTreePluginCollectionCustom {\n const {\n badges,\n badgesLinks,\n breadcrumbsFieldSlug,\n defaultLimit,\n hideBreadcrumbs,\n homeIndicator,\n parentFieldSlug,\n } = args\n\n return {\n badges,\n badgesLinks,\n breadcrumbsFieldSlug,\n defaultLimit,\n hideBreadcrumbs,\n homeIndicator,\n parentFieldSlug,\n }\n}\n\nfunction getHomeIndicatorCollectionSlugs(\n homeIndicator: NestedDocsPageTreePluginConfig['homeIndicator'],\n): Set<string> {\n if (homeIndicator === false) {\n return new Set()\n }\n\n return new Set(homeIndicator?.collections ?? DEFAULT_HOME_INDICATOR_COLLECTIONS)\n}\n\nexport type {\n NestedDocsPageTreePluginBadgeConfig,\n NestedDocsPageTreePluginBadgeMap,\n NestedDocsPageTreePluginBadgesLinks,\n NestedDocsPageTreePluginBadgeStatus,\n NestedDocsPageTreePluginConfig,\n NestedDocsPageTreePluginHomeIndicatorConfig,\n PageTreeMoveContext,\n} from './types.js'\n\nexport { pageTreeMoveContextKey } from './types.js'\n\nexport const nestedDocsPageTreePlugin =\n (pluginOptions: NestedDocsPageTreePluginConfig) =>\n (config: Config): Config => {\n if (!pluginOptions.collections?.length) {\n throw new Error('payload-nested-docs-page-tree requires at least one collection slug.')\n }\n\n if (pluginOptions.disabled) {\n return config\n }\n\n const breadcrumbsFieldSlug =\n pluginOptions.breadcrumbsFieldSlug ?? DEFAULT_BREADCRUMBS_FIELD_SLUG\n const defaultLimit = pluginOptions.defaultLimit ?? DEFAULT_LIMIT\n const hideBreadcrumbs = pluginOptions.hideBreadcrumbs ?? true\n const parentFieldSlug = pluginOptions.parentFieldSlug ?? DEFAULT_PARENT_FIELD_SLUG\n const publishOnMove = pluginOptions.publishOnMove ?? false\n const badges = normalizeNestedDocsPageTreePluginBadgeConfig(pluginOptions.badges)\n const diagnostics = resolveDiagnostics(pluginOptions.diagnostics)\n const homeIndicatorCollectionSlugs = getHomeIndicatorCollectionSlugs(\n pluginOptions.homeIndicator,\n )\n const targetedCollectionSlugs = new Set<string>(pluginOptions.collections)\n\n if (!config.collections?.length) {\n throw new Error('payload-nested-docs-page-tree could not find any collections to patch.')\n }\n\n const foundCollectionSlugs = new Set<string>()\n const nextCollections = config.collections.map((collection) => {\n if (!targetedCollectionSlugs.has(collection.slug)) {\n return collection\n }\n\n foundCollectionSlugs.add(collection.slug)\n validateTargetCollection({\n breadcrumbsFieldSlug,\n collection,\n parentFieldSlug,\n })\n const orderableFieldName =\n typeof collection.orderable === 'string'\n ? collection.orderable\n : collection.orderable\n ? '_order'\n : null\n const diagnosticsAfterChangeHook = diagnostics.enabled\n ? createDiagnosticsAfterChangeHook({\n collectionSlug: collection.slug,\n diagnostics,\n orderableFieldName,\n parentFieldSlug,\n })\n : null\n\n return {\n ...collection,\n admin: {\n ...(collection.admin ?? {}),\n components: {\n ...(collection.admin?.components ?? {}),\n views: {\n ...(collection.admin?.components?.views ?? {}),\n list: {\n ...(collection.admin?.components?.views?.list ?? {}),\n Component: PAGE_TREE_LIST_VIEW_PATH,\n },\n },\n },\n pagination: {\n ...(collection.admin?.pagination ?? {}),\n defaultLimit:\n collection.admin?.pagination?.defaultLimit === undefined\n ? defaultLimit\n : collection.admin.pagination.defaultLimit,\n },\n },\n custom: {\n ...(collection.custom ?? {}),\n [nestedDocsPageTreePluginCustomKey]: buildCollectionCustom({\n badges,\n badgesLinks: pluginOptions.badgesLinks,\n breadcrumbsFieldSlug,\n defaultLimit,\n hideBreadcrumbs,\n homeIndicator: {\n enabled: homeIndicatorCollectionSlugs.has(collection.slug),\n },\n parentFieldSlug,\n }),\n },\n endpoints: [\n ...getCollectionEndpoints(collection),\n createMovePageEndpoint({\n collectionSlug: collection.slug,\n diagnostics,\n parentFieldSlug,\n publishOnMove,\n }),\n ...(orderableFieldName\n ? [\n createReorderPageEndpoint({\n collectionSlug: collection.slug,\n diagnostics,\n orderableFieldName,\n parentFieldSlug,\n }),\n ]\n : []),\n ],\n fields: mapTopLevelFields(collection.fields, (field) =>\n patchBreadcrumbField({\n breadcrumbsFieldSlug,\n field,\n hideBreadcrumbs,\n }),\n ),\n hooks: {\n ...(collection.hooks ?? {}),\n ...(diagnosticsAfterChangeHook\n ? {\n afterChange: [\n ...(collection.hooks?.afterChange ?? []),\n diagnosticsAfterChangeHook,\n ],\n }\n : {}),\n },\n }\n })\n\n const missingCollections = pluginOptions.collections.filter(\n (collectionSlug) => !foundCollectionSlugs.has(collectionSlug),\n )\n\n if (missingCollections.length > 0) {\n throw new Error(\n `payload-nested-docs-page-tree could not find the following collections: ${missingCollections.join(', ')}`,\n )\n }\n\n return {\n ...config,\n collections: nextCollections as CollectionConfig[],\n }\n }\n"],"names":["createMovePageEndpoint","createReorderPageEndpoint","nestedDocsPageTreePluginCustomKey","pageTreeWriteContextKey","normalizeNestedDocsPageTreePluginBadgeConfig","DIAGNOSTICS_FLOW_CONTEXT_KEY","createFlowID","projectField","resolveDiagnostics","findTopLevelField","mapTopLevelFields","DEFAULT_BREADCRUMBS_FIELD_SLUG","DEFAULT_HOME_INDICATOR_COLLECTIONS","DEFAULT_LIMIT","DEFAULT_PARENT_FIELD_SLUG","PAGE_TREE_LIST_VIEW_PATH","createDiagnosticsAfterChangeHook","args","collectionSlug","diagnostics","orderableFieldName","parentFieldSlug","snapshotFields","push","doc","operation","previousDoc","req","enabled","context","docID","id","flow","before","after","changed","field","beforeValue","afterValue","JSON","stringify","log","collection","data","String","level","message","source","beforeStatus","_status","afterStatus","getCollectionEndpoints","Array","isArray","endpoints","patchBreadcrumbField","breadcrumbsFieldSlug","hideBreadcrumbs","name","admin","hidden","validateTargetCollection","useAsTitle","includes","Error","slug","fields","existingListView","components","views","list","Component","existingMoveEndpoint","find","endpoint","path","existingReorderEndpoint","buildCollectionCustom","badges","badgesLinks","defaultLimit","homeIndicator","getHomeIndicatorCollectionSlugs","Set","collections","pageTreeMoveContextKey","nestedDocsPageTreePlugin","pluginOptions","config","length","disabled","publishOnMove","homeIndicatorCollectionSlugs","targetedCollectionSlugs","foundCollectionSlugs","nextCollections","map","has","add","orderable","diagnosticsAfterChangeHook","pagination","undefined","custom","hooks","afterChange","missingCollections","filter","join"],"mappings":"AAMA,SAASA,sBAAsB,QAAQ,wCAAuC;AAC9E,SAASC,yBAAyB,QAAQ,2CAA0C;AAKpF,SAASC,iCAAiC,EAAEC,uBAAuB,QAAQ,aAAY;AACvF,SAASC,4CAA4C,QAAQ,6BAA4B;AACzF,SACEC,4BAA4B,EAE5BC,YAAY,EACZC,YAAY,EACZC,kBAAkB,QACb,6BAA4B;AACnC,SAASC,iBAAiB,EAAEC,iBAAiB,QAAQ,wBAAuB;AAE5E,MAAMC,iCAAiC;AACvC,MAAMC,qCAAqC;IAAC;C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