@puckeditor/plugin-ai 0.9.0-canary.f8c1abd5 → 0.9.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/index.mjs CHANGED
@@ -36,37 +36,6 @@ var init_react_import = __esm({
36
36
  }
37
37
  });
38
38
 
39
- // ../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js
40
- var require_throttleit = __commonJS({
41
- "../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js"(exports, module) {
42
- "use strict";
43
- init_react_import();
44
- function throttle2(function_, wait) {
45
- if (typeof function_ !== "function") {
46
- throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof function_}\`.`);
47
- }
48
- let timeoutId;
49
- let lastCallTime = 0;
50
- return function throttled(...arguments_) {
51
- clearTimeout(timeoutId);
52
- const now = Date.now();
53
- const timeSinceLastCall = now - lastCallTime;
54
- const delayForNextCall = wait - timeSinceLastCall;
55
- if (delayForNextCall <= 0) {
56
- lastCallTime = now;
57
- function_.apply(this, arguments_);
58
- } else {
59
- timeoutId = setTimeout(() => {
60
- lastCallTime = Date.now();
61
- function_.apply(this, arguments_);
62
- }, delayForNextCall);
63
- }
64
- };
65
- }
66
- module.exports = throttle2;
67
- }
68
- });
69
-
70
39
  // ../../node_modules/.pnpm/classnames@2.5.1/node_modules/classnames/index.js
71
40
  var require_classnames = __commonJS({
72
41
  "../../node_modules/.pnpm/classnames@2.5.1/node_modules/classnames/index.js"(exports, module) {
@@ -129,6 +98,37 @@ var require_classnames = __commonJS({
129
98
  }
130
99
  });
131
100
 
101
+ // ../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js
102
+ var require_throttleit = __commonJS({
103
+ "../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js"(exports, module) {
104
+ "use strict";
105
+ init_react_import();
106
+ function throttle2(function_, wait) {
107
+ if (typeof function_ !== "function") {
108
+ throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof function_}\`.`);
109
+ }
110
+ let timeoutId;
111
+ let lastCallTime = 0;
112
+ return function throttled(...arguments_) {
113
+ clearTimeout(timeoutId);
114
+ const now = Date.now();
115
+ const timeSinceLastCall = now - lastCallTime;
116
+ const delayForNextCall = wait - timeSinceLastCall;
117
+ if (delayForNextCall <= 0) {
118
+ lastCallTime = now;
119
+ function_.apply(this, arguments_);
120
+ } else {
121
+ timeoutId = setTimeout(() => {
122
+ lastCallTime = Date.now();
123
+ function_.apply(this, arguments_);
124
+ }, delayForNextCall);
125
+ }
126
+ };
127
+ }
128
+ module.exports = throttle2;
129
+ }
130
+ });
131
+
132
132
  // ../reducer/dist/index.js
133
133
  var require_dist = __commonJS({
134
134
  "../reducer/dist/index.js"(exports, module) {
@@ -728,315 +728,46 @@ import { ulid as ulid2 } from "ulid";
728
728
 
729
729
  // src/components/Chat/index.tsx
730
730
  init_react_import();
731
+ import { createUsePuck as createUsePuck3, useGetPuck as useGetPuck5 } from "@puckeditor/core";
732
+ import {
733
+ useCallback as useCallback6,
734
+ useEffect as useEffect10,
735
+ useId as useId3,
736
+ useMemo as useMemo5,
737
+ useRef as useRef9,
738
+ useState as useState10
739
+ } from "react";
731
740
 
732
- // ../../node_modules/.pnpm/@ai-sdk+react@3.0.232_react@19.2.8_zod@3.25.76/node_modules/@ai-sdk/react/dist/index.mjs
741
+ // ../platform-client/lib/get-class-name-factory.ts
733
742
  init_react_import();
734
- var import_throttleit = __toESM(require_throttleit(), 1);
735
- import {
736
- DefaultChatTransport
737
- } from "ai";
738
- import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
739
- import {
740
- AbstractChat
741
- } from "ai";
742
- import {
743
- callCompletionApi
744
- } from "ai";
745
- import { useCallback as useCallback2, useEffect as useEffect2, useId, useRef as useRef2, useState } from "react";
746
- import {
747
- asSchema,
748
- isDeepEqualData,
749
- parsePartialJson
750
- } from "ai";
751
- import { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState2 } from "react";
752
- var __accessCheck = (obj, member, msg) => {
753
- if (!member.has(obj))
754
- throw TypeError("Cannot " + msg);
755
- };
756
- var __privateGet = (obj, member, getter) => {
757
- __accessCheck(obj, member, "read from private field");
758
- return getter ? getter.call(obj) : member.get(obj);
759
- };
760
- var __privateAdd = (obj, member, value) => {
761
- if (member.has(obj))
762
- throw TypeError("Cannot add the same private member more than once");
763
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
764
- };
765
- var __privateSet = (obj, member, value, setter) => {
766
- __accessCheck(obj, member, "write to private field");
767
- setter ? setter.call(obj, value) : member.set(obj, value);
768
- return value;
769
- };
770
- function throttle(fn, waitMs) {
771
- return waitMs != null ? (0, import_throttleit.default)(fn, waitMs) : fn;
772
- }
773
- var _messages;
774
- var _status;
775
- var _error;
776
- var _messagesCallbacks;
777
- var _statusCallbacks;
778
- var _errorCallbacks;
779
- var _callMessagesCallbacks;
780
- var _callStatusCallbacks;
781
- var _callErrorCallbacks;
782
- var ReactChatState = class {
783
- constructor(initialMessages = []) {
784
- __privateAdd(this, _messages, void 0);
785
- __privateAdd(this, _status, "ready");
786
- __privateAdd(this, _error, void 0);
787
- __privateAdd(this, _messagesCallbacks, /* @__PURE__ */ new Set());
788
- __privateAdd(this, _statusCallbacks, /* @__PURE__ */ new Set());
789
- __privateAdd(this, _errorCallbacks, /* @__PURE__ */ new Set());
790
- this.pushMessage = (message) => {
791
- __privateSet(this, _messages, __privateGet(this, _messages).concat(message));
792
- __privateGet(this, _callMessagesCallbacks).call(this);
793
- };
794
- this.popMessage = () => {
795
- __privateSet(this, _messages, __privateGet(this, _messages).slice(0, -1));
796
- __privateGet(this, _callMessagesCallbacks).call(this);
797
- };
798
- this.replaceMessage = (index, message) => {
799
- __privateSet(this, _messages, [
800
- ...__privateGet(this, _messages).slice(0, index),
801
- // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:
802
- this.snapshot(message),
803
- ...__privateGet(this, _messages).slice(index + 1)
804
- ]);
805
- __privateGet(this, _callMessagesCallbacks).call(this);
806
- };
807
- this.snapshot = (value) => structuredClone(value);
808
- this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => {
809
- const callback = throttleWaitMs ? throttle(onChange, throttleWaitMs) : onChange;
810
- __privateGet(this, _messagesCallbacks).add(callback);
811
- return () => {
812
- __privateGet(this, _messagesCallbacks).delete(callback);
813
- };
814
- };
815
- this["~registerStatusCallback"] = (onChange) => {
816
- __privateGet(this, _statusCallbacks).add(onChange);
817
- return () => {
818
- __privateGet(this, _statusCallbacks).delete(onChange);
819
- };
820
- };
821
- this["~registerErrorCallback"] = (onChange) => {
822
- __privateGet(this, _errorCallbacks).add(onChange);
823
- return () => {
824
- __privateGet(this, _errorCallbacks).delete(onChange);
825
- };
826
- };
827
- __privateAdd(this, _callMessagesCallbacks, () => {
828
- __privateGet(this, _messagesCallbacks).forEach((callback) => callback());
829
- });
830
- __privateAdd(this, _callStatusCallbacks, () => {
831
- __privateGet(this, _statusCallbacks).forEach((callback) => callback());
832
- });
833
- __privateAdd(this, _callErrorCallbacks, () => {
834
- __privateGet(this, _errorCallbacks).forEach((callback) => callback());
835
- });
836
- __privateSet(this, _messages, initialMessages);
837
- }
838
- get status() {
839
- return __privateGet(this, _status);
840
- }
841
- set status(newStatus) {
842
- __privateSet(this, _status, newStatus);
843
- __privateGet(this, _callStatusCallbacks).call(this);
844
- }
845
- get error() {
846
- return __privateGet(this, _error);
847
- }
848
- set error(newError) {
849
- __privateSet(this, _error, newError);
850
- __privateGet(this, _callErrorCallbacks).call(this);
851
- }
852
- get messages() {
853
- return __privateGet(this, _messages);
854
- }
855
- set messages(newMessages) {
856
- __privateSet(this, _messages, [...newMessages]);
857
- __privateGet(this, _callMessagesCallbacks).call(this);
743
+ var import_classnames = __toESM(require_classnames());
744
+ var getClassNameFactory = (rootClass, styles, { baseClass = "" } = {}) => (options = {}) => {
745
+ let descendant = false;
746
+ let modifiers = false;
747
+ if (typeof options === "string") {
748
+ descendant = options;
749
+ } else if (typeof options === "object") {
750
+ modifiers = options;
858
751
  }
859
- };
860
- _messages = /* @__PURE__ */ new WeakMap();
861
- _status = /* @__PURE__ */ new WeakMap();
862
- _error = /* @__PURE__ */ new WeakMap();
863
- _messagesCallbacks = /* @__PURE__ */ new WeakMap();
864
- _statusCallbacks = /* @__PURE__ */ new WeakMap();
865
- _errorCallbacks = /* @__PURE__ */ new WeakMap();
866
- _callMessagesCallbacks = /* @__PURE__ */ new WeakMap();
867
- _callStatusCallbacks = /* @__PURE__ */ new WeakMap();
868
- _callErrorCallbacks = /* @__PURE__ */ new WeakMap();
869
- var _state;
870
- var Chat = class extends AbstractChat {
871
- constructor({ messages, ...init }) {
872
- const state = new ReactChatState(messages);
873
- super({ ...init, state });
874
- __privateAdd(this, _state, void 0);
875
- this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => __privateGet(this, _state)["~registerMessagesCallback"](onChange, throttleWaitMs);
876
- this["~registerStatusCallback"] = (onChange) => __privateGet(this, _state)["~registerStatusCallback"](onChange);
877
- this["~registerErrorCallback"] = (onChange) => __privateGet(this, _state)["~registerErrorCallback"](onChange);
878
- __privateSet(this, _state, state);
879
- }
880
- };
881
- _state = /* @__PURE__ */ new WeakMap();
882
- function useChat({
883
- experimental_throttle: throttleWaitMs,
884
- resume = false,
885
- ...options
886
- } = {}) {
887
- const latestRef = useRef({});
888
- if (!("chat" in options)) {
889
- latestRef.current = {
890
- onToolCall: options.onToolCall,
891
- onData: options.onData,
892
- onFinish: options.onFinish,
893
- onError: options.onError,
894
- sendAutomaticallyWhen: options.sendAutomaticallyWhen,
895
- transport: options.transport
896
- };
897
- }
898
- let defaultTransport;
899
- const getTransport = () => {
900
- var _a;
901
- return (_a = latestRef.current.transport) != null ? _a : defaultTransport != null ? defaultTransport : defaultTransport = new DefaultChatTransport();
902
- };
903
- const chatOptions = {
904
- ...options,
905
- transport: {
906
- sendMessages: (sendOptions) => getTransport().sendMessages(sendOptions),
907
- reconnectToStream: (reconnectOptions) => getTransport().reconnectToStream(reconnectOptions)
908
- },
909
- onToolCall: (arg) => {
910
- var _a, _b;
911
- return (_b = (_a = latestRef.current).onToolCall) == null ? void 0 : _b.call(_a, arg);
912
- },
913
- onData: (arg) => {
914
- var _a, _b;
915
- return (_b = (_a = latestRef.current).onData) == null ? void 0 : _b.call(_a, arg);
916
- },
917
- onFinish: (arg) => {
918
- var _a, _b;
919
- return (_b = (_a = latestRef.current).onFinish) == null ? void 0 : _b.call(_a, arg);
920
- },
921
- onError: (arg) => {
922
- var _a, _b;
923
- return (_b = (_a = latestRef.current).onError) == null ? void 0 : _b.call(_a, arg);
924
- },
925
- sendAutomaticallyWhen: (arg) => {
926
- var _a, _b, _c;
927
- return (_c = (_b = (_a = latestRef.current).sendAutomaticallyWhen) == null ? void 0 : _b.call(_a, arg)) != null ? _c : false;
928
- }
929
- };
930
- const chatRef = useRef(
931
- "chat" in options ? options.chat : new Chat(chatOptions)
932
- );
933
- const shouldRecreateChat = "chat" in options && options.chat !== chatRef.current || "id" in options && options.id != null && chatRef.current.id !== options.id;
934
- if (shouldRecreateChat) {
935
- chatRef.current = "chat" in options ? options.chat : new Chat(chatOptions);
936
- }
937
- const subscribeToMessages = useCallback(
938
- (update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs),
939
- // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
940
- // eslint-disable-next-line react-hooks/exhaustive-deps
941
- [throttleWaitMs, chatRef.current.id]
942
- );
943
- const messages = useSyncExternalStore(
944
- subscribeToMessages,
945
- () => chatRef.current.messages,
946
- () => chatRef.current.messages
947
- );
948
- const status = useSyncExternalStore(
949
- chatRef.current["~registerStatusCallback"],
950
- () => chatRef.current.status,
951
- () => chatRef.current.status
952
- );
953
- const error = useSyncExternalStore(
954
- chatRef.current["~registerErrorCallback"],
955
- () => chatRef.current.error,
956
- () => chatRef.current.error
957
- );
958
- const setMessages = useCallback(
959
- (messagesParam) => {
960
- if (typeof messagesParam === "function") {
961
- messagesParam = messagesParam(chatRef.current.messages);
962
- }
963
- chatRef.current.messages = messagesParam;
964
- },
965
- [chatRef]
966
- );
967
- useEffect(() => {
968
- if (resume) {
969
- chatRef.current.resumeStream();
970
- }
971
- }, [resume, chatRef]);
972
- return {
973
- id: chatRef.current.id,
974
- messages,
975
- setMessages,
976
- sendMessage: chatRef.current.sendMessage,
977
- regenerate: chatRef.current.regenerate,
978
- clearError: chatRef.current.clearError,
979
- stop: chatRef.current.stop,
980
- error,
981
- resumeStream: chatRef.current.resumeStream,
982
- status,
983
- /**
984
- * @deprecated Use `addToolOutput` instead.
985
- */
986
- addToolResult: chatRef.current.addToolOutput,
987
- addToolOutput: chatRef.current.addToolOutput,
988
- addToolApprovalResponse: chatRef.current.addToolApprovalResponse
989
- };
990
- }
991
-
992
- // src/components/Chat/index.tsx
993
- import {
994
- createUsePuck as createUsePuck2,
995
- useGetPuck as useGetPuck4
996
- } from "@puckeditor/core";
997
- import {
998
- DefaultChatTransport as DefaultChatTransport2
999
- } from "ai";
1000
- import {
1001
- useCallback as useCallback6,
1002
- useEffect as useEffect9,
1003
- useId as useId3,
1004
- useMemo as useMemo4,
1005
- useRef as useRef9,
1006
- useState as useState9
1007
- } from "react";
1008
- import { ulid } from "ulid";
1009
-
1010
- // ../platform-client/lib/get-class-name-factory.ts
1011
- init_react_import();
1012
- var import_classnames = __toESM(require_classnames());
1013
- var getClassNameFactory = (rootClass, styles, { baseClass = "" } = {}) => (options = {}) => {
1014
- let descendant = false;
1015
- let modifiers = false;
1016
- if (typeof options === "string") {
1017
- descendant = options;
1018
- } else if (typeof options === "object") {
1019
- modifiers = options;
1020
- }
1021
- if (descendant) {
1022
- const style = styles[`${rootClass}-${descendant}`];
1023
- if (style) {
1024
- return baseClass + styles[`${rootClass}-${descendant}`] || "";
1025
- }
1026
- return "";
1027
- } else if (modifiers) {
1028
- const prefixedModifiers = {};
1029
- for (let modifier in modifiers) {
1030
- prefixedModifiers[styles[`${rootClass}--${modifier}`]] = modifiers[modifier];
1031
- }
1032
- const c = styles[rootClass];
1033
- return baseClass + (0, import_classnames.default)({
1034
- [c]: !!c,
1035
- // only apply the class if it exists
1036
- ...prefixedModifiers
1037
- });
1038
- } else {
1039
- return baseClass + styles[rootClass] || "";
752
+ if (descendant) {
753
+ const style = styles[`${rootClass}-${descendant}`];
754
+ if (style) {
755
+ return baseClass + styles[`${rootClass}-${descendant}`] || "";
756
+ }
757
+ return "";
758
+ } else if (modifiers) {
759
+ const prefixedModifiers = {};
760
+ for (let modifier in modifiers) {
761
+ prefixedModifiers[styles[`${rootClass}--${modifier}`]] = modifiers[modifier];
762
+ }
763
+ const c = styles[rootClass];
764
+ return baseClass + (0, import_classnames.default)({
765
+ [c]: !!c,
766
+ // only apply the class if it exists
767
+ ...prefixedModifiers
768
+ });
769
+ } else {
770
+ return baseClass + styles[rootClass] || "";
1040
771
  }
1041
772
  };
1042
773
  var get_class_name_factory_default = getClassNameFactory;
@@ -1049,10 +780,10 @@ var styles_module_default = { "Chat": "_Chat_gflib_1", "Chat-header": "_Chat-hea
1049
780
  init_react_import();
1050
781
  import {
1051
782
  useContext,
1052
- useEffect as useEffect5,
783
+ useEffect as useEffect3,
1053
784
  useMemo,
1054
- useRef as useRef5,
1055
- useState as useState6
785
+ useRef as useRef2,
786
+ useState as useState4
1056
787
  } from "react";
1057
788
  import { useStickToBottom } from "use-stick-to-bottom";
1058
789
  import Markdown from "react-markdown";
@@ -1062,7 +793,7 @@ init_react_import();
1062
793
 
1063
794
  // ../platform-client/components/IconButton/IconButton.tsx
1064
795
  init_react_import();
1065
- import { useState as useState3 } from "react";
796
+ import { useState } from "react";
1066
797
 
1067
798
  // css-module:/home/runner/work/platform/platform/packages/platform-client/components/IconButton/IconButton.module.css#css-module
1068
799
  init_react_import();
@@ -1118,7 +849,7 @@ var IconButton = ({
1118
849
  title,
1119
850
  dark
1120
851
  }) => {
1121
- const [loading, setLoading] = useState3(false);
852
+ const [loading, setLoading] = useState(false);
1122
853
  const ElementType = href ? "a" : onClick ? "button" : "div";
1123
854
  const el = /* @__PURE__ */ jsxs(
1124
855
  ElementType,
@@ -1164,10 +895,10 @@ var styles_module_default3 = { "Chat": "_Chat_epa47_1", "Chat--hasMessages": "_C
1164
895
  // src/components/PromptForm/index.tsx
1165
896
  init_react_import();
1166
897
  import {
1167
- useCallback as useCallback4,
1168
- useEffect as useEffect3,
1169
- useRef as useRef4,
1170
- useState as useState4
898
+ useCallback,
899
+ useEffect,
900
+ useRef,
901
+ useState as useState2
1171
902
  } from "react";
1172
903
 
1173
904
  // ../platform-client/components/Textarea/index.tsx
@@ -1360,13 +1091,13 @@ function PromptForm({
1360
1091
  "plugin-ai-prompt-attachment-item-remove"
1361
1092
  );
1362
1093
  const loadingLabel = useMessage("loader-loading");
1363
- const hasSetInitialPrompt = useRef4(false);
1364
- const [prompt, setPrompt] = useState4(value);
1365
- const internalRef = useRef4(null);
1366
- const [isDragOver, setIsDragOver] = useState4(false);
1367
- const dragCounterRef = useRef4(0);
1094
+ const hasSetInitialPrompt = useRef(false);
1095
+ const [prompt, setPrompt] = useState2(value);
1096
+ const internalRef = useRef(null);
1097
+ const [isDragOver, setIsDragOver] = useState2(false);
1098
+ const dragCounterRef = useRef(0);
1368
1099
  const canDrop = !!onFileDrop && !isDisabled && !isLoading;
1369
- const handleDragEnter = useCallback4(
1100
+ const handleDragEnter = useCallback(
1370
1101
  (e) => {
1371
1102
  e.preventDefault();
1372
1103
  dragCounterRef.current++;
@@ -1376,17 +1107,17 @@ function PromptForm({
1376
1107
  },
1377
1108
  [canDrop]
1378
1109
  );
1379
- const handleDragLeave = useCallback4((e) => {
1110
+ const handleDragLeave = useCallback((e) => {
1380
1111
  e.preventDefault();
1381
1112
  dragCounterRef.current--;
1382
1113
  if (dragCounterRef.current === 0) {
1383
1114
  setIsDragOver(false);
1384
1115
  }
1385
1116
  }, []);
1386
- const handleDragOver = useCallback4((e) => {
1117
+ const handleDragOver = useCallback((e) => {
1387
1118
  e.preventDefault();
1388
1119
  }, []);
1389
- const handleDrop = useCallback4(
1120
+ const handleDrop = useCallback(
1390
1121
  (e) => {
1391
1122
  e.preventDefault();
1392
1123
  dragCounterRef.current = 0;
@@ -1400,7 +1131,7 @@ function PromptForm({
1400
1131
  },
1401
1132
  [canDrop, onFileDrop]
1402
1133
  );
1403
- const handlePaste = useCallback4(
1134
+ const handlePaste = useCallback(
1404
1135
  (e) => {
1405
1136
  if (!canDrop) return;
1406
1137
  const files = getFilesFromClipboard(e.clipboardData);
@@ -1410,7 +1141,7 @@ function PromptForm({
1410
1141
  },
1411
1142
  [canDrop, onFileDrop]
1412
1143
  );
1413
- useEffect3(() => {
1144
+ useEffect(() => {
1414
1145
  setPrompt(value);
1415
1146
  }, [setPrompt, value]);
1416
1147
  const sendPrompt = async () => {
@@ -1425,7 +1156,7 @@ function PromptForm({
1425
1156
  setPrompt("");
1426
1157
  }
1427
1158
  };
1428
- useEffect3(() => {
1159
+ useEffect(() => {
1429
1160
  const currentUrl = new URL(location.href);
1430
1161
  const initialPrompt = currentUrl.searchParams.get("initialPrompt");
1431
1162
  if (!hasSetInitialPrompt.current && initialPrompt && prompt === "") {
@@ -1581,11 +1312,11 @@ var SubagentStateProvider = subagentStateContext.Provider;
1581
1312
 
1582
1313
  // src/lib/use-attachment-url.ts
1583
1314
  init_react_import();
1584
- import { useEffect as useEffect4, useState as useState5 } from "react";
1315
+ import { useEffect as useEffect2, useState as useState3 } from "react";
1585
1316
  function useAttachmentUrl(url, endpoint) {
1586
1317
  const isRef = getAttachmentIdFromRef(url) !== null;
1587
- const [fetched, setFetched] = useState5();
1588
- useEffect4(() => {
1318
+ const [fetched, setFetched] = useState3();
1319
+ useEffect2(() => {
1589
1320
  if (!isRef) return;
1590
1321
  const controller = new AbortController();
1591
1322
  const loadUrl = async () => {
@@ -1807,12 +1538,12 @@ function ChatMessageWrapper({
1807
1538
  return /* @__PURE__ */ jsx4("span", { children });
1808
1539
  }
1809
1540
  function ReasoningBlock({ part }) {
1810
- const startTimeRef = useRef5(null);
1811
- const [durationSecs, setDurationSecs] = useState6(null);
1541
+ const startTimeRef = useRef2(null);
1542
+ const [durationSecs, setDurationSecs] = useState4(null);
1812
1543
  if (part.state !== "done" && startTimeRef.current === null) {
1813
1544
  startTimeRef.current = Date.now();
1814
1545
  }
1815
- useEffect5(() => {
1546
+ useEffect3(() => {
1816
1547
  if (part.state === "done" && startTimeRef.current !== null) {
1817
1548
  setDurationSecs(Math.round((Date.now() - startTimeRef.current) / 1e3));
1818
1549
  }
@@ -1914,7 +1645,7 @@ function SubagentBlock({ toolCallId }) {
1914
1645
  const loading = state ? state.state !== "done" : toolStatus?.loading ?? true;
1915
1646
  const hasBody = !!state && state.parts.length > 0;
1916
1647
  const parts = state?.parts ?? [];
1917
- const [isOpen, setIsOpen] = useState6(false);
1648
+ const [isOpen, setIsOpen] = useState4(false);
1918
1649
  return /* @__PURE__ */ jsxs3(
1919
1650
  "details",
1920
1651
  {
@@ -1972,7 +1703,7 @@ function ChatEvent({
1972
1703
  status,
1973
1704
  icon = /* @__PURE__ */ jsx4(Check, { size: 18 })
1974
1705
  }) {
1975
- const [isOpen, setIsOpen] = useState6(false);
1706
+ const [isOpen, setIsOpen] = useState4(false);
1976
1707
  const loadingLabel = useMessage("loader-loading");
1977
1708
  return /* @__PURE__ */ jsxs3(
1978
1709
  "details",
@@ -2039,11 +1770,6 @@ function ExamplePrompt({
2039
1770
  );
2040
1771
  }
2041
1772
 
2042
- // src/components/Chat/index.tsx
2043
- var import_reducer = __toESM(require_dist());
2044
- import qler from "qler";
2045
- import { useDebouncedCallback } from "use-debounce";
2046
-
2047
1773
  // src/lib/scroll-tracking-events.ts
2048
1774
  init_react_import();
2049
1775
  var listeners = /* @__PURE__ */ new Set();
@@ -2093,197 +1819,496 @@ function DesignModeToggle({
2093
1819
  ) });
2094
1820
  }
2095
1821
 
2096
- // src/lib/design/runtime.tsx
1822
+ // src/components/PluginTheme/index.ts
2097
1823
  init_react_import();
2098
- import {
2099
- walkTree
2100
- } from "@puckeditor/core";
2101
1824
 
2102
- // src/lib/design/component.tsx
1825
+ // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/PluginTheme/styles.module.css#css-module
2103
1826
  init_react_import();
2104
- import {
2105
- useGetPuck as useGetPuck2
2106
- } from "@puckeditor/core";
2107
- import {
2108
- useCallback as useCallback5,
2109
- useEffect as useEffect7,
2110
- useLayoutEffect,
2111
- useMemo as useMemo3,
2112
- useRef as useRef7,
2113
- useState as useState8,
2114
- useSyncExternalStore as useSyncExternalStore2
2115
- } from "react";
1827
+ var styles_module_default6 = { "PluginTheme": "_PluginTheme_u3emj_8" };
2116
1828
 
2117
- // src/lib/morph-html.ts
2118
- init_react_import();
1829
+ // src/components/PluginTheme/index.ts
1830
+ var cx4 = getClassNameFactory("PluginTheme", styles_module_default6);
1831
+ var pluginThemeClassName = cx4();
2119
1832
 
2120
- // src/lib/design/annotations.ts
1833
+ // src/lib/use-puck-ai.ts
2121
1834
  init_react_import();
2122
1835
 
2123
- // src/lib/html-annotations.ts
1836
+ // ../../node_modules/.pnpm/@ai-sdk+react@3.0.232_react@19.2.8_zod@3.25.76/node_modules/@ai-sdk/react/dist/index.mjs
2124
1837
  init_react_import();
2125
- import { parseDocument } from "htmlparser2";
2126
- import { appendChild, getInnerHTML, getOuterHTML, textContent } from "domutils";
2127
- import { Text } from "domhandler";
2128
- var FIELD_ATTR_PREFIX = "data-puck-field-";
2129
- var OPTIONS_ATTR_PREFIX = "data-puck-options-";
2130
- var BIND_ATTR_PREFIX = "data-puck-bind-";
2131
- var BIND_INPUT_ATTR_PREFIX = "data-puck-bind-input-";
2132
- var TYPE_ATTR_PREFIX = "data-puck-type-";
2133
- var MIN_ATTR_PREFIX = "data-puck-min-";
2134
- var MAX_ATTR_PREFIX = "data-puck-max-";
2135
- var STEP_ATTR_PREFIX = "data-puck-step-";
2136
- var SLOT_ATTR = "data-puck-slot";
2137
- var ARRAY_ATTR = "data-puck-array";
2138
- var RECOGNIZED_FIELD_TYPES = /* @__PURE__ */ new Set([
2139
- "text",
2140
- "textarea",
2141
- "number",
2142
- "richtext",
2143
- "radio",
2144
- "select",
2145
- "slot"
2146
- ]);
2147
- var tryParseFieldShape = (value) => {
2148
- const trimmed = value.trimStart();
2149
- if (!trimmed.startsWith("{")) return null;
2150
- try {
2151
- const parsed = JSON.parse(trimmed);
2152
- if (isRecord(parsed) && typeof parsed.type === "string" && RECOGNIZED_FIELD_TYPES.has(parsed.type)) {
2153
- return parsed;
2154
- }
2155
- } catch {
2156
- }
2157
- return null;
2158
- };
2159
- var collapseWhitespace = (value) => value.replace(/\s+/g, " ").trim();
2160
- var sanitizeStringArray = (value) => {
2161
- if (!Array.isArray(value)) return void 0;
2162
- const items = value.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);
2163
- return items.length > 0 ? items : void 0;
1838
+ var import_throttleit = __toESM(require_throttleit(), 1);
1839
+ import {
1840
+ DefaultChatTransport
1841
+ } from "ai";
1842
+ import { useCallback as useCallback2, useEffect as useEffect4, useRef as useRef3, useSyncExternalStore } from "react";
1843
+ import {
1844
+ AbstractChat
1845
+ } from "ai";
1846
+ import {
1847
+ callCompletionApi
1848
+ } from "ai";
1849
+ import { useCallback as useCallback22, useEffect as useEffect22, useId, useRef as useRef22, useState as useState5 } from "react";
1850
+ import {
1851
+ asSchema,
1852
+ isDeepEqualData,
1853
+ parsePartialJson
1854
+ } from "ai";
1855
+ import { useCallback as useCallback3, useId as useId2, useRef as useRef32, useState as useState22 } from "react";
1856
+ var __accessCheck = (obj, member, msg) => {
1857
+ if (!member.has(obj))
1858
+ throw TypeError("Cannot " + msg);
2164
1859
  };
2165
- var isElement = (node) => node.type === "tag";
2166
- var textContentWithBreaks = (node) => {
2167
- if (isElement(node) && node.name === "br") return " ";
2168
- if ("children" in node) {
2169
- return node.children.map(textContentWithBreaks).join("");
2170
- }
2171
- return textContent(node);
1860
+ var __privateGet = (obj, member, getter) => {
1861
+ __accessCheck(obj, member, "read from private field");
1862
+ return getter ? getter.call(obj) : member.get(obj);
2172
1863
  };
2173
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2174
- var FIELD_NAME_RE = /^[A-Za-z0-9_]+(?:[-.][A-Za-z0-9_]+)*$/;
2175
- var isValidFieldName = (name) => FIELD_NAME_RE.test(name);
2176
- var isFieldNameClaimed = (name, claimed, includeExact = true) => {
2177
- for (const entry of claimed) {
2178
- if (includeExact && entry === name || entry.startsWith(`${name}.`) || name.startsWith(`${entry}.`)) {
2179
- return true;
2180
- }
2181
- }
2182
- return false;
1864
+ var __privateAdd = (obj, member, value) => {
1865
+ if (member.has(obj))
1866
+ throw TypeError("Cannot add the same private member more than once");
1867
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2183
1868
  };
2184
- var attrBoundFieldNames = (attribs) => new Set(
2185
- Object.entries(attribs).filter(
2186
- ([name, value]) => name.startsWith(FIELD_ATTR_PREFIX) && name !== `${FIELD_ATTR_PREFIX}name` && !name.startsWith(`${FIELD_ATTR_PREFIX}value-`) && !tryParseFieldShape(value)
2187
- ).map(([, value]) => value.trim()).filter(isValidFieldName)
2188
- );
2189
- var getDeepValue = (source, path) => {
2190
- if (!path.includes(".")) return source[path];
2191
- let current = source;
2192
- for (const segment of path.split(".")) {
2193
- if (!isRecord(current)) return void 0;
2194
- current = current[segment];
2195
- }
2196
- return current;
1869
+ var __privateSet = (obj, member, value, setter) => {
1870
+ __accessCheck(obj, member, "write to private field");
1871
+ setter ? setter.call(obj, value) : member.set(obj, value);
1872
+ return value;
2197
1873
  };
2198
- var setExtractedValue = (target, path, value) => {
2199
- const segments = path.split(".");
2200
- let current = target;
2201
- for (let i = 0; i < segments.length - 1; i++) {
2202
- const existing = current[segments[i]];
2203
- if (existing === void 0) {
2204
- const next = {};
2205
- current[segments[i]] = next;
2206
- current = next;
2207
- } else if (isRecord(existing)) {
2208
- current = existing;
2209
- } else {
2210
- return;
2211
- }
1874
+ function throttle(fn, waitMs) {
1875
+ return waitMs != null ? (0, import_throttleit.default)(fn, waitMs) : fn;
1876
+ }
1877
+ var _messages;
1878
+ var _status;
1879
+ var _error;
1880
+ var _messagesCallbacks;
1881
+ var _statusCallbacks;
1882
+ var _errorCallbacks;
1883
+ var _callMessagesCallbacks;
1884
+ var _callStatusCallbacks;
1885
+ var _callErrorCallbacks;
1886
+ var ReactChatState = class {
1887
+ constructor(initialMessages = []) {
1888
+ __privateAdd(this, _messages, void 0);
1889
+ __privateAdd(this, _status, "ready");
1890
+ __privateAdd(this, _error, void 0);
1891
+ __privateAdd(this, _messagesCallbacks, /* @__PURE__ */ new Set());
1892
+ __privateAdd(this, _statusCallbacks, /* @__PURE__ */ new Set());
1893
+ __privateAdd(this, _errorCallbacks, /* @__PURE__ */ new Set());
1894
+ this.pushMessage = (message) => {
1895
+ __privateSet(this, _messages, __privateGet(this, _messages).concat(message));
1896
+ __privateGet(this, _callMessagesCallbacks).call(this);
1897
+ };
1898
+ this.popMessage = () => {
1899
+ __privateSet(this, _messages, __privateGet(this, _messages).slice(0, -1));
1900
+ __privateGet(this, _callMessagesCallbacks).call(this);
1901
+ };
1902
+ this.replaceMessage = (index, message) => {
1903
+ __privateSet(this, _messages, [
1904
+ ...__privateGet(this, _messages).slice(0, index),
1905
+ // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:
1906
+ this.snapshot(message),
1907
+ ...__privateGet(this, _messages).slice(index + 1)
1908
+ ]);
1909
+ __privateGet(this, _callMessagesCallbacks).call(this);
1910
+ };
1911
+ this.snapshot = (value) => structuredClone(value);
1912
+ this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => {
1913
+ const callback = throttleWaitMs ? throttle(onChange, throttleWaitMs) : onChange;
1914
+ __privateGet(this, _messagesCallbacks).add(callback);
1915
+ return () => {
1916
+ __privateGet(this, _messagesCallbacks).delete(callback);
1917
+ };
1918
+ };
1919
+ this["~registerStatusCallback"] = (onChange) => {
1920
+ __privateGet(this, _statusCallbacks).add(onChange);
1921
+ return () => {
1922
+ __privateGet(this, _statusCallbacks).delete(onChange);
1923
+ };
1924
+ };
1925
+ this["~registerErrorCallback"] = (onChange) => {
1926
+ __privateGet(this, _errorCallbacks).add(onChange);
1927
+ return () => {
1928
+ __privateGet(this, _errorCallbacks).delete(onChange);
1929
+ };
1930
+ };
1931
+ __privateAdd(this, _callMessagesCallbacks, () => {
1932
+ __privateGet(this, _messagesCallbacks).forEach((callback) => callback());
1933
+ });
1934
+ __privateAdd(this, _callStatusCallbacks, () => {
1935
+ __privateGet(this, _statusCallbacks).forEach((callback) => callback());
1936
+ });
1937
+ __privateAdd(this, _callErrorCallbacks, () => {
1938
+ __privateGet(this, _errorCallbacks).forEach((callback) => callback());
1939
+ });
1940
+ __privateSet(this, _messages, initialMessages);
2212
1941
  }
2213
- const leaf = segments[segments.length - 1];
2214
- if (current[leaf] === void 0) {
2215
- current[leaf] = value;
1942
+ get status() {
1943
+ return __privateGet(this, _status);
2216
1944
  }
2217
- };
2218
- var valuesEqual = (a, b) => {
2219
- if (a === b) return true;
2220
- if (typeof a !== "object" || typeof b !== "object" || a === null || b === null || Array.isArray(a) !== Array.isArray(b)) {
2221
- return false;
1945
+ set status(newStatus) {
1946
+ __privateSet(this, _status, newStatus);
1947
+ __privateGet(this, _callStatusCallbacks).call(this);
1948
+ }
1949
+ get error() {
1950
+ return __privateGet(this, _error);
1951
+ }
1952
+ set error(newError) {
1953
+ __privateSet(this, _error, newError);
1954
+ __privateGet(this, _callErrorCallbacks).call(this);
1955
+ }
1956
+ get messages() {
1957
+ return __privateGet(this, _messages);
1958
+ }
1959
+ set messages(newMessages) {
1960
+ __privateSet(this, _messages, [...newMessages]);
1961
+ __privateGet(this, _callMessagesCallbacks).call(this);
2222
1962
  }
2223
- const aKeys = Object.keys(a);
2224
- const bKeys = Object.keys(b);
2225
- if (aKeys.length !== bKeys.length) return false;
2226
- return aKeys.every(
2227
- (key) => valuesEqual(
2228
- a[key],
2229
- b[key]
2230
- )
2231
- );
2232
- };
2233
- var parseNumber = (raw) => {
2234
- if (raw === void 0) return void 0;
2235
- const value = parseFloat(raw);
2236
- return Number.isFinite(value) ? value : void 0;
2237
- };
2238
- var getTypeModifier = (attribs, name) => {
2239
- const raw = attribs[TYPE_ATTR_PREFIX + name.toLowerCase()];
2240
- return raw === "textarea" || raw === "number" || raw === "richtext" ? raw : void 0;
2241
1963
  };
2242
- var getNumberConstraints = (attribs, name) => {
2243
- const lower = name.toLowerCase();
2244
- const constraints = {};
2245
- const min = parseNumber(attribs[MIN_ATTR_PREFIX + lower]);
2246
- const max = parseNumber(attribs[MAX_ATTR_PREFIX + lower]);
2247
- const step = parseNumber(attribs[STEP_ATTR_PREFIX + lower]);
2248
- if (min !== void 0) constraints.min = min;
2249
- if (max !== void 0) constraints.max = max;
2250
- if (step !== void 0) constraints.step = step;
2251
- return constraints;
1964
+ _messages = /* @__PURE__ */ new WeakMap();
1965
+ _status = /* @__PURE__ */ new WeakMap();
1966
+ _error = /* @__PURE__ */ new WeakMap();
1967
+ _messagesCallbacks = /* @__PURE__ */ new WeakMap();
1968
+ _statusCallbacks = /* @__PURE__ */ new WeakMap();
1969
+ _errorCallbacks = /* @__PURE__ */ new WeakMap();
1970
+ _callMessagesCallbacks = /* @__PURE__ */ new WeakMap();
1971
+ _callStatusCallbacks = /* @__PURE__ */ new WeakMap();
1972
+ _callErrorCallbacks = /* @__PURE__ */ new WeakMap();
1973
+ var _state;
1974
+ var Chat = class extends AbstractChat {
1975
+ constructor({ messages, ...init }) {
1976
+ const state = new ReactChatState(messages);
1977
+ super({ ...init, state });
1978
+ __privateAdd(this, _state, void 0);
1979
+ this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => __privateGet(this, _state)["~registerMessagesCallback"](onChange, throttleWaitMs);
1980
+ this["~registerStatusCallback"] = (onChange) => __privateGet(this, _state)["~registerStatusCallback"](onChange);
1981
+ this["~registerErrorCallback"] = (onChange) => __privateGet(this, _state)["~registerErrorCallback"](onChange);
1982
+ __privateSet(this, _state, state);
1983
+ }
2252
1984
  };
2253
- var createAccumulator = () => ({
2254
- fields: [],
2255
- values: {},
2256
- seenFields: /* @__PURE__ */ new Set(),
2257
- optionsByField: {},
2258
- bindByField: {},
2259
- bindInputsByField: {}
2260
- });
2261
- var collectElementFields = (element, acc) => {
2262
- const attribs = element.attribs ?? {};
2263
- const arrayName = attribs[ARRAY_ATTR]?.trim();
2264
- if (arrayName) {
2265
- if (isValidFieldName(arrayName) && !acc.seenFields.has(arrayName)) {
2266
- acc.seenFields.add(arrayName);
2267
- const itemElements = element.children.filter(isElement);
2268
- const template = itemElements[0];
2269
- const templateAcc = createAccumulator();
2270
- if (template) {
2271
- collectFields([template], templateAcc);
2272
- }
2273
- acc.fields.push({
2274
- name: arrayName,
2275
- binding: "array",
2276
- itemFields: attachOptions(templateAcc),
2277
- ...Object.keys(templateAcc.bindByField).length > 0 ? { itemBinds: templateAcc.bindByField } : {}
2278
- });
2279
- const items = itemElements.map((item) => {
2280
- const itemAcc = createAccumulator();
2281
- collectFields([item], itemAcc);
2282
- return itemAcc.values;
2283
- });
2284
- setExtractedValue(acc.values, arrayName, items);
1985
+ _state = /* @__PURE__ */ new WeakMap();
1986
+ function useChat({
1987
+ experimental_throttle: throttleWaitMs,
1988
+ resume = false,
1989
+ ...options
1990
+ } = {}) {
1991
+ const latestRef = useRef3({});
1992
+ if (!("chat" in options)) {
1993
+ latestRef.current = {
1994
+ onToolCall: options.onToolCall,
1995
+ onData: options.onData,
1996
+ onFinish: options.onFinish,
1997
+ onError: options.onError,
1998
+ sendAutomaticallyWhen: options.sendAutomaticallyWhen,
1999
+ transport: options.transport
2000
+ };
2001
+ }
2002
+ let defaultTransport;
2003
+ const getTransport = () => {
2004
+ var _a;
2005
+ return (_a = latestRef.current.transport) != null ? _a : defaultTransport != null ? defaultTransport : defaultTransport = new DefaultChatTransport();
2006
+ };
2007
+ const chatOptions = {
2008
+ ...options,
2009
+ transport: {
2010
+ sendMessages: (sendOptions) => getTransport().sendMessages(sendOptions),
2011
+ reconnectToStream: (reconnectOptions) => getTransport().reconnectToStream(reconnectOptions)
2012
+ },
2013
+ onToolCall: (arg) => {
2014
+ var _a, _b;
2015
+ return (_b = (_a = latestRef.current).onToolCall) == null ? void 0 : _b.call(_a, arg);
2016
+ },
2017
+ onData: (arg) => {
2018
+ var _a, _b;
2019
+ return (_b = (_a = latestRef.current).onData) == null ? void 0 : _b.call(_a, arg);
2020
+ },
2021
+ onFinish: (arg) => {
2022
+ var _a, _b;
2023
+ return (_b = (_a = latestRef.current).onFinish) == null ? void 0 : _b.call(_a, arg);
2024
+ },
2025
+ onError: (arg) => {
2026
+ var _a, _b;
2027
+ return (_b = (_a = latestRef.current).onError) == null ? void 0 : _b.call(_a, arg);
2028
+ },
2029
+ sendAutomaticallyWhen: (arg) => {
2030
+ var _a, _b, _c;
2031
+ return (_c = (_b = (_a = latestRef.current).sendAutomaticallyWhen) == null ? void 0 : _b.call(_a, arg)) != null ? _c : false;
2285
2032
  }
2286
- return true;
2033
+ };
2034
+ const chatRef = useRef3(
2035
+ "chat" in options ? options.chat : new Chat(chatOptions)
2036
+ );
2037
+ const shouldRecreateChat = "chat" in options && options.chat !== chatRef.current || "id" in options && options.id != null && chatRef.current.id !== options.id;
2038
+ if (shouldRecreateChat) {
2039
+ chatRef.current = "chat" in options ? options.chat : new Chat(chatOptions);
2040
+ }
2041
+ const subscribeToMessages = useCallback2(
2042
+ (update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs),
2043
+ // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
2044
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2045
+ [throttleWaitMs, chatRef.current.id]
2046
+ );
2047
+ const messages = useSyncExternalStore(
2048
+ subscribeToMessages,
2049
+ () => chatRef.current.messages,
2050
+ () => chatRef.current.messages
2051
+ );
2052
+ const status = useSyncExternalStore(
2053
+ chatRef.current["~registerStatusCallback"],
2054
+ () => chatRef.current.status,
2055
+ () => chatRef.current.status
2056
+ );
2057
+ const error = useSyncExternalStore(
2058
+ chatRef.current["~registerErrorCallback"],
2059
+ () => chatRef.current.error,
2060
+ () => chatRef.current.error
2061
+ );
2062
+ const setMessages = useCallback2(
2063
+ (messagesParam) => {
2064
+ if (typeof messagesParam === "function") {
2065
+ messagesParam = messagesParam(chatRef.current.messages);
2066
+ }
2067
+ chatRef.current.messages = messagesParam;
2068
+ },
2069
+ [chatRef]
2070
+ );
2071
+ useEffect4(() => {
2072
+ if (resume) {
2073
+ chatRef.current.resumeStream();
2074
+ }
2075
+ }, [resume, chatRef]);
2076
+ return {
2077
+ id: chatRef.current.id,
2078
+ messages,
2079
+ setMessages,
2080
+ sendMessage: chatRef.current.sendMessage,
2081
+ regenerate: chatRef.current.regenerate,
2082
+ clearError: chatRef.current.clearError,
2083
+ stop: chatRef.current.stop,
2084
+ error,
2085
+ resumeStream: chatRef.current.resumeStream,
2086
+ status,
2087
+ /**
2088
+ * @deprecated Use `addToolOutput` instead.
2089
+ */
2090
+ addToolResult: chatRef.current.addToolOutput,
2091
+ addToolOutput: chatRef.current.addToolOutput,
2092
+ addToolApprovalResponse: chatRef.current.addToolApprovalResponse
2093
+ };
2094
+ }
2095
+
2096
+ // src/lib/use-puck-ai.ts
2097
+ var import_reducer = __toESM(require_dist());
2098
+ import {
2099
+ createUsePuck as createUsePuck2,
2100
+ useGetPuck as useGetPuck4
2101
+ } from "@puckeditor/core";
2102
+ import {
2103
+ DefaultChatTransport as DefaultChatTransport2
2104
+ } from "ai";
2105
+ import { useCallback as useCallback5, useEffect as useEffect9, useMemo as useMemo4, useRef as useRef8, useState as useState9 } from "react";
2106
+ import { ulid } from "ulid";
2107
+ import qler from "qler";
2108
+ import { useDebouncedCallback } from "use-debounce";
2109
+
2110
+ // src/lib/design/runtime.tsx
2111
+ init_react_import();
2112
+ import {
2113
+ walkTree
2114
+ } from "@puckeditor/core";
2115
+
2116
+ // src/lib/design/component.tsx
2117
+ init_react_import();
2118
+ import {
2119
+ useGetPuck as useGetPuck2
2120
+ } from "@puckeditor/core";
2121
+ import {
2122
+ isValidElement,
2123
+ useCallback as useCallback4,
2124
+ useEffect as useEffect7,
2125
+ useLayoutEffect,
2126
+ useMemo as useMemo3,
2127
+ useRef as useRef6,
2128
+ useState as useState8,
2129
+ useSyncExternalStore as useSyncExternalStore2
2130
+ } from "react";
2131
+
2132
+ // src/lib/morph-html.ts
2133
+ init_react_import();
2134
+
2135
+ // src/lib/design/annotations.ts
2136
+ init_react_import();
2137
+
2138
+ // src/lib/html-annotations.ts
2139
+ init_react_import();
2140
+ import { parseDocument } from "htmlparser2";
2141
+ import { appendChild, getInnerHTML, getOuterHTML, textContent } from "domutils";
2142
+ import { Text } from "domhandler";
2143
+ var FIELD_ATTR_PREFIX = "data-puck-field-";
2144
+ var OPTIONS_ATTR_PREFIX = "data-puck-options-";
2145
+ var BIND_ATTR_PREFIX = "data-puck-bind-";
2146
+ var BIND_INPUT_ATTR_PREFIX = "data-puck-bind-input-";
2147
+ var TYPE_ATTR_PREFIX = "data-puck-type-";
2148
+ var MIN_ATTR_PREFIX = "data-puck-min-";
2149
+ var MAX_ATTR_PREFIX = "data-puck-max-";
2150
+ var STEP_ATTR_PREFIX = "data-puck-step-";
2151
+ var SLOT_ATTR = "data-puck-slot";
2152
+ var ARRAY_ATTR = "data-puck-array";
2153
+ var BUILT_IN_FIELD_TYPES = /* @__PURE__ */ new Set([
2154
+ "text",
2155
+ "textarea",
2156
+ "number",
2157
+ "richtext",
2158
+ "radio",
2159
+ "select",
2160
+ "checkbox",
2161
+ "slot",
2162
+ "array",
2163
+ "object",
2164
+ "external",
2165
+ "custom"
2166
+ ]);
2167
+ var isBuiltInFieldType = (type) => BUILT_IN_FIELD_TYPES.has(type);
2168
+ var tryParseFieldShape = (value) => {
2169
+ const trimmed = value.trimStart();
2170
+ if (!trimmed.startsWith("{")) return null;
2171
+ try {
2172
+ const parsed = JSON.parse(trimmed);
2173
+ if (isRecord(parsed) && typeof parsed.type === "string" && parsed.type) {
2174
+ return parsed;
2175
+ }
2176
+ } catch {
2177
+ }
2178
+ return null;
2179
+ };
2180
+ var collapseWhitespace = (value) => value.replace(/\s+/g, " ").trim();
2181
+ var sanitizeStringArray = (value) => {
2182
+ if (!Array.isArray(value)) return void 0;
2183
+ const items = value.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);
2184
+ return items.length > 0 ? items : void 0;
2185
+ };
2186
+ var isElement = (node) => node.type === "tag";
2187
+ var textContentWithBreaks = (node) => {
2188
+ if (isElement(node) && node.name === "br") return " ";
2189
+ if ("children" in node) {
2190
+ return node.children.map(textContentWithBreaks).join("");
2191
+ }
2192
+ return textContent(node);
2193
+ };
2194
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2195
+ var FIELD_NAME_RE = /^[A-Za-z0-9_]+(?:[-.][A-Za-z0-9_]+)*$/;
2196
+ var UNSAFE_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
2197
+ var hasUnsafeSegment = (path) => path.split(".").some((segment) => UNSAFE_SEGMENTS.has(segment));
2198
+ var isValidFieldName = (name) => FIELD_NAME_RE.test(name) && !hasUnsafeSegment(name);
2199
+ var isFieldNameClaimed = (name, claimed, includeExact = true) => {
2200
+ for (const entry of claimed) {
2201
+ if (includeExact && entry === name || entry.startsWith(`${name}.`) || name.startsWith(`${entry}.`)) {
2202
+ return true;
2203
+ }
2204
+ }
2205
+ return false;
2206
+ };
2207
+ var attrBoundFieldNames = (attribs) => new Set(
2208
+ Object.entries(attribs).filter(
2209
+ ([name, value]) => name.startsWith(FIELD_ATTR_PREFIX) && name !== `${FIELD_ATTR_PREFIX}name` && !name.startsWith(`${FIELD_ATTR_PREFIX}value-`) && !tryParseFieldShape(value)
2210
+ ).map(([, value]) => value.trim()).filter(isValidFieldName)
2211
+ );
2212
+ var getDeepValue = (source, path) => {
2213
+ if (!path.includes(".")) return source[path];
2214
+ let current = source;
2215
+ for (const segment of path.split(".")) {
2216
+ if (!isRecord(current)) return void 0;
2217
+ current = current[segment];
2218
+ }
2219
+ return current;
2220
+ };
2221
+ var setExtractedValue = (target, path, value) => {
2222
+ if (hasUnsafeSegment(path)) return;
2223
+ const segments = path.split(".");
2224
+ let current = target;
2225
+ for (let i = 0; i < segments.length - 1; i++) {
2226
+ const existing = current[segments[i]];
2227
+ if (existing === void 0) {
2228
+ const next = {};
2229
+ current[segments[i]] = next;
2230
+ current = next;
2231
+ } else if (isRecord(existing)) {
2232
+ current = existing;
2233
+ } else {
2234
+ return;
2235
+ }
2236
+ }
2237
+ const leaf = segments[segments.length - 1];
2238
+ if (current[leaf] === void 0) {
2239
+ current[leaf] = value;
2240
+ }
2241
+ };
2242
+ var valuesEqual = (a, b) => {
2243
+ if (a === b) return true;
2244
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null || Array.isArray(a) !== Array.isArray(b)) {
2245
+ return false;
2246
+ }
2247
+ const aKeys = Object.keys(a);
2248
+ const bKeys = Object.keys(b);
2249
+ if (aKeys.length !== bKeys.length) return false;
2250
+ return aKeys.every(
2251
+ (key) => valuesEqual(
2252
+ a[key],
2253
+ b[key]
2254
+ )
2255
+ );
2256
+ };
2257
+ var parseNumber = (raw) => {
2258
+ if (raw === void 0) return void 0;
2259
+ const value = parseFloat(raw);
2260
+ return Number.isFinite(value) ? value : void 0;
2261
+ };
2262
+ var getTypeModifier = (attribs, name) => {
2263
+ const raw = attribs[TYPE_ATTR_PREFIX + name.toLowerCase()];
2264
+ return raw === "textarea" || raw === "number" || raw === "richtext" ? raw : void 0;
2265
+ };
2266
+ var getNumberConstraints = (attribs, name) => {
2267
+ const lower = name.toLowerCase();
2268
+ const constraints = {};
2269
+ const min = parseNumber(attribs[MIN_ATTR_PREFIX + lower]);
2270
+ const max = parseNumber(attribs[MAX_ATTR_PREFIX + lower]);
2271
+ const step = parseNumber(attribs[STEP_ATTR_PREFIX + lower]);
2272
+ if (min !== void 0) constraints.min = min;
2273
+ if (max !== void 0) constraints.max = max;
2274
+ if (step !== void 0) constraints.step = step;
2275
+ return constraints;
2276
+ };
2277
+ var createAccumulator = (known) => ({
2278
+ known,
2279
+ fields: [],
2280
+ values: {},
2281
+ seenFields: /* @__PURE__ */ new Set(),
2282
+ optionsByField: {},
2283
+ bindByField: {},
2284
+ bindInputsByField: {}
2285
+ });
2286
+ var collectElementFields = (element, acc) => {
2287
+ const attribs = element.attribs ?? {};
2288
+ const arrayName = attribs[ARRAY_ATTR]?.trim();
2289
+ if (arrayName) {
2290
+ if (isValidFieldName(arrayName) && !acc.seenFields.has(arrayName)) {
2291
+ acc.seenFields.add(arrayName);
2292
+ const itemElements = element.children.filter(isElement);
2293
+ const template = itemElements[0];
2294
+ const templateAcc = createAccumulator();
2295
+ if (template) {
2296
+ collectFields([template], templateAcc);
2297
+ }
2298
+ acc.fields.push({
2299
+ name: arrayName,
2300
+ binding: "array",
2301
+ itemFields: attachOptions(templateAcc),
2302
+ ...Object.keys(templateAcc.bindByField).length > 0 ? { itemBinds: templateAcc.bindByField } : {}
2303
+ });
2304
+ const items = itemElements.map((item) => {
2305
+ const itemAcc = createAccumulator();
2306
+ collectFields([item], itemAcc);
2307
+ return itemAcc.values;
2308
+ });
2309
+ setExtractedValue(acc.values, arrayName, items);
2310
+ }
2311
+ return true;
2287
2312
  }
2288
2313
  let skipChildren = false;
2289
2314
  const attrBound = attrBoundFieldNames(attribs);
@@ -2318,6 +2343,8 @@ var collectElementFields = (element, acc) => {
2318
2343
  if (!attrName.startsWith(FIELD_ATTR_PREFIX)) continue;
2319
2344
  const target = attrName.slice(FIELD_ATTR_PREFIX.length);
2320
2345
  if (!target) continue;
2346
+ const dotted = target.includes(".");
2347
+ const attrTarget = dotted ? target.split(".").pop() : target;
2321
2348
  const shape = tryParseFieldShape(attrValue);
2322
2349
  if (shape) {
2323
2350
  if (shape.type === "slot") continue;
@@ -2334,7 +2361,16 @@ var collectElementFields = (element, acc) => {
2334
2361
  continue;
2335
2362
  }
2336
2363
  acc.seenFields.add(name2);
2337
- if (shape.type === "richtext") {
2364
+ if (!isBuiltInFieldType(shape.type)) {
2365
+ const { type, ...value } = shape;
2366
+ acc.fields.push({
2367
+ name: name2,
2368
+ binding: "text",
2369
+ shape: { type },
2370
+ format: "json"
2371
+ });
2372
+ setExtractedValue(acc.values, name2, value);
2373
+ } else if (shape.type === "richtext") {
2338
2374
  acc.fields.push({ name: name2, binding: "text", shape, format: "json" });
2339
2375
  setExtractedValue(acc.values, name2, getInnerHTML(element).trim());
2340
2376
  skipChildren = true;
@@ -2356,7 +2392,29 @@ var collectElementFields = (element, acc) => {
2356
2392
  }
2357
2393
  continue;
2358
2394
  }
2359
- const name = attrValue.trim();
2395
+ if ((!attrValue || dotted && !(attrTarget in attribs)) && isValidFieldName(target)) {
2396
+ if (isFieldNameClaimed(target, attrBound, false) || isFieldNameClaimed(target, acc.seenFields)) {
2397
+ continue;
2398
+ }
2399
+ acc.seenFields.add(target);
2400
+ const knownShape = getFieldShapeAt(acc.known, target);
2401
+ acc.fields.push({
2402
+ name: target,
2403
+ binding: "text",
2404
+ format: "json",
2405
+ ...knownShape ? { shape: knownShape } : {}
2406
+ });
2407
+ const asHtml = knownShape ? knownShape.type === "richtext" : element.children.some(isElement);
2408
+ if (asHtml) {
2409
+ setExtractedValue(acc.values, target, getInnerHTML(element).trim());
2410
+ skipChildren = true;
2411
+ } else {
2412
+ const text = collapseWhitespace(textContentWithBreaks(element));
2413
+ if (text) setExtractedValue(acc.values, target, text);
2414
+ }
2415
+ continue;
2416
+ }
2417
+ const name = attrValue.trim();
2360
2418
  if (!name) continue;
2361
2419
  if (!isValidFieldName(name)) continue;
2362
2420
  if (acc.seenFields.has(name)) {
@@ -2369,7 +2427,7 @@ var collectElementFields = (element, acc) => {
2369
2427
  acc.fields[idx] = {
2370
2428
  name,
2371
2429
  binding: "attr",
2372
- attr: target,
2430
+ attr: attrTarget,
2373
2431
  shape: prev.shape
2374
2432
  };
2375
2433
  const segments = name.split(".");
@@ -2382,7 +2440,7 @@ var collectElementFields = (element, acc) => {
2382
2440
  break;
2383
2441
  }
2384
2442
  }
2385
- current[segments[segments.length - 1]] = attribs[target] ?? "";
2443
+ current[segments[segments.length - 1]] = attribs[attrTarget] ?? "";
2386
2444
  }
2387
2445
  }
2388
2446
  continue;
@@ -2423,11 +2481,11 @@ var collectElementFields = (element, acc) => {
2423
2481
  acc.fields.push({
2424
2482
  name,
2425
2483
  binding: "attr",
2426
- attr: target,
2484
+ attr: attrTarget,
2427
2485
  fieldType,
2428
2486
  ...constraints
2429
2487
  });
2430
- const value = parseNumber(attribs[target]);
2488
+ const value = parseNumber(attribs[attrTarget]);
2431
2489
  if (value !== void 0) {
2432
2490
  setExtractedValue(acc.values, name, value);
2433
2491
  }
@@ -2435,10 +2493,10 @@ var collectElementFields = (element, acc) => {
2435
2493
  acc.fields.push({
2436
2494
  name,
2437
2495
  binding: "attr",
2438
- attr: target,
2496
+ attr: attrTarget,
2439
2497
  ...fieldType && fieldType !== "richtext" ? { fieldType } : {}
2440
2498
  });
2441
- setExtractedValue(acc.values, name, attribs[target] ?? "");
2499
+ setExtractedValue(acc.values, name, attribs[attrTarget] ?? "");
2442
2500
  }
2443
2501
  }
2444
2502
  }
@@ -2463,7 +2521,16 @@ var attachOptions = (acc) => {
2463
2521
  return options ? { ...field, options } : field;
2464
2522
  });
2465
2523
  };
2466
- var parseHtmlAnnotations = (html) => {
2524
+ var getFieldShapeAt = (shapes, name) => {
2525
+ const segments = name.split(".");
2526
+ let cursor = shapes;
2527
+ for (let i = 0; i < segments.length - 1; i++) {
2528
+ cursor = cursor?.[segments[i]]?.objectFields;
2529
+ }
2530
+ const shape = cursor?.[segments[segments.length - 1]];
2531
+ return shape && shape.type !== "object" ? shape : void 0;
2532
+ };
2533
+ var parseHtmlAnnotations = (html, known) => {
2467
2534
  const annotations = {
2468
2535
  fields: [],
2469
2536
  slots: [],
@@ -2472,7 +2539,7 @@ var parseHtmlAnnotations = (html) => {
2472
2539
  bindInputs: {}
2473
2540
  };
2474
2541
  if (!html) return annotations;
2475
- const acc = createAccumulator();
2542
+ const acc = createAccumulator(known);
2476
2543
  const seenSlots = /* @__PURE__ */ new Set();
2477
2544
  const walk = (nodes) => {
2478
2545
  for (const node of nodes) {
@@ -2657,6 +2724,25 @@ var patchElement = (element, props) => {
2657
2724
  element.children = [text];
2658
2725
  continue;
2659
2726
  }
2727
+ const dotted = target.includes(".");
2728
+ const attrTarget = dotted ? target.split(".").pop() : target;
2729
+ if (!attrValue || dotted && !(attrTarget in attribs)) {
2730
+ if (isFieldNameClaimed(target, attrBoundFields, false)) continue;
2731
+ const value2 = getDeepValue(props, target);
2732
+ if (element.children.some(isElement)) {
2733
+ if (typeof value2 !== "string") continue;
2734
+ replaceChildrenWithHtml(element, value2);
2735
+ didPatch = true;
2736
+ skipChildren = true;
2737
+ continue;
2738
+ }
2739
+ if (!isPatchablePrimitive(value2)) continue;
2740
+ didPatch = true;
2741
+ const text = new Text(String(value2));
2742
+ text.parent = element;
2743
+ element.children = [text];
2744
+ continue;
2745
+ }
2660
2746
  const name = attrValue.trim();
2661
2747
  if (!name) continue;
2662
2748
  if (target === "name" && isFieldNameClaimed(name, attrBoundFields)) {
@@ -2677,7 +2763,7 @@ var patchElement = (element, props) => {
2677
2763
  text.parent = element;
2678
2764
  element.children = [text];
2679
2765
  } else {
2680
- attribs[target] = String(value);
2766
+ attribs[attrTarget] = String(value);
2681
2767
  }
2682
2768
  }
2683
2769
  return { didPatch, skipChildren };
@@ -2735,20 +2821,39 @@ var renderHtmlArrayItems = (html, arrayName, items) => {
2735
2821
 
2736
2822
  // src/lib/design/annotations.ts
2737
2823
  var cache = /* @__PURE__ */ new Map();
2824
+ var shapeSignature = (shapes) => Object.entries(shapes).map(([name, shape]) => `${name}:${shape?.type ?? ""}`).join(",");
2738
2825
  var MAX_CACHE_ENTRIES = 32;
2739
- var getAnnotations = (html) => {
2740
- const cached = cache.get(html);
2826
+ var getAnnotations = (html, known) => {
2827
+ const key = known ? `${html}\0${shapeSignature(known)}` : html;
2828
+ const cached = cache.get(key);
2741
2829
  if (cached) return cached;
2742
- const parsed = parseHtmlAnnotations(html);
2830
+ const parsed = parseHtmlAnnotations(html, known);
2743
2831
  if (cache.size >= MAX_CACHE_ENTRIES) {
2744
2832
  cache.delete(cache.keys().next().value);
2745
2833
  }
2746
- cache.set(html, parsed);
2834
+ cache.set(key, parsed);
2747
2835
  return parsed;
2748
2836
  };
2749
2837
  var getSlotFields = (html) => Object.fromEntries(
2750
2838
  getAnnotations(html).slots.map((slot) => [slot.name, toSlotField(slot)])
2751
2839
  );
2840
+ var UNTRANSFORMABLE_FIELD_TYPES = /* @__PURE__ */ new Set(["richtext", "array", "slot"]);
2841
+ var isTransformable = (field) => {
2842
+ if (!field?.type) return false;
2843
+ if (UNTRANSFORMABLE_FIELD_TYPES.has(field.type)) return false;
2844
+ const nested = field.objectFields ?? field.arrayFields;
2845
+ return nested ? Object.values(nested).every(isTransformable) : true;
2846
+ };
2847
+ var getTransformableFields = (reg) => {
2848
+ const annotations = getAnnotations(reg.html ?? "", reg.fields);
2849
+ const source = {
2850
+ ...toPuckFields(annotations.fields, annotations.values),
2851
+ ...reg.fields ?? {}
2852
+ };
2853
+ return Object.fromEntries(
2854
+ Object.entries(source).filter(([, field]) => isTransformable(field))
2855
+ );
2856
+ };
2752
2857
 
2753
2858
  // src/lib/morph-html.ts
2754
2859
  var PROTECTED_ATTRS = /* @__PURE__ */ new Set([
@@ -2764,9 +2869,11 @@ var hasTextBinding = (el, parsedTextFields) => {
2764
2869
  for (const attr of Array.from(el.attributes)) {
2765
2870
  if (!attr.name.startsWith(FIELD_ATTR_PREFIX2)) continue;
2766
2871
  if (attr.name.startsWith(VALUE_ATTR_PREFIX)) continue;
2872
+ const target = attr.name.slice(FIELD_ATTR_PREFIX2.length);
2767
2873
  const isShape = attr.value.trimStart().startsWith("{");
2768
- const fieldName = isShape ? attr.name.slice(FIELD_ATTR_PREFIX2.length) : attr.value.trim();
2769
- if (isValidFieldName(fieldName) && (attr.name === LEGACY_TEXT_ATTR || isShape) && (!parsedTextFields || parsedTextFields.has(fieldName))) {
2874
+ const isBare = !attr.value || target.includes(".") && !el.hasAttribute(target.split(".").pop());
2875
+ const fieldName = isShape || isBare ? target : attr.value.trim();
2876
+ if (isValidFieldName(fieldName) && (attr.name === LEGACY_TEXT_ATTR || isShape || isBare) && (!parsedTextFields || parsedTextFields.has(fieldName))) {
2770
2877
  return true;
2771
2878
  }
2772
2879
  }
@@ -2904,6 +3011,158 @@ ${script}
2904
3011
  })();`;
2905
3012
  };
2906
3013
 
3014
+ // src/lib/field-types.ts
3015
+ init_react_import();
3016
+
3017
+ // src/lib/json-schema-example.ts
3018
+ init_react_import();
3019
+ var FORMAT_EXAMPLES = {
3020
+ "date-time": "2024-01-31T09:30:00Z",
3021
+ time: "09:30:00",
3022
+ date: "2024-01-31",
3023
+ duration: "P1D",
3024
+ email: "hello@example.com",
3025
+ hostname: "example.com",
3026
+ ipv4: "192.0.2.1",
3027
+ ipv6: "2001:db8::1",
3028
+ uuid: "1e4f8b6a-4c2e-4a1b-9f3d-9a6b1c2d3e4f"
3029
+ };
3030
+ var NAME_EXAMPLES = {
3031
+ href: "/path",
3032
+ url: "https://example.com",
3033
+ link: "/path",
3034
+ src: "/image.png",
3035
+ alt: "Description"
3036
+ };
3037
+ var stringExample = (schema, key, valid) => {
3038
+ if (valid && typeof schema.pattern === "string") return void 0;
3039
+ if (schema.format && FORMAT_EXAMPLES[schema.format]) {
3040
+ return FORMAT_EXAMPLES[schema.format];
3041
+ }
3042
+ if (key && NAME_EXAMPLES[key]) return NAME_EXAMPLES[key];
3043
+ if (typeof schema.pattern === "string") return `<matching ${schema.pattern}>`;
3044
+ return "Example";
3045
+ };
3046
+ var numberExample = (schema) => {
3047
+ const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf } = schema;
3048
+ const isInteger = schema.type === "integer";
3049
+ const step = typeof multipleOf === "number" && multipleOf > 0 ? multipleOf : 1;
3050
+ let value = typeof minimum === "number" ? minimum : typeof exclusiveMinimum === "number" ? exclusiveMinimum + (isInteger ? 1 : step) : step;
3051
+ if (typeof multipleOf === "number" && multipleOf > 0) {
3052
+ value = Math.ceil(value / multipleOf) * multipleOf;
3053
+ }
3054
+ if (typeof maximum === "number" && value > maximum) value = maximum;
3055
+ if (typeof exclusiveMaximum === "number" && value >= exclusiveMaximum) {
3056
+ value = exclusiveMaximum - (isInteger ? 1 : step);
3057
+ }
3058
+ return isInteger ? Math.round(value) : value;
3059
+ };
3060
+ var synthesize = (schema, key, valid) => {
3061
+ if (!schema || typeof schema !== "object") return "Example";
3062
+ if (Array.isArray(schema.examples) && schema.examples.length > 0) {
3063
+ return schema.examples[0];
3064
+ }
3065
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) {
3066
+ return schema.enum[0];
3067
+ }
3068
+ if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
3069
+ if (!valid) return synthesize(schema.anyOf[0], void 0, false);
3070
+ for (const branch of schema.anyOf) {
3071
+ const value = synthesize(branch, void 0, true);
3072
+ if (value !== void 0) return value;
3073
+ }
3074
+ return void 0;
3075
+ }
3076
+ switch (schema.type) {
3077
+ case "string":
3078
+ return stringExample(schema, key, valid);
3079
+ case "number":
3080
+ case "integer":
3081
+ return numberExample(schema);
3082
+ case "boolean":
3083
+ return true;
3084
+ case "array": {
3085
+ const min = typeof schema.minItems === "number" ? schema.minItems : 1;
3086
+ const max = typeof schema.maxItems === "number" ? schema.maxItems : Infinity;
3087
+ const count = Math.max(Math.min(min || 1, max), 0);
3088
+ const item = synthesize(schema.items, key, valid);
3089
+ if (item === void 0) return void 0;
3090
+ return Array.from(
3091
+ { length: count },
3092
+ () => synthesize(schema.items, key, valid)
3093
+ );
3094
+ }
3095
+ case "object": {
3096
+ const properties = schema.properties ?? {};
3097
+ return Object.fromEntries(
3098
+ Object.entries(properties).map(([name, value]) => [name, synthesize(value, name, valid)]).filter(([, value]) => value !== void 0)
3099
+ );
3100
+ }
3101
+ default:
3102
+ return "Example";
3103
+ }
3104
+ };
3105
+ var jsonSchemaPlaceholder = (schema) => synthesize(schema, void 0, true);
3106
+
3107
+ // src/lib/field-types.ts
3108
+ var toWireFieldTypes = (registry) => Object.fromEntries(
3109
+ Object.entries(registry).map(
3110
+ ([type, { description, schema, defaultValue }]) => [
3111
+ type,
3112
+ {
3113
+ ...description !== void 0 ? { description } : {},
3114
+ ...schema !== void 0 ? { schema } : {},
3115
+ ...typeof defaultValue === "function" ? { editorDefault: true } : defaultValue !== void 0 ? { defaultValue } : {}
3116
+ }
3117
+ ]
3118
+ )
3119
+ );
3120
+ var getFieldTypeDefault = (fieldTypes, type, ctx) => {
3121
+ const fieldType = fieldTypes[type];
3122
+ if (!fieldType) return void 0;
3123
+ if (fieldType.defaultValue !== void 0) {
3124
+ return typeof fieldType.defaultValue === "function" ? fieldType.defaultValue(ctx) : fieldType.defaultValue;
3125
+ }
3126
+ return jsonSchemaPlaceholder(fieldType.schema);
3127
+ };
3128
+ var isUnvalued = (value) => value === void 0 || !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
3129
+ var fill = (values, fields, fieldTypes, componentName, declared, path) => {
3130
+ let out = values;
3131
+ for (const [fieldName, field] of Object.entries(fields ?? {})) {
3132
+ const type = field?.type;
3133
+ if (!type) continue;
3134
+ const qualified = path ? `${path}.${fieldName}` : fieldName;
3135
+ if (fieldTypes[type]) {
3136
+ if (!isUnvalued(out[fieldName])) continue;
3137
+ const declaredValue = declared?.[fieldName];
3138
+ const value = isUnvalued(declaredValue) ? getFieldTypeDefault(fieldTypes, type, {
3139
+ componentName,
3140
+ fieldName: qualified
3141
+ }) : declaredValue;
3142
+ if (isUnvalued(value)) continue;
3143
+ if (out === values) out = { ...values };
3144
+ out[fieldName] = value;
3145
+ continue;
3146
+ }
3147
+ if (!field.objectFields) continue;
3148
+ const group = out[fieldName];
3149
+ const declaredGroup = declared?.[fieldName];
3150
+ const filled = fill(
3151
+ group && typeof group === "object" ? group : {},
3152
+ field.objectFields,
3153
+ fieldTypes,
3154
+ componentName,
3155
+ declaredGroup && typeof declaredGroup === "object" ? declaredGroup : void 0,
3156
+ qualified
3157
+ );
3158
+ if (filled === group) continue;
3159
+ if (out === values) out = { ...values };
3160
+ out[fieldName] = filled;
3161
+ }
3162
+ return out;
3163
+ };
3164
+ var withFieldTypeDefaults = (values, fields, fieldTypes, componentName, declared) => fill(values, fields, fieldTypes, componentName, declared, "");
3165
+
2907
3166
  // src/lib/design/registration-store.ts
2908
3167
  init_react_import();
2909
3168
  var RegistrationStore = class {
@@ -2977,7 +3236,12 @@ init_react_import();
2977
3236
  import { registerOverlayPortal, setDeep } from "@puckeditor/core";
2978
3237
  var CONTENT_EDITABLE_ATTR = "data-puck-content-editable";
2979
3238
  var isInlineEditingDisabled = (el) => el.closest(`[${CONTENT_EDITABLE_ATTR}="false"]`) !== null;
2980
- var cssEscape = (value) => typeof CSS !== "undefined" && CSS.escape ? CSS.escape(value) : value.replace(/["\\]/g, "\\$&");
3239
+ var cssEscape = (value) => typeof CSS !== "undefined" && CSS.escape ? CSS.escape(value) : (
3240
+ // Escapes for an IDENTIFIER, not just a quoted value: a dotted field name
3241
+ // sits in the attribute-name slot too, where an unescaped `.` reads as a
3242
+ // class selector and throws. Over-escaping inside quotes is harmless.
3243
+ value.replace(/[^\w-]/g, "\\$&")
3244
+ );
2981
3245
  var queryScopedFields = (entry, selector) => Array.from(entry.querySelectorAll(selector)).filter((el) => {
2982
3246
  if (el.closest("[data-puck-array]")) return false;
2983
3247
  const closestSlot = el.closest("[data-puck-slot]");
@@ -3271,7 +3535,18 @@ var parseStyleString = (cssText) => {
3271
3535
  return style;
3272
3536
  };
3273
3537
  var isEventHandlerAttr2 = (name) => /^on/i.test(name);
3274
- var nodeToReact = (node, slots, key) => {
3538
+ var FIELD_ATTR_PREFIX3 = "data-puck-field-";
3539
+ var fieldContentFor = (attribs, fields) => {
3540
+ for (const name of Object.keys(fields)) {
3541
+ const own = attribs[`${FIELD_ATTR_PREFIX3}${name}`]?.trim();
3542
+ if (own !== void 0 && (own === "" || own.startsWith("{") || own === name)) {
3543
+ return name;
3544
+ }
3545
+ if (attribs["data-puck-field-name"] === name) return name;
3546
+ }
3547
+ return void 0;
3548
+ };
3549
+ var nodeToReact = (node, slots, fields, key) => {
3275
3550
  if (node.type === "text") {
3276
3551
  return node.data;
3277
3552
  }
@@ -3302,13 +3577,17 @@ var nodeToReact = (node, slots, key) => {
3302
3577
  if (VOID_ELEMENTS.has(tag)) {
3303
3578
  return createElement3(tag, props);
3304
3579
  }
3305
- const children = el.children.map((child, i) => nodeToReact(child, slots, i)).filter((c) => c !== null);
3580
+ const fieldName = fieldContentFor(attribs, fields);
3581
+ if (fieldName !== void 0) {
3582
+ return createElement3(tag, props, fields[fieldName]);
3583
+ }
3584
+ const children = el.children.map((child, i) => nodeToReact(child, slots, fields, i)).filter((c) => c !== null);
3306
3585
  return createElement3(tag, props, ...children);
3307
3586
  };
3308
- var htmlToReactTree = (html, slots) => {
3587
+ var htmlToReactTree = (html, slots, fields = {}) => {
3309
3588
  if (!html) return null;
3310
3589
  const doc = parseDocument2(html);
3311
- const children = doc.children.map((child, i) => nodeToReact(child, slots, i)).filter((c) => c !== null);
3590
+ const children = doc.children.map((child, i) => nodeToReact(child, slots, fields, i)).filter((c) => c !== null);
3312
3591
  if (children.length === 0) return null;
3313
3592
  if (children.length === 1) return children[0];
3314
3593
  return createElement3(Fragment3, null, ...children);
@@ -3316,7 +3595,7 @@ var htmlToReactTree = (html, slots) => {
3316
3595
 
3317
3596
  // src/lib/design/slot-portal.tsx
3318
3597
  init_react_import();
3319
- import { useEffect as useEffect6, useMemo as useMemo2, useRef as useRef6, useState as useState7 } from "react";
3598
+ import { useEffect as useEffect5, useMemo as useMemo2, useRef as useRef4, useState as useState6 } from "react";
3320
3599
  import { createPortal } from "react-dom";
3321
3600
  import { jsx as jsx6 } from "react/jsx-runtime";
3322
3601
  var parseInlineStyle = (cssText) => {
@@ -3340,13 +3619,13 @@ var SlotPortal = ({
3340
3619
  slotClassName,
3341
3620
  SlotContent
3342
3621
  }) => {
3343
- const [target, setTarget] = useState7(null);
3344
- const lastTarget = useRef6(null);
3622
+ const [target, setTarget] = useState6(null);
3623
+ const lastTarget = useRef4(null);
3345
3624
  const style = useMemo2(
3346
3625
  () => slotStyle ? parseInlineStyle(slotStyle) : void 0,
3347
3626
  [slotStyle]
3348
3627
  );
3349
- useEffect6(() => {
3628
+ useEffect5(() => {
3350
3629
  const el = entry.querySelector(`[data-puck-slot="${cssEscape(slotName)}"]`);
3351
3630
  if (el !== lastTarget.current) {
3352
3631
  el?.replaceChildren();
@@ -3365,6 +3644,30 @@ var SlotPortal = ({
3365
3644
  );
3366
3645
  };
3367
3646
 
3647
+ // src/lib/design/field-portal.tsx
3648
+ init_react_import();
3649
+ import { useEffect as useEffect6, useRef as useRef5, useState as useState7 } from "react";
3650
+ import { createPortal as createPortal2 } from "react-dom";
3651
+ var FieldPortal = ({
3652
+ entry,
3653
+ html,
3654
+ selector,
3655
+ children
3656
+ }) => {
3657
+ const [target, setTarget] = useState7(null);
3658
+ const lastTarget = useRef5(null);
3659
+ useEffect6(() => {
3660
+ const el = queryScopedFields(entry, selector)[0] ?? null;
3661
+ if (el !== lastTarget.current) {
3662
+ el?.replaceChildren();
3663
+ lastTarget.current = el;
3664
+ setTarget(el);
3665
+ }
3666
+ }, [entry, html, selector]);
3667
+ if (!target) return null;
3668
+ return createPortal2(children, target);
3669
+ };
3670
+
3368
3671
  // src/lib/design/component.tsx
3369
3672
  import { Fragment as Fragment4, jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
3370
3673
  var DESIGN_COMPONENT = Symbol("puck-ai.designComponent");
@@ -3387,16 +3690,44 @@ var getRegistrationSlotFields = (reg) => {
3387
3690
  ])
3388
3691
  );
3389
3692
  };
3390
- function createDesignComponentConfig(registration) {
3693
+ var hasPendingUserField = (field, value) => {
3694
+ if (!field?.type || field.type === "slot") return false;
3695
+ if (!isBuiltInFieldType(field.type)) return value === void 0;
3696
+ if (field.objectFields) {
3697
+ const group = value && typeof value === "object" ? value : {};
3698
+ return Object.entries(field.objectFields).some(
3699
+ ([key, child]) => hasPendingUserField(child, group[key])
3700
+ );
3701
+ }
3702
+ if (field.arrayFields) {
3703
+ const items = Array.isArray(value) ? value : [];
3704
+ return items.some(
3705
+ (item) => Object.entries(field.arrayFields).some(
3706
+ ([key, child]) => hasPendingUserField(child, item?.[key])
3707
+ )
3708
+ );
3709
+ }
3710
+ return false;
3711
+ };
3712
+ function createDesignComponentConfig(registration, fieldTypes = {}) {
3391
3713
  const name = registration.name;
3392
3714
  if (registrationStore.get(name) !== registration) {
3393
3715
  registrationStore.apply(registration);
3394
3716
  }
3395
3717
  const slotFields = getRegistrationSlotFields(registration);
3718
+ const staticFields = {
3719
+ ...slotFields,
3720
+ ...getTransformableFields(registration)
3721
+ };
3396
3722
  const componentConfig = {
3397
3723
  ...registration.label ? { label: registration.label } : {},
3398
- fields: { ...slotFields },
3399
- defaultProps: { ...registration.defaultProps ?? {} },
3724
+ fields: staticFields,
3725
+ defaultProps: withFieldTypeDefaults(
3726
+ { ...registration.defaultProps ?? {} },
3727
+ staticFields,
3728
+ fieldTypes,
3729
+ name
3730
+ ),
3400
3731
  resolveData: (data, { trigger }) => {
3401
3732
  if (trigger !== "replace" && trigger !== "insert" && trigger !== "force") {
3402
3733
  return data;
@@ -3404,22 +3735,23 @@ function createDesignComponentConfig(registration) {
3404
3735
  const reg = registrationStore.get(name) ?? registration;
3405
3736
  const markup = reg.html ?? "";
3406
3737
  if (!markup) return { props: {} };
3407
- const annotations = getAnnotations(markup);
3738
+ const annotations = getAnnotations(markup, reg.fields);
3739
+ const fieldSet = getTransformableFields(reg);
3740
+ const extracted = withFieldTypeDefaults(
3741
+ annotations.values,
3742
+ fieldSet,
3743
+ fieldTypes,
3744
+ name,
3745
+ reg.defaultProps
3746
+ );
3408
3747
  const cacheKey = instanceKey(name, data.props.id);
3409
3748
  let newProps;
3410
3749
  if (reg.streaming) {
3411
3750
  const previous = streamingValues.get(cacheKey) ?? registrationStore.getPreviousValues(name);
3412
- newProps = resolveStreamingProps(
3413
- data.props,
3414
- annotations.values,
3415
- previous
3416
- );
3417
- streamingValues.set(cacheKey, annotations.values);
3751
+ newProps = resolveStreamingProps(data.props, extracted, previous);
3752
+ streamingValues.set(cacheKey, extracted);
3418
3753
  } else {
3419
- const values = {
3420
- ...annotations.values,
3421
- ...reg.defaultProps ?? {}
3422
- };
3754
+ const values = { ...extracted, ...reg.defaultProps ?? {} };
3423
3755
  const previous = streamingValues.get(cacheKey);
3424
3756
  if (previous) {
3425
3757
  newProps = resolveStreamingProps(data.props, values, previous);
@@ -3433,24 +3765,41 @@ function createDesignComponentConfig(registration) {
3433
3765
  }
3434
3766
  streamingValues.delete(cacheKey);
3435
3767
  }
3768
+ const merged = { ...data.props, ...newProps };
3769
+ const filled = withFieldTypeDefaults(
3770
+ merged,
3771
+ fieldSet,
3772
+ fieldTypes,
3773
+ name,
3774
+ reg.defaultProps
3775
+ );
3776
+ if (filled !== merged) {
3777
+ for (const [key, value] of Object.entries(filled)) {
3778
+ if (value !== merged[key]) newProps[key] = value;
3779
+ }
3780
+ }
3436
3781
  if (Object.keys(newProps).length === 0) return { props: {} };
3437
3782
  return { props: newProps };
3438
3783
  },
3439
- resolveFields: () => {
3784
+ resolveFields: (data) => {
3440
3785
  const reg = registrationStore.get(name) ?? registration;
3441
3786
  const fields = reg.fields ?? {};
3787
+ let resolvedFields;
3442
3788
  if (Object.keys(fields).length > 0) {
3443
- return { ...fields };
3789
+ resolvedFields = { ...fields };
3790
+ } else {
3791
+ const annotations = getAnnotations(reg.html ?? "");
3792
+ resolvedFields = toPuckFields(annotations.fields, annotations.values);
3793
+ for (const slot of annotations.slots) {
3794
+ resolvedFields[slot.name] = toSlotField(slot);
3795
+ }
3444
3796
  }
3445
- const annotations = getAnnotations(reg.html ?? "");
3446
- const resolvedFields = toPuckFields(
3447
- annotations.fields,
3448
- annotations.values
3797
+ if (!reg.streaming) return resolvedFields;
3798
+ return Object.fromEntries(
3799
+ Object.entries(resolvedFields).filter(
3800
+ ([key, field]) => !hasPendingUserField(field, getDeepValue(data.props, key))
3801
+ )
3449
3802
  );
3450
- for (const slot of annotations.slots) {
3451
- resolvedFields[slot.name] = toSlotField(slot);
3452
- }
3453
- return resolvedFields;
3454
3803
  },
3455
3804
  render: (renderProps) => renderProps.puck?.isEditing ? /* @__PURE__ */ jsx7(EditorEntry, { ...renderProps }) : /* @__PURE__ */ jsx7(Entry, { ...renderProps, getPuck: null })
3456
3805
  };
@@ -3467,7 +3816,7 @@ function createDesignComponentConfig(registration) {
3467
3816
  style,
3468
3817
  ...props
3469
3818
  }) {
3470
- const getSnapshot = useCallback5(
3819
+ const getSnapshot = useCallback4(
3471
3820
  () => registrationStore.get(name) ?? registration,
3472
3821
  []
3473
3822
  );
@@ -3480,8 +3829,11 @@ function createDesignComponentConfig(registration) {
3480
3829
  const styles = reg.styles;
3481
3830
  const script = reg.script;
3482
3831
  const [entryEl, setEntryEl] = useState8(null);
3483
- const scriptRef = useRef7(null);
3484
- const annotations = useMemo3(() => getAnnotations(html), [html]);
3832
+ const scriptRef = useRef6(null);
3833
+ const annotations = useMemo3(
3834
+ () => getAnnotations(html, reg.fields),
3835
+ [html, reg.fields]
3836
+ );
3485
3837
  const { attrFields, arrayFields, attrSig, arraySig } = useMemo3(() => {
3486
3838
  const attr = [];
3487
3839
  const arrays = [];
@@ -3504,6 +3856,34 @@ function createDesignComponentConfig(registration) {
3504
3856
  arraySig: JSON.stringify(arrays)
3505
3857
  };
3506
3858
  }, [props, annotations]);
3859
+ const nodeFields = useMemo3(() => {
3860
+ const out = [];
3861
+ for (const field of annotations.fields) {
3862
+ if (field.binding !== "text") continue;
3863
+ const value = getDeepValue(props, field.name);
3864
+ if (!isValidElement(value)) continue;
3865
+ out.push({
3866
+ name: field.name,
3867
+ selector: textFieldSelector(field),
3868
+ node: value
3869
+ });
3870
+ }
3871
+ return out;
3872
+ }, [annotations, props]);
3873
+ const storedProps = useMemo3(
3874
+ () => getPuck ? getPuck().getItemById(id)?.props : void 0,
3875
+ [getPuck, id, props]
3876
+ );
3877
+ const editableFields = useMemo3(() => {
3878
+ const mounted = new Set(nodeFields.map((f) => f.name));
3879
+ return annotations.fields.filter((field) => {
3880
+ if (mounted.has(field.name)) return false;
3881
+ if (field.binding === "array") return true;
3882
+ if (field.shape && !isBuiltInFieldType(field.shape.type)) return false;
3883
+ if (!storedProps) return true;
3884
+ return getDeepValue(props, field.name) === getDeepValue(storedProps, field.name);
3885
+ });
3886
+ }, [annotations, nodeFields, props, storedProps]);
3507
3887
  const patchedHtml = useMemo3(() => {
3508
3888
  if (puck.isEditing) return html;
3509
3889
  return patchHtmlAnnotations(html, props);
@@ -3515,6 +3895,7 @@ function createDesignComponentConfig(registration) {
3515
3895
  const value = getDeepValue(props, field.name);
3516
3896
  if (value === void 0 || value === null) continue;
3517
3897
  if (!isValidFieldName(field.name)) continue;
3898
+ if (isValidElement(value)) continue;
3518
3899
  attrs[`data-puck-field-value-${field.name}`] = typeof value === "string" || typeof value === "number" ? String(value) : JSON.stringify(value);
3519
3900
  }
3520
3901
  return attrs;
@@ -3527,8 +3908,8 @@ function createDesignComponentConfig(registration) {
3527
3908
  if (!puck.isEditing || !getPuck) return;
3528
3909
  getPuck().resolveDataById(id, "force");
3529
3910
  }, [reg, puck.isEditing, getPuck, id]);
3530
- const fieldWiring = useRef7(/* @__PURE__ */ new Map());
3531
- const morphed = useRef7(null);
3911
+ const fieldWiring = useRef6(/* @__PURE__ */ new Map());
3912
+ const morphed = useRef6(null);
3532
3913
  useLayoutEffect(() => {
3533
3914
  if (!puck.isEditing || !entryEl) return;
3534
3915
  if (morphed.current?.el !== entryEl || morphed.current?.html !== html || morphed.current?.attrSig !== attrSig) {
@@ -3540,7 +3921,7 @@ function createDesignComponentConfig(registration) {
3540
3921
  }
3541
3922
  syncFieldValues(entryEl, annotations.fields, props);
3542
3923
  if (getPuck) {
3543
- wireFieldEditing(entryEl, annotations.fields, fieldWiring.current, {
3924
+ wireFieldEditing(entryEl, editableFields, fieldWiring.current, {
3544
3925
  componentId: id,
3545
3926
  getPuck
3546
3927
  });
@@ -3566,9 +3947,9 @@ function createDesignComponentConfig(registration) {
3566
3947
  }
3567
3948
  }
3568
3949
  }, [entryEl, fieldValueAttrs]);
3569
- const appliedArrayHtml = useRef7(/* @__PURE__ */ new WeakMap());
3570
- const arrayItemWiring = useRef7({});
3571
- const appliedArrays = useRef7(null);
3950
+ const appliedArrayHtml = useRef6(/* @__PURE__ */ new WeakMap());
3951
+ const arrayItemWiring = useRef6({});
3952
+ const appliedArrays = useRef6(null);
3572
3953
  useEffect7(() => {
3573
3954
  if (!puck.isEditing || !entryEl || !getPuck) return;
3574
3955
  if (appliedArrays.current?.el === entryEl && appliedArrays.current?.html === html && appliedArrays.current?.sig === arraySig) {
@@ -3656,16 +4037,30 @@ function createDesignComponentConfig(registration) {
3656
4037
  );
3657
4038
  }
3658
4039
  }
4040
+ const fieldContent = {};
4041
+ for (const { name: name2, node } of nodeFields) {
4042
+ fieldContent[name2] = node;
4043
+ }
3659
4044
  return /* @__PURE__ */ jsxs5(Fragment4, { children: [
3660
4045
  styles && /* @__PURE__ */ jsx7("style", { children: styles }),
3661
4046
  style && /* @__PURE__ */ jsx7("style", { children: style }),
3662
- /* @__PURE__ */ jsx7("div", { ref: setEntryEl, ...fieldValueAttrs, children: htmlToReactTree(patchedHtml, slotContent) })
4047
+ /* @__PURE__ */ jsx7("div", { ref: setEntryEl, ...fieldValueAttrs, children: htmlToReactTree(patchedHtml, slotContent, fieldContent) })
3663
4048
  ] });
3664
4049
  }
3665
4050
  return /* @__PURE__ */ jsxs5(Fragment4, { children: [
3666
4051
  styles && /* @__PURE__ */ jsx7("style", { children: styles }),
3667
4052
  style && /* @__PURE__ */ jsx7("style", { children: style }),
3668
4053
  editorEntryNode,
4054
+ entryEl && nodeFields.map(({ name: name2, selector, node }) => /* @__PURE__ */ jsx7(
4055
+ FieldPortal,
4056
+ {
4057
+ entry: entryEl,
4058
+ html,
4059
+ selector,
4060
+ children: node
4061
+ },
4062
+ name2
4063
+ )),
3669
4064
  entryEl && annotations.slots.map((slot) => /* @__PURE__ */ jsx7(
3670
4065
  SlotPortal,
3671
4066
  {
@@ -3684,7 +4079,7 @@ function createDesignComponentConfig(registration) {
3684
4079
 
3685
4080
  // src/lib/design/globals.tsx
3686
4081
  init_react_import();
3687
- import { useEffect as useEffect8, useRef as useRef8 } from "react";
4082
+ import { useEffect as useEffect8, useRef as useRef7 } from "react";
3688
4083
  import { Fragment as Fragment5, jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
3689
4084
  function getDynamicConfigGlobals(dynamicConfig) {
3690
4085
  if (typeof dynamicConfig !== "object" || dynamicConfig === null) return {};
@@ -3700,8 +4095,8 @@ function DesignGlobals({
3700
4095
  script,
3701
4096
  isEditing
3702
4097
  }) {
3703
- const scriptRef = useRef8(null);
3704
- const hostRef = useRef8(null);
4098
+ const scriptRef = useRef7(null);
4099
+ const hostRef = useRef7(null);
3705
4100
  useEffect8(() => {
3706
4101
  if (!script) return;
3707
4102
  scriptRef.current?.remove();
@@ -3840,7 +4235,7 @@ function syncDesignedComponentsCategory(getPuck, designedComponents, hadRemovals
3840
4235
  }
3841
4236
  var lastSynced = /* @__PURE__ */ new Map();
3842
4237
  var registrationContentEqual = (a, b) => !!a && !!b && a.html === b.html && a.styles === b.styles && a.script === b.script && a.label === b.label && !a.streaming === !b.streaming;
3843
- function syncDesignComponents(getPuck) {
4238
+ function syncDesignComponents(getPuck, fieldTypes = {}) {
3844
4239
  const { config, appState, dispatch } = getPuck();
3845
4240
  const persisted = getPersistedRegistrations(appState.data) ?? {};
3846
4241
  if (cachedFieldMetadata === void 0) {
@@ -3859,7 +4254,10 @@ function syncDesignComponents(getPuck) {
3859
4254
  const isSettled = !registration.streaming;
3860
4255
  if (!config.components[name] || !prev) {
3861
4256
  ensureDynamicConfigField(config);
3862
- const componentConfig = createDesignComponentConfig(registration);
4257
+ const componentConfig = createDesignComponentConfig(
4258
+ registration,
4259
+ fieldTypes
4260
+ );
3863
4261
  if (cachedFieldMetadata) {
3864
4262
  applyFieldMetadata(componentConfig, cachedFieldMetadata);
3865
4263
  }
@@ -3868,13 +4266,18 @@ function syncDesignComponents(getPuck) {
3868
4266
  } else {
3869
4267
  if (registration.label)
3870
4268
  config.components[name].label = registration.label;
3871
- if (isSettled) {
3872
- config.components[name].defaultProps = {
3873
- ...registration.defaultProps ?? {}
3874
- };
3875
- }
3876
4269
  }
3877
- config.components[name].fields = getSlotFields(registration.html ?? "");
4270
+ const fields = {
4271
+ ...getSlotFields(registration.html ?? ""),
4272
+ ...getTransformableFields(registration)
4273
+ };
4274
+ config.components[name].fields = fields;
4275
+ config.components[name].defaultProps = withFieldTypeDefaults(
4276
+ { ...registration.defaultProps ?? {} },
4277
+ fields,
4278
+ fieldTypes,
4279
+ name
4280
+ );
3878
4281
  }
3879
4282
  let hasRemovals = false;
3880
4283
  for (const [name] of registrationStore.getAll()) {
@@ -4004,6 +4407,43 @@ var waitForIframeReady = async (root, imageTimeout = 1e4) => {
4004
4407
  await waitForNextPaint(document2);
4005
4408
  };
4006
4409
 
4410
+ // src/lib/to-serializable.ts
4411
+ init_react_import();
4412
+ function toSerializable(value, ancestors = []) {
4413
+ const json = typeof value === "object" && value !== null && "toJSON" in value && typeof value.toJSON === "function" ? value.toJSON() : value;
4414
+ if (typeof json !== "object" || json === null) {
4415
+ return typeof json === "function" || typeof json === "symbol" || typeof json === "bigint" ? void 0 : json;
4416
+ }
4417
+ if ("$$typeof" in json || ancestors.includes(json)) return void 0;
4418
+ ancestors.push(json);
4419
+ let copy;
4420
+ if (Array.isArray(json)) {
4421
+ copy = json.map((item) => toSerializable(item, ancestors) ?? null);
4422
+ } else {
4423
+ const record = json;
4424
+ const object = {};
4425
+ for (const key of Object.keys(record)) {
4426
+ const item = toSerializable(record[key], ancestors);
4427
+ if (item !== void 0) object[key] = item;
4428
+ }
4429
+ copy = object;
4430
+ }
4431
+ ancestors.pop();
4432
+ return copy;
4433
+ }
4434
+
4435
+ // src/lib/merge-headers.ts
4436
+ init_react_import();
4437
+ function mergeHeaders(...inits) {
4438
+ const result = {};
4439
+ for (const init of inits) {
4440
+ new Headers(init).forEach((value, name) => {
4441
+ result[name] = value;
4442
+ });
4443
+ }
4444
+ return result;
4445
+ }
4446
+
4007
4447
  // src/lib/capture-screenshot.ts
4008
4448
  init_react_import();
4009
4449
  import html2canvas from "html2canvas-pro";
@@ -4128,76 +4568,757 @@ var captureScreenshot = async (root, { scale = CAPTURE_SCALE, quality = 0.8, wid
4128
4568
  if (fitted !== canvas) releaseCanvas(fitted);
4129
4569
  releaseCanvas(canvas);
4130
4570
  }
4131
- };
4132
-
4133
- // src/lib/client-tool-response.ts
4134
- init_react_import();
4135
- async function postClientToolResponse(host, body) {
4136
- const response = await fetch(`${host.replace(/\/+$/, "")}/tool`, {
4137
- method: "POST",
4138
- headers: { "Content-Type": "application/json" },
4139
- body: JSON.stringify(body)
4140
- });
4141
- if (!response.ok) {
4142
- throw new Error(
4143
- `Client tool endpoint returned ${response.status} ${response.statusText}`.trim()
4144
- );
4571
+ };
4572
+
4573
+ // src/lib/client-tool-response.ts
4574
+ init_react_import();
4575
+ async function postClientToolResponse(host, body, {
4576
+ headers,
4577
+ credentials,
4578
+ signal
4579
+ } = {}) {
4580
+ const response = await fetch(`${host.replace(/\/+$/, "")}/tool`, {
4581
+ method: "POST",
4582
+ headers: { "Content-Type": "application/json", ...headers },
4583
+ credentials,
4584
+ body: JSON.stringify(body),
4585
+ signal
4586
+ });
4587
+ if (!response.ok) {
4588
+ throw new Error(
4589
+ `Client tool endpoint returned ${response.status} ${response.statusText}`.trim()
4590
+ );
4591
+ }
4592
+ }
4593
+
4594
+ // ../utils/lib/iterate-sse.ts
4595
+ init_react_import();
4596
+ async function* iterateSSE(body) {
4597
+ const reader = body.getReader();
4598
+ const dec = new TextDecoder();
4599
+ let buf = "";
4600
+ try {
4601
+ while (true) {
4602
+ const { done, value } = await reader.read();
4603
+ if (done) break;
4604
+ buf += dec.decode(value, { stream: true });
4605
+ let idx;
4606
+ while ((idx = buf.indexOf("\n\n")) >= 0) {
4607
+ const chunk = buf.slice(0, idx).trim();
4608
+ buf = buf.slice(idx + 2);
4609
+ if (!chunk) continue;
4610
+ const line = chunk.startsWith("data: ") ? chunk.slice(6) : chunk;
4611
+ try {
4612
+ yield JSON.parse(line);
4613
+ } catch {
4614
+ }
4615
+ }
4616
+ }
4617
+ } finally {
4618
+ reader.cancel().catch(() => {
4619
+ });
4620
+ reader.releaseLock();
4621
+ }
4622
+ }
4623
+
4624
+ // src/lib/use-puck-ai.ts
4625
+ var q = qler();
4626
+ var usePuck2 = createUsePuck2();
4627
+ var DEFAULT_API_VERSION = "v2";
4628
+ var BUILD_OP_DEBOUNCE_MS = 1e3 / 60;
4629
+ var CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE = "Unable to verify the page data. Please enable the `/chat/tool` endpoint on the server and try again.";
4630
+ var PLUGIN_AI_VERSION = true ? "0.9.0" : "unknown";
4631
+ var prefixedUlid = (prefix = "") => `${prefix ? `${prefix}_` : ""}${ulid()}`;
4632
+ async function prepareRequestOptions(defaults, prepareRequest) {
4633
+ if (!prepareRequest) return defaults;
4634
+ const userOptions = await prepareRequest(defaults);
4635
+ return {
4636
+ headers: mergeHeaders(defaults.headers, userOptions.headers),
4637
+ credentials: userOptions.credentials ?? defaults.credentials,
4638
+ body: { ...defaults.body, ...userOptions.body }
4639
+ };
4640
+ }
4641
+ var abortError = () => new DOMException("The generation was cancelled.", "AbortError");
4642
+ var untilAborted = (promise, signal) => new Promise((resolve, reject) => {
4643
+ const onAbort = () => reject(abortError());
4644
+ if (signal.aborted) return onAbort();
4645
+ signal.addEventListener("abort", onAbort, { once: true });
4646
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
4647
+ });
4648
+ function usePuckAiInternal({
4649
+ host = "/api/puck/chat",
4650
+ mode = "assembly",
4651
+ apiVersion = DEFAULT_API_VERSION,
4652
+ prepareRequest,
4653
+ onFinish,
4654
+ onError,
4655
+ fieldTypes
4656
+ } = {}) {
4657
+ const puckDispatch = usePuck2((s) => s.dispatch);
4658
+ const getPuck = useGetPuck4();
4659
+ const localChatId = useRef8("");
4660
+ const pendingBuildOpsRef = useRef8([]);
4661
+ const clientToolEndpointUnavailableRef = useRef8(false);
4662
+ const stopRef = useRef8(null);
4663
+ const generateAbortRef = useRef8(null);
4664
+ const unmountedRef = useRef8(false);
4665
+ const lastStreamActivityRef = useRef8(0);
4666
+ const hiddenSinceRef = useRef8(null);
4667
+ const [error, setError] = useState9();
4668
+ const [toolStatus, setToolStatus] = useState9({});
4669
+ const [subagentState, setSubagentState] = useState9({});
4670
+ const modeRef = useRef8(mode);
4671
+ const onErrorRef = useRef8(onError);
4672
+ useEffect9(() => {
4673
+ onErrorRef.current = onError;
4674
+ }, [onError]);
4675
+ useEffect9(() => {
4676
+ modeRef.current = mode;
4677
+ }, [mode]);
4678
+ const puckData = usePuck2((s) => s.appState.data);
4679
+ useEffect9(() => {
4680
+ syncDesignComponents(getPuck, fieldTypes);
4681
+ }, [puckData, getPuck, fieldTypes]);
4682
+ const debouncedFlushBuildOps = useDebouncedCallback(
4683
+ () => {
4684
+ const operations = pendingBuildOpsRef.current;
4685
+ pendingBuildOpsRef.current = [];
4686
+ if (operations.length === 0) return;
4687
+ q.queue(
4688
+ () => new Promise((resolve) => {
4689
+ nextFrame(() => {
4690
+ const { dispatch, config, resolveDataById } = getPuck();
4691
+ operations.forEach((queuedOperation) => {
4692
+ (0, import_reducer.dispatchOp)(queuedOperation, {
4693
+ getState: () => {
4694
+ const { __private } = getPuck();
4695
+ return __private.appState;
4696
+ },
4697
+ dispatchAction: dispatch,
4698
+ config
4699
+ });
4700
+ if (queuedOperation.op === "add" || queuedOperation.op === "update") {
4701
+ resolveDataById(queuedOperation.id, "replace");
4702
+ }
4703
+ if (queuedOperation.op === "updateRoot") {
4704
+ syncDesignComponents(getPuck, fieldTypes);
4705
+ }
4706
+ });
4707
+ resolve();
4708
+ });
4709
+ })
4710
+ );
4711
+ },
4712
+ BUILD_OP_DEBOUNCE_MS,
4713
+ { maxWait: BUILD_OP_DEBOUNCE_MS }
4714
+ );
4715
+ const queueBuildOp = useCallback5(
4716
+ (operation) => {
4717
+ pendingBuildOpsRef.current.push(operation);
4718
+ debouncedFlushBuildOps();
4719
+ },
4720
+ [debouncedFlushBuildOps]
4721
+ );
4722
+ const handleClientToolEndpointUnavailable = useCallback5(() => {
4723
+ if (clientToolEndpointUnavailableRef.current) return;
4724
+ clientToolEndpointUnavailableRef.current = true;
4725
+ setError(CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE);
4726
+ console.error(CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE);
4727
+ onErrorRef.current?.(
4728
+ new Error(CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE)
4729
+ );
4730
+ setToolStatus(
4731
+ (current) => finishLoadingTools(current, "Verification unavailable")
4732
+ );
4733
+ stopRef.current?.();
4734
+ }, []);
4735
+ const prepare = useCallback5(
4736
+ (defaults) => prepareRequestOptions(defaults, prepareRequest),
4737
+ [prepareRequest]
4738
+ );
4739
+ const sendClientToolResponse = useCallback5(
4740
+ async (body, signal) => {
4741
+ const request = await prepare({ body });
4742
+ try {
4743
+ await postClientToolResponse(host, request.body, {
4744
+ headers: request.headers,
4745
+ credentials: request.credentials,
4746
+ signal
4747
+ });
4748
+ } catch (e) {
4749
+ if (signal?.aborted) throw e;
4750
+ throw new Error(CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE);
4751
+ }
4752
+ },
4753
+ [host, prepare]
4754
+ );
4755
+ const clearError = useCallback5(() => {
4756
+ clientToolEndpointUnavailableRef.current = false;
4757
+ setError(void 0);
4758
+ }, []);
4759
+ const applyToEditor = useCallback5(
4760
+ async (dataPart, { chatId, signal } = {}) => {
4761
+ if (dataPart.type.indexOf("data-") !== 0) {
4762
+ return;
4763
+ }
4764
+ switch (dataPart.type) {
4765
+ case "data-puck-actions": {
4766
+ dataPart.data.forEach((action) => {
4767
+ try {
4768
+ puckDispatch(action);
4769
+ } catch (e) {
4770
+ console.error("Bad action: ", action);
4771
+ console.error(e);
4772
+ }
4773
+ });
4774
+ return;
4775
+ }
4776
+ case "data-build-op": {
4777
+ const { pageId, ...operation } = dataPart.data;
4778
+ if (pageId) {
4779
+ return;
4780
+ }
4781
+ queueBuildOp(operation);
4782
+ return;
4783
+ }
4784
+ case "data-client-request": {
4785
+ const request = dataPart.data;
4786
+ debouncedFlushBuildOps.flush();
4787
+ await q.wait();
4788
+ if (signal?.aborted) return;
4789
+ let output;
4790
+ if (request.action === "getPageData") {
4791
+ output = getPuck().appState.data;
4792
+ } else {
4793
+ const blob = await uploadPreviewScreenshot(request.params.putUrl, {
4794
+ signal
4795
+ }).catch((e) => {
4796
+ console.error("Failed to capture the screenshot:", e);
4797
+ return null;
4798
+ });
4799
+ output = { sizeBytes: blob?.size ?? 0 };
4800
+ }
4801
+ if (signal?.aborted) return;
4802
+ await sendClientToolResponse(
4803
+ {
4804
+ id: request.requestId,
4805
+ chatId,
4806
+ responses: [{ action: request.action, output }]
4807
+ },
4808
+ signal
4809
+ );
4810
+ return;
4811
+ }
4812
+ case "data-send-screenshot": {
4813
+ dataPart.data.urls.forEach((obj) => {
4814
+ const [entry] = Object.entries(obj);
4815
+ if (!entry) return;
4816
+ const [key, value] = entry;
4817
+ uploadPreviewScreenshot(value, { width: Number(key) }).catch(
4818
+ (e) => console.error("Failed to upload screenshot", e)
4819
+ );
4820
+ });
4821
+ return;
4822
+ }
4823
+ case "data-finish": {
4824
+ debouncedFlushBuildOps.flush();
4825
+ return;
4826
+ }
4827
+ case "data-page": {
4828
+ return;
4829
+ }
4830
+ case "data-version-notice": {
4831
+ console.warn(dataPart.data.message);
4832
+ return;
4833
+ }
4834
+ // The chat's progress, which only its own UI shows
4835
+ case "data-new-chat-created":
4836
+ case "data-tool-status":
4837
+ case "data-subagent-event": {
4838
+ return;
4839
+ }
4840
+ default:
4841
+ console.warn("dataPart without case:", dataPart);
4842
+ return;
4843
+ }
4844
+ },
4845
+ [
4846
+ debouncedFlushBuildOps,
4847
+ getPuck,
4848
+ puckDispatch,
4849
+ queueBuildOp,
4850
+ sendClientToolResponse
4851
+ ]
4852
+ );
4853
+ const applyChatPart = useCallback5(
4854
+ (dataPart) => {
4855
+ lastStreamActivityRef.current = Date.now();
4856
+ switch (dataPart.type) {
4857
+ case "data-new-chat-created": {
4858
+ localChatId.current = dataPart.data.chatId;
4859
+ return;
4860
+ }
4861
+ case "data-tool-status": {
4862
+ setToolStatus((s) => ({
4863
+ ...s,
4864
+ [dataPart.data.toolCallId]: dataPart.data.status
4865
+ }));
4866
+ return;
4867
+ }
4868
+ case "data-subagent-event": {
4869
+ setSubagentState(
4870
+ (current) => reduceSubagentEvent(current, dataPart.data)
4871
+ );
4872
+ return;
4873
+ }
4874
+ }
4875
+ applyToEditor(dataPart, {
4876
+ chatId: localChatId.current || void 0
4877
+ }).catch(handleClientToolEndpointUnavailable);
4878
+ },
4879
+ [applyToEditor, handleClientToolEndpointUnavailable]
4880
+ );
4881
+ const getRequestConfig = useCallback5(() => {
4882
+ const { config, appState } = getPuck();
4883
+ const root = config.root ?? {
4884
+ fields: {
4885
+ title: {
4886
+ type: "text",
4887
+ ai: { instructions: "The title for the page" }
4888
+ }
4889
+ }
4890
+ };
4891
+ return toSerializable({
4892
+ ...config,
4893
+ root,
4894
+ components: {
4895
+ ...config.components,
4896
+ ...getRequestComponentConfigs(appState.data)
4897
+ }
4898
+ });
4899
+ }, [getPuck]);
4900
+ const settle = useCallback5(
4901
+ async ({ recordHistory = true } = {}) => {
4902
+ debouncedFlushBuildOps.flush();
4903
+ await q.wait();
4904
+ if (recordHistory && !unmountedRef.current) {
4905
+ puckDispatch({
4906
+ type: "set",
4907
+ state: getPuck().appState,
4908
+ recordHistory: true
4909
+ });
4910
+ }
4911
+ },
4912
+ [debouncedFlushBuildOps, getPuck, puckDispatch]
4913
+ );
4914
+ const {
4915
+ messages,
4916
+ status: chatStatus,
4917
+ sendMessage: chatSendMessage,
4918
+ regenerate,
4919
+ setMessages,
4920
+ stop
4921
+ } = useChat({
4922
+ generateId: () => prefixedUlid("msg"),
4923
+ messages: [],
4924
+ transport: new DefaultChatTransport2({
4925
+ api: host,
4926
+ prepareSendMessagesRequest: async (opts) => {
4927
+ const { appState } = getPuck();
4928
+ const configWithRoot = getRequestConfig();
4929
+ return prepare({
4930
+ headers: mergeHeaders(opts.headers, {
4931
+ "puck-api-version": apiVersion,
4932
+ "x-puck-plugin-ai-version": PLUGIN_AI_VERSION
4933
+ }),
4934
+ credentials: opts.credentials,
4935
+ body: {
4936
+ ...opts.body,
4937
+ chatId: localChatId.current,
4938
+ trigger: opts.trigger,
4939
+ messages: opts.messages,
4940
+ pageData: appState.data,
4941
+ config: configWithRoot,
4942
+ fieldTypes: toWireFieldTypes(fieldTypes ?? {}),
4943
+ mode: opts.body?.mode ?? modeRef.current
4944
+ }
4945
+ });
4946
+ }
4947
+ }),
4948
+ onData: applyChatPart,
4949
+ onError: (e) => {
4950
+ console.error(e);
4951
+ if (!clientToolEndpointUnavailableRef.current) {
4952
+ setError(e.message);
4953
+ }
4954
+ onError?.(e);
4955
+ },
4956
+ onFinish: (options) => {
4957
+ if (options.isAbort || options.isDisconnect || options.isError) {
4958
+ setToolStatus((current) => finishLoadingTools(current, "Interrupted"));
4959
+ }
4960
+ settle().then(() => onFinish?.(options));
4961
+ }
4962
+ });
4963
+ const sendMessage = useCallback5(
4964
+ async (prompt, opts = {}) => {
4965
+ const text = prompt.trim();
4966
+ const files = opts.files ?? [];
4967
+ if (!text && files.length === 0) return;
4968
+ clearError();
4969
+ await chatSendMessage(
4970
+ {
4971
+ role: "user",
4972
+ parts: [...text ? [{ type: "text", text }] : [], ...files]
4973
+ },
4974
+ opts.mode ? { body: { mode: opts.mode } } : void 0
4975
+ );
4976
+ },
4977
+ [chatSendMessage, clearError]
4978
+ );
4979
+ const regenerateTurn = useCallback5(
4980
+ (...args) => {
4981
+ clearError();
4982
+ return regenerate(...args);
4983
+ },
4984
+ [clearError, regenerate]
4985
+ );
4986
+ const applyPart = useCallback5(
4987
+ async (part, { recordHistory = false } = {}) => {
4988
+ await applyToEditor(part);
4989
+ if (recordHistory) await settle();
4990
+ },
4991
+ [applyToEditor, settle]
4992
+ );
4993
+ const generate = useCallback5(
4994
+ async (prompt, opts = {}) => {
4995
+ const text = prompt.trim();
4996
+ if (!text) return getPuck().appState.data;
4997
+ generateAbortRef.current?.abort();
4998
+ const controller = new AbortController();
4999
+ const cancel = () => controller.abort();
5000
+ generateAbortRef.current = controller;
5001
+ let changed = false;
5002
+ if (opts.signal?.aborted) cancel();
5003
+ opts.signal?.addEventListener("abort", cancel, { once: true });
5004
+ try {
5005
+ debouncedFlushBuildOps.flush();
5006
+ await q.wait();
5007
+ const { appState } = getPuck();
5008
+ const request = await untilAborted(
5009
+ prepare({
5010
+ headers: {
5011
+ "Content-Type": "application/json",
5012
+ "puck-api-version": apiVersion,
5013
+ "x-puck-plugin-ai-version": PLUGIN_AI_VERSION
5014
+ },
5015
+ body: {
5016
+ prompt: text,
5017
+ config: getRequestConfig(),
5018
+ pageData: appState.data,
5019
+ mode: opts.mode ?? modeRef.current
5020
+ }
5021
+ }),
5022
+ controller.signal
5023
+ );
5024
+ const response = await fetch(`${host.replace(/\/+$/, "")}/generate`, {
5025
+ method: "POST",
5026
+ headers: request.headers,
5027
+ credentials: request.credentials,
5028
+ body: JSON.stringify(request.body),
5029
+ signal: controller.signal
5030
+ });
5031
+ if (!response.ok || !response.body) {
5032
+ const body = await response.json().catch(() => null);
5033
+ throw new Error(
5034
+ body?.error ?? `Puck AI request failed: ${response.status} ${response.statusText}`
5035
+ );
5036
+ }
5037
+ for await (const part of iterateSSE(response.body)) {
5038
+ if (controller.signal.aborted) throw abortError();
5039
+ if (part.type === "error") throw new Error(part.errorText);
5040
+ if (part.type === "data-build-op" || part.type === "data-puck-actions") {
5041
+ changed = true;
5042
+ }
5043
+ await untilAborted(
5044
+ applyToEditor(part, { signal: controller.signal }),
5045
+ controller.signal
5046
+ );
5047
+ }
5048
+ if (controller.signal.aborted) throw abortError();
5049
+ await settle();
5050
+ return getPuck().appState.data;
5051
+ } catch (e) {
5052
+ await settle({ recordHistory: changed });
5053
+ throw controller.signal.aborted ? abortError() : e;
5054
+ } finally {
5055
+ opts.signal?.removeEventListener("abort", cancel);
5056
+ controller.abort();
5057
+ if (generateAbortRef.current === controller) {
5058
+ generateAbortRef.current = null;
5059
+ }
5060
+ }
5061
+ },
5062
+ [
5063
+ apiVersion,
5064
+ applyToEditor,
5065
+ debouncedFlushBuildOps,
5066
+ getPuck,
5067
+ host,
5068
+ getRequestConfig,
5069
+ prepare,
5070
+ settle
5071
+ ]
5072
+ );
5073
+ useEffect9(() => {
5074
+ unmountedRef.current = false;
5075
+ stopRef.current = stop;
5076
+ return () => {
5077
+ unmountedRef.current = true;
5078
+ stopRef.current = null;
5079
+ generateAbortRef.current?.abort();
5080
+ stop();
5081
+ };
5082
+ }, [stop]);
5083
+ const chatStatusRef = useRef8(chatStatus);
5084
+ useEffect9(() => {
5085
+ chatStatusRef.current = chatStatus;
5086
+ }, [chatStatus]);
5087
+ useEffect9(() => {
5088
+ lastStreamActivityRef.current = Date.now();
5089
+ }, [messages]);
5090
+ useEffect9(() => {
5091
+ const FROZEN_HIDDEN_MS = 3 * 6e4;
5092
+ const RESUME_GRACE_MS = 12e3;
5093
+ const isStreaming = () => chatStatusRef.current === "streaming" || chatStatusRef.current === "submitted";
5094
+ let graceTimer;
5095
+ const recoverIfSevered = () => {
5096
+ if (!isStreaming()) return;
5097
+ if (Date.now() - lastStreamActivityRef.current < RESUME_GRACE_MS) return;
5098
+ stop();
5099
+ setToolStatus((current) => finishLoadingTools(current, "Interrupted"));
5100
+ };
5101
+ const onVisibilityChange = () => {
5102
+ if (document.hidden) {
5103
+ hiddenSinceRef.current = isStreaming() ? Date.now() : null;
5104
+ return;
5105
+ }
5106
+ const hiddenSince = hiddenSinceRef.current;
5107
+ hiddenSinceRef.current = null;
5108
+ if (graceTimer) clearTimeout(graceTimer);
5109
+ if (hiddenSince === null || Date.now() - hiddenSince < FROZEN_HIDDEN_MS) {
5110
+ return;
5111
+ }
5112
+ lastStreamActivityRef.current = 0;
5113
+ graceTimer = setTimeout(recoverIfSevered, RESUME_GRACE_MS);
5114
+ };
5115
+ document.addEventListener("visibilitychange", onVisibilityChange);
5116
+ return () => {
5117
+ document.removeEventListener("visibilitychange", onVisibilityChange);
5118
+ if (graceTimer) clearTimeout(graceTimer);
5119
+ };
5120
+ }, [stop]);
5121
+ const chat = useMemo4(
5122
+ () => ({
5123
+ /** Send a new message to the agent. */
5124
+ sendMessage,
5125
+ /** Run the conversation's last turn again. */
5126
+ regenerate: regenerateTurn,
5127
+ /** Stop the running turn. */
5128
+ stop,
5129
+ /** The conversation's AI SDK status. */
5130
+ status: chatStatus,
5131
+ /** The last chat error's message, or `undefined`. Also passed to `onError`. */
5132
+ error,
5133
+ /** The conversation, as AI SDK `UIMessage`s. */
5134
+ messages,
5135
+ /** The live progress of the agent's tools, keyed by tool call id. */
5136
+ toolStatus
5137
+ }),
5138
+ [chatStatus, error, messages, regenerateTurn, sendMessage, stop, toolStatus]
5139
+ );
5140
+ return {
5141
+ chat,
5142
+ generate,
5143
+ applyPart,
5144
+ /** Live subagent progress, keyed by tool call id */
5145
+ subagentState,
5146
+ /** Apply a part as part of the chat, as its own turns do */
5147
+ applyChatPart,
5148
+ /** Replace the conversation's messages, for the homepage demo's replay */
5149
+ setMessages
5150
+ };
5151
+ }
5152
+ function usePuckAi(options = {}) {
5153
+ const { chat, generate, applyPart } = usePuckAiInternal(options);
5154
+ return {
5155
+ chat,
5156
+ /**
5157
+ * Run a generation against the current page. Returns the page's Data once
5158
+ * it's applied. Iterates once, unless the handler's `ai.maxIterations`
5159
+ * allows more.
5160
+ */
5161
+ generate,
5162
+ /** Apply and process an AI Part. */
5163
+ applyPart
5164
+ };
5165
+ }
5166
+ async function uploadPreviewScreenshot(url, { signal, ...captureOptions } = {}) {
5167
+ const iframeDocument = document?.getElementById("preview-frame")?.contentDocument?.documentElement ?? null;
5168
+ if (!iframeDocument) {
5169
+ throw new Error("Preview frame not found");
5170
+ }
5171
+ await waitForIframeReady(iframeDocument);
5172
+ const blob = await captureScreenshot(iframeDocument, captureOptions);
5173
+ if (signal?.aborted) throw abortError();
5174
+ const uploadResponse = await fetch(url, {
5175
+ method: "PUT",
5176
+ body: blob,
5177
+ signal
5178
+ });
5179
+ if (!uploadResponse.ok) {
5180
+ throw new Error(`Upload failed with status ${uploadResponse.status}`);
5181
+ }
5182
+ return blob;
5183
+ }
5184
+ function finishLoadingTools(current, label) {
5185
+ let changed = false;
5186
+ const next = {};
5187
+ for (const [id, toolState] of Object.entries(current)) {
5188
+ if (toolState.loading) {
5189
+ changed = true;
5190
+ next[id] = { ...toolState, loading: false, label };
5191
+ } else {
5192
+ next[id] = toolState;
5193
+ }
5194
+ }
5195
+ return changed ? next : current;
5196
+ }
5197
+ function finalizeReasoningParts(parts) {
5198
+ return parts.map(
5199
+ (part) => part.kind === "reasoning" && part.state !== "done" ? { ...part, state: "done" } : part
5200
+ );
5201
+ }
5202
+ function reduceSubagentEvent(current, event) {
5203
+ if (event.kind === "start") {
5204
+ if (current[event.toolCallId]) return current;
5205
+ return {
5206
+ ...current,
5207
+ [event.toolCallId]: {
5208
+ toolCallId: event.toolCallId,
5209
+ parentToolCallId: event.parentToolCallId,
5210
+ agentType: event.agentType,
5211
+ depth: event.depth,
5212
+ label: event.label,
5213
+ state: "running",
5214
+ parts: []
5215
+ }
5216
+ };
5217
+ }
5218
+ const existing = current[event.toolCallId];
5219
+ if (!existing) return current;
5220
+ if (event.kind === "finish") {
5221
+ return {
5222
+ ...current,
5223
+ [event.toolCallId]: {
5224
+ ...existing,
5225
+ state: "done",
5226
+ parts: finalizeReasoningParts(existing.parts)
5227
+ }
5228
+ };
5229
+ }
5230
+ if (event.kind === "reasoning-delta") {
5231
+ const parts = [...existing.parts];
5232
+ const last = parts[parts.length - 1];
5233
+ if (last && last.kind === "reasoning" && last.state !== "done") {
5234
+ const separator = last.blockId !== event.blockId ? "\n\n" : "";
5235
+ parts[parts.length - 1] = {
5236
+ ...last,
5237
+ blockId: event.blockId,
5238
+ text: last.text + separator + event.text
5239
+ };
5240
+ } else {
5241
+ parts.push({
5242
+ kind: "reasoning",
5243
+ blockId: event.blockId,
5244
+ text: event.text,
5245
+ state: "streaming"
5246
+ });
5247
+ }
5248
+ return {
5249
+ ...current,
5250
+ [event.toolCallId]: { ...existing, parts }
5251
+ };
5252
+ }
5253
+ if (event.kind === "text-delta") {
5254
+ const parts = finalizeReasoningParts(existing.parts);
5255
+ const last = parts[parts.length - 1];
5256
+ if (last && last.kind === "text" && last.blockId === event.blockId) {
5257
+ parts[parts.length - 1] = { ...last, text: last.text + event.text };
5258
+ } else {
5259
+ parts.push({ kind: "text", blockId: event.blockId, text: event.text });
5260
+ }
5261
+ return {
5262
+ ...current,
5263
+ [event.toolCallId]: { ...existing, parts }
5264
+ };
5265
+ }
5266
+ if (event.kind === "tool-call") {
5267
+ return {
5268
+ ...current,
5269
+ [event.toolCallId]: {
5270
+ ...existing,
5271
+ parts: [
5272
+ ...finalizeReasoningParts(existing.parts),
5273
+ {
5274
+ kind: "tool",
5275
+ childToolCallId: event.childToolCallId,
5276
+ toolName: event.toolName,
5277
+ input: event.input
5278
+ }
5279
+ ]
5280
+ }
5281
+ };
5282
+ }
5283
+ if (event.kind === "tool-result") {
5284
+ return {
5285
+ ...current,
5286
+ [event.toolCallId]: {
5287
+ ...existing,
5288
+ parts: existing.parts.map(
5289
+ (part) => part.kind === "tool" && part.childToolCallId === event.childToolCallId ? { ...part, output: event.output } : part
5290
+ )
5291
+ }
5292
+ };
4145
5293
  }
5294
+ return current;
4146
5295
  }
4147
-
4148
- // src/lib/to-serializable.ts
4149
- init_react_import();
4150
- function toSerializable(value, ancestors = []) {
4151
- const json = typeof value === "object" && value !== null && "toJSON" in value && typeof value.toJSON === "function" ? value.toJSON() : value;
4152
- if (typeof json !== "object" || json === null) {
4153
- return typeof json === "function" || typeof json === "symbol" || typeof json === "bigint" ? void 0 : json;
4154
- }
4155
- if ("$$typeof" in json || ancestors.includes(json)) return void 0;
4156
- ancestors.push(json);
4157
- let copy;
4158
- if (Array.isArray(json)) {
4159
- copy = json.map((item) => toSerializable(item, ancestors) ?? null);
4160
- } else {
4161
- const record = json;
4162
- const object = {};
4163
- for (const key of Object.keys(record)) {
4164
- const item = toSerializable(record[key], ancestors);
4165
- if (item !== void 0) object[key] = item;
4166
- }
4167
- copy = object;
5296
+ function nextFrame(cb) {
5297
+ let ran = false;
5298
+ const run = () => {
5299
+ if (ran) return;
5300
+ ran = true;
5301
+ cb();
5302
+ };
5303
+ if (typeof document !== "undefined" && document.hidden) {
5304
+ queueMicrotask(run);
5305
+ return;
4168
5306
  }
4169
- ancestors.pop();
4170
- return copy;
5307
+ requestAnimationFrame(run);
5308
+ setTimeout(run, 100);
4171
5309
  }
4172
5310
 
4173
- // src/components/PluginTheme/index.ts
4174
- init_react_import();
4175
-
4176
- // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/PluginTheme/styles.module.css#css-module
4177
- init_react_import();
4178
- var styles_module_default6 = { "PluginTheme": "_PluginTheme_u3emj_8" };
4179
-
4180
- // src/components/PluginTheme/index.ts
4181
- var cx4 = getClassNameFactory("PluginTheme", styles_module_default6);
4182
- var pluginThemeClassName = cx4();
4183
-
4184
5311
  // src/components/Chat/index.tsx
4185
5312
  import { Fragment as Fragment6, jsx as jsx10, jsxs as jsxs7 } from "react/jsx-runtime";
4186
- var q = qler();
4187
- var DEFAULT_API_VERSION = "v2";
4188
- var BUILD_OP_DEBOUNCE_MS = 1e3 / 60;
4189
- var CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE = "Unable to verify the page data. Please enable the `/chat/tool` endpoint on the server and try again.";
4190
- var PLUGIN_AI_VERSION = true ? "0.9.0-canary.f8c1abd5" : "unknown";
4191
- var BENCHMARK = false;
4192
- var prefixedUlid = (prefix = "") => `${prefix ? `${prefix}_` : ""}${ulid()}`;
4193
5313
  var getClassName3 = getClassNameFactory("Chat", styles_module_default);
4194
- var usePuck2 = createUsePuck2();
5314
+ var usePuck3 = createUsePuck3();
4195
5315
  function Chat2(props) {
4196
5316
  const {
4197
5317
  apiVersion = DEFAULT_API_VERSION,
4198
5318
  chat,
4199
5319
  designMode = false,
4200
5320
  defaultMode = "assembly",
5321
+ fieldTypes,
4201
5322
  host = "/api/puck/chat",
4202
5323
  prepareRequest,
4203
5324
  scrollTrackingId
@@ -4208,433 +5329,73 @@ function Chat2(props) {
4208
5329
  actions: chatActions,
4209
5330
  placeholder
4210
5331
  } = chat ?? {};
4211
- const puckDispatch = usePuck2((s) => s.dispatch);
4212
- const getPuck = useGetPuck4();
5332
+ const puckDispatch = usePuck3((s) => s.dispatch);
5333
+ const getPuck = useGetPuck5();
4213
5334
  const t = (key, params) => getMessage(getPuck().dictionary, key, params);
4214
- const localChatId = useRef9("");
4215
5335
  const inputRef = useRef9(null);
4216
5336
  const pluginRef = useRef9(null);
4217
- const [mode, setMode] = useState9(defaultMode);
4218
- const modeRef = useRef9(mode);
5337
+ const [mode, setMode] = useState10(defaultMode);
4219
5338
  const designModeVisible = typeof designMode === "boolean" ? designMode : designMode.visible ?? false;
4220
- useEffect9(() => {
4221
- modeRef.current = mode;
4222
- }, [mode]);
4223
- const puckData = usePuck2((s) => s.appState.data);
4224
- useEffect9(() => {
4225
- syncDesignComponents(getPuck);
4226
- }, [puckData, getPuck]);
4227
- const [error, setError] = useState9();
4228
- const [userError, setUserError] = useState9();
4229
- const clientToolEndpointUnavailableRef = useRef9(false);
4230
- const stopChatRef = useRef9(null);
4231
- const [composerAttachments, setComposerAttachments] = useState9([]);
5339
+ const [error, setError] = useState10();
5340
+ const [userError, setUserError] = useState10();
5341
+ const [composerAttachments, setComposerAttachments] = useState10([]);
4232
5342
  const removedAttachmentClientIdsRef = useRef9(/* @__PURE__ */ new Set());
4233
5343
  const uploadControllersRef = useRef9(/* @__PURE__ */ new Map());
4234
- const pendingBuildOpsRef = useRef9([]);
4235
- const lastStreamActivityRef = useRef9(0);
4236
- const hiddenSinceRef = useRef9(null);
4237
- const [toolStatus, setToolStatus] = useState9({});
4238
- const [subagentState, setSubagentState] = useState9({});
4239
- const attachmentConfig = useMemo4(
4240
- () => ({
4241
- accept: attachments?.accept ?? defaultAttachmentAccept,
4242
- enabled: attachments?.enabled ?? true,
4243
- endpoint: `${host.replace(/\/$/, "")}/attachments`,
4244
- maxFiles: attachments?.maxFiles ?? defaultAttachmentConfig.maxFiles,
4245
- maxSizeBytes: attachments?.maxSizeBytes ?? defaultAttachmentConfig.maxSizeBytes
4246
- }),
4247
- [attachments, host]
4248
- );
4249
- useEffect9(
4250
- () => () => {
4251
- uploadControllersRef.current.forEach((controller) => controller.abort());
4252
- uploadControllersRef.current.clear();
4253
- },
4254
- []
4255
- );
4256
- const deleteAttachment = useCallback6(
4257
- async (attachmentId) => {
4258
- try {
4259
- await fetch(`${attachmentConfig.endpoint}/${attachmentId}`, {
4260
- method: "DELETE"
4261
- });
4262
- } catch (e) {
4263
- console.error(e);
4264
- }
4265
- },
4266
- [attachmentConfig.endpoint]
4267
- );
4268
- const uploadScreenshot = useCallback6(
4269
- async (width, bucketUrl) => {
4270
- try {
4271
- const iframeDocument = document?.getElementById("preview-frame")?.contentDocument?.documentElement ?? null;
4272
- if (!iframeDocument) {
4273
- throw new Error("Preview frame not found");
4274
- }
4275
- await waitForIframeReady(iframeDocument);
4276
- const blob = await captureScreenshot(iframeDocument, { width });
4277
- const uploadResponse = await fetch(bucketUrl, {
4278
- method: "PUT",
4279
- body: blob
4280
- });
4281
- if (!uploadResponse.ok) {
4282
- throw new Error(`Upload failed with status ${uploadResponse.status}`);
4283
- }
4284
- } catch (e) {
4285
- console.error("Failed to upload screenshot", e);
4286
- }
4287
- },
4288
- []
4289
- );
4290
- const debouncedFlushBuildOps = useDebouncedCallback(
4291
- () => {
4292
- const operations = pendingBuildOpsRef.current;
4293
- pendingBuildOpsRef.current = [];
4294
- if (operations.length === 0) return;
4295
- q.queue(
4296
- () => new Promise((resolve) => {
4297
- nextFrame(() => {
4298
- const { dispatch, config, resolveDataById } = getPuck();
4299
- operations.forEach((queuedOperation) => {
4300
- (0, import_reducer.dispatchOp)(queuedOperation, {
4301
- getState: () => {
4302
- const { __private } = getPuck();
4303
- return __private.appState;
4304
- },
4305
- dispatchAction: dispatch,
4306
- config
4307
- });
4308
- if (queuedOperation.op === "add" || queuedOperation.op === "update") {
4309
- resolveDataById(queuedOperation.id, "replace");
4310
- }
4311
- if (queuedOperation.op === "updateRoot") {
4312
- syncDesignComponents(getPuck);
4313
- }
4314
- });
4315
- resolve();
4316
- });
4317
- })
4318
- );
4319
- },
4320
- BUILD_OP_DEBOUNCE_MS,
4321
- { maxWait: BUILD_OP_DEBOUNCE_MS }
4322
- );
4323
- const queueBuildOp = useCallback6(
4324
- (operation) => {
4325
- pendingBuildOpsRef.current.push(operation);
4326
- debouncedFlushBuildOps();
4327
- },
4328
- [debouncedFlushBuildOps]
4329
- );
4330
- const handleClientToolEndpointUnavailable = useCallback6(() => {
4331
- if (clientToolEndpointUnavailableRef.current) return;
4332
- clientToolEndpointUnavailableRef.current = true;
4333
- setError(CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE);
4334
- console.error(CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE);
4335
- setToolStatus((current) => {
4336
- let changed = false;
4337
- const next = {};
4338
- for (const [id, toolState] of Object.entries(current)) {
4339
- if (toolState.loading) {
4340
- changed = true;
4341
- next[id] = {
4342
- ...toolState,
4343
- loading: false,
4344
- label: "Verification unavailable"
4345
- };
4346
- } else {
4347
- next[id] = toolState;
4348
- }
4349
- }
4350
- return changed ? next : current;
4351
- });
4352
- stopChatRef.current?.();
4353
- }, []);
4354
- const sendClientToolResponse = useCallback6(
4355
- async (body) => {
4356
- try {
4357
- await postClientToolResponse(host, body);
4358
- } catch {
4359
- handleClientToolEndpointUnavailable();
4360
- }
4361
- },
4362
- [handleClientToolEndpointUnavailable, host]
4363
- );
4364
- const processData = useCallback6(
4365
- (dataPart) => {
4366
- lastStreamActivityRef.current = Date.now();
4367
- switch (dataPart.type) {
4368
- case "data-new-chat-created": {
4369
- localChatId.current = dataPart.data.chatId;
4370
- return;
4371
- }
4372
- case "data-puck-actions": {
4373
- dataPart.data.forEach((action) => {
4374
- try {
4375
- puckDispatch(action);
4376
- } catch (e) {
4377
- console.error("Bad action: ", action);
4378
- console.error(e);
4379
- }
4380
- });
4381
- return;
4382
- }
4383
- case "data-build-op": {
4384
- const { pageId, ...operation } = dataPart.data;
4385
- if (pageId) {
4386
- return;
4387
- }
4388
- queueBuildOp(operation);
4389
- return;
4390
- }
4391
- case "data-client-request": {
4392
- const { requestId, action } = dataPart.data;
4393
- const chatId = localChatId.current || void 0;
4394
- if (action === "getPageData") {
4395
- debouncedFlushBuildOps.flush();
4396
- q.wait().then(() => {
4397
- const { appState } = getPuck();
4398
- return sendClientToolResponse({
4399
- id: requestId,
4400
- chatId,
4401
- responses: [{ action, output: appState.data }]
4402
- });
4403
- }).catch((e) => {
4404
- console.error("Failed to respond to client request:", e);
4405
- });
4406
- }
4407
- if (action === "takeScreenshot") {
4408
- const { putUrl } = dataPart.data.params ?? {};
4409
- debouncedFlushBuildOps.flush();
4410
- q.wait().then(async () => {
4411
- const iframeDocument = document?.getElementById(
4412
- "preview-frame"
4413
- )?.contentDocument?.documentElement ?? null;
4414
- if (!iframeDocument) {
4415
- throw new Error("Preview frame not found");
4416
- }
4417
- await waitForIframeReady(iframeDocument);
4418
- const blob = await captureScreenshot(iframeDocument);
4419
- const uploadResponse = await fetch(putUrl, {
4420
- method: "PUT",
4421
- body: blob
4422
- });
4423
- if (!uploadResponse.ok) {
4424
- throw new Error(
4425
- `Upload failed with status ${uploadResponse.status}`
4426
- );
4427
- }
4428
- return sendClientToolResponse({
4429
- id: requestId,
4430
- chatId,
4431
- responses: [{ action, output: { sizeBytes: blob.size } }]
4432
- });
4433
- }).catch((e) => {
4434
- console.error("Failed to respond to client request:", e);
4435
- return sendClientToolResponse({
4436
- id: requestId,
4437
- chatId,
4438
- responses: [{ action, output: { sizeBytes: 0 } }]
4439
- });
4440
- });
4441
- }
4442
- return;
4443
- }
4444
- case "data-tool-status": {
4445
- setToolStatus((s) => ({
4446
- ...s,
4447
- [dataPart.data.toolCallId]: dataPart.data.status
4448
- }));
4449
- return;
4450
- }
4451
- case "data-subagent-event": {
4452
- setSubagentState(
4453
- (current) => reduceSubagentEvent(current, dataPart.data)
4454
- );
4455
- return;
4456
- }
4457
- case "data-send-screenshot": {
4458
- dataPart.data.urls.forEach((obj) => {
4459
- const [[key, value]] = Object.entries(obj);
4460
- const breakpoint = Number(key);
4461
- uploadScreenshot(breakpoint, value);
4462
- });
4463
- return;
4464
- }
4465
- case "data-finish": {
4466
- debouncedFlushBuildOps.flush();
4467
- return;
4468
- }
4469
- case "data-version-notice": {
4470
- console.warn(dataPart.data.message);
4471
- return;
4472
- }
4473
- default:
4474
- console.warn("dataPart without case:", dataPart);
4475
- return;
4476
- }
5344
+ const attachmentConfig = useMemo5(
5345
+ () => ({
5346
+ accept: attachments?.accept ?? defaultAttachmentAccept,
5347
+ enabled: attachments?.enabled ?? true,
5348
+ endpoint: `${host.replace(/\/$/, "")}/attachments`,
5349
+ maxFiles: attachments?.maxFiles ?? defaultAttachmentConfig.maxFiles,
5350
+ maxSizeBytes: attachments?.maxSizeBytes ?? defaultAttachmentConfig.maxSizeBytes
5351
+ }),
5352
+ [attachments, host]
5353
+ );
5354
+ useEffect10(
5355
+ () => () => {
5356
+ uploadControllersRef.current.forEach((controller) => controller.abort());
5357
+ uploadControllersRef.current.clear();
4477
5358
  },
4478
- [
4479
- debouncedFlushBuildOps,
4480
- getPuck,
4481
- puckDispatch,
4482
- queueBuildOp,
4483
- sendClientToolResponse,
4484
- uploadScreenshot
4485
- ]
5359
+ []
4486
5360
  );
4487
- const { messages, status, sendMessage, regenerate, setMessages, stop } = useChat({
4488
- generateId: () => prefixedUlid("msg"),
4489
- messages: [],
4490
- transport: new DefaultChatTransport2({
4491
- api: host,
4492
- prepareSendMessagesRequest: async (opts) => {
4493
- const { config, appState } = getPuck();
4494
- if (BENCHMARK) {
4495
- console.time("chat");
4496
- }
4497
- const root = config.root ?? {
4498
- fields: {
4499
- title: {
4500
- type: "text",
4501
- ai: { instructions: "The title for the page" }
4502
- }
4503
- }
4504
- };
4505
- const configWithRoot = toSerializable({
4506
- ...config,
4507
- root,
4508
- components: {
4509
- ...config.components,
4510
- ...getRequestComponentConfigs(appState.data)
4511
- }
5361
+ const deleteAttachment = useCallback6(
5362
+ async (attachmentId) => {
5363
+ try {
5364
+ await fetch(`${attachmentConfig.endpoint}/${attachmentId}`, {
5365
+ method: "DELETE"
4512
5366
  });
4513
- const defaultOptions = {
4514
- headers: {
4515
- ...opts.headers,
4516
- "puck-api-version": apiVersion,
4517
- "x-puck-plugin-ai-version": PLUGIN_AI_VERSION
4518
- },
4519
- credentials: opts.credentials,
4520
- body: {
4521
- ...opts.body,
4522
- chatId: localChatId.current,
4523
- trigger: opts.trigger,
4524
- messages: opts.messages,
4525
- pageData: appState.data,
4526
- config: configWithRoot,
4527
- mode: modeRef.current
4528
- }
4529
- };
4530
- if (prepareRequest) {
4531
- const userOptions = await prepareRequest(defaultOptions);
4532
- return {
4533
- headers: {
4534
- ...defaultOptions.headers,
4535
- ...userOptions.headers
4536
- },
4537
- credentials: userOptions.credentials ?? defaultOptions.credentials,
4538
- body: {
4539
- ...defaultOptions.body,
4540
- ...userOptions.body
4541
- }
4542
- };
4543
- }
4544
- return defaultOptions;
4545
- }
4546
- }),
4547
- onData: processData,
4548
- onError: (e) => {
4549
- console.error(e);
4550
- if (BENCHMARK) {
4551
- console.timeEnd("chat");
4552
- }
4553
- if (!clientToolEndpointUnavailableRef.current) {
4554
- setError(e.message);
5367
+ } catch (e) {
5368
+ console.error(e);
4555
5369
  }
4556
5370
  },
4557
- onFinish: (options) => {
4558
- debouncedFlushBuildOps.flush();
4559
- q.wait().then(() => {
4560
- if (!options.isAbort || clientToolEndpointUnavailableRef.current) {
4561
- puckDispatch({
4562
- type: "set",
4563
- state: getPuck().appState,
4564
- recordHistory: true
4565
- });
4566
- }
4567
- chat?.onFinish?.(options);
4568
- }).finally(() => {
4569
- if (BENCHMARK) {
4570
- console.timeEnd("chat");
4571
- }
4572
- });
4573
- }
5371
+ [attachmentConfig.endpoint]
5372
+ );
5373
+ const {
5374
+ chat: {
5375
+ sendMessage,
5376
+ status,
5377
+ messages,
5378
+ regenerate,
5379
+ error: aiError,
5380
+ toolStatus
5381
+ },
5382
+ subagentState,
5383
+ applyChatPart,
5384
+ setMessages
5385
+ } = usePuckAiInternal({
5386
+ host,
5387
+ mode,
5388
+ apiVersion,
5389
+ prepareRequest,
5390
+ onFinish: chat?.onFinish,
5391
+ fieldTypes
4574
5392
  });
4575
- useEffect9(() => {
4576
- stopChatRef.current = stop;
4577
- return () => {
4578
- stopChatRef.current = null;
4579
- stop();
4580
- };
4581
- }, [stop]);
4582
- const statusRef = useRef9(status);
4583
- useEffect9(() => {
4584
- statusRef.current = status;
4585
- }, [status]);
4586
- useEffect9(() => {
4587
- lastStreamActivityRef.current = Date.now();
4588
- }, [messages]);
4589
- useEffect9(() => {
4590
- const FROZEN_HIDDEN_MS = 3 * 6e4;
4591
- const RESUME_GRACE_MS = 12e3;
4592
- const isStreaming = () => statusRef.current === "streaming" || statusRef.current === "submitted";
4593
- let graceTimer;
4594
- const recoverIfSevered = () => {
4595
- if (!isStreaming()) return;
4596
- if (Date.now() - lastStreamActivityRef.current < RESUME_GRACE_MS) return;
4597
- stop();
4598
- setToolStatus((current) => {
4599
- let changed = false;
4600
- const next = {};
4601
- for (const [id, toolState] of Object.entries(current)) {
4602
- if (toolState.loading) {
4603
- changed = true;
4604
- next[id] = { ...toolState, loading: false, label: "Interrupted" };
4605
- } else {
4606
- next[id] = toolState;
4607
- }
4608
- }
4609
- return changed ? next : current;
4610
- });
4611
- };
4612
- const onVisibilityChange = () => {
4613
- if (document.hidden) {
4614
- hiddenSinceRef.current = isStreaming() ? Date.now() : null;
4615
- return;
4616
- }
4617
- const hiddenSince = hiddenSinceRef.current;
4618
- hiddenSinceRef.current = null;
4619
- if (graceTimer) clearTimeout(graceTimer);
4620
- if (hiddenSince === null || Date.now() - hiddenSince < FROZEN_HIDDEN_MS) {
4621
- return;
4622
- }
4623
- lastStreamActivityRef.current = 0;
4624
- graceTimer = setTimeout(recoverIfSevered, RESUME_GRACE_MS);
4625
- };
4626
- document.addEventListener("visibilitychange", onVisibilityChange);
4627
- return () => {
4628
- document.removeEventListener("visibilitychange", onVisibilityChange);
4629
- if (graceTimer) clearTimeout(graceTimer);
4630
- };
4631
- }, [stop]);
4632
- const [forcedStatus, setForcedStatus] = useState9();
4633
- const resolvedStatus = useMemo4(
5393
+ const [forcedStatus, setForcedStatus] = useState10();
5394
+ const resolvedStatus = useMemo5(
4634
5395
  () => forcedStatus ?? status,
4635
5396
  [status, forcedStatus]
4636
5397
  );
4637
- useEffect9(() => {
5398
+ useEffect10(() => {
4638
5399
  if (!scrollTrackingId) return;
4639
5400
  dispatchScrollTrackingEvent({
4640
5401
  id: scrollTrackingId,
@@ -4647,15 +5408,19 @@ function Chat2(props) {
4647
5408
  });
4648
5409
  };
4649
5410
  }, [resolvedStatus, scrollTrackingId]);
4650
- useEffect9(() => {
5411
+ useEffect10(() => {
4651
5412
  window.__PUCK_AI = {
4652
- processData,
5413
+ processData: applyChatPart,
4653
5414
  setMessages,
4654
5415
  setStatus: setForcedStatus,
4655
- sendMessage,
5416
+ sendMessage: (message) => sendMessage(
5417
+ message.parts.filter(
5418
+ (part) => Boolean(part && part.type === "text")
5419
+ ).map((part) => part.text).join("")
5420
+ ),
4656
5421
  focus: () => inputRef?.current?.focus()
4657
5422
  };
4658
- }, [processData]);
5423
+ }, [applyChatPart]);
4659
5424
  const handleSubmit = async (prompt) => {
4660
5425
  const text = prompt.trim();
4661
5426
  const readyAttachments = composerAttachments.filter(
@@ -4679,8 +5444,7 @@ function Chat2(props) {
4679
5444
  if (!text && readyAttachments.length === 0) {
4680
5445
  return false;
4681
5446
  }
4682
- clientToolEndpointUnavailableRef.current = false;
4683
- setError("");
5447
+ setError(void 0);
4684
5448
  setUserError("");
4685
5449
  if (chat?.onSubmit) {
4686
5450
  try {
@@ -4696,13 +5460,7 @@ function Chat2(props) {
4696
5460
  }
4697
5461
  setComposerAttachments([]);
4698
5462
  removedAttachmentClientIdsRef.current.clear();
4699
- sendMessage({
4700
- role: "user",
4701
- parts: [
4702
- ...text ? [{ type: "text", text }] : [],
4703
- ...readyAttachments
4704
- ]
4705
- }).catch((e) => {
5463
+ sendMessage(text, { files: readyAttachments }).catch((e) => {
4706
5464
  console.error(e);
4707
5465
  setError("Failed to send message.");
4708
5466
  setComposerAttachments(composerAttachments);
@@ -4865,7 +5623,7 @@ function Chat2(props) {
4865
5623
  if (!target?.attachmentId) return;
4866
5624
  await deleteAttachment(target.attachmentId);
4867
5625
  };
4868
- const messagesWithStatuses = useMemo4(() => {
5626
+ const messagesWithStatuses = useMemo5(() => {
4869
5627
  return messages.map((msg) => {
4870
5628
  return {
4871
5629
  ...msg,
@@ -4930,10 +5688,9 @@ function Chat2(props) {
4930
5688
  label
4931
5689
  )
4932
5690
  ),
4933
- error,
5691
+ error: error || aiError,
4934
5692
  handleRetry: () => {
4935
- clientToolEndpointUnavailableRef.current = false;
4936
- setError("");
5693
+ setError(void 0);
4937
5694
  regenerate();
4938
5695
  },
4939
5696
  userError,
@@ -4951,105 +5708,6 @@ function Chat2(props) {
4951
5708
  }
4952
5709
  );
4953
5710
  }
4954
- function finalizeReasoningParts(parts) {
4955
- return parts.map(
4956
- (part) => part.kind === "reasoning" && part.state !== "done" ? { ...part, state: "done" } : part
4957
- );
4958
- }
4959
- function reduceSubagentEvent(current, event) {
4960
- if (event.kind === "start") {
4961
- if (current[event.toolCallId]) return current;
4962
- return {
4963
- ...current,
4964
- [event.toolCallId]: {
4965
- toolCallId: event.toolCallId,
4966
- parentToolCallId: event.parentToolCallId,
4967
- agentType: event.agentType,
4968
- depth: event.depth,
4969
- label: event.label,
4970
- state: "running",
4971
- parts: []
4972
- }
4973
- };
4974
- }
4975
- const existing = current[event.toolCallId];
4976
- if (!existing) return current;
4977
- if (event.kind === "finish") {
4978
- return {
4979
- ...current,
4980
- [event.toolCallId]: {
4981
- ...existing,
4982
- state: "done",
4983
- parts: finalizeReasoningParts(existing.parts)
4984
- }
4985
- };
4986
- }
4987
- if (event.kind === "reasoning-delta") {
4988
- const parts = [...existing.parts];
4989
- const last = parts[parts.length - 1];
4990
- if (last && last.kind === "reasoning" && last.state !== "done") {
4991
- const separator = last.blockId !== event.blockId ? "\n\n" : "";
4992
- parts[parts.length - 1] = {
4993
- ...last,
4994
- blockId: event.blockId,
4995
- text: last.text + separator + event.text
4996
- };
4997
- } else {
4998
- parts.push({
4999
- kind: "reasoning",
5000
- blockId: event.blockId,
5001
- text: event.text,
5002
- state: "streaming"
5003
- });
5004
- }
5005
- return {
5006
- ...current,
5007
- [event.toolCallId]: { ...existing, parts }
5008
- };
5009
- }
5010
- if (event.kind === "text-delta") {
5011
- const parts = finalizeReasoningParts(existing.parts);
5012
- const last = parts[parts.length - 1];
5013
- if (last && last.kind === "text" && last.blockId === event.blockId) {
5014
- parts[parts.length - 1] = { ...last, text: last.text + event.text };
5015
- } else {
5016
- parts.push({ kind: "text", blockId: event.blockId, text: event.text });
5017
- }
5018
- return {
5019
- ...current,
5020
- [event.toolCallId]: { ...existing, parts }
5021
- };
5022
- }
5023
- if (event.kind === "tool-call") {
5024
- return {
5025
- ...current,
5026
- [event.toolCallId]: {
5027
- ...existing,
5028
- parts: [
5029
- ...finalizeReasoningParts(existing.parts),
5030
- {
5031
- kind: "tool",
5032
- childToolCallId: event.childToolCallId,
5033
- toolName: event.toolName,
5034
- input: event.input
5035
- }
5036
- ]
5037
- }
5038
- };
5039
- }
5040
- if (event.kind === "tool-result") {
5041
- return {
5042
- ...current,
5043
- [event.toolCallId]: {
5044
- ...existing,
5045
- parts: existing.parts.map(
5046
- (part) => part.kind === "tool" && part.childToolCallId === event.childToolCallId ? { ...part, output: event.output } : part
5047
- )
5048
- }
5049
- };
5050
- }
5051
- return current;
5052
- }
5053
5711
  function AttachmentComposer({
5054
5712
  accept,
5055
5713
  attachments,
@@ -5058,7 +5716,7 @@ function AttachmentComposer({
5058
5716
  onChange
5059
5717
  }) {
5060
5718
  const id = useId3();
5061
- const inputId = useMemo4(() => `attachment-input-${id}`, []);
5719
+ const inputId = useMemo5(() => `attachment-input-${id}`, []);
5062
5720
  const attachLabel = useMessage("plugin-ai-prompt-attachment-attach");
5063
5721
  return /* @__PURE__ */ jsxs7("div", { className: getClassName3("attachmentControls"), children: [
5064
5722
  /* @__PURE__ */ jsx10(
@@ -5140,20 +5798,6 @@ function Placeholder({
5140
5798
  ] })
5141
5799
  ] });
5142
5800
  }
5143
- function nextFrame(cb) {
5144
- let ran = false;
5145
- const run = () => {
5146
- if (ran) return;
5147
- ran = true;
5148
- cb();
5149
- };
5150
- if (typeof document !== "undefined" && document.hidden) {
5151
- queueMicrotask(run);
5152
- return;
5153
- }
5154
- requestAnimationFrame(run);
5155
- setTimeout(run, 100);
5156
- }
5157
5801
  function isScrolledIntoView(el) {
5158
5802
  const rect = el.getBoundingClientRect();
5159
5803
  const elemTop = rect.top;
@@ -5163,7 +5807,7 @@ function isScrolledIntoView(el) {
5163
5807
 
5164
5808
  // src/components/ScrollTracking/ScrollTracking.tsx
5165
5809
  init_react_import();
5166
- import { useEffect as useEffect10, useRef as useRef10 } from "react";
5810
+ import { useEffect as useEffect11, useRef as useRef10 } from "react";
5167
5811
 
5168
5812
  // src/lib/scroll-into-view-local.ts
5169
5813
  init_react_import();
@@ -5235,7 +5879,7 @@ var ScrollTracking = ({
5235
5879
  }) => {
5236
5880
  const followedRefs = useRef10([]);
5237
5881
  const enabledRef = useRef10(false);
5238
- useEffect10(() => {
5882
+ useEffect11(() => {
5239
5883
  return subscribeToScrollTrackingEvents(({ id, enabled }) => {
5240
5884
  if (id !== trackingId) return;
5241
5885
  enabledRef.current = enabled;
@@ -5254,7 +5898,7 @@ var ScrollTracking = ({
5254
5898
  });
5255
5899
  }
5256
5900
  });
5257
- useEffect10(() => {
5901
+ useEffect11(() => {
5258
5902
  follow();
5259
5903
  }, [follow]);
5260
5904
  return children;
@@ -5262,16 +5906,16 @@ var ScrollTracking = ({
5262
5906
 
5263
5907
  // src/components/Drawer/index.tsx
5264
5908
  init_react_import();
5265
- import { createUsePuck as createUsePuck3 } from "@puckeditor/core";
5909
+ import { createUsePuck as createUsePuck4 } from "@puckeditor/core";
5266
5910
 
5267
5911
  // src/components/ManageComponents/index.tsx
5268
5912
  init_react_import();
5269
- import { useGetPuck as useGetPuck5 } from "@puckeditor/core";
5913
+ import { useGetPuck as useGetPuck6 } from "@puckeditor/core";
5270
5914
  import {
5271
5915
  Fragment as Fragment7,
5272
5916
  useCallback as useCallback8,
5273
- useEffect as useEffect13,
5274
- useState as useState12,
5917
+ useEffect as useEffect14,
5918
+ useState as useState13,
5275
5919
  useSyncExternalStore as useSyncExternalStore3
5276
5920
  } from "react";
5277
5921
 
@@ -5297,11 +5941,11 @@ import { createContext as createContext2, useContext as useContext2 } from "reac
5297
5941
 
5298
5942
  // ../platform-client/lib/use-modal-visible.ts
5299
5943
  init_react_import();
5300
- import { useEffect as useEffect11, useState as useState10, useRef as useRef11 } from "react";
5944
+ import { useEffect as useEffect12, useState as useState11, useRef as useRef11 } from "react";
5301
5945
  var useModalVisible = (defaultVisible) => {
5302
- const [visible, setVisible] = useState10(defaultVisible ?? false);
5946
+ const [visible, setVisible] = useState11(defaultVisible ?? false);
5303
5947
  const ref = useRef11(null);
5304
- useEffect11(() => {
5948
+ useEffect12(() => {
5305
5949
  if (!visible) {
5306
5950
  return;
5307
5951
  }
@@ -5323,7 +5967,7 @@ init_react_import();
5323
5967
 
5324
5968
  // ../platform-client/components/Button/Button.tsx
5325
5969
  init_react_import();
5326
- import { useEffect as useEffect12, useState as useState11 } from "react";
5970
+ import { useEffect as useEffect13, useState as useState12 } from "react";
5327
5971
 
5328
5972
  // css-module:/home/runner/work/platform/platform/packages/platform-client/components/Button/Button.module.css#css-module
5329
5973
  init_react_import();
@@ -5346,8 +5990,8 @@ var Button = ({
5346
5990
  size = "medium",
5347
5991
  loading: loadingProp = false
5348
5992
  }) => {
5349
- const [loading, setLoading] = useState11(loadingProp);
5350
- useEffect12(() => {
5993
+ const [loading, setLoading] = useState12(loadingProp);
5994
+ useEffect13(() => {
5351
5995
  const resetLoading = () => setLoading(loadingProp);
5352
5996
  resetLoading();
5353
5997
  window.addEventListener("pageshow", resetLoading);
@@ -5572,7 +6216,7 @@ var useRegistrations = () => useSyncExternalStore3(
5572
6216
  () => registrationStore.getAll()
5573
6217
  );
5574
6218
  function ManageModalContent({ onClose }) {
5575
- const getPuck = useGetPuck5();
6219
+ const getPuck = useGetPuck6();
5576
6220
  const deleteTitle = useMessage("plugin-ai-components-delete-title");
5577
6221
  const cancelLabel = useMessage("plugin-ai-components-delete-cancel");
5578
6222
  const deleteLabel = useMessage("plugin-ai-components-delete");
@@ -5580,9 +6224,9 @@ function ManageModalContent({ onClose }) {
5580
6224
  const manageTitle = useMessage("plugin-ai-components-manage");
5581
6225
  const emptyLabel = useMessage("plugin-ai-components-manage-empty");
5582
6226
  const { visible, setVisible } = useModal();
5583
- const [confirmTarget, setConfirmTarget] = useState12(null);
6227
+ const [confirmTarget, setConfirmTarget] = useState13(null);
5584
6228
  const entries = useRegistrations();
5585
- useEffect13(() => {
6229
+ useEffect14(() => {
5586
6230
  if (!visible) onClose();
5587
6231
  }, [visible, onClose]);
5588
6232
  const handleDelete = (name) => {
@@ -5636,7 +6280,7 @@ function ManageModalContent({ onClose }) {
5636
6280
  ] }) });
5637
6281
  }
5638
6282
  function ManageComponentsCta() {
5639
- const [open, setOpen] = useState12(false);
6283
+ const [open, setOpen] = useState13(false);
5640
6284
  const entries = useRegistrations();
5641
6285
  const manageLabel = useMessage("plugin-ai-components-manage");
5642
6286
  const handleClose = useCallback8(() => setOpen(false), []);
@@ -5656,10 +6300,10 @@ var styles_module_default8 = { "Drawer": "_Drawer_1mu8g_1", "Drawer--empty": "_D
5656
6300
 
5657
6301
  // src/components/Drawer/index.tsx
5658
6302
  import { jsx as jsx17, jsxs as jsxs12 } from "react/jsx-runtime";
5659
- var usePuck3 = createUsePuck3();
6303
+ var usePuck4 = createUsePuck4();
5660
6304
  var cx6 = getClassNameFactory("Drawer", styles_module_default8);
5661
6305
  var createDrawer = (designModeVisible) => function Drawer({ children }) {
5662
- const config = usePuck3((s) => s.config);
6306
+ const config = usePuck4((s) => s.config);
5663
6307
  if (Object.keys(config.components).length === 0) {
5664
6308
  return /* @__PURE__ */ jsx17("div", { className: `${cx6({ empty: true })} ${pluginThemeClassName}`, children: "No blocks" });
5665
6309
  }
@@ -5669,8 +6313,8 @@ var createDrawer = (designModeVisible) => function Drawer({ children }) {
5669
6313
  ] });
5670
6314
  };
5671
6315
 
5672
- // src/index.tsx
5673
- import { Fragment as Fragment9, jsx as jsx18 } from "react/jsx-runtime";
6316
+ // src/lib/design/with-dynamic-config.ts
6317
+ init_react_import();
5674
6318
  function withDynamicConfig(config, data) {
5675
6319
  const registrations = getPersistedRegistrations(data);
5676
6320
  const dynamicConfig = {};
@@ -5700,6 +6344,9 @@ function withDynamicConfig(config, data) {
5700
6344
  applyConfigFieldMetadata(result, dynamicConfig);
5701
6345
  return result;
5702
6346
  }
6347
+
6348
+ // src/index.tsx
6349
+ import { Fragment as Fragment9, jsx as jsx18 } from "react/jsx-runtime";
5703
6350
  function createAiPlugin(opts) {
5704
6351
  const { label = "AI", scrollTracking = true, ...rest } = opts || {};
5705
6352
  const scrollTrackingId = `puck-ai-scroll-${ulid2()}`;
@@ -5724,6 +6371,7 @@ function createAiPlugin(opts) {
5724
6371
  export {
5725
6372
  createAiPlugin,
5726
6373
  defaultDictionary,
6374
+ usePuckAi,
5727
6375
  withDynamicConfig
5728
6376
  };
5729
6377
  /*! Bundled license information: