@rebasepro/plugin-data-enhancement 0.4.0 → 0.5.0

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 (31) hide show
  1. package/README.md +70 -78
  2. package/dist/admin/src/collection_editor/ui/collection_editor/PropertyEditView.d.ts +1 -0
  3. package/dist/admin/src/collection_editor/ui/collection_editor/templates/blog_template.d.ts +1 -1
  4. package/dist/admin/src/collection_editor/ui/collection_editor/templates/pages_template.d.ts +1 -1
  5. package/dist/admin/src/collection_editor/ui/collection_editor/templates/products_template.d.ts +1 -1
  6. package/dist/admin/src/collection_editor/ui/collection_editor/templates/users_template.d.ts +1 -1
  7. package/dist/common/src/util/permissions.d.ts +14 -6
  8. package/dist/index.es.js.map +1 -1
  9. package/dist/index.umd.js.map +1 -1
  10. package/dist/plugin-data-enhancement/src/components/DataEnhancementControllerProvider.d.ts +3 -3
  11. package/dist/plugin-data-enhancement/src/components/FormEnhanceAction.d.ts +0 -8
  12. package/dist/types/src/types/backend.d.ts +36 -1
  13. package/dist/types/src/types/collections.d.ts +21 -1
  14. package/dist/types/src/types/properties.d.ts +0 -8
  15. package/package.json +7 -7
  16. package/src/components/DataEnhancementControllerProvider.tsx +2 -2
  17. package/src/components/FormEnhanceAction.tsx +0 -9
  18. package/dist/plugin-data-enhancement/src/locales/de.d.ts +0 -21
  19. package/dist/plugin-data-enhancement/src/locales/en.d.ts +0 -21
  20. package/dist/plugin-data-enhancement/src/locales/es.d.ts +0 -21
  21. package/dist/plugin-data-enhancement/src/locales/fr.d.ts +0 -21
  22. package/dist/plugin-data-enhancement/src/locales/hi.d.ts +0 -21
  23. package/dist/plugin-data-enhancement/src/locales/it.d.ts +0 -21
  24. package/dist/plugin-data-enhancement/src/locales/pt.d.ts +0 -21
  25. package/src/locales/de.ts +0 -21
  26. package/src/locales/en.ts +0 -21
  27. package/src/locales/es.ts +0 -21
  28. package/src/locales/fr.ts +0 -21
  29. package/src/locales/hi.ts +0 -21
  30. package/src/locales/it.ts +0 -21
  31. package/src/locales/pt.ts +0 -21
package/README.md CHANGED
@@ -1,89 +1,81 @@
1
- ## Rebase Data enhancement plugin
1
+ # @rebasepro/plugin-data-enhancement
2
2
 
3
- This plugin allows you to enhance data in your [Rebase](https://rebase.pro)
4
- project, using ChatGPT.
3
+ AI-powered data autofill and text autocomplete plugin for Rebase.
5
4
 
6
- The ChatGPT plugin allows you to use the OpenAI API to generate content using
7
- the latest GPT models. This plugin is able to understand the structure of your
8
- data and generate content that fits your schema.
5
+ ## Installation
9
6
 
10
- <p align="center">
11
- <img src="https://rebase.pro/img/data_enhancement.png" width="800px" alt="Data enhancement UI" />
12
- </p>
7
+ ```bash
8
+ pnpm add @rebasepro/plugin-data-enhancement
9
+ ```
10
+
11
+ **Peer dependencies:** `react >= 19.0.0`, `react-dom >= 19.0.0`, `react-router >= 6.28.0`, `react-router-dom >= 6.28.0`
12
+
13
+ ## What This Package Does
14
+
15
+ This plugin adds AI-powered capabilities to the Rebase admin panel:
16
+
17
+ - **Form autofill** — An "Enhance" action button injected into entity forms that uses AI to suggest and fill field values based on collection schema and existing data.
18
+ - **Editor autocomplete** — A streaming text autocomplete controller for rich text editors, powered by an AI backend.
19
+
20
+ It registers as a standard `RebasePlugin`, injecting UI slots and providers automatically.
13
21
 
14
- In order to be able to use this plugin you need to have a valid subscription.
22
+ ## Key Exports
15
23
 
16
- You can get a subscription in
17
- the [Rebase dashboard](https://app.rebase.pro/subscriptions).
24
+ | Export | Type | Description |
25
+ |---|---|---|
26
+ | `useDataEnhancementPlugin` | Hook | Creates the plugin. Returns a `RebasePlugin` to pass to your app's `plugins` array |
27
+ | `DataEnhancementPluginProps` | Type | Configuration options for the plugin |
28
+ | `useEditorAIController` | Hook | Returns an `EditorAIController` with a streaming `autocomplete` method for rich text editors |
18
29
 
19
- You need to specify the Firebase project id you would like to use the plugin
20
- with,
21
- in the website. And that's it!
30
+ ### `DataEnhancementPluginProps`
22
31
 
23
- No need to add any subscription key or anything like that.
32
+ | Prop | Type | Default | Description |
33
+ |---|---|---|---|
34
+ | `apiKey` | `string` | Built-in default key | API key for the data enhancement service |
35
+ | `getConfigForPath` | `(props: { path, collection, user }) => boolean` | — | Return `false` to disable enhancement for specific paths |
36
+ | `host` | `string` | — | Custom API host (development only) |
37
+
38
+ ## Quick Start
39
+
40
+ ```tsx
41
+ import { useDataEnhancementPlugin } from "@rebasepro/plugin-data-enhancement";
42
+
43
+ // In your app setup:
44
+ const dataEnhancementPlugin = useDataEnhancementPlugin({
45
+ getConfigForPath: ({ path, collection }) => {
46
+ // Disable for certain collections
47
+ return collection.name !== "system_logs";
48
+ }
49
+ });
50
+
51
+ // Pass to your Rebase app:
52
+ <RebaseFirebaseApp
53
+ plugins={[dataEnhancementPlugin]}
54
+ // ...other props
55
+ />
56
+ ```
57
+
58
+ ### Editor AI Autocomplete
24
59
 
25
60
  ```tsx
26
- import React from "react";
27
- import { Rebase } from "@rebasepro/core";
28
- import "@fontsource/rubik";
29
- import "@fontsource/jetbrains-mono";
30
-
31
- import { useDataEnhancementPlugin } from "@rebasepro/data_enhancement";
32
-
33
- // TODO: Replace with your Firebase config
34
- const firebaseConfig = {
35
- apiKey: "",
36
- authDomain: "",
37
- projectId: "",
38
- storageBucket: "",
39
- messagingSenderId: "",
40
- appId: ""
41
- };
42
-
43
- export default function App() {
44
-
45
- const dataEnhancementPlugin = useDataEnhancementPlugin({
46
- // Optional callback for defining which collections should be enhanced
47
- getConfigForPath: ({ path }) => {
48
- if (path === "books")
49
- return true;
50
- return false;
51
- }
52
- });
53
-
54
- const plugins = [dataEnhancementPlugin];
55
-
56
- const navigationController = useBuildNavigationStateController({
57
- // ... rest of your config
58
- plugins
59
- });
60
-
61
- return <Rebase
62
- name={"My Online Shop"}
63
- plugins={[dataEnhancementPlugin]}
64
- authentication={myAuthenticator}
65
- navigationController={navigationController}
66
- firebaseConfig={firebaseConfig}
67
- />;
68
- }
61
+ import { useEditorAIController } from "@rebasepro/plugin-data-enhancement";
62
+
63
+ const aiController = useEditorAIController({
64
+ getAuthToken: () => firebaseUser.getIdToken()
65
+ });
66
+
67
+ // Use in a rich text editor:
68
+ await aiController.autocomplete(
69
+ "The quick brown", // text before cursor
70
+ " over the fence", // text after cursor
71
+ (delta) => { // streaming callback
72
+ appendText(delta);
73
+ }
74
+ );
69
75
  ```
70
76
 
71
- ## How does it work?
72
-
73
- This plugin uses the OpenAI API to generate content using the latest GPT models.
74
- This plugin is able to understand the structure of your data and generate
75
- content that fits your schema.
76
-
77
- Some tips in order to get the best results:
78
-
79
- - Make sure you select the **right data** type for your fields.
80
- - The **field names** are used to generate the content and are usually enough to
81
- generate good results. If you want to get even better results, you can
82
- **add a description** to your fields. This will help the plugin understand the
83
- context of your data and generate better results.
84
- - The **collection name** is important as well.
85
- - You can establish **relations between fields** and the plugin will pick it up.
86
- e.g. if you have a field called `author` and another field called `book`, the
87
- plugin will understand that the author is related to the book and will
88
- generate content accordingly. You can use this for making **summaries, reviews,
89
- translations, SEO content**, etc.
77
+ ## Related Packages
78
+
79
+ - `@rebasepro/admin` The admin panel this plugin extends
80
+ - `@rebasepro/core` Core framework providing the plugin system
81
+ - `@rebasepro/types` Shared types (`RebasePlugin`, `EntityCollection`, etc.)
@@ -3,6 +3,7 @@ import { FormexController } from "@rebasepro/formex";
3
3
  import { Property, PropertyConfig } from "@rebasepro/types";
4
4
  export type PropertyWithId = Property & {
5
5
  id?: string;
6
+ conditions?: import('@rebasepro/types').PropertyConditions;
6
7
  };
7
8
  export type OnPropertyChangedParams = {
8
9
  id?: string;
@@ -1,2 +1,2 @@
1
- import { EntityCollection } from "@rebasepro/types";
1
+ import type { EntityCollection } from "@rebasepro/types";
2
2
  export declare const blogCollectionTemplate: EntityCollection;
@@ -1,2 +1,2 @@
1
- import { EntityCollection } from "@rebasepro/types";
1
+ import type { EntityCollection } from "@rebasepro/types";
2
2
  export declare const pagesCollectionTemplate: EntityCollection;
@@ -1,2 +1,2 @@
1
- import { EntityCollection } from "@rebasepro/types";
1
+ import type { EntityCollection } from "@rebasepro/types";
2
2
  export declare const productsCollectionTemplate: EntityCollection;
@@ -1,2 +1,2 @@
1
- import { EntityCollection } from "@rebasepro/types";
1
+ import type { EntityCollection } from "@rebasepro/types";
2
2
  export declare const usersCollectionTemplate: EntityCollection;
@@ -1,6 +1,14 @@
1
- import { AuthController, Entity, EntityCollection, User } from "@rebasepro/types";
2
- export declare function checkOperation<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authController: AuthController<USER>, entity: Entity<M> | null, targetOperation: "select" | "insert" | "update" | "delete"): boolean;
3
- export declare function canReadCollection<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authController: AuthController<USER>): boolean;
4
- export declare function canEditEntity<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authController: AuthController<USER>, path: string, entity: Entity<M> | null): boolean;
5
- export declare function canCreateEntity<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authController: AuthController<USER>, path: string, entity: Entity<M> | null): boolean;
6
- export declare function canDeleteEntity<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authController: AuthController<USER>, path: string, entity: Entity<M> | null): boolean;
1
+ import { Entity, EntityCollection, User } from "@rebasepro/types";
2
+ /**
3
+ * Minimal auth context for permission checking.
4
+ * Only requires the user object avoids forcing callers to construct
5
+ * a full AuthController just to check permissions.
6
+ */
7
+ export interface AuthContext<USER extends User = User> {
8
+ user: USER | null;
9
+ }
10
+ export declare function checkOperation<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authContext: AuthContext<USER>, entity: Entity<M> | null, targetOperation: "select" | "insert" | "update" | "delete"): boolean;
11
+ export declare function canReadCollection<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authContext: AuthContext<USER>): boolean;
12
+ export declare function canEditEntity<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authContext: AuthContext<USER>, path: string, entity: Entity<M> | null): boolean;
13
+ export declare function canCreateEntity<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authContext: AuthContext<USER>, path: string, entity: Entity<M> | null): boolean;
14
+ export declare function canDeleteEntity<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authContext: AuthContext<USER>, path: string, entity: Entity<M> | null): boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","sources":["../src/utils/values.ts","../src/api.ts","../src/utils/suggestions.ts","../src/utils/properties.ts","../src/editor/useEditorAIController.tsx","../src/components/DataEnhancementControllerProvider.tsx","../src/components/FormEnhanceAction.tsx","../src/useDataEnhancementPlugin.tsx"],"sourcesContent":["export function flatMapEntityValues<M extends object>(values: M, path = \"\"): object {\n if (!values) return {};\n return Object.entries(values).flatMap(([key, value]) => {\n const currentPath = path ? `${path}.${key}` : key;\n if (typeof value === \"object\") {\n return flatMapEntityValues(value, currentPath);\n } else {\n return { [currentPath]: value };\n }\n }).reduce((acc, curr) => ({ ...acc,\n...curr }), {})\n}\n","import {\n DataEnhancementRequest,\n EnhancedDataResult,\n InputEntity,\n InputProperty,\n SamplePromptsResult\n} from \"./types/data_enhancement_controller\";\nimport { EntityValues } from \"@rebasepro/types\";\nimport { flatMapEntityValues } from \"./utils/values\";\n\n// const DEFAULT_SERVER = \"http://localhost:5001/rebase-dev-2da42/europe-west3/api\"; // Local\n\nconst DEFAULT_SERVER = \"https://api.rebase.pro\";\n\nexport async function enhanceDataAPIStream<M extends Record<string, unknown>>(props: {\n apiKey: string,\n entityId?: string | number,\n entityName: string,\n entityDescription?: string,\n propertyKey?: string,\n propertyInstructions?: string;\n values: EntityValues<M>,\n path: string,\n properties: Record<string, InputProperty>,\n\n instructions?: string,\n firebaseToken: string,\n onUpdate: (suggestions: Record<string, string | number>) => void;\n onUpdateDelta: (propertyKey: string, partialValue: string) => void;\n onError: (error: Error) => void;\n onEnd: (result: EnhancedDataResult) => void;\n host?: string;\n}) {\n\n const flatValues = flatMapEntityValues(props.values);\n\n const properties = props.properties;\n\n const inputEntity: InputEntity = {\n entityId: props.entityId,\n values: flatValues\n }\n\n const request: DataEnhancementRequest = {\n inputEntity,\n properties,\n entityName: props.entityName,\n entityDescription: props.entityDescription,\n propertyKey: props.propertyKey,\n propertyInstructions: props.propertyInstructions,\n instructions: props.instructions\n };\n\n console.debug(\"enhanceDataAPIStream\", request);\n\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/enhance_stream/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`,\n \"x-de-api-key\": `Basic ${props.apiKey}`\n // \"x-de-version\": version\n },\n body: JSON.stringify(request)\n })\n .then(async (res) => {\n if (!res.ok) {\n console.error(\"enhanceDataAPIStream error\", res)\n throw await res.json();\n }\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"No reader\");\n }\n\n for await (const chunk of readChunks(reader)) {\n const str = new TextDecoder().decode(chunk);\n try {\n str.split(\"&$# \").forEach((s) => {\n if (s && s.length > 0) {\n const data = JSON.parse(s.trim());\n if (data.type === \"suggestion_delta\")\n props.onUpdateDelta(data.data.propertyKey, data.data.partialValue);\n else if (data.type === \"suggestion\")\n props.onUpdate(data.data);\n else if (data.type === \"result\")\n props.onEnd(data.data);\n }\n });\n } catch (e: unknown) {\n console.error(\"str\", str);\n console.error(\"Error parsing stream\", e);\n props.onError(e instanceof Error ? e : new Error(String(e)));\n }\n }\n\n });\n\n}\n\nfunction readChunks(reader: ReadableStreamDefaultReader) {\n return {\n async *[Symbol.asyncIterator]() {\n let readResult = await reader.read();\n while (!readResult.done) {\n yield readResult.value;\n readResult = await reader.read();\n }\n }\n };\n}\n\nexport async function fetchEntityPromptSuggestion<M extends object>(props: {\n input?: string,\n entityName: string,\n firebaseToken: string,\n apiKey: string,\n host?: string\n}): Promise<SamplePromptsResult> {\n\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/prompt_autocomplete/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`,\n \"x-de-api-key\": `Basic ${props.apiKey}`\n },\n body: JSON.stringify({\n entityName: props.entityName,\n input: props.input ?? null\n })\n })\n .then(async (res) => {\n const data = await res.json();\n if (!res.ok) {\n console.error(\"fetchEntityPromptSuggestion\", data);\n throw Error(data.message);\n }\n return {\n prompts: data.data.prompts.map((e: string) => ({\n prompt: e,\n type: \"sample\"\n }))\n };\n });\n\n}\n\nexport async function autocompleteStream(props: {\n firebaseToken: string,\n textBefore?: string,\n textAfter: string,\n host?: string;\n onUpdate: (delta: string) => void;\n}) {\n\n let result = \"\";\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/autocomplete/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`\n // \"x-de-version\": version\n },\n body: JSON.stringify({\n textBefore: props.textBefore,\n textAfter: props.textAfter\n })\n })\n .then(async (res) => {\n if (!res.ok) {\n console.error(\"enhanceDataAPIStream error\", res)\n throw await res.json();\n }\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"No reader\");\n }\n\n for await (const chunk of readChunks(reader)) {\n const str = new TextDecoder().decode(chunk);\n result += str;\n console.debug(\"Autocomplete update:\", str);\n props.onUpdate(str);\n }\n\n }).then(() => {\n console.debug(\"Autocomplete result:\", result);\n return result;\n });\n\n}\n","export function getAppendableSuggestion(suggestion: string | number | undefined, value: unknown): string | undefined {\n const suggestionIncludesValue = typeof suggestion === \"string\" && typeof value === \"string\" && suggestion.toLowerCase().trim().startsWith(value.toLowerCase().trim());\n return (typeof value === \"string\" && suggestionIncludesValue)\n ? suggestion.substring(suggestion.toLowerCase().trim().indexOf(value.toLowerCase().trim()) + value.trim().length)\n : undefined;\n}\n","import { getFieldId } from \"@rebasepro/admin\";\nimport { EnumValues, Properties, Property } from \"@rebasepro/types\";\nimport { isPropertyBuilder } from \"@rebasepro/common\";\nimport { InputProperty } from \"../types/data_enhancement_controller\";\nimport { getValueInPath } from \"@rebasepro/utils\";\n\nexport function getSimplifiedProperties<M extends Record<string, any>>(properties: Properties, values: M, path = \"\"): Record<string, InputProperty> {\n if (!properties) return {};\n return Object.entries(properties)\n .map(([key, property]) => {\n if (isPropertyBuilder(property)) return {};\n const fullKey = path ? `${path}.${key}` : key;\n const valueInPath = getValueInPath(values, fullKey);\n return getSimplifiedProperty(property, fullKey, valueInPath)\n })\n .reduce((a, b) => ({ ...a,\n...b }), {});\n}\n\nfunction getSimpleProperty(property: Property): InputProperty {\n const fieldId = getFieldId(property);\n if (!fieldId) {\n console.error(\"No fieldId found for property\", property);\n throw new Error(\"Field id not found\");\n }\n return {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: fieldId,\n enum: \"enum\" in property && property.enum\n ? getSimpleEnumValues(property.enum)\n : undefined,\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly)\n };\n}\n\nfunction getSimplifiedProperty(property: Property, path: string, value?: unknown): Record<string, InputProperty> {\n if (isPropertyBuilder(property)) return {};\n if (property.type === \"array\") {\n\n if (property.of && !Array.isArray(property.of) && !isPropertyBuilder(property.of)) {\n const arrayParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"repeat\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly),\n of: getSimpleProperty(property.of as Property)\n };\n\n const result = { [path]: arrayParentProperty };\n // if (Array.isArray(value)) {\n // result = {\n // ...result,\n // ...value\n // .map((v, i) => getSimplifiedProperty(property.of, `${path}.${i}`, v))\n // .reduce((a, b) => ({ ...a, ...b }), {})\n // };\n // }\n //\n // const existingValuesCount = Array.isArray(value) ? value.length : 0;\n //\n // const newValuesCount = property.of && !isPropertyBuilder<any, any>(property.of) && (property.of as Property).type === \"map\" ? 1 : 3;\n // result = {\n // ...result,\n // // ...Array.from(Array(newValuesCount))\n // // .map((v, i) => getSimplifiedProperty(property.of, `${path}.${i + existingValuesCount}`, v))\n // // .reduce((a, b) => ({ ...a, ...b }), {})\n // }\n\n return result;\n } else if (property.oneOf) {\n\n const arrayParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"block\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly),\n oneOf: {\n typeField: property.oneOf.typeField,\n valueField: property.oneOf.valueField,\n properties: Object.entries(property.oneOf.properties)\n .map(([key, prop]) => ({ [key]: getSimpleProperty(prop) }))\n .reduce((a, b) => ({ ...a,\n...b }), {})\n }\n };\n\n if (!Array.isArray(value)) {\n return { [path]: arrayParentProperty };\n }\n\n return value.map((v, i) => {\n if (v == null) return {};\n const typeKey = property.oneOf!.typeField ?? \"type\";\n const oneOfType = v[typeKey];\n const valueKey = property.oneOf!.valueField ?? \"value\";\n const oneOfValue = v[valueKey];\n const childProperty = property.oneOf!.properties[oneOfType];\n if (childProperty === undefined) {\n console.error(`No property found for type ${oneOfType}`, property.oneOf!.properties);\n return {};\n }\n const simplifiedProperty = getSimplifiedProperty(childProperty, `${path}.${i}.${valueKey}`, oneOfValue);\n return {\n [`${path}.${i}.${typeKey}`]: oneOfType,\n ...simplifiedProperty\n };\n }).reduce((a, b) => ({ ...a,\n...b }), { [path]: arrayParentProperty });\n }\n } else if (property.type === \"map\") {\n if (property.properties) {\n const mapProperties: Record<string, InputProperty> = Object.entries(property.properties)\n .map(([key, childProperty]) => {\n const childValue = value && typeof value === \"object\" ? (value as Record<string, unknown>)[key] : undefined;\n return getSimplifiedProperty(childProperty, key, childValue);\n })\n .map(o => attachPathToKeys(o, path))\n .reduce((a, b) => ({ ...a,\n...b }), {});\n\n if (Object.keys(mapProperties).length === 0) return {};\n const mapParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"group\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly)\n };\n return {\n [path]: mapParentProperty,\n ...mapProperties\n } as Record<string, InputProperty>;\n }\n } else {\n const fieldId = getFieldId(property);\n if (!fieldId) {\n console.warn(`No fieldId found for property ${path} with type ${property.type}`);\n return {};\n }\n return {\n [path]: getSimpleProperty(property)\n };\n }\n return {};\n}\n\n// attach a path to every key in an object\nfunction attachPathToKeys(obj: Record<string, InputProperty>, path = \"\"): Record<string, InputProperty> {\n return Object.entries(obj)\n .map(([key, value]) => {\n const fullKey = path ? `${path}.${key}` : key;\n return { [fullKey]: value };\n })\n .reduce((a, b) => ({ ...a,\n...b }), {});\n}\n\nfunction getSimpleEnumValues(enumValues: EnumValues): string[] {\n if (Array.isArray(enumValues))\n return enumValues.map(v => String(v.id));\n if (typeof enumValues === \"object\")\n return Object.keys(enumValues);\n throw Error(\"getSimpleEnumValues: Invalid enumValues\");\n}\n","import { autocompleteStream } from \"../api\";\nimport { EditorAIController } from \"@rebasepro/admin\";\n\nexport function useEditorAIController({ getAuthToken }: { getAuthToken?: () => Promise<string> }): EditorAIController {\n const autocomplete = async (textBefore: string, textAfter: string, onUpdate: (delta: string) => void) => {\n if (!getAuthToken) {\n throw new Error(\"Firebase token is required\");\n }\n const firebaseToken = await getAuthToken();\n return autocompleteStream({\n firebaseToken,\n textBefore,\n textAfter,\n onUpdate\n });\n }\n\n return {\n autocomplete\n };\n}\n\n// async function * generateLoremIpsum(): AsyncGenerator<string> {\n// const loremIpsum = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\\n# Heading\\n\\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\";\n//\n// const words = loremIpsum.split(\" \");\n//\n// for (const word of words) {\n// yield word;\n// await new Promise(resolve => setTimeout(resolve, 100));\n// }\n// }\n//\n// const generator = generateLoremIpsum();\n// for await (const word of generator) {\n//\n// }\n","import React, { PropsWithChildren, useCallback, useContext, useEffect, useMemo, useRef, useState } from \"react\";\n\nimport {\n DataEnhancementController,\n EnhancedDataResult,\n EnhanceParams,\n InputProperty\n} from \"../types/data_enhancement_controller\";\nimport {\n useAuthController,\n useCustomizationController,\n useSnackbarController\n} from \"@rebasepro/core\";\nimport { useUrlController } from \"@rebasepro/admin\";\nimport { DataDriver, Entity, EntityCollection, PluginFormActionProps } from \"@rebasepro/types\";\nimport { enhanceDataAPIStream, fetchEntityPromptSuggestion } from \"../api\";\nimport { getAppendableSuggestion } from \"../utils/suggestions\";\nimport { getSimplifiedProperties } from \"../utils/properties\";\nimport { useEditorAIController } from \"../editor/useEditorAIController\";\nimport { getValueInPath } from \"@rebasepro/utils\";\n\nexport const DataEnhancementControllerContext = React.createContext<DataEnhancementController>(null! as DataEnhancementController);\n\nexport type DataEnhancementControllerProviderProps = {\n\n apiKey: string;\n\n getConfigForPath?: (props: {\n path: string,\n collection: EntityCollection\n }) => boolean;\n\n host?: string;\n}\n\nexport const useDataEnhancementController = (): DataEnhancementController => useContext(DataEnhancementControllerContext);\n\nfunction getPropertyFromKey(properties: Record<string, InputProperty>, propertyKey: string) {\n if (propertyKey in properties) {\n return properties[propertyKey];\n } else {\n //split the property key\n const split = propertyKey.split(\".\");\n if (split.length === 1) {\n return undefined;\n }\n const parentKey = split.slice(0, split.length - 1).join(\".\");\n return getPropertyFromKey(properties, parentKey);\n\n }\n}\n\nexport function DataEnhancementControllerProvider({\n apiKey,\n getConfigForPath,\n children,\n host,\n path,\n collection,\n formContext\n}: PropsWithChildren<DataEnhancementControllerProviderProps & PluginFormActionProps>) {\n\n const [enabled, setEnabled] = useState(false);\n const [suggestions, setSuggestions] = useState<Record<string, string | number>>({});\n const [loadingSuggestions, setLoadingSuggestions] = useState<string[]>([]);\n\n const enhancingInProgress = useRef(false);\n\n const authController = useAuthController();\n const snackbarController = useSnackbarController();\n\n\n const properties = useMemo(() => getSimplifiedProperties(collection.properties, formContext?.values ?? {}), [formContext?.values]);\n // const preEnhanceValuesRef = React.useRef(formContext?.values ?? {});\n const valuesRef = React.useRef(formContext?.values ?? {});\n useEffect(() => {\n if (!enhancingInProgress.current)\n valuesRef.current = formContext?.values ?? {};\n }, [formContext?.values]);\n\n const allowReferenceDataSelection = false;\n\n const updateConfig = useCallback(async () => {\n if (!getConfigForPath) return;\n const config = getConfigForPath({\n path,\n collection\n });\n if (config) {\n setEnabled(true);\n }\n }, [collection, getConfigForPath, path]);\n\n useEffect(() => {\n if (!getConfigForPath) {\n setEnabled(true);\n } else {\n updateConfig();\n }\n\n }, [getConfigForPath, updateConfig]);\n\n\n const urlController = useUrlController();\n\n const clearSuggestion = useCallback((propertyKey: string) => {\n setSuggestions((prev) => {\n //remove propertyKey from prev\n const {\n [propertyKey]: _,\n ...rest\n } = prev;\n return rest;\n });\n }, []);\n\n const appendValueDelta = useCallback((propertyKey: string, delta: string) => {\n\n const property = getPropertyFromKey(properties, propertyKey);\n if (delta === null || property?.disabled) {\n return;\n }\n\n // clearSuggestion(propertyKey);\n const value = getValueInPath(valuesRef.current, propertyKey);\n\n const currentValue = value ? (value as string) + \"\" : \"\";\n const updatedValue = currentValue + delta;\n // if (currentValue.length === 0) updatedValue = updatedValue.trimStart();\n valuesRef.current = {\n ...valuesRef.current,\n [propertyKey]: updatedValue\n };\n formContext?.setFieldValue(propertyKey, updatedValue, false);\n setSuggestions(prev => ({\n ...prev,\n [propertyKey]: (prev[propertyKey] ?? \"\") + delta\n }));\n }, [properties, formContext]);\n\n const updateSuggestedValues = useCallback((currentValues: object, updatedValues: Record<string, string | number>, replaceValues: boolean) => {\n\n setLoadingSuggestions((prev) => {\n return prev.filter(p => !Object.keys(updatedValues).includes(p));\n });\n\n Object.entries(updatedValues).forEach(([propertyKey, suggestion]) => {\n\n const value = getValueInPath(currentValues, propertyKey);\n const property = getPropertyFromKey(properties, propertyKey);\n\n if (!property || suggestion === null || property?.disabled) {\n return;\n }\n\n if (typeof suggestion === \"number\") {\n formContext?.setFieldValue(propertyKey, suggestion);\n return;\n }\n\n if (replaceValues) {\n formContext?.setFieldValue(propertyKey, suggestion);\n return;\n }\n\n const appendableValue = getAppendableSuggestion(suggestion, value);\n\n const currentValue = value ? (value as string) + \"\" : \"\";\n if (appendableValue) {\n formContext?.setFieldValue(propertyKey, suggestion);\n } else {\n const multiline = property?.fieldConfigId === \"multiline\" || property?.fieldConfigId === \"markdown\";\n const trimmedValue = currentValue.trimEnd();\n if (multiline && (trimmedValue.endsWith(\".\") || trimmedValue.endsWith(\"?\") || trimmedValue.endsWith(\"!\") || trimmedValue.endsWith(\":\"))) {\n formContext?.setFieldValue(propertyKey, trimmedValue + \"\\n\\n\" + (suggestion as string).trimStart());\n } else {\n formContext?.setFieldValue(propertyKey, trimmedValue + (trimmedValue.length > 0 ? \" \" : \"\") + (suggestion as string));\n }\n }\n });\n\n setSuggestions(prev => ({\n ...prev,\n ...Object.keys(updatedValues)\n .reduce((acc, key) => {\n const value = getValueInPath(formContext?.values, key);\n const suggestion = updatedValues[key];\n return {\n ...acc,\n [key]: getAppendableSuggestion(suggestion, value) ?? suggestion\n };\n }, {})\n }));\n }, [properties, formContext]);\n\n const displayNeededSubscriptionSnackbar = useCallback((projectId: unknown) => {\n snackbarController.open({\n type: \"warning\",\n message: \"A valid subscription is needed in order to use this function.\",\n autoHideDuration: 4000\n });\n }, [snackbarController]);\n\n const editorAIController = useEditorAIController({ getAuthToken: authController.getAuthToken });\n\n const clearAllSuggestions = useCallback(() => {\n setSuggestions({});\n }, []);\n\n const enhance = useCallback(async (props: EnhanceParams<Record<string, unknown>>): Promise<EnhancedDataResult | null> => {\n\n if (!authController.user) {\n snackbarController.open({\n type: \"warning\",\n message: \"You need to be logged in to enhance data\"\n });\n return Promise.reject(new Error(\"Not logged in\"));\n }\n\n const resolvedPath = urlController.resolveDatabasePathsFrom(path);\n const firebaseToken = await authController.getAuthToken();\n\n if (props.propertyKey) {\n clearSuggestion(props.propertyKey)\n } else {\n clearAllSuggestions();\n }\n\n setLoadingSuggestions((prev) => [...prev, ...(props.propertyKey ? [props.propertyKey] : Object.keys(properties))]);\n enhancingInProgress.current = true;\n\n const currentValues = valuesRef.current ?? {};\n\n return new Promise((resolve, reject) => {\n function onError(e: unknown) {\n setLoadingSuggestions([]);\n const err = e instanceof Error ? e : typeof e === \"object\" && e !== null ? e : new Error(String(e));\n const errorObj = err as Record<string, unknown>;\n if (errorObj.code === \"payment-required\") {\n const data = errorObj.data as Record<string, unknown> | undefined;\n const projectId = data?.projectId;\n displayNeededSubscriptionSnackbar(projectId);\n } else {\n console.error(\"Enhance error\", e);\n }\n reject(e);\n enhancingInProgress.current = false;\n }\n\n try {\n enhanceDataAPIStream({\n ...props,\n host,\n apiKey,\n properties,\n path: resolvedPath,\n entityName: collection.singularName ?? collection.name,\n entityDescription: collection.description,\n\n firebaseToken,\n onUpdate: (suggestions) => {\n console.debug(\"de onUpdate\", suggestions);\n updateSuggestedValues(currentValues, suggestions, props.replaceValues ?? false);\n },\n onUpdateDelta: (propertyKey: string, partialValue: string) => {\n // console.debug(\"de delta\", propertyKey, partialValue);\n appendValueDelta(propertyKey, partialValue);\n },\n onError,\n onEnd: (result) => {\n console.debug(\"de onEnd\", result);\n if (result.errors) {\n result.errors.forEach((error) => {\n snackbarController.open({\n type: \"warning\",\n message: error\n })\n });\n }\n if (Object.keys(result.suggestions).length === 0) {\n snackbarController.open({\n type: \"info\",\n autoHideDuration: 1800,\n message: \"No fields were updated\"\n })\n }\n setLoadingSuggestions([]);\n resolve(result);\n enhancingInProgress.current = false;\n }\n }).catch(onError);\n } catch (e: unknown) {\n onError(e);\n }\n });\n }, [\n authController, urlController, path, clearSuggestion, clearAllSuggestions,\n properties, host, apiKey, collection, updateSuggestedValues, appendValueDelta, displayNeededSubscriptionSnackbar, snackbarController\n ]);\n\n const getSamplePrompts = useCallback(async (entityName: string, input?: string) => {\n const firebaseToken = await authController.getAuthToken()\n return fetchEntityPromptSuggestion({\n host,\n entityName,\n firebaseToken,\n apiKey,\n input\n });\n }, [apiKey, authController.getAuthToken, host]);\n\n const dataEnhancementController: DataEnhancementController = useMemo(() => ({\n enabled,\n suggestions,\n clearSuggestion,\n enhance,\n allowReferenceDataSelection,\n clearAllSuggestions,\n getSamplePrompts,\n loadingSuggestions,\n editorAIController\n }), [\n enabled,\n suggestions,\n clearSuggestion,\n enhance,\n allowReferenceDataSelection,\n clearAllSuggestions,\n getSamplePrompts,\n loadingSuggestions,\n editorAIController\n ]);\n\n return (\n <DataEnhancementControllerContext.Provider\n value={dataEnhancementController}>\n {children}\n </DataEnhancementControllerContext.Provider>\n );\n}\n\n\n","\nimport React, { useCallback, useDeferredValue, useEffect, useRef } from \"react\";\n\nimport {\n Button,\n CircularProgress,\n cls,\n focusedDisabled,\n IconButton,\n iconSize,\n Menu,\n MenuItem,\n SendIcon,\n Separator,\n TextareaAutosize,\n XIcon\n} from \"@rebasepro/ui\";\nimport {\n AIIcon,\n useLargeLayout\n} from \"@rebasepro/core\";\nimport { EntityStatus, PluginFormActionProps, Properties, Property } from \"@rebasepro/types\";\nimport { isPropertyBuilder, stripCollectionPath } from \"@rebasepro/common\";\nimport { useDataEnhancementController } from \"./DataEnhancementControllerProvider\";\nimport { SamplePrompt } from \"../types/data_enhancement_controller\";\n\nexport function FormEnhanceAction({\n entityId,\n path,\n status,\n collection,\n formContext,\n openEntityMode\n}: PluginFormActionProps) {\n\n const largeLayout = useLargeLayout();\n\n const storageKey = createLocalStorageKey(path, status);\n\n const [loading, setLoading] = React.useState(false);\n const dataEnhancementController = useDataEnhancementController();\n\n const [samplePrompts, setSamplePrompts] = React.useState<SamplePrompt[] | undefined>(undefined);\n const [instructions, setInstructions] = React.useState<string>(\"\");\n\n const getSamplePrompts = dataEnhancementController?.getSamplePrompts;\n\n const loadingPrompts = useRef(false);\n const updateSuggestedPrompts = useCallback(async function updateSuggestedPrompts(instructions?: string) {\n if (!getSamplePrompts) return;\n if (loadingPrompts.current) return;\n loadingPrompts.current = true;\n const prompts = status === \"new\"\n ? (await getSamplePrompts(collection.singularName ?? collection.name, instructions)).prompts\n : getPromptsForExistingEntities(collection.properties);\n\n const recentPromptsFromStorage = getRecentPromptsFromStorage(storageKey);\n const recentPrompts = recentPromptsFromStorage.map(prompt => prompt.prompt);\n setSamplePrompts([...recentPromptsFromStorage, ...prompts.filter(p => !recentPrompts.includes(p.prompt))].slice(0, 5));\n loadingPrompts.current = false;\n },\n [collection.name, collection.singularName, getSamplePrompts, status]);\n\n const deferredValues = useDeferredValue(formContext?.values);\n // const enoughData = countStringCharacters(deferredValues, collection.properties) > 20;\n\n useEffect(() => {\n if (!dataEnhancementController) return;\n if (!samplePrompts) {\n setSamplePrompts(getRecentPromptsFromStorage(storageKey));\n updateSuggestedPrompts().then();\n }\n }, [dataEnhancementController, samplePrompts, storageKey, updateSuggestedPrompts, instructions, status]);\n\n useEffect(() => {\n if (!dataEnhancementController) return;\n updateSuggestedPrompts().then();\n }, [dataEnhancementController, status]);\n\n const enhance = (prompt?: string) => {\n if (!dataEnhancementController || !formContext?.values) return;\n setLoading(true);\n if (prompt) {\n addRecentPrompt(storageKey, prompt);\n setSamplePrompts([{\n prompt,\n type: \"recent\"\n }, ...(samplePrompts ?? []).slice(0, 5)]);\n }\n return dataEnhancementController.enhance({\n entityId,\n values: formContext!.values,\n instructions: prompt,\n replaceValues: true\n }).finally(() => {\n setLoading(false);\n });\n };\n\n if (!dataEnhancementController?.enabled)\n return null;\n\n const suggestions = dataEnhancementController.suggestions;\n const hasSuggestions = Object.values(suggestions).filter(Boolean).length > 0;\n\n const disabledSuggestionActions = !hasSuggestions;\n const promptSuggestionsEnabled = (samplePrompts ?? []).length > 0 && instructions.length === 0;\n\n // const noIdSet = !formContext?.entityId;\n\n function submit() {\n enhance(instructions);\n }\n\n return (\n <Menu\n align={\"end\"}\n sideOffset={8}\n className={\"max-w-[100vw]\"}\n trigger={<Button variant={\"filled\"}\n color={\"neutral\"}\n fullWidth={largeLayout && openEntityMode === \"full_screen\"}\n size={\"small\"}\n disabled={loading}>\n {!loading && <AIIcon size={\"small\"}/>}\n {loading && <CircularProgress size={\"small\"}/>}\n Autofill\n </Button>}>\n\n <MenuItem className={\"py-4\"}\n onClick={() => {\n enhance();\n }}>\n <AIIcon size={\"small\"}/>\n Autofill based on the current content\n </MenuItem>\n\n <Separator orientation={\"horizontal\"} className={\"mt-2\"}/>\n\n {samplePrompts?.map((samplePrompt, index) => {\n return <MenuItem\n key={index + \"_\" + samplePrompt.prompt}\n onClick={() => {\n setInstructions(samplePrompt.prompt);\n enhance(samplePrompt.prompt);\n }}\n >\n <div className={\"pl-9 grow text-text-secondary dark:text-text-secondary-dark\"}>\n {samplePrompt.prompt}\n </div>\n\n {samplePrompt.type === \"recent\" && <IconButton\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n removeRecentPrompt(storageKey, samplePrompt.prompt);\n setSamplePrompts((samplePrompts ?? []).filter(p => p.prompt !== samplePrompt.prompt));\n }}\n size={\"smallest\"}\n >\n <XIcon size={iconSize.smallest}/>\n </IconButton>\n }\n </MenuItem>;\n })}\n\n <Separator orientation={\"horizontal\"}/>\n\n <div\n className={cls(\n \"my-2 w-[500px] max-w-full flex items-start text-surface-700 dark:text-surface-200\"\n )}>\n\n <TextareaAutosize\n className={cls(\"p-4 rounded-lg resize-none bg-surface-100 dark:bg-surface-950 mx-2 w-full grow outline-hidden max-h-[300px] overflow-auto\", focusedDisabled)}\n value={instructions}\n autoFocus={status === \"new\"}\n disabled={loading}\n onFocus={(event) => {\n event.stopPropagation();\n }}\n placeholder={\"...or provide instructions\"}\n onKeyDown={(e) => {\n e.stopPropagation();\n if (e.key === \"Enter\" && !e.shiftKey) {\n e.preventDefault();\n submit();\n }\n\n }}\n onChange={(e) => {\n setInstructions(e.target.value);\n }}\n />\n\n <IconButton\n size={\"small\"}\n onClick={() => {\n setInstructions(\"\");\n }}\n color={!instructions ? \"primary\" : undefined}\n disabled={loading || !instructions}>\n <XIcon size={iconSize.small}/>\n </IconButton>\n\n <IconButton\n onClick={() => enhance(instructions)}\n size={\"small\"}\n color={!instructions ? \"primary\" : undefined}\n disabled={loading || !instructions}>\n {loading &&\n <CircularProgress size={\"smallest\"}/>}\n {!loading &&\n <SendIcon color={\"primary\"}/>}\n </IconButton>\n\n </div>\n\n </Menu>\n );\n}\n\nexport interface EnhanceDialogProps {\n open: boolean;\n onClose: () => void;\n selectReferences: () => void;\n loading: boolean;\n enhance: (instructions: string) => void;\n samplePrompts?: string[];\n}\n\nfunction getPromptsForExistingEntities(properties: Properties): SamplePrompt[] {\n\n const multilineProperties = Object.values(properties).filter((p: Property) => {\n if (isPropertyBuilder(p)) {\n return false;\n }\n return p.type === \"string\" && (p.ui?.markdown || p.ui?.multiline);\n });\n\n const multilinePrompt: Property | undefined = multilineProperties.length > 0\n ? multilineProperties[Math.floor(Math.random() * multilineProperties.length)] as Property\n : undefined;\n\n const prompts = [\n \"Fill the missing fields\",\n \"Translate the missing content\"\n ];\n if (multilinePrompt) {\n prompts.push(`Add 2 paragraphs to '${multilinePrompt.name}'`);\n }\n return prompts.map(p => ({\n prompt: p,\n type: \"sample\"\n }));\n}\n\nconst createLocalStorageKey = (path: string, status: EntityStatus) => {\n const statusString = status === \"new\" ? \"new\" : \"existing\";\n return `data_enhancement::${statusString}::${stripCollectionPath(path)}`;\n};\n\nconst getRecentPromptsFromStorage = (storageKey: string): SamplePrompt[] => {\n const item = localStorage.getItem(storageKey);\n return item ? JSON.parse(item).map((e: string) => ({\n prompt: e,\n type: \"recent\"\n })) : [];\n};\n\nconst addRecentPrompt = (storageKey: string, prompt: string) => {\n if (!prompt || prompt.trim().length === 0) {\n return;\n }\n const recentPrompts = getRecentPromptsFromStorage(storageKey);\n localStorage.setItem(storageKey, JSON.stringify([prompt, ...recentPrompts\n .map(e => e.prompt)\n .filter(e => e !== prompt)\n .slice(0, 5)]));\n};\n\nconst removeRecentPrompt = (storageKey: string, prompt: string) => {\n localStorage.setItem(storageKey, JSON.stringify(getRecentPromptsFromStorage(storageKey)\n .map(e => e.prompt)\n .filter(e => e !== prompt)));\n};\n","import React from \"react\";\n\nimport { EntityCollection, RebasePlugin, User } from \"@rebasepro/types\";\nimport { DataEnhancementControllerProvider } from \"./components/DataEnhancementControllerProvider\";\nimport { FormEnhanceAction } from \"./components/FormEnhanceAction\";\n\nconst DEFAULT_API_KEY = \"fcms-U9jdDii0xXWSDC34asfrf54lbkFJBfKfRWcEDEwdc4V5wDWEDF\";\n\nexport interface DataEnhancementPluginProps {\n\n apiKey?: string;\n\n /**\n * Use this function to determine if the data enhancement plugin should be enabled for a given path.\n * If this function is not provided, the plugin will be enabled for all paths.\n * If the function returns false, the plugin will be disabled for the given path.\n * You can also return a configuration object to override the default configuration.\n *\n * @param path\n * @param collection\n */\n getConfigForPath?: (props: {\n path: string,\n collection: EntityCollection,\n user: User | null\n }) => boolean;\n\n /**\n * Host to use for the data enhancement API.\n * This prop is only use in development mode.\n */\n host?: string;\n}\n\n/**\n * Use this hook to initialise the data enhancement plugin.\n * This is likely the only hook you will need to use.\n * @param props\n */\nexport function useDataEnhancementPlugin(props?: DataEnhancementPluginProps): RebasePlugin {\n\n const apiKey = props?.apiKey ?? DEFAULT_API_KEY;\n const getConfigForPath = props?.getConfigForPath;\n\n return React.useMemo(() => ({\n key: \"data_enhancement\",\n slots: [\n {\n slot: \"form.actions\",\n Component: FormEnhanceAction,\n order: 40\n }\n ],\n providers: [\n {\n scope: \"form\" as const,\n Component: DataEnhancementControllerProvider as React.ComponentType<any>,\n props: {\n apiKey,\n getConfigForPath,\n host: props?.host\n }\n }\n ]\n }), [apiKey, getConfigForPath, props?.host]);\n}\n"],"names":["flatMapEntityValues","values","path","Object","entries","flatMap","key","value","currentPath","reduce","acc","curr","DEFAULT_SERVER","enhanceDataAPIStream","props","flatValues","properties","inputEntity","entityId","request","entityName","entityDescription","propertyKey","propertyInstructions","instructions","console","debug","fetch","host","method","headers","Authorization","firebaseToken","apiKey","body","JSON","stringify","then","res","ok","error","json","reader","getReader","Error","chunk","readChunks","str","TextDecoder","decode","split","forEach","s","length","data","parse","trim","type","onUpdateDelta","partialValue","onUpdate","onEnd","e","onError","String","Symbol","asyncIterator","readResult","read","done","fetchEntityPromptSuggestion","input","message","prompts","map","prompt","autocompleteStream","result","textBefore","textAfter","getAppendableSuggestion","suggestion","suggestionIncludesValue","toLowerCase","startsWith","substring","indexOf","undefined","getSimplifiedProperties","property","isPropertyBuilder","fullKey","valueInPath","getValueInPath","getSimplifiedProperty","a","b","getSimpleProperty","fieldId","getFieldId","name","description","fieldConfigId","enum","getSimpleEnumValues","disabled","Boolean","ui","readOnly","of","Array","isArray","arrayParentProperty","oneOf","typeField","valueField","prop","v","i","typeKey","oneOfType","valueKey","oneOfValue","childProperty","simplifiedProperty","mapProperties","childValue","o","attachPathToKeys","keys","mapParentProperty","warn","obj","enumValues","id","useEditorAIController","getAuthToken","autocomplete","DataEnhancementControllerContext","React","createContext","useDataEnhancementController","useContext","getPropertyFromKey","parentKey","slice","join","DataEnhancementControllerProvider","getConfigForPath","children","collection","formContext","enabled","setEnabled","useState","suggestions","setSuggestions","loadingSuggestions","setLoadingSuggestions","enhancingInProgress","useRef","authController","useAuthController","snackbarController","useSnackbarController","useMemo","valuesRef","useEffect","current","allowReferenceDataSelection","updateConfig","useCallback","config","urlController","useUrlController","clearSuggestion","prev","_","rest","appendValueDelta","delta","currentValue","updatedValue","setFieldValue","updateSuggestedValues","currentValues","updatedValues","replaceValues","filter","p","includes","appendableValue","multiline","trimmedValue","trimEnd","endsWith","trimStart","displayNeededSubscriptionSnackbar","projectId","open","autoHideDuration","editorAIController","clearAllSuggestions","enhance","user","Promise","reject","resolvedPath","resolveDatabasePathsFrom","resolve","err","errorObj","code","singularName","errors","catch","getSamplePrompts","dataEnhancementController","FormEnhanceAction","status","openEntityMode","largeLayout","useLargeLayout","storageKey","createLocalStorageKey","loading","setLoading","samplePrompts","setSamplePrompts","setInstructions","loadingPrompts","updateSuggestedPrompts","getPromptsForExistingEntities","recentPromptsFromStorage","getRecentPromptsFromStorage","recentPrompts","useDeferredValue","addRecentPrompt","finally","submit","samplePrompt","index","preventDefault","stopPropagation","removeRecentPrompt","iconSize","smallest","cls","focusedDisabled","event","shiftKey","target","small","multilineProperties","markdown","multilinePrompt","Math","floor","random","push","statusString","stripCollectionPath","item","localStorage","getItem","setItem","DEFAULT_API_KEY","useDataEnhancementPlugin","$","_c","t0","t1","for","slot","Component","order","t2","t3","slots","providers","scope"],"mappings":";;;;;;;;AAAO,SAASA,oBAAsCC,QAAWC,OAAO,IAAY;AAChF,MAAI,CAACD,OAAQ,QAAO,CAAA;AACpB,SAAOE,OAAOC,QAAQH,MAAM,EAAEI,QAAQ,CAAC,CAACC,KAAKC,KAAK,MAAM;AACpD,UAAMC,cAAcN,OAAO,GAAGA,IAAI,IAAII,GAAG,KAAKA;AAC9C,QAAI,OAAOC,UAAU,UAAU;AAC3B,aAAOP,oBAAoBO,OAAOC,WAAW;AAAA,IACjD,OAAO;AACH,aAAO;AAAA,QAAE,CAACA,WAAW,GAAGD;AAAAA,MAAAA;AAAAA,IAC5B;AAAA,EACJ,CAAC,EAAEE,OAAO,CAACC,KAAKC,UAAU;AAAA,IAAE,GAAGD;AAAAA,IACnC,GAAGC;AAAAA,EAAAA,IAAS,CAAA,CAAE;AACd;ACCA,MAAMC,iBAAiB;AAEvB,eAAsBC,qBAAwDC,OAkB3E;AAEC,QAAMC,aAAaf,oBAAoBc,MAAMb,MAAM;AAEnD,QAAMe,aAAaF,MAAME;AAEzB,QAAMC,cAA2B;AAAA,IAC7BC,UAAUJ,MAAMI;AAAAA,IAChBjB,QAAQc;AAAAA,EAAAA;AAGZ,QAAMI,UAAkC;AAAA,IACpCF;AAAAA,IACAD;AAAAA,IACAI,YAAYN,MAAMM;AAAAA,IAClBC,mBAAmBP,MAAMO;AAAAA,IACzBC,aAAaR,MAAMQ;AAAAA,IACnBC,sBAAsBT,MAAMS;AAAAA,IAC5BC,cAAcV,MAAMU;AAAAA,EAAAA;AAGxBC,UAAQC,MAAM,wBAAwBP,OAAO;AAE7C,SAAOQ,OAAOb,MAAMc,QAAQhB,kBAAkB,yBAC1C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,WAAAxH;AAAAwH,WAAAQ;AAAAR,WAAAS;AAAAA,EAAA,OAAA;AAAAA,SAAAT,EAAA,CAAA;AAAA,EAAA;AAAAE,OApB2BO;AAoB3B,SApBMP;AAoBqC;"}
1
+ {"version":3,"file":"index.es.js","sources":["../src/utils/values.ts","../src/api.ts","../src/utils/suggestions.ts","../src/utils/properties.ts","../src/editor/useEditorAIController.tsx","../src/components/DataEnhancementControllerProvider.tsx","../src/components/FormEnhanceAction.tsx","../src/useDataEnhancementPlugin.tsx"],"sourcesContent":["export function flatMapEntityValues<M extends object>(values: M, path = \"\"): object {\n if (!values) return {};\n return Object.entries(values).flatMap(([key, value]) => {\n const currentPath = path ? `${path}.${key}` : key;\n if (typeof value === \"object\") {\n return flatMapEntityValues(value, currentPath);\n } else {\n return { [currentPath]: value };\n }\n }).reduce((acc, curr) => ({ ...acc,\n...curr }), {})\n}\n","import {\n DataEnhancementRequest,\n EnhancedDataResult,\n InputEntity,\n InputProperty,\n SamplePromptsResult\n} from \"./types/data_enhancement_controller\";\nimport { EntityValues } from \"@rebasepro/types\";\nimport { flatMapEntityValues } from \"./utils/values\";\n\n// const DEFAULT_SERVER = \"http://localhost:5001/rebase-dev-2da42/europe-west3/api\"; // Local\n\nconst DEFAULT_SERVER = \"https://api.rebase.pro\";\n\nexport async function enhanceDataAPIStream<M extends Record<string, unknown>>(props: {\n apiKey: string,\n entityId?: string | number,\n entityName: string,\n entityDescription?: string,\n propertyKey?: string,\n propertyInstructions?: string;\n values: EntityValues<M>,\n path: string,\n properties: Record<string, InputProperty>,\n\n instructions?: string,\n firebaseToken: string,\n onUpdate: (suggestions: Record<string, string | number>) => void;\n onUpdateDelta: (propertyKey: string, partialValue: string) => void;\n onError: (error: Error) => void;\n onEnd: (result: EnhancedDataResult) => void;\n host?: string;\n}) {\n\n const flatValues = flatMapEntityValues(props.values);\n\n const properties = props.properties;\n\n const inputEntity: InputEntity = {\n entityId: props.entityId,\n values: flatValues\n }\n\n const request: DataEnhancementRequest = {\n inputEntity,\n properties,\n entityName: props.entityName,\n entityDescription: props.entityDescription,\n propertyKey: props.propertyKey,\n propertyInstructions: props.propertyInstructions,\n instructions: props.instructions\n };\n\n console.debug(\"enhanceDataAPIStream\", request);\n\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/enhance_stream/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`,\n \"x-de-api-key\": `Basic ${props.apiKey}`\n // \"x-de-version\": version\n },\n body: JSON.stringify(request)\n })\n .then(async (res) => {\n if (!res.ok) {\n console.error(\"enhanceDataAPIStream error\", res)\n throw await res.json();\n }\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"No reader\");\n }\n\n for await (const chunk of readChunks(reader)) {\n const str = new TextDecoder().decode(chunk);\n try {\n str.split(\"&$# \").forEach((s) => {\n if (s && s.length > 0) {\n const data = JSON.parse(s.trim());\n if (data.type === \"suggestion_delta\")\n props.onUpdateDelta(data.data.propertyKey, data.data.partialValue);\n else if (data.type === \"suggestion\")\n props.onUpdate(data.data);\n else if (data.type === \"result\")\n props.onEnd(data.data);\n }\n });\n } catch (e: unknown) {\n console.error(\"str\", str);\n console.error(\"Error parsing stream\", e);\n props.onError(e instanceof Error ? e : new Error(String(e)));\n }\n }\n\n });\n\n}\n\nfunction readChunks(reader: ReadableStreamDefaultReader) {\n return {\n async *[Symbol.asyncIterator]() {\n let readResult = await reader.read();\n while (!readResult.done) {\n yield readResult.value;\n readResult = await reader.read();\n }\n }\n };\n}\n\nexport async function fetchEntityPromptSuggestion<M extends object>(props: {\n input?: string,\n entityName: string,\n firebaseToken: string,\n apiKey: string,\n host?: string\n}): Promise<SamplePromptsResult> {\n\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/prompt_autocomplete/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`,\n \"x-de-api-key\": `Basic ${props.apiKey}`\n },\n body: JSON.stringify({\n entityName: props.entityName,\n input: props.input ?? null\n })\n })\n .then(async (res) => {\n const data = await res.json();\n if (!res.ok) {\n console.error(\"fetchEntityPromptSuggestion\", data);\n throw Error(data.message);\n }\n return {\n prompts: data.data.prompts.map((e: string) => ({\n prompt: e,\n type: \"sample\"\n }))\n };\n });\n\n}\n\nexport async function autocompleteStream(props: {\n firebaseToken: string,\n textBefore?: string,\n textAfter: string,\n host?: string;\n onUpdate: (delta: string) => void;\n}) {\n\n let result = \"\";\n return fetch((props.host ?? DEFAULT_SERVER) + \"/data/autocomplete/\",\n {\n // mode: \"no-cors\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Basic ${props.firebaseToken}`\n // \"x-de-version\": version\n },\n body: JSON.stringify({\n textBefore: props.textBefore,\n textAfter: props.textAfter\n })\n })\n .then(async (res) => {\n if (!res.ok) {\n console.error(\"enhanceDataAPIStream error\", res)\n throw await res.json();\n }\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"No reader\");\n }\n\n for await (const chunk of readChunks(reader)) {\n const str = new TextDecoder().decode(chunk);\n result += str;\n console.debug(\"Autocomplete update:\", str);\n props.onUpdate(str);\n }\n\n }).then(() => {\n console.debug(\"Autocomplete result:\", result);\n return result;\n });\n\n}\n","export function getAppendableSuggestion(suggestion: string | number | undefined, value: unknown): string | undefined {\n const suggestionIncludesValue = typeof suggestion === \"string\" && typeof value === \"string\" && suggestion.toLowerCase().trim().startsWith(value.toLowerCase().trim());\n return (typeof value === \"string\" && suggestionIncludesValue)\n ? suggestion.substring(suggestion.toLowerCase().trim().indexOf(value.toLowerCase().trim()) + value.trim().length)\n : undefined;\n}\n","import { getFieldId } from \"@rebasepro/admin\";\nimport { EnumValues, Properties, Property } from \"@rebasepro/types\";\nimport { isPropertyBuilder } from \"@rebasepro/common\";\nimport { InputProperty } from \"../types/data_enhancement_controller\";\nimport { getValueInPath } from \"@rebasepro/utils\";\n\nexport function getSimplifiedProperties<M extends Record<string, any>>(properties: Properties, values: M, path = \"\"): Record<string, InputProperty> {\n if (!properties) return {};\n return Object.entries(properties)\n .map(([key, property]) => {\n if (isPropertyBuilder(property)) return {};\n const fullKey = path ? `${path}.${key}` : key;\n const valueInPath = getValueInPath(values, fullKey);\n return getSimplifiedProperty(property, fullKey, valueInPath)\n })\n .reduce((a, b) => ({ ...a,\n...b }), {});\n}\n\nfunction getSimpleProperty(property: Property): InputProperty {\n const fieldId = getFieldId(property);\n if (!fieldId) {\n console.error(\"No fieldId found for property\", property);\n throw new Error(\"Field id not found\");\n }\n return {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: fieldId,\n enum: \"enum\" in property && property.enum\n ? getSimpleEnumValues(property.enum)\n : undefined,\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly)\n };\n}\n\nfunction getSimplifiedProperty(property: Property, path: string, value?: unknown): Record<string, InputProperty> {\n if (isPropertyBuilder(property)) return {};\n if (property.type === \"array\") {\n\n if (property.of && !Array.isArray(property.of) && !isPropertyBuilder(property.of)) {\n const arrayParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"repeat\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly),\n of: getSimpleProperty(property.of as Property)\n };\n\n const result = { [path]: arrayParentProperty };\n // if (Array.isArray(value)) {\n // result = {\n // ...result,\n // ...value\n // .map((v, i) => getSimplifiedProperty(property.of, `${path}.${i}`, v))\n // .reduce((a, b) => ({ ...a, ...b }), {})\n // };\n // }\n //\n // const existingValuesCount = Array.isArray(value) ? value.length : 0;\n //\n // const newValuesCount = property.of && !isPropertyBuilder<any, any>(property.of) && (property.of as Property).type === \"map\" ? 1 : 3;\n // result = {\n // ...result,\n // // ...Array.from(Array(newValuesCount))\n // // .map((v, i) => getSimplifiedProperty(property.of, `${path}.${i + existingValuesCount}`, v))\n // // .reduce((a, b) => ({ ...a, ...b }), {})\n // }\n\n return result;\n } else if (property.oneOf) {\n\n const arrayParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"block\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly),\n oneOf: {\n typeField: property.oneOf.typeField,\n valueField: property.oneOf.valueField,\n properties: Object.entries(property.oneOf.properties)\n .map(([key, prop]) => ({ [key]: getSimpleProperty(prop) }))\n .reduce((a, b) => ({ ...a,\n...b }), {})\n }\n };\n\n if (!Array.isArray(value)) {\n return { [path]: arrayParentProperty };\n }\n\n return value.map((v, i) => {\n if (v == null) return {};\n const typeKey = property.oneOf!.typeField ?? \"type\";\n const oneOfType = v[typeKey];\n const valueKey = property.oneOf!.valueField ?? \"value\";\n const oneOfValue = v[valueKey];\n const childProperty = property.oneOf!.properties[oneOfType];\n if (childProperty === undefined) {\n console.error(`No property found for type ${oneOfType}`, property.oneOf!.properties);\n return {};\n }\n const simplifiedProperty = getSimplifiedProperty(childProperty, `${path}.${i}.${valueKey}`, oneOfValue);\n return {\n [`${path}.${i}.${typeKey}`]: oneOfType,\n ...simplifiedProperty\n };\n }).reduce((a, b) => ({ ...a,\n...b }), { [path]: arrayParentProperty });\n }\n } else if (property.type === \"map\") {\n if (property.properties) {\n const mapProperties: Record<string, InputProperty> = Object.entries(property.properties)\n .map(([key, childProperty]) => {\n const childValue = value && typeof value === \"object\" ? (value as Record<string, unknown>)[key] : undefined;\n return getSimplifiedProperty(childProperty, key, childValue);\n })\n .map(o => attachPathToKeys(o, path))\n .reduce((a, b) => ({ ...a,\n...b }), {});\n\n if (Object.keys(mapProperties).length === 0) return {};\n const mapParentProperty: InputProperty = {\n name: property.name,\n description: property.description,\n type: property.type,\n fieldConfigId: \"group\",\n disabled: Boolean(property.ui?.disabled || property.ui?.readOnly)\n };\n return {\n [path]: mapParentProperty,\n ...mapProperties\n } as Record<string, InputProperty>;\n }\n } else {\n const fieldId = getFieldId(property);\n if (!fieldId) {\n console.warn(`No fieldId found for property ${path} with type ${property.type}`);\n return {};\n }\n return {\n [path]: getSimpleProperty(property)\n };\n }\n return {};\n}\n\n// attach a path to every key in an object\nfunction attachPathToKeys(obj: Record<string, InputProperty>, path = \"\"): Record<string, InputProperty> {\n return Object.entries(obj)\n .map(([key, value]) => {\n const fullKey = path ? `${path}.${key}` : key;\n return { [fullKey]: value };\n })\n .reduce((a, b) => ({ ...a,\n...b }), {});\n}\n\nfunction getSimpleEnumValues(enumValues: EnumValues): string[] {\n if (Array.isArray(enumValues))\n return enumValues.map(v => String(v.id));\n if (typeof enumValues === \"object\")\n return Object.keys(enumValues);\n throw Error(\"getSimpleEnumValues: Invalid enumValues\");\n}\n","import { autocompleteStream } from \"../api\";\nimport { EditorAIController } from \"@rebasepro/admin\";\n\nexport function useEditorAIController({ getAuthToken }: { getAuthToken?: () => Promise<string> }): EditorAIController {\n const autocomplete = async (textBefore: string, textAfter: string, onUpdate: (delta: string) => void) => {\n if (!getAuthToken) {\n throw new Error(\"Firebase token is required\");\n }\n const firebaseToken = await getAuthToken();\n return autocompleteStream({\n firebaseToken,\n textBefore,\n textAfter,\n onUpdate\n });\n }\n\n return {\n autocomplete\n };\n}\n\n// async function * generateLoremIpsum(): AsyncGenerator<string> {\n// const loremIpsum = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\\n# Heading\\n\\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\";\n//\n// const words = loremIpsum.split(\" \");\n//\n// for (const word of words) {\n// yield word;\n// await new Promise(resolve => setTimeout(resolve, 100));\n// }\n// }\n//\n// const generator = generateLoremIpsum();\n// for await (const word of generator) {\n//\n// }\n","import React, { PropsWithChildren, useCallback, useContext, useEffect, useMemo, useRef, useState } from \"react\";\n\nimport {\n DataEnhancementController,\n EnhancedDataResult,\n EnhanceParams,\n InputProperty\n} from \"../types/data_enhancement_controller\";\nimport {\n useAuthController,\n useCustomizationController,\n useSnackbarController\n} from \"@rebasepro/core\";\nimport { useUrlController } from \"@rebasepro/admin\";\nimport { DataDriver, Entity, EntityCollection, PluginFormActionProps } from \"@rebasepro/types\";\nimport { enhanceDataAPIStream, fetchEntityPromptSuggestion } from \"../api\";\nimport { getAppendableSuggestion } from \"../utils/suggestions\";\nimport { getSimplifiedProperties } from \"../utils/properties\";\nimport { useEditorAIController } from \"../editor/useEditorAIController\";\nimport { getValueInPath } from \"@rebasepro/utils\";\n\nconst DataEnhancementControllerContext = React.createContext<DataEnhancementController>(null! as DataEnhancementController);\n\ntype DataEnhancementControllerProviderProps = {\n\n apiKey: string;\n\n getConfigForPath?: (props: {\n path: string,\n collection: EntityCollection\n }) => boolean;\n\n host?: string;\n}\n\nexport const useDataEnhancementController = (): DataEnhancementController => useContext(DataEnhancementControllerContext);\n\nfunction getPropertyFromKey(properties: Record<string, InputProperty>, propertyKey: string) {\n if (propertyKey in properties) {\n return properties[propertyKey];\n } else {\n //split the property key\n const split = propertyKey.split(\".\");\n if (split.length === 1) {\n return undefined;\n }\n const parentKey = split.slice(0, split.length - 1).join(\".\");\n return getPropertyFromKey(properties, parentKey);\n\n }\n}\n\nexport function DataEnhancementControllerProvider({\n apiKey,\n getConfigForPath,\n children,\n host,\n path,\n collection,\n formContext\n}: PropsWithChildren<DataEnhancementControllerProviderProps & PluginFormActionProps>) {\n\n const [enabled, setEnabled] = useState(false);\n const [suggestions, setSuggestions] = useState<Record<string, string | number>>({});\n const [loadingSuggestions, setLoadingSuggestions] = useState<string[]>([]);\n\n const enhancingInProgress = useRef(false);\n\n const authController = useAuthController();\n const snackbarController = useSnackbarController();\n\n\n const properties = useMemo(() => getSimplifiedProperties(collection.properties, formContext?.values ?? {}), [formContext?.values]);\n // const preEnhanceValuesRef = React.useRef(formContext?.values ?? {});\n const valuesRef = React.useRef(formContext?.values ?? {});\n useEffect(() => {\n if (!enhancingInProgress.current)\n valuesRef.current = formContext?.values ?? {};\n }, [formContext?.values]);\n\n const allowReferenceDataSelection = false;\n\n const updateConfig = useCallback(async () => {\n if (!getConfigForPath) return;\n const config = getConfigForPath({\n path,\n collection\n });\n if (config) {\n setEnabled(true);\n }\n }, [collection, getConfigForPath, path]);\n\n useEffect(() => {\n if (!getConfigForPath) {\n setEnabled(true);\n } else {\n updateConfig();\n }\n\n }, [getConfigForPath, updateConfig]);\n\n\n const urlController = useUrlController();\n\n const clearSuggestion = useCallback((propertyKey: string) => {\n setSuggestions((prev) => {\n //remove propertyKey from prev\n const {\n [propertyKey]: _,\n ...rest\n } = prev;\n return rest;\n });\n }, []);\n\n const appendValueDelta = useCallback((propertyKey: string, delta: string) => {\n\n const property = getPropertyFromKey(properties, propertyKey);\n if (delta === null || property?.disabled) {\n return;\n }\n\n // clearSuggestion(propertyKey);\n const value = getValueInPath(valuesRef.current, propertyKey);\n\n const currentValue = value ? (value as string) + \"\" : \"\";\n const updatedValue = currentValue + delta;\n // if (currentValue.length === 0) updatedValue = updatedValue.trimStart();\n valuesRef.current = {\n ...valuesRef.current,\n [propertyKey]: updatedValue\n };\n formContext?.setFieldValue(propertyKey, updatedValue, false);\n setSuggestions(prev => ({\n ...prev,\n [propertyKey]: (prev[propertyKey] ?? \"\") + delta\n }));\n }, [properties, formContext]);\n\n const updateSuggestedValues = useCallback((currentValues: object, updatedValues: Record<string, string | number>, replaceValues: boolean) => {\n\n setLoadingSuggestions((prev) => {\n return prev.filter(p => !Object.keys(updatedValues).includes(p));\n });\n\n Object.entries(updatedValues).forEach(([propertyKey, suggestion]) => {\n\n const value = getValueInPath(currentValues, propertyKey);\n const property = getPropertyFromKey(properties, propertyKey);\n\n if (!property || suggestion === null || property?.disabled) {\n return;\n }\n\n if (typeof suggestion === \"number\") {\n formContext?.setFieldValue(propertyKey, suggestion);\n return;\n }\n\n if (replaceValues) {\n formContext?.setFieldValue(propertyKey, suggestion);\n return;\n }\n\n const appendableValue = getAppendableSuggestion(suggestion, value);\n\n const currentValue = value ? (value as string) + \"\" : \"\";\n if (appendableValue) {\n formContext?.setFieldValue(propertyKey, suggestion);\n } else {\n const multiline = property?.fieldConfigId === \"multiline\" || property?.fieldConfigId === \"markdown\";\n const trimmedValue = currentValue.trimEnd();\n if (multiline && (trimmedValue.endsWith(\".\") || trimmedValue.endsWith(\"?\") || trimmedValue.endsWith(\"!\") || trimmedValue.endsWith(\":\"))) {\n formContext?.setFieldValue(propertyKey, trimmedValue + \"\\n\\n\" + (suggestion as string).trimStart());\n } else {\n formContext?.setFieldValue(propertyKey, trimmedValue + (trimmedValue.length > 0 ? \" \" : \"\") + (suggestion as string));\n }\n }\n });\n\n setSuggestions(prev => ({\n ...prev,\n ...Object.keys(updatedValues)\n .reduce((acc, key) => {\n const value = getValueInPath(formContext?.values, key);\n const suggestion = updatedValues[key];\n return {\n ...acc,\n [key]: getAppendableSuggestion(suggestion, value) ?? suggestion\n };\n }, {})\n }));\n }, [properties, formContext]);\n\n const displayNeededSubscriptionSnackbar = useCallback((projectId: unknown) => {\n snackbarController.open({\n type: \"warning\",\n message: \"A valid subscription is needed in order to use this function.\",\n autoHideDuration: 4000\n });\n }, [snackbarController]);\n\n const editorAIController = useEditorAIController({ getAuthToken: authController.getAuthToken });\n\n const clearAllSuggestions = useCallback(() => {\n setSuggestions({});\n }, []);\n\n const enhance = useCallback(async (props: EnhanceParams<Record<string, unknown>>): Promise<EnhancedDataResult | null> => {\n\n if (!authController.user) {\n snackbarController.open({\n type: \"warning\",\n message: \"You need to be logged in to enhance data\"\n });\n return Promise.reject(new Error(\"Not logged in\"));\n }\n\n const resolvedPath = urlController.resolveDatabasePathsFrom(path);\n const firebaseToken = await authController.getAuthToken();\n\n if (props.propertyKey) {\n clearSuggestion(props.propertyKey)\n } else {\n clearAllSuggestions();\n }\n\n setLoadingSuggestions((prev) => [...prev, ...(props.propertyKey ? [props.propertyKey] : Object.keys(properties))]);\n enhancingInProgress.current = true;\n\n const currentValues = valuesRef.current ?? {};\n\n return new Promise((resolve, reject) => {\n function onError(e: unknown) {\n setLoadingSuggestions([]);\n const err = e instanceof Error ? e : typeof e === \"object\" && e !== null ? e : new Error(String(e));\n const errorObj = err as Record<string, unknown>;\n if (errorObj.code === \"payment-required\") {\n const data = errorObj.data as Record<string, unknown> | undefined;\n const projectId = data?.projectId;\n displayNeededSubscriptionSnackbar(projectId);\n } else {\n console.error(\"Enhance error\", e);\n }\n reject(e);\n enhancingInProgress.current = false;\n }\n\n try {\n enhanceDataAPIStream({\n ...props,\n host,\n apiKey,\n properties,\n path: resolvedPath,\n entityName: collection.singularName ?? collection.name,\n entityDescription: collection.description,\n\n firebaseToken,\n onUpdate: (suggestions) => {\n console.debug(\"de onUpdate\", suggestions);\n updateSuggestedValues(currentValues, suggestions, props.replaceValues ?? false);\n },\n onUpdateDelta: (propertyKey: string, partialValue: string) => {\n // console.debug(\"de delta\", propertyKey, partialValue);\n appendValueDelta(propertyKey, partialValue);\n },\n onError,\n onEnd: (result) => {\n console.debug(\"de onEnd\", result);\n if (result.errors) {\n result.errors.forEach((error) => {\n snackbarController.open({\n type: \"warning\",\n message: error\n })\n });\n }\n if (Object.keys(result.suggestions).length === 0) {\n snackbarController.open({\n type: \"info\",\n autoHideDuration: 1800,\n message: \"No fields were updated\"\n })\n }\n setLoadingSuggestions([]);\n resolve(result);\n enhancingInProgress.current = false;\n }\n }).catch(onError);\n } catch (e: unknown) {\n onError(e);\n }\n });\n }, [\n authController, urlController, path, clearSuggestion, clearAllSuggestions,\n properties, host, apiKey, collection, updateSuggestedValues, appendValueDelta, displayNeededSubscriptionSnackbar, snackbarController\n ]);\n\n const getSamplePrompts = useCallback(async (entityName: string, input?: string) => {\n const firebaseToken = await authController.getAuthToken()\n return fetchEntityPromptSuggestion({\n host,\n entityName,\n firebaseToken,\n apiKey,\n input\n });\n }, [apiKey, authController.getAuthToken, host]);\n\n const dataEnhancementController: DataEnhancementController = useMemo(() => ({\n enabled,\n suggestions,\n clearSuggestion,\n enhance,\n allowReferenceDataSelection,\n clearAllSuggestions,\n getSamplePrompts,\n loadingSuggestions,\n editorAIController\n }), [\n enabled,\n suggestions,\n clearSuggestion,\n enhance,\n allowReferenceDataSelection,\n clearAllSuggestions,\n getSamplePrompts,\n loadingSuggestions,\n editorAIController\n ]);\n\n return (\n <DataEnhancementControllerContext.Provider\n value={dataEnhancementController}>\n {children}\n </DataEnhancementControllerContext.Provider>\n );\n}\n\n\n","\nimport React, { useCallback, useDeferredValue, useEffect, useRef } from \"react\";\n\nimport {\n Button,\n CircularProgress,\n cls,\n focusedDisabled,\n IconButton,\n iconSize,\n Menu,\n MenuItem,\n SendIcon,\n Separator,\n TextareaAutosize,\n XIcon\n} from \"@rebasepro/ui\";\nimport {\n AIIcon,\n useLargeLayout\n} from \"@rebasepro/core\";\nimport { EntityStatus, PluginFormActionProps, Properties, Property } from \"@rebasepro/types\";\nimport { isPropertyBuilder, stripCollectionPath } from \"@rebasepro/common\";\nimport { useDataEnhancementController } from \"./DataEnhancementControllerProvider\";\nimport { SamplePrompt } from \"../types/data_enhancement_controller\";\n\nexport function FormEnhanceAction({\n entityId,\n path,\n status,\n collection,\n formContext,\n openEntityMode\n}: PluginFormActionProps) {\n\n const largeLayout = useLargeLayout();\n\n const storageKey = createLocalStorageKey(path, status);\n\n const [loading, setLoading] = React.useState(false);\n const dataEnhancementController = useDataEnhancementController();\n\n const [samplePrompts, setSamplePrompts] = React.useState<SamplePrompt[] | undefined>(undefined);\n const [instructions, setInstructions] = React.useState<string>(\"\");\n\n const getSamplePrompts = dataEnhancementController?.getSamplePrompts;\n\n const loadingPrompts = useRef(false);\n const updateSuggestedPrompts = useCallback(async function updateSuggestedPrompts(instructions?: string) {\n if (!getSamplePrompts) return;\n if (loadingPrompts.current) return;\n loadingPrompts.current = true;\n const prompts = status === \"new\"\n ? (await getSamplePrompts(collection.singularName ?? collection.name, instructions)).prompts\n : getPromptsForExistingEntities(collection.properties);\n\n const recentPromptsFromStorage = getRecentPromptsFromStorage(storageKey);\n const recentPrompts = recentPromptsFromStorage.map(prompt => prompt.prompt);\n setSamplePrompts([...recentPromptsFromStorage, ...prompts.filter(p => !recentPrompts.includes(p.prompt))].slice(0, 5));\n loadingPrompts.current = false;\n },\n [collection.name, collection.singularName, getSamplePrompts, status]);\n\n const deferredValues = useDeferredValue(formContext?.values);\n // const enoughData = countStringCharacters(deferredValues, collection.properties) > 20;\n\n useEffect(() => {\n if (!dataEnhancementController) return;\n if (!samplePrompts) {\n setSamplePrompts(getRecentPromptsFromStorage(storageKey));\n updateSuggestedPrompts().then();\n }\n }, [dataEnhancementController, samplePrompts, storageKey, updateSuggestedPrompts, instructions, status]);\n\n useEffect(() => {\n if (!dataEnhancementController) return;\n updateSuggestedPrompts().then();\n }, [dataEnhancementController, status]);\n\n const enhance = (prompt?: string) => {\n if (!dataEnhancementController || !formContext?.values) return;\n setLoading(true);\n if (prompt) {\n addRecentPrompt(storageKey, prompt);\n setSamplePrompts([{\n prompt,\n type: \"recent\"\n }, ...(samplePrompts ?? []).slice(0, 5)]);\n }\n return dataEnhancementController.enhance({\n entityId,\n values: formContext!.values,\n instructions: prompt,\n replaceValues: true\n }).finally(() => {\n setLoading(false);\n });\n };\n\n if (!dataEnhancementController?.enabled)\n return null;\n\n const suggestions = dataEnhancementController.suggestions;\n const hasSuggestions = Object.values(suggestions).filter(Boolean).length > 0;\n\n const disabledSuggestionActions = !hasSuggestions;\n const promptSuggestionsEnabled = (samplePrompts ?? []).length > 0 && instructions.length === 0;\n\n // const noIdSet = !formContext?.entityId;\n\n function submit() {\n enhance(instructions);\n }\n\n return (\n <Menu\n align={\"end\"}\n sideOffset={8}\n className={\"max-w-[100vw]\"}\n trigger={<Button variant={\"filled\"}\n color={\"neutral\"}\n fullWidth={largeLayout && openEntityMode === \"full_screen\"}\n size={\"small\"}\n disabled={loading}>\n {!loading && <AIIcon size={\"small\"}/>}\n {loading && <CircularProgress size={\"small\"}/>}\n Autofill\n </Button>}>\n\n <MenuItem className={\"py-4\"}\n onClick={() => {\n enhance();\n }}>\n <AIIcon size={\"small\"}/>\n Autofill based on the current content\n </MenuItem>\n\n <Separator orientation={\"horizontal\"} className={\"mt-2\"}/>\n\n {samplePrompts?.map((samplePrompt, index) => {\n return <MenuItem\n key={index + \"_\" + samplePrompt.prompt}\n onClick={() => {\n setInstructions(samplePrompt.prompt);\n enhance(samplePrompt.prompt);\n }}\n >\n <div className={\"pl-9 grow text-text-secondary dark:text-text-secondary-dark\"}>\n {samplePrompt.prompt}\n </div>\n\n {samplePrompt.type === \"recent\" && <IconButton\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n removeRecentPrompt(storageKey, samplePrompt.prompt);\n setSamplePrompts((samplePrompts ?? []).filter(p => p.prompt !== samplePrompt.prompt));\n }}\n size={\"smallest\"}\n >\n <XIcon size={iconSize.smallest}/>\n </IconButton>\n }\n </MenuItem>;\n })}\n\n <Separator orientation={\"horizontal\"}/>\n\n <div\n className={cls(\n \"my-2 w-[500px] max-w-full flex items-start text-surface-700 dark:text-surface-200\"\n )}>\n\n <TextareaAutosize\n className={cls(\"p-4 rounded-lg resize-none bg-surface-100 dark:bg-surface-950 mx-2 w-full grow outline-hidden max-h-[300px] overflow-auto\", focusedDisabled)}\n value={instructions}\n autoFocus={status === \"new\"}\n disabled={loading}\n onFocus={(event) => {\n event.stopPropagation();\n }}\n placeholder={\"...or provide instructions\"}\n onKeyDown={(e) => {\n e.stopPropagation();\n if (e.key === \"Enter\" && !e.shiftKey) {\n e.preventDefault();\n submit();\n }\n\n }}\n onChange={(e) => {\n setInstructions(e.target.value);\n }}\n />\n\n <IconButton\n size={\"small\"}\n onClick={() => {\n setInstructions(\"\");\n }}\n color={!instructions ? \"primary\" : undefined}\n disabled={loading || !instructions}>\n <XIcon size={iconSize.small}/>\n </IconButton>\n\n <IconButton\n onClick={() => enhance(instructions)}\n size={\"small\"}\n color={!instructions ? \"primary\" : undefined}\n disabled={loading || !instructions}>\n {loading &&\n <CircularProgress size={\"smallest\"}/>}\n {!loading &&\n <SendIcon color={\"primary\"}/>}\n </IconButton>\n\n </div>\n\n </Menu>\n );\n}\n\nfunction getPromptsForExistingEntities(properties: Properties): SamplePrompt[] {\n\n const multilineProperties = Object.values(properties).filter((p: Property) => {\n if (isPropertyBuilder(p)) {\n return false;\n }\n return p.type === \"string\" && (p.ui?.markdown || p.ui?.multiline);\n });\n\n const multilinePrompt: Property | undefined = multilineProperties.length > 0\n ? multilineProperties[Math.floor(Math.random() * multilineProperties.length)] as Property\n : undefined;\n\n const prompts = [\n \"Fill the missing fields\",\n \"Translate the missing content\"\n ];\n if (multilinePrompt) {\n prompts.push(`Add 2 paragraphs to '${multilinePrompt.name}'`);\n }\n return prompts.map(p => ({\n prompt: p,\n type: \"sample\"\n }));\n}\n\nconst createLocalStorageKey = (path: string, status: EntityStatus) => {\n const statusString = status === \"new\" ? \"new\" : \"existing\";\n return `data_enhancement::${statusString}::${stripCollectionPath(path)}`;\n};\n\nconst getRecentPromptsFromStorage = (storageKey: string): SamplePrompt[] => {\n const item = localStorage.getItem(storageKey);\n return item ? JSON.parse(item).map((e: string) => ({\n prompt: e,\n type: \"recent\"\n })) : [];\n};\n\nconst addRecentPrompt = (storageKey: string, prompt: string) => {\n if (!prompt || prompt.trim().length === 0) {\n return;\n }\n const recentPrompts = getRecentPromptsFromStorage(storageKey);\n localStorage.setItem(storageKey, JSON.stringify([prompt, ...recentPrompts\n .map(e => e.prompt)\n .filter(e => e !== prompt)\n .slice(0, 5)]));\n};\n\nconst removeRecentPrompt = (storageKey: string, prompt: string) => {\n localStorage.setItem(storageKey, JSON.stringify(getRecentPromptsFromStorage(storageKey)\n .map(e => e.prompt)\n .filter(e => e !== prompt)));\n};\n","import React from \"react\";\n\nimport { EntityCollection, RebasePlugin, User } from \"@rebasepro/types\";\nimport { DataEnhancementControllerProvider } from \"./components/DataEnhancementControllerProvider\";\nimport { FormEnhanceAction } from \"./components/FormEnhanceAction\";\n\nconst DEFAULT_API_KEY = \"fcms-U9jdDii0xXWSDC34asfrf54lbkFJBfKfRWcEDEwdc4V5wDWEDF\";\n\nexport interface DataEnhancementPluginProps {\n\n apiKey?: string;\n\n /**\n * Use this function to determine if the data enhancement plugin should be enabled for a given path.\n * If this function is not provided, the plugin will be enabled for all paths.\n * If the function returns false, the plugin will be disabled for the given path.\n * You can also return a configuration object to override the default configuration.\n *\n * @param path\n * @param collection\n */\n getConfigForPath?: (props: {\n path: string,\n collection: EntityCollection,\n user: User | null\n }) => boolean;\n\n /**\n * Host to use for the data enhancement API.\n * This prop is only use in development mode.\n */\n host?: string;\n}\n\n/**\n * Use this hook to initialise the data enhancement plugin.\n * This is likely the only hook you will need to use.\n * @param props\n */\nexport function useDataEnhancementPlugin(props?: DataEnhancementPluginProps): RebasePlugin {\n\n const apiKey = props?.apiKey ?? DEFAULT_API_KEY;\n const getConfigForPath = props?.getConfigForPath;\n\n return React.useMemo(() => ({\n key: \"data_enhancement\",\n slots: [\n {\n slot: \"form.actions\",\n Component: FormEnhanceAction,\n order: 40\n }\n ],\n providers: [\n {\n scope: \"form\" as const,\n Component: DataEnhancementControllerProvider as React.ComponentType<any>,\n props: {\n apiKey,\n getConfigForPath,\n host: props?.host\n }\n }\n ]\n }), [apiKey, getConfigForPath, props?.host]);\n}\n"],"names":["flatMapEntityValues","values","path","Object","entries","flatMap","key","value","currentPath","reduce","acc","curr","DEFAULT_SERVER","enhanceDataAPIStream","props","flatValues","properties","inputEntity","entityId","request","entityName","entityDescription","propertyKey","propertyInstructions","instructions","console","debug","fetch","host","method","headers","Authorization","firebaseToken","apiKey","body","JSON","stringify","then","res","ok","error","json","reader","getReader","Error","chunk","readChunks","str","TextDecoder","decode","split","forEach","s","length","data","parse","trim","type","onUpdateDelta","partialValue","onUpdate","onEnd","e","onError","String","Symbol","asyncIterator","readResult","read","done","fetchEntityPromptSuggestion","input","message","prompts","map","prompt","autocompleteStream","result","textBefore","textAfter","getAppendableSuggestion","suggestion","suggestionIncludesValue","toLowerCase","startsWith","substring","indexOf","undefined","getSimplifiedProperties","property","isPropertyBuilder","fullKey","valueInPath","getValueInPath","getSimplifiedProperty","a","b","getSimpleProperty","fieldId","getFieldId","name","description","fieldConfigId","enum","getSimpleEnumValues","disabled","Boolean","ui","readOnly","of","Array","isArray","arrayParentProperty","oneOf","typeField","valueField","prop","v","i","typeKey","oneOfType","valueKey","oneOfValue","childProperty","simplifiedProperty","mapProperties","childValue","o","attachPathToKeys","keys","mapParentProperty","warn","obj","enumValues","id","useEditorAIController","getAuthToken","autocomplete","DataEnhancementControllerContext","React","createContext","useDataEnhancementController","useContext","getPropertyFromKey","parentKey","slice","join","DataEnhancementControllerProvider","getConfigForPath","children","collection","formContext","enabled","setEnabled","useState","suggestions","setSuggestions","loadingSuggestions","setLoadingSuggestions","enhancingInProgress","useRef","authController","useAuthController","snackbarController","useSnackbarController","useMemo","valuesRef","useEffect","current","allowReferenceDataSelection","updateConfig","useCallback","config","urlController","useUrlController","clearSuggestion","prev","_","rest","appendValueDelta","delta","currentValue","updatedValue","setFieldValue","updateSuggestedValues","currentValues","updatedValues","replaceValues","filter","p","includes","appendableValue","multiline","trimmedValue","trimEnd","endsWith","trimStart","displayNeededSubscriptionSnackbar","projectId","open","autoHideDuration","editorAIController","clearAllSuggestions","enhance","user","Promise","reject","resolvedPath","resolveDatabasePathsFrom","resolve","err","errorObj","code","singularName","errors","catch","getSamplePrompts","dataEnhancementController","FormEnhanceAction","status","openEntityMode","largeLayout","useLargeLayout","storageKey","createLocalStorageKey","loading","setLoading","samplePrompts","setSamplePrompts","setInstructions","loadingPrompts","updateSuggestedPrompts","getPromptsForExistingEntities","recentPromptsFromStorage","getRecentPromptsFromStorage","recentPrompts","useDeferredValue","addRecentPrompt","finally","submit","samplePrompt","index","preventDefault","stopPropagation","removeRecentPrompt","iconSize","smallest","cls","focusedDisabled","event","shiftKey","target","small","multilineProperties","markdown","multilinePrompt","Math","floor","random","push","statusString","stripCollectionPath","item","localStorage","getItem","setItem","DEFAULT_API_KEY","useDataEnhancementPlugin","$","_c","t0","t1","for","slot","Component","order","t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