@davincicoding/payload-utils 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,24 @@
1
+ import type { BasePayload, JsonObject, TypeWithID } from 'payload';
2
+ import z from 'zod';
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;
17
+ export type IdentifiableDocument = TypeWithID['id'] | TypeWithID;
18
+ export declare function isIdentifiableDocument(value: unknown): value is IdentifiableDocument;
19
+ export declare const resolveDocumentID: (entity: IdentifiableDocument) => DocumentID;
20
+ export declare const uncaughtSwitchCase: (value: never) => never;
21
+ export declare function fetchDocumentByReference(payload: BasePayload, ref: DocumentReference): Promise<JsonObject>;
22
+ export declare function updateDocumentByReference(payload: BasePayload, ref: DocumentReference, data: JsonObject): Promise<JsonObject>;
23
+ export { getAdminURL, getApiURL, getServerURL } from './urls';
24
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":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,CAAC,CAgBrB;AAED,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,WAAW,EACpB,GAAG,EAAE,iBAAiB,EACtB,IAAI,EAAE,UAAU,uBAiBjB;AAED,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,76 @@
1
+ import z from 'zod';
2
+ // MARK: Types
3
+ export const documentIdSchema = z.union([
4
+ z.number(),
5
+ z.string()
6
+ ]);
7
+ export const documentReferenceSchema = z.discriminatedUnion('entity', [
8
+ z.object({
9
+ entity: z.literal('collection'),
10
+ slug: z.string(),
11
+ id: documentIdSchema
12
+ }),
13
+ z.object({
14
+ entity: z.literal('global'),
15
+ slug: z.string()
16
+ })
17
+ ]);
18
+ // MARK: Type Guards
19
+ export const isPopulated = (relationship)=>typeof relationship === 'object';
20
+ export function assertPopulated(value, errorMessage = (id)=>`Doc is not populated: [${id}]`) {
21
+ if (value === null) return value;
22
+ if (Array.isArray(value)) {
23
+ return value.map((item)=>assertPopulated(item, errorMessage));
24
+ }
25
+ if (isPopulated(value)) return value;
26
+ throw new Error(errorMessage(value));
27
+ }
28
+ export function isIdentifiableDocument(value) {
29
+ if (typeof value === 'string') return true;
30
+ if (typeof value === 'number') return true;
31
+ if (value === null) return false;
32
+ if (typeof value !== 'object') return true;
33
+ if (!('id' in value)) return false;
34
+ return isIdentifiableDocument(value.id);
35
+ }
36
+ export const resolveDocumentID = (entity)=>typeof entity === 'object' ? entity.id : entity;
37
+ export const uncaughtSwitchCase = (value)=>{
38
+ throw new Error(`Unhandled switch case: ${value}`);
39
+ };
40
+ export function fetchDocumentByReference(payload, ref) {
41
+ switch(ref.entity){
42
+ case 'collection':
43
+ return payload.findByID({
44
+ collection: ref.slug,
45
+ id: ref.id,
46
+ depth: 0
47
+ });
48
+ case 'global':
49
+ return payload.findGlobal({
50
+ slug: ref.slug,
51
+ depth: 0
52
+ });
53
+ default:
54
+ return uncaughtSwitchCase(ref);
55
+ }
56
+ }
57
+ export async function updateDocumentByReference(payload, ref, data) {
58
+ switch(ref.entity){
59
+ case 'collection':
60
+ return payload.update({
61
+ collection: ref.slug,
62
+ id: ref.id,
63
+ data: data
64
+ });
65
+ case 'global':
66
+ return payload.updateGlobal({
67
+ slug: ref.slug,
68
+ data: data
69
+ });
70
+ default:
71
+ return uncaughtSwitchCase(ref);
72
+ }
73
+ }
74
+ export { getAdminURL, getApiURL, getServerURL } from './urls';
75
+
76
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n BasePayload,\n CollectionSlug,\n GlobalSlug,\n JsonObject,\n TypeWithID,\n} from 'payload';\nimport z from 'zod';\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 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 const uncaughtSwitchCase = (value: never) => {\n throw new Error(`Unhandled switch case: ${value}`);\n};\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 { getAdminURL, getApiURL, getServerURL } from './urls';\n"],"names":["z","documentIdSchema","union","number","string","documentReferenceSchema","discriminatedUnion","object","entity","literal","slug","id","isPopulated","relationship","assertPopulated","value","errorMessage","Array","isArray","map","item","Error","isIdentifiableDocument","resolveDocumentID","uncaughtSwitchCase","fetchDocumentByReference","payload","ref","findByID","collection","depth","findGlobal","updateDocumentByReference","data","update","updateGlobal","getAdminURL","getApiURL","getServerURL"],"mappings":"AAOA,OAAOA,OAAO,MAAM;AAEpB,cAAc;AAEd,OAAO,MAAMC,mBAAmBD,EAAEE,KAAK,CAAC;IAACF,EAAEG,MAAM;IAAIH,EAA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B,QAAQE,QAAQ,CAAC;gBACtBC,YAAYF,IAAIjB,IAAI;gBACpBC,IAAIgB,IAAIhB,EAAE;gBACVmB,OAAO;YACT;QACF,KAAK;YACH,OAAOJ,QAAQK,UAAU,CAAC;gBACxBrB,MAAMiB,IAAIjB,IAAI;gBACdoB,OAAO;YACT;QACF;YACE,OAAON,mBAAmBG;IAC9B;AACF;AAEA,OAAO,eAAeK,0BACpBN,OAAoB,EACpBC,GAAsB,EACtBM,IAAgB;IAEhB,OAAQN,IAAInB,MAAM;QAChB,KAAK;YACH,OAAOkB,QAAQQ,MAAM,CAAC;gBACpBL,YAAYF,IAAIjB,IAAI;gBACpBC,IAAIgB,IAAIhB,EAAE;gBACVsB,MAAMA;YACR;QACF,KAAK;YACH,OAAOP,QAAQS,YAAY,CAAC;gBAC1BzB,MAAMiB,IAAIjB,IAAI;gBACduB,MAAMA;YACR;QACF;YACE,OAAOT,mBAAmBG;IAC9B;AACF;AAEA,SAASS,WAAW,EAAEC,SAAS,EAAEC,YAAY,QAAQ,SAAS"}
package/dist/urls.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ export declare function getServerURL(req: PayloadRequest): string;
3
+ export declare function getAdminURL({ req, path, }: {
4
+ req: PayloadRequest;
5
+ path?: '' | `/${string}` | null;
6
+ }): string;
7
+ export declare function getApiURL({ req, path, }: {
8
+ req: PayloadRequest;
9
+ path?: '' | `/${string}` | null;
10
+ }): string;
11
+ //# sourceMappingURL=urls.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"urls.d.ts","sourceRoot":"","sources":["../src/urls.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAG9C,wBAAgB,YAAY,CAAC,GAAG,EAAE,cAAc,GAAG,MAAM,CAWxD;AAED,wBAAgB,WAAW,CAAC,EAC1B,GAAG,EACH,IAAI,GACL,EAAE;IACD,GAAG,EAAE,cAAc,CAAC;IACpB,IAAI,CAAC,EAAE,EAAE,GAAG,IAAI,MAAM,EAAE,GAAG,IAAI,CAAC;CACjC,GAAG,MAAM,CAMT;AAED,wBAAgB,SAAS,CAAC,EACxB,GAAG,EACH,IAAI,GACL,EAAE;IACD,GAAG,EAAE,cAAc,CAAC;IACpB,IAAI,CAAC,EAAE,EAAE,GAAG,IAAI,MAAM,EAAE,GAAG,IAAI,CAAC;CACjC,GAAG,MAAM,CAMT"}
package/dist/urls.js ADDED
@@ -0,0 +1,23 @@
1
+ import { formatAdminURL } from 'payload/shared';
2
+ export function getServerURL(req) {
3
+ if (!req.url) throw new Error('Could not get serverURL, since request URL is not available');
4
+ const { config } = req.payload;
5
+ if (config.serverURL) return config.serverURL;
6
+ return `${new URL(req.url).protocol}//${req.headers.get('host')}`;
7
+ }
8
+ export function getAdminURL({ req, path }) {
9
+ return formatAdminURL({
10
+ adminRoute: req.payload.config.routes.admin,
11
+ serverURL: getServerURL(req),
12
+ path
13
+ });
14
+ }
15
+ export function getApiURL({ req, path }) {
16
+ return formatAdminURL({
17
+ apiRoute: req.payload.config.routes.api,
18
+ serverURL: getServerURL(req),
19
+ path
20
+ });
21
+ }
22
+
23
+ //# sourceMappingURL=urls.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/urls.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload';\nimport { formatAdminURL } from 'payload/shared';\n\nexport function getServerURL(req: PayloadRequest): string {\n if (!req.url)\n throw new Error(\n 'Could not get serverURL, since request URL is not available',\n );\n\n const { config } = req.payload;\n\n if (config.serverURL) return config.serverURL;\n\n return `${new URL(req.url).protocol}//${req.headers.get('host')}`;\n}\n\nexport function getAdminURL({\n req,\n path,\n}: {\n req: PayloadRequest;\n path?: '' | `/${string}` | null;\n}): string {\n return formatAdminURL({\n adminRoute: req.payload.config.routes.admin,\n serverURL: getServerURL(req),\n path,\n });\n}\n\nexport function getApiURL({\n req,\n path,\n}: {\n req: PayloadRequest;\n path?: '' | `/${string}` | null;\n}): string {\n return formatAdminURL({\n apiRoute: req.payload.config.routes.api,\n serverURL: getServerURL(req),\n path,\n });\n}\n"],"names":["formatAdminURL","getServerURL","req","url","Error","config","payload","serverURL","URL","protocol","headers","get","getAdminURL","path","adminRoute","routes","admin","getApiURL","apiRoute","api"],"mappings":"AACA,SAASA,cAAc,QAAQ,iBAAiB;AAEhD,OAAO,SAASC,aAAaC,GAAmB;IAC9C,IAAI,CAACA,IAAIC,GAAG,EACV,MAAM,IAAIC,MACR;IAGJ,MAAM,EAAEC,MAAM,EAAE,GAAGH,IAAII,OAAO;IAE9B,IAAID,OAAOE,SAAS,EAAE,OAAOF,OAAOE,SAAS;IAE7C,OAAO,GAAG,IAAIC,IAAIN,IAAIC,GAAG,EAAEM,QAAQ,CAAC,EAAE,EAAEP,IAAIQ,OAAO,CAACC,GAAG,CAAC,SAAS;AACnE;AAEA,OAAO,SAASC,YAAY,EAC1BV,GAAG,EACHW,IAAI,EAIL;IACC,OAAOb,eAAe;QACpBc,YAAYZ,IAAII,OAAO,CAACD,MAAM,CAACU,MAAM,CAACC,KAAK;QAC3CT,WAAWN,aAAaC;QACxBW;IACF;AACF;AAEA,OAAO,SAASI,UAAU,EACxBf,GAAG,EACHW,IAAI,EAIL;IACC,OAAOb,eAAe;QACpBkB,UAAUhB,IAAII,OAAO,CAACD,MAAM,CAACU,MAAM,CAACI,GAAG;QACvCZ,WAAWN,aAAaC;QACxBW;IACF;AACF"}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@davincicoding/payload-utils",
3
+ "version": "0.0.1",
4
+ "description": "Shared utilities for Payload CMS plugins and applications.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/davincicoding-org/payload-plugins.git",
8
+ "directory": "packages/utils"
9
+ },
10
+ "type": "module",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./urls": {
18
+ "types": "./dist/urls.d.ts",
19
+ "import": "./dist/urls.js",
20
+ "default": "./dist/urls.js"
21
+ }
22
+ },
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "scripts": {
29
+ "build": "swc src -d dist --config-file .swcrc --strip-leading-paths --ignore '**/*.test.ts' && tsc -p tsconfig.build.json --emitDeclarationOnly",
30
+ "check:types": "tsc --noEmit",
31
+ "clean": "rm -rf dist && rm -rf node_modules",
32
+ "test": "vitest run",
33
+ "test:watch": "vitest"
34
+ },
35
+ "dependencies": {
36
+ "zod": "catalog:"
37
+ },
38
+ "devDependencies": {
39
+ "@swc/cli": "^0.6.0",
40
+ "@swc/core": "^1.11.0",
41
+ "@types/node": "^22.5.4",
42
+ "payload": "catalog:payload-stack",
43
+ "typescript": "catalog:payload-stack",
44
+ "vitest": "^3.1.2"
45
+ },
46
+ "peerDependencies": {
47
+ "payload": ">=3.72.0"
48
+ },
49
+ "engines": {
50
+ "node": "^18.20.2 || >=20.9.0"
51
+ }
52
+ }