@payloadcms/plugin-search 4.0.0-internal.38b7f1d → 4.0.0-internal.3b50481

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 (33) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/Search/hooks/deleteFromSearch.d.ts.map +1 -1
  3. package/dist/Search/hooks/deleteFromSearch.js +1 -0
  4. package/dist/Search/hooks/deleteFromSearch.js.map +1 -1
  5. package/dist/Search/index.d.ts.map +1 -1
  6. package/dist/Search/index.js +4 -1
  7. package/dist/Search/index.js.map +1 -1
  8. package/dist/Search/ui/LinkToDoc/index.client.d.ts +1 -0
  9. package/dist/Search/ui/LinkToDoc/index.client.d.ts.map +1 -1
  10. package/dist/Search/ui/LinkToDoc/index.client.js +11 -18
  11. package/dist/Search/ui/LinkToDoc/index.client.js.map +1 -1
  12. package/dist/Search/ui/LinkToDoc/index.css +26 -0
  13. package/dist/Search/ui/ReindexButton/ReindexButtonLabel/index.d.ts +12 -1
  14. package/dist/Search/ui/ReindexButton/ReindexButtonLabel/index.d.ts.map +1 -1
  15. package/dist/Search/ui/ReindexButton/ReindexButtonLabel/index.js +17 -7
  16. package/dist/Search/ui/ReindexButton/ReindexButtonLabel/index.js.map +1 -1
  17. package/dist/Search/ui/ReindexButton/index.client.d.ts.map +1 -1
  18. package/dist/Search/ui/ReindexButton/index.client.js +10 -7
  19. package/dist/Search/ui/ReindexButton/index.client.js.map +1 -1
  20. package/dist/index.d.ts +1 -2
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +16 -8
  23. package/dist/index.js.map +1 -1
  24. package/dist/types.d.ts +9 -18
  25. package/dist/types.d.ts.map +1 -1
  26. package/dist/types.js.map +1 -1
  27. package/dist/utilities/generateReindexHandler.d.ts.map +1 -1
  28. package/dist/utilities/generateReindexHandler.js +2 -1
  29. package/dist/utilities/generateReindexHandler.js.map +1 -1
  30. package/dist/utilities/syncDocAsSearchIndex.d.ts.map +1 -1
  31. package/dist/utilities/syncDocAsSearchIndex.js +9 -0
  32. package/dist/utilities/syncDocAsSearchIndex.js.map +1 -1
  33. package/package.json +8 -8
package/LICENSE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2018-2025 Payload CMS, Inc. <info@payloadcms.com>
3
+ Copyright (c) 2018-2026 Payload CMS, LLC <info@payloadcms.com>
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining
6
6
  a copy of this software and associated documentation files (the
@@ -1 +1 @@
1
- {"version":3,"file":"deleteFromSearch.d.ts","sourceRoot":"","sources":["../../../src/Search/hooks/deleteFromSearch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAA;AAEtD,eAAO,MAAM,gBAAgB,EAAE,gBAyB5B,CAAA"}
1
+ {"version":3,"file":"deleteFromSearch.d.ts","sourceRoot":"","sources":["../../../src/Search/hooks/deleteFromSearch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAA;AAEtD,eAAO,MAAM,gBAAgB,EAAE,gBA0B5B,CAAA"}
@@ -4,6 +4,7 @@ export const deleteFromSearch = (pluginConfig)=>async ({ id, collection, req: {
4
4
  await payload.delete({
5
5
  collection: searchSlug,
6
6
  depth: 0,
7
+ overrideAccess: true,
7
8
  req,
8
9
  where: {
9
10
  'doc.relationTo': {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/Search/hooks/deleteFromSearch.ts"],"sourcesContent":["import type { DeleteFromSearch } from '../../types.js'\n\nexport const deleteFromSearch: DeleteFromSearch =\n (pluginConfig) =>\n async ({ id, collection, req: { payload }, req }) => {\n const searchSlug = pluginConfig?.searchOverrides?.slug || 'search'\n\n try {\n await payload.delete({\n collection: searchSlug,\n depth: 0,\n req,\n where: {\n 'doc.relationTo': {\n equals: collection.slug,\n },\n 'doc.value': {\n equals: id,\n },\n },\n })\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: `Error deleting ${searchSlug} doc.`,\n })\n }\n }\n"],"names":["deleteFromSearch","pluginConfig","id","collection","req","payload","searchSlug","searchOverrides","slug","delete","depth","where","equals","err","logger","error","msg"],"mappings":"AAEA,OAAO,MAAMA,mBACX,CAACC,eACD,OAAO,EAAEC,EAAE,EAAEC,UAAU,EAAEC,KAAK,EAAEC,OAAO,EAAE,EAAED,GAAG,EAAE;QAC9C,MAAME,aAAaL,cAAcM,iBAAiBC,QAAQ;QAE1D,IAAI;YACF,MAAMH,QAAQI,MAAM,CAAC;gBACnBN,YAAYG;gBACZI,OAAO;gBACPN;gBACAO,OAAO;oBACL,kBAAkB;wBAChBC,QAAQT,WAAWK,IAAI;oBACzB;oBACA,aAAa;wBACXI,QAAQV;oBACV;gBACF;YACF;QACF,EAAE,OAAOW,KAAc;YACrBR,QAAQS,MAAM,CAACC,KAAK,CAAC;gBACnBF;gBACAG,KAAK,CAAC,eAAe,EAAEV,WAAW,KAAK,CAAC;YAC1C;QACF;IACF,EAAC"}
1
+ {"version":3,"sources":["../../../src/Search/hooks/deleteFromSearch.ts"],"sourcesContent":["import type { DeleteFromSearch } from '../../types.js'\n\nexport const deleteFromSearch: DeleteFromSearch =\n (pluginConfig) =>\n async ({ id, collection, req: { payload }, req }) => {\n const searchSlug = pluginConfig?.searchOverrides?.slug || 'search'\n\n try {\n await payload.delete({\n collection: searchSlug,\n depth: 0,\n overrideAccess: true,\n req,\n where: {\n 'doc.relationTo': {\n equals: collection.slug,\n },\n 'doc.value': {\n equals: id,\n },\n },\n })\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: `Error deleting ${searchSlug} doc.`,\n })\n }\n }\n"],"names":["deleteFromSearch","pluginConfig","id","collection","req","payload","searchSlug","searchOverrides","slug","delete","depth","overrideAccess","where","equals","err","logger","error","msg"],"mappings":"AAEA,OAAO,MAAMA,mBACX,CAACC,eACD,OAAO,EAAEC,EAAE,EAAEC,UAAU,EAAEC,KAAK,EAAEC,OAAO,EAAE,EAAED,GAAG,EAAE;QAC9C,MAAME,aAAaL,cAAcM,iBAAiBC,QAAQ;QAE1D,IAAI;YACF,MAAMH,QAAQI,MAAM,CAAC;gBACnBN,YAAYG;gBACZI,OAAO;gBACPC,gBAAgB;gBAChBP;gBACAQ,OAAO;oBACL,kBAAkB;wBAChBC,QAAQV,WAAWK,IAAI;oBACzB;oBACA,aAAa;wBACXK,QAAQX;oBACV;gBACF;YACF;QACF,EAAE,OAAOY,KAAc;YACrBT,QAAQU,MAAM,CAACC,KAAK,CAAC;gBACnBF;gBACAG,KAAK,CAAC,eAAe,EAAEX,WAAW,KAAK,CAAC;YAC1C;QACF;IACF,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/Search/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAM9D,eAAO,MAAM,wBAAwB,iBACrB,2BAA2B,KACxC,gBAyGF,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/Search/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAM9D,eAAO,MAAM,wBAAwB,iBACrB,2BAA2B,KACxC,gBA4GF,CAAA"}
@@ -97,7 +97,10 @@ export const generateSearchCollection = (pluginConfig)=>{
97
97
  plural: 'Search Results',
98
98
  singular: 'Search Result'
99
99
  }
100
- }
100
+ },
101
+ // Internal search index; opt out of authorship (a searchOverride can re-enable it).
102
+ authorship: pluginConfig?.searchOverrides?.authorship ?? false,
103
+ versions: pluginConfig?.searchOverrides?.versions ?? false
101
104
  };
102
105
  return newConfig;
103
106
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/Search/index.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { SanitizedSearchPluginConfig } from '../types.js'\nimport type { ReindexButtonServerProps } from './ui/ReindexButton/types.js'\n\nimport { generateReindexHandler } from '../utilities/generateReindexHandler.js'\n\n// all settings can be overridden by the config\nexport const generateSearchCollection = (\n pluginConfig: SanitizedSearchPluginConfig,\n): CollectionConfig => {\n const searchSlug = pluginConfig?.searchOverrides?.slug || 'search'\n const searchCollections = pluginConfig?.collections || []\n const collectionLabels = pluginConfig?.labels\n\n const defaultFields: Field[] = [\n {\n name: 'title',\n type: 'text',\n admin: {\n readOnly: true,\n },\n localized: pluginConfig.localize,\n },\n {\n name: 'priority',\n type: 'number',\n admin: {\n position: 'sidebar',\n },\n },\n {\n name: 'doc',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n index: true,\n maxDepth: 0,\n relationTo: searchCollections,\n required: true,\n },\n {\n name: 'docUrl',\n type: 'ui',\n admin: {\n components: {\n Field: {\n path: '@payloadcms/plugin-search/client#LinkToDoc',\n },\n },\n position: 'sidebar',\n },\n },\n ]\n\n if (!collectionLabels) {\n throw new Error('collectionLabels is required')\n }\n\n const newConfig: CollectionConfig = {\n ...(pluginConfig?.searchOverrides || {}),\n slug: searchSlug,\n access: {\n create: (): boolean => false,\n read: (): boolean => true,\n ...(pluginConfig?.searchOverrides?.access || {}),\n },\n admin: {\n components: {\n views: {\n list: {\n actions: [\n {\n path: '@payloadcms/plugin-search/client#ReindexButton',\n serverProps: {\n collectionLabels,\n searchCollections,\n searchSlug,\n } satisfies ReindexButtonServerProps,\n },\n ],\n },\n },\n },\n defaultColumns: ['title'],\n description:\n 'This is a collection of automatically created search results. These results are used by the global site search and will be updated automatically as documents in the CMS are created or updated.',\n enableRichTextRelationship: false,\n useAsTitle: 'title',\n ...(pluginConfig?.searchOverrides?.admin || {}),\n },\n endpoints: [\n ...(pluginConfig?.searchOverrides?.endpoints || []),\n {\n handler: generateReindexHandler(pluginConfig),\n method: 'post',\n path: '/reindex',\n },\n ],\n fields:\n pluginConfig?.searchOverrides?.fields &&\n typeof pluginConfig?.searchOverrides?.fields === 'function'\n ? pluginConfig?.searchOverrides.fields({ defaultFields })\n : defaultFields,\n labels: {\n ...(pluginConfig?.searchOverrides?.labels || {\n plural: 'Search Results',\n singular: 'Search Result',\n }),\n },\n }\n\n return newConfig\n}\n"],"names":["generateReindexHandler","generateSearchCollection","pluginConfig","searchSlug","searchOverrides","slug","searchCollections","collections","collectionLabels","labels","defaultFields","name","type","admin","readOnly","localized","localize","position","index","maxDepth","relationTo","required","components","Field","path","Error","newConfig","access","create","read","views","list","actions","serverProps","defaultColumns","description","enableRichTextRelationship","useAsTitle","endpoints","handler","method","fields","plural","singular"],"mappings":"AAKA,SAASA,sBAAsB,QAAQ,yCAAwC;AAE/E,+CAA+C;AAC/C,OAAO,MAAMC,2BAA2B,CACtCC;IAEA,MAAMC,aAAaD,cAAcE,iBAAiBC,QAAQ;IAC1D,MAAMC,oBAAoBJ,cAAcK,eAAe,EAAE;IACzD,MAAMC,mBAAmBN,cAAcO;IAEvC,MAAMC,gBAAyB;QAC7B;YACEC,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLC,UAAU;YACZ;YACAC,WAAWb,aAAac,QAAQ;QAClC;QACA;YACEL,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLI,UAAU;YACZ;QACF;QACA;YACEN,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLI,UAAU;gBACVH,UAAU;YACZ;YACAI,OAAO;YACPC,UAAU;YACVC,YAAYd;YACZe,UAAU;QACZ;QACA;YACEV,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLS,YAAY;oBACVC,OAAO;wBACLC,MAAM;oBACR;gBACF;gBACAP,UAAU;YACZ;QACF;KACD;IAED,IAAI,CAACT,kBAAkB;QACrB,MAAM,IAAIiB,MAAM;IAClB;IAEA,MAAMC,YAA8B;QAClC,GAAIxB,cAAcE,mBAAmB,CAAC,CAAC;QACvCC,MAAMF;QACNwB,QAAQ;YACNC,QAAQ,IAAe;YACvBC,MAAM,IAAe;YACrB,GAAI3B,cAAcE,iBAAiBuB,UAAU,CAAC,CAAC;QACjD;QACAd,OAAO;YACLS,YAAY;gBACVQ,OAAO;oBACLC,MAAM;wBACJC,SAAS;4BACP;gCACER,MAAM;gCACNS,aAAa;oCACXzB;oCACAF;oCACAH;gCACF;4BACF;yBACD;oBACH;gBACF;YACF;YACA+B,gBAAgB;gBAAC;aAAQ;YACzBC,aACE;YACFC,4BAA4B;YAC5BC,YAAY;YACZ,GAAInC,cAAcE,iBAAiBS,SAAS,CAAC,CAAC;QAChD;QACAyB,WAAW;eACLpC,cAAcE,iBAAiBkC,aAAa,EAAE;YAClD;gBACEC,SAASvC,uBAAuBE;gBAChCsC,QAAQ;gBACRhB,MAAM;YACR;SACD;QACDiB,QACEvC,cAAcE,iBAAiBqC,UAC/B,OAAOvC,cAAcE,iBAAiBqC,WAAW,aAC7CvC,cAAcE,gBAAgBqC,OAAO;YAAE/B;QAAc,KACrDA;QACND,QAAQ;YACN,GAAIP,cAAcE,iBAAiBK,UAAU;gBAC3CiC,QAAQ;gBACRC,UAAU;YACZ,CAAC;QACH;IACF;IAEA,OAAOjB;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/Search/index.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { SanitizedSearchPluginConfig } from '../types.js'\nimport type { ReindexButtonServerProps } from './ui/ReindexButton/types.js'\n\nimport { generateReindexHandler } from '../utilities/generateReindexHandler.js'\n\n// all settings can be overridden by the config\nexport const generateSearchCollection = (\n pluginConfig: SanitizedSearchPluginConfig,\n): CollectionConfig => {\n const searchSlug = pluginConfig?.searchOverrides?.slug || 'search'\n const searchCollections = pluginConfig?.collections || []\n const collectionLabels = pluginConfig?.labels\n\n const defaultFields: Field[] = [\n {\n name: 'title',\n type: 'text',\n admin: {\n readOnly: true,\n },\n localized: pluginConfig.localize,\n },\n {\n name: 'priority',\n type: 'number',\n admin: {\n position: 'sidebar',\n },\n },\n {\n name: 'doc',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n index: true,\n maxDepth: 0,\n relationTo: searchCollections,\n required: true,\n },\n {\n name: 'docUrl',\n type: 'ui',\n admin: {\n components: {\n Field: {\n path: '@payloadcms/plugin-search/client#LinkToDoc',\n },\n },\n position: 'sidebar',\n },\n },\n ]\n\n if (!collectionLabels) {\n throw new Error('collectionLabels is required')\n }\n\n const newConfig: CollectionConfig = {\n ...(pluginConfig?.searchOverrides || {}),\n slug: searchSlug,\n access: {\n create: (): boolean => false,\n read: (): boolean => true,\n ...(pluginConfig?.searchOverrides?.access || {}),\n },\n admin: {\n components: {\n views: {\n list: {\n actions: [\n {\n path: '@payloadcms/plugin-search/client#ReindexButton',\n serverProps: {\n collectionLabels,\n searchCollections,\n searchSlug,\n } satisfies ReindexButtonServerProps,\n },\n ],\n },\n },\n },\n defaultColumns: ['title'],\n description:\n 'This is a collection of automatically created search results. These results are used by the global site search and will be updated automatically as documents in the CMS are created or updated.',\n enableRichTextRelationship: false,\n useAsTitle: 'title',\n ...(pluginConfig?.searchOverrides?.admin || {}),\n },\n endpoints: [\n ...(pluginConfig?.searchOverrides?.endpoints || []),\n {\n handler: generateReindexHandler(pluginConfig),\n method: 'post',\n path: '/reindex',\n },\n ],\n fields:\n pluginConfig?.searchOverrides?.fields &&\n typeof pluginConfig?.searchOverrides?.fields === 'function'\n ? pluginConfig?.searchOverrides.fields({ defaultFields })\n : defaultFields,\n labels: {\n ...(pluginConfig?.searchOverrides?.labels || {\n plural: 'Search Results',\n singular: 'Search Result',\n }),\n },\n // Internal search index; opt out of authorship (a searchOverride can re-enable it).\n authorship: pluginConfig?.searchOverrides?.authorship ?? false,\n versions: pluginConfig?.searchOverrides?.versions ?? false,\n }\n\n return newConfig\n}\n"],"names":["generateReindexHandler","generateSearchCollection","pluginConfig","searchSlug","searchOverrides","slug","searchCollections","collections","collectionLabels","labels","defaultFields","name","type","admin","readOnly","localized","localize","position","index","maxDepth","relationTo","required","components","Field","path","Error","newConfig","access","create","read","views","list","actions","serverProps","defaultColumns","description","enableRichTextRelationship","useAsTitle","endpoints","handler","method","fields","plural","singular","authorship","versions"],"mappings":"AAKA,SAASA,sBAAsB,QAAQ,yCAAwC;AAE/E,+CAA+C;AAC/C,OAAO,MAAMC,2BAA2B,CACtCC;IAEA,MAAMC,aAAaD,cAAcE,iBAAiBC,QAAQ;IAC1D,MAAMC,oBAAoBJ,cAAcK,eAAe,EAAE;IACzD,MAAMC,mBAAmBN,cAAcO;IAEvC,MAAMC,gBAAyB;QAC7B;YACEC,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLC,UAAU;YACZ;YACAC,WAAWb,aAAac,QAAQ;QAClC;QACA;YACEL,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLI,UAAU;YACZ;QACF;QACA;YACEN,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLI,UAAU;gBACVH,UAAU;YACZ;YACAI,OAAO;YACPC,UAAU;YACVC,YAAYd;YACZe,UAAU;QACZ;QACA;YACEV,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLS,YAAY;oBACVC,OAAO;wBACLC,MAAM;oBACR;gBACF;gBACAP,UAAU;YACZ;QACF;KACD;IAED,IAAI,CAACT,kBAAkB;QACrB,MAAM,IAAIiB,MAAM;IAClB;IAEA,MAAMC,YAA8B;QAClC,GAAIxB,cAAcE,mBAAmB,CAAC,CAAC;QACvCC,MAAMF;QACNwB,QAAQ;YACNC,QAAQ,IAAe;YACvBC,MAAM,IAAe;YACrB,GAAI3B,cAAcE,iBAAiBuB,UAAU,CAAC,CAAC;QACjD;QACAd,OAAO;YACLS,YAAY;gBACVQ,OAAO;oBACLC,MAAM;wBACJC,SAAS;4BACP;gCACER,MAAM;gCACNS,aAAa;oCACXzB;oCACAF;oCACAH;gCACF;4BACF;yBACD;oBACH;gBACF;YACF;YACA+B,gBAAgB;gBAAC;aAAQ;YACzBC,aACE;YACFC,4BAA4B;YAC5BC,YAAY;YACZ,GAAInC,cAAcE,iBAAiBS,SAAS,CAAC,CAAC;QAChD;QACAyB,WAAW;eACLpC,cAAcE,iBAAiBkC,aAAa,EAAE;YAClD;gBACEC,SAASvC,uBAAuBE;gBAChCsC,QAAQ;gBACRhB,MAAM;YACR;SACD;QACDiB,QACEvC,cAAcE,iBAAiBqC,UAC/B,OAAOvC,cAAcE,iBAAiBqC,WAAW,aAC7CvC,cAAcE,gBAAgBqC,OAAO;YAAE/B;QAAc,KACrDA;QACND,QAAQ;YACN,GAAIP,cAAcE,iBAAiBK,UAAU;gBAC3CiC,QAAQ;gBACRC,UAAU;YACZ,CAAC;QACH;QACA,oFAAoF;QACpFC,YAAY1C,cAAcE,iBAAiBwC,cAAc;QACzDC,UAAU3C,cAAcE,iBAAiByC,YAAY;IACvD;IAEA,OAAOnB;AACT,EAAC"}
@@ -1,3 +1,4 @@
1
1
  import React from 'react';
2
+ import './index.css';
2
3
  export declare const LinkToDocClient: React.FC;
3
4
  //# sourceMappingURL=index.client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.client.d.ts","sourceRoot":"","sources":["../../../../src/Search/ui/LinkToDoc/index.client.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,EAgDnC,CAAA"}
1
+ {"version":3,"file":"index.client.d.ts","sourceRoot":"","sources":["../../../../src/Search/ui/LinkToDoc/index.client.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB,OAAO,aAAa,CAAA;AAIpB,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,EAmCnC,CAAA"}
@@ -1,8 +1,10 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { CopyToClipboard, Link, useConfig, useField } from '@payloadcms/ui';
3
+ import { CopyToClipboard, FieldLabel, Link, useConfig, useField } from '@payloadcms/ui';
4
4
  import { formatAdminURL } from 'payload/shared';
5
5
  import React from 'react';
6
+ import './index.css';
7
+ const baseClass = 'link-to-doc';
6
8
  export const LinkToDocClient = ()=>{
7
9
  const { config } = useConfig();
8
10
  const { routes: { admin: adminRoute }, serverURL } = config;
@@ -18,18 +20,14 @@ export const LinkToDocClient = ()=>{
18
20
  serverURL
19
21
  });
20
22
  return /*#__PURE__*/ _jsxs("div", {
21
- style: {
22
- marginBottom: 'var(--spacing-field, 1rem)'
23
- },
23
+ className: baseClass,
24
24
  children: [
25
25
  /*#__PURE__*/ _jsxs("div", {
26
+ className: `${baseClass}__header`,
26
27
  children: [
27
- /*#__PURE__*/ _jsx("span", {
28
- className: "label",
29
- style: {
30
- color: '#9A9A9A'
31
- },
32
- children: "Doc URL"
28
+ /*#__PURE__*/ _jsx(FieldLabel, {
29
+ htmlFor: baseClass,
30
+ label: "Doc URL"
33
31
  }),
34
32
  /*#__PURE__*/ _jsx(CopyToClipboard, {
35
33
  value: href
@@ -37,16 +35,11 @@ export const LinkToDocClient = ()=>{
37
35
  ]
38
36
  }),
39
37
  /*#__PURE__*/ _jsx("div", {
40
- style: {
41
- fontWeight: '600',
42
- overflow: 'hidden',
43
- textOverflow: 'ellipsis'
44
- },
38
+ className: `${baseClass}__url`,
45
39
  children: /*#__PURE__*/ _jsx(Link, {
46
40
  href: href,
47
- passHref: true,
48
- rel: 'noopener noreferrer',
49
- target: '_blank',
41
+ rel: "noopener noreferrer",
42
+ target: "_blank",
50
43
  children: href
51
44
  })
52
45
  })
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/Search/ui/LinkToDoc/index.client.tsx"],"sourcesContent":["'use client'\n\nimport { CopyToClipboard, Link, useConfig, useField } from '@payloadcms/ui'\nimport { formatAdminURL } from 'payload/shared'\nimport React from 'react'\n\nexport const LinkToDocClient: React.FC = () => {\n const { config } = useConfig()\n\n const {\n routes: {\n admin: adminRoute, // already includes leading slash\n },\n serverURL,\n } = config\n\n const { value } = useField<{ relationTo?: string; value?: string }>({ path: 'doc' })\n\n if (!value?.relationTo || !value?.value) {\n return null\n }\n\n const href = formatAdminURL({\n adminRoute,\n path: `/collections/${value.relationTo || ''}/${value.value || ''}`,\n serverURL,\n })\n\n return (\n <div style={{ marginBottom: 'var(--spacing-field, 1rem)' }}>\n <div>\n <span\n className=\"label\"\n style={{\n color: '#9A9A9A',\n }}\n >\n Doc URL\n </span>\n <CopyToClipboard value={href} />\n </div>\n <div\n style={{\n fontWeight: '600',\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n }}\n >\n <Link href={href} passHref {...{ rel: 'noopener noreferrer', target: '_blank' }}>\n {href}\n </Link>\n </div>\n </div>\n )\n}\n"],"names":["CopyToClipboard","Link","useConfig","useField","formatAdminURL","React","LinkToDocClient","config","routes","admin","adminRoute","serverURL","value","path","relationTo","href","div","style","marginBottom","span","className","color","fontWeight","overflow","textOverflow","passHref","rel","target"],"mappings":"AAAA;;AAEA,SAASA,eAAe,EAAEC,IAAI,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,iBAAgB;AAC3E,SAASC,cAAc,QAAQ,iBAAgB;AAC/C,OAAOC,WAAW,QAAO;AAEzB,OAAO,MAAMC,kBAA4B;IACvC,MAAM,EAAEC,MAAM,EAAE,GAAGL;IAEnB,MAAM,EACJM,QAAQ,EACNC,OAAOC,UAAU,EAClB,EACDC,SAAS,EACV,GAAGJ;IAEJ,MAAM,EAAEK,KAAK,EAAE,GAAGT,SAAkD;QAAEU,MAAM;IAAM;IAElF,IAAI,CAACD,OAAOE,cAAc,CAACF,OAAOA,OAAO;QACvC,OAAO;IACT;IAEA,MAAMG,OAAOX,eAAe;QAC1BM;QACAG,MAAM,CAAC,aAAa,EAAED,MAAME,UAAU,IAAI,GAAG,CAAC,EAAEF,MAAMA,KAAK,IAAI,IAAI;QACnED;IACF;IAEA,qBACE,MAACK;QAAIC,OAAO;YAAEC,cAAc;QAA6B;;0BACvD,MAACF;;kCACC,KAACG;wBACCC,WAAU;wBACVH,OAAO;4BACLI,OAAO;wBACT;kCACD;;kCAGD,KAACrB;wBAAgBY,OAAOG;;;;0BAE1B,KAACC;gBACCC,OAAO;oBACLK,YAAY;oBACZC,UAAU;oBACVC,cAAc;gBAChB;0BAEA,cAAA,KAACvB;oBAAKc,MAAMA;oBAAMU,QAAQ;oBAAOC,KAAK;oBAAuBC,QAAQ;8BAClEZ;;;;;AAKX,EAAC"}
1
+ {"version":3,"sources":["../../../../src/Search/ui/LinkToDoc/index.client.tsx"],"sourcesContent":["'use client'\n\nimport { CopyToClipboard, FieldLabel, Link, useConfig, useField } from '@payloadcms/ui'\nimport { formatAdminURL } from 'payload/shared'\nimport React from 'react'\n\nimport './index.css'\n\nconst baseClass = 'link-to-doc'\n\nexport const LinkToDocClient: React.FC = () => {\n const { config } = useConfig()\n\n const {\n routes: {\n admin: adminRoute, // already includes leading slash\n },\n serverURL,\n } = config\n\n const { value } = useField<{ relationTo?: string; value?: string }>({ path: 'doc' })\n\n if (!value?.relationTo || !value?.value) {\n return null\n }\n\n const href = formatAdminURL({\n adminRoute,\n path: `/collections/${value.relationTo || ''}/${value.value || ''}`,\n serverURL,\n })\n\n return (\n <div className={baseClass}>\n <div className={`${baseClass}__header`}>\n <FieldLabel htmlFor={baseClass} label=\"Doc URL\" />\n <CopyToClipboard value={href} />\n </div>\n <div className={`${baseClass}__url`}>\n <Link href={href} rel=\"noopener noreferrer\" target=\"_blank\">\n {href}\n </Link>\n </div>\n </div>\n )\n}\n"],"names":["CopyToClipboard","FieldLabel","Link","useConfig","useField","formatAdminURL","React","baseClass","LinkToDocClient","config","routes","admin","adminRoute","serverURL","value","path","relationTo","href","div","className","htmlFor","label","rel","target"],"mappings":"AAAA;;AAEA,SAASA,eAAe,EAAEC,UAAU,EAAEC,IAAI,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,iBAAgB;AACvF,SAASC,cAAc,QAAQ,iBAAgB;AAC/C,OAAOC,WAAW,QAAO;AAEzB,OAAO,cAAa;AAEpB,MAAMC,YAAY;AAElB,OAAO,MAAMC,kBAA4B;IACvC,MAAM,EAAEC,MAAM,EAAE,GAAGN;IAEnB,MAAM,EACJO,QAAQ,EACNC,OAAOC,UAAU,EAClB,EACDC,SAAS,EACV,GAAGJ;IAEJ,MAAM,EAAEK,KAAK,EAAE,GAAGV,SAAkD;QAAEW,MAAM;IAAM;IAElF,IAAI,CAACD,OAAOE,cAAc,CAACF,OAAOA,OAAO;QACvC,OAAO;IACT;IAEA,MAAMG,OAAOZ,eAAe;QAC1BO;QACAG,MAAM,CAAC,aAAa,EAAED,MAAME,UAAU,IAAI,GAAG,CAAC,EAAEF,MAAMA,KAAK,IAAI,IAAI;QACnED;IACF;IAEA,qBACE,MAACK;QAAIC,WAAWZ;;0BACd,MAACW;gBAAIC,WAAW,GAAGZ,UAAU,QAAQ,CAAC;;kCACpC,KAACN;wBAAWmB,SAASb;wBAAWc,OAAM;;kCACtC,KAACrB;wBAAgBc,OAAOG;;;;0BAE1B,KAACC;gBAAIC,WAAW,GAAGZ,UAAU,KAAK,CAAC;0BACjC,cAAA,KAACL;oBAAKe,MAAMA;oBAAMK,KAAI;oBAAsBC,QAAO;8BAChDN;;;;;AAKX,EAAC"}
@@ -0,0 +1,26 @@
1
+ @layer payload-default {
2
+ .link-to-doc {
3
+ margin-bottom: var(--spacing-field);
4
+ }
5
+
6
+ .link-to-doc__header {
7
+ display: flex;
8
+ align-items: center;
9
+ width: fit-content;
10
+ gap: var(--spacer-1);
11
+ }
12
+
13
+ .link-to-doc__url {
14
+ overflow: hidden;
15
+ font-weight: 600;
16
+ text-overflow: ellipsis;
17
+ }
18
+
19
+ .link-to-doc__url a {
20
+ color: var(--color-text-secondary);
21
+
22
+ &:hover {
23
+ color: var(--color-text);
24
+ }
25
+ }
26
+ }
@@ -1,2 +1,13 @@
1
- export declare const ReindexButtonLabel: () => import("react").JSX.Element;
1
+ import type { AriaAttributes } from 'react';
2
+ import React from 'react';
3
+ type ReindexButtonLabelProps = {
4
+ readonly active?: boolean;
5
+ readonly 'aria-controls'?: AriaAttributes['aria-controls'];
6
+ readonly 'aria-expanded'?: AriaAttributes['aria-expanded'];
7
+ readonly 'aria-haspopup'?: AriaAttributes['aria-haspopup'];
8
+ readonly onClick?: React.MouseEventHandler;
9
+ readonly onKeyDown?: React.KeyboardEventHandler;
10
+ };
11
+ export declare const ReindexButtonLabel: React.FC<ReindexButtonLabelProps>;
12
+ export {};
2
13
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/Search/ui/ReindexButton/ReindexButtonLabel/index.tsx"],"names":[],"mappings":"AAEA,eAAO,MAAM,kBAAkB,mCAS9B,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/Search/ui/ReindexButton/ReindexButtonLabel/index.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,OAAO,CAAA;AAG3C,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB,KAAK,uBAAuB,GAAG;IAC7B,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAA;IACzB,QAAQ,CAAC,eAAe,CAAC,EAAE,cAAc,CAAC,eAAe,CAAC,CAAA;IAC1D,QAAQ,CAAC,eAAe,CAAC,EAAE,cAAc,CAAC,eAAe,CAAC,CAAA;IAC1D,QAAQ,CAAC,eAAe,CAAC,EAAE,cAAc,CAAC,eAAe,CAAC,CAAA;IAC1D,QAAQ,CAAC,OAAO,CAAC,EAAE,KAAK,CAAC,iBAAiB,CAAA;IAC1C,QAAQ,CAAC,SAAS,CAAC,EAAE,KAAK,CAAC,oBAAoB,CAAA;CAChD,CAAA;AAED,eAAO,MAAM,kBAAkB,EAAE,KAAK,CAAC,EAAE,CAAC,uBAAuB,CAuBhE,CAAA"}
@@ -1,12 +1,22 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { ChevronIcon, Pill, useTranslation } from '@payloadcms/ui';
3
- export const ReindexButtonLabel = ()=>{
2
+ import { Button, ChevronIcon, useTranslation } from '@payloadcms/ui';
3
+ import React from 'react';
4
+ export const ReindexButtonLabel = ({ active, onClick, onKeyDown, ...ariaProps })=>{
4
5
  const { i18n: { t } } = useTranslation();
5
- return /*#__PURE__*/ _jsx(Pill, {
6
- className: "pill--has-action",
7
- icon: /*#__PURE__*/ _jsx(ChevronIcon, {}),
8
- pillStyle: "light",
9
- size: "small",
6
+ return /*#__PURE__*/ _jsx(Button, {
7
+ buttonStyle: "secondary",
8
+ extraButtonProps: {
9
+ onKeyDown
10
+ },
11
+ icon: /*#__PURE__*/ _jsx(ChevronIcon, {
12
+ direction: active ? 'up' : 'down',
13
+ size: 16
14
+ }),
15
+ iconPosition: "right",
16
+ onClick: onClick,
17
+ selected: active,
18
+ size: "medium",
19
+ ...ariaProps,
10
20
  children: t('general:reindex')
11
21
  });
12
22
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/Search/ui/ReindexButton/ReindexButtonLabel/index.tsx"],"sourcesContent":["import { ChevronIcon, Pill, useTranslation } from '@payloadcms/ui'\n\nexport const ReindexButtonLabel = () => {\n const {\n i18n: { t },\n } = useTranslation()\n return (\n <Pill className=\"pill--has-action\" icon={<ChevronIcon />} pillStyle=\"light\" size=\"small\">\n {t('general:reindex')}\n </Pill>\n )\n}\n"],"names":["ChevronIcon","Pill","useTranslation","ReindexButtonLabel","i18n","t","className","icon","pillStyle","size"],"mappings":";AAAA,SAASA,WAAW,EAAEC,IAAI,EAAEC,cAAc,QAAQ,iBAAgB;AAElE,OAAO,MAAMC,qBAAqB;IAChC,MAAM,EACJC,MAAM,EAAEC,CAAC,EAAE,EACZ,GAAGH;IACJ,qBACE,KAACD;QAAKK,WAAU;QAAmBC,oBAAM,KAACP;QAAgBQ,WAAU;QAAQC,MAAK;kBAC9EJ,EAAE;;AAGT,EAAC"}
1
+ {"version":3,"sources":["../../../../../src/Search/ui/ReindexButton/ReindexButtonLabel/index.tsx"],"sourcesContent":["import type { AriaAttributes } from 'react'\n\nimport { Button, ChevronIcon, useTranslation } from '@payloadcms/ui'\nimport React from 'react'\n\ntype ReindexButtonLabelProps = {\n readonly active?: boolean\n readonly 'aria-controls'?: AriaAttributes['aria-controls']\n readonly 'aria-expanded'?: AriaAttributes['aria-expanded']\n readonly 'aria-haspopup'?: AriaAttributes['aria-haspopup']\n readonly onClick?: React.MouseEventHandler\n readonly onKeyDown?: React.KeyboardEventHandler\n}\n\nexport const ReindexButtonLabel: React.FC<ReindexButtonLabelProps> = ({\n active,\n onClick,\n onKeyDown,\n ...ariaProps\n}) => {\n const {\n i18n: { t },\n } = useTranslation()\n return (\n <Button\n buttonStyle=\"secondary\"\n extraButtonProps={{ onKeyDown }}\n icon={<ChevronIcon direction={active ? 'up' : 'down'} size={16} />}\n iconPosition=\"right\"\n onClick={onClick}\n selected={active}\n size=\"medium\"\n {...ariaProps}\n >\n {t('general:reindex')}\n </Button>\n )\n}\n"],"names":["Button","ChevronIcon","useTranslation","React","ReindexButtonLabel","active","onClick","onKeyDown","ariaProps","i18n","t","buttonStyle","extraButtonProps","icon","direction","size","iconPosition","selected"],"mappings":";AAEA,SAASA,MAAM,EAAEC,WAAW,EAAEC,cAAc,QAAQ,iBAAgB;AACpE,OAAOC,WAAW,QAAO;AAWzB,OAAO,MAAMC,qBAAwD,CAAC,EACpEC,MAAM,EACNC,OAAO,EACPC,SAAS,EACT,GAAGC,WACJ;IACC,MAAM,EACJC,MAAM,EAAEC,CAAC,EAAE,EACZ,GAAGR;IACJ,qBACE,KAACF;QACCW,aAAY;QACZC,kBAAkB;YAAEL;QAAU;QAC9BM,oBAAM,KAACZ;YAAYa,WAAWT,SAAS,OAAO;YAAQU,MAAM;;QAC5DC,cAAa;QACbV,SAASA;QACTW,UAAUZ;QACVU,MAAK;QACJ,GAAGP,SAAS;kBAEZE,EAAE;;AAGT,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.client.d.ts","sourceRoot":"","sources":["../../../../src/Search/ui/ReindexButton/index.client.tsx"],"names":[],"mappings":"AAcA,OAAO,KAAyC,MAAM,OAAO,CAAA;AAE7D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAMpD,eAAO,MAAM,mBAAmB,EAAE,KAAK,CAAC,EAAE,CAAC,kBAAkB,CAqI5D,CAAA"}
1
+ {"version":3,"file":"index.client.d.ts","sourceRoot":"","sources":["../../../../src/Search/ui/ReindexButton/index.client.tsx"],"names":[],"mappings":"AAcA,OAAO,KAAyC,MAAM,OAAO,CAAA;AAE7D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAMpD,eAAO,MAAM,mBAAmB,EAAE,KAAK,CAAC,EAAE,CAAC,kBAAkB,CAuI5D,CAAA"}
@@ -1,7 +1,6 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { ConfirmationModal, Popup, PopupList, toast, useConfig, useLocale, useModal, useTranslation } from '@payloadcms/ui';
4
- import { useRouter } from 'next/navigation.js';
3
+ import { ConfirmationModal, Popup, PopupList, toast, useConfig, useLocale, useModal, useRouter, useTranslation } from '@payloadcms/ui';
5
4
  import { formatAdminURL } from 'payload/shared';
6
5
  import React, { useCallback, useMemo, useState } from 'react';
7
6
  import { ReindexButtonLabel } from './ReindexButtonLabel/index.js';
@@ -11,6 +10,7 @@ export const ReindexButtonClient = ({ collectionLabels, searchCollections, searc
11
10
  const { config } = useConfig();
12
11
  const { i18n: { t } } = useTranslation();
13
12
  const locale = useLocale();
13
+ const localeCode = locale?.code;
14
14
  const router = useRouter();
15
15
  const [reindexCollections, setReindexCollections] = useState([]);
16
16
  const openConfirmModal = useCallback(()=>openModal(confirmReindexModalSlug), [
@@ -23,7 +23,7 @@ export const ReindexButtonClient = ({ collectionLabels, searchCollections, searc
23
23
  try {
24
24
  const res = await fetch(formatAdminURL({
25
25
  apiRoute: config.routes.api,
26
- path: `/${searchSlug}/reindex?locale=${locale.code}`
26
+ path: `/${searchSlug}/reindex${localeCode ? `?locale=${localeCode}` : ''}`
27
27
  }), {
28
28
  body: JSON.stringify({
29
29
  collections: reindexCollections
@@ -46,7 +46,7 @@ export const ReindexButtonClient = ({ collectionLabels, searchCollections, searc
46
46
  reindexCollections,
47
47
  router,
48
48
  searchSlug,
49
- locale,
49
+ localeCode,
50
50
  config
51
51
  ]);
52
52
  const handleShowConfirmModal = useCallback((collections = searchCollections)=>{
@@ -69,11 +69,11 @@ export const ReindexButtonClient = ({ collectionLabels, searchCollections, searc
69
69
  if (typeof label === 'string') {
70
70
  return label;
71
71
  } else {
72
- return label && Object.hasOwn(label, locale.code) ? label[locale.code] : slug;
72
+ return label && localeCode && Object.hasOwn(label, localeCode) ? label[localeCode] : slug;
73
73
  }
74
74
  }, [
75
75
  collectionLabels,
76
- locale.code
76
+ localeCode
77
77
  ]);
78
78
  const pluralizedLabels = useMemo(()=>{
79
79
  return searchCollections.reduce((acc, slug)=>{
@@ -98,7 +98,7 @@ export const ReindexButtonClient = ({ collectionLabels, searchCollections, searc
98
98
  return /*#__PURE__*/ _jsxs("div", {
99
99
  children: [
100
100
  /*#__PURE__*/ _jsx(Popup, {
101
- button: /*#__PURE__*/ _jsx(ReindexButtonLabel, {}),
101
+ popupType: "menu",
102
102
  render: ({ close })=>/*#__PURE__*/ _jsxs(PopupList.ButtonGroup, {
103
103
  children: [
104
104
  searchCollections.map((collectionSlug)=>/*#__PURE__*/ _jsx(PopupList.Button, {
@@ -111,6 +111,9 @@ export const ReindexButtonClient = ({ collectionLabels, searchCollections, searc
111
111
  })
112
112
  ]
113
113
  }),
114
+ renderButton: (buttonProps)=>/*#__PURE__*/ _jsx(ReindexButtonLabel, {
115
+ ...buttonProps
116
+ }),
114
117
  showScrollbar: true,
115
118
  size: "large",
116
119
  verticalAlign: "bottom"
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/Search/ui/ReindexButton/index.client.tsx"],"sourcesContent":["'use client'\n\nimport {\n ConfirmationModal,\n Popup,\n PopupList,\n toast,\n useConfig,\n useLocale,\n useModal,\n useTranslation,\n} from '@payloadcms/ui'\nimport { useRouter } from 'next/navigation.js'\nimport { formatAdminURL } from 'payload/shared'\nimport React, { useCallback, useMemo, useState } from 'react'\n\nimport type { ReindexButtonProps } from './types.js'\n\nimport { ReindexButtonLabel } from './ReindexButtonLabel/index.js'\n\nconst confirmReindexModalSlug = 'confirm-reindex-modal'\n\nexport const ReindexButtonClient: React.FC<ReindexButtonProps> = ({\n collectionLabels,\n searchCollections,\n searchSlug,\n}) => {\n const { openModal } = useModal()\n\n const { config } = useConfig()\n\n const {\n i18n: { t },\n } = useTranslation()\n\n const locale = useLocale()\n const router = useRouter()\n\n const [reindexCollections, setReindexCollections] = useState<string[]>([])\n\n const openConfirmModal = useCallback(() => openModal(confirmReindexModalSlug), [openModal])\n\n const handleReindexSubmit = useCallback(async () => {\n if (!reindexCollections.length) {\n return\n }\n\n try {\n const res = await fetch(\n formatAdminURL({\n apiRoute: config.routes.api,\n path: `/${searchSlug}/reindex?locale=${locale.code}`,\n }),\n {\n body: JSON.stringify({\n collections: reindexCollections,\n }),\n method: 'POST',\n },\n )\n\n const { message } = (await res.json()) as { message: string }\n\n if (!res.ok) {\n toast.error(message)\n } else {\n toast.success(message)\n return router.refresh()\n }\n } catch (_err: unknown) {\n // swallow error, toast shown above\n } finally {\n setReindexCollections([])\n }\n }, [reindexCollections, router, searchSlug, locale, config])\n\n const handleShowConfirmModal = useCallback(\n (collections: string | string[] = searchCollections) => {\n setReindexCollections(typeof collections === 'string' ? [collections] : collections)\n openConfirmModal()\n },\n [openConfirmModal, searchCollections],\n )\n\n const handlePopupButtonClick = useCallback(\n (closePopup: () => void, slug?: string) => {\n closePopup()\n handleShowConfirmModal(slug)\n },\n [handleShowConfirmModal],\n )\n\n const getPluralizedLabel = useCallback(\n (slug: string) => {\n const label = collectionLabels[slug]\n if (typeof label === 'string') {\n return label\n } else {\n return label && Object.hasOwn(label, locale.code) ? label[locale.code] : slug\n }\n },\n [collectionLabels, locale.code],\n )\n\n const pluralizedLabels = useMemo(() => {\n return searchCollections.reduce<Record<string, string>>((acc, slug) => {\n const label = getPluralizedLabel(slug)\n if (label) {\n acc[slug] = label\n }\n return acc\n }, {})\n }, [searchCollections, getPluralizedLabel])\n\n const selectedAll = reindexCollections.length === searchCollections.length\n const selectedLabels = reindexCollections.map((slug) => pluralizedLabels[slug]).join(', ')\n\n const modalTitle = selectedAll\n ? t('general:confirmReindexAll')\n : t('general:confirmReindex', { collections: selectedLabels })\n const modalDescription = selectedAll\n ? t('general:confirmReindexDescriptionAll')\n : t('general:confirmReindexDescription', { collections: selectedLabels })\n\n return (\n <div>\n <Popup\n button={<ReindexButtonLabel />}\n render={({ close }) => (\n <PopupList.ButtonGroup>\n {searchCollections.map((collectionSlug) => (\n <PopupList.Button\n key={collectionSlug}\n onClick={() => handlePopupButtonClick(close, collectionSlug)}\n >\n {pluralizedLabels[collectionSlug]}\n </PopupList.Button>\n ))}\n <PopupList.Button onClick={() => handlePopupButtonClick(close)}>\n {t('general:allCollections')}\n </PopupList.Button>\n </PopupList.ButtonGroup>\n )}\n showScrollbar\n size=\"large\"\n verticalAlign=\"bottom\"\n />\n <ConfirmationModal\n body={modalDescription}\n heading={modalTitle}\n modalSlug={confirmReindexModalSlug}\n onConfirm={handleReindexSubmit}\n />\n </div>\n )\n}\n"],"names":["ConfirmationModal","Popup","PopupList","toast","useConfig","useLocale","useModal","useTranslation","useRouter","formatAdminURL","React","useCallback","useMemo","useState","ReindexButtonLabel","confirmReindexModalSlug","ReindexButtonClient","collectionLabels","searchCollections","searchSlug","openModal","config","i18n","t","locale","router","reindexCollections","setReindexCollections","openConfirmModal","handleReindexSubmit","length","res","fetch","apiRoute","routes","api","path","code","body","JSON","stringify","collections","method","message","json","ok","error","success","refresh","_err","handleShowConfirmModal","handlePopupButtonClick","closePopup","slug","getPluralizedLabel","label","Object","hasOwn","pluralizedLabels","reduce","acc","selectedAll","selectedLabels","map","join","modalTitle","modalDescription","div","button","render","close","ButtonGroup","collectionSlug","Button","onClick","showScrollbar","size","verticalAlign","heading","modalSlug","onConfirm"],"mappings":"AAAA;;AAEA,SACEA,iBAAiB,EACjBC,KAAK,EACLC,SAAS,EACTC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,cAAc,QACT,iBAAgB;AACvB,SAASC,SAAS,QAAQ,qBAAoB;AAC9C,SAASC,cAAc,QAAQ,iBAAgB;AAC/C,OAAOC,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAI7D,SAASC,kBAAkB,QAAQ,gCAA+B;AAElE,MAAMC,0BAA0B;AAEhC,OAAO,MAAMC,sBAAoD,CAAC,EAChEC,gBAAgB,EAChBC,iBAAiB,EACjBC,UAAU,EACX;IACC,MAAM,EAAEC,SAAS,EAAE,GAAGd;IAEtB,MAAM,EAAEe,MAAM,EAAE,GAAGjB;IAEnB,MAAM,EACJkB,MAAM,EAAEC,CAAC,EAAE,EACZ,GAAGhB;IAEJ,MAAMiB,SAASnB;IACf,MAAMoB,SAASjB;IAEf,MAAM,CAACkB,oBAAoBC,sBAAsB,GAAGd,SAAmB,EAAE;IAEzE,MAAMe,mBAAmBjB,YAAY,IAAMS,UAAUL,0BAA0B;QAACK;KAAU;IAE1F,MAAMS,sBAAsBlB,YAAY;QACtC,IAAI,CAACe,mBAAmBI,MAAM,EAAE;YAC9B;QACF;QAEA,IAAI;YACF,MAAMC,MAAM,MAAMC,MAChBvB,eAAe;gBACbwB,UAAUZ,OAAOa,MAAM,CAACC,GAAG;gBAC3BC,MAAM,CAAC,CAAC,EAAEjB,WAAW,gBAAgB,EAAEK,OAAOa,IAAI,EAAE;YACtD,IACA;gBACEC,MAAMC,KAAKC,SAAS,CAAC;oBACnBC,aAAaf;gBACf;gBACAgB,QAAQ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CAAC,CAACV,OAASK,gBAAgB,CAACL,KAAK,EAAEW,IAAI,CAAC;IAErF,MAAMC,aAAaJ,cACftC,EAAE,+BACFA,EAAE,0BAA0B;QAAEkB,aAAaqB;IAAe;IAC9D,MAAMI,mBAAmBL,cACrBtC,EAAE,0CACFA,EAAE,qCAAqC;QAAEkB,aAAaqB;IAAe;IAEzE,qBACE,MAACK;;0BACC,KAAClE;gBACCmE,sBAAQ,KAACtD;gBACTuD,QAAQ,CAAC,EAAEC,KAAK,EAAE,iBAChB,MAACpE,UAAUqE,WAAW;;4BACnBrD,kBAAkB6C,GAAG,CAAC,CAACS,+BACtB,KAACtE,UAAUuE,MAAM;oCAEfC,SAAS,IAAMvB,uBAAuBmB,OAAOE;8CAE5Cd,gBAAgB,CAACc,eAAe;mCAH5BA;0CAMT,KAACtE,UAAUuE,MAAM;gCAACC,SAAS,IAAMvB,uBAAuBmB;0CACrD/C,EAAE;;;;gBAIToD,aAAa;gBACbC,MAAK;gBACLC,eAAc;;0BAEhB,KAAC7E;gBACCsC,MAAM4B;gBACNY,SAASb;gBACTc,WAAWhE;gBACXiE,WAAWnD;;;;AAInB,EAAC"}
1
+ {"version":3,"sources":["../../../../src/Search/ui/ReindexButton/index.client.tsx"],"sourcesContent":["'use client'\n\nimport {\n ConfirmationModal,\n Popup,\n PopupList,\n toast,\n useConfig,\n useLocale,\n useModal,\n useRouter,\n useTranslation,\n} from '@payloadcms/ui'\nimport { formatAdminURL } from 'payload/shared'\nimport React, { useCallback, useMemo, useState } from 'react'\n\nimport type { ReindexButtonProps } from './types.js'\n\nimport { ReindexButtonLabel } from './ReindexButtonLabel/index.js'\n\nconst confirmReindexModalSlug = 'confirm-reindex-modal'\n\nexport const ReindexButtonClient: React.FC<ReindexButtonProps> = ({\n collectionLabels,\n searchCollections,\n searchSlug,\n}) => {\n const { openModal } = useModal()\n\n const { config } = useConfig()\n\n const {\n i18n: { t },\n } = useTranslation()\n\n const locale = useLocale()\n const localeCode = locale?.code\n const router = useRouter()\n\n const [reindexCollections, setReindexCollections] = useState<string[]>([])\n\n const openConfirmModal = useCallback(() => openModal(confirmReindexModalSlug), [openModal])\n\n const handleReindexSubmit = useCallback(async () => {\n if (!reindexCollections.length) {\n return\n }\n\n try {\n const res = await fetch(\n formatAdminURL({\n apiRoute: config.routes.api,\n path: `/${searchSlug}/reindex${localeCode ? `?locale=${localeCode}` : ''}`,\n }),\n {\n body: JSON.stringify({\n collections: reindexCollections,\n }),\n method: 'POST',\n },\n )\n\n const { message } = (await res.json()) as { message: string }\n\n if (!res.ok) {\n toast.error(message)\n } else {\n toast.success(message)\n return router.refresh()\n }\n } catch (_err: unknown) {\n // swallow error, toast shown above\n } finally {\n setReindexCollections([])\n }\n }, [reindexCollections, router, searchSlug, localeCode, config])\n\n const handleShowConfirmModal = useCallback(\n (collections: string | string[] = searchCollections) => {\n setReindexCollections(typeof collections === 'string' ? [collections] : collections)\n openConfirmModal()\n },\n [openConfirmModal, searchCollections],\n )\n\n const handlePopupButtonClick = useCallback(\n (closePopup: () => void, slug?: string) => {\n closePopup()\n handleShowConfirmModal(slug)\n },\n [handleShowConfirmModal],\n )\n\n const getPluralizedLabel = useCallback(\n (slug: string) => {\n const label = collectionLabels[slug]\n if (typeof label === 'string') {\n return label\n } else {\n return label && localeCode && Object.hasOwn(label, localeCode) ? label[localeCode] : slug\n }\n },\n [collectionLabels, localeCode],\n )\n\n const pluralizedLabels = useMemo(() => {\n return searchCollections.reduce<Record<string, string>>((acc, slug) => {\n const label = getPluralizedLabel(slug)\n if (label) {\n acc[slug] = label\n }\n return acc\n }, {})\n }, [searchCollections, getPluralizedLabel])\n\n const selectedAll = reindexCollections.length === searchCollections.length\n const selectedLabels = reindexCollections.map((slug) => pluralizedLabels[slug]).join(', ')\n\n const modalTitle = selectedAll\n ? t('general:confirmReindexAll')\n : t('general:confirmReindex', { collections: selectedLabels })\n const modalDescription = selectedAll\n ? t('general:confirmReindexDescriptionAll')\n : t('general:confirmReindexDescription', { collections: selectedLabels })\n\n return (\n <div>\n <Popup\n popupType=\"menu\"\n render={({ close }) => (\n <PopupList.ButtonGroup>\n {searchCollections.map((collectionSlug) => (\n <PopupList.Button\n key={collectionSlug}\n onClick={() => handlePopupButtonClick(close, collectionSlug)}\n >\n {pluralizedLabels[collectionSlug]}\n </PopupList.Button>\n ))}\n <PopupList.Button onClick={() => handlePopupButtonClick(close)}>\n {t('general:allCollections')}\n </PopupList.Button>\n </PopupList.ButtonGroup>\n )}\n renderButton={(buttonProps) => <ReindexButtonLabel {...buttonProps} />}\n showScrollbar\n size=\"large\"\n verticalAlign=\"bottom\"\n />\n <ConfirmationModal\n body={modalDescription}\n heading={modalTitle}\n modalSlug={confirmReindexModalSlug}\n onConfirm={handleReindexSubmit}\n />\n </div>\n )\n}\n"],"names":["ConfirmationModal","Popup","PopupList","toast","useConfig","useLocale","useModal","useRouter","useTranslation","formatAdminURL","React","useCallback","useMemo","useState","ReindexButtonLabel","confirmReindexModalSlug","ReindexButtonClient","collectionLabels","searchCollections","searchSlug","openModal","config","i18n","t","locale","localeCode","code","router","reindexCollections","setReindexCollections","openConfirmModal","handleReindexSubmit","length","res","fetch","apiRoute","routes","api","path","body","JSON","stringify","collections","method","message","json","ok","error","success","refresh","_err","handleShowConfirmModal","handlePopupButtonClick","closePopup","slug","getPluralizedLabel","label","Object","hasOwn","pluralizedLabels","reduce","acc","selectedAll","selectedLabels","map","join","modalTitle","modalDescription","div","popupType","render","close","ButtonGroup","collectionSlug","Button","onClick","renderButton","buttonProps","showScrollbar","size","verticalAlign","heading","modalSlug","onConfirm"],"mappings":"AAAA;;AAEA,SACEA,iBAAiB,EACjBC,KAAK,EACLC,SAAS,EACTC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,SAAS,EACTC,cAAc,QACT,iBAAgB;AACvB,SAASC,cAAc,QAAQ,iBAAgB;AAC/C,OAAOC,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAI7D,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uBAAuBmB,OAAOE;8CAE5Cd,gBAAgB,CAACc,eAAe;mCAH5BA;0CAMT,KAACvE,UAAUwE,MAAM;gCAACC,SAAS,IAAMvB,uBAAuBmB;0CACrDhD,EAAE;;;;gBAITqD,cAAc,CAACC,4BAAgB,KAAC/D;wBAAoB,GAAG+D,WAAW;;gBAClEC,aAAa;gBACbC,MAAK;gBACLC,eAAc;;0BAEhB,KAAChF;gBACCuC,MAAM4B;gBACNc,SAASf;gBACTgB,WAAWnE;gBACXoE,WAAWpD;;;;AAInB,EAAC"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import type { Config } from 'payload';
2
1
  import type { SearchPluginConfig } from './types.js';
3
- export declare const searchPlugin: <ConfigTypes = unknown>(incomingPluginConfig: SearchPluginConfig<ConfigTypes>) => (config: Config) => Config;
2
+ export declare const searchPlugin: (options: SearchPluginConfig) => import("payload").Plugin;
4
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA6B,MAAM,EAAE,MAAM,SAAS,CAAA;AAEhE,OAAO,KAAK,EAA+B,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAQjF,eAAO,MAAM,YAAY,GACtB,WAAW,kCAAkC,kBAAkB,CAAC,WAAW,CAAC,cACpE,MAAM,KAAG,MAuEjB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAA+B,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAQjF,eAAO,MAAM,YAAY,2DA8EvB,CAAA"}
package/dist/index.js CHANGED
@@ -1,17 +1,25 @@
1
+ import { definePlugin } from 'payload';
1
2
  import { deleteFromSearch } from './Search/hooks/deleteFromSearch.js';
2
3
  import { syncWithSearch } from './Search/hooks/syncWithSearch.js';
3
4
  import { generateSearchCollection } from './Search/index.js';
4
- export const searchPlugin = (incomingPluginConfig)=>(config)=>{
5
+ export const searchPlugin = definePlugin({
6
+ slug: '@payloadcms/plugin-search',
7
+ plugin: ({ config, options: incomingPluginConfig })=>{
5
8
  const { collections } = config;
6
9
  // If the user defines `localize` to either true or false, use that
7
10
  // Otherwise, set it based on if their config has localization enabled or disabled
8
11
  const shouldLocalize = typeof incomingPluginConfig.localize === 'boolean' ? incomingPluginConfig.localize : Boolean(config.localization);
9
12
  incomingPluginConfig.localize = shouldLocalize;
10
13
  if (collections) {
11
- const labels = Object.fromEntries(collections.filter(({ slug })=>incomingPluginConfig.collections?.includes(slug)).map((collection)=>[
12
- collection.slug,
13
- collection.labels
14
- ]));
14
+ // O(1) slug lookup for enabled-collection checks; replaces an Array.indexOf in the
15
+ // hook-attachment pass that was O(M) per collection.
16
+ const enabledSlugSet = new Set(incomingPluginConfig.collections ?? []);
17
+ const labels = {};
18
+ for (const collection of collections){
19
+ if (enabledSlugSet.has(collection.slug)) {
20
+ labels[collection.slug] = collection.labels;
21
+ }
22
+ }
15
23
  const pluginConfig = {
16
24
  // write any config defaults here
17
25
  deleteDrafts: true,
@@ -23,8 +31,7 @@ export const searchPlugin = (incomingPluginConfig)=>(config)=>{
23
31
  // add afterChange and afterDelete hooks to every search-enabled collection
24
32
  const collectionsWithSearchHooks = config?.collections?.map((collection)=>{
25
33
  const { hooks: existingHooks } = collection;
26
- const enabledCollections = pluginConfig.collections || [];
27
- const isEnabled = enabledCollections.indexOf(collection.slug) > -1;
34
+ const isEnabled = enabledSlugSet.has(collection.slug);
28
35
  if (isEnabled) {
29
36
  return {
30
37
  ...collection,
@@ -58,6 +65,7 @@ export const searchPlugin = (incomingPluginConfig)=>(config)=>{
58
65
  };
59
66
  }
60
67
  return config;
61
- };
68
+ }
69
+ });
62
70
 
63
71
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollectionAfterChangeHook, Config } from 'payload'\n\nimport type { SanitizedSearchPluginConfig, SearchPluginConfig } from './types.js'\n\nimport { deleteFromSearch } from './Search/hooks/deleteFromSearch.js'\nimport { syncWithSearch } from './Search/hooks/syncWithSearch.js'\nimport { generateSearchCollection } from './Search/index.js'\n\ntype CollectionAfterChangeHookArgs = Parameters<CollectionAfterChangeHook>[0]\n\nexport const searchPlugin =\n <ConfigTypes = unknown>(incomingPluginConfig: SearchPluginConfig<ConfigTypes>) =>\n (config: Config): Config => {\n const { collections } = config\n\n // If the user defines `localize` to either true or false, use that\n // Otherwise, set it based on if their config has localization enabled or disabled\n const shouldLocalize =\n typeof incomingPluginConfig.localize === 'boolean'\n ? incomingPluginConfig.localize\n : Boolean(config.localization)\n incomingPluginConfig.localize = shouldLocalize\n\n if (collections) {\n const labels = Object.fromEntries(\n collections\n .filter(({ slug }) => incomingPluginConfig.collections?.includes(slug))\n .map((collection) => [collection.slug, collection.labels]),\n )\n\n const pluginConfig: SanitizedSearchPluginConfig<ConfigTypes> = {\n // write any config defaults here\n deleteDrafts: true,\n labels,\n reindexBatchSize: incomingPluginConfig?.reindexBatchSize || 50,\n syncDrafts: false,\n ...incomingPluginConfig,\n }\n\n // add afterChange and afterDelete hooks to every search-enabled collection\n const collectionsWithSearchHooks = config?.collections\n ?.map((collection) => {\n const { hooks: existingHooks } = collection\n\n const enabledCollections = pluginConfig.collections || []\n const isEnabled = enabledCollections.indexOf(collection.slug) > -1\n if (isEnabled) {\n return {\n ...collection,\n hooks: {\n ...collection.hooks,\n afterChange: [\n ...(existingHooks?.afterChange || []),\n async (args: CollectionAfterChangeHookArgs) => {\n await syncWithSearch({\n ...args,\n collection: collection.slug,\n pluginConfig,\n })\n },\n ],\n beforeDelete: [\n ...(existingHooks?.beforeDelete || []),\n deleteFromSearch(pluginConfig),\n ],\n },\n }\n }\n\n return collection\n })\n .filter(Boolean)\n\n return {\n ...config,\n collections: [\n ...(collectionsWithSearchHooks || []),\n generateSearchCollection(pluginConfig),\n ],\n }\n }\n\n return config\n }\n"],"names":["deleteFromSearch","syncWithSearch","generateSearchCollection","searchPlugin","incomingPluginConfig","config","collections","shouldLocalize","localize","Boolean","localization","labels","Object","fromEntries","filter","slug","includes","map","collection","pluginConfig","deleteDrafts","reindexBatchSize","syncDrafts","collectionsWithSearchHooks","hooks","existingHooks","enabledCollections","isEnabled","indexOf","afterChange","args","beforeDelete"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,wBAAwB,QAAQ,oBAAmB;AAI5D,OAAO,MAAMC,eACX,CAAwBC,uBACxB,CAACC;QACC,MAAM,EAAEC,WAAW,EAAE,GAAGD;QAExB,mEAAmE;QACnE,kFAAkF;QAClF,MAAME,iBACJ,OAAOH,qBAAqBI,QAAQ,KAAK,YACrCJ,qBAAqBI,QAAQ,GAC7BC,QAAQJ,OAAOK,YAAY;QACjCN,qBAAqBI,QAAQ,GAAGD;QAEhC,IAAID,aAAa;YACf,MAAMK,SAASC,OAAOC,WAAW,CAC/BP,YACGQ,MAAM,CAAC,CAAC,EAAEC,IAAI,EAAE,GAAKX,qBAAqBE,WAAW,EAAEU,SAASD,OAChEE,GAAG,CAAC,CAACC,aAAe;oBAACA,WAAWH,IAAI;oBAAEG,WAAWP,MAAM;iBAAC;YAG7D,MAAMQ,eAAyD;gBAC7D,iCAAiC;gBACjCC,cAAc;gBACdT;gBACAU,kBAAkBjB,sBAAsBiB,oBAAoB;gBAC5DC,YAAY;gBACZ,GAAGlB,oBAAoB;YACzB;YAEA,2EAA2E;YAC3E,MAAMmB,6BAA6BlB,QAAQC,aACvCW,IAAI,CAACC;gBACL,MAAM,EAAEM,OAAOC,aAAa,EAAE,GAAGP;gBAEjC,MAAMQ,qBAAqBP,aAAab,WAAW,IAAI,EAAE;gBACzD,MAAMqB,YAAYD,mBAAmBE,OAAO,CAACV,WAAWH,IAAI,IAAI,CAAC;gBACjE,IAAIY,WAAW;oBACb,OAAO;wBACL,GAAGT,UAAU;wBACbM,OAAO;4BACL,GAAGN,WAAWM,KAAK;4BACnBK,aAAa;mCACPJ,eAAeI,eAAe,EAAE;gCACpC,OAAOC;oCACL,MAAM7B,eAAe;wCACnB,GAAG6B,IAAI;wCACPZ,YAAYA,WAAWH,IAAI;wCAC3BI;oCACF;gCACF;6BACD;4BACDY,cAAc;mCACRN,eAAeM,gBAAgB,EAAE;gCACrC/B,iBAAiBmB;6BAClB;wBACH;oBACF;gBACF;gBAEA,OAAOD;YACT,GACCJ,OAAOL;YAEV,OAAO;gBACL,GAAGJ,MAAM;gBACTC,aAAa;uBACPiB,8BAA8B,EAAE;oBACpCrB,yBAAyBiB;iBAC1B;YACH;QACF;QAEA,OAAOd;IACT,EAAC"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollectionAfterChangeHook } from 'payload'\n\nimport { definePlugin } from 'payload'\n\nimport type { SanitizedSearchPluginConfig, SearchPluginConfig } from './types.js'\n\nimport { deleteFromSearch } from './Search/hooks/deleteFromSearch.js'\nimport { syncWithSearch } from './Search/hooks/syncWithSearch.js'\nimport { generateSearchCollection } from './Search/index.js'\n\ntype CollectionAfterChangeHookArgs = Parameters<CollectionAfterChangeHook>[0]\n\nexport const searchPlugin = definePlugin<SearchPluginConfig>({\n slug: '@payloadcms/plugin-search',\n plugin: ({ config, options: incomingPluginConfig }) => {\n const { collections } = config\n\n // If the user defines `localize` to either true or false, use that\n // Otherwise, set it based on if their config has localization enabled or disabled\n const shouldLocalize =\n typeof incomingPluginConfig.localize === 'boolean'\n ? incomingPluginConfig.localize\n : Boolean(config.localization)\n incomingPluginConfig.localize = shouldLocalize\n\n if (collections) {\n // O(1) slug lookup for enabled-collection checks; replaces an Array.indexOf in the\n // hook-attachment pass that was O(M) per collection.\n const enabledSlugSet = new Set(incomingPluginConfig.collections ?? [])\n\n const labels: Record<string, (typeof collections)[number]['labels']> = {}\n for (const collection of collections) {\n if (enabledSlugSet.has(collection.slug)) {\n labels[collection.slug] = collection.labels\n }\n }\n\n const pluginConfig: SanitizedSearchPluginConfig = {\n // write any config defaults here\n deleteDrafts: true,\n labels,\n reindexBatchSize: incomingPluginConfig?.reindexBatchSize || 50,\n syncDrafts: false,\n ...incomingPluginConfig,\n }\n\n // add afterChange and afterDelete hooks to every search-enabled collection\n const collectionsWithSearchHooks = config?.collections\n ?.map((collection) => {\n const { hooks: existingHooks } = collection\n\n const isEnabled = enabledSlugSet.has(collection.slug)\n if (isEnabled) {\n return {\n ...collection,\n hooks: {\n ...collection.hooks,\n afterChange: [\n ...(existingHooks?.afterChange || []),\n async (args: CollectionAfterChangeHookArgs) => {\n await syncWithSearch({\n ...args,\n collection: collection.slug,\n pluginConfig,\n })\n },\n ],\n beforeDelete: [\n ...(existingHooks?.beforeDelete || []),\n deleteFromSearch(pluginConfig),\n ],\n },\n }\n }\n\n return collection\n })\n .filter(Boolean)\n\n return {\n ...config,\n collections: [\n ...(collectionsWithSearchHooks || []),\n generateSearchCollection(pluginConfig),\n ],\n }\n }\n\n return config\n },\n})\n"],"names":["definePlugin","deleteFromSearch","syncWithSearch","generateSearchCollection","searchPlugin","slug","plugin","config","options","incomingPluginConfig","collections","shouldLocalize","localize","Boolean","localization","enabledSlugSet","Set","labels","collection","has","pluginConfig","deleteDrafts","reindexBatchSize","syncDrafts","collectionsWithSearchHooks","map","hooks","existingHooks","isEnabled","afterChange","args","beforeDelete","filter"],"mappings":"AAEA,SAASA,YAAY,QAAQ,UAAS;AAItC,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,wBAAwB,QAAQ,oBAAmB;AAI5D,OAAO,MAAMC,eAAeJ,aAAiC;IAC3DK,MAAM;IACNC,QAAQ,CAAC,EAAEC,MAAM,EAAEC,SAASC,oBAAoB,EAAE;QAChD,MAAM,EAAEC,WAAW,EAAE,GAAGH;QAExB,mEAAmE;QACnE,kFAAkF;QAClF,MAAMI,iBACJ,O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d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CollectionAfterChangeHook, CollectionBeforeDeleteHook, CollectionConfig, Field, Locale, Payload, PayloadRequest, StaticLabel } from 'payload';
1
+ import type { CollectionAfterChangeHook, CollectionBeforeDeleteHook, CollectionConfig, Field, Locale, Payload, PayloadRequest, StaticLabel, TypedLocale } from 'payload';
2
2
  export type DocToSync = {
3
3
  [key: string]: any;
4
4
  doc: {
@@ -19,22 +19,13 @@ export type BeforeSync = (args: {
19
19
  export type FieldsOverride = (args: {
20
20
  defaultFields: Field[];
21
21
  }) => Field[];
22
- export type SkipSyncFunction<ConfigTypes = unknown> = (args: {
22
+ export type SkipSyncFunction = (args: {
23
23
  collectionSlug: string;
24
24
  doc: any;
25
- locale: ConfigTypes extends {
26
- locale: unknown;
27
- } ? ConfigTypes['locale'] : string | undefined;
25
+ locale: TypedLocale | undefined;
28
26
  req: PayloadRequest;
29
27
  }) => boolean | Promise<boolean>;
30
- export type SearchPluginConfig<ConfigTypes = unknown> = {
31
- /**
32
- * @deprecated
33
- * This plugin gets the api route from the config directly and does not need to be passed in.
34
- * As long as you have `routes.api` set in your Payload config, the plugin will use that.
35
- * This property will be removed in the next major version.
36
- */
37
- apiBasePath?: string;
28
+ export type SearchPluginConfig = {
38
29
  beforeSync?: BeforeSync;
39
30
  collections?: string[];
40
31
  defaultPriorities?: {
@@ -76,7 +67,7 @@ export type SearchPluginConfig<ConfigTypes = unknown> = {
76
67
  * return !tenant.allowedLocales.includes(locale)
77
68
  * }
78
69
  */
79
- skipSync?: SkipSyncFunction<ConfigTypes>;
70
+ skipSync?: SkipSyncFunction;
80
71
  /**
81
72
  * Controls whether drafts are synced to the search index
82
73
  *
@@ -90,13 +81,13 @@ export type CollectionLabels = {
90
81
  export type ResolvedCollectionLabels = {
91
82
  [collection: string]: StaticLabel;
92
83
  };
93
- export type SearchPluginConfigWithLocales<ConfigTypes = unknown> = {
84
+ export type SearchPluginConfigWithLocales = {
94
85
  labels?: CollectionLabels;
95
- } & SearchPluginConfig<ConfigTypes>;
96
- export type SanitizedSearchPluginConfig<ConfigTypes = unknown> = {
86
+ } & SearchPluginConfig;
87
+ export type SanitizedSearchPluginConfig = {
97
88
  reindexBatchSize: number;
98
89
  syncDrafts: boolean;
99
- } & SearchPluginConfigWithLocales<ConfigTypes>;
90
+ } & SearchPluginConfigWithLocales;
100
91
  export type SyncWithSearchArgs = {
101
92
  collection: string;
102
93
  pluginConfig: SanitizedSearchPluginConfig;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,yBAAyB,EACzB,0BAA0B,EAC1B,gBAAgB,EAChB,KAAK,EACL,MAAM,EACN,OAAO,EACP,cAAc,EACd,WAAW,EACZ,MAAM,SAAS,CAAA;AAEhB,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;IAClB,GAAG,EAAE;QACH,UAAU,EAAE,MAAM,CAAA;QAClB,KAAK,EAAE,MAAM,CAAA;KACd,CAAA;IACD,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AAED,MAAM,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE;IAC9B,cAAc,EAAE,MAAM,CAAA;IACtB,WAAW,EAAE;QACX,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KACnB,CAAA;IACD,OAAO,EAAE,OAAO,CAAA;IAChB,GAAG,EAAE,cAAc,CAAA;IACnB,SAAS,EAAE,SAAS,CAAA;CACrB,KAAK,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC,CAAA;AAEpC,MAAM,MAAM,cAAc,GAAG,CAAC,IAAI,EAAE;IAAE,aAAa,EAAE,KAAK,EAAE,CAAA;CAAE,KAAK,KAAK,EAAE,CAAA;AAE1E,MAAM,MAAM,gBAAgB,CAAC,WAAW,GAAG,OAAO,IAAI,CAAC,IAAI,EAAE;IAC3D,cAAc,EAA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version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n CollectionAfterChangeHook,\n CollectionBeforeDeleteHook,\n CollectionConfig,\n Field,\n Locale,\n Payload,\n PayloadRequest,\n StaticLabel,\n} from 'payload'\n\nexport type DocToSync = {\n [key: string]: any\n doc: {\n relationTo: string\n value: string\n }\n title: string\n}\n\nexport type BeforeSync = (args: {\n collectionSlug: string\n originalDoc: {\n [key: string]: any\n }\n payload: Payload\n req: PayloadRequest\n searchDoc: DocToSync\n}) => DocToSync | Promise<DocToSync>\n\nexport type FieldsOverride = (args: { defaultFields: Field[] }) => Field[]\n\nexport type SkipSyncFunction<ConfigTypes = unknown> = (args: {\n collectionSlug: string\n doc: any\n locale: ConfigTypes extends { locale: unknown } ? ConfigTypes['locale'] : string | undefined\n req: PayloadRequest\n}) => boolean | Promise<boolean>\n\nexport type SearchPluginConfig<ConfigTypes = unknown> = {\n /**\n * @deprecated\n * This plugin gets the api route from the config directly and does not need to be passed in.\n * As long as you have `routes.api` set in your Payload config, the plugin will use that.\n * This property will be removed in the next major version.\n */\n apiBasePath?: string\n beforeSync?: BeforeSync\n collections?: string[]\n defaultPriorities?: {\n [collection: string]: ((doc: any) => number | Promise<number>) | number\n }\n /**\n * Controls whether drafts are deleted from the search index\n *\n * @default true\n */\n deleteDrafts?: boolean\n localize?: boolean\n /**\n * We use batching when re-indexing large collections. You can control the amount of items per batch, lower numbers should help with memory.\n *\n * @default 50\n */\n reindexBatchSize?: number\n searchOverrides?: { fields?: FieldsOverride } & Partial<Omit<CollectionConfig, 'fields'>>\n /**\n * Determine whether to skip syncing a document for a specific locale.\n * Useful for multi-tenant applications, conditional indexing, or any scenario where\n * sync behavior should vary by locale, document, or other factors.\n *\n * @default undefined - All configured locales will be synced\n *\n * @example\n * // Skip syncing based on document's tenant settings\n * skipSync: async ({ locale, req, doc, collectionSlug }) => {\n * // For non-localized collections, locale will be undefined\n * if (!locale) return false\n *\n * const tenant = await req.payload.findByID({\n * collection: 'tenants',\n * id: doc.tenant.id\n * })\n * return !tenant.allowedLocales.includes(locale)\n * }\n */\n skipSync?: SkipSyncFunction<ConfigTypes>\n /**\n * Controls whether drafts are synced to the search index\n *\n * @default false\n */\n syncDrafts?: boolean\n}\n\nexport type CollectionLabels = {\n [collection: string]: CollectionConfig['labels']\n}\n\nexport type ResolvedCollectionLabels = {\n [collection: string]: StaticLabel\n}\n\nexport type SearchPluginConfigWithLocales<ConfigTypes = unknown> = {\n labels?: CollectionLabels\n} & SearchPluginConfig<ConfigTypes>\n\nexport type SanitizedSearchPluginConfig<ConfigTypes = unknown> = {\n reindexBatchSize: number\n syncDrafts: boolean\n} & SearchPluginConfigWithLocales<ConfigTypes>\n\nexport type SyncWithSearchArgs = {\n collection: string\n pluginConfig: SanitizedSearchPluginConfig\n} & Omit<Parameters<CollectionAfterChangeHook>[0], 'collection'>\n\nexport type SyncDocArgs = {\n locale?: Locale['code']\n onSyncError?: () => void\n} & Omit<SyncWithSearchArgs, 'context' | 'previousDoc'>\n\n// Extend the `CollectionAfterChangeHook` with more function args\n// Convert the `collection` arg from `SanitizedCollectionConfig` to a string\nexport type SyncWithSearch = (Args: SyncWithSearchArgs) => ReturnType<CollectionAfterChangeHook>\n\nexport type DeleteFromSearch = (args: SearchPluginConfig) => CollectionBeforeDeleteHook\n"],"names":[],"mappings":"AA8HA,WAAuF"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n CollectionAfterChangeHook,\n CollectionBeforeDeleteHook,\n CollectionConfig,\n Field,\n Locale,\n Payload,\n PayloadRequest,\n StaticLabel,\n TypedLocale,\n} from 'payload'\n\nexport type DocToSync = {\n [key: string]: any\n doc: {\n relationTo: string\n value: string\n }\n title: string\n}\n\nexport type BeforeSync = (args: {\n collectionSlug: string\n originalDoc: {\n [key: string]: any\n }\n payload: Payload\n req: PayloadRequest\n searchDoc: DocToSync\n}) => DocToSync | Promise<DocToSync>\n\nexport type FieldsOverride = (args: { defaultFields: Field[] }) => Field[]\n\nexport type SkipSyncFunction = (args: {\n collectionSlug: string\n doc: any\n locale: TypedLocale | undefined\n req: PayloadRequest\n}) => boolean | Promise<boolean>\n\nexport type SearchPluginConfig = {\n beforeSync?: BeforeSync\n collections?: string[]\n defaultPriorities?: {\n [collection: string]: ((doc: any) => number | Promise<number>) | number\n }\n /**\n * Controls whether drafts are deleted from the search index\n *\n * @default true\n */\n deleteDrafts?: boolean\n localize?: boolean\n /**\n * We use batching when re-indexing large collections. You can control the amount of items per batch, lower numbers should help with memory.\n *\n * @default 50\n */\n reindexBatchSize?: number\n searchOverrides?: { fields?: FieldsOverride } & Partial<Omit<CollectionConfig, 'fields'>>\n /**\n * Determine whether to skip syncing a document for a specific locale.\n * Useful for multi-tenant applications, conditional indexing, or any scenario where\n * sync behavior should vary by locale, document, or other factors.\n *\n * @default undefined - All configured locales will be synced\n *\n * @example\n * // Skip syncing based on document's tenant settings\n * skipSync: async ({ locale, req, doc, collectionSlug }) => {\n * // For non-localized collections, locale will be undefined\n * if (!locale) return false\n *\n * const tenant = await req.payload.findByID({\n * collection: 'tenants',\n * id: doc.tenant.id\n * })\n * return !tenant.allowedLocales.includes(locale)\n * }\n */\n skipSync?: SkipSyncFunction\n /**\n * Controls whether drafts are synced to the search index\n *\n * @default false\n */\n syncDrafts?: boolean\n}\n\nexport type CollectionLabels = {\n [collection: string]: CollectionConfig['labels']\n}\n\nexport type ResolvedCollectionLabels = {\n [collection: string]: StaticLabel\n}\n\nexport type SearchPluginConfigWithLocales = {\n labels?: CollectionLabels\n} & SearchPluginConfig\n\nexport type SanitizedSearchPluginConfig = {\n reindexBatchSize: number\n syncDrafts: boolean\n} & SearchPluginConfigWithLocales\n\nexport type SyncWithSearchArgs = {\n collection: string\n pluginConfig: SanitizedSearchPluginConfig\n} & Omit<Parameters<CollectionAfterChangeHook>[0], 'collection'>\n\nexport type SyncDocArgs = {\n locale?: Locale['code']\n onSyncError?: () => void\n} & Omit<SyncWithSearchArgs, 'context' | 'previousDoc'>\n\n// Extend the `CollectionAfterChangeHook` with more function args\n// Convert the `collection` arg from `SanitizedCollectionConfig` to a string\nexport type SyncWithSearch = (Args: SyncWithSearchArgs) => ReturnType<CollectionAfterChangeHook>\n\nexport type DeleteFromSearch = (args: SearchPluginConfig) => CollectionBeforeDeleteHook\n"],"names":[],"mappings":"AAwHA,WAAuF"}
@@ -1 +1 @@
1
- {"version":3,"file":"generateReindexHandler.d.ts","sourceRoot":"","sources":["../../src/utilities/generateReindexHandler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAS,MAAM,SAAS,CAAA;AAWpD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAS9D,eAAO,MAAM,sBAAsB,iBAClB,2BAA2B,KAAG,cAwN5C,CAAA"}
1
+ {"version":3,"file":"generateReindexHandler.d.ts","sourceRoot":"","sources":["../../src/utilities/generateReindexHandler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAS,MAAM,SAAS,CAAA;AAWpD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAS9D,eAAO,MAAM,sBAAsB,iBAClB,2BAA2B,KAAG,cAyN5C,CAAA"}
@@ -78,6 +78,7 @@ export const generateReindexHandler = (pluginConfig)=>async (req)=>{
78
78
  }
79
79
  const payload = req.payload;
80
80
  const { reindexBatchSize: batchSize, syncDrafts } = pluginConfig;
81
+ const defaultLocale = payload.config.localization ? payload.config.localization.defaultLocale : req.locale;
81
82
  const defaultLocalApiProps = {
82
83
  overrideAccess: false,
83
84
  req,
@@ -92,6 +93,7 @@ export const generateReindexHandler = (pluginConfig)=>async (req)=>{
92
93
  const { totalDocs } = await payload.count({
93
94
  collection,
94
95
  ...defaultLocalApiProps,
96
+ locale: defaultLocale,
95
97
  req: undefined,
96
98
  where: drafts ? undefined : whereStatusPublished
97
99
  });
@@ -120,7 +122,6 @@ export const generateReindexHandler = (pluginConfig)=>async (req)=>{
120
122
  let localErrors = 0;
121
123
  // Loop through batches, then documents, then locales per document
122
124
  for(let i = 0; i < totalBatches; i++){
123
- const defaultLocale = req.payload.config.localization ? req.payload.config.localization.defaultLocale : req.locale;
124
125
  const { docs } = await payload.find({
125
126
  collection,
126
127
  depth: 0,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/generateReindexHandler.ts"],"sourcesContent":["import type { PayloadHandler, Where } from 'payload'\n\nimport {\n addLocalesToRequestFromData,\n commitTransaction,\n getAccessResults,\n headersWithCors,\n initTransaction,\n killTransaction,\n} from 'payload'\n\nimport type { SanitizedSearchPluginConfig } from '../types.js'\n\nimport { syncDocAsSearchIndex } from './syncDocAsSearchIndex.js'\n\ntype ValidationResult = {\n isValid: boolean\n message?: string\n}\n\nexport const generateReindexHandler =\n (pluginConfig: SanitizedSearchPluginConfig): PayloadHandler =>\n async (req) => {\n addLocalesToRequestFromData(req)\n if (!req.json) {\n return new Response('Req.json is undefined', { status: 400 })\n }\n const { collections = [] } = (await req.json()) as { collections: string[] }\n const t = req.t\n\n const searchSlug = pluginConfig?.searchOverrides?.slug || 'search'\n const searchCollections = pluginConfig?.collections || []\n\n async function validatePermissions(): Promise<ValidationResult> {\n const accessResults = await getAccessResults({ req })\n const searchAccessResults = accessResults.collections?.[searchSlug]\n if (!searchAccessResults) {\n return { isValid: false, message: t('error:notAllowedToPerformAction') }\n }\n\n const permissions = [searchAccessResults.delete, searchAccessResults.update]\n // plugin doesn't allow create by default:\n // if user provided, then add it to check\n if (pluginConfig.searchOverrides?.access?.create) {\n permissions.push(searchAccessResults.create)\n }\n // plugin allows reads by anyone by default:\n // so if user provided, then add to check\n if (pluginConfig.searchOverrides?.access?.read) {\n permissions.push(searchAccessResults.read)\n }\n return permissions.every(Boolean)\n ? { isValid: true }\n : { isValid: false, message: t('error:notAllowedToPerformAction') }\n }\n\n function validateCollections(): ValidationResult {\n const collectionsAreValid = collections.every((col) => searchCollections.includes(col))\n return collections.length && collectionsAreValid\n ? { isValid: true }\n : { isValid: false, message: t('error:invalidRequestArgs', { args: `'collections'` }) }\n }\n\n const headers = headersWithCors({\n headers: new Headers(),\n req,\n })\n\n const { isValid: hasPermissions, message: permissionError } = await validatePermissions()\n if (!hasPermissions) {\n return Response.json({ message: permissionError }, { headers, status: 401 })\n }\n\n const { isValid: validCollections, message: collectionError } = validateCollections()\n if (!validCollections) {\n return Response.json({ message: collectionError }, { headers, status: 400 })\n }\n\n const payload = req.payload\n const { reindexBatchSize: batchSize, syncDrafts } = pluginConfig\n\n const defaultLocalApiProps = {\n overrideAccess: false,\n req,\n user: req.user,\n }\n const whereStatusPublished: Where = {\n _status: {\n equals: 'published',\n },\n }\n async function countDocuments(collection: string, drafts?: boolean): Promise<number> {\n const { totalDocs } = await payload.count({\n collection,\n ...defaultLocalApiProps,\n req: undefined,\n where: drafts ? undefined : whereStatusPublished,\n })\n return totalDocs\n }\n\n async function deleteIndexes(collection: string) {\n await payload.delete({\n collection: searchSlug,\n depth: 0,\n select: { id: true },\n where: { 'doc.relationTo': { equals: collection } },\n ...defaultLocalApiProps,\n })\n }\n\n async function reindexCollection(\n collection: string,\n ): Promise<{ docs: number; docsWithDrafts: number; errors: number }> {\n const draftsEnabled = Boolean(payload.collections[collection]?.config.versions?.drafts)\n\n const totalDocsWithDrafts = await countDocuments(collection, true)\n const totalDocs =\n syncDrafts || !draftsEnabled\n ? totalDocsWithDrafts\n : await countDocuments(collection, !draftsEnabled)\n const totalBatches = Math.ceil(totalDocs / batchSize)\n\n let localErrors = 0\n\n // Loop through batches, then documents, then locales per document\n for (let i = 0; i < totalBatches; i++) {\n const defaultLocale = req.payload.config.localization\n ? req.payload.config.localization.defaultLocale\n : req.locale\n\n const { docs } = await payload.find({\n collection,\n depth: 0,\n limit: batchSize,\n locale: defaultLocale,\n page: i + 1,\n where: syncDrafts || !draftsEnabled ? undefined : whereStatusPublished,\n ...defaultLocalApiProps,\n })\n\n for (const doc of docs) {\n // Get all configured locales\n // If no localization, use [undefined] to sync once without a locale\n const allLocales = req.payload.config.localization\n ? req.payload.config.localization.localeCodes\n : [undefined]\n\n // Loop through all locales and check each one\n let firstAllowedLocale = true\n for (const localeToSync of allLocales) {\n // Check if we should skip this locale for this document\n let shouldSkip = false\n if (typeof pluginConfig.skipSync === 'function') {\n try {\n shouldSkip = await pluginConfig.skipSync({\n collectionSlug: collection,\n doc,\n locale: localeToSync,\n req,\n })\n } catch (err) {\n req.payload.logger.error({\n err,\n msg: 'Search plugin: Error executing skipSync. Proceeding with sync.',\n })\n }\n }\n\n if (shouldSkip) {\n continue // Skip this locale\n }\n\n // Sync this locale (create first index, then update with other locales accordingly)\n const operation = firstAllowedLocale ? 'create' : 'update'\n firstAllowedLocale = false\n\n await syncDocAsSearchIndex({\n collection,\n data: doc,\n doc,\n locale: localeToSync,\n onSyncError: () => operation === 'create' && localErrors++,\n operation,\n pluginConfig,\n req,\n })\n }\n }\n }\n\n return { docs: totalDocs, docsWithDrafts: totalDocsWithDrafts, errors: localErrors }\n }\n\n const shouldCommit = await initTransaction(req)\n\n // Collections are processed sequentially to avoid race conditions within the shared transaction.\n // Concurrent writes to the search collection interleave on the same DB connection and can cause\n // locale data to be missing non-deterministically.\n const results: Array<{ docs: number; docsWithDrafts: number; errors: number }> = []\n try {\n for (const collection of collections) {\n try {\n await deleteIndexes(collection)\n results.push(await reindexCollection(collection))\n } catch (err) {\n const message = t('error:unableToReindexCollection', { collection })\n payload.logger.error({ err, msg: message })\n results.push({ docs: 0, docsWithDrafts: 0, errors: 0 })\n }\n }\n } catch (err: unknown) {\n if (shouldCommit) {\n await killTransaction(req)\n }\n return Response.json(\n { message: err instanceof Error ? err.message : String(err) },\n { headers, status: 500 },\n )\n }\n\n const aggregateDocsWithDrafts = results.reduce((sum, r) => sum + r.docsWithDrafts, 0)\n const aggregateDocs = results.reduce((sum, r) => sum + r.docs, 0)\n const aggregateErrors = results.reduce((sum, r) => sum + r.errors, 0)\n\n const message = t('general:successfullyReindexed', {\n collections: collections.join(', '),\n count: aggregateDocs - aggregateErrors,\n skips: syncDrafts ? 0 : aggregateDocsWithDrafts - aggregateDocs,\n total: aggregateDocsWithDrafts,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n return Response.json({ message }, { headers, status: 200 })\n }\n"],"names":["addLocalesToRequestFromData","commitTransaction","getAccessResults","headersWithCors","initTransaction","killTransaction","syncDocAsSearchIndex","generateReindexHandler","pluginConfig","req","json","Response","status","collections","t","searchSlug","searchOverrides","slug","searchCollections","validatePermissions","accessResults","searchAccessResults","isValid","message","permissions","delete","update","access","create","push","read","every","Boolean","validateCollections","collectionsAreValid","col","includes","length","args","headers","Headers","hasPermissions","permissionError","validCollections","collectionError","payload","reindexBatchSize","batchSize","syncDrafts","defaultLocalApiProps","overrideAccess","user","whereStatusPublished","_status","equals","countDocuments","collection","drafts","totalDocs","count","undefined","where","deleteIndexes","depth","select","id","reindexCollection","draftsEnabled","config","versions","totalDocsWithDrafts","totalBatches","Math","ceil","localErrors","i","defaultLocale","localization","locale","docs","find","limit","page","doc","allLocales","localeCodes","firstAllowedLocale","localeToSync","shouldSkip","skipSync","collectionSlug","err","logger","error","msg","operation","data","onSyncError","docsWithDrafts","errors","shouldCommit","results","Error","String","aggregateDocsWithDrafts","reduce","sum","r","aggregateDocs","aggregateErrors","join","skips","total"],"mappings":"AAEA,SACEA,2BAA2B,EAC3BC,iBAAiB,EACjBC,gBAAgB,EAChBC,eAAe,EACfC,eAAe,EACfC,eAAe,QACV,UAAS;AAIhB,SAASC,oBAAoB,QAAQ,4BAA2B;AAOhE,OAAO,MAAMC,yBACX,CAACC,eACD,OAAOC;QACLT,4BAA4BS;QAC5B,IAAI,CAACA,IAAIC,IAAI,EAAE;YACb,OAAO,IAAIC,SAAS,yBAAyB;gBAAEC,QAAQ;YAAI;QAC7D;QACA,MAAM,EAAEC,cAAc,EAAE,EAAE,GAAI,MAAMJ,IAAIC,IAAI;QAC5C,MAAMI,IAAIL,IAAIK,CAAC;QAEf,MAAMC,aAAaP,cAA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a,IAAIwD,0BAA0BI;YAClDI,OAAOR;QACT;QAEA,IAAIJ,cAAc;YAChB,MAAMnG,kBAAkBQ;QAC1B;QAEA,OAAOE,SAASD,IAAI,CAAC;YAAEa;QAAQ,GAAG;YAAEgB;YAAS3B,QAAQ;QAAI;IAC3D,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/generateReindexHandler.ts"],"sourcesContent":["import type { PayloadHandler, Where } from 'payload'\n\nimport {\n addLocalesToRequestFromData,\n commitTransaction,\n getAccessResults,\n headersWithCors,\n initTransaction,\n killTransaction,\n} from 'payload'\n\nimport type { SanitizedSearchPluginConfig } from '../types.js'\n\nimport { syncDocAsSearchIndex } from './syncDocAsSearchIndex.js'\n\ntype ValidationResult = {\n isValid: boolean\n message?: string\n}\n\nexport const generateReindexHandler =\n (pluginConfig: SanitizedSearchPluginConfig): PayloadHandler =>\n async (req) => {\n addLocalesToRequestFromData(req)\n if (!req.json) {\n return new Response('Req.json is undefined', { status: 400 })\n }\n const { collections = [] } = (await req.json()) as { collections: string[] }\n const t = req.t\n\n const searchSlug = pluginConfig?.searchOverrides?.slug || 'search'\n const searchCollections = pluginConfig?.collections || []\n\n async function validatePermissions(): Promise<ValidationResult> {\n const accessResults = await getAccessResults({ req })\n const searchAccessResults = accessResults.collections?.[searchSlug]\n if (!searchAccessResults) {\n return { isValid: false, message: t('error:notAllowedToPerformAction') }\n }\n\n const permissions = [searchAccessResults.delete, searchAccessResults.update]\n // plugin doesn't allow create by default:\n // if user provided, then add it to check\n if (pluginConfig.searchOverrides?.access?.create) {\n permissions.push(searchAccessResults.create)\n }\n // plugin allows reads by anyone by default:\n // so if user provided, then add to check\n if (pluginConfig.searchOverrides?.access?.read) {\n permissions.push(searchAccessResults.read)\n }\n return permissions.every(Boolean)\n ? { isValid: true }\n : { isValid: false, message: t('error:notAllowedToPerformAction') }\n }\n\n function validateCollections(): ValidationResult {\n const collectionsAreValid = collections.every((col) => searchCollections.includes(col))\n return collections.length && collectionsAreValid\n ? { isValid: true }\n : { isValid: false, message: t('error:invalidRequestArgs', { args: `'collections'` }) }\n }\n\n const headers = headersWithCors({\n headers: new Headers(),\n req,\n })\n\n const { isValid: hasPermissions, message: permissionError } = await validatePermissions()\n if (!hasPermissions) {\n return Response.json({ message: permissionError }, { headers, status: 401 })\n }\n\n const { isValid: validCollections, message: collectionError } = validateCollections()\n if (!validCollections) {\n return Response.json({ message: collectionError }, { headers, status: 400 })\n }\n\n const payload = req.payload\n const { reindexBatchSize: batchSize, syncDrafts } = pluginConfig\n\n const defaultLocale = payload.config.localization\n ? payload.config.localization.defaultLocale\n : req.locale\n\n const defaultLocalApiProps = {\n overrideAccess: false,\n req,\n user: req.user,\n }\n const whereStatusPublished: Where = {\n _status: {\n equals: 'published',\n },\n }\n async function countDocuments(collection: string, drafts?: boolean): Promise<number> {\n const { totalDocs } = await payload.count({\n collection,\n ...defaultLocalApiProps,\n locale: defaultLocale,\n req: undefined,\n where: drafts ? undefined : whereStatusPublished,\n })\n return totalDocs\n }\n\n async function deleteIndexes(collection: string) {\n await payload.delete({\n collection: searchSlug,\n depth: 0,\n select: { id: true },\n where: { 'doc.relationTo': { equals: collection } },\n ...defaultLocalApiProps,\n })\n }\n\n async function reindexCollection(\n collection: string,\n ): Promise<{ docs: number; docsWithDrafts: number; errors: number }> {\n const draftsEnabled = Boolean(payload.collections[collection]?.config.versions?.drafts)\n\n const totalDocsWithDrafts = await countDocuments(collection, true)\n const totalDocs =\n syncDrafts || !draftsEnabled\n ? totalDocsWithDrafts\n : await countDocuments(collection, !draftsEnabled)\n const totalBatches = Math.ceil(totalDocs / batchSize)\n\n let localErrors = 0\n\n // Loop through batches, then documents, then locales per document\n for (let i = 0; i < totalBatches; i++) {\n const { docs } = await payload.find({\n collection,\n depth: 0,\n limit: batchSize,\n locale: defaultLocale,\n page: i + 1,\n where: syncDrafts || !draftsEnabled ? undefined : whereStatusPublished,\n ...defaultLocalApiProps,\n })\n\n for (const doc of docs) {\n // Get all configured locales\n // If no localization, use [undefined] to sync once without a locale\n const allLocales = req.payload.config.localization\n ? req.payload.config.localization.localeCodes\n : [undefined]\n\n // Loop through all locales and check each one\n let firstAllowedLocale = true\n for (const localeToSync of allLocales) {\n // Check if we should skip this locale for this document\n let shouldSkip = false\n if (typeof pluginConfig.skipSync === 'function') {\n try {\n shouldSkip = await pluginConfig.skipSync({\n collectionSlug: collection,\n doc,\n locale: localeToSync,\n req,\n })\n } catch (err) {\n req.payload.logger.error({\n err,\n msg: 'Search plugin: Error executing skipSync. Proceeding with sync.',\n })\n }\n }\n\n if (shouldSkip) {\n continue // Skip this locale\n }\n\n // Sync this locale (create first index, then update with other locales accordingly)\n const operation = firstAllowedLocale ? 'create' : 'update'\n firstAllowedLocale = false\n\n await syncDocAsSearchIndex({\n collection,\n data: doc,\n doc,\n locale: localeToSync,\n onSyncError: () => operation === 'create' && localErrors++,\n operation,\n pluginConfig,\n req,\n })\n }\n }\n }\n\n return { docs: totalDocs, docsWithDrafts: totalDocsWithDrafts, errors: localErrors }\n }\n\n const shouldCommit = await initTransaction(req)\n\n // Collections are processed sequentially to avoid race conditions within the shared transaction.\n // Concurrent writes to the search collection interleave on the same DB connection and can cause\n // locale data to be missing non-deterministically.\n const results: Array<{ docs: number; docsWithDrafts: number; errors: number }> = []\n try {\n for (const collection of collections) {\n try {\n await deleteIndexes(collection)\n results.push(await reindexCollection(collection))\n } catch (err) {\n const message = t('error:unableToReindexCollection', { collection })\n payload.logger.error({ err, msg: message })\n results.push({ docs: 0, docsWithDrafts: 0, errors: 0 })\n }\n }\n } catch (err: unknown) {\n if (shouldCommit) {\n await killTransaction(req)\n }\n return Response.json(\n { message: err instanceof Error ? err.message : String(err) },\n { headers, status: 500 },\n )\n }\n\n const aggregateDocsWithDrafts = results.reduce((sum, r) => sum + r.docsWithDrafts, 0)\n const aggregateDocs = results.reduce((sum, r) => sum + r.docs, 0)\n const aggregateErrors = results.reduce((sum, r) => sum + r.errors, 0)\n\n const message = t('general:successfullyReindexed', {\n collections: collections.join(', '),\n count: aggregateDocs - aggregateErrors,\n skips: syncDrafts ? 0 : aggregateDocsWithDrafts - aggregateDocs,\n total: aggregateDocsWithDrafts,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n return Response.json({ message }, { headers, status: 200 })\n }\n"],"names":["addLocalesToRequestFromData","commitTransaction","getAccessResults","headersWithCors","initTransaction","killTransaction","syncDocAsSearchIndex","generateReindexHandler","pluginConfig","req","json","Response","status","collections","t","searchSlug","searchOverrides","slug","searchCollections","validatePermissions","accessResults","searchAccessResults","isValid","message","permissions","delete","update","access","create","push","read","every","Boolean","validateCollections","collectionsAreValid","col","includes","length","args","headers","Headers","hasPermissions","permissionError","validCollections","collectionError","payload","reindexBatchSize","batchSize","syncDrafts","defaultLocale","config","localization","locale","defaultLocalApiProps","overrideAccess","user","whereStatusPublished","_status","equals","countDocuments","collection","drafts","totalDocs","count","undefined","where","deleteIndexes","depth","select","id","reindexCollection","draftsEnabled","versions","totalDocsWithDrafts","totalBatches","Math","ceil","localErrors","i","docs","find","limit","page","doc","allLocales","localeCodes","firstAllowedLocale","localeToSync","shouldSkip","skipSync","collectionSlug","err","logger","error","msg","operation","data","onSyncError","docsWithDrafts","errors","shouldCommit","results","Error","String","aggregateDocsWithDrafts","reduce","sum","r","aggregateDocs","aggregateErrors","join","skips","total"],"mappings":"AAEA,SACEA,2BAA2B,EAC3BC,iBAAiB,EACjBC,gBAAgB,EAChBC,eAAe,EACfC,eAAe,EACfC,eAAe,QACV,UAAS;AAIhB,SAASC,oBAAoB,QAAQ,4BAA2B;AAOhE,OAAO,MAAMC,yBACX,CAACC,eACD,OAAOC;QACLT,4BAA4BS;QAC5B,IAAI,CAACA,IAAIC,IAAI,EAAE;YACb,OAAO,IAAIC,SAAS,yBAAyB;gBAAEC,QAAQ;YAAI;QAC7D;QACA,MAAM,EAAEC,cAAc,EAAE,EAAE,GAAI,MAAMJ,IAAIC,IAAI;QAC5C,MAAMI,IAAIL,IAAIK,CAAC;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OAAO/D,aAAa,IAAIwD,0BAA0BI;YAClDI,OAAOR;QACT;QAEA,IAAIJ,cAAc;YAChB,MAAMnG,kBAAkBQ;QAC1B;QAEA,OAAOE,SAASD,IAAI,CAAC;YAAEa;QAAQ,GAAG;YAAEgB;YAAS3B,QAAQ;QAAI;IAC3D,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"syncDocAsSearchIndex.d.ts","sourceRoot":"","sources":["../../src/utilities/syncDocAsSearchIndex.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAa,WAAW,EAAE,MAAM,aAAa,CAAA;AAEzD,eAAO,MAAM,oBAAoB,8FAS9B,WAAW,iBAgRb,CAAA"}
1
+ {"version":3,"file":"syncDocAsSearchIndex.d.ts","sourceRoot":"","sources":["../../src/utilities/syncDocAsSearchIndex.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAa,WAAW,EAAE,MAAM,aAAa,CAAA;AAEzD,eAAO,MAAM,oBAAoB,8FAS9B,WAAW,iBAyRb,CAAA"}
@@ -51,6 +51,7 @@ export const syncDocAsSearchIndex = async ({ collection, doc, locale, onSyncErro
51
51
  id,
52
52
  collection,
53
53
  locale: syncLocale,
54
+ overrideAccess: true,
54
55
  req,
55
56
  // Include trashed documents when the document being synced is trashed
56
57
  trash: isTrashDocument
@@ -89,6 +90,7 @@ export const syncDocAsSearchIndex = async ({ collection, doc, locale, onSyncErro
89
90
  },
90
91
  depth: 0,
91
92
  locale: syncLocale,
93
+ overrideAccess: true,
92
94
  req
93
95
  });
94
96
  }
@@ -99,6 +101,7 @@ export const syncDocAsSearchIndex = async ({ collection, doc, locale, onSyncErro
99
101
  collection: searchSlug,
100
102
  depth: 0,
101
103
  locale: syncLocale,
104
+ overrideAccess: true,
102
105
  req,
103
106
  where: {
104
107
  'doc.relationTo': {
@@ -119,6 +122,7 @@ export const syncDocAsSearchIndex = async ({ collection, doc, locale, onSyncErro
119
122
  await payload.delete({
120
123
  collection: searchSlug,
121
124
  depth: 0,
125
+ overrideAccess: true,
122
126
  req,
123
127
  where: {
124
128
  id: {
@@ -143,6 +147,7 @@ export const syncDocAsSearchIndex = async ({ collection, doc, locale, onSyncErro
143
147
  id: searchDocID,
144
148
  collection: searchSlug,
145
149
  depth: 0,
150
+ overrideAccess: true,
146
151
  req
147
152
  });
148
153
  } catch (err) {
@@ -164,6 +169,7 @@ export const syncDocAsSearchIndex = async ({ collection, doc, locale, onSyncErro
164
169
  },
165
170
  depth: 0,
166
171
  locale: syncLocale,
172
+ overrideAccess: true,
167
173
  req
168
174
  });
169
175
  } catch (err) {
@@ -182,6 +188,7 @@ export const syncDocAsSearchIndex = async ({ collection, doc, locale, onSyncErro
182
188
  draft: false,
183
189
  limit: 1,
184
190
  locale: syncLocale,
191
+ overrideAccess: true,
185
192
  pagination: false,
186
193
  req,
187
194
  where: {
@@ -206,6 +213,7 @@ export const syncDocAsSearchIndex = async ({ collection, doc, locale, onSyncErro
206
213
  id: searchDocID,
207
214
  collection: searchSlug,
208
215
  depth: 0,
216
+ overrideAccess: true,
209
217
  req
210
218
  });
211
219
  } catch (err) {
@@ -227,6 +235,7 @@ export const syncDocAsSearchIndex = async ({ collection, doc, locale, onSyncErro
227
235
  },
228
236
  depth: 0,
229
237
  locale: syncLocale,
238
+ overrideAccess: true,
230
239
  req
231
240
  });
232
241
  } catch (err) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/syncDocAsSearchIndex.ts"],"sourcesContent":["import type { DocToSync, SyncDocArgs } from '../types.js'\n\nexport const syncDocAsSearchIndex = async ({\n collection,\n doc,\n locale,\n onSyncError,\n operation,\n pluginConfig,\n req: { payload },\n req,\n}: SyncDocArgs) => {\n const { id, _status: status, title } = doc || {}\n\n const { beforeSync, defaultPriorities, deleteDrafts, searchOverrides, syncDrafts } = pluginConfig\n\n const searchSlug = searchOverrides?.slug || 'search'\n\n // Determine sync locale\n const syncLocale = locale || req.locale || undefined\n\n if (typeof pluginConfig.skipSync === 'function') {\n try {\n const skipSync = await pluginConfig.skipSync({\n collectionSlug: collection,\n doc,\n locale: syncLocale,\n req,\n })\n\n if (skipSync) {\n return doc\n }\n } catch (err) {\n req.payload.logger.error({\n err,\n msg: 'Search plugin: Error executing skipSync. Proceeding with sync.',\n })\n }\n }\n\n let dataToSave: DocToSync = {\n doc: {\n relationTo: collection,\n value: id,\n },\n title,\n }\n const docKeyPrefix = `${collection}:${id}`\n const docKey = req.payload.config.localization ? `${docKeyPrefix}:${syncLocale}` : docKeyPrefix\n const syncedDocsSet = (req.context?.syncedDocsSet as Set<string>) || new Set<string>()\n\n if (syncedDocsSet.has(docKey)) {\n /*\n * prevents duplicate syncing of documents in the same request\n * this can happen when hooks call `payload.update` within the create lifecycle\n * like the nested-docs plugin does\n */\n return doc\n } else {\n syncedDocsSet.add(docKey)\n }\n\n req.context.syncedDocsSet = syncedDocsSet\n\n if (typeof beforeSync === 'function') {\n let docToSyncWith = doc\n if (payload.config?.localization) {\n // Check if document is trashed (has deletedAt field)\n const isTrashDocument = doc && 'deletedAt' in doc && doc.deletedAt\n\n docToSyncWith = await payload.findByID({\n id,\n collection,\n locale: syncLocale,\n req,\n // Include trashed documents when the document being synced is trashed\n trash: isTrashDocument,\n })\n }\n dataToSave = await beforeSync({\n collectionSlug: collection,\n originalDoc: docToSyncWith,\n payload,\n req,\n searchDoc: dataToSave,\n })\n }\n\n let defaultPriority = 0\n if (defaultPriorities) {\n const { [collection]: priority } = defaultPriorities\n\n if (typeof priority === 'function') {\n try {\n defaultPriority = await priority(doc)\n } catch (err: unknown) {\n payload.logger.error(err)\n payload.logger.error(\n `Error gathering default priority for ${searchSlug} documents related to ${collection}`,\n )\n }\n } else if (priority !== undefined) {\n defaultPriority = priority\n }\n }\n\n const doSync = syncDrafts || (!syncDrafts && status !== 'draft')\n\n try {\n if (operation === 'create' && doSync) {\n await payload.create({\n collection: searchSlug,\n data: {\n ...dataToSave,\n priority: defaultPriority,\n },\n depth: 0,\n locale: syncLocale,\n req,\n })\n }\n\n if (operation === 'update') {\n try {\n // find the correct doc to sync with\n const searchDocQuery = await payload.find({\n collection: searchSlug,\n depth: 0,\n locale: syncLocale,\n req,\n where: {\n 'doc.relationTo': {\n equals: collection,\n },\n 'doc.value': {\n equals: id,\n },\n },\n })\n\n const docs: Array<{\n id: number | string\n priority?: number\n }> = searchDocQuery?.docs || []\n\n const [foundDoc, ...duplicativeDocs] = docs\n\n // delete all duplicative search docs (docs that reference the same page)\n // to ensure the same, out-of-date result does not appear twice (where only syncing the first found doc)\n if (duplicativeDocs.length > 0) {\n try {\n const duplicativeDocIDs = duplicativeDocs.map(({ id }) => id)\n await payload.delete({\n collection: searchSlug,\n depth: 0,\n req,\n where: { id: { in: duplicativeDocIDs } },\n })\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: `Error deleting duplicative ${searchSlug} documents.`,\n })\n }\n }\n\n if (foundDoc) {\n const { id: searchDocID } = foundDoc\n\n // Check if document is trashed and delete from search\n const isTrashDocument = doc && 'deletedAt' in doc && doc.deletedAt\n\n if (isTrashDocument) {\n try {\n await payload.delete({\n id: searchDocID,\n collection: searchSlug,\n depth: 0,\n req,\n })\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: `Error deleting ${searchSlug} document for trashed doc.`,\n })\n }\n } else {\n if (doSync) {\n // update the doc normally\n try {\n await payload.update({\n id: searchDocID,\n collection: searchSlug,\n data: {\n ...dataToSave,\n priority: foundDoc.priority || defaultPriority,\n },\n depth: 0,\n locale: syncLocale,\n req,\n })\n } catch (err: unknown) {\n payload.logger.error({ err, msg: `Error updating ${searchSlug} document.` })\n }\n }\n\n if (deleteDrafts && status === 'draft') {\n // Check to see if there's a published version of the doc\n // We don't want to remove the search doc if there is a published version but a new draft has been created\n const {\n docs: [docWithPublish],\n } = await payload.find({\n collection,\n depth: 0,\n draft: false,\n limit: 1,\n locale: syncLocale,\n pagination: false,\n req,\n where: {\n and: [\n {\n _status: {\n equals: 'published',\n },\n },\n {\n id: {\n equals: id,\n },\n },\n ],\n },\n })\n\n if (!docWithPublish) {\n // do not include draft docs in search results, so delete the record\n try {\n await payload.delete({\n id: searchDocID,\n collection: searchSlug,\n depth: 0,\n req,\n })\n } catch (err: unknown) {\n payload.logger.error({ err, msg: `Error deleting ${searchSlug} document.` })\n }\n }\n }\n }\n } else if (doSync) {\n try {\n await payload.create({\n collection: searchSlug,\n data: {\n ...dataToSave,\n priority: defaultPriority,\n },\n depth: 0,\n locale: syncLocale,\n req,\n })\n } catch (err: unknown) {\n payload.logger.error({ err, msg: `Error creating ${searchSlug} document.` })\n }\n }\n } catch (err: unknown) {\n payload.logger.error({ err, msg: `Error finding ${searchSlug} document.` })\n }\n }\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: `Error syncing ${searchSlug} document related to ${collection} with id: '${id}'.`,\n })\n\n if (onSyncError) {\n onSyncError()\n }\n }\n\n return doc\n}\n"],"names":["syncDocAsSearchIndex","collection","doc","locale","onSyncError","operation","pluginConfig","req","payload","id","_status","status","title","beforeSync","defaultPriorities","deleteDrafts","searchOverrides","syncDrafts","searchSlug","slug","syncLocale","undefined","skipSync","collectionSlug","err","logger","error","msg","dataToSave","relationTo","value","docKeyPrefix","docKey","config","localization","syncedDocsSet","context","Set","has","add","docToSyncWith","isTrashDocument","deletedAt","findByID","trash","originalDoc","searchDoc","defaultPriority","priority","doSync","create","data","depth","searchDocQuery","find","where","equals","docs","foundDoc","duplicativeDocs","length","duplicativeDocIDs","map","delete","in","searchDocID","update","docWithPublish","draft","limit","pagination","and"],"mappings":"AAEA,OAAO,MAAMA,uBAAuB,OAAO,EACzCC,UAAU,EACVC,GAAG,EACHC,MAAM,EACNC,WAAW,EACXC,SAAS,EACTC,YAAY,EACZC,KAAK,EAAEC,OAAO,EAAE,EAChBD,GAAG,EACS;IACZ,MAAM,EAAEE,EAAE,EAAEC,SAASC,MAAM,EAAEC,KAAK,EAAE,GAAGV,OAAO,CAAC;IAE/C,MAAM,EAAEW,UAAU,EAAEC,iBAAiB,EAAEC,Y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,cAAc,EAAET,WAAW,qBAAqB,EAAEjB,WAAW,WAAW,EAAEQ,GAAG,EAAE,CAAC;QACxF;QAEA,IAAIL,aAAa;YACfA;QACF;IACF;IAEA,OAAOF;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/syncDocAsSearchIndex.ts"],"sourcesContent":["import type { DocToSync, SyncDocArgs } from '../types.js'\n\nexport const syncDocAsSearchIndex = async ({\n collection,\n doc,\n locale,\n onSyncError,\n operation,\n pluginConfig,\n req: { payload },\n req,\n}: SyncDocArgs) => {\n const { id, _status: status, title } = doc || {}\n\n const { beforeSync, defaultPriorities, deleteDrafts, searchOverrides, syncDrafts } = pluginConfig\n\n const searchSlug = searchOverrides?.slug || 'search'\n\n // Determine sync locale\n const syncLocale = locale || req.locale || undefined\n\n if (typeof pluginConfig.skipSync === 'function') {\n try {\n const skipSync = await pluginConfig.skipSync({\n collectionSlug: collection,\n doc,\n locale: syncLocale,\n req,\n })\n\n if (skipSync) {\n return doc\n }\n } catch (err) {\n req.payload.logger.error({\n err,\n msg: 'Search plugin: Error executing skipSync. Proceeding with sync.',\n })\n }\n }\n\n let dataToSave: DocToSync = {\n doc: {\n relationTo: collection,\n value: id,\n },\n title,\n }\n const docKeyPrefix = `${collection}:${id}`\n const docKey = req.payload.config.localization ? `${docKeyPrefix}:${syncLocale}` : docKeyPrefix\n const syncedDocsSet = (req.context?.syncedDocsSet as Set<string>) || new Set<string>()\n\n if (syncedDocsSet.has(docKey)) {\n /*\n * prevents duplicate syncing of documents in the same request\n * this can happen when hooks call `payload.update` within the create lifecycle\n * like the nested-docs plugin does\n */\n return doc\n } else {\n syncedDocsSet.add(docKey)\n }\n\n req.context.syncedDocsSet = syncedDocsSet\n\n if (typeof beforeSync === 'function') {\n let docToSyncWith = doc\n if (payload.config?.localization) {\n // Check if document is trashed (has deletedAt field)\n const isTrashDocument = doc && 'deletedAt' in doc && doc.deletedAt\n\n docToSyncWith = await payload.findByID({\n id,\n collection,\n locale: syncLocale,\n overrideAccess: true,\n req,\n // Include trashed documents when the document being synced is trashed\n trash: isTrashDocument,\n })\n }\n dataToSave = await beforeSync({\n collectionSlug: collection,\n originalDoc: docToSyncWith,\n payload,\n req,\n searchDoc: dataToSave,\n })\n }\n\n let defaultPriority = 0\n if (defaultPriorities) {\n const { [collection]: priority } = defaultPriorities\n\n if (typeof priority === 'function') {\n try {\n defaultPriority = await priority(doc)\n } catch (err: unknown) {\n payload.logger.error(err)\n payload.logger.error(\n `Error gathering default priority for ${searchSlug} documents related to ${collection}`,\n )\n }\n } else if (priority !== undefined) {\n defaultPriority = priority\n }\n }\n\n const doSync = syncDrafts || (!syncDrafts && status !== 'draft')\n\n try {\n if (operation === 'create' && doSync) {\n await payload.create({\n collection: searchSlug,\n data: {\n ...dataToSave,\n priority: defaultPriority,\n },\n depth: 0,\n locale: syncLocale,\n overrideAccess: true,\n req,\n })\n }\n\n if (operation === 'update') {\n try {\n // find the correct doc to sync with\n const searchDocQuery = await payload.find({\n collection: searchSlug,\n depth: 0,\n locale: syncLocale,\n overrideAccess: true,\n req,\n where: {\n 'doc.relationTo': {\n equals: collection,\n },\n 'doc.value': {\n equals: id,\n },\n },\n })\n\n const docs: Array<{\n id: number | string\n priority?: number\n }> = searchDocQuery?.docs || []\n\n const [foundDoc, ...duplicativeDocs] = docs\n\n // delete all duplicative search docs (docs that reference the same page)\n // to ensure the same, out-of-date result does not appear twice (where only syncing the first found doc)\n if (duplicativeDocs.length > 0) {\n try {\n const duplicativeDocIDs = duplicativeDocs.map(({ id }) => id)\n await payload.delete({\n collection: searchSlug,\n depth: 0,\n overrideAccess: true,\n req,\n where: { id: { in: duplicativeDocIDs } },\n })\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: `Error deleting duplicative ${searchSlug} documents.`,\n })\n }\n }\n\n if (foundDoc) {\n const { id: searchDocID } = foundDoc\n\n // Check if document is trashed and delete from search\n const isTrashDocument = doc && 'deletedAt' in doc && doc.deletedAt\n\n if (isTrashDocument) {\n try {\n await payload.delete({\n id: searchDocID,\n collection: searchSlug,\n depth: 0,\n overrideAccess: true,\n req,\n })\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: `Error deleting ${searchSlug} document for trashed doc.`,\n })\n }\n } else {\n if (doSync) {\n // update the doc normally\n try {\n await payload.update({\n id: searchDocID,\n collection: searchSlug,\n data: {\n ...dataToSave,\n priority: foundDoc.priority || defaultPriority,\n },\n depth: 0,\n locale: syncLocale,\n overrideAccess: true,\n req,\n })\n } catch (err: unknown) {\n payload.logger.error({ err, msg: `Error updating ${searchSlug} document.` })\n }\n }\n\n if (deleteDrafts && status === 'draft') {\n // Check to see if there's a published version of the doc\n // We don't want to remove the search doc if there is a published version but a new draft has been created\n const {\n docs: [docWithPublish],\n } = await payload.find({\n collection,\n depth: 0,\n draft: false,\n limit: 1,\n locale: syncLocale,\n overrideAccess: true,\n pagination: false,\n req,\n where: {\n and: [\n {\n _status: {\n equals: 'published',\n },\n },\n {\n id: {\n equals: id,\n },\n },\n ],\n },\n })\n\n if (!docWithPublish) {\n // do not include draft docs in search results, so delete the record\n try {\n await payload.delete({\n id: searchDocID,\n collection: searchSlug,\n depth: 0,\n overrideAccess: true,\n req,\n })\n } catch (err: unknown) {\n payload.logger.error({ err, msg: `Error deleting ${searchSlug} document.` })\n }\n }\n }\n }\n } else if (doSync) {\n try {\n await payload.create({\n collection: searchSlug,\n data: {\n ...dataToSave,\n priority: defaultPriority,\n },\n depth: 0,\n locale: syncLocale,\n overrideAccess: true,\n req,\n })\n } catch (err: unknown) {\n payload.logger.error({ err, msg: `Error creating ${searchSlug} document.` })\n }\n }\n } catch (err: unknown) {\n payload.logger.error({ err, msg: `Error finding ${searchSlug} document.` })\n }\n }\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: `Error syncing ${searchSlug} document related to ${collection} with id: '${id}'.`,\n })\n\n if (onSyncError) {\n onSyncError()\n }\n }\n\n return doc\n}\n"],"names":["syncDocAsSearchIndex","collection","doc","locale","onSyncError","operation","pluginConfig","req","payload","id","_status","status","title","beforeSync","defaultPriorities","deleteDrafts","searchOverrides","syncDrafts","searchSlug","slug","syncLocale","undefined","skipSync","collectionSlug","err","logger","error","msg","dataToSave","relationTo","value","docKeyPrefix","docKey","config","localization","syncedDocsSet","context","Set","has","add","docToSyncWith","isTrashDocument","deletedAt","findByID","overrideAccess","trash","originalDoc","searchDoc","defaultPriority","priority","doSync","create","data","depth","searchDocQuery","find","where","equals","docs","foundDoc","duplicativeDocs","length","duplicativeDocIDs","map","delete","in","searchDocID","update","docWithPublish","draft","limit","pagination","and"],"mappings":"AAEA,OAAO,MAAMA,uBAAuB,OAAO,EACzCC,UAAU,EACVC,GAAG,EACHC,MAAM,EACNC,WAAW,EACXC,SAAS,EACTC,YAAY,EACZC,KAAK,EAAEC,OAAO,EAAE,EAChBD,GAAG,EACS;IACZ,MAAM,EAAEE,EAAE,EAAEC,SAASC,MAAM,EAAEC,KAAK,EAAE,GAAGV,OAAO,CAAC;IAE/C,MAAM,EAAEW,UAAU,EAAEC,iBAAiB,EAAEC,YAAY,EAAEC,eAAe,EAAEC,UAAU,EAAE,GAAGX;IAErF,MAAMY,aAAaF,iBAAiBG,QAAQ;IAE5C,wBAAwB;IACxB,MAAMC,aAAajB,UAAUI,IAAIJ,MAAM,IAAIkB;IAE3C,IAAI,OAAOf,aAAagB,QAAQ,KAAK,YAAY;QAC/C,IAAI;YACF,MAAMA,WAAW,MAAMhB,aAAagB,QAAQ,CAAC;gBAC3CC,gBAAgBtB;gBAChBC;gBACAC,QAAQiB;gBACRb;YACF;YAEA,IAAIe,UAAU;gBACZ,OAAOpB;YACT;QACF,EAAE,OAAOsB,KAAK;YACZjB,IAAIC,OAAO,CAACiB,MAAM,CAACC,KAAK,CAAC;gBACvBF;gBACAG,KAAK;YACP;QACF;IACF;IAEA,IAAIC,aAAwB;QAC1B1B,KAAK;YACH2B,YAAY5B;YACZ6B,OAAOrB;QACT;QACAG;IACF;IACA,MAAMmB,eAAe,GAAG9B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;wCACJjE,YAAYiB;wCACZmC,OAAO;wCACPT,gBAAgB;wCAChBrC;oCACF;gCACF,EAAE,OAAOiB,KAAc;oCACrBhB,QAAQiB,MAAM,CAACC,KAAK,CAAC;wCAAEF;wCAAKG,KAAK,CAAC,eAAe,EAAET,WAAW,UAAU,CAAC;oCAAC;gCAC5E;4BACF;wBACF;oBACF;gBACF,OAAO,IAAIgC,QAAQ;oBACjB,IAAI;wBACF,MAAM1C,QAAQ2C,MAAM,CAAC;4BACnBlD,YAAYiB;4BACZkC,MAAM;gCACJ,GAAGxB,UAAU;gCACbqB,UAAUD;4BACZ;4BACAK,OAAO;4BACPlD,QAAQiB;4BACRwB,gBAAgB;4BAChBrC;wBACF;oBACF,EAAE,OAAOiB,KAAc;wBACrBhB,QAAQiB,MAAM,CAACC,KAAK,CAAC;4BAAEF;4BAAKG,KAAK,CAAC,eAAe,EAAET,WAAW,UAAU,CAAC;wBAAC;oBAC5E;gBACF;YACF,EAAE,OAAOM,KAAc;gBACrBhB,QAAQiB,MAAM,CAACC,KAAK,CAAC;oBAAEF;oBAAKG,KAAK,CAAC,cAAc,EAAET,WAAW,UAAU,CAAC;gBAAC;YAC3E;QACF;IACF,EAAE,OAAOM,KAAc;QACrBhB,QAAQiB,MAAM,CAACC,KAAK,CAAC;YACnBF;YACAG,KAAK,CAAC,cAAc,EAAET,WAAW,qBAAqB,EAAEjB,WAAW,WAAW,EAAEQ,GAAG,EAAE,CAAC;QACxF;QAEA,IAAIL,aAAa;YACfA;QACF;IACF;IAEA,OAAOF;AACT,EAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/plugin-search",
3
- "version": "4.0.0-internal.38b7f1d",
3
+ "version": "4.0.0-internal.3b50481",
4
4
  "description": "Search plugin for Payload",
5
5
  "keywords": [
6
6
  "payload",
@@ -50,19 +50,19 @@
50
50
  "dist"
51
51
  ],
52
52
  "dependencies": {
53
- "@payloadcms/ui": "4.0.0-internal.38b7f1d",
54
- "@payloadcms/next": "4.0.0-internal.38b7f1d"
53
+ "@payloadcms/next": "4.0.0-internal.3b50481",
54
+ "@payloadcms/ui": "4.0.0-internal.3b50481"
55
55
  },
56
56
  "devDependencies": {
57
- "@types/react": "19.2.14",
58
- "@types/react-dom": "19.2.3",
57
+ "@types/react": "19.3.0",
58
+ "@types/react-dom": "19.3.0",
59
59
  "@payloadcms/eslint-config": "3.28.0",
60
- "payload": "4.0.0-internal.38b7f1d"
60
+ "payload": "4.0.0-internal.3b50481"
61
61
  },
62
62
  "peerDependencies": {
63
63
  "react": "^19.0.1 || ^19.1.2 || ^19.2.1",
64
64
  "react-dom": "^19.0.1 || ^19.1.2 || ^19.2.1",
65
- "payload": "4.0.0-internal.38b7f1d"
65
+ "payload": "4.0.0-internal.3b50481"
66
66
  },
67
67
  "publishConfig": {
68
68
  "registry": "https://registry.npmjs.org/"
@@ -74,7 +74,7 @@
74
74
  "build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
75
75
  "build:types": "tsc --emitDeclarationOnly --outDir dist",
76
76
  "clean": "rimraf -g {dist,*.tsbuildinfo}",
77
- "copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
77
+ "copyfiles": "copyfiles -u 1 -e \"**/*.spec.*\" \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
78
78
  "lint": "eslint .",
79
79
  "lint:fix": "eslint . --fix",
80
80
  "test": "echo \"Error: no tests specified\""