@rebasepro/plugin-data-enhancement 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/LICENSE +17 -109
  2. package/README.md +1 -1
  3. package/dist/common/src/util/entities.d.ts +2 -2
  4. package/dist/common/src/util/relations.d.ts +1 -1
  5. package/dist/core/src/components/LoginView/LoginView.d.ts +1 -6
  6. package/dist/core/src/contexts/SnackbarProvider.d.ts +1 -1
  7. package/dist/core/src/hooks/data/save.d.ts +2 -2
  8. package/dist/core/src/hooks/data/useEntityFetch.d.ts +5 -0
  9. package/dist/core/src/hooks/useResolvedComponent.d.ts +1 -1
  10. package/dist/index.es.js +1 -2
  11. package/dist/index.es.js.map +1 -1
  12. package/dist/index.umd.js +5 -5
  13. package/dist/index.umd.js.map +1 -1
  14. package/dist/types/src/controllers/auth.d.ts +9 -8
  15. package/dist/types/src/controllers/client.d.ts +3 -0
  16. package/dist/types/src/types/auth_adapter.d.ts +356 -0
  17. package/dist/types/src/types/collections.d.ts +67 -2
  18. package/dist/types/src/types/database_adapter.d.ts +94 -0
  19. package/dist/types/src/types/entity_actions.d.ts +7 -1
  20. package/dist/types/src/types/entity_callbacks.d.ts +1 -1
  21. package/dist/types/src/types/entity_views.d.ts +36 -1
  22. package/dist/types/src/types/index.d.ts +2 -0
  23. package/dist/types/src/types/plugins.d.ts +1 -1
  24. package/dist/types/src/types/properties.d.ts +24 -5
  25. package/dist/types/src/types/property_config.d.ts +6 -2
  26. package/dist/types/src/types/relations.d.ts +1 -1
  27. package/dist/types/src/types/translations.d.ts +8 -0
  28. package/dist/types/src/users/user.d.ts +5 -0
  29. package/dist/ui/src/components/FilterChip.d.ts +42 -0
  30. package/dist/ui/src/components/index.d.ts +5 -0
  31. package/dist/ui/src/icons/index.d.ts +2 -0
  32. package/package.json +15 -16
  33. package/src/components/FormEnhanceAction.tsx +14 -2
package/LICENSE CHANGED
@@ -1,114 +1,22 @@
1
- Business Source License 1.1
1
+ MIT License
2
2
 
3
- Parameters
3
+ Copyright (c) 2026 Rebase
4
4
 
5
- Licensor: Rebase S.L.
6
- Licensed Work: Rebase CMS packages:
7
- cli
8
- collection_editor
9
- collection_editor_firebase
10
- data_enhancement
11
- data_export
12
- data_export
13
- editor
14
- rebase_cloud
15
- schema_inference
16
- user_management
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
17
11
 
18
- The Licensed Work is (c) 2024 Rebase S.L
19
- Additional Use Grant: You may make use of the Licensed Work, provided that
20
- you may not use the Licensed Work for a CMS Data Enhancement
21
- Service.
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
22
14
 
23
- A “CMS package” is a commercial offering that
24
- allows third parties (other than your employees and
25
- contractors) to access the functionality of the
26
- Licensed Work by using software to extend the base features of
27
- content management system controlled by such third parties.
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
28
22
 
29
- Change Date: Four years from the date the Licensed Work is published.
30
-
31
- Change License: MIT
32
-
33
- For information about alternative licensing arrangements for the Software,
34
- please visit: https://rebase.pro
35
-
36
- Notice
37
-
38
- The Business Source License (this document, or the “License”) is not an Open
39
- Source license. However, the Licensed Work will eventually be made available
40
- under an Open Source License, as stated in this License.
41
-
42
- License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved.
43
- “Business Source License” is a trademark of MariaDB Corporation Ab.
44
-
45
- -----------------------------------------------------------------------------
46
-
47
- Business Source License 1.1
48
-
49
- Terms
50
-
51
- The Licensor hereby grants you the right to copy, modify, create derivative
52
- works, redistribute, and make non-production use of the Licensed Work. The
53
- Licensor may make an Additional Use Grant, above, permitting limited
54
- production use.
55
-
56
- Effective on the Change Date, or the fourth anniversary of the first publicly
57
- available distribution of a specific version of the Licensed Work under this
58
- License, whichever comes first, the Licensor hereby grants you rights under
59
- the terms of the Change License, and the rights granted in the paragraph
60
- above terminate.
61
-
62
- If your use of the Licensed Work does not comply with the requirements
63
- currently in effect as described in this License, you must purchase a
64
- commercial license from the Licensor, its affiliated entities, or authorized
65
- resellers, or you must refrain from using the Licensed Work.
66
-
67
- All copies of the original and modified Licensed Work, and derivative works
68
- of the Licensed Work, are subject to this License. This License applies
69
- separately for each version of the Licensed Work and the Change Date may vary
70
- for each version of the Licensed Work released by Licensor.
71
-
72
- You must conspicuously display this License on each original or modified copy
73
- of the Licensed Work. If you receive the Licensed Work in original or
74
- modified form from a third party, the terms and conditions set forth in this
75
- License apply to your use of that work.
76
-
77
- Any use of the Licensed Work in violation of this License will automatically
78
- terminate your rights under this License for the current and all other
79
- versions of the Licensed Work.
80
-
81
- This License does not grant you any right in any trademark or logo of
82
- Licensor or its affiliates (provided that you may use a trademark or logo of
83
- Licensor as expressly required by this License).
84
-
85
- TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
86
- AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
87
- EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
88
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
89
- TITLE.
90
-
91
- MariaDB hereby grants you permission to use this License’s text to license
92
- your works, and to refer to it using the trademark “Business Source License”,
93
- as long as you comply with the Covenants of Licensor below.
94
-
95
- Covenants of Licensor
96
-
97
- In consideration of the right to use this License’s text and the “Business
98
- Source License” name and trademark, Licensor covenants to MariaDB, and to all
99
- other recipients of the licensed work to be provided by Licensor:
100
-
101
- 1. To specify as the Change License the GPL Version 2.0 or any later version,
102
- or a license that is compatible with GPL Version 2.0 or a later version,
103
- where “compatible” means that software provided under the Change License can
104
- be included in a program with software provided under GPL Version 2.0 or a
105
- later version. Licensor may specify additional Change Licenses without
106
- limitation.
107
-
108
- 2. To either: (a) specify an additional grant of rights to use that does not
109
- impose any additional restriction on the right granted in this License, as
110
- the Additional Use Grant; or (b) insert the text “None”.
111
-
112
- 3. To specify a Change Date.
113
-
114
- 4. Not to modify this License in any other way.
package/README.md CHANGED
@@ -25,7 +25,7 @@ No need to add any subscription key or anything like that.
25
25
  ```tsx
26
26
  import React from "react";
27
27
  import { Rebase } from "@rebasepro/core";
28
- import "typeface-rubik";
28
+ import "@fontsource/rubik";
29
29
  import "@fontsource/jetbrains-mono";
30
30
 
31
31
  import { useDataEnhancementPlugin } from "@rebasepro/data_enhancement";
@@ -3,8 +3,8 @@ export declare function isReadOnly(property: Property): boolean;
3
3
  export declare function isHidden(property: Property): boolean;
4
4
  export declare function isPropertyBuilder(property?: Property): boolean;
5
5
  export declare function getDefaultValuesFor<M extends Record<string, unknown>>(properties: Properties): Partial<EntityValues<M>>;
6
- export declare function getDefaultValueFor(property?: Property): {} | null | undefined;
7
- export declare function getDefaultValueFortype(type: DataType): {} | null;
6
+ export declare function getDefaultValueFor(property?: Property): unknown;
7
+ export declare function getDefaultValueFortype(type: DataType): unknown;
8
8
  /**
9
9
  * Update the automatic values in an entity before save
10
10
  * @group Driver
@@ -1,5 +1,5 @@
1
1
  import { EntityCollection, Property, Relation } from "@rebasepro/types";
2
- export declare function sanitizeRelation(relation: Partial<Relation>, sourceCollection: EntityCollection): Relation;
2
+ export declare function sanitizeRelation(relation: Partial<Relation>, sourceCollection: EntityCollection, resolveCollection?: (slugOrTable: string) => EntityCollection | undefined): Relation;
3
3
  export declare function resolveCollectionRelations(collection: EntityCollection): Record<string, Relation>;
4
4
  export declare function resolvePropertyRelation({ propertyKey, property, sourceCollection }: {
5
5
  propertyKey: string;
@@ -61,11 +61,6 @@ export interface LoginViewProps {
61
61
  * Error message when user is not allowed access
62
62
  */
63
63
  notAllowedError?: string | Error;
64
- /**
65
- * Override: enable Google login button.
66
- * If not set, checks `authController.capabilities.googleLogin`.
67
- */
68
- googleEnabled?: boolean;
69
64
  /**
70
65
  * Google client ID for Google OAuth.
71
66
  * Required when Google login is enabled via ID token flow.
@@ -87,4 +82,4 @@ export interface LoginViewProps {
87
82
  * Feature-detects capabilities to show/hide login methods.
88
83
  * @group Core
89
84
  */
90
- export declare function LoginView({ logo, authController, noUserComponent, disableSignupScreen, disabled, notAllowedError, googleEnabled, googleClientId, needsSetup, registrationEnabled }: LoginViewProps): import("react/jsx-runtime").JSX.Element;
85
+ export declare function LoginView({ logo, authController, noUserComponent, disableSignupScreen, disabled, notAllowedError, googleClientId, needsSetup, registrationEnabled }: LoginViewProps): import("react/jsx-runtime").JSX.Element;
@@ -1,2 +1,2 @@
1
1
  import React, { PropsWithChildren } from "react";
2
- export declare const SnackbarProvider: React.FC<PropsWithChildren<{}>>;
2
+ export declare const SnackbarProvider: React.FC<PropsWithChildren>;
@@ -4,7 +4,7 @@ import { RebaseData } from "@rebasepro/types";
4
4
  /**
5
5
  * @group Hooks and utilities
6
6
  */
7
- export type SaveEntityWithCallbacksProps<M extends Record<string, any>> = SaveEntityProps<M> & {
7
+ export type SaveEntityWithCallbacksProps<M extends Record<string, unknown>> = SaveEntityProps<M> & {
8
8
  afterSave?: (updatedEntity: Entity<M>) => void;
9
9
  afterSaveError?: (e: Error) => void;
10
10
  };
@@ -27,7 +27,7 @@ export type SaveEntityWithCallbacksProps<M extends Record<string, any>> = SaveEn
27
27
  * @param afterSaveError
28
28
  * @group Hooks and utilities
29
29
  */
30
- export declare function saveEntityWithCallbacks<M extends Record<string, any>>({ collection, path, entityId, values, previousValues, status, data, context, afterSave, afterSaveError }: SaveEntityWithCallbacksProps<M> & {
30
+ export declare function saveEntityWithCallbacks<M extends Record<string, unknown>>({ collection, path, entityId, values, previousValues, status, data, context, afterSave, afterSaveError }: SaveEntityWithCallbacksProps<M> & {
31
31
  collection: EntityCollection;
32
32
  data: RebaseData;
33
33
  context: RebaseContext;
@@ -26,6 +26,11 @@ export interface EntityFetchResult<M extends Record<string, any>> {
26
26
  * @param entities - Array of entities to cache
27
27
  */
28
28
  export declare function populateEntityFetchCache<M extends Record<string, any>>(path: string, entities: Entity<M>[]): void;
29
+ /**
30
+ * Clear the entity fetch cache. Call this on auth state changes (e.g. logout)
31
+ * to prevent stale data from a previous session leaking into the next.
32
+ */
33
+ export declare function clearEntityFetchCache(): void;
29
34
  /**
30
35
  * This hook is used to fetch an entity.
31
36
  * It gives real time updates if the driver supports it.
@@ -35,7 +35,7 @@ import type { ComponentRef } from "@rebasepro/types";
35
35
  * </Suspense>
36
36
  * );
37
37
  * ```
38
- */
38
+ * */
39
39
  export declare function useResolvedComponent<P = unknown>(ref: ComponentRef<P> | undefined): React.ComponentType<P> | undefined;
40
40
  /**
41
41
  * Pure function version of the resolver, for use outside React components.
package/dist/index.es.js CHANGED
@@ -5,8 +5,7 @@ import { useAuthController, useSnackbarController, useLargeLayout, AIIcon } from
5
5
  import { getFieldId, useUrlController } from "@rebasepro/admin";
6
6
  import { isPropertyBuilder, stripCollectionPath } from "@rebasepro/common";
7
7
  import { getValueInPath } from "@rebasepro/utils";
8
- import { Menu, MenuItem, Separator, IconButton, iconSize, TextareaAutosize, cls, focusedDisabled, CircularProgress, Button } from "@rebasepro/ui";
9
- import { XIcon, SendIcon } from "lucide-react";
8
+ import { Menu, MenuItem, Separator, IconButton, XIcon, iconSize, TextareaAutosize, cls, focusedDisabled, CircularProgress, SendIcon, Button } from "@rebasepro/ui";
10
9
  function flatMapEntityValues(values, path = "") {
11
10
  if (!values) return {};
12
11
  return Object.entries(values).flatMap(([key, value]) => {
@@ -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, any>) => void;\n onUpdateDelta: (propertyKey: string, partialValue: any) => 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: any) {\n console.error(\"str\", str);\n console.error(\"Error parsing stream\", e);\n props.onError(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: any): 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?: any): 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?.[key];\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, any>, path = \"\"): Record<string, any> {\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<any>>) {\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: any) => {\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<any>): 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: any) {\n setLoadingSuggestions([]);\n if (e.code === \"payment-required\") {\n const projectId = e.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: any) {\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 { Button, CircularProgress, cls, focusedDisabled, IconButton, Menu, MenuItem, Separator, TextareaAutosize , iconSize } from \"@rebasepro/ui\";\nimport { XIcon, SendIcon } from \"lucide-react\";\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","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","String","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","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,OA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BtI,OAAKsI;AAsBCtI,SAAKc;AAAA,MAAAgP;AAAA,MAAAC;AAAA,MAAAH,EAAA,CAAA,MAAA1M,uBAAA8M,IAAA,2BAAA,GAAA;AAlBzBD,SAAA,CAAA;AAAA,MAAAE,MAEO;AAAA,MAAcC,WAAAxD;AAAAA,MAAAyD,OAAA;AAAA,IAAA,CAAA;AAI3BP,WAAAG;AAAAA,EAAA,OAAA;AAAAA,SAAAH,EAAA,CAAA;AAAA,EAAA;AAQiB,QAAAQ,KAAApQ,OAAKc;AAAM,MAAAuP;AAAA,MAAAT,EAAA,CAAA,MAAAzO,UAAAyO,SAAAtH,oBAAAsH,EAAA,CAAA,MAAAQ,IAAA;AAhBLC,SAAA;AAAA,MAAA7Q,KACnB;AAAA,MAAkB8Q,OAChBP;AAAAA,MAMNQ,WAAA,CAAA;AAAA,QAAAC,OAGc;AAAA,QAAeN,WAAA7H;AAAAA,QACkDrI,OAAA;AAAA,UAAAmB;AAAAA,UAAAmH;AAAAA,UAAAxH,MAI9DsP;AAAAA,QAAAA;AAAAA,MAAW,CAAA;AAAA,IAAA;AAIhCR,WAAAzO;AAAAyO,WAAAtH;AAAAsH,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, any>) => void;\n onUpdateDelta: (propertyKey: string, partialValue: any) => 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: any) {\n console.error(\"str\", str);\n console.error(\"Error parsing stream\", e);\n props.onError(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: any): 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?: any): 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?.[key];\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, any>, path = \"\"): Record<string, any> {\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<any>>) {\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: any) => {\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<any>): 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: any) {\n setLoadingSuggestions([]);\n if (e.code === \"payment-required\") {\n const projectId = e.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: any) {\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","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","String","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","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,MA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,OAGc;AAAA,QAAeN,WAAA7H;AAAAA,QACkDrI,OAAA;AAAA,UAAAmB;AAAAA,UAAAmH;AAAAA,UAAAxH,MAI9DsP;AAAAA,QAAAA;AAAAA,MAAW,CAAA;AAAA,IAAA;AAIhCR,WAAAzO;AAAAyO,WAAAtH;AAAAsH,WAAAQ;AAAAR,WAAAS;AAAAA,EAAA,OAAA;AAAAA,SAAAT,EAAA,CAAA;AAAA,EAAA;AAAAE,OApB2BO;AAoB3B,SApBMP;AAoBqC;"}
package/dist/index.umd.js CHANGED
@@ -1,6 +1,6 @@
1
1
  (function(global, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("react-compiler-runtime"), require("react/jsx-runtime"), require("react"), require("@rebasepro/core"), require("@rebasepro/admin"), require("@rebasepro/common"), require("@rebasepro/utils"), require("@rebasepro/ui"), require("lucide-react")) : typeof define === "function" && define.amd ? define(["exports", "react-compiler-runtime", "react/jsx-runtime", "react", "@rebasepro/core", "@rebasepro/admin", "@rebasepro/common", "@rebasepro/utils", "@rebasepro/ui", "lucide-react"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.Rebase = {}, global.reactCompilerRuntime, global.jsxRuntime, global.React, global.core, global.admin, global.common, global.utils, global.ui, global.lucideReact));
3
- })(this, (function(exports2, reactCompilerRuntime, jsxRuntime, React, core, admin, common, utils, ui, lucideReact) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("react-compiler-runtime"), require("react/jsx-runtime"), require("react"), require("@rebasepro/core"), require("@rebasepro/admin"), require("@rebasepro/common"), require("@rebasepro/utils"), require("@rebasepro/ui")) : typeof define === "function" && define.amd ? define(["exports", "react-compiler-runtime", "react/jsx-runtime", "react", "@rebasepro/core", "@rebasepro/admin", "@rebasepro/common", "@rebasepro/utils", "@rebasepro/ui"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.Rebase = {}, global.reactCompilerRuntime, global.jsxRuntime, global.React, global.core, global.admin, global.common, global.utils, global.ui));
3
+ })(this, (function(exports2, reactCompilerRuntime, jsxRuntime, React, core, admin, common, utils, ui) {
4
4
  "use strict";
5
5
  function flatMapEntityValues(values, path = "") {
6
6
  if (!values) return {};
@@ -632,7 +632,7 @@
632
632
  e.stopPropagation();
633
633
  removeRecentPrompt(storageKey, samplePrompt.prompt);
634
634
  setSamplePrompts((samplePrompts ?? []).filter((p_0) => p_0.prompt !== samplePrompt.prompt));
635
- }, size: "smallest", children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.XIcon, { size: ui.iconSize.smallest }) })
635
+ }, size: "smallest", children: /* @__PURE__ */ jsxRuntime.jsx(ui.XIcon, { size: ui.iconSize.smallest }) })
636
636
  ] }, index + "_" + samplePrompt.prompt);
637
637
  }),
638
638
  /* @__PURE__ */ jsxRuntime.jsx(ui.Separator, { orientation: "horizontal" }),
@@ -650,10 +650,10 @@
650
650
  } }),
651
651
  /* @__PURE__ */ jsxRuntime.jsx(ui.IconButton, { size: "small", onClick: () => {
652
652
  setInstructions("");
653
- }, color: !instructions ? "primary" : void 0, disabled: loading || !instructions, children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.XIcon, { size: ui.iconSize.small }) }),
653
+ }, color: !instructions ? "primary" : void 0, disabled: loading || !instructions, children: /* @__PURE__ */ jsxRuntime.jsx(ui.XIcon, { size: ui.iconSize.small }) }),
654
654
  /* @__PURE__ */ jsxRuntime.jsxs(ui.IconButton, { onClick: () => enhance(instructions), size: "small", color: !instructions ? "primary" : void 0, disabled: loading || !instructions, children: [
655
655
  loading && /* @__PURE__ */ jsxRuntime.jsx(ui.CircularProgress, { size: "smallest" }),
656
- !loading && /* @__PURE__ */ jsxRuntime.jsx(lucideReact.SendIcon, { color: "primary" })
656
+ !loading && /* @__PURE__ */ jsxRuntime.jsx(ui.SendIcon, { color: "primary" })
657
657
  ] })
658
658
  ] })
659
659
  ] });