@foundrykit/menu-plugin 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +65 -109
  2. package/dist/cache.d.ts +4 -3
  3. package/dist/cache.js +13 -15
  4. package/dist/cache.js.map +1 -1
  5. package/dist/collections/Menus.d.ts +3 -1
  6. package/dist/collections/Menus.js +53 -24
  7. package/dist/collections/Menus.js.map +1 -1
  8. package/dist/endpoints/exportMenusHandler.d.ts +5 -0
  9. package/dist/endpoints/exportMenusHandler.js +20 -13
  10. package/dist/endpoints/exportMenusHandler.js.map +1 -1
  11. package/dist/endpoints/getMenuHandler.d.ts +6 -0
  12. package/dist/endpoints/getMenuHandler.js +45 -42
  13. package/dist/endpoints/getMenuHandler.js.map +1 -1
  14. package/dist/endpoints/importMenusHandler.d.ts +5 -0
  15. package/dist/endpoints/importMenusHandler.js +84 -48
  16. package/dist/endpoints/importMenusHandler.js.map +1 -1
  17. package/dist/exports/client.d.ts +1 -0
  18. package/dist/exports/client.js +1 -0
  19. package/dist/exports/client.js.map +1 -1
  20. package/dist/exports/rsc.d.ts +1 -1
  21. package/dist/exports/rsc.js +1 -1
  22. package/dist/exports/rsc.js.map +1 -1
  23. package/dist/fetchMenu.d.ts +17 -0
  24. package/dist/fetchMenu.js +24 -0
  25. package/dist/fetchMenu.js.map +1 -0
  26. package/dist/fields/MenuItem.d.ts +1 -0
  27. package/dist/fields/MenuItem.js +8 -9
  28. package/dist/fields/MenuItem.js.map +1 -1
  29. package/dist/hooks/useMenu.d.ts +5 -6
  30. package/dist/hooks/useMenu.js +36 -19
  31. package/dist/hooks/useMenu.js.map +1 -1
  32. package/dist/index.d.ts +3 -0
  33. package/dist/index.js +41 -29
  34. package/dist/index.js.map +1 -1
  35. package/dist/utilities/menuIdentity.d.ts +2 -0
  36. package/dist/utilities/menuIdentity.js +9 -0
  37. package/dist/utilities/menuIdentity.js.map +1 -0
  38. package/dist/utilities/requireAdminUser.d.ts +2 -0
  39. package/dist/utilities/requireAdminUser.js +20 -0
  40. package/dist/utilities/requireAdminUser.js.map +1 -0
  41. package/dist/utilities/sanitizeMenuDocument.d.ts +1 -0
  42. package/dist/utilities/sanitizeMenuDocument.js +6 -0
  43. package/dist/utilities/sanitizeMenuDocument.js.map +1 -0
  44. package/package.json +1 -1
@@ -1,17 +1,35 @@
1
1
  'use client';
2
- import { useConfig } from '@payloadcms/ui';
3
2
  import { useCallback, useEffect, useRef, useState } from 'react';
3
+ import { fetchMenu as requestMenu } from '../fetchMenu.js';
4
+ import { normalizeMenuLocale } from '../utilities/menuIdentity.js';
4
5
  const clientCache = new Map();
5
6
  const CACHE_TTL = 30_000;
6
- export const useMenu = ({ slug, depth = 0, locale })=>{
7
- const { config } = useConfig();
7
+ const getDefaultBaseURL = ()=>{
8
+ if (typeof window === 'undefined') return undefined;
9
+ return window.location.origin;
10
+ };
11
+ const getCacheKey = ({ apiRoute = '/api', baseURL, depth = 0, locale, slug })=>{
12
+ return JSON.stringify({
13
+ apiRoute,
14
+ baseURL: baseURL || getDefaultBaseURL(),
15
+ depth,
16
+ locale: normalizeMenuLocale(locale),
17
+ slug
18
+ });
19
+ };
20
+ export const useMenu = ({ apiRoute = '/api', baseURL, depth = 0, fetch: fetchImpl, locale, slug })=>{
8
21
  const [menu, setMenu] = useState(null);
9
22
  const [error, setError] = useState(null);
10
23
  const [isLoading, setIsLoading] = useState(true);
11
24
  const abortRef = useRef(null);
12
- const cacheKey = `${slug}:${locale || ''}:${depth}`;
25
+ const cacheKey = getCacheKey({
26
+ apiRoute,
27
+ baseURL,
28
+ depth,
29
+ locale,
30
+ slug
31
+ });
13
32
  const fetchMenu = useCallback(async ()=>{
14
- // Check client-side cache
15
33
  const cached = clientCache.get(cacheKey);
16
34
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
17
35
  setMenu(cached.data);
@@ -25,20 +43,17 @@ export const useMenu = ({ slug, depth = 0, locale })=>{
25
43
  setIsLoading(true);
26
44
  setError(null);
27
45
  try {
28
- const params = new URLSearchParams();
29
- if (locale) params.set('locale', locale);
30
- if (depth) params.set('depth', String(depth));
31
- const query = params.toString();
32
- const apiRoute = config.routes?.api || '/api';
33
- const url = `${apiRoute}/menus/${slug}${query ? `?${query}` : ''}`;
34
- const response = await fetch(url, {
35
- signal: controller.signal
46
+ const data = await requestMenu({
47
+ apiRoute,
48
+ baseURL: baseURL || getDefaultBaseURL(),
49
+ depth,
50
+ fetch: async (input, init)=>(fetchImpl || globalThis.fetch)(input, {
51
+ ...init,
52
+ signal: controller.signal
53
+ }),
54
+ locale,
55
+ slug
36
56
  });
37
- if (!response.ok) {
38
- const body = await response.json().catch(()=>({}));
39
- throw new Error(body.error || `Failed to fetch menu: ${response.status}`);
40
- }
41
- const data = await response.json();
42
57
  clientCache.set(cacheKey, {
43
58
  data,
44
59
  timestamp: Date.now()
@@ -52,9 +67,11 @@ export const useMenu = ({ slug, depth = 0, locale })=>{
52
67
  setIsLoading(false);
53
68
  }
54
69
  }, [
70
+ apiRoute,
71
+ baseURL,
55
72
  cacheKey,
56
- config.routes?.api,
57
73
  depth,
74
+ fetchImpl,
58
75
  locale,
59
76
  slug
60
77
  ]);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/useMenu.ts"],"sourcesContent":["'use client'\n\nimport { useConfig } from '@payloadcms/ui'\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\ntype UseMenuOptions = {\n depth?: number\n locale?: string\n slug: string\n}\n\ntype UseMenuResult = {\n error: null | string\n isLoading: boolean\n menu: any | null\n refetch: () => Promise<void>\n}\n\nconst clientCache = new Map<string, { data: any; timestamp: number }>()\nconst CACHE_TTL = 30_000\n\nexport const useMenu = ({ slug, depth = 0, locale }: UseMenuOptions): UseMenuResult => {\n const { config } = useConfig()\n const [menu, setMenu] = useState<any | null>(null)\n const [error, setError] = useState<null | string>(null)\n const [isLoading, setIsLoading] = useState(true)\n const abortRef = useRef<AbortController | null>(null)\n\n const cacheKey = `${slug}:${locale || ''}:${depth}`\n\n const fetchMenu = useCallback(async () => {\n // Check client-side cache\n const cached = clientCache.get(cacheKey)\n if (cached && Date.now() - cached.timestamp < CACHE_TTL) {\n setMenu(cached.data)\n setIsLoading(false)\n setError(null)\n return\n }\n\n abortRef.current?.abort()\n const controller = new AbortController()\n abortRef.current = controller\n\n setIsLoading(true)\n setError(null)\n\n try {\n const params = new URLSearchParams()\n if (locale) params.set('locale', locale)\n if (depth) params.set('depth', String(depth))\n const query = params.toString()\n\n const apiRoute = config.routes?.api || '/api'\n const url = `${apiRoute}/menus/${slug}${query ? `?${query}` : ''}`\n\n const response = await fetch(url, { signal: controller.signal })\n\n if (!response.ok) {\n const body = await response.json().catch(() => ({}))\n throw new Error(body.error || `Failed to fetch menu: ${response.status}`)\n }\n\n const data = await response.json()\n clientCache.set(cacheKey, { data, timestamp: Date.now() })\n setMenu(data)\n } catch (err: any) {\n if (err.name !== 'AbortError') {\n setError(err.message)\n }\n } finally {\n setIsLoading(false)\n }\n }, [cacheKey, config.routes?.api, depth, locale, slug])\n\n useEffect(() => {\n void fetchMenu()\n return () => {\n abortRef.current?.abort()\n }\n }, [fetchMenu])\n\n return { error, isLoading, menu, refetch: fetchMenu }\n}\n"],"names":["useConfig","useCallback","useEffect","useRef","useState","clientCache","Map","CACHE_TTL","useMenu","slug","depth","locale","config","menu","setMenu","error","setError","isLoading","setIsLoading","abortRef","cacheKey","fetchMenu","cached","get","Date","now","timestamp","data","current","abort","controller","AbortController","params","URLSearchParams","set","String","query","toString","apiRoute","routes","api","url","response","fetch","signal","ok","body","json","catch","Error","status","err","name","message","refetch"],"mappings":"AAAA;AAEA,SAASA,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAehE,MAAMC,cAAc,IAAIC;AACxB,MAAMC,YAAY;AAElB,OAAO,MAAMC,UAAU,CAAC,EAAEC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IAAI,CAAC,sBAAsB,EAAE2B,SAASQ,MAAM,EAAE;YAC1E;YAEA,MAAMvB,OAAO,MAAMe,SAASK,IAAI;YAChC1C,YAAY6B,GAAG,CAACd,UAAU;gBAAEO;gBAAMD,WAAWF,KAAKC,GAAG;YAAG;YACxDX,QAAQa;QACV,EAAE,OAAOwB,KAAU;YACjB,IAAIA,IAAIC,IAAI,KAAK,cAAc;gBAC7BpC,SAASmC,IAAIE,OAAO;YACtB;QACF,SAAU;YACRnC,aAAa;QACf;IACF,GAAG;QAACE;QAAUR,OAAO2B,MAAM,EAAEC;QAAK9B;QAAOC;QAAQF;KAAK;IAEtDP,UAAU;QACR,KAAKmB;QACL,OAAO;YACLF,SAASS,OAAO,EAAEC;QACpB;IACF,GAAG;QAACR;KAAU;IAEd,OAAO;QAAEN;QAAOE;QAAWJ;QAAMyC,SAASjC;IAAU;AACtD,EAAC"}
1
+ {"version":3,"sources":["../../src/hooks/useMenu.ts"],"sourcesContent":["'use client'\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\nimport { fetchMenu as requestMenu, type FetchMenuOptions, type MenuDocument } from '../fetchMenu.js'\nimport { normalizeMenuLocale } from '../utilities/menuIdentity.js'\n\ntype UseMenuOptions = Omit<FetchMenuOptions, 'fetch'> & {\n fetch?: typeof globalThis.fetch\n}\n\ntype UseMenuResult = {\n error: null | string\n isLoading: boolean\n menu: MenuDocument | null\n refetch: () => Promise<void>\n}\n\ntype ClientCacheEntry = {\n data: MenuDocument\n timestamp: number\n}\n\nconst clientCache = new Map<string, ClientCacheEntry>()\nconst CACHE_TTL = 30_000\n\nconst getDefaultBaseURL = (): string | undefined => {\n if (typeof window === 'undefined') return undefined\n return window.location.origin\n}\n\nconst getCacheKey = ({ apiRoute = '/api', baseURL, depth = 0, locale, slug }: UseMenuOptions): string => {\n return JSON.stringify({\n apiRoute,\n baseURL: baseURL || getDefaultBaseURL(),\n depth,\n locale: normalizeMenuLocale(locale),\n slug,\n })\n}\n\nexport const useMenu = ({\n apiRoute = '/api',\n baseURL,\n depth = 0,\n fetch: fetchImpl,\n locale,\n slug,\n}: UseMenuOptions): UseMenuResult => {\n const [menu, setMenu] = useState<MenuDocument | null>(null)\n const [error, setError] = useState<null | string>(null)\n const [isLoading, setIsLoading] = useState(true)\n const abortRef = useRef<AbortController | null>(null)\n\n const cacheKey = getCacheKey({ apiRoute, baseURL, depth, locale, slug })\n\n const fetchMenu = useCallback(async () => {\n const cached = clientCache.get(cacheKey)\n if (cached && Date.now() - cached.timestamp < CACHE_TTL) {\n setMenu(cached.data)\n setIsLoading(false)\n setError(null)\n return\n }\n\n abortRef.current?.abort()\n const controller = new AbortController()\n abortRef.current = controller\n\n setIsLoading(true)\n setError(null)\n\n try {\n const data = await requestMenu({\n apiRoute,\n baseURL: baseURL || getDefaultBaseURL(),\n depth,\n fetch: async (input, init) =>\n (fetchImpl || globalThis.fetch)(input, {\n ...init,\n signal: controller.signal,\n }),\n locale,\n slug,\n })\n\n clientCache.set(cacheKey, { data, timestamp: Date.now() })\n setMenu(data)\n } catch (err: any) {\n if (err.name !== 'AbortError') {\n setError(err.message)\n }\n } finally {\n setIsLoading(false)\n }\n }, [apiRoute, baseURL, cacheKey, depth, fetchImpl, locale, slug])\n\n useEffect(() => {\n void fetchMenu()\n return () => {\n abortRef.current?.abort()\n }\n }, [fetchMenu])\n\n return { error, isLoading, menu, refetch: fetchMenu }\n}\n"],"names":["useCallback","useEffect","useRef","useState","fetchMenu","requestMenu","normalizeMenuLocale","clientCache","Map","CACHE_TTL","getDefaultBaseURL","window","undefined","location","origin","getCacheKey","apiRoute","baseURL","depth","locale","slug","JSON","stringify","useMenu","fetch","fetchImpl","menu","setMenu","error","setError","isLoading","setIsLoading","abortRef","cacheKey","cached","get","Date","now","timestamp","data","current","abort","controller","AbortController","input","init","globalThis","signal","set","err","name","message","refetch"],"mappings":"AAAA;AAEA,SAASA,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;A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gBACAM,OAAO,OAAOoB,OAAOC,OACnB,AAACpB,CAAAA,aAAaqB,WAAWtB,KAAK,AAAD,EAAGoB,OAAO;wBACrC,GAAGC,IAAI;wBACPE,QAAQL,WAAWK,MAAM;oBAC3B;gBACF5B;gBACAC;YACF;YAEAb,YAAYyC,GAAG,CAACf,UAAU;gBAAEM;gBAAMD,WAAWF,KAAKC,GAAG;YAAG;YACxDV,QAAQY;QACV,EAAE,OAAOU,KAAU;YACjB,IAAIA,IAAIC,IAAI,KAAK,cAAc;gBAC7BrB,SAASoB,IAAIE,OAAO;YACtB;QACF,SAAU;YACRpB,aAAa;QACf;IACF,GAAG;QAACf;QAAUC;QAASgB;QAAUf;QAAOO;QAAWN;QAAQC;KAAK;IAEhEnB,UAAU;QACR,KAAKG;QACL,OAAO;YACL4B,SAASQ,OAAO,EAAEC;QACpB;IACF,GAAG;QAACrC;KAAU;IAEd,OAAO;QAAEwB;QAAOE;QAAWJ;QAAM0B,SAAShD;IAAU;AACtD,EAAC"}
package/dist/index.d.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  import type { CollectionSlug, Config } from 'payload';
2
2
  export type MenuPluginConfig = {
3
3
  baseUrl?: string;
4
+ cacheTTL?: number;
4
5
  disabled?: boolean;
6
+ enableImportExport?: boolean;
5
7
  maxDepth?: number;
6
8
  relationTo?: CollectionSlug | CollectionSlug[];
9
+ requireAdminForImportExport?: boolean;
7
10
  };
8
11
  export declare const menuPlugin: (pluginOptions: MenuPluginConfig) => (config: Config) => Config;
package/dist/index.js CHANGED
@@ -1,37 +1,49 @@
1
+ import { menuCache } from './cache.js';
1
2
  import { createMenusCollection } from './collections/Menus.js';
2
- import { exportMenusHandler } from './endpoints/exportMenusHandler.js';
3
- import { getMenuHandler } from './endpoints/getMenuHandler.js';
4
- import { importMenusHandler } from './endpoints/importMenusHandler.js';
3
+ import { createExportMenusHandler } from './endpoints/exportMenusHandler.js';
4
+ import { createGetMenuHandler } from './endpoints/getMenuHandler.js';
5
+ import { createImportMenusHandler } from './endpoints/importMenusHandler.js';
5
6
  export const menuPlugin = (pluginOptions)=>(config)=>{
6
- if (!config.collections) {
7
- config.collections = [];
8
- }
9
- config.collections.push(createMenusCollection({
10
- baseUrl: pluginOptions.baseUrl,
11
- maxDepth: pluginOptions.maxDepth,
12
- relationTo: pluginOptions.relationTo
13
- }));
7
+ const cacheTTL = pluginOptions.cacheTTL ?? 60_000;
8
+ const enableImportExport = pluginOptions.enableImportExport ?? true;
9
+ const requireAdminForImportExport = pluginOptions.requireAdminForImportExport ?? true;
10
+ menuCache.configure(cacheTTL);
11
+ config.collections = [
12
+ ...config.collections || [],
13
+ createMenusCollection({
14
+ baseUrl: pluginOptions.baseUrl,
15
+ disabled: pluginOptions.disabled,
16
+ maxDepth: pluginOptions.maxDepth,
17
+ relationTo: pluginOptions.relationTo
18
+ })
19
+ ];
14
20
  if (pluginOptions.disabled) {
15
21
  return config;
16
22
  }
17
- if (!config.endpoints) {
18
- config.endpoints = [];
19
- }
20
- config.endpoints.push({
21
- handler: getMenuHandler,
22
- method: 'get',
23
- path: '/api/menus/:slug'
24
- });
25
- config.endpoints.push({
26
- handler: exportMenusHandler,
27
- method: 'get',
28
- path: '/api/menus-export'
29
- });
30
- config.endpoints.push({
31
- handler: importMenusHandler,
32
- method: 'post',
33
- path: '/api/menus-import'
34
- });
23
+ config.endpoints = [
24
+ ...config.endpoints || [],
25
+ {
26
+ handler: createGetMenuHandler(),
27
+ method: 'get',
28
+ path: '/api/menus/:slug'
29
+ },
30
+ ...enableImportExport ? [
31
+ {
32
+ handler: createExportMenusHandler({
33
+ requireAdmin: requireAdminForImportExport
34
+ }),
35
+ method: 'get',
36
+ path: '/api/menus-export'
37
+ },
38
+ {
39
+ handler: createImportMenusHandler({
40
+ requireAdmin: requireAdminForImportExport
41
+ }),
42
+ method: 'post',
43
+ path: '/api/menus-import'
44
+ }
45
+ ] : []
46
+ ];
35
47
  return config;
36
48
  };
37
49
 
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollectionSlug, Config } from 'payload'\n\nimport { createMenusCollection } from './collections/Menus.js'\nimport { exportMenusHandler } from './endpoints/exportMenusHandler.js'\nimport { getMenuHandler } from './endpoints/getMenuHandler.js'\nimport { importMenusHandler } from './endpoints/importMenusHandler.js'\n\nexport type MenuPluginConfig = {\n baseUrl?: string\n disabled?: boolean\n maxDepth?: number\n relationTo?: CollectionSlug | CollectionSlug[]\n}\n\nexport const menuPlugin =\n (pluginOptions: MenuPluginConfig) =>\n (config: Config): Config => {\n if (!config.collections) {\n config.collections = []\n }\n\n config.collections.push(\n createMenusCollection({\n baseUrl: pluginOptions.baseUrl,\n maxDepth: pluginOptions.maxDepth,\n relationTo: pluginOptions.relationTo,\n }),\n )\n\n if (pluginOptions.disabled) {\n return config\n }\n\n if (!config.endpoints) {\n config.endpoints = []\n }\n\n config.endpoints.push({\n handler: getMenuHandler,\n method: 'get',\n path: '/api/menus/:slug',\n })\n\n config.endpoints.push({\n handler: exportMenusHandler,\n method: 'get',\n path: '/api/menus-export',\n })\n\n config.endpoints.push({\n handler: importMenusHandler,\n method: 'post',\n path: '/api/menus-import',\n })\n\n return config\n }\n"],"names":["createMenusCollection","exportMenusHandler","getMenuHandler","importMenusHandler","menuPlugin","pluginOptions","config","collections","push","baseUrl","maxDepth","relationTo","disabled","endpoints","handler","method","path"],"mappings":"AAEA,SAASA,qBAAqB,QAAQ,yBAAwB;AAC9D,SAASC,kBAAkB,QAAQ,oCAAmC;AACtE,SAASC,cAAc,QAAQ,gCAA+B;AAC9D,SAASC,kBAAkB,QAAQ,oCAAmC;AAStE,OAAO,MAAMC,aACX,CAACC,gBACD,CAACC;QACC,IAAI,CAACA,OAAOC,WAAW,EAAE;YACvBD,OAAOC,WAAW,GAAG,EAAE;QACzB;QAEAD,OAAOC,WAAW,CAACC,IAAI,CACrBR,sBAAsB;YACpBS,SAASJ,cAAcI,OAAO;YAC9BC,UAAUL,cAAcK,QAAQ;YAChCC,YAAYN,cAAcM,UAAU;QACtC;QAGF,IAAIN,cAAcO,QAAQ,EAAE;YAC1B,OAAON;QACT;QAEA,IAAI,CAACA,OAAOO,SAAS,EAAE;YACrBP,OAAOO,SAAS,GAAG,EAAE;QACvB;QAEAP,OAAOO,SAAS,CAACL,IAAI,CAAC;YACpBM,SAASZ;YACTa,QAAQ;YACRC,MAAM;QACR;QAEAV,OAAOO,SAAS,CAACL,IAAI,CAAC;YACpBM,SAASb;YACTc,QAAQ;YACRC,MAAM;QACR;QAEAV,OAAOO,SAAS,CAACL,IAAI,CAAC;YACpBM,SAASX;YACTY,QAAQ;YACRC,MAAM;QACR;QAEA,OAAOV;IACT,EAAC"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollectionSlug, Config } from 'payload'\n\nimport { menuCache } from './cache.js'\nimport { createMenusCollection } from './collections/Menus.js'\nimport { createExportMenusHandler } from './endpoints/exportMenusHandler.js'\nimport { createGetMenuHandler } from './endpoints/getMenuHandler.js'\nimport { createImportMenusHandler } from './endpoints/importMenusHandler.js'\n\nexport type MenuPluginConfig = {\n baseUrl?: string\n cacheTTL?: number\n disabled?: boolean\n enableImportExport?: boolean\n maxDepth?: number\n relationTo?: CollectionSlug | CollectionSlug[]\n requireAdminForImportExport?: boolean\n}\n\nexport const menuPlugin =\n (pluginOptions: MenuPluginConfig) =>\n (config: Config): Config => {\n const cacheTTL = pluginOptions.cacheTTL ?? 60_000\n const enableImportExport = pluginOptions.enableImportExport ?? true\n const requireAdminForImportExport = pluginOptions.requireAdminForImportExport ?? true\n\n menuCache.configure(cacheTTL)\n\n config.collections = [\n ...(config.collections || []),\n createMenusCollection({\n baseUrl: pluginOptions.baseUrl,\n disabled: pluginOptions.disabled,\n maxDepth: pluginOptions.maxDepth,\n relationTo: pluginOptions.relationTo,\n }),\n ]\n\n if (pluginOptions.disabled) {\n return config\n }\n\n config.endpoints = [\n ...(config.endpoints || []),\n {\n handler: createGetMenuHandler(),\n method: 'get',\n path: '/api/menus/:slug',\n },\n ...(enableImportExport\n ? [\n {\n handler: createExportMenusHandler({ requireAdmin: requireAdminForImportExport }),\n method: 'get' as const,\n path: '/api/menus-export',\n },\n {\n handler: createImportMenusHandler({ requireAdmin: requireAdminForImportExport }),\n method: 'post' as const,\n path: '/api/menus-import',\n },\n ]\n : []),\n ]\n\n return config\n }\n"],"names":["menuCache","createMenusCollection","createExportMenusHandler","createGetMenuHandler","createImportMenusHandler","menuPlugin","pluginOptions","config","cacheTTL","enableImportExport","requireAdminForImportExport","configure","collections","baseUrl","disabled","maxDepth","relationTo","endpoints","handler","method","path","requireAdmin"],"mappings":"AAEA,SAASA,SAAS,QAAQ,aAAY;AACtC,SAASC,qBAAqB,QAAQ,yBAAwB;AAC9D,SAASC,wBAAwB,QAAQ,oCAAmC;AAC5E,SAASC,oBAAoB,QAAQ,gCAA+B;AACpE,SAASC,wBAAwB,QAAQ,oCAAmC;AAY5E,OAAO,MAAMC,aACX,CAACC,gBACD,CAACC;QACC,MAAMC,WAAWF,cAAcE,QAAQ,IAAI;QAC3C,MAAMC,qBAAqBH,cAAcG,kBAAkB,IAAI;QAC/D,MAAMC,8BAA8BJ,cAAcI,2BAA2B,IAAI;QAEjFV,UAAUW,SAAS,CAACH;QAEpBD,OAAOK,WAAW,GAAG;eACfL,OAAOK,WAAW,IAAI,EAAE;YAC5BX,sBAAsB;gBACpBY,SAASP,cAAcO,OAAO;gBAC9BC,UAAUR,cAAcQ,QAAQ;gBAChCC,UAAUT,cAAcS,QAAQ;gBAChCC,YAAYV,cAAcU,UAAU;YACtC;SACD;QAED,IAAIV,cAAcQ,QAAQ,EAAE;YAC1B,OAAOP;QACT;QAEAA,OAAOU,SAAS,GAAG;eACbV,OAAOU,SAAS,IAAI,EAAE;YAC1B;gBACEC,SAASf;gBACTgB,QAAQ;gBACRC,MAAM;YACR;eACIX,qBACA;gBACE;oBACES,SAAShB,yBAAyB;wBAAEmB,cAAcX;oBAA4B;oBAC9ES,QAAQ;oBACRC,MAAM;gBACR;gBACA;oBACEF,SAASd,yBAAyB;wBAAEiB,cAAcX;oBAA4B;oBAC9ES,QAAQ;oBACRC,MAAM;gBACR;aACD,GACD,EAAE;SACP;QAED,OAAOb;IACT,EAAC"}
@@ -0,0 +1,2 @@
1
+ export declare const normalizeMenuLocale: (locale?: null | string) => string | undefined;
2
+ export declare const buildMenuIdentityKey: (slug: string, locale?: null | string) => string;
@@ -0,0 +1,9 @@
1
+ export const normalizeMenuLocale = (locale)=>{
2
+ const normalized = locale?.trim().toLowerCase();
3
+ return normalized ? normalized : undefined;
4
+ };
5
+ export const buildMenuIdentityKey = (slug, locale)=>{
6
+ return `${slug}::${normalizeMenuLocale(locale) || '__default'}`;
7
+ };
8
+
9
+ //# sourceMappingURL=menuIdentity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utilities/menuIdentity.ts"],"sourcesContent":["export const normalizeMenuLocale = (locale?: null | string): string | undefined => {\n const normalized = locale?.trim().toLowerCase()\n return normalized ? normalized : undefined\n}\n\nexport const buildMenuIdentityKey = (slug: string, locale?: null | string): string => {\n return `${slug}::${normalizeMenuLocale(locale) || '__default'}`\n}\n"],"names":["normalizeMenuLocale","locale","normalized","trim","toLowerCase","undefined","buildMenuIdentityKey","slug"],"mappings":"AAAA,OAAO,MAAMA,sBAAsB,CAACC;IAClC,MAAMC,aAAaD,QAAQE,OAAOC;IAClC,OAAOF,aAAaA,aAAaG;AACnC,EAAC;AAED,OAAO,MAAMC,uBAAuB,CAACC,MAAcN;IACjD,OAAO,GAAGM,KAAK,EAAE,EAAEP,oBAAoBC,WAAW,aAAa;AACjE,EAAC"}
@@ -0,0 +1,2 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ export declare const requireAdminUser: (req: PayloadRequest) => Response | undefined;
@@ -0,0 +1,20 @@
1
+ export const requireAdminUser = (req)=>{
2
+ const adminCollection = req.payload.config.admin?.user;
3
+ if (!req.user) {
4
+ return Response.json({
5
+ error: 'Authentication required'
6
+ }, {
7
+ status: 401
8
+ });
9
+ }
10
+ if (adminCollection && req.user.collection !== adminCollection) {
11
+ return Response.json({
12
+ error: 'Admin access required'
13
+ }, {
14
+ status: 403
15
+ });
16
+ }
17
+ return undefined;
18
+ };
19
+
20
+ //# sourceMappingURL=requireAdminUser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utilities/requireAdminUser.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nexport const requireAdminUser = (req: PayloadRequest): Response | undefined => {\n const adminCollection = req.payload.config.admin?.user\n\n if (!req.user) {\n return Response.json({ error: 'Authentication required' }, { status: 401 })\n }\n\n if (adminCollection && req.user.collection !== adminCollection) {\n return Response.json({ error: 'Admin access required' }, { status: 403 })\n }\n\n return undefined\n}\n"],"names":["requireAdminUser","req","adminCollection","payload","config","admin","user","Response","json","error","status","collection","undefined"],"mappings":"AAEA,OAAO,MAAMA,mBAAmB,CAACC;IAC/B,MAAMC,kBAAkBD,IAAIE,OAAO,CAACC,MAAM,CAACC,KAAK,EAAEC;IAElD,IAAI,CAACL,IAAIK,IAAI,EAAE;QACb,OAAOC,SAASC,IAAI,CAAC;YAAEC,OAAO;QAA0B,GAAG;YAAEC,QAAQ;QAAI;IAC3E;IAEA,IAAIR,mBAAmBD,IAAIK,IAAI,CAACK,UAAU,KAAKT,iBAAiB;QAC9D,OAAOK,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAwB,GAAG;YAAEC,QAAQ;QAAI;IACzE;IAEA,OAAOE;AACT,EAAC"}
@@ -0,0 +1 @@
1
+ export declare const sanitizeMenuDocument: <T extends Record<string, unknown>>(menu: T) => T;
@@ -0,0 +1,6 @@
1
+ export const sanitizeMenuDocument = (menu)=>{
2
+ const { slugLocaleKey: _slugLocaleKey, ...sanitized } = menu;
3
+ return sanitized;
4
+ };
5
+
6
+ //# sourceMappingURL=sanitizeMenuDocument.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utilities/sanitizeMenuDocument.ts"],"sourcesContent":["export const sanitizeMenuDocument = <T extends Record<string, unknown>>(menu: T): T => {\n const { slugLocaleKey: _slugLocaleKey, ...sanitized } = menu\n return sanitized as T\n}\n"],"names":["sanitizeMenuDocument","menu","slugLocaleKey","_slugLocaleKey","sanitized"],"mappings":"AAAA,OAAO,MAAMA,uBAAuB,CAAoCC;IACtE,MAAM,EAAEC,eAAeC,cAAc,EAAE,GAAGC,WAAW,GAAGH;IACxD,OAAOG;AACT,EAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foundrykit/menu-plugin",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "A plugin for Payload CMS that provides a flexible and customisable menu system.",
5
5
  "license": "MIT",
6
6
  "type": "module",