@rebasepro/plugin-data-enhancement 0.0.1-canary.eae7889 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/src/components/BootstrapAdminBanner.d.ts +4 -0
- package/dist/core/src/components/LoginView/LoginView.d.ts +22 -0
- package/dist/core/src/components/common/useDataTableController.d.ts +3 -3
- package/dist/core/src/components/index.d.ts +1 -0
- package/dist/core/src/hooks/data/useRelationSelector.d.ts +2 -2
- package/dist/core/src/hooks/index.d.ts +1 -0
- package/dist/core/src/hooks/useCollapsedGroups.d.ts +16 -1
- package/dist/core/src/hooks/useResolvedComponent.d.ts +47 -0
- package/dist/index.es.js +14 -13
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +14 -13
- package/dist/index.umd.js.map +1 -1
- package/dist/types/src/controllers/auth.d.ts +8 -2
- package/dist/types/src/controllers/client.d.ts +13 -0
- package/dist/types/src/controllers/collection_registry.d.ts +2 -1
- package/dist/types/src/controllers/data_driver.d.ts +36 -1
- package/dist/types/src/controllers/navigation.d.ts +18 -6
- package/dist/types/src/controllers/registry.d.ts +9 -1
- package/dist/types/src/controllers/side_entity_controller.d.ts +7 -0
- package/dist/types/src/rebase_context.d.ts +17 -0
- package/dist/types/src/types/backend_hooks.d.ts +187 -0
- package/dist/types/src/types/collections.d.ts +31 -11
- package/dist/types/src/types/component_ref.d.ts +47 -0
- package/dist/types/src/types/cron.d.ts +1 -1
- package/dist/types/src/types/entity_views.d.ts +6 -7
- package/dist/types/src/types/formex.d.ts +40 -0
- package/dist/types/src/types/index.d.ts +3 -0
- package/dist/types/src/types/plugins.d.ts +6 -3
- package/dist/types/src/types/properties.d.ts +72 -88
- package/dist/types/src/types/slots.d.ts +20 -10
- package/dist/types/src/types/translations.d.ts +6 -0
- package/dist/ui/src/components/FileUpload.d.ts +1 -1
- package/dist/ui/src/components/SearchBar.d.ts +5 -1
- package/dist/ui/src/styles.d.ts +2 -2
- package/package.json +9 -9
- package/src/components/DataEnhancementControllerProvider.tsx +1 -1
- package/src/components/FormEnhanceAction.tsx +9 -8
- package/src/utils/properties.ts +4 -4
- package/src/utils/strings_counter.ts +1 -1
|
@@ -1,4 +1,26 @@
|
|
|
1
1
|
import { ReactNode } from "react";
|
|
2
|
+
/** Google Identity Services SDK — injected by the GIS <script> tag. */
|
|
3
|
+
declare global {
|
|
4
|
+
interface Window {
|
|
5
|
+
google?: {
|
|
6
|
+
accounts: {
|
|
7
|
+
oauth2: {
|
|
8
|
+
initCodeClient(config: {
|
|
9
|
+
client_id: string;
|
|
10
|
+
scope: string;
|
|
11
|
+
ux_mode: "popup" | "redirect";
|
|
12
|
+
callback: (response: {
|
|
13
|
+
code?: string;
|
|
14
|
+
error?: string;
|
|
15
|
+
}) => void;
|
|
16
|
+
}): {
|
|
17
|
+
requestCode(): void;
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
2
24
|
import { AuthControllerExtended } from "@rebasepro/types";
|
|
3
25
|
/**
|
|
4
26
|
* Props for the generic LoginView.
|
|
@@ -20,7 +20,7 @@ export type DataTableControllerProps<M extends Record<string, any> = any> = {
|
|
|
20
20
|
/**
|
|
21
21
|
* Force filter to be applied to the table.
|
|
22
22
|
*/
|
|
23
|
-
|
|
23
|
+
fixedFilter?: FilterValues<string>;
|
|
24
24
|
scrollRestoration?: ScrollRestorationController;
|
|
25
25
|
/**
|
|
26
26
|
* When set to true the filters and sort will be updated in the URL
|
|
@@ -39,7 +39,7 @@ export type DataTableControllerProps<M extends Record<string, any> = any> = {
|
|
|
39
39
|
* @param scrollRestoration
|
|
40
40
|
* @param entitiesDisplayedFirst
|
|
41
41
|
* @param lastDeleteTimestamp
|
|
42
|
-
* @param
|
|
42
|
+
* @param fixedFilterFromProps
|
|
43
43
|
* @param updateUrl
|
|
44
44
|
*/
|
|
45
|
-
export declare function useDataTableController<M extends Record<string, any> = any, USER extends User = User>({ path, collection, scrollRestoration, entitiesDisplayedFirst, lastDeleteTimestamp: _lastDeleteTimestamp,
|
|
45
|
+
export declare function useDataTableController<M extends Record<string, any> = any, USER extends User = User>({ path, collection, scrollRestoration, entitiesDisplayedFirst, lastDeleteTimestamp: _lastDeleteTimestamp, fixedFilter: fixedFilterFromProps, updateUrl }: DataTableControllerProps<M>): EntityTableController<M>;
|
|
@@ -19,7 +19,7 @@ export interface UseRelationSelectorProps<M extends Record<string, any> = any> {
|
|
|
19
19
|
/**
|
|
20
20
|
* Force filter to be applied to the relation search
|
|
21
21
|
*/
|
|
22
|
-
|
|
22
|
+
fixedFilter?: FilterValues<string>;
|
|
23
23
|
/**
|
|
24
24
|
* Page size for pagination
|
|
25
25
|
*/
|
|
@@ -49,4 +49,4 @@ export interface RelationSelectorController {
|
|
|
49
49
|
/**
|
|
50
50
|
* Hook to manage relation selection with data fetching from Rebase data source
|
|
51
51
|
*/
|
|
52
|
-
export declare function useRelationSelector<M extends Record<string, any> = any>({ path, collection,
|
|
52
|
+
export declare function useRelationSelector<M extends Record<string, any> = any>({ path, collection, fixedFilter, pageSize, getLabelFromEntity, getDescriptionFromEntity, descriptionProperty }: UseRelationSelectorProps<M>): RelationSelectorController;
|
|
@@ -3,10 +3,25 @@
|
|
|
3
3
|
* with localStorage persistence. Automatically cleans up stale group entries
|
|
4
4
|
* when groups are removed from the navigation.
|
|
5
5
|
*
|
|
6
|
+
* Groups that have never been toggled by the user fall back to
|
|
7
|
+
* `defaults[groupName]` (driven by `collapsedByDefault` in config).
|
|
8
|
+
*
|
|
6
9
|
* @param groupNames - Array of group names to track
|
|
7
10
|
* @param namespace - Namespace for localStorage key (e.g., "home", "drawer") to allow independent state
|
|
11
|
+
* @param defaults - Optional map of group name → collapsed boolean from config
|
|
8
12
|
*/
|
|
9
|
-
export declare function useCollapsedGroups(groupNames: string[], namespace?: string): {
|
|
13
|
+
export declare function useCollapsedGroups(groupNames: string[], namespace?: string, defaults?: Record<string, boolean>): {
|
|
10
14
|
isGroupCollapsed: (name: string) => boolean;
|
|
11
15
|
toggleGroupCollapsed: (name: string) => void;
|
|
12
16
|
};
|
|
17
|
+
/**
|
|
18
|
+
* Build a defaults map from navigationGroupMappings for a given namespace.
|
|
19
|
+
* Returns a Record<groupName, collapsed> that can be passed to useCollapsedGroups.
|
|
20
|
+
*/
|
|
21
|
+
export declare function buildCollapsedDefaults(mappings: Array<{
|
|
22
|
+
name: string;
|
|
23
|
+
collapsedByDefault?: boolean | {
|
|
24
|
+
drawer?: boolean;
|
|
25
|
+
home?: boolean;
|
|
26
|
+
};
|
|
27
|
+
}> | undefined, namespace: "drawer" | "home"): Record<string, boolean>;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import type { ComponentRef } from "@rebasepro/types";
|
|
3
|
+
/**
|
|
4
|
+
* Resolves a `ComponentRef` into a renderable `React.ComponentType`.
|
|
5
|
+
*
|
|
6
|
+
* This hook handles all three forms of `ComponentRef`:
|
|
7
|
+
*
|
|
8
|
+
* 1. **`LazyComponentRef`** (produced by the Vite plugin from string paths):
|
|
9
|
+
* Wraps the lazy loader with `React.lazy()` for automatic code-splitting.
|
|
10
|
+
*
|
|
11
|
+
* 2. **`() => Promise<{ default: ComponentType }>`** (manual lazy import):
|
|
12
|
+
* Also wraps with `React.lazy()`. Distinguished from regular components
|
|
13
|
+
* by checking that the function has no parameters and is not a known
|
|
14
|
+
* React internal (no `$$typeof`).
|
|
15
|
+
*
|
|
16
|
+
* 3. **Direct `React.ComponentType`**:
|
|
17
|
+
* Returned as-is.
|
|
18
|
+
*
|
|
19
|
+
* If the ref is `undefined` or a raw string (which should never happen at
|
|
20
|
+
* runtime in the browser since the Vite plugin transforms strings), returns `undefined`.
|
|
21
|
+
*
|
|
22
|
+
* The returned component is stable across re-renders as long as the `ref`
|
|
23
|
+
* is referentially stable.
|
|
24
|
+
*
|
|
25
|
+
* **Usage:** Wrap the rendered component in `<Suspense>` to handle the
|
|
26
|
+
* loading state of lazy components.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```tsx
|
|
30
|
+
* const ResolvedField = useResolvedComponent(property.ui?.Field);
|
|
31
|
+
* if (!ResolvedField) return null;
|
|
32
|
+
* return (
|
|
33
|
+
* <Suspense fallback={<CircularProgress />}>
|
|
34
|
+
* <ResolvedField {...fieldProps} />
|
|
35
|
+
* </Suspense>
|
|
36
|
+
* );
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
export declare function useResolvedComponent<P = unknown>(ref: ComponentRef<P> | undefined): React.ComponentType<P> | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Pure function version of the resolver, for use outside React components.
|
|
42
|
+
* Same resolution logic as `useResolvedComponent`.
|
|
43
|
+
*
|
|
44
|
+
* Results are cached per reference identity — calling this multiple times
|
|
45
|
+
* with the same `ref` object returns the same `React.ComponentType`.
|
|
46
|
+
*/
|
|
47
|
+
export declare function resolveComponentRef<P = unknown>(ref: ComponentRef<P> | undefined): React.ComponentType<P> | undefined;
|
package/dist/index.es.js
CHANGED
|
@@ -179,7 +179,7 @@ function getSimpleProperty(property) {
|
|
|
179
179
|
type: property.type,
|
|
180
180
|
fieldConfigId: fieldId,
|
|
181
181
|
enum: "enum" in property && property.enum ? getSimpleEnumValues(property.enum) : void 0,
|
|
182
|
-
disabled: Boolean(property.disabled || property.readOnly)
|
|
182
|
+
disabled: Boolean(property.ui?.disabled || property.ui?.readOnly)
|
|
183
183
|
};
|
|
184
184
|
}
|
|
185
185
|
function getSimplifiedProperty(property, path, value) {
|
|
@@ -191,7 +191,7 @@ function getSimplifiedProperty(property, path, value) {
|
|
|
191
191
|
description: property.description,
|
|
192
192
|
type: property.type,
|
|
193
193
|
fieldConfigId: "repeat",
|
|
194
|
-
disabled: Boolean(property.disabled || property.readOnly),
|
|
194
|
+
disabled: Boolean(property.ui?.disabled || property.ui?.readOnly),
|
|
195
195
|
of: getSimpleProperty(property.of)
|
|
196
196
|
};
|
|
197
197
|
const result = {
|
|
@@ -204,7 +204,7 @@ function getSimplifiedProperty(property, path, value) {
|
|
|
204
204
|
description: property.description,
|
|
205
205
|
type: property.type,
|
|
206
206
|
fieldConfigId: "block",
|
|
207
|
-
disabled: Boolean(property.disabled || property.readOnly),
|
|
207
|
+
disabled: Boolean(property.ui?.disabled || property.ui?.readOnly),
|
|
208
208
|
oneOf: {
|
|
209
209
|
typeField: property.oneOf.typeField,
|
|
210
210
|
valueField: property.oneOf.valueField,
|
|
@@ -259,7 +259,7 @@ function getSimplifiedProperty(property, path, value) {
|
|
|
259
259
|
description: property.description,
|
|
260
260
|
type: property.type,
|
|
261
261
|
fieldConfigId: "group",
|
|
262
|
-
disabled: Boolean(property.disabled || property.readOnly)
|
|
262
|
+
disabled: Boolean(property.ui?.disabled || property.ui?.readOnly)
|
|
263
263
|
};
|
|
264
264
|
return {
|
|
265
265
|
[path]: mapParentProperty,
|
|
@@ -402,7 +402,7 @@ function DataEnhancementControllerProvider({
|
|
|
402
402
|
Object.entries(updatedValues).forEach(([propertyKey_1, suggestion]) => {
|
|
403
403
|
const value_0 = getValueInPath(currentValues, propertyKey_1);
|
|
404
404
|
const property_0 = getPropertyFromKey(properties, propertyKey_1);
|
|
405
|
-
if (!property_0 || suggestion === null || property_0
|
|
405
|
+
if (!property_0 || suggestion === null || property_0?.disabled) {
|
|
406
406
|
return;
|
|
407
407
|
}
|
|
408
408
|
if (typeof suggestion === "number") {
|
|
@@ -564,12 +564,10 @@ function FormEnhanceAction({
|
|
|
564
564
|
const dataEnhancementController = useDataEnhancementController();
|
|
565
565
|
const [samplePrompts, setSamplePrompts] = React.useState(void 0);
|
|
566
566
|
const [instructions, setInstructions] = React.useState("");
|
|
567
|
-
const
|
|
568
|
-
suggestions,
|
|
569
|
-
getSamplePrompts
|
|
570
|
-
} = dataEnhancementController;
|
|
567
|
+
const getSamplePrompts = dataEnhancementController?.getSamplePrompts;
|
|
571
568
|
const loadingPrompts = useRef(false);
|
|
572
569
|
const updateSuggestedPrompts = useCallback(async function updateSuggestedPrompts2(instructions_0) {
|
|
570
|
+
if (!getSamplePrompts) return;
|
|
573
571
|
if (loadingPrompts.current) return;
|
|
574
572
|
loadingPrompts.current = true;
|
|
575
573
|
const prompts = status === "new" ? (await getSamplePrompts(collection.singularName ?? collection.name, instructions_0)).prompts : getPromptsForExistingEntities(collection.properties);
|
|
@@ -580,16 +578,18 @@ function FormEnhanceAction({
|
|
|
580
578
|
}, [collection.name, collection.singularName, getSamplePrompts, status]);
|
|
581
579
|
useDeferredValue(formContext?.values);
|
|
582
580
|
useEffect(() => {
|
|
581
|
+
if (!dataEnhancementController) return;
|
|
583
582
|
if (!samplePrompts) {
|
|
584
583
|
setSamplePrompts(getRecentPromptsFromStorage(storageKey));
|
|
585
584
|
updateSuggestedPrompts().then();
|
|
586
585
|
}
|
|
587
|
-
}, [samplePrompts, storageKey, updateSuggestedPrompts, instructions, status]);
|
|
586
|
+
}, [dataEnhancementController, samplePrompts, storageKey, updateSuggestedPrompts, instructions, status]);
|
|
588
587
|
useEffect(() => {
|
|
588
|
+
if (!dataEnhancementController) return;
|
|
589
589
|
updateSuggestedPrompts().then();
|
|
590
|
-
}, [status]);
|
|
590
|
+
}, [dataEnhancementController, status]);
|
|
591
591
|
const enhance = (prompt_0) => {
|
|
592
|
-
if (!formContext?.values) return;
|
|
592
|
+
if (!dataEnhancementController || !formContext?.values) return;
|
|
593
593
|
setLoading(true);
|
|
594
594
|
if (prompt_0) {
|
|
595
595
|
addRecentPrompt(storageKey, prompt_0);
|
|
@@ -608,6 +608,7 @@ function FormEnhanceAction({
|
|
|
608
608
|
});
|
|
609
609
|
};
|
|
610
610
|
if (!dataEnhancementController?.enabled) return null;
|
|
611
|
+
const suggestions = dataEnhancementController.suggestions;
|
|
611
612
|
Object.values(suggestions).filter(Boolean).length > 0;
|
|
612
613
|
(samplePrompts ?? []).length > 0 && instructions.length === 0;
|
|
613
614
|
function submit() {
|
|
@@ -667,7 +668,7 @@ function getPromptsForExistingEntities(properties) {
|
|
|
667
668
|
if (isPropertyBuilder(p)) {
|
|
668
669
|
return false;
|
|
669
670
|
}
|
|
670
|
-
return p.type === "string" && (p.markdown || p.multiline);
|
|
671
|
+
return p.type === "string" && (p.ui?.markdown || p.ui?.multiline);
|
|
671
672
|
});
|
|
672
673
|
const multilinePrompt = multilineProperties.length > 0 ? multilineProperties[Math.floor(Math.random() * multilineProperties.length)] : void 0;
|
|
673
674
|
const prompts = ["Fill the missing fields", "Translate the missing content"];
|
package/dist/index.es.js.map
CHANGED
|
@@ -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.disabled || property.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.disabled || property.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.disabled || property.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.disabled || property.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 {\n suggestions,\n getSamplePrompts\n } = dataEnhancementController;\n\n const loadingPrompts = useRef(false);\n const updateSuggestedPrompts = useCallback(async function updateSuggestedPrompts(instructions?: string) {\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 (!samplePrompts) {\n setSamplePrompts(getRecentPromptsFromStorage(storageKey));\n updateSuggestedPrompts().then();\n }\n }, [samplePrompts, storageKey, updateSuggestedPrompts, instructions, status]);\n\n useEffect(() => {\n updateSuggestedPrompts().then();\n }, [status]);\n\n const enhance = (prompt?: string) => {\n if (!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 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.markdown || p.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","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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AAAE,MAEO;AAAA,MAAcC,WAAAxD;AAAAA,MAAAyD,OAAA;AAAA,IAAA,CAAA;AAI3BP,WAAAG;AAAAA,EAAA,OAAA;AAAAA,SAAAH,EAAA,CAAA;AAAA,EAAA;AAQiB,QAAAQ,KAAAnQ,OAAKc;AAAM,MAAAsP;AAAA,MAAAT,EAAA,CAAA,MAAAxO,UAAAwO,SAAAtH,oBAAAsH,EAAA,CAAA,MAAAQ,IAAA;AAhBLC,SAAA;AAAA,MAAA5Q,KACnB;AAAA,MAAkB6Q,OAChBP;AAAAA,MAMNQ,WAAA,CAAA;AAAA,QAAAC,OAGc;AAAA,QAAeN,WAAA7H;AAAAA,QACkDpI,OAAA;AAAA,UAAAmB;AAAAA,UAAAkH;AAAAA,UAAAvH,MAI9DqP;AAAAA,QAAAA;AAAAA,MAAW,CAAA;AAAA,IAAA;AAIhCR,WAAAxO;AAAAwO,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 { 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,OAAQ,QAAO,CAAA;AACpB,SAAOE,OAAOC,QAAQH,MAAM,EAAEI,QAAQ,CAAC,CAACC,KAAKC,KAAK,MAAM;AACpD,UAAMC,cAAcN,OAAO,GAAGA,IAAI,IAAII,GAAG,KAAKA;AAC9C,QAAI,OAAOC,UAAU,UAAU;AAC3B,aAAOP,oBAAoBO,OAAOC,WAAW;AAAA,IACjD,OAAO;AACH,aAAO;AAAA,QAAE,CAACA,WAAW,GAAGD;AAAAA,MAAAA;AAAAA,IAC5B;AAAA,EACJ,CAAC,EAAEE,OAAO,CAACC,KAAKC,UAAU;AAAA,IAAE,GAAGD;AAAAA,IACnC,GAAGC;AAAAA,EAAAA,IAAS,CAAA,CAAE;AACd;ACCA,MAAMC,iBAAiB;AAEvB,eAAsBC,qBAAwDC,OAkB3E;AAEC,QAAMC,aAAaf,oBAAoBc,MAAMb,MAAM;AAEnD,QAAMe,aAAaF,MAAME;AAEzB,QAAMC,cAA2B;AAAA,IAC7BC,UAAUJ,MAAMI;AAAAA,IAChBjB,QAAQc;AAAAA,EAAAA;AAGZ,QAAMI,UAAkC;AAA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