payload-intl 1.2.3 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,25 +27,25 @@ pnpm add payload-intl
27
27
 
28
28
  ```ts
29
29
  // payload.config.ts
30
- import { buildConfig } from 'payload';
31
- import { intlPlugin } from 'payload-intl';
30
+ import { buildConfig } from "payload";
31
+ import { intlPlugin } from "payload-intl";
32
32
 
33
33
  export default buildConfig({
34
34
  localization: {
35
- locales: ['en', 'de', 'fr'],
36
- defaultLocale: 'en',
35
+ locales: ["en", "de", "fr"],
36
+ defaultLocale: "en",
37
37
  },
38
38
  // ...
39
39
  plugins: [
40
40
  intlPlugin({
41
41
  schema: {
42
42
  common: {
43
- greeting: '[Main greeting] Hello {name}!',
44
- items: '{count, plural, one {# item} other {# items}}',
43
+ greeting: "[Main greeting] Hello {name}!",
44
+ items: "{count, plural, one {# item} other {# items}}",
45
45
  },
46
46
  auth: {
47
- login: 'Sign in',
48
- logout: 'Sign out',
47
+ login: "Sign in",
48
+ logout: "Sign out",
49
49
  },
50
50
  },
51
51
  tabs: true,
@@ -57,24 +57,27 @@ export default buildConfig({
57
57
  Fetch messages in your application:
58
58
 
59
59
  ```ts
60
- import { fetchMessages } from 'payload-intl';
60
+ import { fetchMessages } from "payload-intl";
61
61
 
62
62
  // Server-side — pass the Payload instance directly
63
- const messages = await fetchMessages(payload, 'en');
63
+ const messages = await fetchMessages(payload, "en");
64
64
 
65
65
  // Client-side — pass a config object to fetch from the REST API
66
- const messages = await fetchMessages({ serverUrl: 'http://localhost:3000' }, 'en');
66
+ const messages = await fetchMessages(
67
+ { serverUrl: "http://localhost:3000" },
68
+ "en",
69
+ );
67
70
  ```
68
71
 
69
72
  ### Options
70
73
 
71
- | Option | Type | Default | Description |
72
- | --- | --- | --- | --- |
73
- | `schema` | `MessagesSchema` | — | Required. Nested object defining message keys and ICU templates. Leaf values are ICU MessageFormat strings, optionally prefixed with a `[description]`. |
74
- | `collectionSlug` | `CollectionSlug` | `'messages'` | Slug of the collection used to store translation files. |
75
- | `editorAccess` | `(req: PayloadRequest) => boolean \| Promise<boolean>` | `(req) => req.user !== null` | Access control function that determines who can edit messages. |
76
- | `hooks` | `MessagesHooks` | `{}` | Collection hooks. Extends Payload's collection hooks with an additional `afterUpdate` callback fired when translations are saved. |
77
- | `tabs` | `boolean` | `false` | When enabled, top-level keys in the schema are rendered as tabs in the admin UI. |
74
+ | Option | Type | Default | Description |
75
+ | ---------------- | ------------------------------------------------------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
76
+ | `schema` | `MessagesSchema` | — | Required. Nested object defining message keys and ICU templates. Leaf values are ICU MessageFormat strings, optionally prefixed with a `[description]`. |
77
+ | `collectionSlug` | `string` | `'messages'` | Slug of the collection used to store translation files. |
78
+ | `editorAccess` | `(req: PayloadRequest) => boolean \| Promise<boolean>` | `(req) => req.user !== null` | Access control function that determines who can edit messages. |
79
+ | `hooks` | `MessagesHooks` | `{}` | Collection hooks. Extends Payload's collection hooks with an additional `afterUpdate` callback fired when translations are saved. |
80
+ | `tabs` | `boolean` | `false` | When enabled, top-level keys in the schema are rendered as tabs in the admin UI. |
78
81
 
79
82
  ## Contributing
80
83
 
@@ -1,5 +1,5 @@
1
1
  import type { ResolvedPluginOptions } from './types';
2
2
  export declare const Messages: (options: ResolvedPluginOptions<"hooks"> & {
3
- slug: import("payload").CollectionSlug;
3
+ slug: string;
4
4
  }) => import("payload").CollectionConfig;
5
5
  //# sourceMappingURL=entities.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CollectionSlug, Plugin } from 'payload';
1
+ import type { Plugin } from 'payload';
2
2
  import type { MessagesGuard, MessagesHooks, MessagesSchema } from './types.ts';
3
3
  export interface MessagesPluginConfig {
4
4
  schema: MessagesSchema;
@@ -7,7 +7,7 @@ export interface MessagesPluginConfig {
7
7
  *
8
8
  * @default `messages`
9
9
  */
10
- collectionSlug?: CollectionSlug;
10
+ collectionSlug?: string;
11
11
  /**
12
12
  * Access control for allowing to edit the messages.
13
13
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAKtD,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAG/E,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,cAAc,CAAC;IACvB;;;;OAIG;IACH,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC;;;;OAIG;IACH,YAAY,CAAC,EAAE,aAAa,CAAC;IAC7B,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED,eAAO,MAAM,UAAU,2DAOlB,oBAAoB,KAAG,MAgEzB,CAAC;AAEJ,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAEzD,YAAY,EACV,QAAQ,EACR,cAAc,GACf,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAKtC,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAG/E,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,cAAc,CAAC;IACvB;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;OAIG;IACH,YAAY,CAAC,EAAE,aAAa,CAAC;IAC7B,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED,eAAO,MAAM,UAAU,2DAOlB,oBAAoB,KAAG,MAgEzB,CAAC;AAEJ,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAEzD,YAAY,EACV,QAAQ,EACR,cAAc,GACf,MAAM,YAAY,CAAC"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollectionSlug, Plugin } from 'payload';\nimport type { MessagesViewProps } from './components/MessagesView';\nimport { getMessagesEndpoint } from './endpoints/get-messages';\nimport { setMessagesEndpoint } from './endpoints/set-messages';\nimport { Messages } from './entities';\nimport type { MessagesGuard, MessagesHooks, MessagesSchema } from './types.ts';\nimport { attachPluginContext, getSupportedLocales } from './utils/config';\n\nexport interface MessagesPluginConfig {\n schema: MessagesSchema;\n /**\n * The slug of the collection to use for the messages.\n *\n * @default `messages`\n */\n collectionSlug?: CollectionSlug;\n /**\n * Access control for allowing to edit the messages.\n *\n * @default `(req) => req.user !== null // Authenticated users only`\n */\n editorAccess?: MessagesGuard;\n hooks?: MessagesHooks;\n tabs?: boolean;\n}\n\nexport const intlPlugin =\n ({\n schema,\n tabs,\n collectionSlug = 'messages',\n hooks = {},\n editorAccess = (req) => req.user !== null,\n }: MessagesPluginConfig): Plugin =>\n (config) => {\n if (!config.localization) {\n console.warn(\n '[payload-intl] You have not set the localization option in your Payload config, so this plugin will have no effect.',\n );\n return config;\n }\n\n const locales = getSupportedLocales(config.localization);\n\n config.admin ??= {};\n config.admin.components ??= {};\n config.admin.components.actions ??= [];\n config.admin.components.actions.push({\n exportName: 'MessagesLink',\n path: 'payload-intl/rsc#MessagesLink',\n });\n\n config.admin.components.views = {\n ...config.admin.components.views,\n intl: {\n Component: {\n path: 'payload-intl/rsc#MessagesView',\n serverProps: {\n access: editorAccess,\n locales,\n schema,\n tabs,\n } satisfies MessagesViewProps,\n },\n path: '/intl',\n },\n };\n\n attachPluginContext(config, {\n collectionSlug,\n });\n // config.globals ??= [];\n // config.globals.push({\n // slug: 'intl-plugin',\n // fields: [\n // {\n // name: 'editorTemplate',\n // type: 'richText',\n // editor: lexicalEditor({\n // features: ({ defaultFeatures }) =>\n // defaultFeatures.filter(\n // ({ key }) => !['relationship', 'upload'].includes(key),\n // ),\n // }),\n // admin: { hidden: true },\n // },\n // ],\n // });\n\n config.collections ??= [];\n config.collections.push(Messages({ slug: collectionSlug, hooks }));\n\n config.endpoints ??= [];\n config.endpoints.push(getMessagesEndpoint);\n config.endpoints.push(setMessagesEndpoint);\n\n return config;\n };\n\nexport { fetchMessages } from './requests/fetchMessages';\n\nexport type {\n Messages,\n MessagesSchema,\n} from './types.ts';\n"],"names":["getMessagesEndpoint","setMessagesEndpoint","Messages","attachPluginContext","getSupportedLocales","intlPlugin","schema","tabs","collectionSlug","hooks","editorAccess","req","user","config","localization","console","warn","locales","admin","components","actions","push","exportName","path","views","intl","Component","serverProps","access","collections","slug","endpoints","fetchMessages"],"mappings":"AAEA,SAASA,mBAAmB,QAAQ,2BAA2B;AAC/D,SAASC,mBAAmB,QAAQ,2BAA2B;AAC/D,SAASC,QAAQ,QAAQ,aAAa;AAEtC,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,iBAAiB;AAoB1E,OAAO,MAAMC,aACX,CAAC,EACCC,MAAM,EACNC,IAAI,EACJC,iBAAiB,UAAU,EAC3BC,QAAQ,CAAC,CAAC,EACVC,eAAe,CAACC,MAAQA,IAAIC,IAAI,KAAK,IAAI,EACpB,GACvB,CAACC;QACC,IAAI,CAACA,OAAOC,YAAY,EAAE;YACxBC,QAAQC,IAAI,CACV;YAEF,OAAOH;QACT;QAEA,MAAMI,UAAUb,oBAAoBS,OAAOC,YAAY;QAEvDD,OAAOK,KAAK,KAAK,CAAC;QAClBL,OAAOK,KAAK,CAACC,UAAU,KAAK,CAAC;QAC7BN,OAAOK,KAAK,CAACC,UAAU,CAACC,OAAO,KAAK,EAAE;QACtCP,OAAOK,KAAK,CAACC,UAAU,CAACC,OAAO,CAACC,IAAI,CAAC;YACnCC,YAAY;YACZC,MAAM;QACR;QAEAV,OAAOK,KAAK,CAACC,UAAU,CAACK,KAAK,GAAG;YAC9B,GAAGX,OAAOK,KAAK,CAACC,UAAU,CAACK,KAAK;YAChCC,MAAM;gBACJC,WAAW;oBACTH,MAAM;oBACNI,aAAa;wBACXC,QAAQlB;wBACRO;wBACAX;wBACAC;oBACF;gBACF;gBACAgB,MAAM;YACR;QACF;QAEApB,oBAAoBU,QAAQ;YAC1BL;QACF;QACA,yBAAyB;QACzB,wBAAwB;QACxB,yBAAyB;QACzB,cAAc;QACd,QAAQ;QACR,gCAAgC;QAChC,0BAA0B;QAC1B,gCAAgC;QAChC,6CAA6C;QAC7C,oCAAoC;QACpC,sEAAsE;QACtE,eAAe;QACf,YAAY;QACZ,iCAAiC;QACjC,SAAS;QACT,OAAO;QACP,MAAM;QAENK,OAAOgB,WAAW,KAAK,EAAE;QACzBhB,OAAOgB,WAAW,CAACR,IAAI,CAACnB,SAAS;YAAE4B,MAAMtB;YAAgBC;QAAM;QAE/DI,OAAOkB,SAAS,KAAK,EAAE;QACvBlB,OAAOkB,SAAS,CAACV,IAAI,CAACrB;QACtBa,OAAOkB,SAAS,CAACV,IAAI,CAACpB;QAEtB,OAAOY;IACT,EAAE;AAEJ,SAASmB,aAAa,QAAQ,2BAA2B"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Plugin } from 'payload';\nimport type { MessagesViewProps } from './components/MessagesView';\nimport { getMessagesEndpoint } from './endpoints/get-messages';\nimport { setMessagesEndpoint } from './endpoints/set-messages';\nimport { Messages } from './entities';\nimport type { MessagesGuard, MessagesHooks, MessagesSchema } from './types.ts';\nimport { attachPluginContext, getSupportedLocales } from './utils/config';\n\nexport interface MessagesPluginConfig {\n schema: MessagesSchema;\n /**\n * The slug of the collection to use for the messages.\n *\n * @default `messages`\n */\n collectionSlug?: string;\n /**\n * Access control for allowing to edit the messages.\n *\n * @default `(req) => req.user !== null // Authenticated users only`\n */\n editorAccess?: MessagesGuard;\n hooks?: MessagesHooks;\n tabs?: boolean;\n}\n\nexport const intlPlugin =\n ({\n schema,\n tabs,\n collectionSlug = 'messages',\n hooks = {},\n editorAccess = (req) => req.user !== null,\n }: MessagesPluginConfig): Plugin =>\n (config) => {\n if (!config.localization) {\n console.warn(\n '[payload-intl] You have not set the localization option in your Payload config, so this plugin will have no effect.',\n );\n return config;\n }\n\n const locales = getSupportedLocales(config.localization);\n\n config.admin ??= {};\n config.admin.components ??= {};\n config.admin.components.actions ??= [];\n config.admin.components.actions.push({\n exportName: 'MessagesLink',\n path: 'payload-intl/rsc#MessagesLink',\n });\n\n config.admin.components.views = {\n ...config.admin.components.views,\n intl: {\n Component: {\n path: 'payload-intl/rsc#MessagesView',\n serverProps: {\n access: editorAccess,\n locales,\n schema,\n tabs,\n } satisfies MessagesViewProps,\n },\n path: '/intl',\n },\n };\n\n attachPluginContext(config, {\n collectionSlug,\n });\n // config.globals ??= [];\n // config.globals.push({\n // slug: 'intl-plugin',\n // fields: [\n // {\n // name: 'editorTemplate',\n // type: 'richText',\n // editor: lexicalEditor({\n // features: ({ defaultFeatures }) =>\n // defaultFeatures.filter(\n // ({ key }) => !['relationship', 'upload'].includes(key),\n // ),\n // }),\n // admin: { hidden: true },\n // },\n // ],\n // });\n\n config.collections ??= [];\n config.collections.push(Messages({ slug: collectionSlug, hooks }));\n\n config.endpoints ??= [];\n config.endpoints.push(getMessagesEndpoint);\n config.endpoints.push(setMessagesEndpoint);\n\n return config;\n };\n\nexport { fetchMessages } from './requests/fetchMessages';\n\nexport type {\n Messages,\n MessagesSchema,\n} from './types.ts';\n"],"names":["getMessagesEndpoint","setMessagesEndpoint","Messages","attachPluginContext","getSupportedLocales","intlPlugin","schema","tabs","collectionSlug","hooks","editorAccess","req","user","config","localization","console","warn","locales","admin","components","actions","push","exportName","path","views","intl","Component","serverProps","access","collections","slug","endpoints","fetchMessages"],"mappings":"AAEA,SAASA,mBAAmB,QAAQ,2BAA2B;AAC/D,SAASC,mBAAmB,QAAQ,2BAA2B;AAC/D,SAASC,QAAQ,QAAQ,a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OkB,SAAS,CAACV,IAAI,CAACrB;QACtBa,OAAOkB,SAAS,CAACV,IAAI,CAACpB;QAEtB,OAAOY;IACT,EAAE;AAEJ,SAASmB,aAAa,QAAQ,2BAA2B"}
@@ -1,16 +1,29 @@
1
- import type { CollectionConfig, CollectionSlug, TypeWithID } from 'payload';
1
+ import type { BasePayload, CollectionConfig, CollectionSlug, JsonObject, TypeWithID } from 'payload';
2
2
  import z from 'zod';
3
- export declare const entityIdSchema: z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>;
4
- export type EntityID = TypeWithID['id'] & z.infer<typeof entityIdSchema>;
5
- export declare const isPopulated: <T extends TypeWithID>(relationship: T | EntityID) => relationship is T;
6
- export declare function assertPopulated<T extends TypeWithID | null>(docsOrIds: (T | EntityID)[], errorMessage?: (id: EntityID) => string): T[];
7
- export declare function assertPopulated<T extends TypeWithID | null>(docOrId: T | EntityID, errorMessage?: (id: EntityID) => string): T;
3
+ export declare const documentIdSchema: z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>;
4
+ export type DocumentID = TypeWithID['id'] & z.infer<typeof documentIdSchema>;
5
+ export declare const documentReferenceSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
6
+ entity: z.ZodLiteral<"collection">;
7
+ slug: z.ZodString;
8
+ id: z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>;
9
+ }, z.core.$strip>, z.ZodObject<{
10
+ entity: z.ZodLiteral<"global">;
11
+ slug: z.ZodString;
12
+ }, z.core.$strip>], "entity">;
13
+ export type DocumentReference = z.infer<typeof documentReferenceSchema>;
14
+ export declare const isPopulated: <T extends TypeWithID>(relationship: T | DocumentID) => relationship is T;
15
+ export declare function assertPopulated<T extends TypeWithID | null>(docsOrIds: (T | DocumentID)[], errorMessage?: (id: DocumentID) => string): T[];
16
+ export declare function assertPopulated<T extends TypeWithID | null>(docOrId: T | DocumentID, errorMessage?: (id: DocumentID) => string): T;
8
17
  export declare const createCollectionConfigFactory: <T extends Record<string, unknown>>(factory: Omit<CollectionConfig, "slug"> | ((options: T & {
9
- slug: CollectionSlug;
18
+ slug: string;
10
19
  }) => Omit<CollectionConfig, "slug">)) => (options: T & {
11
- slug: CollectionSlug;
20
+ slug: string;
12
21
  }) => CollectionConfig;
13
- export declare const resolveForeignKey: (entity: TypeWithID["id"] | TypeWithID) => string | number;
22
+ export type IdentifiableDocument = TypeWithID['id'] | TypeWithID;
23
+ export declare function isIdentifiableDocument(value: unknown): value is IdentifiableDocument;
24
+ export declare const resolveDocumentID: (entity: IdentifiableDocument) => DocumentID;
25
+ export declare function fetchDocumentByReference(payload: BasePayload, ref: DocumentReference): Promise<JsonObject>;
26
+ export declare function updateDocumentByReference(payload: BasePayload, ref: DocumentReference, data: JsonObject): Promise<import("payload").DataFromCollectionSlug<CollectionSlug>>;
14
27
  export { defineProcedure, type Procedure, type ProcedureBuilder, } from './procedure';
15
28
  export { getAdminURL, getApiURL, getServerURL } from './urls';
16
29
  export { findFields, uncaughtSwitchCase } from './utils';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/internals/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAC5E,OAAO,CAAC,MAAM,KAAK,CAAC;AAIpB,eAAO,MAAM,cAAc,iDAAoC,CAAC;AAChE,MAAM,MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AAIzE,eAAO,MAAM,WAAW,GAAI,CAAC,SAAS,UAAU,gBAChC,CAAC,GAAG,QAAQ,KACzB,YAAY,IAAI,CAAqC,CAAC;AAEzD,wBAAgB,eAAe,CAAC,CAAC,SAAS,UAAU,GAAG,IAAI,EACzD,SAAS,EAAE,CAAC,CAAC,GAAG,QAAQ,CAAC,EAAE,EAC3B,YAAY,CAAC,EAAE,CAAC,EAAE,EAAE,QA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gBrB;AAED,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,WAAW,EACpB,GAAG,EAAE,iBAAiB,EACtB,IAAI,EAAE,UAAU,qEAiBjB;AAED,OAAO,EACL,eAAe,EACf,KAAK,SAAS,EACd,KAAK,gBAAgB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC"}
@@ -1,9 +1,21 @@
1
1
  import z from 'zod';
2
+ import { uncaughtSwitchCase } from './utils';
2
3
  // MARK: Types
3
- export const entityIdSchema = z.union([
4
+ export const documentIdSchema = z.union([
4
5
  z.number(),
5
6
  z.string()
6
7
  ]);
8
+ export const documentReferenceSchema = z.discriminatedUnion('entity', [
9
+ z.object({
10
+ entity: z.literal('collection'),
11
+ slug: z.string(),
12
+ id: documentIdSchema
13
+ }),
14
+ z.object({
15
+ entity: z.literal('global'),
16
+ slug: z.string()
17
+ })
18
+ ]);
7
19
  // MARK: Type Guards
8
20
  export const isPopulated = (relationship)=>typeof relationship === 'object';
9
21
  export function assertPopulated(value, errorMessage = (id)=>`Doc is not populated: [${id}]`) {
@@ -19,7 +31,49 @@ export const createCollectionConfigFactory = (factory)=>(options)=>({
19
31
  slug: options.slug,
20
32
  ...typeof factory === 'function' ? factory(options) : factory
21
33
  });
22
- export const resolveForeignKey = (entity)=>typeof entity === 'object' ? entity.id : entity;
34
+ export function isIdentifiableDocument(value) {
35
+ if (typeof value === 'string') return true;
36
+ if (typeof value === 'number') return true;
37
+ if (value === null) return false;
38
+ if (typeof value !== 'object') return true;
39
+ if (!('id' in value)) return false;
40
+ return isIdentifiableDocument(value.id);
41
+ }
42
+ export const resolveDocumentID = (entity)=>typeof entity === 'object' ? entity.id : entity;
43
+ export function fetchDocumentByReference(payload, ref) {
44
+ switch(ref.entity){
45
+ case 'collection':
46
+ return payload.findByID({
47
+ collection: ref.slug,
48
+ id: ref.id,
49
+ depth: 0
50
+ });
51
+ case 'global':
52
+ return payload.findGlobal({
53
+ slug: ref.slug,
54
+ depth: 0
55
+ });
56
+ default:
57
+ return uncaughtSwitchCase(ref);
58
+ }
59
+ }
60
+ export async function updateDocumentByReference(payload, ref, data) {
61
+ switch(ref.entity){
62
+ case 'collection':
63
+ return payload.update({
64
+ collection: ref.slug,
65
+ id: ref.id,
66
+ data: data
67
+ });
68
+ case 'global':
69
+ return payload.updateGlobal({
70
+ slug: ref.slug,
71
+ data: data
72
+ });
73
+ default:
74
+ return uncaughtSwitchCase(ref);
75
+ }
76
+ }
23
77
  export { defineProcedure } from './procedure';
24
78
  export { getAdminURL, getApiURL, getServerURL } from './urls';
25
79
  export { findFields, uncaughtSwitchCase } from './utils';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/internals/index.ts"],"sourcesContent":["import type { CollectionConfig, CollectionSlug, TypeWithID } from 'payload';\nimport z from 'zod';\n\n// MARK: Types\n\nexport const entityIdSchema = z.union([z.number(), z.string()]);\nexport type EntityID = TypeWithID['id'] & z.infer<typeof entityIdSchema>;\n\n// MARK: Type Guards\n\nexport const isPopulated = <T extends TypeWithID>(\n relationship: T | EntityID,\n): relationship is T => typeof relationship === 'object';\n\nexport function assertPopulated<T extends TypeWithID | null>(\n docsOrIds: (T | EntityID)[],\n errorMessage?: (id: EntityID) => string,\n): T[];\nexport function assertPopulated<T extends TypeWithID | null>(\n docOrId: T | EntityID,\n errorMessage?: (id: EntityID) => string,\n): T;\nexport function assertPopulated<T extends TypeWithID | null>(\n value: T | EntityID | (T | EntityID)[],\n errorMessage = (id: EntityID) => `Doc is not populated: [${id}]`,\n): T | T[] {\n if (value === null) return value;\n if (Array.isArray(value)) {\n return value.map((item) => assertPopulated(item, errorMessage));\n }\n if (isPopulated(value)) return value;\n throw new Error(errorMessage(value as EntityID));\n}\n\n// MARK: Utilities\n\nexport const createCollectionConfigFactory =\n <T extends Record<string, unknown>>(\n factory:\n | Omit<CollectionConfig, 'slug'>\n | ((\n options: T & { slug: CollectionSlug },\n ) => Omit<CollectionConfig, 'slug'>),\n ) =>\n (options: T & { slug: CollectionSlug }): CollectionConfig => ({\n slug: options.slug,\n ...(typeof factory === 'function' ? factory(options) : factory),\n });\n\nexport const resolveForeignKey = (entity: TypeWithID['id'] | TypeWithID) =>\n typeof entity === 'object' ? entity.id : entity;\n\nexport {\n defineProcedure,\n type Procedure,\n type ProcedureBuilder,\n} from './procedure';\nexport { getAdminURL, getApiURL, getServerURL } from './urls';\nexport { findFields, uncaughtSwitchCase } from './utils';\n"],"names":["z","entityIdSchema","union","number","string","isPopulated","relationship","assertPopulated","value","errorMessage","id","Array","isArray","map","item","Error","createCollectionConfigFactory","factory","options","slug","resolveForeignKey","entity","defineProcedure","getAdminURL","getApiURL","getServerURL","findFields","uncaughtSwitchCase"],"mappings":"AACA,OAAOA,OAAO,MAAM;AAEpB,cAAc;AAEd,OAAO,MAAMC,iBAAiBD,EAAEE,KAAK,CAAC;IAACF,EAAEG,MAAM;IAAIH,EAAEI,MAAM;CAAG,EAAE;AAGhE,oBAAoB;AAEpB,OAAO,MAAMC,cAAc,CACzBC,eACsB,OAAOA,iBAAiB,SAAS;AAUzD,OAAO,SAASC,gBACdC,KAAsC,EACtCC,eAAe,CAACC,KAAiB,CAAC,uBAAuB,EAAEA,GAAG,CAAC,CAAC;IAEhE,IAAIF,UAAU,MAAM,OAAOA;IAC3B,IAAIG,MAAMC,OAAO,CAACJ,QAAQ;QACxB,OAAOA,MAAMK,GAAG,CAAC,CAACC,OAASP,gBAAgBO,MAAML;IACnD;IACA,IAAIJ,YAAYG,QAAQ,OAAOA;IAC/B,MAAM,IAAIO,MAAMN,aAAaD;AAC/B;AAEA,kBAAkB;AAElB,OAAO,MAAMQ,gCACX,CACEC,UAMF,CAACC,UAA6D,CAAA;YAC5DC,MAAMD,QAAQC,IAAI;YAClB,GAAI,OAAOF,YAAY,aAAaA,QAAQC,WAAWD,OAAO;QAChE,CAAA,EAAG;AAEL,OAAO,MAAMG,oBAAoB,CAACC,SAChC,OAAOA,WAAW,WAAWA,OAAOX,EAAE,GAAGW,OAAO;AAElD,SACEC,eAAe,QAGV,cAAc;AACrB,SAASC,WAAW,EAAEC,SAAS,EAAEC,YAAY,QAAQ,SAAS;AAC9D,SAASC,UAAU,EAAEC,kBAAkB,QAAQ,UAAU"}
1
+ {"version":3,"sources":["../../src/internals/index.ts"],"sourcesContent":["import type {\n BasePayload,\n CollectionConfig,\n CollectionSlug,\n GlobalSlug,\n JsonObject,\n TypeWithID,\n} from 'payload';\nimport z from 'zod';\nimport { uncaughtSwitchCase } from './utils';\n\n// MARK: Types\n\nexport const documentIdSchema = z.union([z.number(), z.string()]);\nexport type DocumentID = TypeWithID['id'] & z.infer<typeof documentIdSchema>;\n\nexport const documentReferenceSchema = z.discriminatedUnion('entity', [\n z.object({\n entity: z.literal('collection'),\n slug: z.string(),\n id: documentIdSchema,\n }),\n z.object({\n entity: z.literal('global'),\n slug: z.string(),\n }),\n]);\n\nexport type DocumentReference = z.infer<typeof documentReferenceSchema>;\n\n// MARK: Type Guards\n\nexport const isPopulated = <T extends TypeWithID>(\n relationship: T | DocumentID,\n): relationship is T => typeof relationship === 'object';\n\nexport function assertPopulated<T extends TypeWithID | null>(\n docsOrIds: (T | DocumentID)[],\n errorMessage?: (id: DocumentID) => string,\n): T[];\nexport function assertPopulated<T extends TypeWithID | null>(\n docOrId: T | DocumentID,\n errorMessage?: (id: DocumentID) => string,\n): T;\nexport function assertPopulated<T extends TypeWithID | null>(\n value: T | DocumentID | (T | DocumentID)[],\n errorMessage = (id: DocumentID) => `Doc is not populated: [${id}]`,\n): T | T[] {\n if (value === null) return value;\n if (Array.isArray(value)) {\n return value.map((item) => assertPopulated(item, errorMessage));\n }\n if (isPopulated(value)) return value;\n throw new Error(errorMessage(value as DocumentID));\n}\n\n// MARK: Utilities\n\nexport const createCollectionConfigFactory =\n <T extends Record<string, unknown>>(\n factory:\n | Omit<CollectionConfig, 'slug'>\n | ((options: T & { slug: string }) => Omit<CollectionConfig, 'slug'>),\n ) =>\n (options: T & { slug: string }): CollectionConfig => ({\n slug: options.slug,\n ...(typeof factory === 'function' ? factory(options) : factory),\n });\n\nexport type IdentifiableDocument = TypeWithID['id'] | TypeWithID;\n\nexport function isIdentifiableDocument(\n value: unknown,\n): value is IdentifiableDocument {\n if (typeof value === 'string') return true;\n if (typeof value === 'number') return true;\n if (value === null) return false;\n if (typeof value !== 'object') return true;\n if (!('id' in value)) return false;\n return isIdentifiableDocument(value.id);\n}\n\nexport const resolveDocumentID = (entity: IdentifiableDocument): DocumentID =>\n typeof entity === 'object' ? entity.id : entity;\n\nexport function fetchDocumentByReference(\n payload: BasePayload,\n ref: DocumentReference,\n): Promise<JsonObject> {\n switch (ref.entity) {\n case 'collection':\n return payload.findByID({\n collection: ref.slug as CollectionSlug,\n id: ref.id,\n depth: 0,\n });\n case 'global':\n return payload.findGlobal({\n slug: ref.slug as GlobalSlug,\n depth: 0,\n });\n default:\n return uncaughtSwitchCase(ref);\n }\n}\n\nexport async function updateDocumentByReference(\n payload: BasePayload,\n ref: DocumentReference,\n data: JsonObject,\n) {\n switch (ref.entity) {\n case 'collection':\n return payload.update({\n collection: ref.slug as CollectionSlug,\n id: ref.id,\n data: data,\n });\n case 'global':\n return payload.updateGlobal({\n slug: ref.slug as GlobalSlug,\n data: data as any,\n });\n default:\n return uncaughtSwitchCase(ref);\n }\n}\n\nexport {\n defineProcedure,\n type Procedure,\n type ProcedureBuilder,\n} from './procedure';\nexport { getAdminURL, getApiURL, getServerURL } from './urls';\nexport { findFields, uncaughtSwitchCase } from './utils';\n"],"names":["z","uncaughtSwitchCase","documentIdSchema","union","number","string","documentReferenceSchema","discriminatedUnion","object","entity","literal","slug","id","isPopulated","relationship","assertPopulated","value","errorMessage","Array","isArray","map","item","Error","createCollectionConfigFactory","factory","options","isIdentifiableDocument","resolveDocumentID","fetchDocumentByReference","payload","ref","findByID","collection","depth","findGlobal","updateDocumentByReference","data","update","updateGlobal","defineProcedure","getAdminURL","getApiURL","getServerURL","findFields"],"mappings":"AAQA,OAAOA,OAAO,MAAM;AACpB,SAASC,kBAAkB,QAAQ,UAAU;AAE7C,cAAc;AAEd,OAAO,MAAMC,mBAAmBF,EAAEG,KAAK,CAAC;IAACH,EAAEI,MAAM;IAAIJ,EAAEK,MAAM;CAAG,EAAE;AAGlE,OAAO,MAAMC,0BAA0BN,EAAEO,kBAAkB,CAAC,UAAU;IACpEP,EAAEQ,MAAM,CAAC;QACPC,QAAQT,EAAEU,OAAO,CAAC;QAClBC,MAAMX,EAAEK,MAAM;QACdO,IAAIV;IACN;IACAF,EAAEQ,MAAM,CAAC;QACPC,QAAQT,EAAEU,OAAO,CAAC;QAClBC,MAAMX,EAAEK,MAAM;IAChB;CACD,EAAE;AAIH,oBAAoB;AAEpB,OAAO,MAAMQ,cAAc,CACzBC,eACsB,OAAOA,iBAAiB,SAAS;AAUzD,OAAO,SAASC,gBACdC,KAA0C,EAC1CC,eAAe,CAACL,KAAmB,CAAC,uBAAuB,EAAEA,GAAG,CAAC,CAAC;IAElE,IAAII,UAAU,MAAM,OAAOA;IAC3B,IAAIE,MAAMC,OAAO,CAACH,QAAQ;QACxB,OAAOA,MAAMI,GAAG,CAAC,CAACC,OAASN,gBAAgBM,MAAMJ;IACnD;IACA,IAAIJ,YAAYG,QAAQ,OAAOA;IAC/B,MAAM,IAAIM,MAAML,aAAaD;AAC/B;AAEA,kBAAkB;AAElB,OAAO,MAAMO,gCACX,CACEC,UAIF,CAACC,UAAqD,CAAA;YACpDd,MAAMc,QAAQd,IAAI;YAClB,GAAI,OAAOa,YAAY,aAAaA,QAAQC,WAAWD,OAAO;QAChE,CAAA,EAAG;AAIL,OAAO,SAASE,uBACdV,KAAc;IAEd,IAAI,OAAOA,UAAU,UAAU,OAAO;IACtC,IAAI,OAAOA,UAAU,UAAU,OAAO;IACtC,IAAIA,UAAU,MAAM,OAAO;IAC3B,IAAI,OAAOA,UAAU,UAAU,OAAO;IACtC,IAAI,CAAE,CAAA,QAAQA,KAAI,GAAI,OAAO;IAC7B,OAAOU,uBAAuBV,MAAMJ,EAAE;AACxC;AAEA,OAAO,MAAMe,oBAAoB,CAAClB,SAChC,OAAOA,WAAW,WAAWA,OAAOG,EAAE,GAAGH,OAAO;AAElD,OAAO,SAASmB,yBACdC,OAAoB,EACpBC,GAAsB;IAEtB,OAAQA,IAAIrB,MAAM;QAChB,KAAK;YACH,OAAOoB,QAAQE,QAAQ,CAAC;gBACtBC,YAAYF,IAAInB,IAAI;gBACpBC,IAAIkB,IAAIlB,EAAE;gBACVqB,OAAO;YACT;QACF,KAAK;YACH,OAAOJ,QAAQK,UAAU,CAAC;gBACxBvB,MAAMmB,IAAInB,IAAI;gBACdsB,OAAO;YACT;QACF;YACE,OAAOhC,mBAAmB6B;IAC9B;AACF;AAEA,OAAO,eAAeK,0BACpBN,OAAoB,EACpBC,GAAsB,EACtBM,IAAgB;IAEhB,OAAQN,IAAIrB,MAAM;QAChB,KAAK;YACH,OAAOoB,QAAQQ,MAAM,CAAC;gBACpBL,YAAYF,IAAInB,IAAI;gBACpBC,IAAIkB,IAAIlB,EAAE;gBACVwB,MAAMA;YACR;QACF,KAAK;YACH,OAAOP,QAAQS,YAAY,CAAC;gBAC1B3B,MAAMmB,IAAInB,IAAI;gBACdyB,MAAMA;YACR;QACF;YACE,OAAOnC,mBAAmB6B;IAC9B;AACF;AAEA,SACES,eAAe,QAGV,cAAc;AACrB,SAASC,WAAW,EAAEC,SAAS,EAAEC,YAAY,QAAQ,SAAS;AAC9D,SAASC,UAAU,EAAE1C,kBAAkB,QAAQ,UAAU"}
@@ -1 +1 @@
1
- {"version":3,"file":"procedure.d.ts","sourceRoot":"","sources":["../../src/internals/procedure.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAExD,KAAK,MAAM,GAAG,KAAK,GAA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,SAAS,EAE/C,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,GAC/B,gBAAgB,CAAC,OAAO,SAAS,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,CAazE"}
@@ -58,6 +58,7 @@ function createProcedure(config, inputSchema) {
58
58
  const queryParams = {};
59
59
  if (input) {
60
60
  for (const [key, value] of Object.entries(input)){
61
+ if (value == null) continue;
61
62
  if (resolvedPath.includes(`:${key}`)) {
62
63
  resolvedPath = resolvedPath.replace(`:${key}`, encodeURIComponent(String(value)));
63
64
  } else {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/internals/procedure.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest } from 'payload';\n\ntype Method = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\n/** Any Zod-like schema with safeParse and inferred output */\ninterface ZodLike<TOutput = unknown> {\n safeParse(\n data: unknown,\n ): { success: true; data: TOutput } | { success: false; error: unknown };\n}\n\ntype InferOutput<T> = T extends ZodLike<infer O> ? O : never;\n\ninterface ProcedureConfig<TSchema extends ZodLike | undefined = undefined> {\n path: `/${string}`;\n method: Method;\n input?: TSchema;\n}\n\nexport interface Procedure<TInput, TOutput> {\n path: `/${string}`;\n method: Method;\n endpoint(\n handler: (\n req: PayloadRequest,\n ...args: TInput extends void ? [] : [input: TInput]\n ) => Promise<unknown | Response>,\n ): Endpoint;\n call(\n apiUrl: string,\n ...args: TInput extends void ? [] : [input: TInput]\n ): Promise<TOutput>;\n}\n\nexport interface ProcedureBuilder<TInput> {\n path: string;\n method: Method;\n returns<TOutput>(): Procedure<TInput, TOutput>;\n endpoint(\n handler: (\n req: PayloadRequest,\n ...args: TInput extends void ? [] : [input: TInput]\n ) => Promise<unknown | Response>,\n ): Endpoint;\n call(\n apiUrl: string,\n ...args: TInput extends void ? [] : [input: TInput]\n ): Promise<unknown>;\n}\n\nfunction wrapOutput(output: unknown): Response {\n if (output instanceof Response) return output;\n return Response.json(output);\n}\n\nfunction createProcedure<TInput, TOutput>(\n config: ProcedureConfig<ZodLike | undefined>,\n inputSchema: ZodLike | undefined,\n): Procedure<TInput, TOutput> {\n return {\n path: config.path,\n method: config.method,\n endpoint(handler) {\n return {\n path: config.path,\n method: config.method,\n handler: async (req) => {\n if (inputSchema) {\n if (config.method === 'get') {\n const routeParams = req.routeParams ?? {};\n const searchParams = req.searchParams\n ? Object.fromEntries(req.searchParams.entries())\n : {};\n const merged = { ...searchParams, ...routeParams };\n const result = inputSchema.safeParse(merged);\n if (!result.success) {\n return Response.json({ error: result.error }, { status: 400 });\n }\n // biome-ignore lint/complexity/noBannedTypes: ugly type cast\n const output = await (handler as Function)(req, result.data);\n return wrapOutput(output);\n }\n\n const { addDataAndFileToRequest } = await import(\n /* webpackIgnore: true */ 'payload'\n );\n await addDataAndFileToRequest(req);\n const result = inputSchema.safeParse(req.data);\n if (!result.success) {\n return Response.json({ error: result.error }, { status: 400 });\n }\n // biome-ignore lint/complexity/noBannedTypes: ugly type cast\n const output = await (handler as Function)(req, result.data);\n return wrapOutput(output);\n }\n // biome-ignore lint/complexity/noBannedTypes: ugly type cast\n const output = await (handler as Function)(req);\n return wrapOutput(output);\n },\n };\n },\n call(apiUrl, ...args) {\n const input = args[0] as Record<string, unknown> | undefined;\n\n if (config.method === 'get') {\n let resolvedPath = config.path;\n const queryParams: Record<string, string> = {};\n\n if (input) {\n for (const [key, value] of Object.entries(input)) {\n if (resolvedPath.includes(`:${key}`)) {\n resolvedPath = resolvedPath.replace(\n `:${key}`,\n encodeURIComponent(String(value)),\n ) as `/${string}`;\n } else {\n queryParams[key] = String(value);\n }\n }\n }\n\n const queryString = new URLSearchParams(queryParams).toString();\n const url = `${apiUrl}${resolvedPath}${queryString ? `?${queryString}` : ''}`;\n\n return fetch(url, {\n method: 'GET',\n credentials: 'include',\n }).then(async (response) => {\n if (!response.ok) {\n throw new Error(\n `Request failed: ${response.status} ${response.statusText}`,\n );\n }\n return response.json();\n }) as Promise<TOutput>;\n }\n\n const url = `${apiUrl}${config.path}`;\n return fetch(url, {\n method: config.method.toUpperCase(),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n body: input ? JSON.stringify(input) : undefined,\n }).then(async (response) => {\n if (!response.ok) {\n throw new Error(\n `Request failed: ${response.status} ${response.statusText}`,\n );\n }\n return response.json();\n }) as Promise<TOutput>;\n },\n };\n}\n\nexport function defineProcedure<\n TSchema extends ZodLike | undefined = undefined,\n>(\n config: ProcedureConfig<TSchema>,\n): ProcedureBuilder<TSchema extends ZodLike ? InferOutput<TSchema> : void> {\n type TInput = TSchema extends ZodLike ? InferOutput<TSchema> : undefined;\n const proc = createProcedure<TInput, unknown>(config, config.input);\n\n return {\n path: config.path,\n method: config.method,\n returns<TOutput>(): Procedure<TInput, TOutput> {\n return createProcedure<TInput, TOutput>(config, config.input);\n },\n endpoint: proc.endpoint as unknown as ProcedureBuilder<TInput>['endpoint'],\n call: proc.call as ProcedureBuilder<TInput>['call'],\n };\n}\n"],"names":["wrapOutput","output","Response","json","createProcedure","config","inputSchema","path","method","endpoint","handler","req","routeParams","searchParams","Object","fromEntries","entries","merged","result","safeParse","success","error","status","data","addDataAndFileToRequest","call","apiUrl","args","input","resolvedPath","queryParams","key","value","includes","replace","encodeURIComponent","String","queryString","URLSearchParams","toString","url","fetch","credentials","then","response","ok","Error","statusText","toUpperCase","headers","body","JSON","stringify","undefined","defineProcedure","proc","returns"],"mappings":"AAkDA,SAASA,WAAWC,MAAe;IACjC,IAAIA,kBAAkBC,UAAU,OAAOD;IACvC,OAAOC,SAASC,IAAI,CAACF;AACvB;AAEA,SAASG,gBACPC,MAA4C,EAC5CC,WAAgC;IAEhC,OAAO;QACLC,MAAMF,OAAOE,IAAI;QACjBC,QAAQH,OAAOG,MAAM;QACrBC,UAASC,OAAO;YACd,OAAO;gBACLH,MAAMF,OAAOE,IAAI;gBACjBC,QAAQH,OAAOG,MAAM;gBACrBE,SAAS,OAAOC;oBACd,IAAIL,aAAa;wBACf,IAAID,O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AAMkD,OAAOnD,gBAAiCC,QAAQA,OAAOuB,KAAK;IAElE,OAAO;QACLrB,MAAMF,OAAOE,IAAI;QACjBC,QAAQH,OAAOG,MAAM;QACrBgD;YACE,OAAOpD,gBAAiCC,QAAQA,OAAOuB,KAAK;QAC9D;QACAnB,UAAU8C,KAAK9C,QAAQ;QACvBgB,MAAM8B,KAAK9B,IAAI;IACjB;AACF"}
1
+ {"version":3,"sources":["../../src/internals/procedure.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest } from 'payload';\n\ntype Method = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\n/** Any Zod-like schema with safeParse and inferred output */\ninterface ZodLike<TOutput = unknown> {\n safeParse(\n data: unknown,\n ): { success: true; data: TOutput } | { success: false; error: unknown };\n}\n\ntype InferOutput<T> = T extends ZodLike<infer O> ? O : never;\n\ninterface ProcedureConfig<TSchema extends ZodLike | undefined = undefined> {\n path: `/${string}`;\n method: Method;\n input?: TSchema;\n}\n\nexport interface Procedure<TInput, TOutput> {\n path: `/${string}`;\n method: Method;\n endpoint(\n handler: (\n req: PayloadRequest,\n ...args: TInput extends void ? [] : [input: TInput]\n ) => Promise<unknown | Response>,\n ): Endpoint;\n call(\n apiUrl: string,\n ...args: TInput extends void ? [] : [input: TInput]\n ): Promise<TOutput>;\n}\n\nexport interface ProcedureBuilder<TInput> {\n path: string;\n method: Method;\n returns<TOutput>(): Procedure<TInput, TOutput>;\n endpoint(\n handler: (\n req: PayloadRequest,\n ...args: TInput extends void ? [] : [input: TInput]\n ) => Promise<unknown | Response>,\n ): Endpoint;\n call(\n apiUrl: string,\n ...args: TInput extends void ? [] : [input: TInput]\n ): Promise<unknown>;\n}\n\nfunction wrapOutput(output: unknown): Response {\n if (output instanceof Response) return output;\n return Response.json(output);\n}\n\nfunction createProcedure<TInput, TOutput>(\n config: ProcedureConfig<ZodLike | undefined>,\n inputSchema: ZodLike | undefined,\n): Procedure<TInput, TOutput> {\n return {\n path: config.path,\n method: config.method,\n endpoint(handler) {\n return {\n path: config.path,\n method: config.method,\n handler: async (req) => {\n if (inputSchema) {\n if (config.method === 'get') {\n const routeParams = req.routeParams ?? {};\n const searchParams = req.searchParams\n ? Object.fromEntries(req.searchParams.entries())\n : {};\n const merged = { ...searchParams, ...routeParams };\n const result = inputSchema.safeParse(merged);\n if (!result.success) {\n return Response.json({ error: result.error }, { status: 400 });\n }\n // biome-ignore lint/complexity/noBannedTypes: ugly type cast\n const output = await (handler as Function)(req, result.data);\n return wrapOutput(output);\n }\n\n const { addDataAndFileToRequest } = await import(\n /* webpackIgnore: true */ 'payload'\n );\n await addDataAndFileToRequest(req);\n const result = inputSchema.safeParse(req.data);\n if (!result.success) {\n return Response.json({ error: result.error }, { status: 400 });\n }\n // biome-ignore lint/complexity/noBannedTypes: ugly type cast\n const output = await (handler as Function)(req, result.data);\n return wrapOutput(output);\n }\n // biome-ignore lint/complexity/noBannedTypes: ugly type cast\n const output = await (handler as Function)(req);\n return wrapOutput(output);\n },\n };\n },\n call(apiUrl, ...args) {\n const input = args[0] as Record<string, unknown> | undefined;\n\n if (config.method === 'get') {\n let resolvedPath = config.path;\n const queryParams: Record<string, string> = {};\n\n if (input) {\n for (const [key, value] of Object.entries(input)) {\n if (value == null) continue;\n if (resolvedPath.includes(`:${key}`)) {\n resolvedPath = resolvedPath.replace(\n `:${key}`,\n encodeURIComponent(String(value)),\n ) as `/${string}`;\n } else {\n queryParams[key] = String(value);\n }\n }\n }\n\n const queryString = new URLSearchParams(queryParams).toString();\n const url = `${apiUrl}${resolvedPath}${queryString ? `?${queryString}` : ''}`;\n\n return fetch(url, {\n method: 'GET',\n credentials: 'include',\n }).then(async (response) => {\n if (!response.ok) {\n throw new Error(\n `Request failed: ${response.status} ${response.statusText}`,\n );\n }\n return response.json();\n }) as Promise<TOutput>;\n }\n\n const url = `${apiUrl}${config.path}`;\n return fetch(url, {\n method: config.method.toUpperCase(),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n body: input ? JSON.stringify(input) : undefined,\n }).then(async (response) => {\n if (!response.ok) {\n throw new Error(\n `Request failed: ${response.status} ${response.statusText}`,\n );\n }\n return response.json();\n }) as Promise<TOutput>;\n },\n };\n}\n\nexport function defineProcedure<\n TSchema extends ZodLike | undefined = undefined,\n>(\n config: ProcedureConfig<TSchema>,\n): ProcedureBuilder<TSchema extends ZodLike ? InferOutput<TSchema> : void> {\n type TInput = TSchema extends ZodLike ? InferOutput<TSchema> : undefined;\n const proc = createProcedure<TInput, unknown>(config, config.input);\n\n return {\n path: config.path,\n method: config.method,\n returns<TOutput>(): Procedure<TInput, TOutput> {\n return createProcedure<TInput, TOutput>(config, config.input);\n },\n endpoint: proc.endpoint as unknown as ProcedureBuilder<TInput>['endpoint'],\n call: proc.call as ProcedureBuilder<TInput>['call'],\n };\n}\n"],"names":["wrapOutput","output","Response","json","createProcedure","config","inputSchema","path","method","endpoint","handler","req","routeParams","searchParams","Object","fromEntries","entries","merged","result","safeParse","success","error","status","data","addDataAndFileToRequest","call","apiUrl","args","input","resolvedPath","queryParams","key","value","includes","replace","encodeURIComponent","String","queryString","URLSearchParams","toString","url","fetch","credentials","then","response","ok","Error","statusText","toUpperCase","headers","body","JSON","stringify","undefined","defineProcedure","proc","returns"],"mappings":"AAkDA,SAASA,WAAWC,MAAe;IACjC,IAAIA,kBAAkBC,UAAU,OAAOD;IACvC,OAAOC,SAASC,IAAI,CAACF;AACvB;AAEA,SAASG,gBACPC,MAA4C,EAC5CC,WAAgC;IAEhC,OAAO;QACLC,MAAMF,OAAOE,IAAI;QACjBC,QAAQH,OAAOG,MAAM;QACrBC,UAASC,OAAO;YACd,OAAO;gBACLH,MAAMF,OAAOE,IAAI;gBACjBC,QAAQH,OAAOG,MAAM;gBACrBE,SAAS,OAAOC;oBACd,IAAIL,aAAa;wBACf,IAAID,OAAOG,MAAM,KAAK,OAAO;4BAC3B,MAAMI,cAAcD,IAAIC,WAAW,IAAI,CAAC;4BACxC,MAAMC,eAAeF,IAAIE,YAAY,G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AI;QACjBC,QAAQH,OAAOG,MAAM;QACrBgD;YACE,OAAOpD,gBAAiCC,QAAQA,OAAOuB,KAAK;QAC9D;QACAnB,UAAU8C,KAAK9C,QAAQ;QACvBgB,MAAM8B,KAAK9B,IAAI;IACjB;AACF"}
@@ -1,5 +1,8 @@
1
1
  import type { Field } from 'payload';
2
2
  export declare const uncaughtSwitchCase: (value: never) => never;
3
- export declare function findFields<T extends Field>(fields: Field[], condition: (field: Field) => field is T): T[];
4
- export declare function findFields(fields: Field[], condition: (field: Field) => boolean): Field[];
3
+ export type FieldWithPath<T extends Field> = T & {
4
+ path: string[];
5
+ };
6
+ export declare function findFields<T extends Field>(fields: Field[], condition: (field: Field) => field is T, path?: string[]): FieldWithPath<T>[];
7
+ export declare function findFields(fields: Field[], condition: (field: Field) => boolean, path?: string[]): FieldWithPath<Field>[];
5
8
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/internals/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,eAAO,MAAM,kBAAkB,UAAW,KAAK,UAE9C,CAAC;AAEF,wBAAgB,UAAU,CAAC,CAAC,SAAS,KAAK,EACxC,MAAM,EAAE,KAAK,EAAE,EACf,SAAS,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,KAAK,IAAI,CAAC,GACtC,CAAC,EAAE,CAAC;AACP,wBAAgB,UAAU,CACxB,MAAM,EAAE,KAAK,EAAE,EACf,SAAS,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,OAAO,GACnC,KAAK,EAAE,CAAC"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/internals/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,eAAO,MAAM,kBAAkB,UAAW,KAAK,UAE9C,CAAC;AAEF,MAAM,MAAM,aAAa,CAAC,CAAC,SAAS,KAAK,IAAI,CAAC,GAAG;IAC/C,IAAI,EAAE,MAAM,EAAE,CAAC;CAChB,CAAC;AAEF,wBAAgB,UAAU,CAAC,CAAC,SAAS,KAAK,EACxC,MAAM,EAAE,KAAK,EAAE,EACf,SAAS,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,KAAK,IAAI,CAAC,EACvC,IAAI,CAAC,EAAE,MAAM,EAAE,GACd,aAAa,CAAC,CAAC,CAAC,EAAE,CAAC;AACtB,wBAAgB,UAAU,CACxB,MAAM,EAAE,KAAK,EAAE,EACf,SAAS,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,OAAO,EACpC,IAAI,CAAC,EAAE,MAAM,EAAE,GACd,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC"}
@@ -1,21 +1,36 @@
1
1
  export const uncaughtSwitchCase = (value)=>{
2
2
  throw new Error(`Unhandled switch case: ${value}`);
3
3
  };
4
- export function findFields(fields, condition) {
4
+ export function findFields(fields, condition, path = []) {
5
5
  return fields.flatMap((field)=>{
6
6
  if (condition(field)) {
7
7
  return [
8
- field
8
+ {
9
+ ...field,
10
+ path: 'name' in field ? [
11
+ ...path,
12
+ field.name
13
+ ] : path
14
+ }
9
15
  ];
10
16
  }
11
17
  if ('fields' in field) {
12
- return findFields(field.fields, condition);
18
+ return findFields(field.fields, condition, 'name' in field ? [
19
+ ...path,
20
+ field.name
21
+ ] : path);
13
22
  }
14
23
  switch(field.type){
15
24
  case 'blocks':
16
- return field.blocks.flatMap((block)=>findFields(block.fields, condition));
25
+ return field.blocks.flatMap((block)=>findFields(block.fields, condition, [
26
+ ...path,
27
+ field.name
28
+ ]));
17
29
  case 'tabs':
18
- return field.tabs.flatMap((tab)=>findFields(tab.fields, condition));
30
+ return field.tabs.flatMap((tab)=>findFields(tab.fields, condition, 'name' in tab ? [
31
+ ...path,
32
+ tab.name
33
+ ] : path));
19
34
  case 'text':
20
35
  case 'richText':
21
36
  case 'number':
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/internals/utils.ts"],"sourcesContent":["import type { Field } from 'payload';\n\nexport const uncaughtSwitchCase = (value: never) => {\n throw new Error(`Unhandled switch case: ${value}`);\n};\n\nexport function findFields<T extends Field>(\n fields: Field[],\n condition: (field: Field) => field is T,\n): T[];\nexport function findFields(\n fields: Field[],\n condition: (field: Field) => boolean,\n): Field[];\nexport function findFields(\n fields: Field[],\n condition: (field: Field) => boolean,\n): Field[] {\n return fields.flatMap((field) => {\n if (condition(field)) {\n return [field];\n }\n\n if ('fields' in field) {\n return findFields(field.fields, condition);\n }\n\n switch (field.type) {\n case 'blocks':\n return field.blocks.flatMap((block) =>\n findFields(block.fields, condition),\n );\n case 'tabs':\n return field.tabs.flatMap((tab) => findFields(tab.fields, condition));\n case 'text':\n case 'richText':\n case 'number':\n case 'checkbox':\n case 'date':\n case 'email':\n case 'select':\n case 'json':\n case 'code':\n case 'join':\n case 'point':\n case 'radio':\n case 'textarea':\n case 'ui':\n case 'relationship':\n case 'upload':\n return [];\n default:\n return uncaughtSwitchCase(field);\n }\n });\n}\n"],"names":["uncaughtSwitchCase","value","Error","findFields","fields","condition","flatMap","field","type","blocks","block","tabs","tab"],"mappings":"AAEA,OAAO,MAAMA,qBAAqB,CAACC;IACjC,MAAM,IAAIC,MAAM,CAAC,uBAAuB,EAAED,OAAO;AACnD,EAAE;AAUF,OAAO,SAASE,WACdC,MAAe,EACfC,SAAoC;IAEpC,OAAOD,OAAOE,OAAO,CAAC,CAACC;QACrB,IAAIF,UAAUE,QAAQ;YACpB,OAAO;gBAACA;aAAM;QAChB;QAEA,IAAI,YAAYA,OAAO;YACrB,OAAOJ,WAAWI,MAAMH,MAAM,EAAEC;QAClC;QAEA,OAAQE,MAAMC,IAAI;YAChB,KAAK;gBACH,OAAOD,MAAME,MAAM,CAACH,OAAO,CAAC,CAACI,QAC3BP,WAAWO,MAAMN,MAAM,EAAEC;YAE7B,KAAK;gBACH,OAAOE,MAAMI,IAAI,CAACL,OAAO,CAAC,CAACM,MAAQT,WAAWS,IAAIR,MAAM,EAAEC;YAC5D,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAO,EAAE;YACX;gBACE,OAAOL,mBAAmBO;QAC9B;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/internals/utils.ts"],"sourcesContent":["import type { Field } from 'payload';\n\nexport const uncaughtSwitchCase = (value: never) => {\n throw new Error(`Unhandled switch case: ${value}`);\n};\n\nexport type FieldWithPath<T extends Field> = T & {\n path: string[];\n};\n\nexport function findFields<T extends Field>(\n fields: Field[],\n condition: (field: Field) => field is T,\n path?: string[],\n): FieldWithPath<T>[];\nexport function findFields(\n fields: Field[],\n condition: (field: Field) => boolean,\n path?: string[],\n): FieldWithPath<Field>[];\nexport function findFields(\n fields: Field[],\n condition: (field: Field) => boolean,\n path: string[] = [],\n): FieldWithPath<Field>[] {\n return fields.flatMap((field) => {\n if (condition(field)) {\n return [\n { ...field, path: 'name' in field ? [...path, field.name] : path },\n ];\n }\n\n if ('fields' in field) {\n return findFields(\n field.fields,\n condition,\n 'name' in field ? [...path, field.name] : path,\n );\n }\n\n switch (field.type) {\n case 'blocks':\n return field.blocks.flatMap((block) =>\n findFields(block.fields, condition, [...path, field.name]),\n );\n case 'tabs':\n return field.tabs.flatMap((tab) =>\n findFields(\n tab.fields,\n condition,\n 'name' in tab ? [...path, tab.name] : path,\n ),\n );\n case 'text':\n case 'richText':\n case 'number':\n case 'checkbox':\n case 'date':\n case 'email':\n case 'select':\n case 'json':\n case 'code':\n case 'join':\n case 'point':\n case 'radio':\n case 'textarea':\n case 'ui':\n case 'relationship':\n case 'upload':\n return [];\n default:\n return uncaughtSwitchCase(field);\n }\n });\n}\n"],"names":["uncaughtSwitchCase","value","Error","findFields","fields","condition","path","flatMap","field","name","type","blocks","block","tabs","tab"],"mappings":"AAEA,OAAO,MAAMA,qBAAqB,CAACC;IACjC,MAAM,IAAIC,MAAM,CAAC,uBAAuB,EAAED,OAAO;AACnD,EAAE;AAgBF,OAAO,SAASE,WACdC,MAAe,EACfC,SAAoC,EACpCC,OAAiB,EAAE;IAEnB,OAAOF,OAAOG,OAAO,CAAC,CAACC;QACrB,IAAIH,UAAUG,QAAQ;YACpB,OAAO;gBACL;oBAAE,GAAGA,KAAK;oBAAEF,MAAM,UAAUE,QAAQ;2BAAIF;wBAAME,MAAMC,IAAI;qBAAC,GAAGH;gBAAK;aAClE;QACH;QAEA,IAAI,YAAYE,OAAO;YACrB,OAAOL,WACLK,MAAMJ,MAAM,EACZC,WACA,UAAUG,QAAQ;mBAAIF;gBAAME,MAAMC,IAAI;aAAC,GAAGH;QAE9C;QAEA,OAAQE,MAAME,IAAI;YAChB,KAAK;gBACH,OAAOF,MAAMG,MAAM,CAACJ,OAAO,CAAC,CAACK,QAC3BT,WAAWS,MAAMR,MAAM,EAAEC,WAAW;2BAAIC;wBAAME,MAAMC,IAAI;qBAAC;YAE7D,KAAK;gBACH,OAAOD,MAAMK,IAAI,CAACN,OAAO,CAAC,CAACO,MACzBX,WACEW,IAAIV,MAAM,EACVC,WACA,UAAUS,MAAM;2BAAIR;wBAAMQ,IAAIL,IAAI;qBAAC,GAAGH;YAG5C,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAO,EAAE;YACX;gBACE,OAAON,mBAAmBQ;QAC9B;IACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "payload-intl",
3
- "version": "1.2.3",
3
+ "version": "1.2.4",
4
4
  "description": "Payload Plugin for I18N using ICU Messages",
5
5
  "keywords": [
6
6
  "payload",