@ai-stack/payloadcms 3.0.0-beta.104.4 → 3.0.0-beta.111

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 (78) hide show
  1. package/dist/ai/models/anthropic/generateRichText.d.ts.map +1 -1
  2. package/dist/ai/models/anthropic/generateRichText.js +2 -2
  3. package/dist/ai/models/anthropic/generateRichText.js.map +1 -1
  4. package/dist/ai/models/anthropic/index.d.ts.map +1 -1
  5. package/dist/ai/models/anthropic/index.js +0 -25
  6. package/dist/ai/models/anthropic/index.js.map +1 -1
  7. package/dist/ai/models/openai/generateRichText.js +2 -2
  8. package/dist/ai/models/openai/generateRichText.js.map +1 -1
  9. package/dist/ai/models/openai/index.d.ts.map +1 -1
  10. package/dist/ai/models/openai/index.js +0 -27
  11. package/dist/ai/models/openai/index.js.map +1 -1
  12. package/dist/ai/prompts.js +1 -1
  13. package/dist/ai/prompts.js.map +1 -1
  14. package/dist/ai/schemas/lexicalJsonSchema.d.ts +2 -0
  15. package/dist/ai/schemas/lexicalJsonSchema.d.ts.map +1 -0
  16. package/dist/ai/schemas/lexicalJsonSchema.js +317 -0
  17. package/dist/ai/schemas/lexicalJsonSchema.js.map +1 -0
  18. package/dist/ai/utils/systemGenerate.d.ts +5 -0
  19. package/dist/ai/utils/systemGenerate.d.ts.map +1 -0
  20. package/dist/ai/utils/{generateSeedPrompt.js → systemGenerate.js} +2 -2
  21. package/dist/ai/utils/systemGenerate.js.map +1 -0
  22. package/dist/collections/Instructions.d.ts +1 -1
  23. package/dist/collections/Instructions.d.ts.map +1 -1
  24. package/dist/collections/Instructions.js +177 -85
  25. package/dist/collections/Instructions.js.map +1 -1
  26. package/dist/defaults.d.ts +1 -1
  27. package/dist/defaults.d.ts.map +1 -1
  28. package/dist/defaults.js +1 -1
  29. package/dist/defaults.js.map +1 -1
  30. package/dist/endpoints/fetchFields.d.ts +3 -0
  31. package/dist/endpoints/fetchFields.d.ts.map +1 -0
  32. package/dist/endpoints/fetchFields.js +21 -0
  33. package/dist/endpoints/fetchFields.js.map +1 -0
  34. package/dist/endpoints/index.d.ts.map +1 -1
  35. package/dist/endpoints/index.js +12 -17
  36. package/dist/endpoints/index.js.map +1 -1
  37. package/dist/fields/LexicalEditor/ComposeFeatureComponent.d.ts.map +1 -1
  38. package/dist/fields/LexicalEditor/ComposeFeatureComponent.js +1 -0
  39. package/dist/fields/LexicalEditor/ComposeFeatureComponent.js.map +1 -1
  40. package/dist/index.d.ts +1 -2
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +2 -3
  43. package/dist/index.js.map +1 -1
  44. package/dist/init.d.ts.map +1 -1
  45. package/dist/init.js +11 -15
  46. package/dist/init.js.map +1 -1
  47. package/dist/plugin.d.ts.map +1 -1
  48. package/dist/plugin.js +9 -34
  49. package/dist/plugin.js.map +1 -1
  50. package/dist/providers/InstructionsProvider/InstructionsProvider.d.ts.map +1 -1
  51. package/dist/providers/InstructionsProvider/InstructionsProvider.js +8 -6
  52. package/dist/providers/InstructionsProvider/InstructionsProvider.js.map +1 -1
  53. package/dist/providers/InstructionsProvider/useInstructions.js +1 -1
  54. package/dist/providers/InstructionsProvider/useInstructions.js.map +1 -1
  55. package/dist/types.d.ts +2 -2
  56. package/dist/types.d.ts.map +1 -1
  57. package/dist/types.js.map +1 -1
  58. package/dist/ui/Compose/Compose.d.ts.map +1 -1
  59. package/dist/ui/Compose/Compose.js +6 -4
  60. package/dist/ui/Compose/Compose.js.map +1 -1
  61. package/dist/ui/Compose/hooks/useGenerate.d.ts.map +1 -1
  62. package/dist/ui/Compose/hooks/useGenerate.js +15 -16
  63. package/dist/ui/Compose/hooks/useGenerate.js.map +1 -1
  64. package/dist/utilities/updateFieldsConfig.d.ts.map +1 -1
  65. package/dist/utilities/updateFieldsConfig.js +6 -4
  66. package/dist/utilities/updateFieldsConfig.js.map +1 -1
  67. package/package.json +6 -9
  68. package/dist/ai/schemas/lexical.schema.d.ts +0 -31
  69. package/dist/ai/schemas/lexical.schema.d.ts.map +0 -1
  70. package/dist/ai/schemas/lexical.schema.js +0 -102
  71. package/dist/ai/schemas/lexical.schema.js.map +0 -1
  72. package/dist/ai/utils/generateSeedPrompt.d.ts +0 -5
  73. package/dist/ai/utils/generateSeedPrompt.d.ts.map +0 -1
  74. package/dist/ai/utils/generateSeedPrompt.js.map +0 -1
  75. package/dist/utilities/jsonToZod.d.ts +0 -3
  76. package/dist/utilities/jsonToZod.d.ts.map +0 -1
  77. package/dist/utilities/jsonToZod.js +0 -33
  78. package/dist/utilities/jsonToZod.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ComposeFeatureComponent.d.ts","sourceRoot":"","sources":["../../../src/fields/LexicalEditor/ComposeFeatureComponent.tsx"],"names":[],"mappings":"AAKA,eAAO,MAAM,uBAAuB,+CAQnC,CAAA"}
1
+ {"version":3,"file":"ComposeFeatureComponent.d.ts","sourceRoot":"","sources":["../../../src/fields/LexicalEditor/ComposeFeatureComponent.tsx"],"names":[],"mappings":"AAMA,eAAO,MAAM,uBAAuB,+CAQnC,CAAA"}
@@ -1,5 +1,6 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { useFieldProps } from '@payloadcms/ui';
3
+ import React from 'react';
3
4
  import { useInstructions } from '../../providers/InstructionsProvider/useInstructions.js';
4
5
  import { Compose } from '../../ui/Compose/Compose.js';
5
6
  export const ComposeFeatureComponent = ()=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/fields/LexicalEditor/ComposeFeatureComponent.tsx"],"sourcesContent":["import { useFieldProps } from '@payloadcms/ui'\n\nimport { useInstructions } from '../../providers/InstructionsProvider/useInstructions.js'\nimport { Compose } from '../../ui/Compose/Compose.js'\n\nexport const ComposeFeatureComponent = () => {\n const { schemaPath } = useFieldProps()\n\n const { id: instructionId } = useInstructions({\n path: schemaPath,\n })\n\n return <Compose instructionId={instructionId} />\n}\n"],"names":["useFieldProps","useInstructions","Compose","ComposeFeatureComponent","schemaPath","id","instructionId","path"],"mappings":";AAAA,SAASA,aAAa,QAAQ,iBAAgB;AAE9C,SAASC,eAAe,QAAQ,0DAAyD;AACzF,SAASC,OAAO,QAAQ,8BAA6B;AAErD,OAAO,MAAMC,0BAA0B;IACrC,MAAM,EAAEC,UAAU,EAAE,GAAGJ;IAEvB,MAAM,EAAEK,IAAIC,aAAa,EAAE,GAAGL,gBAAgB;QAC5CM,MAAMH;IACR;IAEA,qBAAO,KAACF;QAAQI,eAAeA;;AACjC,EAAC"}
1
+ {"version":3,"sources":["../../../src/fields/LexicalEditor/ComposeFeatureComponent.tsx"],"sourcesContent":["import { useFieldProps } from '@payloadcms/ui'\nimport React from 'react'\n\nimport { useInstructions } from '../../providers/InstructionsProvider/useInstructions.js'\nimport { Compose } from '../../ui/Compose/Compose.js'\n\nexport const ComposeFeatureComponent = () => {\n const { schemaPath } = useFieldProps()\n\n const { id: instructionId } = useInstructions({\n path: schemaPath,\n })\n\n return <Compose instructionId={instructionId} />\n}\n"],"names":["useFieldProps","React","useInstructions","Compose","ComposeFeatureComponent","schemaPath","id","instructionId","path"],"mappings":";AAAA,SAASA,aAAa,QAAQ,iBAAgB;AAC9C,OAAOC,WAAW,QAAO;AAEzB,SAASC,eAAe,QAAQ,0DAAyD;AACzF,SAASC,OAAO,QAAQ,8BAA6B;AAErD,OAAO,MAAMC,0BAA0B;IACrC,MAAM,EAAEC,UAAU,EAAE,GAAGL;IAEvB,MAAM,EAAEM,IAAIC,aAAa,EAAE,GAAGL,gBAAgB;QAC5CM,MAAMH;IACR;IAEA,qBAAO,KAACF;QAAQI,eAAeA;;AACjC,EAAC"}
package/dist/index.d.ts CHANGED
@@ -4,7 +4,6 @@
4
4
  * COMMERCIAL-LICENSE.md. Unauthorized commercial use or resale of modified versions
5
5
  * without appropriate licensing is prohibited.
6
6
  */
7
- export { payloadAiPlugin } from './plugin.js';
8
7
  export { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js';
9
- export { LexicalBaseNode } from './ai/schemas/lexical.schema.js';
8
+ export { payloadAiPlugin } from './plugin.js';
10
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAC7C,OAAO,EAAE,mCAAmC,EAAE,MAAM,0CAA0C,CAAA;AAC9F,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,mCAAmC,EAAE,MAAM,0CAA0C,CAAA;AAC9F,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA"}
package/dist/index.js CHANGED
@@ -3,8 +3,7 @@
3
3
  * redistribution, or embedding in proprietary systems, please refer to the
4
4
  * COMMERCIAL-LICENSE.md. Unauthorized commercial use or resale of modified versions
5
5
  * without appropriate licensing is prohibited.
6
- */ export { payloadAiPlugin } from './plugin.js';
7
- export { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js';
8
- export { LexicalBaseNode } from './ai/schemas/lexical.schema.js';
6
+ */ export { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js';
7
+ export { payloadAiPlugin } from './plugin.js';
9
8
 
10
9
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @license This software is licensed under the MIT License. For commercial use,\n * redistribution, or embedding in proprietary systems, please refer to the\n * COMMERCIAL-LICENSE.md. Unauthorized commercial use or resale of modified versions\n * without appropriate licensing is prohibited.\n */\n\nexport { payloadAiPlugin } from './plugin.js'\nexport { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js'\nexport { LexicalBaseNode } from './ai/schemas/lexical.schema.js'\n"],"names":["payloadAiPlugin","PayloadAiPluginLexicalEditorFeature","LexicalBaseNode"],"mappings":"AAAA;;;;;CAKC,GAED,SAASA,eAAe,QAAQ,cAAa;AAC7C,SAASC,mCAAmC,QAAQ,2CAA0C;AAC9F,SAASC,eAAe,QAAQ,iCAAgC"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @license This software is licensed under the MIT License. For commercial use,\n * redistribution, or embedding in proprietary systems, please refer to the\n * COMMERCIAL-LICENSE.md. Unauthorized commercial use or resale of modified versions\n * without appropriate licensing is prohibited.\n */\n\nexport { PayloadAiPluginLexicalEditorFeature } from './fields/LexicalEditor/feature.server.js'\nexport { payloadAiPlugin } from './plugin.js'\n"],"names":["PayloadAiPluginLexicalEditorFeature","payloadAiPlugin"],"mappings":"AAAA;;;;;CAKC,GAED,SAASA,mCAAmC,QAAQ,2CAA0C;AAC9F,SAASC,eAAe,QAAQ,cAAa"}
@@ -1 +1 @@
1
- {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAMtC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAE9C,eAAO,MAAM,IAAI,YAAmB,OAAO,uCAAkC,YAAY,kBA2FxF,CAAA"}
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAEtC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAO9C,eAAO,MAAM,IAAI,YAAmB,OAAO,uCAAkC,YAAY,kBAuFxF,CAAA"}
package/dist/init.js CHANGED
@@ -1,17 +1,17 @@
1
1
  import { GenerationModels } from './ai/models/index.js';
2
2
  import { seedPrompts } from './ai/prompts.js';
3
- import { generateSeedPrompt } from './ai/utils/generateSeedPrompt.js';
4
- import { PLUGIN_INSTRUCTIONS_MAP_GLOBAL, PLUGIN_INSTRUCTIONS_TABLE } from './defaults.js';
3
+ import { systemGenerate } from './ai/utils/systemGenerate.js';
4
+ import { PLUGIN_INSTRUCTIONS_TABLE } from './defaults.js';
5
5
  export const init = async (payload, fieldSchemaPaths, pluginConfig)=>{
6
6
  payload.logger.info(`— AI Plugin: Initializing...`);
7
7
  const paths = Object.keys(fieldSchemaPaths);
8
8
  const fieldInstructionsMap = {};
9
9
  for(let i = 0; i < paths.length; i++){
10
10
  const path = paths[i];
11
- const { type: fieldType, label: fieldLabel } = fieldSchemaPaths[path];
12
- //TODO: if global is broken the plugin doesn't know and does not run reindexing
11
+ const { type: fieldType, label: fieldLabel, relationTo } = fieldSchemaPaths[path];
13
12
  const entry = await payload.find({
14
13
  collection: PLUGIN_INSTRUCTIONS_TABLE,
14
+ pagination: false,
15
15
  where: {
16
16
  'field-type': {
17
17
  equals: fieldType
@@ -30,7 +30,7 @@ export const init = async (payload, fieldSchemaPaths, pluginConfig)=>{
30
30
  });
31
31
  let generatedPrompt = '{{ title }}';
32
32
  if (pluginConfig.generatePromptOnInit) {
33
- generatedPrompt = await generateSeedPrompt({
33
+ generatedPrompt = await systemGenerate({
34
34
  prompt,
35
35
  system
36
36
  });
@@ -44,10 +44,11 @@ export const init = async (payload, fieldSchemaPaths, pluginConfig)=>{
44
44
  return a.fields.includes(fieldType);
45
45
  })?.id,
46
46
  prompt: generatedPrompt,
47
+ 'relation-to': relationTo,
47
48
  'schema-path': path
48
49
  }
49
- }).then((a)=>a).catch((a)=>{
50
- console.log('err-', a);
50
+ }).then((a)=>a).catch((err)=>{
51
+ console.log('— AI Plugin: Error creating Compose settings-', err);
51
52
  });
52
53
  // @ts-expect-error
53
54
  if (instructions?.id) {
@@ -64,14 +65,9 @@ export const init = async (payload, fieldSchemaPaths, pluginConfig)=>{
64
65
  };
65
66
  }
66
67
  }
67
- payload.logger.info(`— AI Plugin: Enabled fieldMap: ${JSON.stringify(fieldInstructionsMap, null, 2)}`);
68
- await payload.updateGlobal({
69
- slug: PLUGIN_INSTRUCTIONS_MAP_GLOBAL,
70
- data: {
71
- map: fieldInstructionsMap
72
- },
73
- depth: 2
74
- });
68
+ if (pluginConfig.debugging) {
69
+ payload.logger.info(`— AI Plugin: Enabled fields map: ${JSON.stringify(fieldInstructionsMap, null, 2)}`);
70
+ }
75
71
  payload.logger.info(`— AI Plugin: Initialized!`);
76
72
  if (pluginConfig.generatePromptOnInit) {
77
73
  payload.logger.info('\n\n-AI Plugin: Example prompts are added to get you started, Now go break some code 🚀🚀🚀\n\n');
package/dist/init.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/init.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport { GenerationModels } from './ai/models/index.js'\nimport { seedPrompts } from './ai/prompts.js'\nimport { generateSeedPrompt } from './ai/utils/generateSeedPrompt.js'\nimport { PLUGIN_INSTRUCTIONS_MAP_GLOBAL, PLUGIN_INSTRUCTIONS_TABLE } from './defaults.js'\nimport type { PluginConfig } from './types.js'\n\nexport const init = async (payload: Payload, fieldSchemaPaths, pluginConfig: PluginConfig) => {\n payload.logger.info(`— AI Plugin: Initializing...`)\n\n const paths = Object.keys(fieldSchemaPaths)\n\n const fieldInstructionsMap = {}\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i]\n const { type: fieldType, label: fieldLabel } = fieldSchemaPaths[path]\n //TODO: if global is broken the plugin doesn't know and does not run reindexing\n const entry = await payload.find({\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n where: {\n 'field-type': {\n equals: fieldType,\n },\n 'schema-path': {\n equals: path,\n },\n },\n })\n\n if (!entry?.docs?.length) {\n const { prompt, system } = seedPrompts({\n fieldLabel,\n fieldSchemaPaths,\n fieldType,\n path,\n })\n\n let generatedPrompt = '{{ title }}'\n if (pluginConfig.generatePromptOnInit) {\n generatedPrompt = await generateSeedPrompt({\n prompt,\n system,\n })\n payload.logger.info(\n `\\nPrompt generated for \"${fieldLabel}\" field:\\nprompt: ${generatedPrompt}\\n\\n`,\n )\n }\n\n const instructions = await payload\n .create({\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n data: {\n 'field-type': fieldType,\n 'model-id': GenerationModels.find((a) => {\n return a.fields.includes(fieldType)\n })?.id,\n prompt: generatedPrompt,\n 'schema-path': path,\n },\n })\n .then((a) => a)\n .catch((a) => {\n console.log('err-', a)\n })\n\n // @ts-expect-error\n if (instructions?.id) {\n fieldInstructionsMap[path] = {\n id: instructions.id,\n fieldType,\n }\n }\n } else {\n const [instructions] = entry.docs\n fieldInstructionsMap[path] = {\n id: instructions.id,\n fieldType,\n }\n }\n }\n\n payload.logger.info(\n `— AI Plugin: Enabled fieldMap: ${JSON.stringify(fieldInstructionsMap, null, 2)}`,\n )\n await payload.updateGlobal({\n slug: PLUGIN_INSTRUCTIONS_MAP_GLOBAL, // required\n data: {\n map: fieldInstructionsMap,\n },\n depth: 2,\n })\n\n payload.logger.info(`— AI Plugin: Initialized!`)\n if (pluginConfig.generatePromptOnInit) {\n payload.logger.info(\n '\\n\\n-AI Plugin: Example prompts are added to get you started, Now go break some code 🚀🚀🚀\\n\\n',\n )\n }\n}\n"],"names":["GenerationModels","seedPrompts","generateSeedPrompt","PLUGIN_INSTRUCTIONS_MAP_GLOBAL","PLUGIN_INSTRUCTIONS_TABLE","init","payload","fieldSchemaPaths","pluginConfig","logger","info","paths","Object","keys","fieldInstructionsMap","i","length","path","type","fieldType","label","fieldLabel","entry","find","collection","where","equals","docs","prompt","system","generatedPrompt","generatePromptOnInit","instructions","create","data","a","fields","includes","id","then","catch","console","log","JSON","stringify","updateGlobal","slug","map","depth"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,uBAAsB;AACvD,SAASC,WAAW,QAAQ,kBAAiB;AAC7C,SAASC,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,8BAA8B,EAAEC,yBAAyB,QAAQ,gBAAe;AAGzF,OAAO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AmB;YACnB,IAAIH,cAAcM,IAAI;gBACpBxB,oBAAoB,CAACG,KAAK,GAAG;oBAC3BqB,IAAIN,aAAaM,EAAE;oBACnBnB;gBACF;YACF;QACF,OAAO;YACL,MAAM,CAACa,aAAa,GAAGV,MAAMK,IAAI;YACjCb,oBAAoB,CAACG,KAAK,GAAG;gBAC3BqB,IAAIN,aAAaM,EAAE;gBACnBnB;YACF;QACF;IACF;IAEAb,QAAQG,MAAM,CAACC,IAAI,CACjB,CAAC,+BAA+B,EAAEiC,KAAKC,SAAS,CAAC9B,sBAAsB,MAAM,GAAG,CAAC;IAEnF,MAAMR,QAAQuC,YAAY,CAAC;QACzBC,MAAM3C;QACN+B,MAAM;YACJa,KAAKjC;QACP;QACAkC,OAAO;IACT;IAEA1C,QAAQG,MAAM,CAACC,IAAI,CAAC,CAAC,yBAAyB,CAAC;IAC/C,IAAIF,aAAauB,oBAAoB,EAAE;QACrCzB,QAAQG,MAAM,CAACC,IAAI,CACjB;IAEJ;AACF,EAAC"}
1
+ {"version":3,"sources":["../src/init.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport type { PluginConfig } from './types.js'\n\nimport { GenerationModels } from './ai/models/index.js'\nimport { seedPrompts } from './ai/prompts.js'\nimport { systemGenerate } from './ai/utils/systemGenerate.js'\nimport { PLUGIN_INSTRUCTIONS_TABLE } from './defaults.js'\n\nexport const init = async (payload: Payload, fieldSchemaPaths, pluginConfig: PluginConfig) => {\n payload.logger.info(`— AI Plugin: Initializing...`)\n\n const paths = Object.keys(fieldSchemaPaths)\n\n const fieldInstructionsMap = {}\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i]\n const { type: fieldType, label: fieldLabel, relationTo } = fieldSchemaPaths[path]\n const entry = await payload.find({\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n pagination: false,\n where: {\n 'field-type': {\n equals: fieldType,\n },\n 'schema-path': {\n equals: path,\n },\n },\n })\n\n if (!entry?.docs?.length) {\n const { prompt, system } = seedPrompts({\n fieldLabel,\n fieldSchemaPaths,\n fieldType,\n path,\n })\n\n let generatedPrompt = '{{ title }}'\n if (pluginConfig.generatePromptOnInit) {\n generatedPrompt = await systemGenerate({\n prompt,\n system,\n })\n payload.logger.info(\n `\\nPrompt generated for \"${fieldLabel}\" field:\\nprompt: ${generatedPrompt}\\n\\n`,\n )\n }\n\n const instructions = await payload\n .create({\n collection: PLUGIN_INSTRUCTIONS_TABLE,\n data: {\n 'field-type': fieldType,\n 'model-id': GenerationModels.find((a) => {\n return a.fields.includes(fieldType)\n })?.id,\n prompt: generatedPrompt,\n 'relation-to': relationTo,\n 'schema-path': path,\n },\n })\n .then((a) => a)\n .catch((err) => {\n console.log('— AI Plugin: Error creating Compose settings-', err)\n })\n\n // @ts-expect-error\n if (instructions?.id) {\n fieldInstructionsMap[path] = {\n id: instructions.id,\n fieldType,\n }\n }\n } else {\n const [instructions] = entry.docs\n fieldInstructionsMap[path] = {\n id: instructions.id,\n fieldType,\n }\n }\n }\n\n if (pluginConfig.debugging) {\n payload.logger.info(\n `— AI Plugin: Enabled fields map: ${JSON.stringify(fieldInstructionsMap, null, 2)}`,\n )\n }\n\n payload.logger.info(`— AI Plugin: Initialized!`)\n if (pluginConfig.generatePromptOnInit) {\n payload.logger.info(\n '\\n\\n-AI Plugin: Example prompts are added to get you started, Now go break some code 🚀🚀🚀\\n\\n',\n )\n }\n}\n"],"names":["GenerationModels","seedPrompts","systemGenerate","PLUGIN_INSTRUCTIONS_TABLE","init","payload","fieldSchemaPaths","pluginConfig","logger","info","paths","Object","keys","fieldInstructionsMap","i","length","path","type","fieldType","label","fieldLabel","relationTo","entry","find","collection","pagination","where","equals","docs","prompt","system","generatedPrompt","generatePromptOnInit","instructions","create","data","a","fields","includes","id","then","catch","err","console","log","debugging","JSON","stringify"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,uBAAsB;AACvD,SAASC,WAAW,QAAQ,kBAAiB;AAC7C,SAASC,cAAc,QAAQ,+BAA8B;AAC7D,SA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,CAAC,CAACC;gBACNC,QAAQC,GAAG,CAAC,iDAAiDF;YAC/D;YAEF,mBAAmB;YACnB,IAAIT,cAAcM,IAAI;gBACpB1B,oBAAoB,CAACG,KAAK,GAAG;oBAC3BuB,IAAIN,aAAaM,EAAE;oBACnBrB;gBACF;YACF;QACF,OAAO;YACL,MAAM,CAACe,aAAa,GAAGX,MAAMM,IAAI;YACjCf,oBAAoB,CAACG,KAAK,GAAG;gBAC3BuB,IAAIN,aAAaM,EAAE;gBACnBrB;YACF;QACF;IACF;IAEA,IAAIX,aAAasC,SAAS,EAAE;QAC1BxC,QAAQG,MAAM,CAACC,IAAI,CACjB,CAAC,iCAAiC,EAAEqC,KAAKC,SAAS,CAAClC,sBAAsB,MAAM,GAAG,CAAC;IAEvF;IAEAR,QAAQG,MAAM,CAACC,IAAI,CAAC,CAAC,yBAAyB,CAAC;IAC/C,IAAIF,aAAayB,oBAAoB,EAAE;QACrC3B,QAAQG,MAAM,CAACC,IAAI,CACjB;IAEJ;AACF,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAKrC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAgB9C,QAAA,MAAM,eAAe,iBACJ,YAAY,sBACV,MAAM,KAAG,MAgHzB,CAAA;AAEH,OAAO,EAAE,eAAe,EAAE,CAAA"}
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAIrC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAiB9C,QAAA,MAAM,eAAe,iBACJ,YAAY,sBACV,MAAM,KAAG,MAyFzB,CAAA;AAEH,OAAO,EAAE,eAAe,EAAE,CAAA"}
package/dist/plugin.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { deepMerge } from 'payload/shared';
2
- import { zodToJsonSchema } from 'zod-to-json-schema';
3
- import { lexicalSchema } from './ai/schemas/lexical.schema.js';
4
- import { Instructions } from './collections/Instructions.js';
5
- import { PLUGIN_INSTRUCTIONS_MAP_GLOBAL, PLUGIN_NAME } from './defaults.js';
2
+ import { lexicalJsonSchema } from './ai/schemas/lexicalJsonSchema.js';
3
+ import { instructionsCollection } from './collections/Instructions.js';
4
+ import { PLUGIN_NAME } from './defaults.js';
5
+ import { fetchFields } from './endpoints/fetchFields.js';
6
6
  import { endpoints } from './endpoints/index.js';
7
7
  import { init } from './init.js';
8
8
  import { translations } from './translations/index.js';
@@ -23,8 +23,9 @@ const payloadAiPlugin = (pluginConfig)=>(incomingConfig)=>{
23
23
  };
24
24
  let collectionsFieldPathMap = {};
25
25
  if (isActivated) {
26
+ const Instructions = instructionsCollection();
26
27
  // Inject editor schema to config, so that it can be accessed when /textarea endpoint will hit
27
- const zodLexicalSchema = lexicalSchema(pluginConfig.editorConfig?.nodes);
28
+ const lexicalSchema = lexicalJsonSchema(pluginConfig.editorConfig?.nodes);
28
29
  if (pluginConfig.debugging) {
29
30
  Instructions.admin.hidden = false;
30
31
  }
@@ -33,16 +34,7 @@ const payloadAiPlugin = (pluginConfig)=>(incomingConfig)=>{
33
34
  [PLUGIN_NAME]: {
34
35
  editorConfig: {
35
36
  // Used in admin client for useObject hook
36
- schema: zodToJsonSchema(zodLexicalSchema)
37
- }
38
- }
39
- };
40
- Instructions.custom = {
41
- ...Instructions.custom || {},
42
- [PLUGIN_NAME]: {
43
- editorConfig: {
44
- // Used in textarea endpoint for llm
45
- schema: zodLexicalSchema
37
+ schema: lexicalSchema
46
38
  }
47
39
  }
48
40
  };
@@ -83,25 +75,8 @@ const payloadAiPlugin = (pluginConfig)=>(incomingConfig)=>{
83
75
  endpoints: [
84
76
  ...incomingConfig.endpoints ?? [],
85
77
  endpoints.textarea,
86
- endpoints.upload
87
- ],
88
- globals: [
89
- ...incomingConfig.globals || [],
90
- {
91
- slug: PLUGIN_INSTRUCTIONS_MAP_GLOBAL,
92
- access: {
93
- read: ()=>true
94
- },
95
- admin: {
96
- hidden: !pluginConfig.debugging
97
- },
98
- fields: [
99
- {
100
- name: 'map',
101
- type: 'json'
102
- }
103
- ]
104
- }
78
+ endpoints.upload,
79
+ fetchFields
105
80
  ],
106
81
  i18n: {
107
82
  ...incomingConfig.i18n || {},
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/plugin.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport { deepMerge } from 'payload/shared'\nimport { zodToJsonSchema } from 'zod-to-json-schema'\n\nimport type { PluginConfig } from './types.js'\n\nimport { lexicalSchema } from './ai/schemas/lexical.schema.js'\nimport { Instructions } from './collections/Instructions.js'\nimport { PLUGIN_INSTRUCTIONS_MAP_GLOBAL, PLUGIN_NAME } from './defaults.js'\nimport { endpoints } from './endpoints/index.js'\nimport { init } from './init.js'\nimport { translations } from './translations/index.js'\nimport { isPluginActivated } from './utilities/isPluginActivated.js'\nimport { updateFieldsConfig } from './utilities/updateFieldsConfig.js'\n\nconst defaultPluginConfig: PluginConfig = {\n collections: {},\n generatePromptOnInit: true,\n}\n\nconst payloadAiPlugin =\n (pluginConfig: PluginConfig) =>\n (incomingConfig: Config): Config => {\n pluginConfig = { ...defaultPluginConfig, ...pluginConfig }\n const isActivated = isPluginActivated()\n let updatedConfig: Config = { ...incomingConfig }\n let collectionsFieldPathMap = {}\n\n if (isActivated) {\n // Inject editor schema to config, so that it can be accessed when /textarea endpoint will hit\n const zodLexicalSchema = lexicalSchema(pluginConfig.editorConfig?.nodes)\n\n if (pluginConfig.debugging) {\n Instructions.admin.hidden = false\n }\n\n Instructions.admin.custom = {\n ...(Instructions.admin.custom || {}),\n [PLUGIN_NAME]: {\n editorConfig: {\n // Used in admin client for useObject hook\n schema: zodToJsonSchema(zodLexicalSchema),\n },\n },\n }\n\n Instructions.custom = {\n ...(Instructions.custom || {}),\n [PLUGIN_NAME]: {\n editorConfig: {\n // Used in textarea endpoint for llm\n schema: zodLexicalSchema,\n },\n },\n }\n\n const collections = [...(incomingConfig.collections ?? []), Instructions]\n const { collections: collectionSlugs = [] } = pluginConfig\n\n const { components: { providers = [] } = {} } = incomingConfig.admin || {}\n const updatedProviders = [\n ...(providers ?? []),\n {\n clientProps: {},\n path: '@ai-stack/payloadcms/client#InstructionsProvider',\n serverProps: {},\n },\n ]\n\n incomingConfig.admin = {\n ...(incomingConfig.admin || {}),\n components: {\n ...(incomingConfig.admin?.components ?? {}),\n providers: updatedProviders,\n },\n }\n\n updatedConfig = {\n ...incomingConfig,\n collections: collections.map((collection) => {\n if (collectionSlugs[collection.slug]) {\n const { schemaPathMap, updatedCollectionConfig } = updateFieldsConfig(collection)\n collectionsFieldPathMap = {\n ...collectionsFieldPathMap,\n ...schemaPathMap,\n }\n return updatedCollectionConfig\n }\n\n return collection\n }),\n endpoints: [...(incomingConfig.endpoints ?? []), endpoints.textarea, endpoints.upload],\n globals: [\n ...(incomingConfig.globals || []),\n {\n slug: PLUGIN_INSTRUCTIONS_MAP_GLOBAL,\n access: {\n read: () => true,\n },\n admin: {\n hidden: !pluginConfig.debugging,\n },\n fields: [\n {\n name: 'map',\n type: 'json',\n },\n ],\n },\n ],\n i18n: {\n ...(incomingConfig.i18n || {}),\n translations: {\n ...deepMerge(translations, incomingConfig.i18n?.translations),\n },\n },\n }\n }\n\n updatedConfig.onInit = async (payload) => {\n if (incomingConfig.onInit) await incomingConfig.onInit(payload)\n\n if (!isActivated) {\n payload.logger.warn(`— AI Plugin: Not activated. Please verify your environment keys.`)\n return\n }\n\n await init(payload, collectionsFieldPathMap, pluginConfig).catch((error) => {\n console.error(error)\n payload.logger.error(`— AI Plugin: Initialization Error: ${error}`)\n })\n }\n\n return updatedConfig\n }\n\nexport { payloadAiPlugin }\n"],"names":["deepMerge","zodToJsonSchema","lexicalSchema","Instructions","PLUGIN_INSTRUCTIONS_MAP_GLOBAL","PLUGIN_NAME","endpoints","init","translations","isPluginActivated","updateFieldsConfig","defaultPluginConfig","collections","generatePromptOnInit","payloadAiPlugin","pluginConfig","incomingConfig","isActivated","updatedConfig","collectionsFieldPathMap","zodLexicalSchema","editorConfig","nodes","debugging","admin","hidden","custom","schema","collectionSlugs","components","providers","updatedProviders","clientProps","path","serverProps","map","collection","slug","schemaPathMap","updatedCollectionConfig","textarea","upload","globals","access","read","fields","name","type","i18n","onInit","payload","logger","warn","catch","error","console"],"mappings":"AAEA,SAASA,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,eAAe,QAAQ,qBAAoB;AAIpD,SAASC,aAAa,QAAQ,iCAAgC;AAC9D,SAASC,YAAY,QAAQ,gCAA+B;AAC5D,SAASC,8BAA8B,EAAEC,WAAW,QAAQ,gBAAe;AAC3E,SAASC,SAAS,QAAQ,uBAAsB;AAChD,SAASC,IAAI,QAAQ,YAAW;AAChC,SAASC,YAAY,QAAQ,0BAAyB;AACtD,SAASC,iBAAiB,QAAQ,mCAAkC;AACpE,SAASC,kBAAkB,QAAQ,oCAAmC;AAEtE,MAAMC,sBAAoC;IACxCC,aAAa,CAAC;IACdC,sBAAsB;AACxB;AAEA,MAAMC,kBACJ,CAACC,eACD,CAACC;QACCD,eAAe;YAAE,GAAGJ,mBAAmB;YAAE,GAAGI,YAAY;QAAC;QACzD,MAAME,cAAcR;QACpB,IAAIS,gBAAwB;YAAE,GAAGF,cAAc;QAAC;QAChD,IAAIG,0BAA0B,CAAC;QAE/B,IAAIF,aAAa;YACf,8FAA8F;YAC9F,MAAMG,mBAAmBlB,cAAca,aAAaM,YAAY,EAAEC;YAElE,IAAIP,aAAaQ,SAAS,EAAE;gBAC1BpB,aAAaqB,KAAK,CAACC,MAAM,GAAG;YAC9B;YAEAtB,aAAaqB,KAAK,CAACE,MAAM,GAAG;gBAC1B,GAAIvB,aAAaqB,KAAK,CAACE,MAAM,IAAI,CAAC,CAAC;gBACnC,CAACrB,YA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oBAChC;wBACEL,MAAMjC;wBACNuC,QAAQ;4BACNC,MAAM,IAAM;wBACd;wBACApB,OAAO;4BACLC,QAAQ,CAACV,aAAaQ,SAAS;wBACjC;wBACAsB,QAAQ;4BACN;gCACEC,MAAM;gCACNC,MAAM;4BACR;yBACD;oBACH;iBACD;gBACDC,MAAM;oBACJ,GAAIhC,eAAegC,IAAI,IAAI,CAAC,CAAC;oBAC7BxC,cAAc;wBACZ,GAAGR,UAAUQ,cAAcQ,eAAegC,IAAI,EAAExC,aAAa;oBAC/D;gBACF;YACF;QACF;QAEAU,cAAc+B,MAAM,GAAG,OAAOC;YAC5B,IAAIlC,eAAeiC,MAAM,EAAE,MAAMjC,eAAeiC,MAAM,CAACC;YAEvD,IAAI,CAACjC,aAAa;gBAChBiC,QAAQC,MAAM,CAACC,IAAI,CAAC,CAAC,gEAAgE,CAAC;gBACtF;YACF;YAEA,MAAM7C,KAAK2C,SAAS/B,yBAAyBJ,cAAcsC,KAAK,CAAC,CAACC;gBAChEC,QAAQD,KAAK,CAACA;gBACdJ,QAAQC,MAAM,CAACG,KAAK,CAAC,CAAC,mCAAmC,EAAEA,MAAM,CAAC;YACpE;QACF;QAEA,OAAOpC;IACT;AAEF,SAASJ,eAAe,GAAE"}
1
+ {"version":3,"sources":["../src/plugin.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport { deepMerge } from 'payload/shared'\n\nimport type { PluginConfig } from './types.js'\n\nimport { lexicalJsonSchema } from './ai/schemas/lexicalJsonSchema.js'\nimport { instructionsCollection } from './collections/Instructions.js'\nimport { PLUGIN_NAME } from './defaults.js'\nimport { fetchFields } from './endpoints/fetchFields.js'\nimport { endpoints } from './endpoints/index.js'\nimport { init } from './init.js'\nimport { translations } from './translations/index.js'\nimport { isPluginActivated } from './utilities/isPluginActivated.js'\nimport { updateFieldsConfig } from './utilities/updateFieldsConfig.js'\n\nconst defaultPluginConfig: PluginConfig = {\n collections: {},\n generatePromptOnInit: true,\n}\n\nconst payloadAiPlugin =\n (pluginConfig: PluginConfig) =>\n (incomingConfig: Config): Config => {\n pluginConfig = { ...defaultPluginConfig, ...pluginConfig }\n const isActivated = isPluginActivated()\n let updatedConfig: Config = { ...incomingConfig }\n let collectionsFieldPathMap = {}\n if (isActivated) {\n const Instructions = instructionsCollection()\n // Inject editor schema to config, so that it can be accessed when /textarea endpoint will hit\n const lexicalSchema = lexicalJsonSchema(pluginConfig.editorConfig?.nodes)\n\n if (pluginConfig.debugging) {\n Instructions.admin.hidden = false\n }\n\n Instructions.admin.custom = {\n ...(Instructions.admin.custom || {}),\n [PLUGIN_NAME]: {\n editorConfig: {\n // Used in admin client for useObject hook\n schema: lexicalSchema,\n },\n },\n }\n\n const collections = [...(incomingConfig.collections ?? []), Instructions]\n const { collections: collectionSlugs = [] } = pluginConfig\n\n const { components: { providers = [] } = {} } = incomingConfig.admin || {}\n const updatedProviders = [\n ...(providers ?? []),\n {\n clientProps: {},\n path: '@ai-stack/payloadcms/client#InstructionsProvider',\n serverProps: {},\n },\n ]\n\n incomingConfig.admin = {\n ...(incomingConfig.admin || {}),\n components: {\n ...(incomingConfig.admin?.components ?? {}),\n providers: updatedProviders,\n },\n }\n\n updatedConfig = {\n ...incomingConfig,\n collections: collections.map((collection) => {\n if (collectionSlugs[collection.slug]) {\n const { schemaPathMap, updatedCollectionConfig } = updateFieldsConfig(collection)\n collectionsFieldPathMap = {\n ...collectionsFieldPathMap,\n ...schemaPathMap,\n }\n return updatedCollectionConfig\n }\n\n return collection\n }),\n endpoints: [\n ...(incomingConfig.endpoints ?? []),\n endpoints.textarea,\n endpoints.upload,\n fetchFields,\n ],\n i18n: {\n ...(incomingConfig.i18n || {}),\n translations: {\n ...deepMerge(translations, incomingConfig.i18n?.translations),\n },\n },\n }\n }\n\n updatedConfig.onInit = async (payload) => {\n if (incomingConfig.onInit) await incomingConfig.onInit(payload)\n\n if (!isActivated) {\n payload.logger.warn(`— AI Plugin: Not activated. Please verify your environment keys.`)\n return\n }\n\n await init(payload, collectionsFieldPathMap, pluginConfig).catch((error) => {\n console.error(error)\n payload.logger.error(`— AI Plugin: Initialization Error: ${error}`)\n })\n }\n\n return updatedConfig\n }\n\nexport { payloadAiPlugin }\n"],"names":["deepMerge","lexicalJsonSchema","instructionsCollection","PLUGIN_NAME","fetchFields","endpoints","init","translations","isPluginActivated","updateFieldsConfig","defaultPluginConfig","collections","generatePromptOnInit","payloadAiPlugin","pluginConfig","incomingConfig","isActivated","updatedConfig","collectionsFieldPathMap","Instructions","lexicalSchema","editorConfig","nodes","debugging","admin","hidden","custom","schema","collectionSlugs","components","providers","updatedProviders","clientProps","path","serverProps","map","collection","slug","schemaPathMap","updatedCollectionConfig","textarea","upload","i18n","onInit","payload","logger","warn","catch","error","console"],"mappings":"AAEA,SAASA,SAAS,QAAQ,iBAAgB;AAI1C,SAASC,iBAAiB,QAAQ,oCAAmC;AACrE,SAASC,sBAAsB,QAAQ,gCAA+B;AACtE,SAASC,WAAW,QAAQ,gBAAe;AAC3C,SAASC,WAAW,QAAQ,6BAA4B;AACxD,SAASC,SAAS,QAAQ,uBAAsB;AAChD,SAASC,IAAI,QAAQ,YAAW;AAChC,SAASC,YAAY,QAAQ,0BAAyB;AACtD,SAASC,iBAAiB,QAAQ,mCAAkC;AACpE,SAASC,kBAAkB,QAAQ,oCAAmC;AAEtE,MAAMC,sBAAoC;IACxCC,aAAa,CAAC;IACdC,sBAAsB;AACxB;AAEA,MAAMC,kBACJ,CAACC,eACD,CAACC;QACCD,eAAe;YAAE,GAAGJ,mBAAmB;YAAE,GAAGI,YAAY;QAAC;QACzD,MAAME,cAAcR;QACpB,IAAIS,gBAAwB;YAAE,GAAGF,cAAc;QAAC;QAChD,IAAIG,0BAA0B,CAAC;QAC/B,IAAIF,aAAa;YACf,MAAMG,eAAejB;YACrB,8FAA8F;YAC9F,MAAMkB,gBAAgBnB,kBAAkBa,aAAaO,YAAY,EAAEC;YAEnE,IAAIR,aAAaS,SAAS,EAAE;gBAC1BJ,aAAaK,K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ACZ,GAAGP,UAAUO,cAAcQ,eAAe2B,IAAI,EAAEnC,aAAa;oBAC/D;gBACF;YACF;QACF;QAEAU,cAAc0B,MAAM,GAAG,OAAOC;YAC5B,IAAI7B,eAAe4B,MAAM,EAAE,MAAM5B,eAAe4B,MAAM,CAACC;YAEvD,IAAI,CAAC5B,aAAa;gBAChB4B,QAAQC,MAAM,CAACC,IAAI,CAAC,CAAC,gEAAgE,CAAC;gBACtF;YACF;YAEA,MAAMxC,KAAKsC,SAAS1B,yBAAyBJ,cAAciC,KAAK,CAAC,CAACC;gBAChEC,QAAQD,KAAK,CAACA;gBACdJ,QAAQC,MAAM,CAACG,KAAK,CAAC,CAAC,mCAAmC,EAAEA,MAAM,CAAC;YACpE;QACF;QAEA,OAAO/B;IACT;AAEF,SAASJ,eAAe,GAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"InstructionsProvider.d.ts","sourceRoot":"","sources":["../../../src/providers/InstructionsProvider/InstructionsProvider.tsx"],"names":[],"mappings":"AAEA,OAAO,KAA6C,MAAM,OAAO,CAAA;AAQjE,eAAO,MAAM,mBAAmB;;EAAgC,CAAA;AAEhE,eAAO,MAAM,oBAAoB,EAAE,KAAK,CAAC,EAqBxC,CAAA"}
1
+ {"version":3,"file":"InstructionsProvider.d.ts","sourceRoot":"","sources":["../../../src/providers/InstructionsProvider/InstructionsProvider.tsx"],"names":[],"mappings":"AAIA,OAAO,KAA6C,MAAM,OAAO,CAAA;AAUjE,eAAO,MAAM,mBAAmB;;EAAgC,CAAA;AAEhE,eAAO,MAAM,oBAAoB,EAAE,KAAK,CAAC,EA0BxC,CAAA"}
@@ -1,20 +1,22 @@
1
1
  'use client';
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { useConfig } from '@payloadcms/ui';
3
4
  import React, { createContext, useEffect, useState } from 'react';
4
- import { PLUGIN_INSTRUCTIONS_MAP_GLOBAL } from '../../defaults.js';
5
+ import { PLUGIN_FETCH_FIELDS_ENDPOINT } from '../../defaults.js';
5
6
  const initialContext = {
6
7
  instructions: undefined
7
8
  };
8
9
  export const InstructionsContext = /*#__PURE__*/ createContext(initialContext);
9
10
  export const InstructionsProvider = ({ children })=>{
10
11
  const [instructions, setInstructionsState] = useState({});
12
+ const { config } = useConfig();
13
+ const { routes: { api }, serverURL } = config;
11
14
  // This is here because each field have separate instructions and
12
- // their ID is needed to edit them for Drawer, so instead of fetching it
13
- // one by one its map is saved in globals during build
15
+ // their ID is needed to edit them for Drawer
14
16
  useEffect(()=>{
15
- fetch(`/api/globals/${PLUGIN_INSTRUCTIONS_MAP_GLOBAL}`).then((res)=>{
16
- res.json().then((data)=>{
17
- setInstructionsState(data.map);
17
+ fetch(`${serverURL}${api}${PLUGIN_FETCH_FIELDS_ENDPOINT}`).then(async (res)=>{
18
+ await res.json().then((data)=>{
19
+ setInstructionsState(data);
18
20
  });
19
21
  }).catch((err)=>{
20
22
  console.error('InstructionsProvider:', err);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/providers/InstructionsProvider/InstructionsProvider.tsx"],"sourcesContent":["'use client'\n\nimport React, { createContext, useEffect, useState } from 'react'\n\nimport { PLUGIN_INSTRUCTIONS_MAP_GLOBAL } from '../../defaults.js'\n\nconst initialContext = {\n instructions: undefined,\n}\n\nexport const InstructionsContext = createContext(initialContext)\n\nexport const InstructionsProvider: React.FC = ({ children }: { children: React.ReactNode }) => {\n const [instructions, setInstructionsState] = useState({})\n\n // This is here because each field have separate instructions and\n // their ID is needed to edit them for Drawer, so instead of fetching it\n // one by one its map is saved in globals during build\n useEffect(() => {\n fetch(`/api/globals/${PLUGIN_INSTRUCTIONS_MAP_GLOBAL}`)\n .then((res) => {\n res.json().then((data) => {\n setInstructionsState(data.map)\n })\n })\n .catch((err) => {\n console.error('InstructionsProvider:', err)\n })\n }, [])\n\n return (\n <InstructionsContext.Provider value={{ instructions }}>{children}</InstructionsContext.Provider>\n )\n}\n"],"names":["React","createContext","useEffect","useState","PLUGIN_INSTRUCTIONS_MAP_GLOBAL","initialContext","instructions","undefined","InstructionsContext","InstructionsProvider","children","setInstructionsState","fetch","then","res","json","data","map","catch","err","console","error","Provider","value"],"mappings":"AAAA;;AAEA,OAAOA,SAASC,aAAa,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAEjE,SAASC,8BAA8B,QAAQ,oBAAmB;AAElE,MAAMC,iBAAiB;IACrBC,cAAcC;AAChB;AAEA,OAAO,MAAMC,oCAAsBP,cAAcI,gBAAe;AAEhE,OAAO,MAAMI,uBAAiC,CAAC,EAAEC,QAAQ,EAAiC;IACxF,MAAM,CAACJ,cAAcK,qBAAqB,GAAGR,SAAS,CAAC;IAEvD,iEAAiE;IACjE,wEAAwE;IACxE,sDAAsD;IACtDD,UAAU;QACRU,MAAM,CAAC,aAAa,EAAER,+BAA+B,CAAC,EACnDS,IAAI,CAAC,CAACC;YACLA,IAAIC,IAAI,GAAGF,IAAI,CAAC,CAACG;gBACfL,qBAAqBK,KAAKC,GAAG;YAC/B;QACF,GACCC,KAAK,CAAC,CAACC;YACNC,QAAQC,KAAK,CAAC,yBAAyBF;QACzC;IACJ,GAAG,EAAE;IAEL,qBACE,KAACX,oBAAoBc,QAAQ;QAACC,OAAO;YAAEjB;QAAa;kBAAII;;AAE5D,EAAC"}
1
+ {"version":3,"sources":["../../../src/providers/InstructionsProvider/InstructionsProvider.tsx"],"sourcesContent":["'use client'\n\nimport { useConfig } from '@payloadcms/ui'\nimport { getPayload } from 'payload'\nimport React, { createContext, useEffect, useState } from 'react'\n\nimport type { GenerateTextarea } from '../../types.js'\n\nimport { PLUGIN_FETCH_FIELDS_ENDPOINT } from '../../defaults.js'\n\nconst initialContext = {\n instructions: undefined,\n}\n\nexport const InstructionsContext = createContext(initialContext)\n\nexport const InstructionsProvider: React.FC = ({ children }: { children: React.ReactNode }) => {\n const [instructions, setInstructionsState] = useState({})\n\n const { config } = useConfig()\n const {\n routes: { api },\n serverURL,\n } = config\n\n // This is here because each field have separate instructions and\n // their ID is needed to edit them for Drawer\n useEffect(() => {\n fetch(`${serverURL}${api}${PLUGIN_FETCH_FIELDS_ENDPOINT}`)\n .then(async (res) => {\n await res.json().then((data) => {\n setInstructionsState(data)\n })\n })\n .catch((err) => {\n console.error('InstructionsProvider:', err)\n })\n }, [])\n\n return (\n <InstructionsContext.Provider value={{ instructions }}>{children}</InstructionsContext.Provider>\n )\n}\n"],"names":["useConfig","React","createContext","useEffect","useState","PLUGIN_FETCH_FIELDS_ENDPOINT","initialContext","instructions","undefined","InstructionsContext","InstructionsProvider","children","setInstructionsState","config","routes","api","serverURL","fetch","then","res","json","data","catch","err","console","error","Provider","value"],"mappings":"AAAA;;AAEA,SAASA,SAAS,QAAQ,iBAAgB;AAE1C,OAAOC,SAASC,aAAa,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAIjE,SAASC,4BAA4B,QAAQ,oBAAmB;AAEhE,MAAMC,iBAAiB;IACrBC,cAAcC;AAChB;AAEA,OAAO,MAAMC,oCAAsBP,cAAcI,gBAAe;AAEhE,OAAO,MAAMI,uBAAiC,CAAC,EAAEC,QAAQ,EAAiC;IACxF,MAAM,CAACJ,cAAcK,qBAAqB,GAAGR,SAAS,CAAC;IAEvD,MAAM,EAAES,MAAM,EAAE,GAAGb;IACnB,MAAM,EACJc,QAAQ,EAAEC,GAAG,EAAE,EACfC,SAAS,EACV,GAAGH;IAEJ,iEAAiE;IACjE,6CAA6C;IAC7CV,UAAU;QACRc,MAAM,CAAC,EAAED,UAAU,EAAED,IAAI,EAAEV,6BAA6B,CAAC,EACtDa,IAAI,CAAC,OAAOC;YACX,MAAMA,IAAIC,IAAI,GAAGF,IAAI,CAAC,CAACG;gBACrBT,qBAAqBS;YACvB;QACF,GACCC,KAAK,CAAC,CAACC;YACNC,QAAQC,KAAK,CAAC,yBAAyBF;QACzC;IACJ,GAAG,EAAE;IAEL,qBACE,KAACd,oBAAoBiB,QAAQ;QAACC,OAAO;YAAEpB;QAAa;kBAAII;;AAE5D,EAAC"}
@@ -1,6 +1,6 @@
1
1
  import { useContext } from 'react';
2
- import { InstructionsContext } from './InstructionsProvider.js';
3
2
  import { handlebarsHelpers, handlebarsHelpersMap } from '../../libraries/handlebars/helpersMap.js';
3
+ import { InstructionsContext } from './InstructionsProvider.js';
4
4
  export const useInstructions = ({ path })=>{
5
5
  const context = useContext(InstructionsContext);
6
6
  //Fields are used for autocompletion in PromptTextareaField
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/providers/InstructionsProvider/useInstructions.ts"],"sourcesContent":["import { useContext } from 'react'\n\nimport { InstructionsContext } from './InstructionsProvider.js'\nimport { handlebarsHelpers, handlebarsHelpersMap } from '../../libraries/handlebars/helpersMap.js'\n\nexport const useInstructions = ({ path }) => {\n const context = useContext(InstructionsContext)\n\n //Fields are used for autocompletion in PromptTextareaField\n const fields = Object.keys(context.instructions || {}).map((key) => {\n return key.split('.').slice(1).join('.')\n })\n\n const promptEditorSuggestions = [...fields].reduce((acc, f) => {\n const fieldKey = Object.keys(context.instructions).find((k) => k.endsWith(f))\n const fieldInfo = context.instructions[fieldKey]\n\n // Currently, Upload fields are excluded from suggestions\n if (fieldInfo.fieldType === 'upload') {\n return acc\n }\n\n const helpers = handlebarsHelpers.filter(\n (h) => handlebarsHelpersMap[h]?.field === fieldInfo.fieldType,\n )\n\n if (helpers.length) {\n for (const helper of helpers) {\n acc.push(helper + ` ${f}`)\n }\n return acc\n }\n\n acc.push(f)\n return acc\n }, [])\n\n return {\n ...context,\n ...(context.instructions[path] || {}),\n fields,\n map: context.instructions,\n promptEditorSuggestions,\n }\n}\n"],"names":["useContext","InstructionsContext","handlebarsHelpers","handlebarsHelpersMap","useInstructions","path","context","fields","Object","keys","instructions","map","key","split","slice","join","promptEditorSuggestions","reduce","acc","f","fieldKey","find","k","endsWith","fieldInfo","fieldType","helpers","filter","h","field","length","helper","push"],"mappings":"AAAA,SAASA,UAAU,QAAQ,QAAO;AAElC,SAASC,mBAAmB,QAAQ,4BAA2B;AAC/D,SAASC,iBAAiB,EAAEC,oBAAoB,QAAQ,2CAA0C;AAElG,OAAO,MAAMC,kBAAkB,CAAC,EAAEC,IAAI,EAAE;IACtC,MAAMC,UAAUN,WAAWC;IAE3B,2DAA2D;IAC3D,MAAMM,SAASC,OAAOC,IAAI,CAACH,QAAQI,YAAY,IAAI,CAAC,GAAGC,GAAG,CAAC,CAACC;QAC1D,OAAOA,IAAIC,KAAK,CAAC,KAAKC,KAAK,CAAC,GAAGC,IAAI,CAAC;IACtC;IAEA,MAAMC,0BAA0B;WAAIT;KAAO,CAACU,MAAM,CAAC,CAACC,KAAKC;QACvD,MAAMC,WAAWZ,OAAOC,IAAI,CAACH,QAAQI,YAAY,EAAEW,IAAI,CAAC,CAACC,IAAMA,EAAEC,QAAQ,CAACJ;QAC1E,MAAMK,YAAYlB,QAAQI,YAAY,CAACU,SAAS;QAEhD,yDAAyD;QACzD,IAAII,UAAUC,SAAS,KAAK,UAAU;YACpC,OAAOP;QACT;QAEA,MAAMQ,UAAUxB,kBAAkByB,MAAM,CACtC,CAACC,IAAMzB,oBAAoB,CAACyB,EAAE,EAAEC,UAAUL,UAAUC,SAAS;QAG/D,IAAIC,QAAQI,MAAM,EAAE;YAClB,KAAK,MAAMC,UAAUL,QAAS;gBAC5BR,IAAIc,IAAI,CAACD,SAAS,CAAC,CAAC,EAAEZ,EAAE,CAAC;YAC3B;YACA,OAAOD;QACT;QAEAA,IAAIc,IAAI,CAACb;QACT,OAAOD;IACT,GAAG,EAAE;IAEL,OAAO;QACL,GAAGZ,OAAO;QACV,GAAIA,QAAQI,YAAY,CAACL,KAAK,IAAI,CAAC,CAAC;QACpCE;QACAI,KAAKL,QAAQI,YAAY;QACzBM;IACF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../src/providers/InstructionsProvider/useInstructions.ts"],"sourcesContent":["import { useContext } from 'react'\n\nimport { handlebarsHelpers, handlebarsHelpersMap } from '../../libraries/handlebars/helpersMap.js'\nimport { InstructionsContext } from './InstructionsProvider.js'\n\nexport const useInstructions = ({ path }) => {\n const context = useContext(InstructionsContext)\n\n //Fields are used for autocompletion in PromptTextareaField\n const fields = Object.keys(context.instructions || {}).map((key) => {\n return key.split('.').slice(1).join('.')\n })\n\n const promptEditorSuggestions = [...fields].reduce((acc, f) => {\n const fieldKey = Object.keys(context.instructions).find((k) => k.endsWith(f))\n const fieldInfo = context.instructions[fieldKey]\n\n // Currently, Upload fields are excluded from suggestions\n if (fieldInfo.fieldType === 'upload') {\n return acc\n }\n\n const helpers = handlebarsHelpers.filter(\n (h) => handlebarsHelpersMap[h]?.field === fieldInfo.fieldType,\n )\n\n if (helpers.length) {\n for (const helper of helpers) {\n acc.push(helper + ` ${f}`)\n }\n return acc\n }\n\n acc.push(f)\n return acc\n }, [])\n\n return {\n ...context,\n ...(context.instructions[path] || {}),\n fields,\n map: context.instructions,\n promptEditorSuggestions,\n }\n}\n"],"names":["useContext","handlebarsHelpers","handlebarsHelpersMap","InstructionsContext","useInstructions","path","context","fields","Object","keys","instructions","map","key","split","slice","join","promptEditorSuggestions","reduce","acc","f","fieldKey","find","k","endsWith","fieldInfo","fieldType","helpers","filter","h","field","length","helper","push"],"mappings":"AAAA,SAASA,UAAU,QAAQ,QAAO;AAElC,SAASC,iBAAiB,EAAEC,oBAAoB,QAAQ,2CAA0C;AAClG,SAASC,mBAAmB,QAAQ,4BAA2B;AAE/D,OAAO,MAAMC,kBAAkB,CAAC,EAAEC,IAAI,EAAE;IACtC,MAAMC,UAAUN,WAAWG;IAE3B,2DAA2D;IAC3D,MAAMI,SAASC,OAAOC,IAAI,CAACH,QAAQI,YAAY,IAAI,CAAC,GAAGC,GAAG,CAAC,CAACC;QAC1D,OAAOA,IAAIC,KAAK,CAAC,KAAKC,KAAK,CAAC,GAAGC,IAAI,CAAC;IACtC;IAEA,MAAMC,0BAA0B;WAAIT;KAAO,CAACU,MAAM,CAAC,CAACC,KAAKC;QACvD,MAAMC,WAAWZ,OAAOC,IAAI,CAACH,QAAQI,YAAY,EAAEW,IAAI,CAAC,CAACC,IAAMA,EAAEC,QAAQ,CAACJ;QAC1E,MAAMK,YAAYlB,QAAQI,YAAY,CAACU,SAAS;QAEhD,yDAAyD;QACzD,IAAII,UAAUC,SAAS,KAAK,UAAU;YACpC,OAAOP;QACT;QAEA,MAAMQ,UAAUzB,kBAAkB0B,MAAM,CACtC,CAACC,IAAM1B,oBAAoB,CAAC0B,EAAE,EAAEC,UAAUL,UAAUC,SAAS;QAG/D,IAAIC,QAAQI,MAAM,EAAE;YAClB,KAAK,MAAMC,UAAUL,QAAS;gBAC5BR,IAAIc,IAAI,CAACD,SAAS,CAAC,CAAC,EAAEZ,EAAE,CAAC;YAC3B;YACA,OAAOD;QACT;QAEAA,IAAIc,IAAI,CAACb;QACT,OAAOD;IACT,GAAG,EAAE;IAEL,OAAO;QACL,GAAGZ,OAAO;QACV,GAAIA,QAAQI,YAAY,CAACL,KAAK,IAAI,CAAC,CAAC;QACpCE;QACAI,KAAKL,QAAQI,YAAY;QACzBM;IACF;AACF,EAAC"}
package/dist/types.d.ts CHANGED
@@ -1,13 +1,13 @@
1
+ import type { JSONSchema } from 'openai/lib/jsonschema';
1
2
  import type { Endpoint, Field, GroupField } from 'payload';
2
3
  import type { CSSProperties, MouseEventHandler } from 'react';
3
- import type { LexicalBaseNode } from './ai/schemas/lexical.schema.js';
4
4
  export interface PluginConfig {
5
5
  collections: {
6
6
  [key: string]: boolean;
7
7
  };
8
8
  debugging?: boolean;
9
9
  editorConfig?: {
10
- nodes: (typeof LexicalBaseNode)[];
10
+ nodes: JSONSchema[];
11
11
  };
12
12
  fields?: Field[];
13
13
  generatePromptOnInit?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAc,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACtE,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,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AAC,CAAC,GAAG,SAAS,CAAA;IAC/C,KAAK,CAAC,EAAE,aAAa,GAAG,SAAS,CAAA;CAClC,CAAA"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { Collection, Endpoint, Field, GroupField } from 'payload'\nimport type { CSSProperties, MouseEventHandler } from 'react'\n\nimport type { LexicalBaseNode } from './ai/schemas/lexical.schema.js'\n\nexport interface PluginConfig {\n collections: {\n [key: string]: boolean\n }\n debugging?: boolean\n editorConfig?: { nodes: (typeof LexicalBaseNode)[] }\n fields?: Field[]\n generatePromptOnInit?: boolean\n globals?: string[]\n interfaceName?: string\n}\n\nexport interface GenerationModel {\n fields: string[]\n handler?: (payload: any, options: any) => Promise<any>\n id: string\n name: string\n output: 'audio' | 'file' | 'image' | 'json' | 'text' | 'video'\n settings?: GroupField\n supportsPromptOptimization?: boolean\n}\n\nexport interface GenerationConfig {\n models: GenerationModel[]\n provider: string\n}\n\nexport type GenerateTextarea<T = any> = (args: {\n doc: T\n locale?: string\n options?: any\n}) => Promise<string> | string\n\nexport interface Instructions {\n 'collection-slug': string\n id: string\n 'model-id': string\n prompt: string\n}\n\nexport interface Endpoints {\n textarea: Omit<Endpoint, 'root'>\n upload: Omit<Endpoint, 'root'>\n}\n\nexport type ActionMenuItems =\n | 'Compose'\n | 'Expand'\n | 'Proofread'\n | 'Rephrase'\n | 'Settings'\n | 'Simplify'\n | 'Summarize'\n | 'Tone'\n | 'Translate'\n\nexport type ActionMenuEvents =\n | 'onCompose'\n | 'onExpand'\n | 'onProofread'\n | 'onRephrase'\n | 'onSettings'\n | 'onSimplify'\n | 'onSummarize'\n | 'onTone'\n | 'onTranslate'\n\nexport type UseMenuEvents = {\n [key in ActionMenuEvents]?: (data?: unknown) => void\n}\n\nexport type BaseItemProps<T = any> = {\n children?: React.ReactNode\n disabled?: boolean\n hideIcon?: boolean\n isActive?: boolean\n isMenu?: boolean\n onClick: (data?: unknown) => void\n onMouseEnter?: MouseEventHandler<T> | undefined\n onMouseLeave?: MouseEventHandler<T> | undefined\n style?: CSSProperties | undefined\n}\n"],"names":[],"mappings":"AA4EA,WAUC"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { JSONSchema } from 'openai/lib/jsonschema'\nimport type { Endpoint, Field, GroupField } from 'payload'\nimport type { CSSProperties, MouseEventHandler } from 'react'\n\n\nexport interface PluginConfig {\n collections: {\n [key: string]: boolean\n }\n debugging?: boolean\n editorConfig?: { nodes: JSONSchema[] }\n fields?: Field[]\n generatePromptOnInit?: boolean\n globals?: string[]\n interfaceName?: string\n}\n\nexport interface GenerationModel {\n fields: string[]\n handler?: (payload: any, options: any) => Promise<any>\n id: string\n name: string\n output: 'audio' | 'file' | 'image' | 'json' | 'text' | 'video'\n settings?: GroupField\n supportsPromptOptimization?: boolean\n}\n\nexport interface GenerationConfig {\n models: GenerationModel[]\n provider: string\n}\n\nexport type GenerateTextarea<T = any> = (args: {\n doc: T\n locale?: string\n options?: any\n}) => Promise<string> | string\n\nexport interface Instructions {\n 'collection-slug': string\n id: string\n 'model-id': string\n prompt: string\n}\n\nexport interface Endpoints {\n textarea: Omit<Endpoint, 'root'>\n upload: Omit<Endpoint, 'root'>\n}\n\nexport type ActionMenuItems =\n | 'Compose'\n | 'Expand'\n | 'Proofread'\n | 'Rephrase'\n | 'Settings'\n | 'Simplify'\n | 'Summarize'\n | 'Tone'\n | 'Translate'\n\nexport type ActionMenuEvents =\n | 'onCompose'\n | 'onExpand'\n | 'onProofread'\n | 'onRephrase'\n | 'onSettings'\n | 'onSimplify'\n | 'onSummarize'\n | 'onTone'\n | 'onTranslate'\n\nexport type UseMenuEvents = {\n [key in ActionMenuEvents]?: (data?: unknown) => void\n}\n\nexport type BaseItemProps<T = any> = {\n children?: React.ReactNode\n disabled?: boolean\n hideIcon?: boolean\n isActive?: boolean\n isMenu?: boolean\n onClick: (data?: unknown) => void\n onMouseEnter?: MouseEventHandler<T> | undefined\n onMouseLeave?: MouseEventHandler<T> | undefined\n style?: CSSProperties | undefined\n}\n"],"names":[],"mappings":"AA4EA,WAUC"}
@@ -1 +1 @@
1
- {"version":3,"file":"Compose.d.ts","sourceRoot":"","sources":["../../../src/ui/Compose/Compose.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,SAAS,CAAA;AAC1D,OAAO,KAAK,EAAE,EAAE,EAAC,MAAM,OAAO,CAAC;AA6B/B,KAAK,YAAY,GAAG;IAClB,gBAAgB,CAAC,EAAE,2BAA2B,CAAA;IAC9C,aAAa,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,eAAO,MAAM,OAAO,EAAE,EAAE,CAAC,YAAY,CAqJpC,CAAA"}
1
+ {"version":3,"file":"Compose.d.ts","sourceRoot":"","sources":["../../../src/ui/Compose/Compose.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,SAAS,CAAA;AAC1D,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,OAAO,CAAA;AA6B/B,KAAK,YAAY,GAAG;IAClB,gBAAgB,CAAC,EAAE,2BAA2B,CAAA;IAC9C,aAAa,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,eAAO,MAAM,OAAO,EAAE,EAAE,CAAC,YAAY,CAwJpC,CAAA"}
@@ -22,9 +22,11 @@ function findParentWithClass(element, className) {
22
22
  // Recursively call the function on the parent element
23
23
  return findParentWithClass(element.parentElement, className);
24
24
  }
25
- export const Compose = (props)=>{
25
+ export const Compose = ({ descriptionProps, instructionId })=>{
26
+ // Disable Component if no instructionId is provided
27
+ if (!instructionId) return null;
26
28
  const [DocumentDrawer, _, { closeDrawer, openDrawer }] = useDocumentDrawer({
27
- id: props.instructionId,
29
+ id: instructionId,
28
30
  collectionSlug: PLUGIN_INSTRUCTIONS_TABLE
29
31
  });
30
32
  const { type: fieldType, path: pathFromContext, schemaPath } = useFieldProps();
@@ -165,9 +167,9 @@ export const Compose = (props)=>{
165
167
  })
166
168
  ]
167
169
  }),
168
- props.descriptionProps ? /*#__PURE__*/ _jsx("div", {
170
+ descriptionProps ? /*#__PURE__*/ _jsx("div", {
169
171
  children: /*#__PURE__*/ _jsx(FieldDescription, {
170
- ...props.descriptionProps
172
+ ...descriptionProps
171
173
  })
172
174
  }) : null
173
175
  ]
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/ui/Compose/Compose.tsx"],"sourcesContent":["'use client'\n\nimport type { FieldDescriptionClientProps } from 'payload'\nimport type { FC} from 'react';\n\nimport { useEditorConfigContext } from '@payloadcms/richtext-lexical/client'\nimport { FieldDescription, Popup, useDocumentDrawer, useField, useFieldProps } from '@payloadcms/ui'\nimport React, { useCallback, useEffect, useRef, useState } from 'react'\n\nimport { PLUGIN_INSTRUCTIONS_TABLE } from '../../defaults.js'\nimport { setSafeLexicalState } from '../../utilities/setSafeLexicalState.js'\nimport { PluginIcon } from '../Icons/Icons.js'\nimport { UndoRedoActions } from './UndoRedoActions.js'\nimport styles from './compose.module.scss'\nimport { useMenu } from './hooks/menu/useMenu.js'\nimport { useGenerate } from './hooks/useGenerate.js'\n\nfunction findParentWithClass(element, className) {\n // Base case: if the element is null or we've reached the top of the DOM\n if (!element || element === document.body) {\n return null\n }\n\n // Check if the current element has the class we're looking for\n if (element.classList.contains(className)) {\n return element\n }\n\n // Recursively call the function on the parent element\n return findParentWithClass(element.parentElement, className)\n}\n\ntype ComposeProps = {\n descriptionProps?: FieldDescriptionClientProps\n instructionId: string\n}\n\nexport const Compose: FC<ComposeProps> = (props) => {\n const [DocumentDrawer, _, { closeDrawer, openDrawer }] = useDocumentDrawer({\n id: props.instructionId,\n collectionSlug: PLUGIN_INSTRUCTIONS_TABLE,\n })\n\n const { type: fieldType, path: pathFromContext, schemaPath } = useFieldProps()\n const { editor: lexicalEditor, editorContainerRef } = useEditorConfigContext()\n\n // Below snippet is used to show/hide the actions menu on AI enabled fields\n const [input, setInput] = useState(null)\n const actionsRef = useRef(null)\n\n // Set input element for current field\n useEffect(() => {\n if (!actionsRef.current) return\n\n const fieldId = `field-${pathFromContext.replace(/\\./g, '__')}`\n const inputElement = document.getElementById(fieldId)\n\n if (!inputElement && fieldType === 'richText') {\n setInput(editorContainerRef.current)\n } else {\n actionsRef.current.setAttribute('for', fieldId)\n setInput(inputElement)\n }\n }, [pathFromContext, schemaPath, actionsRef, editorContainerRef])\n\n // Show or hide actions menu on field\n useEffect(() => {\n if (!input || !actionsRef.current) return\n\n actionsRef.current.classList.add(styles.actions_hidden)\n input.addEventListener('click', (event) => {\n document.querySelectorAll('.ai-plugin-active')?.forEach((element) => {\n const actionElement = element.querySelector(`.${styles.actions}`)\n if (actionElement) {\n actionElement.classList.add(styles.actions_hidden)\n element.classList.remove('ai-plugin-active')\n }\n })\n\n actionsRef.current.classList.remove(styles.actions_hidden)\n const parentWithClass = findParentWithClass(event.target, 'field-type')\n parentWithClass.classList.add('ai-plugin-active')\n })\n }, [input, actionsRef])\n\n const [isProcessing, setIsProcessing] = useState(false)\n const { generate, isLoading } = useGenerate()\n\n const { ActiveComponent, Menu } = useMenu({\n onCompose: async () => {\n console.log('Composing...')\n setIsProcessing(true)\n await generate({\n action: 'Compose',\n }).finally(() => {\n setIsProcessing(false)\n })\n },\n onExpand: async () => {\n console.log('Expanding...')\n await generate({\n action: 'Expand',\n })\n },\n onProofread: async () => {\n console.log('Proofreading...')\n await generate({\n action: 'Proofread',\n })\n },\n onRephrase: async () => {\n console.log('Rephrasing...')\n await generate({\n action: 'Rephrase',\n })\n },\n onSettings: openDrawer,\n onSimplify: async () => {\n console.log('Simplifying...')\n await generate({\n action: 'Simplify',\n })\n },\n onSummarize: async () => {\n console.log('Summarizing...')\n await generate({\n action: 'Summarize',\n })\n },\n onTranslate: async (data) => {\n console.log('Translating...')\n await generate({\n action: 'Translate',\n params: data,\n })\n },\n })\n\n const { setValue } = useField<string>({\n path: pathFromContext,\n })\n\n const setIfValueIsLexicalState = useCallback((val: any) => {\n if (val.root && lexicalEditor) {\n setSafeLexicalState(JSON.stringify(val), lexicalEditor)\n }\n\n // DO NOT PROVIDE lexicalEditor as a dependency, it freaks out and does not update the editor after first undo/redo\n }, [])\n\n return (\n <React.Fragment>\n <label\n className={`${styles.actions}`}\n onClick={(e) => e.preventDefault()}\n ref={actionsRef}\n role=\"presentation\"\n >\n <DocumentDrawer\n onSave={() => {\n closeDrawer()\n }}\n />\n <Popup\n button={<PluginIcon isLoading={isProcessing || isLoading} />}\n render={({ close }) => {\n return <Menu isLoading={isProcessing || isLoading} onClose={close} />\n }}\n verticalAlign=\"bottom\"\n />\n <ActiveComponent isLoading={isProcessing || isLoading} />\n <UndoRedoActions\n onChange={(val) => {\n setValue(val)\n setIfValueIsLexicalState(val)\n }}\n />\n </label>\n {/*Render incoming description field*/}\n {props.descriptionProps ? (\n <div>\n <FieldDescription {...props.descriptionProps} />\n </div>\n ) : null}\n </React.Fragment>\n )\n}\n"],"names":["useEditorConfigContext","FieldDescription","Popup","useDocumentDrawer","useField","useFieldProps","React","useCallback","useEffect","useRef","useState","PLUGIN_INSTRUCTIONS_TABLE","setSafeLexicalState","PluginIcon","UndoRedoActions","styles","useMenu","useGenerate","findParentWithClass","element","className","document","body","classList","contains","parentElement","Compose","props","DocumentDrawer","_","closeDrawer","openDrawer","id","instructionId","collectionSlug","type","fieldType","path","pathFromContext","schemaPath","editor","lexicalEditor","editorContainerRef","input","setInput","actionsRef","current","fieldId","replace","inputElement","getElementById","setAttribute","add","actions_hidden","addEventListener","event","querySelectorAll","forEach","actionElement","querySelector","actions","remove","parentWithClass","target","isProcessing","setIsProcessing","generate","isLoading","ActiveComponent","Menu","onCompose","console","log","action","finally","onExpand","onProofread","onRephrase","onSettings","onSimplify","onSummarize","onTranslate","data","params","setValue","setIfValueIsLexicalState","val","root","JSON","stringify","Fragment","label","onClick","e","preventDefault","ref","role","onSave","button","render","close","onClose","verticalAlign","onChange","descriptionProps","div"],"mappings":"AAAA;;AAKA,SAASA,sBAAsB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;wBAAgBD,WAAWH,gBAAgBG;;kCAC5C,KAACrD;wBACCyF,UAAU,CAACjB;4BACTF,SAASE;4BACTD,yBAAyBC;wBAC3B;;;;YAIH3D,MAAM6E,gBAAgB,iBACrB,KAACC;0BACC,cAAA,KAACxG;oBAAkB,GAAG0B,MAAM6E,gBAAgB;;iBAE5C;;;AAGV,EAAC"}
1
+ {"version":3,"sources":["../../../src/ui/Compose/Compose.tsx"],"sourcesContent":["'use client'\n\nimport type { FieldDescriptionClientProps } from 'payload'\nimport type { FC } from 'react'\n\nimport { useEditorConfigContext } from '@payloadcms/richtext-lexical/client'\nimport { FieldDescription, Popup, useDocumentDrawer, useField, useFieldProps } from '@payloadcms/ui'\nimport React, { useCallback, useEffect, useRef, useState } from 'react'\n\nimport { PLUGIN_INSTRUCTIONS_TABLE } from '../../defaults.js'\nimport { setSafeLexicalState } from '../../utilities/setSafeLexicalState.js'\nimport { PluginIcon } from '../Icons/Icons.js'\nimport { UndoRedoActions } from './UndoRedoActions.js'\nimport styles from './compose.module.scss'\nimport { useMenu } from './hooks/menu/useMenu.js'\nimport { useGenerate } from './hooks/useGenerate.js'\n\nfunction findParentWithClass(element, className) {\n // Base case: if the element is null or we've reached the top of the DOM\n if (!element || element === document.body) {\n return null\n }\n\n // Check if the current element has the class we're looking for\n if (element.classList.contains(className)) {\n return element\n }\n\n // Recursively call the function on the parent element\n return findParentWithClass(element.parentElement, className)\n}\n\ntype ComposeProps = {\n descriptionProps?: FieldDescriptionClientProps\n instructionId: string\n}\n\nexport const Compose: FC<ComposeProps> = ({ descriptionProps, instructionId }) => {\n // Disable Component if no instructionId is provided\n if (!instructionId) return null\n\n const [DocumentDrawer, _, { closeDrawer, openDrawer }] = useDocumentDrawer({\n id: instructionId,\n collectionSlug: PLUGIN_INSTRUCTIONS_TABLE,\n })\n\n const { type: fieldType, path: pathFromContext, schemaPath } = useFieldProps()\n const { editor: lexicalEditor, editorContainerRef } = useEditorConfigContext()\n\n // Below snippet is used to show/hide the actions menu on AI enabled fields\n const [input, setInput] = useState(null)\n const actionsRef = useRef(null)\n\n // Set input element for current field\n useEffect(() => {\n if (!actionsRef.current) return\n\n const fieldId = `field-${pathFromContext.replace(/\\./g, '__')}`\n const inputElement = document.getElementById(fieldId)\n\n if (!inputElement && fieldType === 'richText') {\n setInput(editorContainerRef.current)\n } else {\n actionsRef.current.setAttribute('for', fieldId)\n setInput(inputElement)\n }\n }, [pathFromContext, schemaPath, actionsRef, editorContainerRef])\n\n // Show or hide actions menu on field\n useEffect(() => {\n if (!input || !actionsRef.current) return\n\n actionsRef.current.classList.add(styles.actions_hidden)\n input.addEventListener('click', (event) => {\n document.querySelectorAll('.ai-plugin-active')?.forEach((element) => {\n const actionElement = element.querySelector(`.${styles.actions}`)\n if (actionElement) {\n actionElement.classList.add(styles.actions_hidden)\n element.classList.remove('ai-plugin-active')\n }\n })\n\n actionsRef.current.classList.remove(styles.actions_hidden)\n const parentWithClass = findParentWithClass(event.target, 'field-type')\n parentWithClass.classList.add('ai-plugin-active')\n })\n }, [input, actionsRef])\n\n const [isProcessing, setIsProcessing] = useState(false)\n const { generate, isLoading } = useGenerate()\n\n const { ActiveComponent, Menu } = useMenu({\n onCompose: async () => {\n console.log('Composing...')\n setIsProcessing(true)\n await generate({\n action: 'Compose',\n }).finally(() => {\n setIsProcessing(false)\n })\n },\n onExpand: async () => {\n console.log('Expanding...')\n await generate({\n action: 'Expand',\n })\n },\n onProofread: async () => {\n console.log('Proofreading...')\n await generate({\n action: 'Proofread',\n })\n },\n onRephrase: async () => {\n console.log('Rephrasing...')\n await generate({\n action: 'Rephrase',\n })\n },\n onSettings: openDrawer,\n onSimplify: async () => {\n console.log('Simplifying...')\n await generate({\n action: 'Simplify',\n })\n },\n onSummarize: async () => {\n console.log('Summarizing...')\n await generate({\n action: 'Summarize',\n })\n },\n onTranslate: async (data) => {\n console.log('Translating...')\n await generate({\n action: 'Translate',\n params: data,\n })\n },\n })\n\n const { setValue } = useField<string>({\n path: pathFromContext,\n })\n\n const setIfValueIsLexicalState = useCallback((val: any) => {\n if (val.root && lexicalEditor) {\n setSafeLexicalState(JSON.stringify(val), lexicalEditor)\n }\n\n // DO NOT PROVIDE lexicalEditor as a dependency, it freaks out and does not update the editor after first undo/redo\n }, [])\n\n return (\n <React.Fragment>\n <label\n className={`${styles.actions}`}\n onClick={(e) => e.preventDefault()}\n ref={actionsRef}\n role=\"presentation\"\n >\n <DocumentDrawer\n onSave={() => {\n closeDrawer()\n }}\n />\n <Popup\n button={<PluginIcon isLoading={isProcessing || isLoading} />}\n render={({ close }) => {\n return <Menu isLoading={isProcessing || isLoading} onClose={close} />\n }}\n verticalAlign=\"bottom\"\n />\n <ActiveComponent isLoading={isProcessing || isLoading} />\n <UndoRedoActions\n onChange={(val) => {\n setValue(val)\n setIfValueIsLexicalState(val)\n }}\n />\n </label>\n {/*Render incoming description field*/}\n {descriptionProps ? (\n <div>\n <FieldDescription {...descriptionProps} />\n </div>\n ) : null}\n </React.Fragment>\n )\n}\n"],"names":["useEditorConfigContext","FieldDescription","Popup","useDocumentDrawer","useField","useFieldProps","React","useCallback","useEffect","useRef","useState","PLUGIN_INSTRUCTIONS_TABLE","setSafeLexicalState","PluginIcon","UndoRedoActions","styles","useMenu","useGenerate","findParentWithClass","element","className","document","body","classList","contains","parentElement","Compose","descriptionProps","instructionId","DocumentDrawer","_","closeDrawer","openDrawer","id","collectionSlug","type","fieldType","path","pathFromContext","schemaPath","editor","lexicalEditor","editorContainerRef","input","setInput","actionsRef","current","fieldId","replace","inputElement","getElementById","setAttribute","add","actions_hidden","addEventListener","event","querySelectorAll","forEach","actionElement","querySelector","actions","remove","parentWithClass","target","isProcessing","setIsProcessing","generate","isLoading","ActiveComponent","Menu","onCompose","console","log","action","finally","onExpand","onProofread","onRephrase","onSettings","onSimplify","onSummarize","onTranslate","data","params","setValue","setIfValueIsLexicalState","val","root","JSON","stringify","Fragment","label","onClick","e","preventDefault","ref","role","onSave","button","render","close","onClose","verticalAlign","onChange","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AE;4BAChB,qBAAO,KAAC/B;gCAAKF,WAAWH,gBAAgBG;gCAAWkC,SAASD;;wBAC9D;wBACAE,eAAc;;kCAEhB,KAAClC;wBAAgBD,WAAWH,gBAAgBG;;kCAC5C,KAACrD;wBACCyF,UAAU,CAACjB;4BACTF,SAASE;4BACTD,yBAAyBC;wBAC3B;;;;YAIH3D,iCACC,KAAC6E;0BACC,cAAA,KAACvG;oBAAkB,GAAG0B,gBAAgB;;iBAEtC;;;AAGV,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"useGenerate.d.ts","sourceRoot":"","sources":["../../../../src/ui/Compose/hooks/useGenerate.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,eAAe,EAAoB,MAAM,mBAAmB,CAAA;AAa1E,KAAK,oBAAoB,GAAG;IAAE,MAAM,EAAE,eAAe,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,CAAA;AAGzE,eAAO,MAAM,WAAW;yBAuKH,oBAAoB;;CAoBxC,CAAA"}
1
+ {"version":3,"file":"useGenerate.d.ts","sourceRoot":"","sources":["../../../../src/ui/Compose/hooks/useGenerate.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAoB,MAAM,mBAAmB,CAAA;AAY1E,KAAK,oBAAoB,GAAG;IAAE,MAAM,EAAE,eAAe,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,CAAA;AAEzE,eAAO,MAAM,WAAW;yBAsKH,oBAAoB;;CAoBxC,CAAA"}
@@ -1,19 +1,18 @@
1
1
  import { useEditorConfigContext } from '@payloadcms/richtext-lexical/client';
2
- import { useConfig, useDocumentInfo, useField, useFieldProps, useForm, useLocale } from '@payloadcms/ui';
2
+ import { useConfig, useField, useFieldProps, useForm, useLocale } from '@payloadcms/ui';
3
+ import { jsonSchema } from 'ai';
3
4
  import { useCompletion, experimental_useObject as useObject } from 'ai/react';
4
- import { useCallback, useEffect } from 'react';
5
- import { PLUGIN_API_ENDPOINT_GENERATE, PLUGIN_API_ENDPOINT_GENERATE_UPLOAD, PLUGIN_INSTRUCTIONS_TABLE } from '../../../defaults.js';
5
+ import { useCallback, useEffect, useMemo } from 'react';
6
+ import { PLUGIN_API_ENDPOINT_GENERATE, PLUGIN_API_ENDPOINT_GENERATE_UPLOAD, PLUGIN_INSTRUCTIONS_TABLE, PLUGIN_NAME } from '../../../defaults.js';
6
7
  import { useInstructions } from '../../../providers/InstructionsProvider/useInstructions.js';
7
- import { getFieldBySchemaPath } from '../../../utilities/getFieldBySchemaPath.js';
8
- import { jsonSchemaToZod } from '../../../utilities/jsonToZod.js';
9
8
  import { setSafeLexicalState } from '../../../utilities/setSafeLexicalState.js';
10
9
  import { useHistory } from './useHistory.js';
11
- //TODO: DONATION IDEA - Add a url to donate in cli when user installs the plugin and uses it for couple of times.
12
10
  export const useGenerate = ()=>{
13
11
  const { type, path: pathFromContext, schemaPath } = useFieldProps();
14
12
  const editorConfigContext = useEditorConfigContext();
15
13
  const { editor } = editorConfigContext;
16
- const { docConfig } = useDocumentInfo();
14
+ const { config } = useConfig();
15
+ const { routes: { api }, serverURL } = config;
17
16
  const { setValue } = useField({
18
17
  path: pathFromContext
19
18
  });
@@ -25,9 +24,11 @@ export const useGenerate = ()=>{
25
24
  const localFromContext = useLocale();
26
25
  const { config: { collections } } = useConfig();
27
26
  const collection = collections.find((collection)=>collection.slug === PLUGIN_INSTRUCTIONS_TABLE);
28
- const { custom: { editorConfig } = {} } = collection.admin;
29
- const { schema: DocumentSchema = {} } = editorConfig || {};
30
- const lexicalZodSchema = jsonSchemaToZod(DocumentSchema);
27
+ const { custom: { [PLUGIN_NAME]: { editorConfig = {} } = {} } = {} } = collection.admin;
28
+ const { schema: editorSchema = {} } = editorConfig;
29
+ const memoizedSchema = useMemo(()=>jsonSchema(editorSchema), [
30
+ editorSchema
31
+ ]);
31
32
  const { isLoading: loadingObject, object, stop, submit } = useObject({
32
33
  api: `/api${PLUGIN_API_ENDPOINT_GENERATE}`,
33
34
  onError: (error)=>{
@@ -41,7 +42,7 @@ export const useGenerate = ()=>{
41
42
  console.log('onFinish: result ', result);
42
43
  }
43
44
  },
44
- schema: lexicalZodSchema
45
+ schema: memoizedSchema
45
46
  });
46
47
  useEffect(()=>{
47
48
  if (!object) return;
@@ -57,7 +58,7 @@ export const useGenerate = ()=>{
57
58
  object
58
59
  ]);
59
60
  const { complete, completion, isLoading: loadingCompletion } = useCompletion({
60
- api: `/api${PLUGIN_API_ENDPOINT_GENERATE}`,
61
+ api: `${serverURL}${api}${PLUGIN_API_ENDPOINT_GENERATE}`,
61
62
  onError: (error)=>{
62
63
  console.error('Error generating text:', error);
63
64
  },
@@ -112,14 +113,12 @@ export const useGenerate = ()=>{
112
113
  ]);
113
114
  const generateUpload = useCallback(async ()=>{
114
115
  const doc = getData();
115
- const fieldInfo = getFieldBySchemaPath(docConfig, schemaPath);
116
- return fetch(`/api${PLUGIN_API_ENDPOINT_GENERATE_UPLOAD}`, {
116
+ return fetch(`${serverURL}${api}${PLUGIN_API_ENDPOINT_GENERATE_UPLOAD}`, {
117
117
  body: JSON.stringify({
118
118
  doc,
119
119
  locale: localFromContext?.code,
120
120
  options: {
121
- instructionId,
122
- uploadCollectionSlug: fieldInfo.relationTo || 'media'
121
+ instructionId
123
122
  }
124
123
  }),
125
124
  credentials: 'include',