@ai-stack/payloadcms 3.2.18-beta → 3.2.20-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +15 -0
  2. package/dist/ai/prompts.js +1 -1
  3. package/dist/ai/prompts.js.map +1 -1
  4. package/dist/collections/Instructions.d.ts +1 -1
  5. package/dist/collections/Instructions.js +18 -9
  6. package/dist/collections/Instructions.js.map +1 -1
  7. package/dist/endpoints/fetchFields.js +2 -0
  8. package/dist/endpoints/fetchFields.js.map +1 -1
  9. package/dist/endpoints/index.js +10 -6
  10. package/dist/endpoints/index.js.map +1 -1
  11. package/dist/exports/types.d.ts +1 -1
  12. package/dist/exports/types.js.map +1 -1
  13. package/dist/fields/ComposeField/ComposeField.js +23 -15
  14. package/dist/fields/ComposeField/ComposeField.js.map +1 -1
  15. package/dist/fields/LexicalEditor/ComposeFeatureComponent.d.ts +1 -1
  16. package/dist/fields/LexicalEditor/ComposeFeatureComponent.js +4 -1
  17. package/dist/fields/LexicalEditor/ComposeFeatureComponent.js.map +1 -1
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/init.js +61 -30
  22. package/dist/init.js.map +1 -1
  23. package/dist/plugin.js +3 -3
  24. package/dist/plugin.js.map +1 -1
  25. package/dist/providers/InstructionsProvider/InstructionsProvider.js +8 -4
  26. package/dist/providers/InstructionsProvider/InstructionsProvider.js.map +1 -1
  27. package/dist/providers/InstructionsProvider/context.d.ts +2 -0
  28. package/dist/providers/InstructionsProvider/context.js +2 -0
  29. package/dist/providers/InstructionsProvider/context.js.map +1 -1
  30. package/dist/providers/InstructionsProvider/useInstructions.js +15 -3
  31. package/dist/providers/InstructionsProvider/useInstructions.js.map +1 -1
  32. package/dist/types.d.ts +10 -3
  33. package/dist/types.js.map +1 -1
  34. package/dist/ui/Compose/Compose.js +21 -30
  35. package/dist/ui/Compose/Compose.js.map +1 -1
  36. package/dist/utilities/extractImageData.js +1 -1
  37. package/dist/utilities/extractImageData.js.map +1 -1
  38. package/package.json +1 -1
package/README.md CHANGED
@@ -201,6 +201,21 @@ export default buildConfig({
201
201
  }
202
202
  ],
203
203
 
204
+ // Optional: Control how field prompts are seeded for the first time
205
+ seedPrompts: ({path}) => {
206
+ if (path.endsWith('.meta.description')) {
207
+ return {
208
+ data: {
209
+ prompt: 'Generate SEO-friendly title for this document: {{markdown}}',
210
+ // other instruction options
211
+ }
212
+ }
213
+ }
214
+ // Don't allow generating slugs
215
+ if (path.endswith('.slug')) return false
216
+ // returning undefined fallbacks to default seed prompt
217
+ },
218
+
204
219
  // Optional: Custom media upload handling, useful for multi-tenant setups
205
220
  mediaUpload: async (result, { request, collection }) => {
206
221
  return request.payload.create({
@@ -198,7 +198,7 @@ For upload:
198
198
  field-type: upload
199
199
  field-name: Voice
200
200
  schema-path: posts.upload
201
- Generated prompt: {{ title }} {{ toHTML schema-path here... }}
201
+ Generated prompt: {{ title }} {{ toHTML [provide schema-path here...] }}
202
202
 
203
203
 
204
204
  Remember to adapt the prompts based on the specific schema-path provided, considering the context and purpose of the field within the CMS structure. The prompts should directly instruct the AI model on what content to generate or describe, without assuming a user perspective.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ai/prompts.ts"],"sourcesContent":["import type { ActionPrompt, SeedPromptFunction } from '../types.js'\n\n//TODO: This is a temporary solution make use of structured output\nexport const defaultSystemPrompt = `IMPORTANT INSTRUCTION:\nProduce only the requested output text.\nDo not add any explanations, comments, or engagement.\nDo not use quotation marks in the response.\nBEGIN OUTPUT:`\n\nexport const defaultPrompts: ActionPrompt[] = [\n {\n name: 'Rephrase',\n system: ({\n prompt = '',\n systemPrompt = '',\n }) => `You are a skilled language expert. Rephrase the given text while maintaining its original meaning, tone, and emotional content. Use different words and sentence structures where possible, but preserve the overall style and sentiment of the original.\n \n -------------\n INSTRUCTIONS:\n - Rephrase the text according to the guidelines of the ORIGINAL SYSTEM PROMPT, if provided.\n - Retain the original meaning, tone, and emotional content.\n - Use different vocabulary and sentence structures where appropriate.\n - Ensure the rephrased text conveys the same message and feeling as the original.\n ${prompt ? '\\n\\nPrevious prompt:\\n' + prompt : ''}\n ${systemPrompt ? '\\n\\nORIGINAL SYSTEM PROMPT:\\n' + systemPrompt : ''}\n -------------`,\n },\n {\n name: 'Expand',\n system:\n () => `You are a creative writer and subject matter expert. Expand the given text by adding depth, detail, and relevant information while maintaining the original tone and style.\n \n -------------\n INSTRUCTIONS:\n - Understand the main ideas and tone of the text.\n - Add more details, examples, explanations, or context.\n - Maintain the original tone, style, and intent.\n - Ensure the expanded version flows naturally and coherently.\n - Do not contradict or alter the original meaning.\n -------------`,\n },\n {\n name: 'Proofread',\n system:\n () => `You are an English language expert. Proofread the given text, focusing on correcting grammar and spelling mistakes without altering the content, style, or tone.\n \n -------------\n INSTRUCTIONS:\n - Correct grammar and spelling errors.\n - Do not change the content, meaning, tone, or style.\n - Return the full text, whether corrections were made or not.\n - Do not provide additional comments or analysis.\n -------------`,\n },\n {\n name: 'Simplify',\n system: ({\n prompt = '',\n }) => `You are a skilled communicator specializing in clear and concise writing. Simplify the given text to make it easier to understand while retaining its core message.\n \n -------------\n INSTRUCTIONS:\n - Simplify the language, using more common words and shorter sentences.\n - Remove unnecessary details or jargon while keeping essential information.\n - Maintain the original meaning and key points.\n - Aim for clarity and readability for a general audience.\n - The simplified text should be more concise than the original.\n ${prompt ? '\\n\\nPREVIOUS PROMPT:\\n' + prompt : ''}\n -------------`,\n },\n {\n name: 'Summarize',\n layout: () => `\n[heading] - Summary\n[paragraph] - Your summary goes here...\n `,\n system: () =>\n `You are an expert at summarizing information. Your task is to create a concise summary of the given text that captures its key points and essential details while preserving the original meaning.\n\nINSTRUCTIONS:\n1. Carefully read and analyze the provided text.\n2. Identify and extract the main ideas and crucial supporting details.\n3. Condense the information into a clear and coherent summary that maintains the core message.\n4. Preserve the original tone and intent of the text.\n5. Ensure your summary is approximately 25-30% of the original text length.\n6. Use clear and precise language, avoiding unnecessary jargon or complexity.\n`,\n },\n {\n name: 'Tone',\n system: () =>\n `You are a tone adjustment specialist. Modify the tone of the given text as specified while keeping the original message and content intact.\n \n -------------\n INSTRUCTIONS:\n - Adjust the tone to match the specified style (e.g., formal, informal, professional, friendly).\n - Maintain the original content and meaning.\n - Ensure the adjusted text flows naturally with the new tone.\n -------------`,\n },\n {\n name: 'Translate',\n system: ({ locale, prompt = '', systemPrompt = '' }) =>\n `You are a skilled translator. Translate the following text into ${locale}, ensuring the original meaning, tone, and context are preserved.\n \n -------------\n INSTRUCTIONS:\n - Accurately translate the text into ${locale}.\n - Preserve the original meaning, tone, and context.\n - Ensure the translation is culturally appropriate and natural in the target language.\n ${prompt ? '\\n\\nPREVIOUS PROMPT:\\n' + prompt : ''}\n ${systemPrompt ? '\\n\\nORIGINAL SYSTEM PROMPT:\\n' + systemPrompt : ''}\n -------------`,\n },\n]\n\nexport const defaultSeedPrompts: SeedPromptFunction = ({\n fieldLabel,\n fieldSchemaPaths,\n fieldType,\n path,\n}: {\n fieldLabel: string\n fieldSchemaPaths: any\n fieldType: string\n path: string\n}) => {\n return {\n prompt: `field-type: ${fieldType}\nfield-name: ${fieldLabel}\nschema-path: ${path}\n\nGive me a prompt that relate to the given field type and schema path.\n\nGenerated prompt:\n`,\n system: `# AI Assistant for CMS Prompt Generation\n\nYour role: Generate prompts for Content Management System (CMS) fields based on field-type and schema-path.\n\n## Key Guidelines:\n- Tailor prompts to specific field-type and purpose\n- Use schema-path for context\n- Include \" {{ title }} \" in every prompt\n- Be clear, concise, and instructive\n- Focus on content generation, not user perspective\n- For Image, Voice, or Banner fields, use provided example prompts verbatim\n- Image, Banner prompt MUST NOT CONTAIN ANY TYPOGRAPHY/TEXT DETAILS\n\n## Field Types and Prompts:\n\n1. richText:\n - Craft detailed, structured content\n - Include intro, sections, body, formatting, and conclusion\n - Aim for engaging, informative, and valuable content\n\n2. text:\n - For titles: Generate concise, engaging titles\n - For keywords: List relevant SEO terms\n\n3. textarea:\n - Provide comprehensive details (e.g., event information)\n\n4. upload:\n - Describe high-quality images or media\n\n## Schema-path Examples:\n- posts.title: Blog/article title\n- products.name: Product name\n\n## Must Follow:\n- Adapt prompts to schema-path context\n- Generate content directly, avoid personal pronouns\n- Use provided examples as guidelines\n\n### Examples for each field type along with generated prompt:\n\nFor richText:\n field-type: richText\n field-name: Content\n schema-path: posts.content\n Generated prompt: Craft compelling content for a blog post with the title \" {{ title }} \". Develop a well-structured narrative that captivates readers from start to finish. Incorporate the following elements to create a polished and engaging piece:\n\n- Engaging introduction that hooks the reader\n- Clearly defined sections with relevant subheadings\n- Well-researched and informative body paragraphs\n- Creative use of formatting to enhance readability (e.g., bullet points, blockquotes, italics, headings, bolds, other text formats)\n- Compelling conclusion that reinforces the main theme\n- Make the format easily digestible and clear for enhanced readability and improved CTR. \n- The user should be engaged, consistently interested, and feel that they’ve gained the knowledge they were seeking. \n\nInfuse the content with your expertise and a touch of personality to make it both informative and enjoyable to read. Aim to provide value to your target audience while maintaining a professional tone that aligns with the blog's overall style.\nFeel free to incorporate relevant anecdotes, statistics, or examples to support your points and add depth to the post. Remember, the goal is to create content that not only informs but also inspires and entertains your readers.\n\nFor text:\n field-type: text\n field-name: title\n schema-path: posts.title\n Generated prompt: Generate a captivating title for the blog post based on \" {{ title }} \" that effectively encapsulates the main theme and draws in readers. The title should be concise, engaging, and relevant to the content being presented. If no input is provided then generate creative title.\n\nFor text:\n field-type: text\n field-name: keywords\n schema-path: posts.keywords\n Generated prompt: Identify and list relevant keywords for the blog post titled \" {{ title }} \". Focus on terms that enhance search engine optimization and accurately reflect the main themes and topics of the content.\nkeywords will with comma separated.\n\n\nFor textarea:\n field-type: textarea:\n field-name: details\n schema-path: posts.details\n Generated prompt: Provide comprehensive details for the event \" {{ title }} \". Include essential information such as date, time, location, and any specific instructions or requirements.\n\nFor upload:\n field-type: upload\n field-name: Featured Image\n schema-path: posts.image\n Generated prompt: Imagine {{ title }}\n\nFor upload:\n field-type: upload\n field-name: Voice\n schema-path: posts.upload\n Generated prompt: {{ title }} {{ toHTML schema-path here... }}\n\n\nRemember to adapt the prompts based on the specific schema-path provided, considering the context and purpose of the field within the CMS structure. The prompts should directly instruct the AI model on what content to generate or describe, without assuming a user perspective.\n\nSchema Map Context:\n${JSON.stringify(fieldSchemaPaths)}\n\n${defaultSystemPrompt}\n`,\n }\n}\n"],"names":["defaultSystemPrompt","defaultPrompts","name","system","prompt","systemPrompt","layout","locale","defaultSeedPrompts","fieldLabel","fieldSchemaPaths","fieldType","path","JSON","stringify"],"mappings":"AAEA,kEAAkE;AAClE,OAAO,MAAMA,sBAAsB,CAAC;;;;aAIvB,CAAC,CAAA;AAEd,OAAO,MAAMC,iBAAiC;IAC5C;QACEC,MAAM;QACNC,QAAQ,CAAC,EACPC,SAAS,EAAE,EACXC,eAAe,EAAE,EAClB,GAAK,CAAC;;;;;;;;MAQL,EAAED,SAAS,2BAA2BA,SAAS,GAAG;MAClD,EAAEC,eAAe,kCAAkCA,eAAe,GAAG;mBACxD,CAAC;IAClB;IACA;QACEH,MAAM;QACNC,QACE,IAAM,CAAC;;;;;;;;;mBASM,CAAC;IAClB;IACA;QACED,MAAM;QACNC,QACE,IAAM,CAAC;;;;;;;;mBAQM,CAAC;IAClB;IACA;QACED,MAAM;QACNC,QAAQ,CAAC,EACPC,SAAS,EAAE,EACZ,GAAK,CAAC;;;;;;;;;MASL,EAAEA,SAAS,2BAA2BA,SAAS,GAAG;mBACrC,CAAC;IAClB;IACA;QACEF,MAAM;QACNI,QAAQ,IAAM,CAAC;;;IAGf,CAAC;QACDH,QAAQ,IACN,CAAC;;;;;;;;;AASP,CAAC;IACC;IACA;QACED,MAAM;QACNC,QAAQ,IACN,CAAC;;;;;;;mBAOY,CAAC;IAClB;IACA;QACED,MAAM;QACNC,QAAQ,CAAC,EAAEI,MAAM,EAAEH,SAAS,EAAE,EAAEC,eAAe,EAAE,EAAE,GACjD,CAAC,gEAAgE,EAAEE,OAAO;;;;yCAIvC,EAAEA,OAAO;;;IAG9C,EAAEH,SAAS,2BAA2BA,SAAS,GAAG;IAClD,EAAEC,eAAe,kCAAkCA,eAAe,GAAG;iBACxD,CAAC;IAChB;CACD,CAAA;AAED,OAAO,MAAMG,qBAAyC,CAAC,EACrDC,UAAU,EACVC,gBAAgB,EAChBC,SAAS,EACTC,IAAI,EAML;IACC,OAAO;QACLR,QAAQ,CAAC,YAAY,EAAEO,UAAU;YACzB,EAAEF,WAAW;aACZ,EAAEG,KAAK;;;;;AAKpB,CAAC;QACGT,QAAQ,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8Fb,EAAEU,KAAKC,SAAS,CAACJ,kBAAkB;;AAEnC,EAAEV,oBAAoB;AACtB,CAAC;IACC;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/ai/prompts.ts"],"sourcesContent":["import type { ActionPrompt, SeedPromptFunction } from '../types.js'\n\n//TODO: This is a temporary solution make use of structured output\nexport const defaultSystemPrompt = `IMPORTANT INSTRUCTION:\nProduce only the requested output text.\nDo not add any explanations, comments, or engagement.\nDo not use quotation marks in the response.\nBEGIN OUTPUT:`\n\nexport const defaultPrompts: ActionPrompt[] = [\n {\n name: 'Rephrase',\n system: ({\n prompt = '',\n systemPrompt = '',\n }) => `You are a skilled language expert. Rephrase the given text while maintaining its original meaning, tone, and emotional content. Use different words and sentence structures where possible, but preserve the overall style and sentiment of the original.\n \n -------------\n INSTRUCTIONS:\n - Rephrase the text according to the guidelines of the ORIGINAL SYSTEM PROMPT, if provided.\n - Retain the original meaning, tone, and emotional content.\n - Use different vocabulary and sentence structures where appropriate.\n - Ensure the rephrased text conveys the same message and feeling as the original.\n ${prompt ? '\\n\\nPrevious prompt:\\n' + prompt : ''}\n ${systemPrompt ? '\\n\\nORIGINAL SYSTEM PROMPT:\\n' + systemPrompt : ''}\n -------------`,\n },\n {\n name: 'Expand',\n system:\n () => `You are a creative writer and subject matter expert. Expand the given text by adding depth, detail, and relevant information while maintaining the original tone and style.\n \n -------------\n INSTRUCTIONS:\n - Understand the main ideas and tone of the text.\n - Add more details, examples, explanations, or context.\n - Maintain the original tone, style, and intent.\n - Ensure the expanded version flows naturally and coherently.\n - Do not contradict or alter the original meaning.\n -------------`,\n },\n {\n name: 'Proofread',\n system:\n () => `You are an English language expert. Proofread the given text, focusing on correcting grammar and spelling mistakes without altering the content, style, or tone.\n \n -------------\n INSTRUCTIONS:\n - Correct grammar and spelling errors.\n - Do not change the content, meaning, tone, or style.\n - Return the full text, whether corrections were made or not.\n - Do not provide additional comments or analysis.\n -------------`,\n },\n {\n name: 'Simplify',\n system: ({\n prompt = '',\n }) => `You are a skilled communicator specializing in clear and concise writing. Simplify the given text to make it easier to understand while retaining its core message.\n \n -------------\n INSTRUCTIONS:\n - Simplify the language, using more common words and shorter sentences.\n - Remove unnecessary details or jargon while keeping essential information.\n - Maintain the original meaning and key points.\n - Aim for clarity and readability for a general audience.\n - The simplified text should be more concise than the original.\n ${prompt ? '\\n\\nPREVIOUS PROMPT:\\n' + prompt : ''}\n -------------`,\n },\n {\n name: 'Summarize',\n layout: () => `\n[heading] - Summary\n[paragraph] - Your summary goes here...\n `,\n system: () =>\n `You are an expert at summarizing information. Your task is to create a concise summary of the given text that captures its key points and essential details while preserving the original meaning.\n\nINSTRUCTIONS:\n1. Carefully read and analyze the provided text.\n2. Identify and extract the main ideas and crucial supporting details.\n3. Condense the information into a clear and coherent summary that maintains the core message.\n4. Preserve the original tone and intent of the text.\n5. Ensure your summary is approximately 25-30% of the original text length.\n6. Use clear and precise language, avoiding unnecessary jargon or complexity.\n`,\n },\n {\n name: 'Tone',\n system: () =>\n `You are a tone adjustment specialist. Modify the tone of the given text as specified while keeping the original message and content intact.\n \n -------------\n INSTRUCTIONS:\n - Adjust the tone to match the specified style (e.g., formal, informal, professional, friendly).\n - Maintain the original content and meaning.\n - Ensure the adjusted text flows naturally with the new tone.\n -------------`,\n },\n {\n name: 'Translate',\n system: ({ locale, prompt = '', systemPrompt = '' }) =>\n `You are a skilled translator. Translate the following text into ${locale}, ensuring the original meaning, tone, and context are preserved.\n \n -------------\n INSTRUCTIONS:\n - Accurately translate the text into ${locale}.\n - Preserve the original meaning, tone, and context.\n - Ensure the translation is culturally appropriate and natural in the target language.\n ${prompt ? '\\n\\nPREVIOUS PROMPT:\\n' + prompt : ''}\n ${systemPrompt ? '\\n\\nORIGINAL SYSTEM PROMPT:\\n' + systemPrompt : ''}\n -------------`,\n },\n]\n\nexport const defaultSeedPrompts: SeedPromptFunction = ({\n fieldLabel,\n fieldSchemaPaths,\n fieldType,\n path,\n}: {\n fieldLabel: string\n fieldSchemaPaths: any\n fieldType: string\n path: string\n}) => {\n return {\n prompt: `field-type: ${fieldType}\nfield-name: ${fieldLabel}\nschema-path: ${path}\n\nGive me a prompt that relate to the given field type and schema path.\n\nGenerated prompt:\n`,\n system: `# AI Assistant for CMS Prompt Generation\n\nYour role: Generate prompts for Content Management System (CMS) fields based on field-type and schema-path.\n\n## Key Guidelines:\n- Tailor prompts to specific field-type and purpose\n- Use schema-path for context\n- Include \" {{ title }} \" in every prompt\n- Be clear, concise, and instructive\n- Focus on content generation, not user perspective\n- For Image, Voice, or Banner fields, use provided example prompts verbatim\n- Image, Banner prompt MUST NOT CONTAIN ANY TYPOGRAPHY/TEXT DETAILS\n\n## Field Types and Prompts:\n\n1. richText:\n - Craft detailed, structured content\n - Include intro, sections, body, formatting, and conclusion\n - Aim for engaging, informative, and valuable content\n\n2. text:\n - For titles: Generate concise, engaging titles\n - For keywords: List relevant SEO terms\n\n3. textarea:\n - Provide comprehensive details (e.g., event information)\n\n4. upload:\n - Describe high-quality images or media\n\n## Schema-path Examples:\n- posts.title: Blog/article title\n- products.name: Product name\n\n## Must Follow:\n- Adapt prompts to schema-path context\n- Generate content directly, avoid personal pronouns\n- Use provided examples as guidelines\n\n### Examples for each field type along with generated prompt:\n\nFor richText:\n field-type: richText\n field-name: Content\n schema-path: posts.content\n Generated prompt: Craft compelling content for a blog post with the title \" {{ title }} \". Develop a well-structured narrative that captivates readers from start to finish. Incorporate the following elements to create a polished and engaging piece:\n\n- Engaging introduction that hooks the reader\n- Clearly defined sections with relevant subheadings\n- Well-researched and informative body paragraphs\n- Creative use of formatting to enhance readability (e.g., bullet points, blockquotes, italics, headings, bolds, other text formats)\n- Compelling conclusion that reinforces the main theme\n- Make the format easily digestible and clear for enhanced readability and improved CTR. \n- The user should be engaged, consistently interested, and feel that they’ve gained the knowledge they were seeking. \n\nInfuse the content with your expertise and a touch of personality to make it both informative and enjoyable to read. Aim to provide value to your target audience while maintaining a professional tone that aligns with the blog's overall style.\nFeel free to incorporate relevant anecdotes, statistics, or examples to support your points and add depth to the post. Remember, the goal is to create content that not only informs but also inspires and entertains your readers.\n\nFor text:\n field-type: text\n field-name: title\n schema-path: posts.title\n Generated prompt: Generate a captivating title for the blog post based on \" {{ title }} \" that effectively encapsulates the main theme and draws in readers. The title should be concise, engaging, and relevant to the content being presented. If no input is provided then generate creative title.\n\nFor text:\n field-type: text\n field-name: keywords\n schema-path: posts.keywords\n Generated prompt: Identify and list relevant keywords for the blog post titled \" {{ title }} \". Focus on terms that enhance search engine optimization and accurately reflect the main themes and topics of the content.\nkeywords will with comma separated.\n\n\nFor textarea:\n field-type: textarea:\n field-name: details\n schema-path: posts.details\n Generated prompt: Provide comprehensive details for the event \" {{ title }} \". Include essential information such as date, time, location, and any specific instructions or requirements.\n\nFor upload:\n field-type: upload\n field-name: Featured Image\n schema-path: posts.image\n Generated prompt: Imagine {{ title }}\n\nFor upload:\n field-type: upload\n field-name: Voice\n schema-path: posts.upload\n Generated prompt: {{ title }} {{ toHTML [provide schema-path here...] }}\n\n\nRemember to adapt the prompts based on the specific schema-path provided, considering the context and purpose of the field within the CMS structure. The prompts should directly instruct the AI model on what content to generate or describe, without assuming a user perspective.\n\nSchema Map Context:\n${JSON.stringify(fieldSchemaPaths)}\n\n${defaultSystemPrompt}\n`,\n }\n}\n"],"names":["defaultSystemPrompt","defaultPrompts","name","system","prompt","systemPrompt","layout","locale","defaultSeedPrompts","fieldLabel","fieldSchemaPaths","fieldType","path","JSON","stringify"],"mappings":"AAEA,kEAAkE;AAClE,OAAO,MAAMA,sBAAsB,CAAC;;;;aAIvB,CAAC,CAAA;AAEd,OAAO,MAAMC,iBAAiC;IAC5C;QACEC,MAAM;QACNC,QAAQ,CAAC,EACPC,SAAS,EAAE,EACXC,eAAe,EAAE,EAClB,GAAK,CAAC;;;;;;;;MAQL,EAAED,SAAS,2BAA2BA,SAAS,GAAG;MAClD,EAAEC,eAAe,kCAAkCA,eAAe,GAAG;mBACxD,CAAC;IAClB;IACA;QACEH,MAAM;QACNC,QACE,IAAM,CAAC;;;;;;;;;mBASM,CAAC;IAClB;IACA;QACED,MAAM;QACNC,QACE,IAAM,CAAC;;;;;;;;mBAQM,CAAC;IAClB;IACA;QACED,MAAM;QACNC,QAAQ,CAAC,EACPC,SAAS,EAAE,EACZ,GAAK,CAAC;;;;;;;;;MASL,EAAEA,SAAS,2BAA2BA,SAAS,GAAG;mBACrC,CAAC;IAClB;IACA;QACEF,MAAM;QACNI,QAAQ,IAAM,CAAC;;;IAGf,CAAC;QACDH,QAAQ,IACN,CAAC;;;;;;;;;AASP,CAAC;IACC;IACA;QACED,MAAM;QACNC,QAAQ,IACN,CAAC;;;;;;;mBAOY,CAAC;IAClB;IACA;QACED,MAAM;QACNC,QAAQ,CAAC,EAAEI,MAAM,EAAEH,SAAS,EAAE,EAAEC,eAAe,EAAE,EAAE,GACjD,CAAC,gEAAgE,EAAEE,OAAO;;;;yCAIvC,EAAEA,OAAO;;;IAG9C,EAAEH,SAAS,2BAA2BA,SAAS,GAAG;IAClD,EAAEC,eAAe,kCAAkCA,eAAe,GAAG;iBACxD,CAAC;IAChB;CACD,CAAA;AAED,OAAO,MAAMG,qBAAyC,CAAC,EACrDC,UAAU,EACVC,gBAAgB,EAChBC,SAAS,EACTC,IAAI,EAML;IACC,OAAO;QACLR,QAAQ,CAAC,YAAY,EAAEO,UAAU;YACzB,EAAEF,WAAW;aACZ,EAAEG,KAAK;;;;;AAKpB,CAAC;QACGT,QAAQ,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8Fb,EAAEU,KAAKC,SAAS,CAACJ,kBAAkB;;AAEnC,EAAEV,oBAAoB;AACtB,CAAC;IACC;AACF,EAAC"}
@@ -1,3 +1,3 @@
1
1
  import type { CollectionConfig } from 'payload';
2
2
  import type { PluginConfig } from 'src/types.js';
3
- export declare const instructionsCollection: (pluginConfig: PluginConfig, options?: Partial<CollectionConfig>) => CollectionConfig;
3
+ export declare const instructionsCollection: (pluginConfig: PluginConfig) => CollectionConfig;
@@ -43,16 +43,20 @@ const defaultAdminConfig = {
43
43
  group: 'Plugins',
44
44
  hidden: true
45
45
  };
46
- export const instructionsCollection = (pluginConfig, options)=>({
46
+ export const instructionsCollection = (pluginConfig)=>({
47
+ labels: {
48
+ plural: 'Compose Settings',
49
+ singular: 'Compose Setting'
50
+ },
51
+ ...pluginConfig.overrideInstructions,
47
52
  slug: PLUGIN_INSTRUCTIONS_TABLE,
48
53
  access: {
49
54
  ...defaultAccessConfig,
50
- ...options?.access
55
+ ...pluginConfig.overrideInstructions?.access
51
56
  },
52
57
  admin: {
53
58
  ...defaultAdminConfig,
54
- ...options?.admin,
55
- group: 'Plugins'
59
+ ...pluginConfig.overrideInstructions?.admin
56
60
  },
57
61
  fields: [
58
62
  {
@@ -122,6 +126,15 @@ export const instructionsCollection = (pluginConfig, options)=>({
122
126
  };
123
127
  })
124
128
  },
129
+ {
130
+ name: 'disabled',
131
+ type: 'checkbox',
132
+ admin: {
133
+ description: 'Please reload your collection after applying the changes'
134
+ },
135
+ defaultValue: false,
136
+ label: 'Hide Compose button for this field'
137
+ },
125
138
  {
126
139
  id: 'ai-prompts-tabs',
127
140
  type: 'tabs',
@@ -229,11 +242,7 @@ informative and accurate but also captivating and beautifully structured.`,
229
242
  ]
230
243
  },
231
244
  ...groupSettings(pluginConfig)
232
- ],
233
- labels: {
234
- plural: 'Compose Settings',
235
- singular: 'Compose Setting'
236
- }
245
+ ]
237
246
  });
238
247
 
239
248
  //# sourceMappingURL=Instructions.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/collections/Instructions.ts"],"sourcesContent":["import type { CollectionConfig, GroupField } from 'payload'\nimport type { PluginConfig } from 'src/types.js'\n\nimport { PLUGIN_INSTRUCTIONS_TABLE } from '../defaults.js'\nimport { getGenerationModels } from '../utilities/getGenerationModels.js'\n\nconst groupSettings = (pluginConfig: PluginConfig) =>\n (getGenerationModels(pluginConfig) ?? []).reduce((fields, model) => {\n if (model.settings) {\n fields.push(model.settings)\n }\n return fields\n }, [] as GroupField[])\n\nconst modelOptions = (pluginConfig: PluginConfig) =>\n (getGenerationModels(pluginConfig) ?? []).map((model) => {\n return {\n fields: model.fields,\n label: model.name,\n value: model.id,\n }\n })\n\nconst defaultAccessConfig = {\n create: ({ req }: { req: { user?: any } }) => {\n if (!req.user) {\n return false\n }\n return true\n },\n delete: ({ req }: { req: { user?: any } }) => {\n if (!req.user) {\n return false\n }\n return true\n },\n read: ({ req }: { req: { user?: any } }) => {\n if (!req.user) {\n return false\n }\n return true\n },\n update: ({ req }: { req: { user?: any } }) => {\n if (!req.user) {\n return false\n }\n return true\n },\n}\n\nconst defaultAdminConfig = {\n group: 'Plugins',\n hidden: true,\n}\n\nexport const instructionsCollection = (\n pluginConfig: PluginConfig,\n options?: Partial<CollectionConfig>,\n) =>\n <CollectionConfig>{\n slug: PLUGIN_INSTRUCTIONS_TABLE,\n access: {\n ...defaultAccessConfig,\n ...options?.access,\n },\n admin: {\n ...defaultAdminConfig,\n ...options?.admin,\n group: 'Plugins',\n },\n fields: [\n {\n name: 'schema-path',\n type: 'text',\n admin: {\n description: \"Please don't change this unless you're sure of what you're doing\",\n },\n unique: true,\n },\n {\n name: 'field-type',\n type: 'select',\n admin: {\n description: \"Please don't change this unless you're sure of what you're doing\",\n },\n defaultValue: 'text',\n label: 'Field type',\n options: [\n {\n label: 'text',\n value: 'text',\n },\n {\n label: 'textarea',\n value: 'textarea',\n },\n {\n label: 'upload',\n value: 'upload',\n },\n {\n label: 'richText',\n value: 'richText',\n },\n ],\n },\n {\n name: 'relation-to',\n type: 'text',\n admin: {\n condition: (_, current) => {\n return current['field-type'] === 'upload'\n },\n },\n label: 'Relation to',\n },\n {\n name: 'model-id',\n type: 'select',\n admin: {\n components: {\n Field: {\n clientProps: {\n filterByField: 'field-type',\n options: modelOptions(pluginConfig),\n },\n path: '@ai-stack/payloadcms/fields#SelectField',\n },\n },\n },\n label: 'Model',\n options: modelOptions(pluginConfig).map((option) => {\n return {\n label: option.label,\n value: option.value,\n }\n }),\n },\n {\n id: 'ai-prompts-tabs',\n type: 'tabs',\n tabs: [\n {\n description:\n 'Define dynamic templates using {{ fieldName }}. Type { to see available field suggestions.',\n fields: [\n {\n name: 'prompt',\n type: 'textarea',\n admin: {\n components: {\n Field: '@ai-stack/payloadcms/fields#PromptEditorField',\n },\n description: \"Click 'Compose' to run this custom prompt and generate content\",\n },\n label: '',\n },\n ],\n label: 'Prompt',\n },\n {\n admin: {\n condition: (_, current) => {\n return current['field-type'] === 'upload' && current['model-id'] === 'gpt-image-1'\n },\n },\n description:\n 'These images will be used to generate new visuals in a similar style, layout, or content. You can combine multiple references for more controlled results.',\n fields: [\n {\n name: 'images',\n type: 'array',\n fields: [\n {\n name: 'image',\n type: 'upload',\n admin: {\n description: 'Please make sure the image is publicly accessible.',\n },\n relationTo: pluginConfig.uploadCollectionSlug\n ? pluginConfig.uploadCollectionSlug\n : 'media',\n },\n ],\n },\n ],\n label: 'Sample Images',\n },\n {\n admin: {\n condition: (_, current) => {\n return current['field-type'] === 'richText'\n },\n },\n description: '',\n fields: [\n {\n name: 'system',\n type: 'textarea',\n defaultValue: `INSTRUCTIONS:\nYou are a highly skilled and professional blog writer,\nrenowned for crafting engaging and well-organized articles.\nWhen given a title, you meticulously create blogs that are not only\ninformative and accurate but also captivating and beautifully structured.`,\n label: '',\n },\n ],\n label: 'System prompt',\n },\n {\n admin: {\n condition: (_, current) => {\n return current['field-type'] === 'richText'\n },\n },\n description: '',\n fields: [\n {\n /** TODO:\n * - Layouts can be saved in as an array\n * - User can add their own layout to collections and use it later for generate specific rich text\n * - User can select previously added layout\n */\n name: 'layout',\n type: 'textarea',\n admin: {\n condition: (_, current) => {\n return current['field-type'] === 'richText'\n },\n },\n defaultValue: `[paragraph] - Write a concise introduction (2-3 sentences) that outlines the main topic.\n[horizontalrule] - Insert a horizontal rule to separate the introduction from the main content.\n[list] - Create a list with 3-5 items. Each list item should contain:\n a. [heading] - A brief, descriptive heading (up to 5 words)\n b. [paragraph] - A short explanation or elaboration (1-2 sentences)\n[horizontalrule] - Insert another horizontal rule to separate the main content from the conclusion.\n[paragraph] - Compose a brief conclusion (2-3 sentences) summarizing the key points.\n[quote] - Include a relevant quote from a famous person, directly related to the topic. Format: \"Quote text.\" - Author Name`,\n label: '',\n },\n ],\n label: 'Layout',\n },\n ],\n },\n ...groupSettings(pluginConfig),\n ],\n labels: {\n plural: 'Compose Settings',\n singular: 'Compose Setting',\n },\n }\n"],"names":["PLUGIN_INSTRUCTIONS_TABLE","getGenerationModels","groupSettings","pluginConfig","reduce","fields","model","settings","push","modelOptions","map","label","name","value","id","defaultAccessConfig","create","req","user","delete","read","update","defaultAdminConfig","group","hidden","instructionsCollection","options","slug","access","admin","type","description","unique","defaultValue","condition","_","current","components","Field","clientProps","filterByField","path","option","tabs","relationTo","uploadCollectionSlug","labels","plural","singular"],"mappings":"AAGA,SAASA,yBAAyB,QAAQ,iBAAgB;AAC1D,SAASC,mBAAmB,QAAQ,sCAAqC;AAEzE,MAAMC,gBAAgB,CAACC,eACrB,AAACF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AM;gBACNkB,MAAM;gBACND,OAAO;oBACLE,aAAa;gBACf;gBACAE,cAAc;gBACdtB,OAAO;gBACPe,SAAS;oBACP;wBACEf,OAAO;wBACPE,OAAO;oBACT;oBACA;wBACEF,OAAO;wBACPE,OAAO;oBACT;oBACA;wBACEF,OAAO;wBACPE,OAAO;oBACT;oBACA;wBACEF,OAAO;wBACPE,OAAO;oBACT;iBACD;YACH;YACA;gBACED,MAAM;gBACNkB,MAAM;gBACND,OAAO;oBACLK,WAAW,CAACC,GAAGC;wBACb,OAAOA,OAAO,CAAC,aAAa,KAAK;oBACnC;gBACF;gBACAzB,OAAO;YACT;YACA;gBACEC,MAAM;gBACNkB,MAAM;gBACND,OAAO;oBACLQ,YAAY;wBACVC,OAAO;4BACLC,aAAa;gCACXC,eAAe;gCACfd,SAASjB,aAAaN;4BACxB;4BACAsC,MAAM;wBACR;oBACF;gBACF;gBACA9B,OAAO;gBACPe,SAASjB,aAAaN,cAAcO,GAAG,CAAC,CAACgC;oBACvC,OAAO;wBACL/B,OAAO+B,OAAO/B,KAAK;wBACnBE,OAAO6B,OAAO7B,KAAK;oBACrB;gBACF;YACF;YACA;gBACEC,IAAI;gBACJgB,MAAM;gBACNa,MAAM;oBACJ;wBACEZ,aACE;wBACF1B,QAAQ;4BACN;gCACEO,MAAM;gCACNkB,MAAM;gCACND,OAAO;oCACLQ,YAAY;wCACVC,OAAO;oCACT;oCACAP,aAAa;gCACf;gCACApB,OAAO;4BACT;yBACD;wBACDA,OAAO;oBACT;oBACA;wBACEkB,OAAO;4BACLK,WAAW,CAACC,GAAGC;gCACb,OAAOA,OAAO,CAAC,aAAa,KAAK,YAAYA,OAAO,CAAC,WAAW,KAAK;4BACvE;wBACF;wBACAL,aACE;wBACF1B,QAAQ;4BACN;gCACEO,MAAM;gCACNkB,MAAM;gCACNzB,QAAQ;oCACN;wCACEO,MAAM;wCACNkB,MAAM;wCACND,OAAO;4CACLE,aAAa;wCACf;wCACAa,YAAYzC,aAAa0C,oBAAoB,GACzC1C,aAAa0C,oBAAoB,GACjC;oCACN;iCACD;4BACH;yBACD;wBACDlC,OAAO;oBACT;oBACA;wBACEkB,OAAO;4BACLK,WAAW,CAACC,GAAGC;gCACb,OAAOA,OAAO,CAAC,aAAa,KAAK;4BACnC;wBACF;wBACAL,aAAa;wBACb1B,QAAQ;4BACN;gCACEO,MAAM;gCACNkB,MAAM;gCACNG,cAAc,CAAC;;;;yEAI0C,CAAC;gCAC1DtB,OAAO;4BACT;yBACD;wBACDA,OAAO;oBACT;oBACA;wBACEkB,OAAO;4BACLK,WAAW,CAACC,GAAGC;gCACb,OAAOA,OAAO,CAAC,aAAa,KAAK;4BACnC;wBACF;wBACAL,aAAa;wBACb1B,QAAQ;4BACN;gCACE;;;;iBAIC,GAJD;;;;iBAIC,GACDO,MAAM;gCACNkB,MAAM;gCACND,OAAO;oCACLK,WAAW,CAACC,GAAGC;wCACb,OAAOA,OAAO,CAAC,aAAa,KAAK;oCACnC;gCACF;gCACAH,cAAc,CAAC;;;;;;;2HAO4F,CAAC;gCAC5GtB,OAAO;4BACT;yBACD;wBACDA,OAAO;oBACT;iBACD;YACH;eACGT,cAAcC;SAClB;QACD2C,QAAQ;YACNC,QAAQ;YACRC,UAAU;QACZ;IACF,CAAA,EAAC"}
1
+ {"version":3,"sources":["../../src/collections/Instructions.ts"],"sourcesContent":["import type { CollectionConfig, GroupField } from 'payload'\nimport type { PluginConfig } from 'src/types.js'\n\nimport { PLUGIN_INSTRUCTIONS_TABLE } from '../defaults.js'\nimport { getGenerationModels } from '../utilities/getGenerationModels.js'\n\nconst groupSettings = (pluginConfig: PluginConfig) =>\n (getGenerationModels(pluginConfig) ?? []).reduce((fields, model) => {\n if (model.settings) {\n fields.push(model.settings)\n }\n return fields\n }, [] as GroupField[])\n\nconst modelOptions = (pluginConfig: PluginConfig) =>\n (getGenerationModels(pluginConfig) ?? []).map((model) => {\n return {\n fields: model.fields,\n label: model.name,\n value: model.id,\n }\n })\n\nconst defaultAccessConfig = {\n create: ({ req }: { req: { user?: any } }) => {\n if (!req.user) {\n return false\n }\n return true\n },\n delete: ({ req }: { req: { user?: any } }) => {\n if (!req.user) {\n return false\n }\n return true\n },\n read: ({ req }: { req: { user?: any } }) => {\n if (!req.user) {\n return false\n }\n return true\n },\n update: ({ req }: { req: { user?: any } }) => {\n if (!req.user) {\n return false\n }\n return true\n },\n}\n\nconst defaultAdminConfig = {\n group: 'Plugins',\n hidden: true,\n}\n\nexport const instructionsCollection = (pluginConfig: PluginConfig) =>\n <CollectionConfig>{\n labels: {\n plural: 'Compose Settings',\n singular: 'Compose Setting',\n },\n ...pluginConfig.overrideInstructions,\n slug: PLUGIN_INSTRUCTIONS_TABLE,\n access: {\n ...defaultAccessConfig,\n ...pluginConfig.overrideInstructions?.access,\n },\n admin: {\n ...defaultAdminConfig,\n ...pluginConfig.overrideInstructions?.admin,\n },\n fields: [\n {\n name: 'schema-path',\n type: 'text',\n admin: {\n description: \"Please don't change this unless you're sure of what you're doing\",\n },\n unique: true,\n },\n {\n name: 'field-type',\n type: 'select',\n admin: {\n description: \"Please don't change this unless you're sure of what you're doing\",\n },\n defaultValue: 'text',\n label: 'Field type',\n options: [\n {\n label: 'text',\n value: 'text',\n },\n {\n label: 'textarea',\n value: 'textarea',\n },\n {\n label: 'upload',\n value: 'upload',\n },\n {\n label: 'richText',\n value: 'richText',\n },\n ],\n },\n {\n name: 'relation-to',\n type: 'text',\n admin: {\n condition: (_, current) => {\n return current['field-type'] === 'upload'\n },\n },\n label: 'Relation to',\n },\n {\n name: 'model-id',\n type: 'select',\n admin: {\n components: {\n Field: {\n clientProps: {\n filterByField: 'field-type',\n options: modelOptions(pluginConfig),\n },\n path: '@ai-stack/payloadcms/fields#SelectField',\n },\n },\n },\n label: 'Model',\n options: modelOptions(pluginConfig).map((option) => {\n return {\n label: option.label,\n value: option.value,\n }\n }),\n },\n {\n name: 'disabled',\n type: 'checkbox',\n admin: {\n description: 'Please reload your collection after applying the changes',\n },\n defaultValue: false,\n label: 'Hide Compose button for this field',\n },\n {\n id: 'ai-prompts-tabs',\n type: 'tabs',\n tabs: [\n {\n description:\n 'Define dynamic templates using {{ fieldName }}. Type { to see available field suggestions.',\n fields: [\n {\n name: 'prompt',\n type: 'textarea',\n admin: {\n components: {\n Field: '@ai-stack/payloadcms/fields#PromptEditorField',\n },\n description: \"Click 'Compose' to run this custom prompt and generate content\",\n },\n label: '',\n },\n ],\n label: 'Prompt',\n },\n {\n admin: {\n condition: (_, current) => {\n return current['field-type'] === 'upload' && current['model-id'] === 'gpt-image-1'\n },\n },\n description:\n 'These images will be used to generate new visuals in a similar style, layout, or content. You can combine multiple references for more controlled results.',\n fields: [\n {\n name: 'images',\n type: 'array',\n fields: [\n {\n name: 'image',\n type: 'upload',\n admin: {\n description: 'Please make sure the image is publicly accessible.',\n },\n relationTo: pluginConfig.uploadCollectionSlug\n ? pluginConfig.uploadCollectionSlug\n : 'media',\n },\n ],\n },\n ],\n label: 'Sample Images',\n },\n {\n admin: {\n condition: (_, current) => {\n return current['field-type'] === 'richText'\n },\n },\n description: '',\n fields: [\n {\n name: 'system',\n type: 'textarea',\n defaultValue: `INSTRUCTIONS:\nYou are a highly skilled and professional blog writer,\nrenowned for crafting engaging and well-organized articles.\nWhen given a title, you meticulously create blogs that are not only\ninformative and accurate but also captivating and beautifully structured.`,\n label: '',\n },\n ],\n label: 'System prompt',\n },\n {\n admin: {\n condition: (_, current) => {\n return current['field-type'] === 'richText'\n },\n },\n description: '',\n fields: [\n {\n /** TODO:\n * - Layouts can be saved in as an array\n * - User can add their own layout to collections and use it later for generate specific rich text\n * - User can select previously added layout\n */\n name: 'layout',\n type: 'textarea',\n admin: {\n condition: (_, current) => {\n return current['field-type'] === 'richText'\n },\n },\n defaultValue: `[paragraph] - Write a concise introduction (2-3 sentences) that outlines the main topic.\n[horizontalrule] - Insert a horizontal rule to separate the introduction from the main content.\n[list] - Create a list with 3-5 items. Each list item should contain:\n a. [heading] - A brief, descriptive heading (up to 5 words)\n b. [paragraph] - A short explanation or elaboration (1-2 sentences)\n[horizontalrule] - Insert another horizontal rule to separate the main content from the conclusion.\n[paragraph] - Compose a brief conclusion (2-3 sentences) summarizing the key points.\n[quote] - Include a relevant quote from a famous person, directly related to the topic. Format: \"Quote text.\" - Author Name`,\n label: '',\n },\n ],\n label: 'Layout',\n },\n ],\n },\n ...groupSettings(pluginConfig),\n ],\n }\n"],"names":["PLUGIN_INSTRUCTIONS_TABLE","getGenerationModels","groupSettings","pluginConfig","reduce","fields","model","settings","push","modelOptions","map","label","name","value","id","defaultAccessConfig","create","req","user","delete","read","update","defaultAdminConfig","group","hidden","instructionsCollection","labels","plural","singular","overrideInstructions","slug","access","admin","type","description","unique","defaultValue","options","condition","_","current","components","Field","clientProps","filterByField","path","option","tabs","relationTo","uploadCollectionSlug"],"mappings":"AAGA,SAASA,yBAAyB,QAAQ,iBAAgB;AAC1D,SAASC,mBAAmB,QAAQ,sCAAqC;AAEzE,MAAMC,gBAAgB,CAACC,eACrB,AAACF,CAAAA,oBAAoBE,iBAAiB,EAAE,AAAD,EAAGC,MAAM,CAAC,CAACC,QAAQC;QACxD,IAAIA,MAAMC,QAAQ,EAAE;YAClBF,OAAOG,IAAI,CAACF,MAAMC,QAAQ;QAC5B;QACA,OAAOF;IACT,GAAG,EAAE;AAEP,MAAMI,eAAe,CAACN,eACpB,AAACF,CAAAA,oBAAoBE,iBAAiB,EAAE,AAAD,EAAGO,GAAG,CAAC,CAACJ;QAC7C,OAAO;YACLD,QAAQC,MAAMD,MAAM;YACpBM,OAAOL,MAAMM,IAAI;YACjBC,OAAOP,MAAMQ,EAAE;QACjB;IACF;AAEF,MAAMC,sBAAsB;IAC1BC,QAAQ,CAAC,EAAEC,GAAG,EAA2B;QACvC,IAAI,CAACA,IAAIC,IAAI,EAAE;YACb,OAAO;QACT;QACA,OAAO;IACT;IACAC,QAAQ,CAAC,EAAEF,GAAG,EAA2B;QACvC,IAAI,CAACA,IAAIC,IAAI,EAAE;Y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a,KAAK;4BACnC;wBACF;wBACAN,aAAa;wBACb7B,QAAQ;4BACN;gCACE;;;;iBAIC,GAJD;;;;iBAIC,GACDO,MAAM;gCACNqB,MAAM;gCACND,OAAO;oCACLM,WAAW,CAACC,GAAGC;wCACb,OAAOA,OAAO,CAAC,aAAa,KAAK;oCACnC;gCACF;gCACAJ,cAAc,CAAC;;;;;;;2HAO4F,CAAC;gCAC5GzB,OAAO;4BACT;yBACD;wBACDA,OAAO;oBACT;iBACD;YACH;eACGT,cAAcC;SAClB;IACH,CAAA,EAAC"}
@@ -22,11 +22,13 @@ export const fetchFields = (config)=>{
22
22
  docs.forEach((doc)=>{
23
23
  fieldMap[doc['schema-path']] = {
24
24
  id: doc.id,
25
+ disabled: !!doc['disabled'],
25
26
  fieldType: doc['field-type']
26
27
  };
27
28
  });
28
29
  return Response.json({
29
30
  ...options,
31
+ debugging: config.debugging,
30
32
  fields: fieldMap,
31
33
  isConfigAllowed,
32
34
  promptFields: promptFields.map(({ getter: _getter, ...field })=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/endpoints/fetchFields.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest } from 'payload'\n\nimport type { PluginConfig, SerializedPromptField } from '../types.js'\n\nimport { PLUGIN_FETCH_FIELDS_ENDPOINT, PLUGIN_INSTRUCTIONS_TABLE } from '../defaults.js'\n\nexport const fetchFields: (config: PluginConfig) => Endpoint = (\n config\n) => {\n const {access, options = {}, promptFields = []} = config\n return {\n handler: async (req: PayloadRequest) => {\n const { docs = [] } = await req.payload.find({\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n pagination: false,\n })\n\n let isConfigAllowed = true // Users allowed to update prompts by default\n\n if (access?.settings) {\n try {\n isConfigAllowed = await access.settings({ req })\n } catch (e) {\n req.payload.logger.error(req, 'Please check your \"access.settings\" for request')\n }\n }\n\n const fieldMap: Record<string, { fieldType: any; id: any }> = {}\n docs.forEach((doc) => {\n fieldMap[doc['schema-path']] = {\n id: doc.id,\n fieldType: doc['field-type'],\n }\n })\n\n return Response.json({\n ...options,\n fields: fieldMap,\n isConfigAllowed,\n promptFields: promptFields.map(({getter: _getter, ...field}): SerializedPromptField => {\n return field\n }),\n })\n },\n method: 'get',\n path: PLUGIN_FETCH_FIELDS_ENDPOINT,\n }\n}\n"],"names":["PLUGIN_FETCH_FIELDS_ENDPOINT","PLUGIN_INSTRUCTIONS_TABLE","fetchFields","config","access","options","promptFields","handler","req","docs","payload","find","collection","pagination","isConfigAllowed","settings","e","logger","error","fieldMap","forEach","doc","id","fieldType","Response","json","fields","map","getter","_getter","field","method","path"],"mappings":"AAIA,SAASA,4BAA4B,EAAEC,yBAAyB,QAAQ,iBAAgB;AAExF,OAAO,MAAMC,cAAkD,CAC7DC;IAEA,MAAM,EAACC,MAAM,EAAEC,UAAU,CAAC,CAAC,EAAEC,eAAe,EAAE,EAAC,GAAGH;IAClD,OAAO;QACLI,SAAS,OAAOC;YACd,MAAM,EAAEC,OAAO,EAAE,EAAE,GAAG,MAAMD,IAAIE,OAAO,CAACC,IAAI,CAAC;gBAC3CC,YAAYX;gBACZY,YAAY;YACd;YAEA,IAAIC,kBAAkB,KAAK,6CAA6C;;YAExE,IAAIV,QAAQW,UAAU;gBACpB,IAAI;oBACFD,kBAAkB,MAAMV,OAAOW,QAAQ,CAAC;wBAAEP;oBAAI;gBAChD,EAAE,OAAOQ,GAAG;oBACVR,IAAIE,OAAO,CAACO,MAAM,CAACC,KAAK,CAACV,KAAK;gBAChC;YACF;YAEA,MAAMW,WAAwD,CAAC;YAC/DV,KAAKW,OAAO,CAAC,CAACC;gBACZF,QAAQ,CAACE,GAAG,CAAC,cAAc,CAAC,GAAG;oBAC7BC,IAAID,IAAIC,EAAE;oBACVC,WAAWF,GAAG,CAAC,aAAa;gBAC9B;YACF;YAEA,OAAOG,SAASC,IAAI,CAAC;gBACnB,GAAGpB,OAAO;gBACVqB,QAAQP;gBACRL;gBACAR,cAAcA,aAAaqB,GAAG,CAAC,CAAC,EAACC,QAAQC,OAAO,EAAE,GAAGC,OAAM;oBACzD,OAAOA;gBACT;YACF;QACF;QACAC,QAAQ;QACRC,MAAMhC;IACR;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/endpoints/fetchFields.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest } from 'payload'\n\nimport type { PluginConfig, SerializedPromptField } from '../types.js'\n\nimport { PLUGIN_FETCH_FIELDS_ENDPOINT, PLUGIN_INSTRUCTIONS_TABLE } from '../defaults.js'\n\nexport const fetchFields: (config: PluginConfig) => Endpoint = (config) => {\n const { access, options = {}, promptFields = [] } = config\n return {\n handler: async (req: PayloadRequest) => {\n const { docs = [] } = await req.payload.find({\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n pagination: false,\n })\n\n let isConfigAllowed = true // Users allowed to update prompts by default\n\n if (access?.settings) {\n try {\n isConfigAllowed = await access.settings({ req })\n } catch (e) {\n req.payload.logger.error(req, 'Please check your \"access.settings\" for request')\n }\n }\n\n const fieldMap: Record<string, { disabled?: boolean; fieldType: any; id: any }> = {}\n docs.forEach((doc) => {\n fieldMap[doc['schema-path']] = {\n id: doc.id,\n disabled: !!doc['disabled'],\n fieldType: doc['field-type'],\n }\n })\n\n return Response.json({\n ...options,\n debugging: config.debugging,\n fields: fieldMap,\n isConfigAllowed,\n promptFields: promptFields.map(({ getter: _getter, ...field }): SerializedPromptField => {\n return field\n }),\n })\n },\n method: 'get',\n path: PLUGIN_FETCH_FIELDS_ENDPOINT,\n }\n}\n"],"names":["PLUGIN_FETCH_FIELDS_ENDPOINT","PLUGIN_INSTRUCTIONS_TABLE","fetchFields","config","access","options","promptFields","handler","req","docs","payload","find","collection","pagination","isConfigAllowed","settings","e","logger","error","fieldMap","forEach","doc","id","disabled","fieldType","Response","json","debugging","fields","map","getter","_getter","field","method","path"],"mappings":"AAIA,SAASA,4BAA4B,EAAEC,yBAAyB,QAAQ,iBAAgB;AAExF,OAAO,MAAMC,cAAkD,CAACC;IAC9D,MAAM,EAAEC,MAAM,EAAEC,UAAU,CAAC,CAAC,EAAEC,eAAe,EAAE,EAAE,GAAGH;IACpD,OAAO;QACLI,SAAS,OAAOC;YACd,MAAM,EAAEC,OAAO,EAAE,EAAE,GAAG,MAAMD,IAAIE,OAAO,CAACC,IAAI,CAAC;gBAC3CC,YAAYX;gBACZY,YAAY;YACd;YAEA,IAAIC,kBAAkB,KAAK,6CAA6C;;YAExE,IAAIV,QAAQW,UAAU;gBACpB,IAAI;oBACFD,kBAAkB,MAAMV,OAAOW,QAAQ,CAAC;wBAAEP;oBAAI;gBAChD,EAAE,OAAOQ,GAAG;oBACVR,IAAIE,OAAO,CAACO,MAAM,CAACC,KAAK,CAACV,KAAK;gBAChC;YACF;YAEA,MAAMW,WAA4E,CAAC;YACnFV,KAAKW,OAAO,CAAC,CAACC;gBACZF,QAAQ,CAACE,GAAG,CAAC,cAAc,CAAC,GAAG;oBAC7BC,IAAID,IAAIC,EAAE;oBACVC,UAAU,CAAC,CAACF,GAAG,CAAC,WAAW;oBAC3BG,WAAWH,GAAG,CAAC,aAAa;gBAC9B;YACF;YAEA,OAAOI,SAASC,IAAI,CAAC;gBACnB,GAAGrB,OAAO;gBACVsB,WAAWxB,OAAOwB,SAAS;gBAC3BC,QAAQT;gBACRL;gBACAR,cAAcA,aAAauB,GAAG,CAAC,CAAC,EAAEC,QAAQC,OAAO,EAAE,GAAGC,OAAO;oBAC3D,OAAOA;gBACT;YACF;QACF;QACAC,QAAQ;QACRC,MAAMlC;IACR;AACF,EAAC"}
@@ -55,12 +55,12 @@ const extendContextWithPromptFields = (data, ctx, pluginConfig)=>{
55
55
  return Object.getOwnPropertyDescriptor(target, prop);
56
56
  },
57
57
  has: (target, prop)=>{
58
- return fieldsMap.has(prop) || prop in target;
58
+ return fieldsMap.has(prop) || target && prop in target;
59
59
  },
60
60
  ownKeys: (target)=>{
61
61
  return [
62
62
  ...fieldsMap.keys(),
63
- ...Object.keys(target)
63
+ ...Object.keys(target || {})
64
64
  ];
65
65
  }
66
66
  });
@@ -262,9 +262,13 @@ export const endpoints = (pluginConfig)=>({
262
262
  ];
263
263
  const editImages = [];
264
264
  for (const img of images){
265
+ const serverURL = req.payload.config?.serverURL || process.env.SERVER_URL || process.env.NEXT_PUBLIC_SERVER_URL;
266
+ let url = img.image.thumbnailURL || img.image.url;
267
+ if (!url.startsWith('http')) {
268
+ url = `${serverURL}${url}`;
269
+ }
265
270
  try {
266
- const serverURL = req.payload.config?.serverURL || process.env.SERVER_URL || process.env.NEXT_PUBLIC_SERVER_URL;
267
- const response = await fetch(`${serverURL}${img.image.url}`, {
271
+ const response = await fetch(url, {
268
272
  headers: {
269
273
  //TODO: Further testing needed or so find a proper way.
270
274
  Authorization: `Bearer ${req.headers.get('Authorization')?.split('Bearer ')[1] || ''}`
@@ -277,10 +281,10 @@ export const endpoints = (pluginConfig)=>({
277
281
  type: img.image.type,
278
282
  data: blob,
279
283
  size: blob.size,
280
- url: `${serverURL}${img.image.url}`
284
+ url
281
285
  });
282
286
  } catch (e) {
283
- req.payload.logger.error(e, 'Error fetching reference images!');
287
+ req.payload.logger.error(e, `Error fetching reference image ${url}`);
284
288
  throw Error("We couldn't fetch the images. Please ensure the images are accessible and hosted publicly.");
285
289
  }
286
290
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/endpoints/index.ts"],"sourcesContent":["import type { CollectionSlug, PayloadRequest } from 'payload'\n\nimport * as process from 'node:process'\n\nimport type {\n ActionMenuItems,\n Endpoints,\n PluginConfig,\n PromptFieldGetterContext,\n} from '../types.js'\n\nimport { defaultPrompts } from '../ai/prompts.js'\nimport { filterEditorSchemaByNodes } from '../ai/utils/filterEditorSchemaByNodes.js'\nimport {\n PLUGIN_API_ENDPOINT_GENERATE,\n PLUGIN_API_ENDPOINT_GENERATE_UPLOAD,\n PLUGIN_INSTRUCTIONS_TABLE,\n PLUGIN_NAME,\n} from '../defaults.js'\nimport { asyncHandlebars } from '../libraries/handlebars/asyncHandlebars.js'\nimport { registerEditorHelper } from '../libraries/handlebars/helpers.js'\nimport { handlebarsHelpersMap } from '../libraries/handlebars/helpersMap.js'\nimport { replacePlaceholders } from '../libraries/handlebars/replacePlaceholders.js'\nimport { extractImageData } from '../utilities/extractImageData.js'\nimport { getGenerationModels } from '../utilities/getGenerationModels.js'\n\nconst requireAuthentication = (req: PayloadRequest) => {\n if (!req.user) {\n throw new Error('Authentication required. Please log in to use AI features.')\n }\n return true\n}\n\nconst checkAccess = async (req: PayloadRequest, pluginConfig: PluginConfig) => {\n requireAuthentication(req)\n\n if (pluginConfig.access?.generate) {\n const hasAccess = await pluginConfig.access.generate({ req })\n if (!hasAccess) {\n throw new Error('Insufficient permissions to use AI generation features.')\n }\n }\n\n return true\n}\n\nconst extendContextWithPromptFields = (\n data: object,\n ctx: PromptFieldGetterContext,\n pluginConfig: PluginConfig,\n) => {\n const { promptFields = [] } = pluginConfig\n const fieldsMap = new Map(\n promptFields\n .filter((f) => !f.collections || f.collections.includes(ctx.collection))\n .map((f) => [f.name, f]),\n )\n return new Proxy(data, {\n get: (target, prop: string) => {\n const field = fieldsMap.get(prop as string)\n if (field?.getter) {\n const value = field.getter(data, ctx)\n return Promise.resolve(value).then((v) => new asyncHandlebars.SafeString(v))\n }\n // {{prop}} escapes content by default. Here we make sure it won't be escaped.\n const value = typeof target === \"object\" ? (target as any)[prop] : undefined\n return typeof value === 'string' ? new asyncHandlebars.SafeString(value) : value\n },\n // It's used by the handlebars library to determine if the property is enumerable\n getOwnPropertyDescriptor: (target, prop) => {\n const field = fieldsMap.get(prop as string)\n if (field) {\n return {\n configurable: true,\n enumerable: true,\n }\n }\n return Object.getOwnPropertyDescriptor(target, prop)\n },\n has: (target, prop) => {\n return fieldsMap.has(prop as string) || prop in target\n },\n ownKeys: (target) => {\n return [...fieldsMap.keys(), ...Object.keys(target)]\n },\n })\n}\n\nconst assignPrompt = async (\n action: ActionMenuItems,\n {\n type,\n actionParams,\n collection,\n context,\n field,\n layout,\n locale,\n pluginConfig,\n systemPrompt = '',\n template,\n }: {\n actionParams: Record<any, any>\n collection: CollectionSlug\n context: object\n field: string\n layout: string\n locale: string\n pluginConfig: PluginConfig\n systemPrompt: string\n template: string\n type: string\n },\n) => {\n const extendedContext = extendContextWithPromptFields(context, { type, collection }, pluginConfig)\n const prompt = await replacePlaceholders(template, extendedContext)\n const toLexicalHTML = type === 'richText' ? handlebarsHelpersMap.toHTML.name : ''\n\n const assignedPrompts = {\n layout: type === 'richText' ? layout : undefined,\n prompt,\n //TODO: Define only once on a collection level\n system: type === 'richText' ? systemPrompt : undefined,\n }\n\n if (action === 'Compose') {\n if (locale && locale !== 'en') {\n /**\n * NOTE: Avoid using the \"system prompt\" for setting the output language,\n * as it causes quotation marks to appear in the output (Currently only tested with openai models).\n * Appending the language instruction directly to the prompt resolves this issue.\n **/\n assignedPrompts.prompt += `\n --- \n OUTPUT LANGUAGE: ${locale}\n `\n }\n\n return assignedPrompts\n }\n\n const prompts = [...(pluginConfig.prompts || []), ...defaultPrompts]\n const foundPrompt = prompts.find((p) => p.name === action)\n const getLayout = foundPrompt?.layout\n const getSystemPrompt = foundPrompt?.system\n\n let updatedLayout = layout\n if (getLayout) {\n updatedLayout = getLayout()\n }\n\n const system = getSystemPrompt\n ? getSystemPrompt({\n ...(actionParams || {}),\n prompt,\n systemPrompt,\n })\n : ''\n\n return {\n layout: updatedLayout,\n // TODO: revisit this toLexicalHTML\n prompt: await replacePlaceholders(`{{${toLexicalHTML} ${field}}}`, extendedContext),\n system,\n }\n}\n\nexport const endpoints: (pluginConfig: PluginConfig) => Endpoints = (pluginConfig) =>\n ({\n textarea: {\n //TODO: This is the main endpoint for generating content - its just needs to be renamed to 'generate' or something.\n handler: async (req: PayloadRequest) => {\n try {\n // Check authentication and authorization first\n await checkAccess(req, pluginConfig)\n\n const data = await req.json?.()\n\n const { allowedEditorNodes = [], locale = 'en', options } = data\n const { action, actionParams, instructionId } = options\n const contextData = data.doc\n\n if (!instructionId) {\n throw new Error(\n `Instruction ID is required for \"${PLUGIN_NAME}\" to work, please check your configuration, or try again`,\n )\n }\n\n // Verify user has access to the specific instruction\n const instructions = await req.payload.findByID({\n id: instructionId,\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n req, // Pass req to ensure access control is applied\n })\n\n const { collections } = req.payload.config\n const collection = collections.find(\n (collection) => collection.slug === PLUGIN_INSTRUCTIONS_TABLE,\n )\n\n if (!collection) {\n throw new Error('Collection not found')\n }\n\n const { custom: { [PLUGIN_NAME]: { editorConfig = {} } = {} } = {} } = collection.admin\n const { schema: editorSchema = {} } = editorConfig\n const { prompt: promptTemplate = '' } = instructions\n\n let allowedEditorSchema = editorSchema\n if (allowedEditorNodes.length) {\n allowedEditorSchema = filterEditorSchemaByNodes(editorSchema, allowedEditorNodes)\n }\n\n const schemaPath = instructions['schema-path'] as string\n const [collectionName, fieldName] = schemaPath?.split('.') || []\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 let localeInfo = locale\n if (\n localeData &&\n defaultLocale &&\n localeData.label &&\n typeof localeData.label === 'object' &&\n defaultLocale in localeData.label\n ) {\n localeInfo = localeData.label[defaultLocale]\n }\n\n const models = getGenerationModels(pluginConfig)\n const model =\n models && Array.isArray(models)\n ? models.find((model) => model.id === instructions['model-id'])\n : undefined\n\n if (!model) {\n throw new Error('Model not found')\n }\n\n // @ts-ignore\n const settingsName = model && model.settings ? model.settings.name : undefined\n if (!settingsName) {\n req.payload.logger.error('— AI Plugin: Error fetching settings name!')\n }\n\n const modelOptions = settingsName ? instructions[settingsName] || {} : {}\n\n const prompts = await assignPrompt(action, {\n type: String(instructions['field-type']),\n actionParams,\n collection: collectionName,\n context: contextData,\n field: fieldName || '',\n layout: instructions.layout,\n locale: localeInfo,\n pluginConfig,\n systemPrompt: instructions.system,\n template: String(promptTemplate),\n })\n\n if (pluginConfig.debugging) {\n req.payload.logger.info(\n { prompts },\n `— AI Plugin: Executing text prompt on ${schemaPath} using ${model.id}`,\n )\n }\n\n return model.handler?.(prompts.prompt, {\n ...modelOptions,\n editorSchema: allowedEditorSchema,\n layout: prompts.layout,\n locale: localeInfo,\n system: prompts.system,\n })\n } catch (error) {\n req.payload.logger.error(error, 'Error generating content: ')\n const message =\n error && typeof error === 'object' && 'message' in error\n ? (error as any).message\n : String(error)\n return new Response(JSON.stringify({ error: message }), {\n headers: { 'Content-Type': 'application/json' },\n status:\n message.includes('Authentication required') ||\n message.includes('Insufficient permissions')\n ? 401\n : 500,\n })\n }\n },\n method: 'post',\n path: PLUGIN_API_ENDPOINT_GENERATE,\n },\n upload: {\n handler: async (req: PayloadRequest) => {\n try {\n // Check authentication and authorization first\n await checkAccess(req, pluginConfig)\n\n const data = await req.json?.()\n\n const { collectionSlug, documentId, options } = data\n const { instructionId } = options\n let docData = {}\n\n if (documentId) {\n try {\n docData = await req.payload.findByID({\n id: documentId,\n collection: collectionSlug,\n draft: true,\n req, // Pass req to ensure access control is applied\n })\n } catch (e) {\n req.payload.logger.error(\n e,\n '— AI Plugin: Error fetching document, you should try again after enabling drafts for this collection',\n )\n }\n }\n\n const contextData = {\n ...data.doc,\n ...docData,\n }\n\n let instructions: Record<string, any> = { images: [], 'model-id': '', prompt: '' }\n\n if (instructionId) {\n // Verify user has access to the specific instruction\n instructions = await req.payload.findByID({\n id: instructionId,\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n req, // Pass req to ensure access control is applied\n })\n }\n\n const { images: sampleImages = [], prompt: promptTemplate = '' } = instructions\n const schemaPath = instructions['schema-path']\n\n registerEditorHelper(req.payload, schemaPath)\n\n const extendedContext = extendContextWithPromptFields(\n contextData,\n { type: instructions['field-type'], collection: collectionSlug },\n pluginConfig,\n )\n const text = await replacePlaceholders(promptTemplate, extendedContext)\n const modelId = instructions['model-id']\n const uploadCollectionSlug = instructions['relation-to']\n\n const images = [...extractImageData(text), ...sampleImages]\n\n const editImages = []\n for (const img of images) {\n try {\n const serverURL =\n req.payload.config?.serverURL ||\n process.env.SERVER_URL ||\n process.env.NEXT_PUBLIC_SERVER_URL\n\n const response = await fetch(`${serverURL}${img.image.url}`, {\n headers: {\n //TODO: Further testing needed or so find a proper way.\n Authorization: `Bearer ${req.headers.get('Authorization')?.split('Bearer ')[1] || ''}`,\n },\n method: 'GET',\n })\n\n const blob = await response.blob()\n editImages.push({\n name: img.image.name,\n type: img.image.type,\n data: blob,\n size: blob.size,\n url: `${serverURL}${img.image.url}`,\n })\n } catch (e) {\n req.payload.logger.error(e, 'Error fetching reference images!')\n throw Error(\n \"We couldn't fetch the images. Please ensure the images are accessible and hosted publicly.\",\n )\n }\n }\n\n const modelsUpload = getGenerationModels(pluginConfig)\n const model =\n modelsUpload && Array.isArray(modelsUpload)\n ? modelsUpload.find((model) => model.id === modelId)\n : undefined\n\n if (!model) {\n throw new Error('Model not found')\n }\n\n // @ts-ignore\n const settingsName = model && model.settings ? model.settings.name : undefined\n if (!settingsName) {\n req.payload.logger.error('— AI Plugin: Error fetching settings name!')\n }\n\n let modelOptions = settingsName ? instructions[settingsName] || {} : {}\n modelOptions = {\n ...modelOptions,\n images: editImages,\n }\n\n if (pluginConfig.debugging) {\n req.payload.logger.info(\n { text },\n `— AI Plugin: Executing image prompt using ${model.id}`,\n )\n }\n\n const result = await model.handler?.(text, modelOptions)\n let assetData: { alt?: string; id: number | string }\n\n if (typeof pluginConfig.mediaUpload === 'function') {\n assetData = await pluginConfig.mediaUpload(result, {\n collection: uploadCollectionSlug,\n request: req,\n })\n } else {\n assetData = await req.payload.create({\n collection: uploadCollectionSlug,\n data: result.data,\n file: result.file,\n req, // Pass req to ensure access control is applied\n })\n }\n\n if (!assetData.id) {\n req.payload.logger.error(\n 'Error uploading generated media, is your media upload function correct?',\n )\n throw new Error('Error uploading generated media!')\n }\n\n return new Response(\n JSON.stringify({\n result: {\n id: assetData.id,\n alt: assetData.alt,\n },\n }),\n )\n } catch (error) {\n req.payload.logger.error(error, 'Error generating upload: ')\n const message =\n error && typeof error === 'object' && 'message' in error\n ? (error as any).message\n : String(error)\n return new Response(JSON.stringify({ error: message }), {\n headers: { 'Content-Type': 'application/json' },\n status:\n message.includes('Authentication required') ||\n message.includes('Insufficient permissions')\n ? 401\n : 500,\n })\n }\n },\n method: 'post',\n path: PLUGIN_API_ENDPOINT_GENERATE_UPLOAD,\n },\n }) satisfies Endpoints\n"],"names":["process","defaultPrompts","filterEditorSchemaByNodes","PLUGIN_API_ENDPOINT_GENERATE","PLUGIN_API_ENDPOINT_GENERATE_UPLOAD","PLUGIN_INSTRUCTIONS_TABLE","PLUGIN_NAME","asyncHandlebars","registerEditorHelper","handlebarsHelpersMap","replacePlaceholders","extractImageData","getGenerationModels","requireAuthentication","req","user","Error","checkAccess","pluginConfig","access","generate","hasAccess","extendContextWithPromptFields","data","ctx","promptFields","fieldsMap","Map","filter","f","collections","includes","collection","map","name","Proxy","get","target","prop","field","getter","value","Promise","resolve","then","v","SafeString","undefined","getOwnPropertyDescriptor","configurable","enumerable","Object","has","ownKeys","keys","assignPrompt","action","type","actionParams","context","layout","locale","systemPrompt","template","extendedContext","prompt","toLexicalHTML","toHTML","assignedPrompts","system","prompts","foundPrompt","find","p","getLayout","getSystemPrompt","updatedLayout","endpoints","textarea","handler","json","allowedEditorNodes","options","instructionId","contextData","doc","instructions","payload","findByID","id","config","slug","custom","editorConfig","admin","schema","editorSchema","promptTemplate","allowedEditorSchema","length","schemaPath","collectionName","fieldName","split","defaultLocale","locales","localization","localeData","l","code","localeInfo","label","models","model","Array","isArray","settingsName","settings","logger","error","modelOptions","String","debugging","info","message","Response","JSON","stringify","headers","status","method","path","upload","collectionSlug","documentId","docData","draft","e","images","sampleImages","text","modelId","uploadCollectionSlug","editImages","img","serverURL","env","SERVER_URL","NEXT_PUBLIC_SERVER_URL","response","fetch","image","url","Authorization","blob","push","size","modelsUpload","result","assetData","mediaUpload","request","create","file","alt"],"mappings":"AAEA,YAAYA,aAAa,eAAc;AASvC,SAASC,cAAc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oBACF;gBAEJ,EAAE,OAAO7C,OAAO;oBACdzG,IAAIyE,OAAO,CAAC+B,MAAM,CAACC,KAAK,CAACA,OAAO;oBAChC,MAAMK,UACJL,SAAS,OAAOA,UAAU,YAAY,aAAaA,QAC/C,AAACA,MAAcK,OAAO,GACtBH,OAAOF;oBACb,OAAO,IAAIM,SAASC,KAAKC,SAAS,CAAC;wBAAER,OAAOK;oBAAQ,IAAI;wBACtDI,SAAS;4BAAE,gBAAgB;wBAAmB;wBAC9CC,QACEL,QAAQ7F,QAAQ,CAAC,8BACjB6F,QAAQ7F,QAAQ,CAAC,8BACb,MACA;oBACR;gBACF;YACF;YACAmG,QAAQ;YACRC,MAAM/H;QACR;IACF,CAAA,EAAsB"}
1
+ {"version":3,"sources":["../../src/endpoints/index.ts"],"sourcesContent":["import type { CollectionSlug, PayloadRequest } from 'payload'\n\nimport * as process from 'node:process'\n\nimport type {\n ActionMenuItems,\n Endpoints,\n PluginConfig,\n PromptFieldGetterContext,\n} from '../types.js'\n\nimport { defaultPrompts } from '../ai/prompts.js'\nimport { filterEditorSchemaByNodes } from '../ai/utils/filterEditorSchemaByNodes.js'\nimport {\n PLUGIN_API_ENDPOINT_GENERATE,\n PLUGIN_API_ENDPOINT_GENERATE_UPLOAD,\n PLUGIN_INSTRUCTIONS_TABLE,\n PLUGIN_NAME,\n} from '../defaults.js'\nimport { asyncHandlebars } from '../libraries/handlebars/asyncHandlebars.js'\nimport { registerEditorHelper } from '../libraries/handlebars/helpers.js'\nimport { handlebarsHelpersMap } from '../libraries/handlebars/helpersMap.js'\nimport { replacePlaceholders } from '../libraries/handlebars/replacePlaceholders.js'\nimport { extractImageData } from '../utilities/extractImageData.js'\nimport { getGenerationModels } from '../utilities/getGenerationModels.js'\n\nconst requireAuthentication = (req: PayloadRequest) => {\n if (!req.user) {\n throw new Error('Authentication required. Please log in to use AI features.')\n }\n return true\n}\n\nconst checkAccess = async (req: PayloadRequest, pluginConfig: PluginConfig) => {\n requireAuthentication(req)\n\n if (pluginConfig.access?.generate) {\n const hasAccess = await pluginConfig.access.generate({ req })\n if (!hasAccess) {\n throw new Error('Insufficient permissions to use AI generation features.')\n }\n }\n\n return true\n}\n\nconst extendContextWithPromptFields = (\n data: object,\n ctx: PromptFieldGetterContext,\n pluginConfig: PluginConfig,\n) => {\n const { promptFields = [] } = pluginConfig\n const fieldsMap = new Map(\n promptFields\n .filter((f) => !f.collections || f.collections.includes(ctx.collection))\n .map((f) => [f.name, f]),\n )\n return new Proxy(data, {\n get: (target, prop: string) => {\n const field = fieldsMap.get(prop as string)\n if (field?.getter) {\n const value = field.getter(data, ctx)\n return Promise.resolve(value).then((v) => new asyncHandlebars.SafeString(v))\n }\n // {{prop}} escapes content by default. Here we make sure it won't be escaped.\n const value = typeof target === \"object\" ? (target as any)[prop] : undefined\n return typeof value === 'string' ? new asyncHandlebars.SafeString(value) : value\n },\n // It's used by the handlebars library to determine if the property is enumerable\n getOwnPropertyDescriptor: (target, prop) => {\n const field = fieldsMap.get(prop as string)\n if (field) {\n return {\n configurable: true,\n enumerable: true,\n }\n }\n return Object.getOwnPropertyDescriptor(target, prop)\n },\n has: (target, prop) => {\n return fieldsMap.has(prop as string) || (target && prop in target)\n },\n ownKeys: (target) => {\n return [...fieldsMap.keys(), ...Object.keys(target || {})]\n },\n })\n}\n\nconst assignPrompt = async (\n action: ActionMenuItems,\n {\n type,\n actionParams,\n collection,\n context,\n field,\n layout,\n locale,\n pluginConfig,\n systemPrompt = '',\n template,\n }: {\n actionParams: Record<any, any>\n collection: CollectionSlug\n context: object\n field: string\n layout: string\n locale: string\n pluginConfig: PluginConfig\n systemPrompt: string\n template: string\n type: string\n },\n) => {\n const extendedContext = extendContextWithPromptFields(context, { type, collection }, pluginConfig)\n const prompt = await replacePlaceholders(template, extendedContext)\n const toLexicalHTML = type === 'richText' ? handlebarsHelpersMap.toHTML.name : ''\n\n const assignedPrompts = {\n layout: type === 'richText' ? layout : undefined,\n prompt,\n //TODO: Define only once on a collection level\n system: type === 'richText' ? systemPrompt : undefined,\n }\n\n if (action === 'Compose') {\n if (locale && locale !== 'en') {\n /**\n * NOTE: Avoid using the \"system prompt\" for setting the output language,\n * as it causes quotation marks to appear in the output (Currently only tested with openai models).\n * Appending the language instruction directly to the prompt resolves this issue.\n **/\n assignedPrompts.prompt += `\n --- \n OUTPUT LANGUAGE: ${locale}\n `\n }\n\n return assignedPrompts\n }\n\n const prompts = [...(pluginConfig.prompts || []), ...defaultPrompts]\n const foundPrompt = prompts.find((p) => p.name === action)\n const getLayout = foundPrompt?.layout\n const getSystemPrompt = foundPrompt?.system\n\n let updatedLayout = layout\n if (getLayout) {\n updatedLayout = getLayout()\n }\n\n const system = getSystemPrompt\n ? getSystemPrompt({\n ...(actionParams || {}),\n prompt,\n systemPrompt,\n })\n : ''\n\n return {\n layout: updatedLayout,\n // TODO: revisit this toLexicalHTML\n prompt: await replacePlaceholders(`{{${toLexicalHTML} ${field}}}`, extendedContext),\n system,\n }\n}\n\nexport const endpoints: (pluginConfig: PluginConfig) => Endpoints = (pluginConfig) =>\n ({\n textarea: {\n //TODO: This is the main endpoint for generating content - its just needs to be renamed to 'generate' or something.\n handler: async (req: PayloadRequest) => {\n try {\n // Check authentication and authorization first\n await checkAccess(req, pluginConfig)\n\n const data = await req.json?.()\n\n const { allowedEditorNodes = [], locale = 'en', options } = data\n const { action, actionParams, instructionId } = options\n const contextData = data.doc\n\n if (!instructionId) {\n throw new Error(\n `Instruction ID is required for \"${PLUGIN_NAME}\" to work, please check your configuration, or try again`,\n )\n }\n\n // Verify user has access to the specific instruction\n const instructions = await req.payload.findByID({\n id: instructionId,\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n req, // Pass req to ensure access control is applied\n })\n\n const { collections } = req.payload.config\n const collection = collections.find(\n (collection) => collection.slug === PLUGIN_INSTRUCTIONS_TABLE,\n )\n\n if (!collection) {\n throw new Error('Collection not found')\n }\n\n const { custom: { [PLUGIN_NAME]: { editorConfig = {} } = {} } = {} } = collection.admin\n const { schema: editorSchema = {} } = editorConfig\n const { prompt: promptTemplate = '' } = instructions\n\n let allowedEditorSchema = editorSchema\n if (allowedEditorNodes.length) {\n allowedEditorSchema = filterEditorSchemaByNodes(editorSchema, allowedEditorNodes)\n }\n\n const schemaPath = instructions['schema-path'] as string\n const [collectionName, fieldName] = schemaPath?.split('.') || []\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 let localeInfo = locale\n if (\n localeData &&\n defaultLocale &&\n localeData.label &&\n typeof localeData.label === 'object' &&\n defaultLocale in localeData.label\n ) {\n localeInfo = localeData.label[defaultLocale]\n }\n\n const models = getGenerationModels(pluginConfig)\n const model =\n models && Array.isArray(models)\n ? models.find((model) => model.id === instructions['model-id'])\n : undefined\n\n if (!model) {\n throw new Error('Model not found')\n }\n\n // @ts-ignore\n const settingsName = model && model.settings ? model.settings.name : undefined\n if (!settingsName) {\n req.payload.logger.error('— AI Plugin: Error fetching settings name!')\n }\n\n const modelOptions = settingsName ? instructions[settingsName] || {} : {}\n\n const prompts = await assignPrompt(action, {\n type: String(instructions['field-type']),\n actionParams,\n collection: collectionName,\n context: contextData,\n field: fieldName || '',\n layout: instructions.layout,\n locale: localeInfo,\n pluginConfig,\n systemPrompt: instructions.system,\n template: String(promptTemplate),\n })\n\n if (pluginConfig.debugging) {\n req.payload.logger.info(\n { prompts },\n `— AI Plugin: Executing text prompt on ${schemaPath} using ${model.id}`,\n )\n }\n\n return model.handler?.(prompts.prompt, {\n ...modelOptions,\n editorSchema: allowedEditorSchema,\n layout: prompts.layout,\n locale: localeInfo,\n system: prompts.system,\n })\n } catch (error) {\n req.payload.logger.error(error, 'Error generating content: ')\n const message =\n error && typeof error === 'object' && 'message' in error\n ? (error as any).message\n : String(error)\n return new Response(JSON.stringify({ error: message }), {\n headers: { 'Content-Type': 'application/json' },\n status:\n message.includes('Authentication required') ||\n message.includes('Insufficient permissions')\n ? 401\n : 500,\n })\n }\n },\n method: 'post',\n path: PLUGIN_API_ENDPOINT_GENERATE,\n },\n upload: {\n handler: async (req: PayloadRequest) => {\n try {\n // Check authentication and authorization first\n await checkAccess(req, pluginConfig)\n\n const data = await req.json?.()\n\n const { collectionSlug, documentId, options } = data\n const { instructionId } = options\n let docData = {}\n\n if (documentId) {\n try {\n docData = await req.payload.findByID({\n id: documentId,\n collection: collectionSlug,\n draft: true,\n req, // Pass req to ensure access control is applied\n })\n } catch (e) {\n req.payload.logger.error(\n e,\n '— AI Plugin: Error fetching document, you should try again after enabling drafts for this collection',\n )\n }\n }\n\n const contextData = {\n ...data.doc,\n ...docData,\n }\n\n let instructions: Record<string, any> = { images: [], 'model-id': '', prompt: '' }\n\n if (instructionId) {\n // Verify user has access to the specific instruction\n instructions = await req.payload.findByID({\n id: instructionId,\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n req, // Pass req to ensure access control is applied\n })\n }\n\n const { images: sampleImages = [], prompt: promptTemplate = '' } = instructions\n const schemaPath = instructions['schema-path']\n\n registerEditorHelper(req.payload, schemaPath)\n\n const extendedContext = extendContextWithPromptFields(\n contextData,\n { type: instructions['field-type'], collection: collectionSlug },\n pluginConfig,\n )\n const text = await replacePlaceholders(promptTemplate, extendedContext)\n const modelId = instructions['model-id']\n const uploadCollectionSlug = instructions['relation-to']\n\n const images = [...extractImageData(text), ...sampleImages]\n\n const editImages = []\n for (const img of images) {\n const serverURL =\n req.payload.config?.serverURL ||\n process.env.SERVER_URL ||\n process.env.NEXT_PUBLIC_SERVER_URL\n\n let url = img.image.thumbnailURL || img.image.url\n if (!url.startsWith('http')) {\n url = `${serverURL}${url}`\n }\n\n try {\n\n const response = await fetch(url, {\n headers: {\n //TODO: Further testing needed or so find a proper way.\n Authorization: `Bearer ${req.headers.get('Authorization')?.split('Bearer ')[1] || ''}`,\n },\n method: 'GET',\n })\n\n const blob = await response.blob()\n editImages.push({\n name: img.image.name,\n type: img.image.type,\n data: blob,\n size: blob.size,\n url,\n })\n } catch (e) {\n req.payload.logger.error(e, `Error fetching reference image ${url}`)\n throw Error(\n \"We couldn't fetch the images. Please ensure the images are accessible and hosted publicly.\",\n )\n }\n }\n\n const modelsUpload = getGenerationModels(pluginConfig)\n const model =\n modelsUpload && Array.isArray(modelsUpload)\n ? modelsUpload.find((model) => model.id === modelId)\n : undefined\n\n if (!model) {\n throw new Error('Model not found')\n }\n\n // @ts-ignore\n const settingsName = model && model.settings ? model.settings.name : undefined\n if (!settingsName) {\n req.payload.logger.error('— AI Plugin: Error fetching settings name!')\n }\n\n let modelOptions = settingsName ? instructions[settingsName] || {} : {}\n modelOptions = {\n ...modelOptions,\n images: editImages,\n }\n\n if (pluginConfig.debugging) {\n req.payload.logger.info(\n { text },\n `— AI Plugin: Executing image prompt using ${model.id}`,\n )\n }\n\n const result = await model.handler?.(text, modelOptions)\n let assetData: { alt?: string; id: number | string }\n\n if (typeof pluginConfig.mediaUpload === 'function') {\n assetData = await pluginConfig.mediaUpload(result, {\n collection: uploadCollectionSlug,\n request: req,\n })\n } else {\n assetData = await req.payload.create({\n collection: uploadCollectionSlug,\n data: result.data,\n file: result.file,\n req, // Pass req to ensure access control is applied\n })\n }\n\n if (!assetData.id) {\n req.payload.logger.error(\n 'Error uploading generated media, is your media upload function correct?',\n )\n throw new Error('Error uploading generated media!')\n }\n\n return new Response(\n JSON.stringify({\n result: {\n id: assetData.id,\n alt: assetData.alt,\n },\n }),\n )\n } catch (error) {\n req.payload.logger.error(error, 'Error generating upload: ')\n const message =\n error && typeof error === 'object' && 'message' in error\n ? (error as any).message\n : String(error)\n return new Response(JSON.stringify({ error: message }), {\n headers: { 'Content-Type': 'application/json' },\n status:\n message.includes('Authentication required') ||\n message.includes('Insufficient permissions')\n ? 401\n : 500,\n })\n }\n },\n method: 'post',\n path: PLUGIN_API_ENDPOINT_GENERATE_UPLOAD,\n },\n }) satisfies Endpoints\n"],"names":["process","defaultPrompts","filterEditorSchemaByNodes","PLUGIN_API_ENDPOINT_GENERATE","PLUGIN_API_ENDPOINT_GENERATE_UPLOAD","PLUGIN_INSTRUCTIONS_TABLE","PLUGIN_NAME","asyncHandlebars","registerEditorHelper","handlebarsHelpersMap","replacePlaceholders","extractImageData","getGenerationModels","requireAuthentication","req","user","Error","checkAccess","pluginConfig","access","generate","hasAccess","extendContextWithPromptFields","data","ctx","promptFields","fieldsMap","Map","filter","f","collections","includes","collection","map","name","Proxy","get","target","prop","field","getter","value","Promise","resolve","then","v","SafeString","undefined","getOwnPropertyDescriptor","configurable","enumerable","Object","has","ownKeys","keys","assignPrompt","action","type","actionParams","context","layout","locale","systemPrompt","template","extendedContext","prompt","toLexicalHTML","toHTML","assignedPrompts","system","prompts","foundPrompt","find","p","getLayout","getSystemPrompt","updatedLayout","endpoints","textarea","handler","json","allowedEditorNodes","options","instructionId","contextData","doc","instructions","payload","findByID","id","config","slug","custom","editorConfig","admin","schema","editorSchema","promptTemplate","allowedEditorSchema","length","schemaPath","collectionName","fieldName","split","defaultLocale","locales","localization","localeData","l","code","localeInfo","label","models","model","Array","isArray","settingsName","settings","logger","error","modelOptions","String","debugging","info","message","Response","JSON","stringify","headers","status","method","path","upload","collectionSlug","documentId","docData","draft","e","images","sampleImages","text","modelId","uploadCollectionSlug","editImages","img","serverURL","env","SERVER_URL","NEXT_PUBLIC_SERVER_URL","url","image","thumbnailURL","startsWith","response","fetch","Authorization","blob","push","size","modelsUpload","result","assetData","mediaUpload","request","create","file","alt"],"mappings":"AAEA,YAAYA,aAAa,eAAc;AASvC,SAASC,cAAc,QAAQ,mBAAkB;AACjD,SAASC,yBAAyB,QAAQ,2CAA0C;AACpF,SACEC,4BAA4B,EAC5BC,mCAAmC,EACnCC,yBAAyB,EACzBC,WAAW,QACN,iBAAgB;AACvB,SAASC,eAAe,QAAQ,6CAA4C;AAC5E,SAASC,oBAAoB,QAAQ,qCAAoC;AACzE,SAASC,oBAAoB,QAAQ,wCAAuC;AAC5E,SAASC,mBAAmB,QAAQ,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AC/C,AAACA,MAAcK,OAAO,GACtBH,OAAOF;oBACb,OAAO,IAAIM,SAASC,KAAKC,SAAS,CAAC;wBAAER,OAAOK;oBAAQ,IAAI;wBACtDI,SAAS;4BAAE,gBAAgB;wBAAmB;wBAC9CC,QACEL,QAAQ7F,QAAQ,CAAC,8BACjB6F,QAAQ7F,QAAQ,CAAC,8BACb,MACA;oBACR;gBACF;YACF;YACAmG,QAAQ;YACRC,MAAM/H;QACR;IACF,CAAA,EAAsB"}
@@ -1,2 +1,2 @@
1
1
  export type { payloadAiPlugin } from '../index.ts';
2
- export type { GenerationConfig, GenerationModel, PluginConfig } from '../types.ts';
2
+ export type { ActionMenuItems, ActionPrompt, ActionPromptOptions, GenerationConfig, GenerationModel, PluginConfig, PluginConfigAccess, PluginConfigMediaUploadFunction, PluginOptions, PromptField, PromptFieldGetterContext, SeedPromptData, SeedPromptFunction, SeedPromptOptions, SeedPromptResult, } from '../types.ts';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/exports/types.ts"],"sourcesContent":["export type { payloadAiPlugin } from '../index.ts'\nexport type { GenerationConfig, GenerationModel, PluginConfig } from '../types.ts'\n"],"names":[],"mappings":"AACA,WAAkF"}
1
+ {"version":3,"sources":["../../src/exports/types.ts"],"sourcesContent":["export type { payloadAiPlugin } from '../index.ts'\nexport type { \n ActionMenuItems,\n ActionPrompt,\n ActionPromptOptions,\n GenerationConfig, \n GenerationModel,\n PluginConfig, \n PluginConfigAccess,\n PluginConfigMediaUploadFunction,\n PluginOptions,\n PromptField,\n PromptFieldGetterContext,\n SeedPromptData,\n SeedPromptFunction,\n SeedPromptOptions,\n SeedPromptResult,\n} from '../types.ts'"],"names":[],"mappings":"AACA,WAgBoB"}
@@ -1,6 +1,6 @@
1
1
  'use client';
2
- import { jsx as _jsx } from "react/jsx-runtime";
3
- import { useDocumentInfo } from '@payloadcms/ui';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { FieldDescription, useDocumentInfo } from '@payloadcms/ui';
4
4
  import React from 'react';
5
5
  import { FieldProvider } from '../../providers/FieldProvider/FieldProvider.js';
6
6
  import { useInstructions } from '../../providers/InstructionsProvider/useInstructions.js';
@@ -8,25 +8,33 @@ import { Compose } from '../../ui/Compose/Compose.js';
8
8
  export const ComposeField = (props)=>{
9
9
  const { collectionSlug } = useDocumentInfo();
10
10
  const finalSchemaPath = props?.schemaPath ?? (collectionSlug ? `${collectionSlug}.${props?.path ?? ''}` : props?.path ?? '');
11
- const { id: instructionId, isConfigAllowed } = useInstructions({
11
+ const { id: instructionId, disabled, hasInstructions, isConfigAllowed } = useInstructions({
12
12
  schemaPath: finalSchemaPath
13
13
  });
14
- return /*#__PURE__*/ _jsx(FieldProvider, {
14
+ return /*#__PURE__*/ _jsxs(FieldProvider, {
15
15
  context: {
16
- type: (props?.field).type,
16
+ type: props?.field.type,
17
17
  path: props?.path ?? '',
18
18
  schemaPath: finalSchemaPath
19
19
  },
20
- children: /*#__PURE__*/ _jsx(Compose, {
21
- descriptionProps: {
22
- ...props,
23
- field: props?.field,
24
- path: props?.path ?? '',
25
- schemaPath: finalSchemaPath
26
- },
27
- instructionId: instructionId,
28
- isConfigAllowed: isConfigAllowed
29
- })
20
+ children: [
21
+ hasInstructions && instructionId && !disabled ? /*#__PURE__*/ _jsx(Compose, {
22
+ descriptionProps: {
23
+ ...props,
24
+ field: props?.field,
25
+ path: props?.path ?? '',
26
+ schemaPath: finalSchemaPath
27
+ },
28
+ instructionId: instructionId,
29
+ isConfigAllowed: isConfigAllowed
30
+ }) : null,
31
+ /*#__PURE__*/ _jsx("div", {
32
+ children: /*#__PURE__*/ _jsx(FieldDescription, {
33
+ path: props?.path ?? '',
34
+ ...props
35
+ })
36
+ })
37
+ ]
30
38
  });
31
39
  };
32
40
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/fields/ComposeField/ComposeField.tsx"],"sourcesContent":["'use client'\n\nimport type { ClientField } from 'payload'\n\nimport { useDocumentInfo } from '@payloadcms/ui'\nimport React from 'react'\n\nimport { FieldProvider } from '../../providers/FieldProvider/FieldProvider.js'\nimport { useInstructions } from '../../providers/InstructionsProvider/useInstructions.js'\nimport { Compose } from '../../ui/Compose/Compose.js'\n\ntype ComposeFieldProps = {\n [key: string]: any\n field: ClientField\n path?: string\n schemaPath?: string\n}\n\nexport const ComposeField = (props: ComposeFieldProps) => {\n const { collectionSlug } = useDocumentInfo()\n\n const finalSchemaPath =\n props?.schemaPath ??\n (collectionSlug ? `${collectionSlug}.${props?.path ?? ''}` : (props?.path ?? ''))\n\n const { id: instructionId, isConfigAllowed } = useInstructions({\n schemaPath: finalSchemaPath,\n })\n\n return (\n <FieldProvider\n context={{\n type: (props?.field as any).type,\n path: props?.path ?? '',\n schemaPath: finalSchemaPath,\n }}\n >\n <Compose\n descriptionProps={{\n ...props,\n field: props?.field,\n path: props?.path ?? '',\n schemaPath: finalSchemaPath,\n }}\n instructionId={instructionId}\n isConfigAllowed={isConfigAllowed}\n />\n </FieldProvider>\n )\n}\n"],"names":["useDocumentInfo","React","FieldProvider","useInstructions","Compose","ComposeField","props","collectionSlug","finalSchemaPath","schemaPath","path","id","instructionId","isConfigAllowed","context","type","field","descriptionProps"],"mappings":"AAAA;;AAIA,SAASA,eAAe,QAAQ,iBAAgB;AAChD,OAAOC,WAAW,QAAO;AAEzB,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SAASC,eAAe,QAAQ,0DAAyD;AACzF,SAASC,OAAO,QAAQ,8BAA6B;AASrD,OAAO,MAAMC,eAAe,CAACC;IAC3B,MAAM,EAAEC,cAAc,EAAE,GAAGP;IAE3B,MAAMQ,kBACJF,OAAOG,cACNF,CAAAA,iBAAiB,GAAGA,eAAe,CAAC,EAAED,OAAOI,QAAQ,IAAI,GAAIJ,OAAOI,QAAQ,EAAE;IAEjF,MAAM,EAAEC,IAAIC,aAAa,EAAEC,eAAe,EAAE,GAAGV,gBAAgB;QAC7DM,YAAYD;IACd;IAEA,qBACE,KAACN;QACCY,SAAS;YACPC,MAAM,AAACT,CAAAA,OAAOU,KAAI,EAAUD,IAAI;YAChCL,MAAMJ,OAAOI,QAAQ;YACrBD,YAAYD;QACd;kBAEA,cAAA,KAACJ;YACCa,kBAAkB;gBAChB,GAAGX,KAAK;gBACRU,OAAOV,OAAOU;gBACdN,MAAMJ,OAAOI,QAAQ;gBACrBD,YAAYD;YACd;YACAI,eAAeA;YACfC,iBAAiBA;;;AAIzB,EAAC"}
1
+ {"version":3,"sources":["../../../src/fields/ComposeField/ComposeField.tsx"],"sourcesContent":["'use client'\n\nimport type { ClientField } from 'payload'\n\nimport { FieldDescription, useDocumentInfo } from '@payloadcms/ui'\nimport React from 'react'\n\nimport { FieldProvider } from '../../providers/FieldProvider/FieldProvider.js'\nimport { useInstructions } from '../../providers/InstructionsProvider/useInstructions.js'\nimport { Compose } from '../../ui/Compose/Compose.js'\n\ntype ComposeFieldProps = {\n [key: string]: any\n field: ClientField\n path?: string\n schemaPath?: string\n}\n\nexport const ComposeField = (props: ComposeFieldProps) => {\n const { collectionSlug } = useDocumentInfo()\n\n const finalSchemaPath =\n props?.schemaPath ??\n (collectionSlug ? `${collectionSlug}.${props?.path ?? ''}` : (props?.path ?? ''))\n\n const {\n id: instructionId,\n disabled,\n hasInstructions,\n isConfigAllowed,\n } = useInstructions({\n schemaPath: finalSchemaPath,\n })\n\n return (\n <FieldProvider\n context={{\n type: props?.field.type,\n path: props?.path ?? '',\n schemaPath: finalSchemaPath,\n }}\n >\n {hasInstructions && instructionId && !disabled ? (\n <Compose\n descriptionProps={{\n ...props,\n field: props?.field,\n path: props?.path ?? '',\n schemaPath: finalSchemaPath,\n }}\n instructionId={instructionId}\n isConfigAllowed={isConfigAllowed}\n />\n ) : null}\n {/*Render the incoming description field*/}\n <div>\n <FieldDescription path={props?.path ?? ''} {...props} />\n </div>\n </FieldProvider>\n )\n}\n"],"names":["FieldDescription","useDocumentInfo","React","FieldProvider","useInstructions","Compose","ComposeField","props","collectionSlug","finalSchemaPath","schemaPath","path","id","instructionId","disabled","hasInstructions","isConfigAllowed","context","type","field","descriptionProps","div"],"mappings":"AAAA;;AAIA,SAASA,gBAAgB,EAAEC,eAAe,QAAQ,iBAAgB;AAClE,OAAOC,WAAW,QAAO;AAEzB,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SAASC,eAAe,QAAQ,0DAAyD;AACzF,SAASC,OAAO,QAAQ,8BAA6B;AASrD,OAAO,MAAMC,eAAe,CAACC;IAC3B,MAAM,EAAEC,cAAc,EAAE,GAAGP;IAE3B,MAAMQ,kBACJF,OAAOG,cACNF,CAAAA,iBAAiB,GAAGA,eAAe,CAAC,EAAED,OAAOI,QAAQ,IAAI,GAAIJ,OAAOI,QAAQ,EAAE;IAEjF,MAAM,EACJC,IAAIC,aAAa,EACjBC,QAAQ,EACRC,eAAe,EACfC,eAAe,EAChB,GAAGZ,gBAAgB;QAClBM,YAAYD;IACd;IAEA,qBACE,MAACN;QACCc,SAAS;YACPC,MAAMX,OAAOY,MAAMD;YACnBP,MAAMJ,OAAOI,QAAQ;YACrBD,YAAYD;QACd;;YAECM,mBAAmBF,iBAAiB,CAACC,yBACpC,KAACT;gBACCe,kBAAkB;oBAChB,GAAGb,KAAK;oBACRY,OAAOZ,OAAOY;oBACdR,MAAMJ,OAAOI,QAAQ;oBACrBD,YAAYD;gBACd;gBACAI,eAAeA;gBACfG,iBAAiBA;iBAEjB;0BAEJ,KAACK;0BACC,cAAA,KAACrB;oBAAiBW,MAAMJ,OAAOI,QAAQ;oBAAK,GAAGJ,KAAK;;;;;AAI5D,EAAC"}
@@ -1,2 +1,2 @@
1
1
  import React from 'react';
2
- export declare const ComposeFeatureComponent: (props: any) => React.JSX.Element;
2
+ export declare const ComposeFeatureComponent: (props: any) => React.JSX.Element | null;
@@ -4,9 +4,12 @@ import { FieldProvider } from '../../providers/FieldProvider/FieldProvider.js';
4
4
  import { useInstructions } from '../../providers/InstructionsProvider/useInstructions.js';
5
5
  import { Compose } from '../../ui/Compose/Compose.js';
6
6
  export const ComposeFeatureComponent = (props)=>{
7
- const { id: instructionId, isConfigAllowed } = useInstructions({
7
+ const { id: instructionId, disabled, isConfigAllowed } = useInstructions({
8
8
  schemaPath: props?.clientProps?.schemaPath
9
9
  });
10
+ if (!instructionId || disabled) {
11
+ return null;
12
+ }
10
13
  return /*#__PURE__*/ _jsx(FieldProvider, {
11
14
  context: {
12
15
  type: props?.clientProps?.field?.type,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/fields/LexicalEditor/ComposeFeatureComponent.tsx"],"sourcesContent":["import React from 'react'\n\nimport { FieldProvider } from '../../providers/FieldProvider/FieldProvider.js'\nimport { useInstructions } from '../../providers/InstructionsProvider/useInstructions.js'\nimport { Compose } from '../../ui/Compose/Compose.js'\n\nexport const ComposeFeatureComponent = (props: any) => {\n const { id: instructionId, isConfigAllowed } = useInstructions({\n schemaPath: props?.clientProps?.schemaPath,\n })\n\n return (\n <FieldProvider\n context={{\n type: props?.clientProps?.field?.type,\n path: props?.clientProps?.path,\n schemaPath: props?.clientProps?.schemaPath,\n }}\n >\n <Compose\n descriptionProps={{\n field: props?.clientProps?.field,\n path: props?.clientProps?.path,\n schemaPath: props?.clientProps?.schemaPath,\n ...props?.clientProps,\n }}\n instructionId={instructionId}\n isConfigAllowed={isConfigAllowed}\n />\n </FieldProvider>\n )\n}\n"],"names":["React","FieldProvider","useInstructions","Compose","ComposeFeatureComponent","props","id","instructionId","isConfigAllowed","schemaPath","clientProps","context","type","field","path","descriptionProps"],"mappings":";AAAA,OAAOA,WAAW,QAAO;AAEzB,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SAASC,eAAe,QAAQ,0DAAyD;AACzF,SAASC,OAAO,QAAQ,8BAA6B;AAErD,OAAO,MAAMC,0BAA0B,CAACC;IACtC,MAAM,EAAEC,IAAIC,aAAa,EAAEC,eAAe,EAAE,GAAGN,gBAAgB;QAC7DO,YAAYJ,OAAOK,aAAaD;IAClC;IAEA,qBACE,KAACR;QACCU,SAAS;YACPC,MAAMP,OAAOK,aAAaG,OAAOD;YACjCE,MAAMT,OAAOK,aAAaI;YAC1BL,YAAYJ,OAAOK,aAAaD;QAClC;kBAEA,cAAA,KAACN;YACCY,kBAAkB;gBAChBF,OAAOR,OAAOK,aAAaG;gBAC3BC,MAAMT,OAAOK,aAAaI;gBAC1BL,YAAYJ,OAAOK,aAAaD;gBAChC,GAAGJ,OAAOK,WAAW;YACvB;YACAH,eAAeA;YACfC,iBAAiBA;;;AAIzB,EAAC"}
1
+ {"version":3,"sources":["../../../src/fields/LexicalEditor/ComposeFeatureComponent.tsx"],"sourcesContent":["import React from 'react'\n\nimport { FieldProvider } from '../../providers/FieldProvider/FieldProvider.js'\nimport { useInstructions } from '../../providers/InstructionsProvider/useInstructions.js'\nimport { Compose } from '../../ui/Compose/Compose.js'\n\nexport const ComposeFeatureComponent = (props: any) => {\n const {\n id: instructionId,\n disabled,\n isConfigAllowed,\n } = useInstructions({\n schemaPath: props?.clientProps?.schemaPath,\n })\n\n if (!instructionId || disabled) {\n return null\n }\n\n return (\n <FieldProvider\n context={{\n type: props?.clientProps?.field?.type,\n path: props?.clientProps?.path,\n schemaPath: props?.clientProps?.schemaPath,\n }}\n >\n <Compose\n descriptionProps={{\n field: props?.clientProps?.field,\n path: props?.clientProps?.path,\n schemaPath: props?.clientProps?.schemaPath,\n ...props?.clientProps,\n }}\n instructionId={instructionId}\n isConfigAllowed={isConfigAllowed}\n />\n </FieldProvider>\n )\n}\n"],"names":["React","FieldProvider","useInstructions","Compose","ComposeFeatureComponent","props","id","instructionId","disabled","isConfigAllowed","schemaPath","clientProps","context","type","field","path","descriptionProps"],"mappings":";AAAA,OAAOA,WAAW,QAAO;AAEzB,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SAASC,eAAe,QAAQ,0DAAyD;AACzF,SAASC,OAAO,QAAQ,8BAA6B;AAErD,OAAO,MAAMC,0BAA0B,CAACC;IACtC,MAAM,EACJC,IAAIC,aAAa,EACjBC,QAAQ,EACRC,eAAe,EAChB,GAAGP,gBAAgB;QAClBQ,YAAYL,OAAOM,aAAaD;IAClC;IAEA,IAAI,CAACH,iBAAiBC,UAAU;QAC9B,OAAO;IACT;IAEA,qBACE,KAACP;QACCW,SAAS;YACPC,MAAMR,OAAOM,aAAaG,OAAOD;YACjCE,MAAMV,OAAOM,aAAaI;YAC1BL,YAAYL,OAAOM,aAAaD;QAClC;kBAEA,cAAA,KAACP;YACCa,kBAAkB;gBAChBF,OAAOT,OAAOM,aAAaG;gBAC3BC,MAAMV,OAAOM,aAAaI;gBAC1BL,YAAYL,OAAOM,aAAaD;gBAChC,GAAGL,OAAOM,WAAW;YACvB;YACAJ,eAAeA;YACfE,iBAAiBA;;;AAIzB,EAAC"}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { defaultPrompts, defaultSeedPrompts as seedPrompts } from './ai/prompts.js';
1
+ export { defaultPrompts, defaultSeedPrompts } from './ai/prompts.js';
2
2
  export { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js';
3
3
  export { payloadAiPlugin } from './plugin.js';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { defaultPrompts, defaultSeedPrompts as seedPrompts } from './ai/prompts.js';
1
+ export { defaultPrompts, defaultSeedPrompts } from './ai/prompts.js';
2
2
  export { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js';
3
3
  export { payloadAiPlugin } from './plugin.js';
4
4
 
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export { defaultPrompts, defaultSeedPrompts as seedPrompts } from './ai/prompts.js'\n\nexport { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js'\nexport { payloadAiPlugin } from './plugin.js'\n"],"names":["defaultPrompts","defaultSeedPrompts","seedPrompts","PayloadAiPluginLexicalEditorFeature","payloadAiPlugin"],"mappings":"AAAA,SAASA,cAAc,EAAEC,sBAAsBC,WAAW,QAAQ,kBAAiB;AAEnF,SAASC,mCAAmC,QAAQ,2CAA0C;AAC9F,SAASC,eAAe,QAAQ,cAAa"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export { defaultPrompts, defaultSeedPrompts } from './ai/prompts.js'\n\nexport { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js'\nexport { payloadAiPlugin } from './plugin.js'\n"],"names":["defaultPrompts","defaultSeedPrompts","PayloadAiPluginLexicalEditorFeature","payloadAiPlugin"],"mappings":"AAAA,SAASA,cAAc,EAAEC,kBAAkB,QAAQ,kBAAiB;AAEpE,SAASC,mCAAmC,QAAQ,2CAA0C;AAC9F,SAASC,eAAe,QAAQ,cAAa"}