diff --git a/dist/ai/editor/lexical.schema.d.ts b/dist/ai/editor/lexical.schema.d.ts new file mode 100644 index 0000000..82aa5a4 --- /dev/null +++ b/dist/ai/editor/lexical.schema.d.ts @@ -0,0 +1,31 @@ +import { z } from 'zod'; +export declare const LexicalBaseNode: z.ZodObject<{ + type: z.ZodString; + children: z.ZodOptional>; + direction: z.ZodOptional>>; + format: z.ZodOptional; + indent: z.ZodOptional; + version: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + children?: any[]; + type?: string; + direction?: "ltr"; + format?: string; + indent?: number; + version?: number; +}, { + children?: any[]; + type?: string; + direction?: "ltr"; + format?: string; + indent?: number; + version?: number; +}>; +export declare const lexicalSchema: (customNodes?: (typeof LexicalBaseNode)[]) => z.ZodObject<{ + root: any; +}, "strip", z.ZodTypeAny, { + root?: any; +}, { + root?: any; +}>; +//# sourceMappingURL=lexical.schema.d.ts.map \ No newline at end of file diff --git a/dist/ai/editor/lexical.schema.d.ts.map b/dist/ai/editor/lexical.schema.d.ts.map new file mode 100644 index 0000000..72a3886 --- /dev/null +++ b/dist/ai/editor/lexical.schema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lexical.schema.d.ts","sourceRoot":"","sources":["../../../src/ai/editor/lexical.schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;EAO1B,CAAA;AAEF,eAAO,MAAM,aAAa,iBAAkB,CAAC,OAAO,eAAe,CAAC,EAAE;;;;;;EA2ErE,CAAA"} \ No newline at end of file diff --git a/dist/ai/editor/lexical.schema.js b/dist/ai/editor/lexical.schema.js new file mode 100644 index 0000000..0121939 --- /dev/null +++ b/dist/ai/editor/lexical.schema.js @@ -0,0 +1,102 @@ +import { z } from 'zod'; +export const LexicalBaseNode = z.object({ + type: z.string(), + children: z.array(z.any()).optional(), + direction: z.enum([ + 'ltr' + ]).nullable().optional(), + format: z.string().optional(), + indent: z.number().optional(), + version: z.number().optional() +}); +export const lexicalSchema = (customNodes)=>{ + const BaseNode = z.object({ + type: z.string(), + children: z.array(z.lazy(()=>Node)).optional(), + direction: z.enum([ + 'ltr' + ]).nullable().optional(), + format: z.string().optional(), + indent: z.number().optional(), + version: z.number().optional() + }); + const TextNode = BaseNode.extend({ + type: z.literal('text'), + format: z.number().optional(), + text: z.string() + }); + const LinkNode = BaseNode.extend({ + id: z.string(), + type: z.literal('link'), + fields: z.object({ + linkType: z.string(), + newTab: z.boolean(), + url: z.string() + }) + }); + const ListItemNode = BaseNode.extend({ + type: z.literal('listitem'), + checked: z.boolean().optional(), + value: z.number() + }); + const ListNode = BaseNode.extend({ + type: z.literal('list'), + listType: z.enum([ + 'check', + 'number', + 'bullet' + ]), + start: z.number(), + tag: z.enum([ + 'ul', + 'ol' + ]) + }); + const HeadingNode = BaseNode.extend({ + type: z.literal('heading'), + tag: z.enum([ + 'h1', + 'h2', + 'h3', + 'h4' + ]) + }); + // Apply these from paylodcma-ai config as example + const MediaNode = BaseNode.extend({ + type: z.literal('block'), + version: z.literal(2), + fields: z.object({ + id: z.string(), + media: z.string(), + position: z.enum([ + 'fullscreen', + 'default' + ]), + blockName: z.string(), + blockType: z.literal('mediaBlock') + }) + }); + const Node = z.union([ + TextNode, + LinkNode, + ListItemNode, + ListNode, + HeadingNode, + BaseNode.extend({ + type: z.enum([ + 'paragraph', + 'quote', + 'horizontalrule' + ]) + }), + ...customNodes || [] + ]); + const RootNode = BaseNode.extend({ + type: z.literal('root') + }); + return z.object({ + root: RootNode + }); +}; + +//# sourceMappingURL=lexical.schema.js.map \ No newline at end of file diff --git a/dist/ai/editor/lexical.schema.js.map b/dist/ai/editor/lexical.schema.js.map new file mode 100644 index 0000000..ef8376c --- /dev/null +++ b/dist/ai/editor/lexical.schema.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/ai/editor/lexical.schema.ts"],"sourcesContent":["import { z } from 'zod'\n\nexport const LexicalBaseNode = z.object({\n type: z.string(),\n children: z.array(z.any()).optional(),\n direction: z.enum(['ltr']).nullable().optional(),\n format: z.string().optional(),\n indent: z.number().optional(),\n version: z.number().optional(),\n})\n\nexport const lexicalSchema = (customNodes?: (typeof LexicalBaseNode)[]) => {\n const BaseNode = z.object({\n type: z.string(),\n children: z.array(z.lazy(() => Node)).optional(),\n direction: z.enum(['ltr']).nullable().optional(),\n format: z.string().optional(),\n indent: z.number().optional(),\n version: z.number().optional(),\n })\n\n const TextNode = BaseNode.extend({\n type: z.literal('text'),\n format: z.number().optional(),\n text: z.string(),\n })\n\n const LinkNode = BaseNode.extend({\n id: z.string(),\n type: z.literal('link'),\n fields: z.object({\n linkType: z.string(),\n newTab: z.boolean(),\n url: z.string(),\n }),\n })\n\n const ListItemNode = BaseNode.extend({\n type: z.literal('listitem'),\n checked: z.boolean().optional(),\n value: z.number(),\n })\n\n const ListNode = BaseNode.extend({\n type: z.literal('list'),\n listType: z.enum(['check', 'number', 'bullet']),\n start: z.number(),\n tag: z.enum(['ul', 'ol']),\n })\n\n const HeadingNode = BaseNode.extend({\n type: z.literal('heading'),\n tag: z.enum(['h1', 'h2', 'h3', 'h4']),\n })\n\n // Apply these from paylodcma-ai config as example\n\n const MediaNode = BaseNode.extend({\n type: z.literal('block'),\n version: z.literal(2),\n fields: z.object({\n id: z.string(),\n media: z.string(),\n position: z.enum(['fullscreen', 'default']),\n blockName: z.string(),\n blockType: z.literal('mediaBlock'),\n }),\n })\n\n const Node = z.union([\n TextNode,\n LinkNode,\n ListItemNode,\n ListNode,\n HeadingNode,\n BaseNode.extend({ type: z.enum(['paragraph', 'quote', 'horizontalrule']) }),\n ...(customNodes || []),\n ])\n\n const RootNode = BaseNode.extend({\n type: z.literal('root'),\n })\n\n return z.object({\n root: RootNode,\n })\n}\n"],"names":["z","LexicalBaseNode","object","type","string","children","array","any","optional","direction","enum","nullable","format","indent","number","version","lexicalSchema","customNodes","BaseNode","lazy","Node","TextNode","extend","literal","text","LinkNode","id","fields","linkType","newTab","boolean","url","ListItemNode","checked","value","ListNode","listType","start","tag","HeadingNode","MediaNode","media","position","blockName","blockType","union","RootNode","root"],"mappings":"AAAA,SAASA,CAAC,QAAQ,MAAK;AAEvB,OAAO,MAAMC,kBAAkBD,EAAEE,MAAM,CAAC;IACtCC,MAAMH,EAAEI,MAAM;IACdC,UAAUL,EAAEM,KAAK,CAACN,EAAEO,GAAG,IAAIC,QAAQ;IACnCC,WAAWT,EAAEU,IAAI,CAAC;QAAC;KAAM,EAAEC,QAAQ,GAAGH,QAAQ;IAC9CI,QAAQZ,EAAEI,MAAM,GAAGI,QAAQ;IAC3BK,QAAQb,EAAEc,MAAM,GAAGN,QAAQ;IAC3BO,SAASf,EAAEc,MAAM,GAAGN,QAAQ;AAC9B,GAAE;AAEF,OAAO,MAAMQ,gBAAgB,CAACC;IAC5B,MAAMC,WAAWlB,EAAEE,MAAM,CAAC;QACxBC,MAAMH,EAAEI,MAAM;QACdC,UAAUL,EAAEM,KAAK,CAACN,EAAEmB,IAAI,CAAC,IAAMC,OAAOZ,QAAQ;QAC9CC,WAAWT,EAAEU,IAAI,CAAC;YAAC;SAAM,EAAEC,QAAQ,GAAGH,QAAQ;QAC9CI,QAAQZ,EAAEI,MAAM,GAAGI,QAAQ;QAC3BK,QAAQb,EAAEc,MAAM,GAAGN,QAAQ;QAC3BO,SAASf,EAAEc,MAAM,GAAGN,QAAQ;IAC9B;IAEA,MAAMa,WAAWH,SAASI,MAAM,CAAC;QAC/BnB,MAAMH,EAAEuB,OAAO,CAAC;QAChBX,QAAQZ,EAAEc,MAAM,GAAGN,QAAQ;QAC3BgB,MAAMxB,EAAEI,MAAM;IAChB;IAEA,MAAMqB,WAAWP,SAASI,MAAM,CAAC;QAC/BI,IAAI1B,EAAEI,MAAM;QACZD,MAAMH,EAAEuB,OAAO,CAAC;QAChBI,QAAQ3B,EAAEE,MAAM,CAAC;YACf0B,UAAU5B,EAAEI,MAAM;YAClByB,QAAQ7B,EAAE8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MAAM,CAAC;QACd6C,MAAMD;IACR;AACF,EAAC"} \ No newline at end of file diff --git a/dist/ai/models/anthropic/generateRichText.d.ts.map b/dist/ai/models/anthropic/generateRichText.d.ts.map index 7c83037..0048eed 100644 --- a/dist/ai/models/anthropic/generateRichText.d.ts.map +++ b/dist/ai/models/anthropic/generateRichText.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"generateRichText.d.ts","sourceRoot":"","sources":["../../../../src/ai/models/anthropic/generateRichText.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,gBAAgB,SAAgB,MAAM,WAAW,GAAG,sBAahE,CAAA"} \ No newline at end of file +{"version":3,"file":"generateRichText.d.ts","sourceRoot":"","sources":["../../../../src/ai/models/anthropic/generateRichText.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,gBAAgB,SAAgB,MAAM,WAAW,GAAG,sBAahE,CAAA"} \ No newline at end of file diff --git a/dist/ai/models/anthropic/generateRichText.js b/dist/ai/models/anthropic/generateRichText.js index 56edc2d..b4ca307 100644 --- a/dist/ai/models/anthropic/generateRichText.js +++ b/dist/ai/models/anthropic/generateRichText.js @@ -1,11 +1,10 @@ import { anthropic } from '@ai-sdk/anthropic'; import { streamObject } from 'ai'; -import { DocumentSchema } from '../../RichTextSchema.js'; export const generateRichText = async (text, options)=>{ const streamResult = await streamObject({ model: anthropic(options.model), prompt: text, - schema: DocumentSchema, + schema: options.editorSchema, system: `${options.system} LAYOUT: diff --git a/dist/ai/models/anthropic/generateRichText.js.map b/dist/ai/models/anthropic/generateRichText.js.map index 1633d7e..2f64660 100644 --- a/dist/ai/models/anthropic/generateRichText.js.map +++ b/dist/ai/models/anthropic/generateRichText.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../../src/ai/models/anthropic/generateRichText.ts"],"sourcesContent":["import { anthropic } from '@ai-sdk/anthropic'\nimport { streamObject } from 'ai'\n\nimport { DocumentSchema } from '../../RichTextSchema.js'\nimport { exampleOutput } from '../example.js'\n\nexport const generateRichText = async (text: string, options: any) => {\n const streamResult = await streamObject({\n model: anthropic(options.model),\n prompt: text,\n schema: DocumentSchema,\n system: `${options.system}\n\n LAYOUT:\n ${options.layout}\n `,\n })\n\n return streamResult.toTextStreamResponse()\n}\n"],"names":["anthropic","streamObject","DocumentSchema","generateRichText","text","options","streamResult","model","prompt","schema","system","layout","toTextStreamResponse"],"mappings":"AAAA,SAASA,SAAS,QAAQ,oBAAmB;AAC7C,SAASC,YAAY,QAAQ,KAAI;AAEjC,SAASC,cAAc,QAAQ,0BAAyB;AAGxD,OAAO,MAAMC,mBAAmB,OAAOC,MAAcC;IACnD,MAAMC,eAAe,MAAML,aAAa;QACtCM,OAAOP,UAAUK,QAAQE,KAAK;QAC9BC,QAAQJ;QACRK,QAAQP;QACRQ,QAAQ,CAAC,EAAEL,QAAQK,MAAM,CAAC;;;MAGxB,EAAEL,QAAQM,MAAM,CAAC;MACjB,CAAC;IACL;IAEA,OAAOL,aAAaM,oBAAoB;AAC1C,EAAC"} \ No newline at end of file +{"version":3,"sources":["../../../../src/ai/models/anthropic/generateRichText.ts"],"sourcesContent":["import { anthropic } from '@ai-sdk/anthropic'\nimport { streamObject } from 'ai'\n\nexport const generateRichText = async (text: string, options: any) => {\n const streamResult = await streamObject({\n model: anthropic(options.model),\n prompt: text,\n schema: options.editorSchema,\n system: `${options.system}\n\n LAYOUT:\n ${options.layout}\n `,\n })\n\n return streamResult.toTextStreamResponse()\n}\n"],"names":["anthropic","streamObject","generateRichText","text","options","streamResult","model","prompt","schema","editorSchema","system","layout","toTextStreamResponse"],"mappings":"AAAA,SAASA,SAAS,QAAQ,oBAAmB;AAC7C,SAASC,YAAY,QAAQ,KAAI;AAEjC,OAAO,MAAMC,mBAAmB,OAAOC,MAAcC;IACnD,MAAMC,eAAe,MAAMJ,aAAa;QACtCK,OAAON,UAAUI,QAAQE,KAAK;QAC9BC,QAAQJ;QACRK,QAAQJ,QAAQK,YAAY;QAC5BC,QAAQ,CAAC,EAAEN,QAAQM,MAAM,CAAC;;;MAGxB,EAAEN,QAAQO,MAAM,CAAC;MACjB,CAAC;IACL;IAEA,OAAON,aAAaO,oBAAoB;AAC1C,EAAC"} \ No newline at end of file diff --git a/dist/ai/models/openai/generateRichText.d.ts.map b/dist/ai/models/openai/generateRichText.d.ts.map index 483ee0c..e896c18 100644 --- a/dist/ai/models/openai/generateRichText.d.ts.map +++ b/dist/ai/models/openai/generateRichText.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"generateRichText.d.ts","sourceRoot":"","sources":["../../../../src/ai/models/openai/generateRichText.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,gBAAgB,SAAgB,MAAM,WAAW,GAAG,sBAsBhE,CAAA;AAED,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,MAAM,MAAM,CAAC,EAAE,EAAE,EAAE,IAAI,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,GAAG,EAAE,CAAA;AACpD,MAAM,MAAM,qBAAqB,CAAC,CAAC,SAAS,qBAAqB,GAAG,qBAAqB,IAAI,MAAM,CACjG;IACE,QAAQ,EAAE,CAAC,EAAE,CAAA;IAEb,SAAS,EAAE,KAAK,GAAG,KAAK,GAAG,IAAI,CAAA;IAE/B,MAAM,EAAE,iBAAiB,CAAA;IAEzB,MAAM,EAAE,MAAM,CAAA;CACf,EACD,qBAAqB,CACtB,CAAA;AAED,MAAM,MAAM,kBAAkB,CAAC,CAAC,SAAS,qBAAqB,GAAG,qBAAqB,IACpF,qBAAqB,CAAC,CAAC,CAAC,CAAA;AAE1B,MAAM,MAAM,iBAAiB,GAAG,EAAE,GAAG,QAAQ,GAAG,KAAK,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAA"} \ No newline at end of file +{"version":3,"file":"generateRichText.d.ts","sourceRoot":"","sources":["../../../../src/ai/models/openai/generateRichText.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,gBAAgB,SAAgB,MAAM,WAAW,GAAG,sBAsBhE,CAAA;AAED,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,MAAM,MAAM,CAAC,EAAE,EAAE,EAAE,IAAI,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,GAAG,EAAE,CAAA;AACpD,MAAM,MAAM,qBAAqB,CAAC,CAAC,SAAS,qBAAqB,GAAG,qBAAqB,IAAI,MAAM,CACjG;IACE,QAAQ,EAAE,CAAC,EAAE,CAAA;IAEb,SAAS,EAAE,KAAK,GAAG,KAAK,GAAG,IAAI,CAAA;IAE/B,MAAM,EAAE,iBAAiB,CAAA;IAEzB,MAAM,EAAE,MAAM,CAAA;CACf,EACD,qBAAqB,CACtB,CAAA;AAED,MAAM,MAAM,kBAAkB,CAAC,CAAC,SAAS,qBAAqB,GAAG,qBAAqB,IACpF,qBAAqB,CAAC,CAAC,CAAC,CAAA;AAE1B,MAAM,MAAM,iBAAiB,GAAG,EAAE,GAAG,QAAQ,GAAG,KAAK,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAA"} \ No newline at end of file diff --git a/dist/ai/models/openai/generateRichText.js b/dist/ai/models/openai/generateRichText.js index ebb9651..9795f90 100644 --- a/dist/ai/models/openai/generateRichText.js +++ b/dist/ai/models/openai/generateRichText.js @@ -1,12 +1,11 @@ import { openai } from '@ai-sdk/openai'; import { streamObject } from 'ai'; -import { DocumentSchema } from '../../RichTextSchema.js'; import { exampleOutput } from '../example.js'; export const generateRichText = async (text, options)=>{ const streamResult = await streamObject({ model: openai(options.model), prompt: text, - schema: DocumentSchema, + schema: options.editorSchema, system: `${options.system} RULES: diff --git a/dist/ai/models/openai/generateRichText.js.map b/dist/ai/models/openai/generateRichText.js.map index 466965c..43a4b91 100644 --- a/dist/ai/models/openai/generateRichText.js.map +++ b/dist/ai/models/openai/generateRichText.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../../src/ai/models/openai/generateRichText.ts"],"sourcesContent":["import { openai } from '@ai-sdk/openai'\nimport { streamObject } from 'ai'\n\nimport { DocumentSchema } from '../../RichTextSchema.js'\nimport { exampleOutput } from '../example.js'\n\nexport const generateRichText = async (text: string, options: any) => {\n const streamResult = await streamObject({\n model: openai(options.model),\n prompt: text,\n schema: DocumentSchema,\n system: `${options.system}\n\n RULES:\n - Must be original and unique content.\n - Must follow given guidelines and instructions.\n - Always use given tool\n - Must follow rules of sample output object\n - Must be valid JSON with no undefined or null values\n\n SAMPLE OUTPUT OBJECT:\n ${JSON.stringify(exampleOutput)}\n \n LAYOUT:\n ${options.layout}\n `,\n })\n return streamResult.toTextStreamResponse()\n}\n\nexport interface SerializedLexicalNode {\n type: string\n version: number\n}\n\nexport type Spread = Omit & T1\nexport type SerializedElementNode = Spread<\n {\n children: T[]\n\n direction: 'ltr' | 'rtl' | null\n\n format: ElementFormatType\n\n indent: number\n },\n SerializedLexicalNode\n>\n\nexport type SerializedRootNode =\n SerializedElementNode\n\nexport type ElementFormatType = '' | 'center' | 'end' | 'justify' | 'left' | 'right' | 'start'\n"],"names":["openai","streamObject","DocumentSchema","exampleOutput","generateRichText","text","options","streamResult","model","prompt","schema","system","JSON","stringify","layout","toTextStreamResponse"],"mappings":"AAAA,SAASA,MAAM,QAAQ,iBAAgB;AACvC,SAASC,YAAY,QAAQ,KAAI;AAEjC,SAASC,cAAc,QAAQ,0BAAyB;AACxD,SAASC,aAAa,QAAQ,gBAAe;AAE7C,OAAO,MAAMC,mBAAmB,OAAOC,MAAcC;IACnD,MAAMC,eAAe,MAAMN,aAAa;QACtCO,OAAOR,OAAOM,QAAQE,KAAK;QAC3BC,QAAQJ;QACRK,QAAQR;QACRS,QAAQ,CAAC,EAAEL,QAAQK,MAAM,CAAC;;;;;;;;;;MAUxB,EAAEC,KAAKC,SAAS,CAACV,eAAe;;;MAGhC,EAAEG,QAAQQ,MAAM,CAAC;MACjB,CAAC;IACL;IACA,OAAOP,aAAaQ,oBAAoB;AAC1C,EAAC"} \ No newline at end of file +{"version":3,"sources":["../../../../src/ai/models/openai/generateRichText.ts"],"sourcesContent":["import { openai } from '@ai-sdk/openai'\nimport { streamObject } from 'ai'\n\nimport { exampleOutput } from '../example.js'\n\nexport const generateRichText = async (text: string, options: any) => {\n const streamResult = await streamObject({\n model: openai(options.model),\n prompt: text,\n schema: options.editorSchema,\n system: `${options.system}\n\n RULES:\n - Must be original and unique content.\n - Must follow given guidelines and instructions.\n - Always use given tool\n - Must follow rules of sample output object\n - Must be valid JSON with no undefined or null values\n\n SAMPLE OUTPUT OBJECT:\n ${JSON.stringify(exampleOutput)}\n \n LAYOUT:\n ${options.layout}\n `,\n })\n return streamResult.toTextStreamResponse()\n}\n\nexport interface SerializedLexicalNode {\n type: string\n version: number\n}\n\nexport type Spread = Omit & T1\nexport type SerializedElementNode = Spread<\n {\n children: T[]\n\n direction: 'ltr' | 'rtl' | null\n\n format: ElementFormatType\n\n indent: number\n },\n SerializedLexicalNode\n>\n\nexport type SerializedRootNode =\n SerializedElementNode\n\nexport type ElementFormatType = '' | 'center' | 'end' | 'justify' | 'left' | 'right' | 'start'\n"],"names":["openai","streamObject","exampleOutput","generateRichText","text","options","streamResult","model","prompt","schema","editorSchema","system","JSON","stringify","layout","toTextStreamResponse"],"mappings":"AAAA,SAASA,MAAM,QAAQ,iBAAgB;AACvC,SAASC,YAAY,QAAQ,KAAI;AAEjC,SAASC,aAAa,QAAQ,gBAAe;AAE7C,OAAO,MAAMC,mBAAmB,OAAOC,MAAcC;IACnD,MAAMC,eAAe,MAAML,aAAa;QACtCM,OAAOP,OAAOK,QAAQE,KAAK;QAC3BC,QAAQJ;QACRK,QAAQJ,QAAQK,YAAY;QAC5BC,QAAQ,CAAC,EAAEN,QAAQM,MAAM,CAAC;;;;;;;;;;MAUxB,EAAEC,KAAKC,SAAS,CAACX,eAAe;;;MAGhC,EAAEG,QAAQS,MAAM,CAAC;MACjB,CAAC;IACL;IACA,OAAOR,aAAaS,oBAAoB;AAC1C,EAAC"} \ No newline at end of file diff --git a/dist/endpoints/index.d.ts.map b/dist/endpoints/index.d.ts.map index 758efe8..ec9ac05 100644 --- a/dist/endpoints/index.d.ts.map +++ b/dist/endpoints/index.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/endpoints/index.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAmB,SAAS,EAAE,MAAM,aAAa,CAAA;AA4F7D,eAAO,MAAM,SAAS,EAAE,SAyHvB,CAAA"} \ No newline at end of file +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/endpoints/index.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAmB,SAAS,EAAE,MAAM,aAAa,CAAA;AA8F7D,eAAO,MAAM,SAAS,EAAE,SAmIvB,CAAA"} \ No newline at end of file diff --git a/dist/endpoints/index.js b/dist/endpoints/index.js index f4542ff..3f2fae8 100644 --- a/dist/endpoints/index.js +++ b/dist/endpoints/index.js @@ -5,6 +5,8 @@ import { defaultPrompts } from '../ai/prompts.js'; import { PLUGIN_API_ENDPOINT_GENERATE, PLUGIN_API_ENDPOINT_GENERATE_UPLOAD, PLUGIN_INSTRUCTIONS_TABLE } from '../defaults.js'; import { getFieldBySchemaPath } from '../utilities/getFieldBySchemaPath.js'; import { lexicalToHTML } from '../utilities/lexicalToHTML.js'; +import { lexicalSchema } from '../ai/editor/lexical.schema.js'; +// import { DocumentSchema } from '../ai/editor/lexical.schema.js' const asyncHandlebars = asyncHelpers(Handlebars); const replacePlaceholders = (prompt, values)=>{ return asyncHandlebars.compile(prompt, { @@ -65,6 +67,10 @@ export const endpoints = { 'model-id': '', prompt: '' }; + const { collections } = req.payload.config; + const collection = collections.find((collection)=>collection.slug === PLUGIN_INSTRUCTIONS_TABLE); + const { editorConfig: { schema: editorSchema = lexicalSchema() } = {} } = collection.custom || {}; + console.log('editorSchema : ', editorSchema); if (instructionId) { // @ts-expect-error instructions = await req.payload.findByID({ @@ -101,7 +107,8 @@ export const endpoints = { return model.handler?.(prompts.prompt, { ...modelOptions, ...opt, - system: prompts.system + system: prompts.system, + editorSchema }).catch((error)=>{ console.error('Error: endpoint - generating text:', error); return new Response(JSON.stringify(error.message), { diff --git a/dist/endpoints/index.js.map b/dist/endpoints/index.js.map index 38cb21a..bc74bb4 100644 --- a/dist/endpoints/index.js.map +++ b/dist/endpoints/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/endpoints/index.ts"],"sourcesContent":["import type { SerializedEditorState } from 'lexical'\nimport type { BasePayload, PayloadRequest } from 'payload'\n\nimport Handlebars from 'handlebars'\nimport asyncHelpers from 'handlebars-async-helpers'\n\nimport type { ActionMenuItems, Endpoints } from '../types.js'\n\nimport { GenerationModels } from '../ai/models/index.js'\nimport { defaultPrompts } from '../ai/prompts.js'\nimport {\n PLUGIN_API_ENDPOINT_GENERATE,\n PLUGIN_API_ENDPOINT_GENERATE_UPLOAD,\n PLUGIN_INSTRUCTIONS_TABLE,\n} from '../defaults.js'\nimport { getFieldBySchemaPath } from '../utilities/getFieldBySchemaPath.js'\nimport { lexicalToHTML } from '../utilities/lexicalToHTML.js'\n\nconst asyncHandlebars = asyncHelpers(Handlebars)\n\nconst replacePlaceholders = (prompt: string, values: object) => {\n return asyncHandlebars.compile(prompt, { trackIds: true })(values)\n}\n\nconst assignPrompt = async (\n action: ActionMenuItems,\n {\n type,\n actionParams,\n context,\n field,\n systemPrompt = '',\n template,\n }: {\n actionParams: unknown\n context: object\n field: string\n systemPrompt: string\n template: string\n type: string\n },\n) => {\n const prompt = await replacePlaceholders(template, context)\n\n const toLexicalHTML = type === 'richText' ? 'toLexicalHTML' : ''\n\n const assignedPrompts = {\n prompt,\n system: systemPrompt,\n }\n\n if (action === 'Compose') {\n return assignedPrompts\n }\n\n const { system: getSystemPrompt } = defaultPrompts.find((p) => p.name === action)\n\n return {\n prompt: await replacePlaceholders(`{{${toLexicalHTML} ${field}}}`, context),\n system: getSystemPrompt(prompt, systemPrompt, (actionParams || '') as string),\n }\n}\n\nconst registerEditorHelper = (payload, schemaPath) => {\n //TODO: add autocomplete ability using handlebars template on PromptEditorField and include custom helpers in dropdown\n\n let fieldInfo = getFieldInfo(payload.collections, schemaPath)\n const schemaPathChunks = schemaPath.split('.')\n\n asyncHandlebars.registerHelper(\n 'toLexicalHTML',\n async function (content: SerializedEditorState, options) {\n const collectionSlug = schemaPathChunks[0]\n const { ids } = options\n for (const id of ids) {\n //TODO: Find a better to get schemaPath of defined field in prompt editor\n const path = `${collectionSlug}.${id}`\n fieldInfo = getFieldInfo(payload.collections, path)\n }\n\n const html = await lexicalToHTML(content, fieldInfo.editor?.editorConfig)\n return new asyncHandlebars.SafeString(html)\n },\n )\n}\n\nconst getFieldInfo = (collections: BasePayload['collections'], schemaPath: string) => {\n let fieldInfo = null\n //TODO: Only run below for enabled collections\n for (const collectionsKey in collections) {\n const collection = collections[collectionsKey]\n fieldInfo = getFieldBySchemaPath(collection.config, schemaPath)\n if (fieldInfo) {\n return fieldInfo\n }\n }\n}\n\nexport const endpoints: Endpoints = {\n textarea: {\n handler: async (req: PayloadRequest) => {\n const data = await req.json?.()\n\n const { locale = 'en', options } = data\n const { action, actionParams, instructionId } = options\n const contextData = data.doc\n\n let instructions = { 'model-id': '', prompt: '' }\n\n if (instructionId) {\n // @ts-expect-error\n instructions = await req.payload.findByID({\n id: instructionId,\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n })\n }\n\n const { prompt: promptTemplate = '' } = instructions\n\n const schemaPath = instructions['schema-path']\n const fieldName = schemaPath?.split('.').pop()\n\n registerEditorHelper(req.payload, schemaPath)\n\n const { defaultLocale, locales = [] } = req.payload.config.localization || {}\n const localeData = locales.find((l) => {\n return l.code === locale\n })\n\n const localeInfo = localeData?.label[defaultLocale] || locale\n\n //TODO: remove this\n const opt = {\n locale: localeInfo,\n modelId: instructions['model-id'],\n }\n\n const model = GenerationModels.find((model) => model.id === opt.modelId)\n const settingsName = model.settings?.name\n const modelOptions = instructions[settingsName] || {}\n\n const prompts = await assignPrompt(action, {\n type: instructions['field-type'],\n actionParams,\n context: contextData,\n field: fieldName,\n systemPrompt: modelOptions.system,\n template: promptTemplate,\n })\n\n console.log('Running handler with prompts:', prompts)\n return model\n .handler?.(prompts.prompt, {\n ...modelOptions,\n ...opt,\n system: prompts.system,\n })\n .catch((error) => {\n console.error('Error: endpoint - generating text:', error)\n return new Response(JSON.stringify(error.message), { status: 500 })\n })\n },\n method: 'post',\n path: PLUGIN_API_ENDPOINT_GENERATE,\n },\n upload: {\n handler: async (req: PayloadRequest) => {\n const data = await req.json?.()\n\n const { options } = data\n const { instructionId, uploadCollectionSlug } = options\n const contextData = data.doc\n\n let instructions = { 'model-id': '', prompt: '' }\n\n if (instructionId) {\n // @ts-expect-error\n instructions = await req.payload.findByID({\n id: instructionId,\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n })\n }\n\n const { prompt: promptTemplate = '' } = instructions\n const schemaPath = instructions['schema-path']\n\n registerEditorHelper(req.payload, schemaPath)\n\n const text = await replacePlaceholders(promptTemplate, contextData)\n const modelId = instructions['model-id']\n console.log('prompt text:', text)\n\n const model = GenerationModels.find((model) => model.id === modelId)\n const settingsName = model.settings?.name\n const modelOptions = instructions[settingsName] || {}\n console.log('modelOptions', modelOptions)\n\n const result = await model.handler?.(text, modelOptions)\n\n const assetData = await req.payload.create({\n collection: uploadCollectionSlug,\n data: result.data,\n file: result.file,\n })\n\n console.log('assetData', assetData)\n\n return new Response(\n JSON.stringify({\n result: {\n id: assetData.id,\n alt: assetData.alt,\n },\n }),\n )\n },\n method: 'post',\n path: PLUGIN_API_ENDPOINT_GENERATE_UPLOAD,\n },\n}\n"],"names":["Handlebars","asyncHelpers","GenerationModels","defaultPrompts","PLUGIN_API_ENDPOINT_GENERATE","PLUGIN_API_ENDPOINT_GENERATE_UPLOAD","PLUGIN_INSTRUCTIONS_TABLE","getFieldBySchemaPath","lexicalToHTML","asyncHandlebars","replacePlaceholders","prompt","values","compile","trackIds","assignPrompt","action","type","actionParams","context","field","systemPrompt","template","toLexicalHTML","assignedPrompts","system","getSystemPrompt","find","p","name","registerEditorHelper","payload","schemaPath","fieldInfo","getFieldInfo","collections","schemaPathChunks","split","registerHelper","content","options","collectionSlug","ids","id","path","html","editor","editorConfig","SafeString","collectionsKey","collection","config","endpoints","textarea","handler","req","data","json","locale","instructionId","contextData","doc","instructions","findByID","promptTemplate","fieldName","pop","defaultLocale","locales","localization","localeData","l","code","localeInfo","label","opt","modelId","model","settingsName","settings","modelOptions","prompts","console","log","catch","error","Response","JSON","stringify","message","status","method","upload","uploadCollectionSlug","text","result","assetData","create","file","alt"],"mappings":"AAGA,OAAOA,gBAAgB,aAAY;AACnC,OAAOC,kBAAkB,2BAA0B;AAInD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,cAAc,QAAQ,mBAAkB;AACjD,SACEC,4BAA4B,EAC5BC,mCAAmC,EACnCC,yBAAyB,QACpB,iBAAgB;AACvB,SAASC,oBAAoB,QAAQ,uCAAsC;AAC3E,SAASC,aAAa,QAAQ,gCAA+B;AAE7D,MAAMC,kBAAkBR,aAAaD;AAErC,MAAMU,sBAAsB,CAACC,QAAgBC;IAC3C,OAAOH,gBAAgBI,OAAO,CAACF,QAAQ;QAAEG,UAAU;IAAK,GAAGF;AAC7D;AAEA,MAAMG,eAAe,OACnBC,QACA,EACEC,IAAI,EACJC,YAAY,EACZC,OAAO,EACPC,KAAK,EACLC,eAAe,EAAE,EACjBC,QAAQ,EAQT;IAED,MAAMX,SAAS,MAAMD,oBAAoBY,UAAUH;IAEnD,MAAMI,gBAAgBN,SAAS,aAAa,kBAAkB;IAE9D,MAAMO,kBAAkB;QACtBb;QACAc,QAAQJ;IACV;IAEA,IAAIL,WAAW,WAAW;QACxB,OAAOQ;IACT;IAEA,MAAM,EAAEC,QAAQC,eAAe,EAAE,GAAGvB,eAAewB,IAA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,OAAO,CAACkE,MAAM,CAAC;gBACzC/C,YAAY2C;gBACZrC,MAAMuC,OAAOvC,IAAI;gBACjB0C,MAAMH,OAAOG,IAAI;YACnB;YAEAhB,QAAQC,GAAG,CAAC,aAAaa;YAEzB,OAAO,IAAIV,SACTC,KAAKC,SAAS,CAAC;gBACbO,QAAQ;oBACNpD,IAAIqD,UAAUrD,EAAE;oBAChBwD,KAAKH,UAAUG,GAAG;gBACpB;YACF;QAEJ;QACAR,QAAQ;QACR/C,MAAMvC;IACR;AACF,EAAC"} \ No newline at end of file +{"version":3,"sources":["../../src/endpoints/index.ts"],"sourcesContent":["import type { SerializedEditorState } from 'lexical'\nimport type { BasePayload, PayloadRequest } from 'payload'\n\nimport Handlebars from 'handlebars'\nimport asyncHelpers from 'handlebars-async-helpers'\n\nimport type { ActionMenuItems, Endpoints } from '../types.js'\n\nimport { GenerationModels } from '../ai/models/index.js'\nimport { defaultPrompts } from '../ai/prompts.js'\nimport {\n PLUGIN_API_ENDPOINT_GENERATE,\n PLUGIN_API_ENDPOINT_GENERATE_UPLOAD,\n PLUGIN_INSTRUCTIONS_TABLE,\n} from '../defaults.js'\nimport { getFieldBySchemaPath } from '../utilities/getFieldBySchemaPath.js'\nimport { lexicalToHTML } from '../utilities/lexicalToHTML.js'\nimport { lexicalSchema } from '../ai/editor/lexical.schema.js'\n// import { DocumentSchema } from '../ai/editor/lexical.schema.js'\n\nconst asyncHandlebars = asyncHelpers(Handlebars)\n\nconst replacePlaceholders = (prompt: string, values: object) => {\n return asyncHandlebars.compile(prompt, { trackIds: true })(values)\n}\n\nconst assignPrompt = async (\n action: ActionMenuItems,\n {\n type,\n actionParams,\n context,\n field,\n systemPrompt = '',\n template,\n }: {\n actionParams: unknown\n context: object\n field: string\n systemPrompt: string\n template: string\n type: string\n },\n) => {\n const prompt = await replacePlaceholders(template, context)\n\n const toLexicalHTML = type === 'richText' ? 'toLexicalHTML' : ''\n\n const assignedPrompts = {\n prompt,\n system: systemPrompt,\n }\n\n if (action === 'Compose') {\n return assignedPrompts\n }\n\n const { system: getSystemPrompt } = defaultPrompts.find((p) => p.name === action)\n\n return {\n prompt: await replacePlaceholders(`{{${toLexicalHTML} ${field}}}`, context),\n system: getSystemPrompt(prompt, systemPrompt, (actionParams || '') as string),\n }\n}\n\nconst registerEditorHelper = (payload, schemaPath) => {\n //TODO: add autocomplete ability using handlebars template on PromptEditorField and include custom helpers in dropdown\n\n let fieldInfo = getFieldInfo(payload.collections, schemaPath)\n const schemaPathChunks = schemaPath.split('.')\n\n asyncHandlebars.registerHelper(\n 'toLexicalHTML',\n async function (content: SerializedEditorState, options) {\n const collectionSlug = schemaPathChunks[0]\n const { ids } = options\n for (const id of ids) {\n //TODO: Find a better to get schemaPath of defined field in prompt editor\n const path = `${collectionSlug}.${id}`\n fieldInfo = getFieldInfo(payload.collections, path)\n }\n\n const html = await lexicalToHTML(content, fieldInfo.editor?.editorConfig)\n return new asyncHandlebars.SafeString(html)\n },\n )\n}\n\nconst getFieldInfo = (collections: BasePayload['collections'], schemaPath: string) => {\n let fieldInfo = null\n //TODO: Only run below for enabled collections\n for (const collectionsKey in collections) {\n const collection = collections[collectionsKey]\n fieldInfo = getFieldBySchemaPath(collection.config, schemaPath)\n if (fieldInfo) {\n return fieldInfo\n }\n }\n}\n\nexport const endpoints: Endpoints = {\n textarea: {\n handler: async (req: PayloadRequest) => {\n const data = await req.json?.()\n\n const { locale = 'en', options } = data\n const { action, actionParams, instructionId } = options\n const contextData = data.doc\n\n let instructions = { 'model-id': '', prompt: '' }\n const { collections } = req.payload.config\n const collection = collections.find(\n (collection) => collection.slug === PLUGIN_INSTRUCTIONS_TABLE,\n )\n\n const { editorConfig: { schema: editorSchema = lexicalSchema() } = {} } =\n collection.custom || {}\n\n console.log('editorSchema : ', editorSchema)\n\n if (instructionId) {\n // @ts-expect-error\n instructions = await req.payload.findByID({\n id: instructionId,\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n })\n }\n\n const { prompt: promptTemplate = '' } = instructions\n\n const schemaPath = instructions['schema-path']\n const fieldName = schemaPath?.split('.').pop()\n\n registerEditorHelper(req.payload, schemaPath)\n\n const { defaultLocale, locales = [] } = req.payload.config.localization || {}\n const localeData = locales.find((l) => {\n return l.code === locale\n })\n\n const localeInfo = localeData?.label[defaultLocale] || locale\n\n //TODO: remove this\n const opt = {\n locale: localeInfo,\n modelId: instructions['model-id'],\n }\n\n const model = GenerationModels.find((model) => model.id === opt.modelId)\n const settingsName = model.settings?.name\n const modelOptions = instructions[settingsName] || {}\n\n const prompts = await assignPrompt(action, {\n type: instructions['field-type'],\n actionParams,\n context: contextData,\n field: fieldName,\n systemPrompt: modelOptions.system,\n template: promptTemplate,\n })\n\n console.log('Running handler with prompts:', prompts)\n return model\n .handler?.(prompts.prompt, {\n ...modelOptions,\n ...opt,\n system: prompts.system,\n editorSchema,\n })\n .catch((error) => {\n console.error('Error: endpoint - generating text:', error)\n return new Response(JSON.stringify(error.message), { status: 500 })\n })\n },\n method: 'post',\n path: PLUGIN_API_ENDPOINT_GENERATE,\n },\n upload: {\n handler: async (req: PayloadRequest) => {\n const data = await req.json?.()\n\n const { options } = data\n const { instructionId, uploadCollectionSlug } = options\n const contextData = data.doc\n\n let instructions = { 'model-id': '', prompt: '' }\n\n if (instructionId) {\n // @ts-expect-error\n instructions = await req.payload.findByID({\n id: instructionId,\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n })\n }\n\n const { prompt: promptTemplate = '' } = instructions\n const schemaPath = instructions['schema-path']\n\n registerEditorHelper(req.payload, schemaPath)\n\n const text = await replacePlaceholders(promptTemplate, contextData)\n const modelId = instructions['model-id']\n console.log('prompt text:', text)\n\n const model = GenerationModels.find((model) => model.id === modelId)\n const settingsName = model.settings?.name\n const modelOptions = instructions[settingsName] || {}\n console.log('modelOptions', modelOptions)\n\n const result = await model.handler?.(text, modelOptions)\n\n const assetData = await req.payload.create({\n collection: uploadCollectionSlug,\n data: result.data,\n file: result.file,\n })\n\n console.log('assetData', assetData)\n\n return new Response(\n JSON.stringify({\n result: {\n id: assetData.id,\n alt: assetData.alt,\n },\n }),\n )\n },\n method: 'post',\n path: PLUGIN_API_ENDPOINT_GENERATE_UPLOAD,\n },\n}\n"],"names":["Handlebars","asyncHelpers","GenerationModels","defaultPrompts","PLUGIN_API_ENDPOINT_GENERATE","PLUGIN_API_ENDPOINT_GENERATE_UPLOAD","PLUGIN_INSTRUCTIONS_TABLE","getFieldBySchemaPath","lexicalToHTML","lexicalSchema","asyncHandlebars","replacePlaceholders","prompt","values","compile","trackIds","assignPrompt","action","type","actionParams","context","field","systemPrompt","template","toLexicalHTML","assignedPrompts","system","getSystemPrompt","find","p","name","registerEditorHelper","payload","schemaPath","fieldInfo","getFieldInfo","collections","schemaPathChunks","split","registerHelper","content","options","collectionSlug","ids","id","path","html","editor","editorConfig","SafeString","collectionsKey","collection","config","endpoints","textarea","handler","req","data","json","locale","instructionId","contextData","doc","instructions","slug","schema","editorSchema","custom","console","log","findByID","promptTemplate","fieldName","pop","defaultLocale","locales","localization","localeData","l","code","localeInfo","label","opt","modelId","model","settingsName","settings","modelOptions","prompts","catch","error","Response","JSON","stringify","message","status","method","upload","uploadCollectionSlug","text","result","assetData","create","file","alt"],"mappings":"AAGA,OAAOA,gBAAgB,aAAY;AACnC,OAAOC,kBAAkB,2BAA0B;AAInD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,cAAc,QAAQ,mBAAkB;AACjD,SACEC,4BAA4B,EAC5BC,mCAAmC,EACnCC,yBAAyB,QACpB,iBAAgB;AACvB,SAASC,oBAAoB,QAAQ,uCAAsC;AAC3E,SAASC,aAAa,QAAQ,gCAA+B;AAC7D,SAASC,aAAa,QAAQ,iCAAgC;AAC9D,kEAAkE;AAElE,MAAMC,kBAAkBT,aAAaD;AAErC,MAAMW,sBAAsB,CAACC,QAAgBC;IAC3C,OAAOH,gBAAgBI,OAAO,CAACF,QAAQ;QAAEG,UAAU;IAAK,GAAGF;AAC7D;AAEA,MAA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ACnBG,eAAe,MAAMP,IAAIxB,OAAO,CAACsC,QAAQ,CAAC;oBACxC1B,IAAIgB;oBACJT,YAAY7C;gBACd;YACF;YAEA,MAAM,EAAEM,QAAQ2D,iBAAiB,EAAE,EAAE,GAAGR;YACxC,MAAM9B,aAAa8B,YAAY,CAAC,cAAc;YAE9ChC,qBAAqByB,IAAIxB,OAAO,EAAEC;YAElC,MAAMkE,OAAO,MAAMxF,oBAAoB4D,gBAAgBV;YACvD,MAAMsB,UAAUpB,YAAY,CAAC,WAAW;YACxCK,QAAQC,GAAG,CAAC,gBAAgB8B;YAE5B,MAAMf,QAAQlF,iBAAiB0B,IAAI,CAAC,CAACwD,QAAUA,MAAMxC,EAAE,KAAKuC;YAC5D,MAAME,eAAeD,MAAME,QAAQ,EAAExD;YACrC,MAAMyD,eAAexB,YAAY,CAACsB,aAAa,IAAI,CAAC;YACpDjB,QAAQC,GAAG,CAAC,gBAAgBkB;YAE5B,MAAMa,SAAS,MAAMhB,MAAM7B,OAAO,GAAG4C,MAAMZ;YAE3C,MAAMc,YAAY,MAAM7C,IAAIxB,OAAO,CAACsE,MAAM,CAAC;gBACzCnD,YAAY+C;gBACZzC,MAAM2C,OAAO3C,IAAI;gBACjB8C,MAAMH,OAAOG,IAAI;YACnB;YAEAnC,QAAQC,GAAG,CAAC,aAAagC;YAEzB,OAAO,IAAIV,SACTC,KAAKC,SAAS,CAAC;gBACbO,QAAQ;oBACNxD,IAAIyD,UAAUzD,EAAE;oBAChB4D,KAAKH,UAAUG,GAAG;gBACpB;YACF;QAEJ;QACAR,QAAQ;QACRnD,MAAMxC;IACR;AACF,EAAC"} \ No newline at end of file diff --git a/dist/fields/LexicalEditor/ActionsFeatureComponent.d.ts.map b/dist/fields/LexicalEditor/ActionsFeatureComponent.d.ts.map index bd74e9a..f92fb73 100644 --- a/dist/fields/LexicalEditor/ActionsFeatureComponent.d.ts.map +++ b/dist/fields/LexicalEditor/ActionsFeatureComponent.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"ActionsFeatureComponent.d.ts","sourceRoot":"","sources":["../../../src/fields/LexicalEditor/ActionsFeatureComponent.tsx"],"names":[],"mappings":"AAMA,eAAO,MAAM,uBAAuB,+CAQnC,CAAA"} \ No newline at end of file +{"version":3,"file":"ActionsFeatureComponent.d.ts","sourceRoot":"","sources":["../../../src/fields/LexicalEditor/ActionsFeatureComponent.tsx"],"names":[],"mappings":"AAKA,eAAO,MAAM,uBAAuB,+CAQnC,CAAA"} \ No newline at end of file diff --git a/dist/fields/LexicalEditor/ActionsFeatureComponent.js.map b/dist/fields/LexicalEditor/ActionsFeatureComponent.js.map index b081ac9..acb88b9 100644 --- a/dist/fields/LexicalEditor/ActionsFeatureComponent.js.map +++ b/dist/fields/LexicalEditor/ActionsFeatureComponent.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/fields/LexicalEditor/ActionsFeatureComponent.tsx"],"sourcesContent":["import { useEditorConfigContext } from '@payloadcms/richtext-lexical/client'\nimport { useFieldProps } from '@payloadcms/ui'\n\nimport { useInstructions } from '../../providers/InstructionsProvider/hook.js'\nimport { Actions } from '../../ui/Actions/Actions.js'\n\nexport const ActionsFeatureComponent = () => {\n const { schemaPath } = useFieldProps()\n\n const { id: instructionId } = useInstructions({\n path: schemaPath,\n })\n\n return \n}\n"],"names":["useFieldProps","useInstructions","Actions","ActionsFeatureComponent","schemaPath","id","instructionId","path"],"mappings":";AACA,SAASA,aAAa,QAAQ,iBAAgB;AAE9C,SAASC,eAAe,QAAQ,+CAA8C;AAC9E,SAASC,OAAO,QAAQ,8BAA6B;AAErD,OAAO,MAAMC,0BAA0B;IACrC,MAAM,EAAEC,UAAU,EAAE,GAAGJ;IAEvB,MAAM,EAAEK,IAAIC,aAAa,EAAE,GAAGL,gBAAgB;QAC5CM,MAAMH;IACR;IAEA,qBAAO,KAACF;QAAQI,eAAeA;;AACjC,EAAC"} \ No newline at end of file +{"version":3,"sources":["../../../src/fields/LexicalEditor/ActionsFeatureComponent.tsx"],"sourcesContent":["import { useFieldProps } from '@payloadcms/ui'\n\nimport { useInstructions } from '../../providers/InstructionsProvider/hook.js'\nimport { Actions } from '../../ui/Actions/Actions.js'\n\nexport const ActionsFeatureComponent = () => {\n const { schemaPath } = useFieldProps()\n\n const { id: instructionId } = useInstructions({\n path: schemaPath,\n })\n\n return \n}\n"],"names":["useFieldProps","useInstructions","Actions","ActionsFeatureComponent","schemaPath","id","instructionId","path"],"mappings":";AAAA,SAASA,aAAa,QAAQ,iBAAgB;AAE9C,SAASC,eAAe,QAAQ,+CAA8C;AAC9E,SAASC,OAAO,QAAQ,8BAA6B;AAErD,OAAO,MAAMC,0BAA0B;IACrC,MAAM,EAAEC,UAAU,EAAE,GAAGJ;IAEvB,MAAM,EAAEK,IAAIC,aAAa,EAAE,GAAGL,gBAAgB;QAC5CM,MAAMH;IACR;IAEA,qBAAO,KAACF;QAAQI,eAAeA;;AACjC,EAAC"} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts index 9c77705..c55d013 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -6,4 +6,5 @@ */ export { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js'; export { payloadAiPlugin } from './plugin.js'; +export { LexicalBaseNode } from './ai/editor/lexical.schema.js'; //# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/index.d.ts.map b/dist/index.d.ts.map index 4eba86c..446ab29 100644 --- a/dist/index.d.ts.map +++ b/dist/index.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,mCAAmC,EAAE,MAAM,0CAA0C,CAAA;AAC9F,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA"} \ No newline at end of file +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,mCAAmC,EAAE,MAAM,0CAA0C,CAAA;AAC9F,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAA"} \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index ba5e446..68114e0 100644 --- a/dist/index.js +++ b/dist/index.js @@ -5,5 +5,6 @@ * without appropriate licensing is prohibited. */ export { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js'; export { payloadAiPlugin } from './plugin.js'; +export { LexicalBaseNode } from './ai/editor/lexical.schema.js'; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map index ef2441b..86cb062 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @license This software is licensed under the MIT License. For commercial use,\n * redistribution, or embedding in proprietary systems, please refer to the\n * COMMERCIAL-LICENSE.md. Unauthorized commercial use or resale of modified versions\n * without appropriate licensing is prohibited.\n */\n\nexport { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js'\nexport { payloadAiPlugin } from './plugin.js'\n"],"names":["PayloadAiPluginLexicalEditorFeature","payloadAiPlugin"],"mappings":"AAAA;;;;;CAKC,GAED,SAASA,mCAAmC,QAAQ,2CAA0C;AAC9F,SAASC,eAAe,QAAQ,cAAa"} \ No newline at end of file +{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @license This software is licensed under the MIT License. For commercial use,\n * redistribution, or embedding in proprietary systems, please refer to the\n * COMMERCIAL-LICENSE.md. Unauthorized commercial use or resale of modified versions\n * without appropriate licensing is prohibited.\n */\n\nexport { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js'\nexport { payloadAiPlugin } from './plugin.js'\nexport { LexicalBaseNode } from './ai/editor/lexical.schema.js'\n"],"names":["PayloadAiPluginLexicalEditorFeature","payloadAiPlugin","LexicalBaseNode"],"mappings":"AAAA;;;;;CAKC,GAED,SAASA,mCAAmC,QAAQ,2CAA0C;AAC9F,SAASC,eAAe,QAAQ,cAAa;AAC7C,SAASC,eAAe,QAAQ,gCAA+B"} \ No newline at end of file diff --git a/dist/plugin.d.ts.map b/dist/plugin.d.ts.map index a155859..503d3a4 100644 --- a/dist/plugin.d.ts.map +++ b/dist/plugin.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAIrC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAU9C,QAAA,MAAM,eAAe,iBACJ,YAAY,sBACV,MAAM,KAAG,MA6DzB,CAAA;AAEH,OAAO,EAAE,eAAe,EAAE,CAAA"} \ No newline at end of file +{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAGrC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAa9C,QAAA,MAAM,eAAe,iBACJ,YAAY,sBACV,MAAM,KAAG,MAoFzB,CAAA;AAEH,OAAO,EAAE,eAAe,EAAE,CAAA"} \ No newline at end of file diff --git a/dist/plugin.js b/dist/plugin.js index 372219c..e4b83d7 100644 --- a/dist/plugin.js +++ b/dist/plugin.js @@ -1,12 +1,34 @@ import { deepMerge } from 'payload/shared'; import { Instructions } from './collections/Instructions.js'; -import { PLUGIN_INSTRUCTIONS_MAP_GLOBAL } from './defaults.js'; +import { PLUGIN_INSTRUCTIONS_MAP_GLOBAL, PLUGIN_NAME } from './defaults.js'; import { endpoints } from './endpoints/index.js'; import { init } from './init.js'; import { InstructionsProvider } from './providers/InstructionsProvider/index.js'; import { translations } from './translations/index.js'; import { updateFieldsConfig } from './utilities/updateFieldsConfig.js'; +import { lexicalSchema } from './ai/editor/lexical.schema.js'; +import { zodToJsonSchema } from 'zod-to-json-schema'; const payloadAiPlugin = (pluginConfig)=>(incomingConfig)=>{ + // Inject editor schema to config, so that it can be accessed when /textarea endpoint will hit + const zodLexicalSchema = lexicalSchema(pluginConfig.editorConfig?.nodes); + Instructions.admin.custom = { + ...Instructions.admin.custom || {}, + [PLUGIN_NAME]: { + editorConfig: { + // Used in admin client for useObject hook + schema: zodToJsonSchema(zodLexicalSchema) + } + } + }; + Instructions.custom = { + ...Instructions.custom || {}, + [PLUGIN_NAME]: { + editorConfig: { + // Used in textarea endpoint for llm + schema: zodLexicalSchema + } + } + }; const collections = [ ...incomingConfig.collections ?? [], Instructions diff --git a/dist/plugin.js.map b/dist/plugin.js.map index 232b696..9a222a5 100644 --- a/dist/plugin.js.map +++ b/dist/plugin.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/plugin.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport { deepMerge } from 'payload/shared'\n\nimport type { PluginConfig } from './types.js'\n\nimport { Instructions } from './collections/Instructions.js'\nimport { PLUGIN_INSTRUCTIONS_MAP_GLOBAL } from './defaults.js'\nimport { endpoints } from './endpoints/index.js'\nimport { init } from './init.js'\nimport { InstructionsProvider } from './providers/InstructionsProvider/index.js'\nimport { translations } from './translations/index.js'\nimport { updateFieldsConfig } from './utilities/updateFieldsConfig.js'\n\nconst payloadAiPlugin =\n (pluginConfig: PluginConfig) =>\n (incomingConfig: Config): Config => {\n const collections = [...(incomingConfig.collections ?? []), Instructions]\n const { collections: collectionSlugs = [] } = pluginConfig\n\n let collectionsFieldPathMap = {}\n\n incomingConfig.admin.components.providers = [\n ...(incomingConfig.admin.components.providers ?? []),\n InstructionsProvider,\n ]\n\n const updatedConfig: Config = {\n ...incomingConfig,\n collections: collections.map((collection) => {\n if (collectionSlugs.indexOf(collection.slug) > -1) {\n const { schemaPathMap, updatedCollectionConfig } = updateFieldsConfig(collection)\n collectionsFieldPathMap = {\n ...collectionsFieldPathMap,\n ...schemaPathMap,\n }\n return updatedCollectionConfig\n }\n\n return collection\n }),\n endpoints: [...(incomingConfig.endpoints ?? []), endpoints.textarea, endpoints.upload],\n globals: [\n ...incomingConfig.globals,\n {\n slug: PLUGIN_INSTRUCTIONS_MAP_GLOBAL,\n access: {\n read: () => true,\n },\n admin: {\n hidden: true,\n },\n fields: [\n {\n name: 'map',\n type: 'json',\n },\n ],\n },\n ],\n i18n: {\n ...incomingConfig.i18n,\n translations: {\n ...deepMerge(translations, incomingConfig.i18n?.translations),\n },\n },\n }\n\n updatedConfig.onInit = async (payload) => {\n if (incomingConfig.onInit) await incomingConfig.onInit(payload)\n\n await init(payload, collectionsFieldPathMap).catch((error) => {\n payload.logger.error(`— AI Plugin: Initialization Error: ${error}`)\n })\n }\n\n return updatedConfig\n }\n\nexport { payloadAiPlugin }\n"],"names":["deepMerge","Instructions","PLUGIN_INSTRUCTIONS_MAP_GLOBAL","endpoints","init","InstructionsProvider","translations","updateFieldsConfig","payloadAiPlugin","pluginConfig","incomingConfig","collections","collectionSlugs","collectionsFieldPathMap","admin","components","providers","updatedConfig","map","collection","indexOf","slug","schemaPathMap","updatedCollectionConfig","textarea","upload","globals","access","read","hidden","fields","name","type","i18n","onInit","payload","catch","error","logger"],"mappings":"AAEA,SAASA,SAAS,QAAQ,iBAAgB;AAI1C,SAASC,YAAY,QAAQ,gCAA+B;AAC5D,SAASC,8BAA8B,QAAQ,gBAAe;AAC9D,SAASC,SAAS,QAAQ,uBAAsB;AAChD,SAASC,IAAI,QAAQ,YAAW;AAChC,SAASC,oBAAoB,QAAQ,4CAA2C;AAChF,SAASC,YAAY,QAAQ,0BAAyB;AACtD,SAASC,kBAAkB,QAAQ,oCAAmC;AAEtE,MAAMC,kBACJ,CAACC,eACD,CAACC;QACC,MAAMC,cAAc;eAAKD,eAAeC,WAAW,IAAI,EAAE;YAAGV;SAAa;QACzE,MAAM,EAAEU,aAAaC,kBAAkB,EAAE,EAAE,GAAG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"],"sourcesContent":["import type { Config } from 'payload'\nimport { deepMerge } from 'payload/shared'\n\nimport type { PluginConfig } from './types.js'\n\nimport { Instructions } from './collections/Instructions.js'\nimport { PLUGIN_INSTRUCTIONS_MAP_GLOBAL, PLUGIN_NAME } from './defaults.js'\nimport { endpoints } from './endpoints/index.js'\nimport { init } from './init.js'\nimport { InstructionsProvider } from './providers/InstructionsProvider/index.js'\nimport { translations } from './translations/index.js'\nimport { updateFieldsConfig } from './utilities/updateFieldsConfig.js'\nimport { lexicalSchema } from './ai/editor/lexical.schema.js'\n\nimport { zodToJsonSchema } from 'zod-to-json-schema'\n\nconst payloadAiPlugin =\n (pluginConfig: PluginConfig) =>\n (incomingConfig: Config): Config => {\n // Inject editor schema to config, so that it can be accessed when /textarea endpoint will hit\n const zodLexicalSchema = lexicalSchema(pluginConfig.editorConfig?.nodes)\n\n Instructions.admin.custom = {\n ...(Instructions.admin.custom || {}),\n [PLUGIN_NAME]: {\n editorConfig: {\n // Used in admin client for useObject hook\n schema: zodToJsonSchema(zodLexicalSchema),\n },\n },\n }\n\n Instructions.custom = {\n ...(Instructions.custom || {}),\n [PLUGIN_NAME]: {\n editorConfig: {\n // Used in textarea endpoint for llm\n schema: zodLexicalSchema,\n },\n },\n }\n\n const collections = [...(incomingConfig.collections ?? []), Instructions]\n const { collections: collectionSlugs = [] } = pluginConfig\n\n let collectionsFieldPathMap = {}\n\n incomingConfig.admin.components.providers = [\n ...(incomingConfig.admin.components.providers ?? []),\n InstructionsProvider,\n ]\n\n const updatedConfig: Config = {\n ...incomingConfig,\n collections: collections.map((collection) => {\n if (collectionSlugs.indexOf(collection.slug) > -1) {\n const { schemaPathMap, updatedCollectionConfig } = updateFieldsConfig(collection)\n collectionsFieldPathMap = {\n ...collectionsFieldPathMap,\n ...schemaPathMap,\n }\n return updatedCollectionConfig\n }\n\n return collection\n }),\n endpoints: [...(incomingConfig.endpoints ?? []), endpoints.textarea, endpoints.upload],\n globals: [\n ...incomingConfig.globals,\n {\n slug: PLUGIN_INSTRUCTIONS_MAP_GLOBAL,\n access: {\n read: () => true,\n },\n admin: {\n hidden: true,\n },\n fields: [\n {\n name: 'map',\n type: 'json',\n },\n ],\n },\n ],\n i18n: {\n ...incomingConfig.i18n,\n translations: {\n ...deepMerge(translations, incomingConfig.i18n?.translations),\n },\n },\n }\n\n updatedConfig.onInit = async (payload) => {\n if (incomingConfig.onInit) await incomingConfig.onInit(payload)\n\n await init(payload, collectionsFieldPathMap).catch((error) => {\n payload.logger.error(`— AI Plugin: Initialization Error: ${error}`)\n })\n }\n\n return updatedConfig\n }\n\nexport { payloadAiPlugin }\n"],"names":["deepMerge","Instructions","PLUGIN_INSTRUCTIONS_MAP_GLOBAL","PLUGIN_NAME","endpoints","init","InstructionsProvider","translations","updateFieldsConfig","lexicalSchema","zodToJsonSchema","payloadAiPlugin","pluginConfig","incomingConfig","zodLexicalSchema","editorConfig","nodes","admin","custom","schema","collections","collectionSlugs","collectionsFieldPathMap","components","providers","updatedConfig","map","collection","indexOf","slug","schemaPathMap","updatedCollectionConfig","textarea","upload","globals","access","read","hidden","fields","name","type","i18n","onInit","payload","catch","error","logger"],"mappings":"AACA,SAASA,SAAS,QAAQ,iBAAgB;AAI1C,SAASC,YAAY,QAAQ,gCAA+B;AAC5D,SAASC,8BAA8B,EAAEC,WAAW,QAAQ,gBAAe;AAC3E,SAASC,SAAS,QAAQ,uBAAsB;AAChD,SAASC,IAAI,QAAQ,YAAW;AAChC,SAASC,oBAAoB,QAAQ,4CAA2C;AAChF,SAASC,YAAY,QAAQ,0BAAyB;AACtD,SAASC,kBAAkB,QAAQ,oCAAmC;AACtE,SAASC,aAAa,QAAQ,gCAA+B;AAE7D,SAASC,eAAe,QAAQ,qBAAoB;AAEpD,MAAMC,kBACJ,CAACC,eACD,CAACC;QACC,8FAA8F;QAC9F,MAAMC,mBAAmBL,cAAcG,aAAaG,YAAY,EAAEC;QAElEf,aAAagB,KAAK,CAACC,MAAM,GAAG;YAC1B,GAAIjB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G5B,eAAe4B,IAAI;gBACtBlC,cAAc;oBACZ,GAAGP,UAAUO,cAAcM,eAAe4B,IAAI,EAAElC,aAAa;gBAC/D;YACF;QACF;QAEAkB,cAAciB,MAAM,GAAG,OAAOC;YAC5B,IAAI9B,eAAe6B,MAAM,EAAE,MAAM7B,eAAe6B,MAAM,CAACC;YAEvD,MAAMtC,KAAKsC,SAASrB,yBAAyBsB,KAAK,CAAC,CAACC;gBAClDF,QAAQG,MAAM,CAACD,KAAK,CAAC,CAAC,mCAAmC,EAAEA,MAAM,CAAC;YACpE;QACF;QAEA,OAAOpB;IACT;AAEF,SAASd,eAAe,GAAE"} \ No newline at end of file diff --git a/dist/types.d.ts b/dist/types.d.ts index ae53440..64309c1 100644 --- a/dist/types.d.ts +++ b/dist/types.d.ts @@ -1,10 +1,14 @@ import type { Endpoint, Field, GroupField } from 'payload'; import { CSSProperties, MouseEventHandler } from 'react'; +import { LexicalBaseNode } from './ai/editor/lexical.schema.js'; export interface PluginConfig { collections?: string[]; fields?: Field[]; globals?: string[]; interfaceName?: string; + editorConfig?: { + nodes: (typeof LexicalBaseNode)[]; + }; } export interface GenerationModel { fields: string[]; diff --git a/dist/types.d.ts.map b/dist/types.d.ts.map index ec547c5..6aba7cc 100644 --- a/dist/types.d.ts.map +++ b/dist/types.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAC1D,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,OAAO,CAAA;AAExD,MAAM,WAAW,YAAY;IAC3B,WAAW,CAAC,EAAE,MAAM,EAAE,CAAA;IACtB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;IAClB,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAED,M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ACX,UAAU,GACV,aAAa,GACb,YAAY,GACZ,YAAY,GACZ,YAAY,GACZ,aAAa,GACb,QAAQ,GACR,aAAa,CAAA;AAEjB,MAAM,MAAM,aAAa,GAAG;KACzB,GAAG,IAAI,gBAAgB,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI;CACrD,CAAA;AAED,MAAM,MAAM,aAAa,CAAC,CAAC,GAAG,GAAG,IAAI;IACnC,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAA;IAC1B,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,OAAO,EAAE,CAAC,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAA;IACjC,YAAY,CAAC,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,SAAS,CAAA;IAC/C,YAAY,CAAC,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,SAAS,CAAA;IAC/C,KAAK,CAAC,EAAE,aAAa,GAAG,SAAS,CAAA;IACjC,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB,CAAA"} \ No newline at end of file diff --git a/dist/types.js.map b/dist/types.js.map index f1b0947..633f04a 100644 --- a/dist/types.js.map +++ b/dist/types.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { Endpoint, Field, GroupField } from 'payload'\nimport { CSSProperties, MouseEventHandler } from 'react'\n\nexport interface PluginConfig {\n collections?: string[]\n fields?: Field[]\n globals?: string[]\n interfaceName?: string\n}\n\nexport interface GenerationModel {\n fields: string[]\n handler?: (payload: any, options: any) => Promise\n id: string\n name: string\n output: 'audio' | 'file' | 'image' | 'json' | 'text' | 'video'\n settings?: GroupField\n supportsPromptOptimization?: boolean\n}\n\nexport interface GenerationConfig {\n models: GenerationModel[]\n provider: string\n}\n\nexport type GenerateTextarea = (args: {\n doc: T\n locale?: string\n options?: any\n}) => Promise | string\n\nexport interface Instructions {\n 'collection-slug': string\n id: string\n 'model-id': string\n prompt: string\n}\n\nexport interface Endpoints {\n textarea: Omit\n upload: Omit\n}\n\nexport type ActionMenuItems =\n | 'Compose'\n | 'Expand'\n | 'Proofread'\n | 'Rephrase'\n | 'Settings'\n | 'Simplify'\n | 'Summarize'\n | 'Tone'\n | 'Translate'\n\nexport type ActionMenuEvents =\n | 'onCompose'\n | 'onExpand'\n | 'onProofread'\n | 'onRephrase'\n | 'onSettings'\n | 'onSimplify'\n | 'onSummarize'\n | 'onTone'\n | 'onTranslate'\n\nexport type UseMenuEvents = {\n [key in ActionMenuEvents]?: (data?: unknown) => void\n}\n\nexport type BaseItemProps = {\n children?: React.ReactNode\n disabled?: boolean\n hideIcon?: boolean\n onClick: (data?: unknown) => void\n onMouseEnter?: MouseEventHandler | undefined\n onMouseLeave?: MouseEventHandler | undefined\n style?: CSSProperties | undefined\n isMenu?: boolean\n isActive?: boolean\n}\n"],"names":[],"mappings":"AAqEA,WAUC"} \ No newline at end of file +{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { Endpoint, Field, GroupField } from 'payload'\nimport { CSSProperties, MouseEventHandler } from 'react'\nimport { LexicalBaseNode } from './ai/editor/lexical.schema.js'\n\nexport interface PluginConfig {\n collections?: string[]\n fields?: Field[]\n globals?: string[]\n interfaceName?: string\n editorConfig?: { nodes: (typeof LexicalBaseNode)[] }\n}\n\nexport interface GenerationModel {\n fields: string[]\n handler?: (payload: any, options: any) => Promise\n id: string\n name: string\n output: 'audio' | 'file' | 'image' | 'json' | 'text' | 'video'\n settings?: GroupField\n supportsPromptOptimization?: boolean\n}\n\nexport interface GenerationConfig {\n models: GenerationModel[]\n provider: string\n}\n\nexport type GenerateTextarea = (args: {\n doc: T\n locale?: string\n options?: any\n}) => Promise | string\n\nexport interface Instructions {\n 'collection-slug': string\n id: string\n 'model-id': string\n prompt: string\n}\n\nexport interface Endpoints {\n textarea: Omit\n upload: Omit\n}\n\nexport type ActionMenuItems =\n | 'Compose'\n | 'Expand'\n | 'Proofread'\n | 'Rephrase'\n | 'Settings'\n | 'Simplify'\n | 'Summarize'\n | 'Tone'\n | 'Translate'\n\nexport type ActionMenuEvents =\n | 'onCompose'\n | 'onExpand'\n | 'onProofread'\n | 'onRephrase'\n | 'onSettings'\n | 'onSimplify'\n | 'onSummarize'\n | 'onTone'\n | 'onTranslate'\n\nexport type UseMenuEvents = {\n [key in ActionMenuEvents]?: (data?: unknown) => void\n}\n\nexport type BaseItemProps = {\n children?: React.ReactNode\n disabled?: boolean\n hideIcon?: boolean\n onClick: (data?: unknown) => void\n onMouseEnter?: MouseEventHandler | undefined\n onMouseLeave?: MouseEventHandler | undefined\n style?: CSSProperties | undefined\n isMenu?: boolean\n isActive?: boolean\n}\n"],"names":[],"mappings":"AAuEA,WAUC"} \ No newline at end of file diff --git a/dist/ui/Actions/Actions.d.ts.map b/dist/ui/Actions/Actions.d.ts.map index f05a3e2..d87c7ae 100644 --- a/dist/ui/Actions/Actions.d.ts.map +++ b/dist/ui/Actions/Actions.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"Actions.d.ts","sourceRoot":"","sources":["../../../src/ui/Actions/Actions.tsx"],"names":[],"mappings":"AA+BA,eAAO,MAAM,OAAO;;;6CAoInB,CAAA"} \ No newline at end of file +{"version":3,"file":"Actions.d.ts","sourceRoot":"","sources":["../../../src/ui/Actions/Actions.tsx"],"names":[],"mappings":"AA+BA,eAAO,MAAM,OAAO;;;6CA4InB,CAAA"} \ No newline at end of file diff --git a/dist/ui/Actions/Actions.js b/dist/ui/Actions/Actions.js index 540b004..f19b7be 100644 --- a/dist/ui/Actions/Actions.js +++ b/dist/ui/Actions/Actions.js @@ -56,8 +56,11 @@ export const Actions = ({ descriptionProps = {}, instructionId })=>{ actionsRef.current.classList.add(styles.actions_hidden); input.addEventListener('click', (event)=>{ document.querySelectorAll('.ai-plugin-active')?.forEach((element)=>{ - element.querySelector(`.${styles.actions}`).classList.add(styles.actions_hidden); - element.classList.remove('ai-plugin-active'); + const actionElement = element.querySelector(`.${styles.actions}`); + if (actionElement) { + actionElement.classList.add(styles.actions_hidden); + element.classList.remove('ai-plugin-active'); + } }); actionsRef.current.classList.remove(styles.actions_hidden); const parentWithClass = findParentWithClass(event.target, 'field-type'); @@ -112,9 +115,17 @@ export const Actions = ({ descriptionProps = {}, instructionId })=>{ }); } }); - const { setValue } = useField({ + const { setValue, value } = useField({ path: pathFromContext }); + useEffect(()=>{ + console.log('lexicalEditor :', value); + console.log('lexicalEditor :', { + setValue + }); + }, [ + value + ]); const setIfValueIsLexicalState = useCallback((val)=>{ if (val.root && lexicalEditor) { setSafeLexicalState(JSON.stringify(val), lexicalEditor); @@ -126,6 +137,7 @@ export const Actions = ({ descriptionProps = {}, instructionId })=>{ /*#__PURE__*/ _jsxs("label", { className: `${styles.actions}`, ref: actionsRef, + onClick: (e)=>e.preventDefault(), children: [ /*#__PURE__*/ _jsx(DocumentDrawer, { onSave: ()=>{ diff --git a/dist/ui/Actions/Actions.js.map b/dist/ui/Actions/Actions.js.map index cabc567..e402fb6 100644 --- a/dist/ui/Actions/Actions.js.map +++ b/dist/ui/Actions/Actions.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/ui/Actions/Actions.tsx"],"sourcesContent":["'use client'\n\nimport { FieldDescription, Popup, useDocumentDrawer, useField, useFieldProps } from '@payloadcms/ui'\nimport React, { useCallback, useEffect, useRef, useState } from 'react'\n\nimport { PLUGIN_INSTRUCTIONS_TABLE } from '../../defaults.js'\nimport { PluginIcon } from '../Icons/Icons.js'\nimport styles from './actions.module.scss'\nimport { useGenerate } from './hooks/useGenerate.js'\n\nimport { useMenu } from './hooks/menu/useMenu.js'\nimport { UndoRedoActions } from './UndoRedoActions.js'\nimport { useEditorConfigContext } from '@payloadcms/richtext-lexical/client'\nimport { setSafeLexicalState } from '../../utilities/setSafeLexicalState.js'\n\nfunction findParentWithClass(element, className) {\n // Base case: if the element is null or we've reached the top of the DOM\n if (!element || element === document.body) {\n return null\n }\n\n // Check if the current element has the class we're looking for\n if (element.classList.contains(className)) {\n return element\n }\n\n // Recursively call the function on the parent element\n return findParentWithClass(element.parentElement, className)\n}\n\n//TODO: Add undo/redo to the actions toolbar\nexport const Actions = ({ descriptionProps = {}, instructionId }) => {\n const [DocumentDrawer, _, { closeDrawer, openDrawer }] = useDocumentDrawer({\n id: instructionId,\n collectionSlug: PLUGIN_INSTRUCTIONS_TABLE,\n })\n\n const { type: fieldType, path: pathFromContext, schemaPath } = useFieldProps()\n const { editor: lexicalEditor, editorContainerRef } = useEditorConfigContext()\n\n // Below snippet is used to show/hide the actions menu on AI enabled fields\n const [input, setInput] = useState(null)\n const actionsRef = useRef(null)\n\n // Set input element for current field\n useEffect(() => {\n if (!actionsRef.current) return\n\n const fieldId = `field-${pathFromContext.replace(/\\./g, '__')}`\n let inputElement = document.getElementById(fieldId)\n\n if (!inputElement && fieldType === 'richText') {\n setInput(editorContainerRef.current)\n } else {\n actionsRef.current.setAttribute('for', fieldId)\n setInput(inputElement)\n }\n }, [pathFromContext, schemaPath, actionsRef, editorContainerRef])\n\n // Show or hide actions menu on field\n useEffect(() => {\n if (!input || !actionsRef.current) return\n\n actionsRef.current.classList.add(styles.actions_hidden)\n input.addEventListener('click', (event) => {\n document.querySelectorAll('.ai-plugin-active')?.forEach((element) => {\n element.querySelector(`.${styles.actions}`).classList.add(styles.actions_hidden)\n element.classList.remove('ai-plugin-active')\n })\n\n actionsRef.current.classList.remove(styles.actions_hidden)\n const parentWithClass = findParentWithClass(event.target, 'field-type')\n parentWithClass.classList.add('ai-plugin-active')\n })\n }, [input, actionsRef])\n\n const [isProcessing, setIsProcessing] = useState(false)\n const { generate, isLoading } = useGenerate()\n\n const { ActiveComponent, Menu } = useMenu({\n onCompose: async () => {\n console.log('Composing...')\n setIsProcessing(true)\n await generate({\n action: 'Compose',\n }).finally(() => {\n setIsProcessing(false)\n })\n },\n onExpand: async () => {\n console.log('Expanding...')\n await generate({\n action: 'Expand',\n })\n },\n onProofread: async () => {\n console.log('Proofreading...')\n await generate({\n action: 'Proofread',\n })\n },\n onRephrase: async () => {\n console.log('Rephrasing...')\n await generate({\n action: 'Rephrase',\n })\n },\n onSettings: openDrawer,\n onSimplify: async () => {\n console.log('Simplifying...')\n await generate({\n action: 'Simplify',\n })\n },\n onTranslate: async (data) => {\n console.log('Translate...', data)\n await generate({\n action: 'Translate',\n params: data,\n })\n },\n })\n\n const { setValue } = useField({\n path: pathFromContext,\n })\n\n const setIfValueIsLexicalState = useCallback((val) => {\n if (val.root && lexicalEditor) {\n setSafeLexicalState(JSON.stringify(val), lexicalEditor)\n }\n\n // DO NOT PROVIDE lexicalEditor as a dependency, it freaks out and does not update the editor after first undo/redo\n }, [])\n\n return (\n \n