@puckeditor/plugin-ai 0.9.0-canary.e2b15643 → 0.9.0-canary.e72fdf32

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.js CHANGED
@@ -43,37 +43,6 @@ var init_react_import = __esm({
43
43
  }
44
44
  });
45
45
 
46
- // ../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js
47
- var require_throttleit = __commonJS({
48
- "../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js"(exports2, module2) {
49
- "use strict";
50
- init_react_import();
51
- function throttle2(function_, wait) {
52
- if (typeof function_ !== "function") {
53
- throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof function_}\`.`);
54
- }
55
- let timeoutId;
56
- let lastCallTime = 0;
57
- return function throttled(...arguments_) {
58
- clearTimeout(timeoutId);
59
- const now = Date.now();
60
- const timeSinceLastCall = now - lastCallTime;
61
- const delayForNextCall = wait - timeSinceLastCall;
62
- if (delayForNextCall <= 0) {
63
- lastCallTime = now;
64
- function_.apply(this, arguments_);
65
- } else {
66
- timeoutId = setTimeout(() => {
67
- lastCallTime = Date.now();
68
- function_.apply(this, arguments_);
69
- }, delayForNextCall);
70
- }
71
- };
72
- }
73
- module2.exports = throttle2;
74
- }
75
- });
76
-
77
46
  // ../../node_modules/.pnpm/classnames@2.5.1/node_modules/classnames/index.js
78
47
  var require_classnames = __commonJS({
79
48
  "../../node_modules/.pnpm/classnames@2.5.1/node_modules/classnames/index.js"(exports2, module2) {
@@ -136,6 +105,37 @@ var require_classnames = __commonJS({
136
105
  }
137
106
  });
138
107
 
108
+ // ../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js
109
+ var require_throttleit = __commonJS({
110
+ "../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js"(exports2, module2) {
111
+ "use strict";
112
+ init_react_import();
113
+ function throttle2(function_, wait) {
114
+ if (typeof function_ !== "function") {
115
+ throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof function_}\`.`);
116
+ }
117
+ let timeoutId;
118
+ let lastCallTime = 0;
119
+ return function throttled(...arguments_) {
120
+ clearTimeout(timeoutId);
121
+ const now = Date.now();
122
+ const timeSinceLastCall = now - lastCallTime;
123
+ const delayForNextCall = wait - timeSinceLastCall;
124
+ if (delayForNextCall <= 0) {
125
+ lastCallTime = now;
126
+ function_.apply(this, arguments_);
127
+ } else {
128
+ timeoutId = setTimeout(() => {
129
+ lastCallTime = Date.now();
130
+ function_.apply(this, arguments_);
131
+ }, delayForNextCall);
132
+ }
133
+ };
134
+ }
135
+ module2.exports = throttle2;
136
+ }
137
+ });
138
+
139
139
  // ../reducer/dist/index.js
140
140
  var require_dist = __commonJS({
141
141
  "../reducer/dist/index.js"(exports2, module2) {
@@ -405,6 +405,7 @@ var index_exports = {};
405
405
  __export(index_exports, {
406
406
  createAiPlugin: () => createAiPlugin,
407
407
  defaultDictionary: () => defaultDictionary,
408
+ usePuckAi: () => usePuckAi,
408
409
  withDynamicConfig: () => withDynamicConfig
409
410
  });
410
411
  module.exports = __toCommonJS(index_exports);
@@ -742,519 +743,265 @@ var import_ulid2 = require("ulid");
742
743
 
743
744
  // src/components/Chat/index.tsx
744
745
  init_react_import();
746
+ var import_core6 = require("@puckeditor/core");
747
+ var import_react18 = require("react");
748
+
749
+ // ../platform-client/lib/get-class-name-factory.ts
750
+ init_react_import();
751
+ var import_classnames = __toESM(require_classnames());
752
+ var getClassNameFactory = (rootClass, styles, { baseClass = "" } = {}) => (options = {}) => {
753
+ let descendant = false;
754
+ let modifiers = false;
755
+ if (typeof options === "string") {
756
+ descendant = options;
757
+ } else if (typeof options === "object") {
758
+ modifiers = options;
759
+ }
760
+ if (descendant) {
761
+ const style = styles[`${rootClass}-${descendant}`];
762
+ if (style) {
763
+ return baseClass + styles[`${rootClass}-${descendant}`] || "";
764
+ }
765
+ return "";
766
+ } else if (modifiers) {
767
+ const prefixedModifiers = {};
768
+ for (let modifier in modifiers) {
769
+ prefixedModifiers[styles[`${rootClass}--${modifier}`]] = modifiers[modifier];
770
+ }
771
+ const c = styles[rootClass];
772
+ return baseClass + (0, import_classnames.default)({
773
+ [c]: !!c,
774
+ // only apply the class if it exists
775
+ ...prefixedModifiers
776
+ });
777
+ } else {
778
+ return baseClass + styles[rootClass] || "";
779
+ }
780
+ };
781
+ var get_class_name_factory_default = getClassNameFactory;
782
+
783
+ // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/Chat/styles.module.css#css-module
784
+ init_react_import();
785
+ var styles_module_default = { "Chat": "_Chat_gflib_1", "Chat-header": "_Chat-header_gflib_9", "Chat-placeholder": "_Chat-placeholder_gflib_24", "Chat-placeholderIcon": "_Chat-placeholderIcon_gflib_43", "Chat-placeholderTitle": "_Chat-placeholderTitle_gflib_57", "Chat-placeholderDescription": "_Chat-placeholderDescription_gflib_62", "Chat-actions": "_Chat-actions_gflib_68", "Chat-action": "_Chat-action_gflib_68", "Chat-actionOutlined": "_Chat-actionOutlined_gflib_77", "Chat-attachmentControls": "_Chat-attachmentControls_gflib_140", "Chat-attachmentInput": "_Chat-attachmentInput_gflib_147", "Chat-attachmentButton": "_Chat-attachmentButton_gflib_151" };
745
786
 
746
- // ../../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
787
+ // src/components/ChatBody/index.tsx
788
+ init_react_import();
789
+ var import_react8 = require("react");
790
+ var import_use_stick_to_bottom = require("use-stick-to-bottom");
791
+ var import_react_markdown = __toESM(require("react-markdown"));
792
+
793
+ // ../platform-client/components/IconButton/index.ts
794
+ init_react_import();
795
+
796
+ // ../platform-client/components/IconButton/IconButton.tsx
747
797
  init_react_import();
748
- var import_ai = require("ai");
749
798
  var import_react4 = require("react");
750
- var import_ai2 = require("ai");
751
- var import_throttleit = __toESM(require_throttleit(), 1);
752
- var import_ai3 = require("ai");
753
- var import_react5 = require("react");
754
- var import_ai4 = require("ai");
755
- var import_react6 = require("react");
756
- var __accessCheck = (obj, member, msg) => {
757
- if (!member.has(obj))
758
- throw TypeError("Cannot " + msg);
759
- };
760
- var __privateGet = (obj, member, getter) => {
761
- __accessCheck(obj, member, "read from private field");
762
- return getter ? getter.call(obj) : member.get(obj);
799
+
800
+ // css-module:/home/runner/work/platform/platform/packages/platform-client/components/IconButton/IconButton.module.css#css-module
801
+ init_react_import();
802
+ var IconButton_module_default = { "IconButton": "_IconButton_voaix_1", "IconButton--disabled": "_IconButton--disabled_voaix_30", "IconButton--dark": "_IconButton--dark_voaix_40", "IconButton-title": "_IconButton-title_voaix_61" };
803
+
804
+ // ../platform-client/components/Loader/index.tsx
805
+ init_react_import();
806
+
807
+ // ../platform-client/lib/index.ts
808
+ init_react_import();
809
+
810
+ // css-module:/home/runner/work/platform/platform/packages/platform-client/components/Loader/styles.module.css#css-module
811
+ init_react_import();
812
+ var styles_module_default2 = { "Loader": "_Loader_68nru_13", "loader-animation": "_loader-animation_68nru_1" };
813
+
814
+ // ../platform-client/components/Loader/index.tsx
815
+ var import_jsx_runtime = require("react/jsx-runtime");
816
+ var getClassName = getClassNameFactory("Loader", styles_module_default2);
817
+ var Loader = ({
818
+ color,
819
+ label = "loading",
820
+ size = 16,
821
+ ...props
822
+ }) => {
823
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
824
+ "span",
825
+ {
826
+ className: getClassName(),
827
+ style: {
828
+ width: size,
829
+ height: size,
830
+ color
831
+ },
832
+ "aria-label": label,
833
+ ...props
834
+ }
835
+ );
763
836
  };
764
- var __privateAdd = (obj, member, value) => {
765
- if (member.has(obj))
766
- throw TypeError("Cannot add the same private member more than once");
767
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
837
+
838
+ // ../platform-client/components/IconButton/IconButton.tsx
839
+ var import_jsx_runtime2 = require("react/jsx-runtime");
840
+ var getClassName2 = get_class_name_factory_default("IconButton", IconButton_module_default);
841
+ var IconButton = ({
842
+ children,
843
+ href,
844
+ onClick,
845
+ variant = "primary",
846
+ type,
847
+ disabled,
848
+ tabIndex,
849
+ newTab,
850
+ fullWidth,
851
+ title,
852
+ dark
853
+ }) => {
854
+ const [loading, setLoading] = (0, import_react4.useState)(false);
855
+ const ElementType = href ? "a" : onClick ? "button" : "div";
856
+ const el = /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
857
+ ElementType,
858
+ {
859
+ className: getClassName2({
860
+ primary: variant === "primary",
861
+ secondary: variant === "secondary",
862
+ disabled,
863
+ fullWidth,
864
+ dark
865
+ }),
866
+ onClick: (e) => {
867
+ if (!onClick) return;
868
+ setLoading(true);
869
+ Promise.resolve(onClick(e)).then(() => {
870
+ setLoading(false);
871
+ });
872
+ },
873
+ type,
874
+ disabled: disabled || loading,
875
+ tabIndex,
876
+ target: newTab ? "_blank" : void 0,
877
+ rel: newTab ? "noreferrer" : void 0,
878
+ href,
879
+ title,
880
+ children: [
881
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: getClassName2("title"), children: title }),
882
+ children,
883
+ loading && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
884
+ "\xA0\xA0",
885
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Loader, { size: 14 })
886
+ ] })
887
+ ]
888
+ }
889
+ );
890
+ return el;
768
891
  };
769
- var __privateSet = (obj, member, value, setter) => {
770
- __accessCheck(obj, member, "write to private field");
771
- setter ? setter.call(obj, value) : member.set(obj, value);
772
- return value;
892
+
893
+ // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/ChatBody/styles.module.css#css-module
894
+ init_react_import();
895
+ var styles_module_default3 = { "Chat": "_Chat_epa47_1", "Chat--hasMessages": "_Chat--hasMessages_epa47_23", "Chat-inner": "_Chat-inner_epa47_34", "Chat--hasChildren": "_Chat--hasChildren_epa47_46", "Chat-body": "_Chat-body_epa47_51", "Chat--isLoading": "_Chat--isLoading_epa47_58", "Chat-messages": "_Chat-messages_epa47_62", "Chat-form": "_Chat-form_epa47_69", "Chat--hideInput": "_Chat--hideInput_epa47_74", "Chat-formHelper": "_Chat-formHelper_epa47_88", "Chat-examplePrompts": "_Chat-examplePrompts_epa47_104", "Chat-examplePrompt": "_Chat-examplePrompt_epa47_104", "Chat-examplePromptArrow": "_Chat-examplePromptArrow_epa47_145", "Chat-default": "_Chat-default_epa47_150", "ChatMessage": "_ChatMessage_epa47_167", "ChatMessage--userRole": "_ChatMessage--userRole_epa47_176", "ChatMessage-userBubble": "_ChatMessage-userBubble_epa47_176", "ChatMessage-userAttachments": "_ChatMessage-userAttachments_epa47_187", "ChatMessage-thumbnail": "_ChatMessage-thumbnail_epa47_193", "ChatMessage-thumbnailLabel": "_ChatMessage-thumbnailLabel_epa47_224", "ChatMessage-text": "_ChatMessage-text_epa47_298", "ChatMessage-event": "_ChatMessage-event_epa47_334", "ChatMessage-eventBody": "_ChatMessage-eventBody_epa47_338", "ChatMessage-eventCollapse": "_ChatMessage-eventCollapse_epa47_347", "ChatMessage-eventHeader": "_ChatMessage-eventHeader_epa47_351", "ChatMessage-eventExpand": "_ChatMessage-eventExpand_epa47_351", "ChatMessage-eventHeader--static": "_ChatMessage-eventHeader--static_epa47_377", "ChatMessage-eventIcon": "_ChatMessage-eventIcon_epa47_383", "ChatMessage-eventLabel": "_ChatMessage-eventLabel_epa47_387", "ChatMessage-attachmentImage": "_ChatMessage-attachmentImage_epa47_401", "ChatMessage-attachmentFile": "_ChatMessage-attachmentFile_epa47_419", "Chat-loader": "_Chat-loader_epa47_443", "Chat-loaderIcon": "_Chat-loaderIcon_epa47_453", "Chat-error": "_Chat-error_epa47_457", "Chat-errorLabel": "_Chat-errorLabel_epa47_466", "Chat-errorAction": "_Chat-errorAction_epa47_470", "Chat-userError": "_Chat-userError_epa47_474", "Chat-userErrorDismiss": "_Chat-userErrorDismiss_epa47_484" };
896
+
897
+ // src/components/PromptForm/index.tsx
898
+ init_react_import();
899
+ var import_react5 = require("react");
900
+
901
+ // ../platform-client/components/Textarea/index.tsx
902
+ init_react_import();
903
+ var import_react_textarea_autosize = __toESM(require("react-textarea-autosize"));
904
+
905
+ // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/PromptForm/styles.module.css#css-module
906
+ init_react_import();
907
+ var styles_module_default4 = { "PromptForm": "_PromptForm_1p0vz_1", "PromptForm-dropOverlay": "_PromptForm-dropOverlay_1p0vz_15", "PromptForm-inner": "_PromptForm-inner_1p0vz_43", "PromptForm--glow": "_PromptForm--glow_1p0vz_52", "PromptForm-glow": "_PromptForm-glow_1p0vz_52", "loop": "_loop_1p0vz_1", "PromptForm-formInner": "_PromptForm-formInner_1p0vz_85", "PromptForm-input": "_PromptForm-input_1p0vz_94", "PromptForm--isDisabled": "_PromptForm--isDisabled_1p0vz_133", "PromptForm-helper": "_PromptForm-helper_1p0vz_152", "PromptForm-actions": "_PromptForm-actions_1p0vz_162", "PromptForm-actionsLeft": "_PromptForm-actionsLeft_1p0vz_173", "PromptForm-actionsRight": "_PromptForm-actionsRight_1p0vz_182", "PromptForm-actionSubmit": "_PromptForm-actionSubmit_1p0vz_187", "PromptForm--userCta": "_PromptForm--userCta_1p0vz_211", "PromptForm--isLoading": "_PromptForm--isLoading_1p0vz_241", "PromptForm-attachments": "_PromptForm-attachments_1p0vz_247", "PromptForm-attachmentChip": "_PromptForm-attachmentChip_1p0vz_255", "PromptForm-attachmentChipUploading": "_PromptForm-attachmentChipUploading_1p0vz_271", "PromptForm-attachmentChipFailed": "_PromptForm-attachmentChipFailed_1p0vz_275", "PromptForm-attachmentError": "_PromptForm-attachmentError_1p0vz_280", "PromptForm-attachmentSpinner": "_PromptForm-attachmentSpinner_1p0vz_285", "PromptForm-attachmentSpin": "_PromptForm-attachmentSpin_1p0vz_285", "PromptForm-attachmentRemove": "_PromptForm-attachmentRemove_1p0vz_289" };
908
+
909
+ // src/lib/attachments.ts
910
+ init_react_import();
911
+ var INTERNAL_MESSAGE_PREFIX = "[puck-internal";
912
+ var defaultAttachmentAccept = [
913
+ "image/*",
914
+ ".pdf",
915
+ ".doc",
916
+ ".docx",
917
+ ".txt",
918
+ ".md"
919
+ ];
920
+ var defaultAttachmentConfig = {
921
+ maxFiles: 5,
922
+ maxSizeBytes: 10 * 1024 * 1024
773
923
  };
774
- function throttle(fn, waitMs) {
775
- return waitMs != null ? (0, import_throttleit.default)(fn, waitMs) : fn;
776
- }
777
- var _messages;
778
- var _status;
779
- var _error;
780
- var _messagesCallbacks;
781
- var _statusCallbacks;
782
- var _errorCallbacks;
783
- var _callMessagesCallbacks;
784
- var _callStatusCallbacks;
785
- var _callErrorCallbacks;
786
- var ReactChatState = class {
787
- constructor(initialMessages = []) {
788
- __privateAdd(this, _messages, void 0);
789
- __privateAdd(this, _status, "ready");
790
- __privateAdd(this, _error, void 0);
791
- __privateAdd(this, _messagesCallbacks, /* @__PURE__ */ new Set());
792
- __privateAdd(this, _statusCallbacks, /* @__PURE__ */ new Set());
793
- __privateAdd(this, _errorCallbacks, /* @__PURE__ */ new Set());
794
- this.pushMessage = (message) => {
795
- __privateSet(this, _messages, __privateGet(this, _messages).concat(message));
796
- __privateGet(this, _callMessagesCallbacks).call(this);
797
- };
798
- this.popMessage = () => {
799
- __privateSet(this, _messages, __privateGet(this, _messages).slice(0, -1));
800
- __privateGet(this, _callMessagesCallbacks).call(this);
801
- };
802
- this.replaceMessage = (index, message) => {
803
- __privateSet(this, _messages, [
804
- ...__privateGet(this, _messages).slice(0, index),
805
- // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:
806
- this.snapshot(message),
807
- ...__privateGet(this, _messages).slice(index + 1)
808
- ]);
809
- __privateGet(this, _callMessagesCallbacks).call(this);
810
- };
811
- this.snapshot = (value) => structuredClone(value);
812
- this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => {
813
- const callback = throttleWaitMs ? throttle(onChange, throttleWaitMs) : onChange;
814
- __privateGet(this, _messagesCallbacks).add(callback);
815
- return () => {
816
- __privateGet(this, _messagesCallbacks).delete(callback);
817
- };
818
- };
819
- this["~registerStatusCallback"] = (onChange) => {
820
- __privateGet(this, _statusCallbacks).add(onChange);
821
- return () => {
822
- __privateGet(this, _statusCallbacks).delete(onChange);
823
- };
824
- };
825
- this["~registerErrorCallback"] = (onChange) => {
826
- __privateGet(this, _errorCallbacks).add(onChange);
827
- return () => {
828
- __privateGet(this, _errorCallbacks).delete(onChange);
829
- };
830
- };
831
- __privateAdd(this, _callMessagesCallbacks, () => {
832
- __privateGet(this, _messagesCallbacks).forEach((callback) => callback());
833
- });
834
- __privateAdd(this, _callStatusCallbacks, () => {
835
- __privateGet(this, _statusCallbacks).forEach((callback) => callback());
836
- });
837
- __privateAdd(this, _callErrorCallbacks, () => {
838
- __privateGet(this, _errorCallbacks).forEach((callback) => callback());
839
- });
840
- __privateSet(this, _messages, initialMessages);
924
+ var getExtension = (filename) => {
925
+ const parts = filename.toLowerCase().split(".");
926
+ if (parts.length < 2) {
927
+ return null;
841
928
  }
842
- get status() {
843
- return __privateGet(this, _status);
929
+ return `.${parts.pop()}`;
930
+ };
931
+ var matchesAccept = (file, accept) => {
932
+ if (accept.length === 0) {
933
+ return true;
844
934
  }
845
- set status(newStatus) {
846
- __privateSet(this, _status, newStatus);
847
- __privateGet(this, _callStatusCallbacks).call(this);
935
+ const extension = getExtension(file.name);
936
+ return accept.some((entry) => {
937
+ if (entry.endsWith("/*")) {
938
+ const prefix = entry.slice(0, -1);
939
+ return file.type.startsWith(prefix);
940
+ }
941
+ if (entry.startsWith(".")) {
942
+ return extension === entry.toLowerCase();
943
+ }
944
+ return file.type === entry;
945
+ });
946
+ };
947
+ var documentExtensionByMediaType = {
948
+ "application/msword": "doc",
949
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
950
+ "text/markdown": "md",
951
+ "application/pdf": "pdf",
952
+ "text/plain": "txt"
953
+ };
954
+ var mediaTypeToExtension = (mediaType) => {
955
+ const mapped = documentExtensionByMediaType[mediaType];
956
+ if (mapped) {
957
+ return mapped;
848
958
  }
849
- get error() {
850
- return __privateGet(this, _error);
959
+ const subtype = mediaType.split("/")[1] ?? "";
960
+ return subtype.split("+")[0] || "bin";
961
+ };
962
+ var getFilesFromClipboard = (data) => {
963
+ const files = [];
964
+ for (const item of data.items ? Array.from(data.items) : []) {
965
+ if (item.kind === "file") {
966
+ const file = item.getAsFile();
967
+ if (file) {
968
+ files.push(file);
969
+ }
970
+ }
851
971
  }
852
- set error(newError) {
853
- __privateSet(this, _error, newError);
854
- __privateGet(this, _callErrorCallbacks).call(this);
972
+ if (files.length === 0 && data.files) {
973
+ files.push(...Array.from(data.files));
855
974
  }
856
- get messages() {
857
- return __privateGet(this, _messages);
975
+ return files.map(
976
+ (file, index) => file.name ? file : new File(
977
+ [file],
978
+ `pasted-${Date.now()}-${index}.${mediaTypeToExtension(file.type)}`,
979
+ { type: file.type }
980
+ )
981
+ );
982
+ };
983
+ var getAttachmentIdFromRef = (url) => url.startsWith("attachment://") ? url.slice("attachment://".length) : null;
984
+ var resolveAttachmentUrl = (url, attachmentEndpoint) => {
985
+ if (!attachmentEndpoint) {
986
+ return url;
858
987
  }
859
- set messages(newMessages) {
860
- __privateSet(this, _messages, [...newMessages]);
861
- __privateGet(this, _callMessagesCallbacks).call(this);
988
+ const attachmentId = getAttachmentIdFromRef(url);
989
+ if (!attachmentId) {
990
+ return url;
862
991
  }
992
+ return `${attachmentEndpoint.replace(/\/$/, "")}/${attachmentId}`;
863
993
  };
864
- _messages = /* @__PURE__ */ new WeakMap();
865
- _status = /* @__PURE__ */ new WeakMap();
866
- _error = /* @__PURE__ */ new WeakMap();
867
- _messagesCallbacks = /* @__PURE__ */ new WeakMap();
868
- _statusCallbacks = /* @__PURE__ */ new WeakMap();
869
- _errorCallbacks = /* @__PURE__ */ new WeakMap();
870
- _callMessagesCallbacks = /* @__PURE__ */ new WeakMap();
871
- _callStatusCallbacks = /* @__PURE__ */ new WeakMap();
872
- _callErrorCallbacks = /* @__PURE__ */ new WeakMap();
873
- var _state;
874
- var Chat = class extends import_ai2.AbstractChat {
875
- constructor({ messages, ...init }) {
876
- const state = new ReactChatState(messages);
877
- super({ ...init, state });
878
- __privateAdd(this, _state, void 0);
879
- this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => __privateGet(this, _state)["~registerMessagesCallback"](onChange, throttleWaitMs);
880
- this["~registerStatusCallback"] = (onChange) => __privateGet(this, _state)["~registerStatusCallback"](onChange);
881
- this["~registerErrorCallback"] = (onChange) => __privateGet(this, _state)["~registerErrorCallback"](onChange);
882
- __privateSet(this, _state, state);
994
+ var fetchAttachmentUrl = async (endpoint, signal) => {
995
+ const response = await fetch(endpoint, { redirect: "manual", signal });
996
+ if (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) {
997
+ return endpoint;
883
998
  }
884
- };
885
- _state = /* @__PURE__ */ new WeakMap();
886
- function useChat({
887
- experimental_throttle: throttleWaitMs,
888
- resume = false,
889
- ...options
890
- } = {}) {
891
- const latestRef = (0, import_react4.useRef)({});
892
- if (!("chat" in options)) {
893
- latestRef.current = {
894
- onToolCall: options.onToolCall,
895
- onData: options.onData,
896
- onFinish: options.onFinish,
897
- onError: options.onError,
898
- sendAutomaticallyWhen: options.sendAutomaticallyWhen,
899
- transport: options.transport
900
- };
999
+ if (!response.ok) {
1000
+ throw new Error(`Attachment URL request failed with ${response.status}`);
901
1001
  }
902
- let defaultTransport;
903
- const getTransport = () => {
904
- var _a;
905
- return (_a = latestRef.current.transport) != null ? _a : defaultTransport != null ? defaultTransport : defaultTransport = new import_ai.DefaultChatTransport();
906
- };
907
- const chatOptions = {
908
- ...options,
909
- transport: {
910
- sendMessages: (sendOptions) => getTransport().sendMessages(sendOptions),
911
- reconnectToStream: (reconnectOptions) => getTransport().reconnectToStream(reconnectOptions)
912
- },
913
- onToolCall: (arg) => {
914
- var _a, _b;
915
- return (_b = (_a = latestRef.current).onToolCall) == null ? void 0 : _b.call(_a, arg);
916
- },
917
- onData: (arg) => {
918
- var _a, _b;
919
- return (_b = (_a = latestRef.current).onData) == null ? void 0 : _b.call(_a, arg);
920
- },
921
- onFinish: (arg) => {
922
- var _a, _b;
923
- return (_b = (_a = latestRef.current).onFinish) == null ? void 0 : _b.call(_a, arg);
924
- },
925
- onError: (arg) => {
926
- var _a, _b;
927
- return (_b = (_a = latestRef.current).onError) == null ? void 0 : _b.call(_a, arg);
928
- },
929
- sendAutomaticallyWhen: (arg) => {
930
- var _a, _b, _c;
931
- return (_c = (_b = (_a = latestRef.current).sendAutomaticallyWhen) == null ? void 0 : _b.call(_a, arg)) != null ? _c : false;
932
- }
933
- };
934
- const chatRef = (0, import_react4.useRef)(
935
- "chat" in options ? options.chat : new Chat(chatOptions)
936
- );
937
- const shouldRecreateChat = "chat" in options && options.chat !== chatRef.current || "id" in options && options.id != null && chatRef.current.id !== options.id;
938
- if (shouldRecreateChat) {
939
- chatRef.current = "chat" in options ? options.chat : new Chat(chatOptions);
940
- }
941
- const subscribeToMessages = (0, import_react4.useCallback)(
942
- (update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs),
943
- // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
944
- // eslint-disable-next-line react-hooks/exhaustive-deps
945
- [throttleWaitMs, chatRef.current.id]
946
- );
947
- const messages = (0, import_react4.useSyncExternalStore)(
948
- subscribeToMessages,
949
- () => chatRef.current.messages,
950
- () => chatRef.current.messages
951
- );
952
- const status = (0, import_react4.useSyncExternalStore)(
953
- chatRef.current["~registerStatusCallback"],
954
- () => chatRef.current.status,
955
- () => chatRef.current.status
956
- );
957
- const error = (0, import_react4.useSyncExternalStore)(
958
- chatRef.current["~registerErrorCallback"],
959
- () => chatRef.current.error,
960
- () => chatRef.current.error
961
- );
962
- const setMessages = (0, import_react4.useCallback)(
963
- (messagesParam) => {
964
- if (typeof messagesParam === "function") {
965
- messagesParam = messagesParam(chatRef.current.messages);
966
- }
967
- chatRef.current.messages = messagesParam;
968
- },
969
- [chatRef]
970
- );
971
- (0, import_react4.useEffect)(() => {
972
- if (resume) {
973
- chatRef.current.resumeStream();
974
- }
975
- }, [resume, chatRef]);
976
- return {
977
- id: chatRef.current.id,
978
- messages,
979
- setMessages,
980
- sendMessage: chatRef.current.sendMessage,
981
- regenerate: chatRef.current.regenerate,
982
- clearError: chatRef.current.clearError,
983
- stop: chatRef.current.stop,
984
- error,
985
- resumeStream: chatRef.current.resumeStream,
986
- status,
987
- /**
988
- * @deprecated Use `addToolOutput` instead.
989
- */
990
- addToolResult: chatRef.current.addToolOutput,
991
- addToolOutput: chatRef.current.addToolOutput,
992
- addToolApprovalResponse: chatRef.current.addToolApprovalResponse
993
- };
994
- }
995
-
996
- // src/components/Chat/index.tsx
997
- var import_core5 = require("@puckeditor/core");
998
- var import_ai5 = require("ai");
999
- var import_react17 = require("react");
1000
- var import_ulid = require("ulid");
1001
-
1002
- // ../platform-client/lib/get-class-name-factory.ts
1003
- init_react_import();
1004
- var import_classnames = __toESM(require_classnames());
1005
- var getClassNameFactory = (rootClass, styles, { baseClass = "" } = {}) => (options = {}) => {
1006
- let descendant = false;
1007
- let modifiers = false;
1008
- if (typeof options === "string") {
1009
- descendant = options;
1010
- } else if (typeof options === "object") {
1011
- modifiers = options;
1012
- }
1013
- if (descendant) {
1014
- const style = styles[`${rootClass}-${descendant}`];
1015
- if (style) {
1016
- return baseClass + styles[`${rootClass}-${descendant}`] || "";
1017
- }
1018
- return "";
1019
- } else if (modifiers) {
1020
- const prefixedModifiers = {};
1021
- for (let modifier in modifiers) {
1022
- prefixedModifiers[styles[`${rootClass}--${modifier}`]] = modifiers[modifier];
1023
- }
1024
- const c = styles[rootClass];
1025
- return baseClass + (0, import_classnames.default)({
1026
- [c]: !!c,
1027
- // only apply the class if it exists
1028
- ...prefixedModifiers
1029
- });
1030
- } else {
1031
- return baseClass + styles[rootClass] || "";
1032
- }
1033
- };
1034
- var get_class_name_factory_default = getClassNameFactory;
1035
-
1036
- // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/Chat/styles.module.css#css-module
1037
- init_react_import();
1038
- var styles_module_default = { "Chat": "_Chat_gflib_1", "Chat-header": "_Chat-header_gflib_9", "Chat-placeholder": "_Chat-placeholder_gflib_24", "Chat-placeholderIcon": "_Chat-placeholderIcon_gflib_43", "Chat-placeholderTitle": "_Chat-placeholderTitle_gflib_57", "Chat-placeholderDescription": "_Chat-placeholderDescription_gflib_62", "Chat-actions": "_Chat-actions_gflib_68", "Chat-action": "_Chat-action_gflib_68", "Chat-actionOutlined": "_Chat-actionOutlined_gflib_77", "Chat-attachmentControls": "_Chat-attachmentControls_gflib_140", "Chat-attachmentInput": "_Chat-attachmentInput_gflib_147", "Chat-attachmentButton": "_Chat-attachmentButton_gflib_151" };
1039
-
1040
- // src/components/ChatBody/index.tsx
1041
- init_react_import();
1042
- var import_react11 = require("react");
1043
- var import_use_stick_to_bottom = require("use-stick-to-bottom");
1044
- var import_react_markdown = __toESM(require("react-markdown"));
1045
-
1046
- // ../platform-client/components/IconButton/index.ts
1047
- init_react_import();
1048
-
1049
- // ../platform-client/components/IconButton/IconButton.tsx
1050
- init_react_import();
1051
- var import_react7 = require("react");
1052
-
1053
- // css-module:/home/runner/work/platform/platform/packages/platform-client/components/IconButton/IconButton.module.css#css-module
1054
- init_react_import();
1055
- var IconButton_module_default = { "IconButton": "_IconButton_voaix_1", "IconButton--disabled": "_IconButton--disabled_voaix_30", "IconButton--dark": "_IconButton--dark_voaix_40", "IconButton-title": "_IconButton-title_voaix_61" };
1056
-
1057
- // ../platform-client/components/Loader/index.tsx
1058
- init_react_import();
1059
-
1060
- // ../platform-client/lib/index.ts
1061
- init_react_import();
1062
-
1063
- // css-module:/home/runner/work/platform/platform/packages/platform-client/components/Loader/styles.module.css#css-module
1064
- init_react_import();
1065
- var styles_module_default2 = { "Loader": "_Loader_68nru_13", "loader-animation": "_loader-animation_68nru_1" };
1066
-
1067
- // ../platform-client/components/Loader/index.tsx
1068
- var import_jsx_runtime = require("react/jsx-runtime");
1069
- var getClassName = getClassNameFactory("Loader", styles_module_default2);
1070
- var Loader = ({
1071
- color,
1072
- label = "loading",
1073
- size = 16,
1074
- ...props
1075
- }) => {
1076
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1077
- "span",
1078
- {
1079
- className: getClassName(),
1080
- style: {
1081
- width: size,
1082
- height: size,
1083
- color
1084
- },
1085
- "aria-label": label,
1086
- ...props
1087
- }
1088
- );
1089
- };
1090
-
1091
- // ../platform-client/components/IconButton/IconButton.tsx
1092
- var import_jsx_runtime2 = require("react/jsx-runtime");
1093
- var getClassName2 = get_class_name_factory_default("IconButton", IconButton_module_default);
1094
- var IconButton = ({
1095
- children,
1096
- href,
1097
- onClick,
1098
- variant = "primary",
1099
- type,
1100
- disabled,
1101
- tabIndex,
1102
- newTab,
1103
- fullWidth,
1104
- title,
1105
- dark
1106
- }) => {
1107
- const [loading, setLoading] = (0, import_react7.useState)(false);
1108
- const ElementType = href ? "a" : onClick ? "button" : "div";
1109
- const el = /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1110
- ElementType,
1111
- {
1112
- className: getClassName2({
1113
- primary: variant === "primary",
1114
- secondary: variant === "secondary",
1115
- disabled,
1116
- fullWidth,
1117
- dark
1118
- }),
1119
- onClick: (e) => {
1120
- if (!onClick) return;
1121
- setLoading(true);
1122
- Promise.resolve(onClick(e)).then(() => {
1123
- setLoading(false);
1124
- });
1125
- },
1126
- type,
1127
- disabled: disabled || loading,
1128
- tabIndex,
1129
- target: newTab ? "_blank" : void 0,
1130
- rel: newTab ? "noreferrer" : void 0,
1131
- href,
1132
- title,
1133
- children: [
1134
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: getClassName2("title"), children: title }),
1135
- children,
1136
- loading && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
1137
- "\xA0\xA0",
1138
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Loader, { size: 14 })
1139
- ] })
1140
- ]
1141
- }
1142
- );
1143
- return el;
1144
- };
1145
-
1146
- // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/ChatBody/styles.module.css#css-module
1147
- init_react_import();
1148
- var styles_module_default3 = { "Chat": "_Chat_epa47_1", "Chat--hasMessages": "_Chat--hasMessages_epa47_23", "Chat-inner": "_Chat-inner_epa47_34", "Chat--hasChildren": "_Chat--hasChildren_epa47_46", "Chat-body": "_Chat-body_epa47_51", "Chat--isLoading": "_Chat--isLoading_epa47_58", "Chat-messages": "_Chat-messages_epa47_62", "Chat-form": "_Chat-form_epa47_69", "Chat--hideInput": "_Chat--hideInput_epa47_74", "Chat-formHelper": "_Chat-formHelper_epa47_88", "Chat-examplePrompts": "_Chat-examplePrompts_epa47_104", "Chat-examplePrompt": "_Chat-examplePrompt_epa47_104", "Chat-examplePromptArrow": "_Chat-examplePromptArrow_epa47_145", "Chat-default": "_Chat-default_epa47_150", "ChatMessage": "_ChatMessage_epa47_167", "ChatMessage--userRole": "_ChatMessage--userRole_epa47_176", "ChatMessage-userBubble": "_ChatMessage-userBubble_epa47_176", "ChatMessage-userAttachments": "_ChatMessage-userAttachments_epa47_187", "ChatMessage-thumbnail": "_ChatMessage-thumbnail_epa47_193", "ChatMessage-thumbnailLabel": "_ChatMessage-thumbnailLabel_epa47_224", "ChatMessage-text": "_ChatMessage-text_epa47_298", "ChatMessage-event": "_ChatMessage-event_epa47_334", "ChatMessage-eventBody": "_ChatMessage-eventBody_epa47_338", "ChatMessage-eventCollapse": "_ChatMessage-eventCollapse_epa47_347", "ChatMessage-eventHeader": "_ChatMessage-eventHeader_epa47_351", "ChatMessage-eventExpand": "_ChatMessage-eventExpand_epa47_351", "ChatMessage-eventHeader--static": "_ChatMessage-eventHeader--static_epa47_377", "ChatMessage-eventIcon": "_ChatMessage-eventIcon_epa47_383", "ChatMessage-eventLabel": "_ChatMessage-eventLabel_epa47_387", "ChatMessage-attachmentImage": "_ChatMessage-attachmentImage_epa47_401", "ChatMessage-attachmentFile": "_ChatMessage-attachmentFile_epa47_419", "Chat-loader": "_Chat-loader_epa47_443", "Chat-loaderIcon": "_Chat-loaderIcon_epa47_453", "Chat-error": "_Chat-error_epa47_457", "Chat-errorLabel": "_Chat-errorLabel_epa47_466", "Chat-errorAction": "_Chat-errorAction_epa47_470", "Chat-userError": "_Chat-userError_epa47_474", "Chat-userErrorDismiss": "_Chat-userErrorDismiss_epa47_484" };
1149
-
1150
- // src/components/PromptForm/index.tsx
1151
- init_react_import();
1152
- var import_react8 = require("react");
1153
-
1154
- // ../platform-client/components/Textarea/index.tsx
1155
- init_react_import();
1156
- var import_react_textarea_autosize = __toESM(require("react-textarea-autosize"));
1157
-
1158
- // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/PromptForm/styles.module.css#css-module
1159
- init_react_import();
1160
- var styles_module_default4 = { "PromptForm": "_PromptForm_1p0vz_1", "PromptForm-dropOverlay": "_PromptForm-dropOverlay_1p0vz_15", "PromptForm-inner": "_PromptForm-inner_1p0vz_43", "PromptForm--glow": "_PromptForm--glow_1p0vz_52", "PromptForm-glow": "_PromptForm-glow_1p0vz_52", "loop": "_loop_1p0vz_1", "PromptForm-formInner": "_PromptForm-formInner_1p0vz_85", "PromptForm-input": "_PromptForm-input_1p0vz_94", "PromptForm--isDisabled": "_PromptForm--isDisabled_1p0vz_133", "PromptForm-helper": "_PromptForm-helper_1p0vz_152", "PromptForm-actions": "_PromptForm-actions_1p0vz_162", "PromptForm-actionsLeft": "_PromptForm-actionsLeft_1p0vz_173", "PromptForm-actionsRight": "_PromptForm-actionsRight_1p0vz_182", "PromptForm-actionSubmit": "_PromptForm-actionSubmit_1p0vz_187", "PromptForm--userCta": "_PromptForm--userCta_1p0vz_211", "PromptForm--isLoading": "_PromptForm--isLoading_1p0vz_241", "PromptForm-attachments": "_PromptForm-attachments_1p0vz_247", "PromptForm-attachmentChip": "_PromptForm-attachmentChip_1p0vz_255", "PromptForm-attachmentChipUploading": "_PromptForm-attachmentChipUploading_1p0vz_271", "PromptForm-attachmentChipFailed": "_PromptForm-attachmentChipFailed_1p0vz_275", "PromptForm-attachmentError": "_PromptForm-attachmentError_1p0vz_280", "PromptForm-attachmentSpinner": "_PromptForm-attachmentSpinner_1p0vz_285", "PromptForm-attachmentSpin": "_PromptForm-attachmentSpin_1p0vz_285", "PromptForm-attachmentRemove": "_PromptForm-attachmentRemove_1p0vz_289" };
1161
-
1162
- // src/lib/attachments.ts
1163
- init_react_import();
1164
- var INTERNAL_MESSAGE_PREFIX = "[puck-internal";
1165
- var defaultAttachmentAccept = [
1166
- "image/*",
1167
- ".pdf",
1168
- ".doc",
1169
- ".docx",
1170
- ".txt",
1171
- ".md"
1172
- ];
1173
- var defaultAttachmentConfig = {
1174
- maxFiles: 5,
1175
- maxSizeBytes: 10 * 1024 * 1024
1176
- };
1177
- var getExtension = (filename) => {
1178
- const parts = filename.toLowerCase().split(".");
1179
- if (parts.length < 2) {
1180
- return null;
1181
- }
1182
- return `.${parts.pop()}`;
1183
- };
1184
- var matchesAccept = (file, accept) => {
1185
- if (accept.length === 0) {
1186
- return true;
1187
- }
1188
- const extension = getExtension(file.name);
1189
- return accept.some((entry) => {
1190
- if (entry.endsWith("/*")) {
1191
- const prefix = entry.slice(0, -1);
1192
- return file.type.startsWith(prefix);
1193
- }
1194
- if (entry.startsWith(".")) {
1195
- return extension === entry.toLowerCase();
1196
- }
1197
- return file.type === entry;
1198
- });
1199
- };
1200
- var documentExtensionByMediaType = {
1201
- "application/msword": "doc",
1202
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
1203
- "text/markdown": "md",
1204
- "application/pdf": "pdf",
1205
- "text/plain": "txt"
1206
- };
1207
- var mediaTypeToExtension = (mediaType) => {
1208
- const mapped = documentExtensionByMediaType[mediaType];
1209
- if (mapped) {
1210
- return mapped;
1211
- }
1212
- const subtype = mediaType.split("/")[1] ?? "";
1213
- return subtype.split("+")[0] || "bin";
1214
- };
1215
- var getFilesFromClipboard = (data) => {
1216
- const files = [];
1217
- for (const item of data.items ? Array.from(data.items) : []) {
1218
- if (item.kind === "file") {
1219
- const file = item.getAsFile();
1220
- if (file) {
1221
- files.push(file);
1222
- }
1223
- }
1224
- }
1225
- if (files.length === 0 && data.files) {
1226
- files.push(...Array.from(data.files));
1227
- }
1228
- return files.map(
1229
- (file, index) => file.name ? file : new File(
1230
- [file],
1231
- `pasted-${Date.now()}-${index}.${mediaTypeToExtension(file.type)}`,
1232
- { type: file.type }
1233
- )
1234
- );
1235
- };
1236
- var getAttachmentIdFromRef = (url) => url.startsWith("attachment://") ? url.slice("attachment://".length) : null;
1237
- var resolveAttachmentUrl = (url, attachmentEndpoint) => {
1238
- if (!attachmentEndpoint) {
1239
- return url;
1240
- }
1241
- const attachmentId = getAttachmentIdFromRef(url);
1242
- if (!attachmentId) {
1243
- return url;
1244
- }
1245
- return `${attachmentEndpoint.replace(/\/$/, "")}/${attachmentId}`;
1246
- };
1247
- var fetchAttachmentUrl = async (endpoint, signal) => {
1248
- const response = await fetch(endpoint, { redirect: "manual", signal });
1249
- if (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) {
1250
- return endpoint;
1251
- }
1252
- if (!response.ok) {
1253
- throw new Error(`Attachment URL request failed with ${response.status}`);
1254
- }
1255
- const { url } = await response.json();
1256
- if (typeof url !== "string" || !url) {
1257
- throw new Error("Attachment URL response did not include a url");
1002
+ const { url } = await response.json();
1003
+ if (typeof url !== "string" || !url) {
1004
+ throw new Error("Attachment URL response did not include a url");
1258
1005
  }
1259
1006
  return url;
1260
1007
  };
@@ -1341,13 +1088,13 @@ function PromptForm({
1341
1088
  "plugin-ai-prompt-attachment-item-remove"
1342
1089
  );
1343
1090
  const loadingLabel = useMessage("loader-loading");
1344
- const hasSetInitialPrompt = (0, import_react8.useRef)(false);
1345
- const [prompt, setPrompt] = (0, import_react8.useState)(value);
1346
- const internalRef = (0, import_react8.useRef)(null);
1347
- const [isDragOver, setIsDragOver] = (0, import_react8.useState)(false);
1348
- const dragCounterRef = (0, import_react8.useRef)(0);
1091
+ const hasSetInitialPrompt = (0, import_react5.useRef)(false);
1092
+ const [prompt, setPrompt] = (0, import_react5.useState)(value);
1093
+ const internalRef = (0, import_react5.useRef)(null);
1094
+ const [isDragOver, setIsDragOver] = (0, import_react5.useState)(false);
1095
+ const dragCounterRef = (0, import_react5.useRef)(0);
1349
1096
  const canDrop = !!onFileDrop && !isDisabled && !isLoading;
1350
- const handleDragEnter = (0, import_react8.useCallback)(
1097
+ const handleDragEnter = (0, import_react5.useCallback)(
1351
1098
  (e) => {
1352
1099
  e.preventDefault();
1353
1100
  dragCounterRef.current++;
@@ -1357,17 +1104,17 @@ function PromptForm({
1357
1104
  },
1358
1105
  [canDrop]
1359
1106
  );
1360
- const handleDragLeave = (0, import_react8.useCallback)((e) => {
1107
+ const handleDragLeave = (0, import_react5.useCallback)((e) => {
1361
1108
  e.preventDefault();
1362
1109
  dragCounterRef.current--;
1363
1110
  if (dragCounterRef.current === 0) {
1364
1111
  setIsDragOver(false);
1365
1112
  }
1366
1113
  }, []);
1367
- const handleDragOver = (0, import_react8.useCallback)((e) => {
1114
+ const handleDragOver = (0, import_react5.useCallback)((e) => {
1368
1115
  e.preventDefault();
1369
1116
  }, []);
1370
- const handleDrop = (0, import_react8.useCallback)(
1117
+ const handleDrop = (0, import_react5.useCallback)(
1371
1118
  (e) => {
1372
1119
  e.preventDefault();
1373
1120
  dragCounterRef.current = 0;
@@ -1381,7 +1128,7 @@ function PromptForm({
1381
1128
  },
1382
1129
  [canDrop, onFileDrop]
1383
1130
  );
1384
- const handlePaste = (0, import_react8.useCallback)(
1131
+ const handlePaste = (0, import_react5.useCallback)(
1385
1132
  (e) => {
1386
1133
  if (!canDrop) return;
1387
1134
  const files = getFilesFromClipboard(e.clipboardData);
@@ -1391,7 +1138,7 @@ function PromptForm({
1391
1138
  },
1392
1139
  [canDrop, onFileDrop]
1393
1140
  );
1394
- (0, import_react8.useEffect)(() => {
1141
+ (0, import_react5.useEffect)(() => {
1395
1142
  setPrompt(value);
1396
1143
  }, [setPrompt, value]);
1397
1144
  const sendPrompt = async () => {
@@ -1406,7 +1153,7 @@ function PromptForm({
1406
1153
  setPrompt("");
1407
1154
  }
1408
1155
  };
1409
- (0, import_react8.useEffect)(() => {
1156
+ (0, import_react5.useEffect)(() => {
1410
1157
  const currentUrl = new URL(location.href);
1411
1158
  const initialPrompt = currentUrl.searchParams.get("initialPrompt");
1412
1159
  if (!hasSetInitialPrompt.current && initialPrompt && prompt === "") {
@@ -1552,21 +1299,21 @@ function PromptForm({
1552
1299
 
1553
1300
  // src/lib/context.ts
1554
1301
  init_react_import();
1555
- var import_react9 = require("react");
1556
- var toolStatusContext = (0, import_react9.createContext)({});
1302
+ var import_react6 = require("react");
1303
+ var toolStatusContext = (0, import_react6.createContext)({});
1557
1304
  var ToolStatusProvider = toolStatusContext.Provider;
1558
- var hostContext = (0, import_react9.createContext)(void 0);
1305
+ var hostContext = (0, import_react6.createContext)(void 0);
1559
1306
  var HostProvider = hostContext.Provider;
1560
- var subagentStateContext = (0, import_react9.createContext)({});
1307
+ var subagentStateContext = (0, import_react6.createContext)({});
1561
1308
  var SubagentStateProvider = subagentStateContext.Provider;
1562
1309
 
1563
1310
  // src/lib/use-attachment-url.ts
1564
1311
  init_react_import();
1565
- var import_react10 = require("react");
1312
+ var import_react7 = require("react");
1566
1313
  function useAttachmentUrl(url, endpoint) {
1567
1314
  const isRef = getAttachmentIdFromRef(url) !== null;
1568
- const [fetched, setFetched] = (0, import_react10.useState)();
1569
- (0, import_react10.useEffect)(() => {
1315
+ const [fetched, setFetched] = (0, import_react7.useState)();
1316
+ (0, import_react7.useEffect)(() => {
1570
1317
  if (!isRef) return;
1571
1318
  const controller = new AbortController();
1572
1319
  const loadUrl = async () => {
@@ -1698,7 +1445,7 @@ function mergeReasoningParts(parts) {
1698
1445
  }
1699
1446
  function ChatMessage({ message }) {
1700
1447
  const { role, parts: rawParts } = message;
1701
- const parts = (0, import_react11.useMemo)(() => mergeReasoningParts(rawParts), [rawParts]);
1448
+ const parts = (0, import_react8.useMemo)(() => mergeReasoningParts(rawParts), [rawParts]);
1702
1449
  if (role === "user") {
1703
1450
  const attachmentParts = parts.filter((part) => part.type === "file");
1704
1451
  const otherParts = parts.filter((part) => part.type !== "file");
@@ -1750,7 +1497,7 @@ function ChatAttachmentThumbnail({
1750
1497
  mediaType,
1751
1498
  url
1752
1499
  }) {
1753
- const host = (0, import_react11.useContext)(hostContext);
1500
+ const host = (0, import_react8.useContext)(hostContext);
1754
1501
  const endpoint = host ? `${host.replace(/\/$/, "")}/attachments` : "/api/puck/chat/attachments";
1755
1502
  const resolvedUrl = useAttachmentUrl(url, endpoint);
1756
1503
  const attachmentId = getAttachmentIdFromRef(url);
@@ -1788,12 +1535,12 @@ function ChatMessageWrapper({
1788
1535
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { children });
1789
1536
  }
1790
1537
  function ReasoningBlock({ part }) {
1791
- const startTimeRef = (0, import_react11.useRef)(null);
1792
- const [durationSecs, setDurationSecs] = (0, import_react11.useState)(null);
1538
+ const startTimeRef = (0, import_react8.useRef)(null);
1539
+ const [durationSecs, setDurationSecs] = (0, import_react8.useState)(null);
1793
1540
  if (part.state !== "done" && startTimeRef.current === null) {
1794
1541
  startTimeRef.current = Date.now();
1795
1542
  }
1796
- (0, import_react11.useEffect)(() => {
1543
+ (0, import_react8.useEffect)(() => {
1797
1544
  if (part.state === "done" && startTimeRef.current !== null) {
1798
1545
  setDurationSecs(Math.round((Date.now() - startTimeRef.current) / 1e3));
1799
1546
  }
@@ -1846,7 +1593,7 @@ function ChatAttachment({
1846
1593
  mediaType,
1847
1594
  url
1848
1595
  }) {
1849
- const host = (0, import_react11.useContext)(hostContext);
1596
+ const host = (0, import_react8.useContext)(hostContext);
1850
1597
  const endpoint = host ? `${host.replace(/\/$/, "")}/attachments` : "/api/puck/chat/attachments";
1851
1598
  const resolvedUrl = useAttachmentUrl(url, endpoint);
1852
1599
  const attachmentId = getAttachmentIdFromRef(url);
@@ -1861,14 +1608,14 @@ function ChatAttachment({
1861
1608
  ] }) });
1862
1609
  }
1863
1610
  function PuckTool({ toolCallId, output, type }) {
1864
- const toolStatus = (0, import_react11.useContext)(toolStatusContext)[toolCallId];
1611
+ const toolStatus = (0, import_react8.useContext)(toolStatusContext)[toolCallId];
1865
1612
  const thinkingLabel = useMessage("plugin-ai-chat-msg-thinking");
1866
1613
  const outputObj = output;
1867
1614
  const status = outputObj && "status" in outputObj ? outputObj.status : toolStatus ?? {
1868
1615
  loading: true,
1869
1616
  label: thinkingLabel
1870
1617
  };
1871
- let icon = (0, import_react11.useMemo)(() => {
1618
+ let icon = (0, import_react8.useMemo)(() => {
1872
1619
  if (type === "tool-write") {
1873
1620
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Pen, { size: 18 });
1874
1621
  } else if (type === "tool-refreshPageData") {
@@ -1885,9 +1632,9 @@ function PuckTool({ toolCallId, output, type }) {
1885
1632
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ChatEvent, { status, icon });
1886
1633
  }
1887
1634
  function SubagentBlock({ toolCallId }) {
1888
- const subagentState = (0, import_react11.useContext)(subagentStateContext);
1635
+ const subagentState = (0, import_react8.useContext)(subagentStateContext);
1889
1636
  const state = subagentState[toolCallId];
1890
- const toolStatusMap = (0, import_react11.useContext)(toolStatusContext);
1637
+ const toolStatusMap = (0, import_react8.useContext)(toolStatusContext);
1891
1638
  const loadingLabel = useMessage("loader-loading");
1892
1639
  const toolStatus = toolStatusMap[toolCallId];
1893
1640
  const fallbackLabel = toolStatus?.label ?? "Running subagent";
@@ -1895,7 +1642,7 @@ function SubagentBlock({ toolCallId }) {
1895
1642
  const loading = state ? state.state !== "done" : toolStatus?.loading ?? true;
1896
1643
  const hasBody = !!state && state.parts.length > 0;
1897
1644
  const parts = state?.parts ?? [];
1898
- const [isOpen, setIsOpen] = (0, import_react11.useState)(false);
1645
+ const [isOpen, setIsOpen] = (0, import_react8.useState)(false);
1899
1646
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
1900
1647
  "details",
1901
1648
  {
@@ -1925,154 +1672,422 @@ function SubagentChildPartRenderer({ part }) {
1925
1672
  if (part.kind === "text") {
1926
1673
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: cxMessage("text"), children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_react_markdown.default, { children: part.text }) });
1927
1674
  }
1928
- if (part.kind === "reasoning") {
1929
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1930
- ReasoningBlock,
1931
- {
1932
- part: {
1933
- type: "reasoning",
1934
- text: part.text,
1935
- state: part.state
1936
- }
1937
- }
1938
- );
1675
+ if (part.kind === "reasoning") {
1676
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1677
+ ReasoningBlock,
1678
+ {
1679
+ part: {
1680
+ type: "reasoning",
1681
+ text: part.text,
1682
+ state: part.state
1683
+ }
1684
+ }
1685
+ );
1686
+ }
1687
+ if (part.toolName === "subagent") {
1688
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(SubagentBlock, { toolCallId: part.childToolCallId });
1689
+ }
1690
+ const synthesized = {
1691
+ toolCallId: part.childToolCallId,
1692
+ type: `tool-${part.toolName}`,
1693
+ state: part.output !== void 0 ? "output-available" : "input-available",
1694
+ input: part.input,
1695
+ output: part.output
1696
+ };
1697
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(PuckTool, { ...synthesized });
1698
+ }
1699
+ function ChatEvent({
1700
+ status,
1701
+ icon = /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Check, { size: 18 })
1702
+ }) {
1703
+ const [isOpen, setIsOpen] = (0, import_react8.useState)(false);
1704
+ const loadingLabel = useMessage("loader-loading");
1705
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
1706
+ "details",
1707
+ {
1708
+ className: cxMessage("event"),
1709
+ onToggle: (e) => setIsOpen(e.currentTarget.open),
1710
+ children: [
1711
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
1712
+ "summary",
1713
+ {
1714
+ className: `${cxMessage("eventHeader")} ${status.summary ? "" : cxMessage("eventHeader--static")}`,
1715
+ children: [
1716
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: cxMessage("eventIcon"), children: status.error ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(TriangleAlert, { size: 18 }) : status.loading ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Loader, { size: 16, label: loadingLabel }) : icon }),
1717
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: status.label }),
1718
+ status.summary && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
1719
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: cxMessage("eventExpand"), children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Plus, { size: 12 }) }),
1720
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: cxMessage("eventCollapse"), children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Minus, { size: 12 }) })
1721
+ ] })
1722
+ ]
1723
+ }
1724
+ ),
1725
+ status.summary && isOpen && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: cxMessage("eventBody"), children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_react_markdown.default, { children: status.summary }) })
1726
+ ]
1727
+ }
1728
+ );
1729
+ }
1730
+ function ExamplePrompt({
1731
+ label,
1732
+ href,
1733
+ onClick,
1734
+ disabled
1735
+ }) {
1736
+ const content = /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
1737
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: label }),
1738
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: cx2("examplePromptArrow"), children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ArrowUp, { size: "16" }) })
1739
+ ] });
1740
+ if (href) {
1741
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1742
+ "a",
1743
+ {
1744
+ className: cx2("examplePrompt"),
1745
+ href: disabled ? void 0 : href,
1746
+ "aria-disabled": disabled || void 0,
1747
+ onClick: (e) => {
1748
+ if (disabled) {
1749
+ e.preventDefault();
1750
+ return;
1751
+ }
1752
+ onClick?.(e);
1753
+ },
1754
+ children: content
1755
+ }
1756
+ );
1757
+ }
1758
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1759
+ "button",
1760
+ {
1761
+ className: cx2("examplePrompt"),
1762
+ type: "button",
1763
+ disabled,
1764
+ onClick,
1765
+ children: content
1766
+ }
1767
+ );
1768
+ }
1769
+
1770
+ // src/lib/scroll-tracking-events.ts
1771
+ init_react_import();
1772
+ var listeners = /* @__PURE__ */ new Set();
1773
+ function dispatchScrollTrackingEvent(detail) {
1774
+ listeners.forEach((listener) => {
1775
+ listener(detail);
1776
+ });
1777
+ }
1778
+ function subscribeToScrollTrackingEvents(listener) {
1779
+ listeners.add(listener);
1780
+ return () => {
1781
+ listeners.delete(listener);
1782
+ };
1783
+ }
1784
+
1785
+ // src/components/DesignModeToggle/index.tsx
1786
+ init_react_import();
1787
+
1788
+ // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/DesignModeToggle/styles.module.css#css-module
1789
+ init_react_import();
1790
+ var styles_module_default5 = { "DesignModeToggle": "_DesignModeToggle_vng7q_1", "DesignModeToggle-button": "_DesignModeToggle-button_vng7q_8", "DesignModeToggle-button--active": "_DesignModeToggle-button--active_vng7q_32" };
1791
+
1792
+ // src/components/DesignModeToggle/index.tsx
1793
+ var import_jsx_runtime5 = require("react/jsx-runtime");
1794
+ var cx3 = getClassNameFactory("DesignModeToggle", styles_module_default5);
1795
+ function DesignModeToggle({
1796
+ active,
1797
+ onToggle,
1798
+ disabled
1799
+ }) {
1800
+ const label = useMessage("plugin-ai-prompt-design-mode");
1801
+ const enableTitle = useMessage("plugin-ai-prompt-design-mode-enable");
1802
+ const disableTitle = useMessage("plugin-ai-prompt-design-mode-disable");
1803
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: cx3(), children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
1804
+ "button",
1805
+ {
1806
+ className: `${cx3("button")} ${active ? cx3("button--active") : ""}`,
1807
+ onClick: onToggle,
1808
+ disabled,
1809
+ type: "button",
1810
+ title: active ? disableTitle : enableTitle,
1811
+ children: [
1812
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(WandSparkles, { size: 12 }),
1813
+ label
1814
+ ]
1815
+ }
1816
+ ) });
1817
+ }
1818
+
1819
+ // src/components/PluginTheme/index.ts
1820
+ init_react_import();
1821
+
1822
+ // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/PluginTheme/styles.module.css#css-module
1823
+ init_react_import();
1824
+ var styles_module_default6 = { "PluginTheme": "_PluginTheme_u3emj_8" };
1825
+
1826
+ // src/components/PluginTheme/index.ts
1827
+ var cx4 = getClassNameFactory("PluginTheme", styles_module_default6);
1828
+ var pluginThemeClassName = cx4();
1829
+
1830
+ // src/lib/use-puck-ai.ts
1831
+ init_react_import();
1832
+
1833
+ // ../../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
1834
+ init_react_import();
1835
+ var import_ai = require("ai");
1836
+ var import_react9 = require("react");
1837
+ var import_ai2 = require("ai");
1838
+ var import_throttleit = __toESM(require_throttleit(), 1);
1839
+ var import_ai3 = require("ai");
1840
+ var import_react10 = require("react");
1841
+ var import_ai4 = require("ai");
1842
+ var import_react11 = require("react");
1843
+ var __accessCheck = (obj, member, msg) => {
1844
+ if (!member.has(obj))
1845
+ throw TypeError("Cannot " + msg);
1846
+ };
1847
+ var __privateGet = (obj, member, getter) => {
1848
+ __accessCheck(obj, member, "read from private field");
1849
+ return getter ? getter.call(obj) : member.get(obj);
1850
+ };
1851
+ var __privateAdd = (obj, member, value) => {
1852
+ if (member.has(obj))
1853
+ throw TypeError("Cannot add the same private member more than once");
1854
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1855
+ };
1856
+ var __privateSet = (obj, member, value, setter) => {
1857
+ __accessCheck(obj, member, "write to private field");
1858
+ setter ? setter.call(obj, value) : member.set(obj, value);
1859
+ return value;
1860
+ };
1861
+ function throttle(fn, waitMs) {
1862
+ return waitMs != null ? (0, import_throttleit.default)(fn, waitMs) : fn;
1863
+ }
1864
+ var _messages;
1865
+ var _status;
1866
+ var _error;
1867
+ var _messagesCallbacks;
1868
+ var _statusCallbacks;
1869
+ var _errorCallbacks;
1870
+ var _callMessagesCallbacks;
1871
+ var _callStatusCallbacks;
1872
+ var _callErrorCallbacks;
1873
+ var ReactChatState = class {
1874
+ constructor(initialMessages = []) {
1875
+ __privateAdd(this, _messages, void 0);
1876
+ __privateAdd(this, _status, "ready");
1877
+ __privateAdd(this, _error, void 0);
1878
+ __privateAdd(this, _messagesCallbacks, /* @__PURE__ */ new Set());
1879
+ __privateAdd(this, _statusCallbacks, /* @__PURE__ */ new Set());
1880
+ __privateAdd(this, _errorCallbacks, /* @__PURE__ */ new Set());
1881
+ this.pushMessage = (message) => {
1882
+ __privateSet(this, _messages, __privateGet(this, _messages).concat(message));
1883
+ __privateGet(this, _callMessagesCallbacks).call(this);
1884
+ };
1885
+ this.popMessage = () => {
1886
+ __privateSet(this, _messages, __privateGet(this, _messages).slice(0, -1));
1887
+ __privateGet(this, _callMessagesCallbacks).call(this);
1888
+ };
1889
+ this.replaceMessage = (index, message) => {
1890
+ __privateSet(this, _messages, [
1891
+ ...__privateGet(this, _messages).slice(0, index),
1892
+ // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:
1893
+ this.snapshot(message),
1894
+ ...__privateGet(this, _messages).slice(index + 1)
1895
+ ]);
1896
+ __privateGet(this, _callMessagesCallbacks).call(this);
1897
+ };
1898
+ this.snapshot = (value) => structuredClone(value);
1899
+ this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => {
1900
+ const callback = throttleWaitMs ? throttle(onChange, throttleWaitMs) : onChange;
1901
+ __privateGet(this, _messagesCallbacks).add(callback);
1902
+ return () => {
1903
+ __privateGet(this, _messagesCallbacks).delete(callback);
1904
+ };
1905
+ };
1906
+ this["~registerStatusCallback"] = (onChange) => {
1907
+ __privateGet(this, _statusCallbacks).add(onChange);
1908
+ return () => {
1909
+ __privateGet(this, _statusCallbacks).delete(onChange);
1910
+ };
1911
+ };
1912
+ this["~registerErrorCallback"] = (onChange) => {
1913
+ __privateGet(this, _errorCallbacks).add(onChange);
1914
+ return () => {
1915
+ __privateGet(this, _errorCallbacks).delete(onChange);
1916
+ };
1917
+ };
1918
+ __privateAdd(this, _callMessagesCallbacks, () => {
1919
+ __privateGet(this, _messagesCallbacks).forEach((callback) => callback());
1920
+ });
1921
+ __privateAdd(this, _callStatusCallbacks, () => {
1922
+ __privateGet(this, _statusCallbacks).forEach((callback) => callback());
1923
+ });
1924
+ __privateAdd(this, _callErrorCallbacks, () => {
1925
+ __privateGet(this, _errorCallbacks).forEach((callback) => callback());
1926
+ });
1927
+ __privateSet(this, _messages, initialMessages);
1928
+ }
1929
+ get status() {
1930
+ return __privateGet(this, _status);
1939
1931
  }
1940
- if (part.toolName === "subagent") {
1941
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(SubagentBlock, { toolCallId: part.childToolCallId });
1932
+ set status(newStatus) {
1933
+ __privateSet(this, _status, newStatus);
1934
+ __privateGet(this, _callStatusCallbacks).call(this);
1942
1935
  }
1943
- const synthesized = {
1944
- toolCallId: part.childToolCallId,
1945
- type: `tool-${part.toolName}`,
1946
- state: part.output !== void 0 ? "output-available" : "input-available",
1947
- input: part.input,
1948
- output: part.output
1936
+ get error() {
1937
+ return __privateGet(this, _error);
1938
+ }
1939
+ set error(newError) {
1940
+ __privateSet(this, _error, newError);
1941
+ __privateGet(this, _callErrorCallbacks).call(this);
1942
+ }
1943
+ get messages() {
1944
+ return __privateGet(this, _messages);
1945
+ }
1946
+ set messages(newMessages) {
1947
+ __privateSet(this, _messages, [...newMessages]);
1948
+ __privateGet(this, _callMessagesCallbacks).call(this);
1949
+ }
1950
+ };
1951
+ _messages = /* @__PURE__ */ new WeakMap();
1952
+ _status = /* @__PURE__ */ new WeakMap();
1953
+ _error = /* @__PURE__ */ new WeakMap();
1954
+ _messagesCallbacks = /* @__PURE__ */ new WeakMap();
1955
+ _statusCallbacks = /* @__PURE__ */ new WeakMap();
1956
+ _errorCallbacks = /* @__PURE__ */ new WeakMap();
1957
+ _callMessagesCallbacks = /* @__PURE__ */ new WeakMap();
1958
+ _callStatusCallbacks = /* @__PURE__ */ new WeakMap();
1959
+ _callErrorCallbacks = /* @__PURE__ */ new WeakMap();
1960
+ var _state;
1961
+ var Chat = class extends import_ai2.AbstractChat {
1962
+ constructor({ messages, ...init }) {
1963
+ const state = new ReactChatState(messages);
1964
+ super({ ...init, state });
1965
+ __privateAdd(this, _state, void 0);
1966
+ this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => __privateGet(this, _state)["~registerMessagesCallback"](onChange, throttleWaitMs);
1967
+ this["~registerStatusCallback"] = (onChange) => __privateGet(this, _state)["~registerStatusCallback"](onChange);
1968
+ this["~registerErrorCallback"] = (onChange) => __privateGet(this, _state)["~registerErrorCallback"](onChange);
1969
+ __privateSet(this, _state, state);
1970
+ }
1971
+ };
1972
+ _state = /* @__PURE__ */ new WeakMap();
1973
+ function useChat({
1974
+ experimental_throttle: throttleWaitMs,
1975
+ resume = false,
1976
+ ...options
1977
+ } = {}) {
1978
+ const latestRef = (0, import_react9.useRef)({});
1979
+ if (!("chat" in options)) {
1980
+ latestRef.current = {
1981
+ onToolCall: options.onToolCall,
1982
+ onData: options.onData,
1983
+ onFinish: options.onFinish,
1984
+ onError: options.onError,
1985
+ sendAutomaticallyWhen: options.sendAutomaticallyWhen,
1986
+ transport: options.transport
1987
+ };
1988
+ }
1989
+ let defaultTransport;
1990
+ const getTransport = () => {
1991
+ var _a;
1992
+ return (_a = latestRef.current.transport) != null ? _a : defaultTransport != null ? defaultTransport : defaultTransport = new import_ai.DefaultChatTransport();
1949
1993
  };
1950
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(PuckTool, { ...synthesized });
1951
- }
1952
- function ChatEvent({
1953
- status,
1954
- icon = /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Check, { size: 18 })
1955
- }) {
1956
- const [isOpen, setIsOpen] = (0, import_react11.useState)(false);
1957
- const loadingLabel = useMessage("loader-loading");
1958
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
1959
- "details",
1960
- {
1961
- className: cxMessage("event"),
1962
- onToggle: (e) => setIsOpen(e.currentTarget.open),
1963
- children: [
1964
- /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
1965
- "summary",
1966
- {
1967
- className: `${cxMessage("eventHeader")} ${status.summary ? "" : cxMessage("eventHeader--static")}`,
1968
- children: [
1969
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: cxMessage("eventIcon"), children: status.error ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(TriangleAlert, { size: 18 }) : status.loading ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Loader, { size: 16, label: loadingLabel }) : icon }),
1970
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: status.label }),
1971
- status.summary && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
1972
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: cxMessage("eventExpand"), children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Plus, { size: 12 }) }),
1973
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: cxMessage("eventCollapse"), children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Minus, { size: 12 }) })
1974
- ] })
1975
- ]
1976
- }
1977
- ),
1978
- status.summary && isOpen && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: cxMessage("eventBody"), children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_react_markdown.default, { children: status.summary }) })
1979
- ]
1994
+ const chatOptions = {
1995
+ ...options,
1996
+ transport: {
1997
+ sendMessages: (sendOptions) => getTransport().sendMessages(sendOptions),
1998
+ reconnectToStream: (reconnectOptions) => getTransport().reconnectToStream(reconnectOptions)
1999
+ },
2000
+ onToolCall: (arg) => {
2001
+ var _a, _b;
2002
+ return (_b = (_a = latestRef.current).onToolCall) == null ? void 0 : _b.call(_a, arg);
2003
+ },
2004
+ onData: (arg) => {
2005
+ var _a, _b;
2006
+ return (_b = (_a = latestRef.current).onData) == null ? void 0 : _b.call(_a, arg);
2007
+ },
2008
+ onFinish: (arg) => {
2009
+ var _a, _b;
2010
+ return (_b = (_a = latestRef.current).onFinish) == null ? void 0 : _b.call(_a, arg);
2011
+ },
2012
+ onError: (arg) => {
2013
+ var _a, _b;
2014
+ return (_b = (_a = latestRef.current).onError) == null ? void 0 : _b.call(_a, arg);
2015
+ },
2016
+ sendAutomaticallyWhen: (arg) => {
2017
+ var _a, _b, _c;
2018
+ return (_c = (_b = (_a = latestRef.current).sendAutomaticallyWhen) == null ? void 0 : _b.call(_a, arg)) != null ? _c : false;
1980
2019
  }
2020
+ };
2021
+ const chatRef = (0, import_react9.useRef)(
2022
+ "chat" in options ? options.chat : new Chat(chatOptions)
1981
2023
  );
1982
- }
1983
- function ExamplePrompt({
1984
- label,
1985
- href,
1986
- onClick,
1987
- disabled
1988
- }) {
1989
- const content = /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
1990
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: label }),
1991
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: cx2("examplePromptArrow"), children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ArrowUp, { size: "16" }) })
1992
- ] });
1993
- if (href) {
1994
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1995
- "a",
1996
- {
1997
- className: cx2("examplePrompt"),
1998
- href: disabled ? void 0 : href,
1999
- "aria-disabled": disabled || void 0,
2000
- onClick: (e) => {
2001
- if (disabled) {
2002
- e.preventDefault();
2003
- return;
2004
- }
2005
- onClick?.(e);
2006
- },
2007
- children: content
2008
- }
2009
- );
2024
+ const shouldRecreateChat = "chat" in options && options.chat !== chatRef.current || "id" in options && options.id != null && chatRef.current.id !== options.id;
2025
+ if (shouldRecreateChat) {
2026
+ chatRef.current = "chat" in options ? options.chat : new Chat(chatOptions);
2010
2027
  }
2011
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
2012
- "button",
2013
- {
2014
- className: cx2("examplePrompt"),
2015
- type: "button",
2016
- disabled,
2017
- onClick,
2018
- children: content
2019
- }
2028
+ const subscribeToMessages = (0, import_react9.useCallback)(
2029
+ (update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs),
2030
+ // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
2031
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2032
+ [throttleWaitMs, chatRef.current.id]
2020
2033
  );
2021
- }
2022
-
2023
- // src/components/Chat/index.tsx
2024
- var import_qler = __toESM(require("qler"));
2025
- var import_reducer = __toESM(require_dist());
2026
- var import_use_debounce = require("use-debounce");
2027
-
2028
- // src/lib/scroll-tracking-events.ts
2029
- init_react_import();
2030
- var listeners = /* @__PURE__ */ new Set();
2031
- function dispatchScrollTrackingEvent(detail) {
2032
- listeners.forEach((listener) => {
2033
- listener(detail);
2034
- });
2035
- }
2036
- function subscribeToScrollTrackingEvents(listener) {
2037
- listeners.add(listener);
2038
- return () => {
2039
- listeners.delete(listener);
2034
+ const messages = (0, import_react9.useSyncExternalStore)(
2035
+ subscribeToMessages,
2036
+ () => chatRef.current.messages,
2037
+ () => chatRef.current.messages
2038
+ );
2039
+ const status = (0, import_react9.useSyncExternalStore)(
2040
+ chatRef.current["~registerStatusCallback"],
2041
+ () => chatRef.current.status,
2042
+ () => chatRef.current.status
2043
+ );
2044
+ const error = (0, import_react9.useSyncExternalStore)(
2045
+ chatRef.current["~registerErrorCallback"],
2046
+ () => chatRef.current.error,
2047
+ () => chatRef.current.error
2048
+ );
2049
+ const setMessages = (0, import_react9.useCallback)(
2050
+ (messagesParam) => {
2051
+ if (typeof messagesParam === "function") {
2052
+ messagesParam = messagesParam(chatRef.current.messages);
2053
+ }
2054
+ chatRef.current.messages = messagesParam;
2055
+ },
2056
+ [chatRef]
2057
+ );
2058
+ (0, import_react9.useEffect)(() => {
2059
+ if (resume) {
2060
+ chatRef.current.resumeStream();
2061
+ }
2062
+ }, [resume, chatRef]);
2063
+ return {
2064
+ id: chatRef.current.id,
2065
+ messages,
2066
+ setMessages,
2067
+ sendMessage: chatRef.current.sendMessage,
2068
+ regenerate: chatRef.current.regenerate,
2069
+ clearError: chatRef.current.clearError,
2070
+ stop: chatRef.current.stop,
2071
+ error,
2072
+ resumeStream: chatRef.current.resumeStream,
2073
+ status,
2074
+ /**
2075
+ * @deprecated Use `addToolOutput` instead.
2076
+ */
2077
+ addToolResult: chatRef.current.addToolOutput,
2078
+ addToolOutput: chatRef.current.addToolOutput,
2079
+ addToolApprovalResponse: chatRef.current.addToolApprovalResponse
2040
2080
  };
2041
2081
  }
2042
2082
 
2043
- // src/components/DesignModeToggle/index.tsx
2044
- init_react_import();
2045
-
2046
- // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/DesignModeToggle/styles.module.css#css-module
2047
- init_react_import();
2048
- var styles_module_default5 = { "DesignModeToggle": "_DesignModeToggle_vng7q_1", "DesignModeToggle-button": "_DesignModeToggle-button_vng7q_8", "DesignModeToggle-button--active": "_DesignModeToggle-button--active_vng7q_32" };
2049
-
2050
- // src/components/DesignModeToggle/index.tsx
2051
- var import_jsx_runtime5 = require("react/jsx-runtime");
2052
- var cx3 = getClassNameFactory("DesignModeToggle", styles_module_default5);
2053
- function DesignModeToggle({
2054
- active,
2055
- onToggle,
2056
- disabled
2057
- }) {
2058
- const label = useMessage("plugin-ai-prompt-design-mode");
2059
- const enableTitle = useMessage("plugin-ai-prompt-design-mode-enable");
2060
- const disableTitle = useMessage("plugin-ai-prompt-design-mode-disable");
2061
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: cx3(), children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
2062
- "button",
2063
- {
2064
- className: `${cx3("button")} ${active ? cx3("button--active") : ""}`,
2065
- onClick: onToggle,
2066
- disabled,
2067
- type: "button",
2068
- title: active ? disableTitle : enableTitle,
2069
- children: [
2070
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(WandSparkles, { size: 12 }),
2071
- label
2072
- ]
2073
- }
2074
- ) });
2075
- }
2083
+ // src/lib/use-puck-ai.ts
2084
+ var import_core5 = require("@puckeditor/core");
2085
+ var import_ai5 = require("ai");
2086
+ var import_react17 = require("react");
2087
+ var import_ulid = require("ulid");
2088
+ var import_qler = __toESM(require("qler"));
2089
+ var import_use_debounce = require("use-debounce");
2090
+ var import_reducer = __toESM(require_dist());
2076
2091
 
2077
2092
  // src/lib/design/runtime.tsx
2078
2093
  init_react_import();
@@ -3534,633 +3549,1337 @@ function createDesignComponentConfig(registration) {
3534
3549
  entryEl.setAttribute(attrName, value);
3535
3550
  }
3536
3551
  }
3537
- }, [entryEl, fieldValueAttrs]);
3538
- const appliedArrayHtml = (0, import_react14.useRef)(/* @__PURE__ */ new WeakMap());
3539
- const arrayItemWiring = (0, import_react14.useRef)({});
3540
- const appliedArrays = (0, import_react14.useRef)(null);
3541
- (0, import_react14.useEffect)(() => {
3542
- if (!puck.isEditing || !entryEl || !getPuck) return;
3543
- if (appliedArrays.current?.el === entryEl && appliedArrays.current?.html === html && appliedArrays.current?.sig === arraySig) {
3544
- return;
3552
+ }, [entryEl, fieldValueAttrs]);
3553
+ const appliedArrayHtml = (0, import_react14.useRef)(/* @__PURE__ */ new WeakMap());
3554
+ const arrayItemWiring = (0, import_react14.useRef)({});
3555
+ const appliedArrays = (0, import_react14.useRef)(null);
3556
+ (0, import_react14.useEffect)(() => {
3557
+ if (!puck.isEditing || !entryEl || !getPuck) return;
3558
+ if (appliedArrays.current?.el === entryEl && appliedArrays.current?.html === html && appliedArrays.current?.sig === arraySig) {
3559
+ return;
3560
+ }
3561
+ let deferredFocus = false;
3562
+ for (const [arrayName, items] of arrayFields) {
3563
+ const itemsHtml = renderHtmlArrayItems(html, arrayName, items);
3564
+ if (itemsHtml === null) continue;
3565
+ const container = findOwnArrayContainer(entryEl, arrayName);
3566
+ if (!container) continue;
3567
+ if (appliedArrayHtml.current.get(container) === itemsHtml) continue;
3568
+ if (hasFocusWithin(container)) {
3569
+ deferredFocus = true;
3570
+ continue;
3571
+ }
3572
+ morphHtml(
3573
+ container,
3574
+ itemsHtml,
3575
+ [],
3576
+ (el) => el.hasAttribute("data-puck-slot")
3577
+ );
3578
+ appliedArrayHtml.current.set(container, itemsHtml);
3579
+ const binding = annotations.fields.find(
3580
+ (field) => field.binding === "array" && field.name === arrayName
3581
+ );
3582
+ const wiring = arrayItemWiring.current[arrayName] ?? (arrayItemWiring.current[arrayName] = /* @__PURE__ */ new Map());
3583
+ if (binding) {
3584
+ wireArrayItemEditing({
3585
+ container,
3586
+ arrayName,
3587
+ itemFields: binding.itemFields,
3588
+ componentId: id,
3589
+ getPuck,
3590
+ wiring
3591
+ });
3592
+ } else {
3593
+ wiring.forEach(({ cleanup }) => cleanup());
3594
+ wiring.clear();
3595
+ }
3596
+ }
3597
+ appliedArrays.current = deferredFocus ? null : { el: entryEl, html, sig: arraySig };
3598
+ }, [
3599
+ arrayFields,
3600
+ arraySig,
3601
+ annotations,
3602
+ entryEl,
3603
+ html,
3604
+ puck.isEditing,
3605
+ id,
3606
+ getPuck
3607
+ ]);
3608
+ (0, import_react14.useEffect)(
3609
+ () => () => {
3610
+ Object.values(arrayItemWiring.current).forEach(
3611
+ (wiring) => wiring.forEach(({ cleanup }) => cleanup())
3612
+ );
3613
+ },
3614
+ []
3615
+ );
3616
+ (0, import_react14.useEffect)(() => {
3617
+ if (!script || !entryEl) return;
3618
+ scriptRef.current?.remove();
3619
+ const doc = entryEl.ownerDocument;
3620
+ const el = doc.createElement("script");
3621
+ el.textContent = wrapScriptWithObserverGuard(script);
3622
+ doc.body.appendChild(el);
3623
+ scriptRef.current = el;
3624
+ return () => {
3625
+ el.remove();
3626
+ scriptRef.current = null;
3627
+ };
3628
+ }, [script, entryEl]);
3629
+ if (!puck.isEditing) {
3630
+ const slotContent = {};
3631
+ for (const slot of annotations.slots) {
3632
+ const Slot = props[slot.name];
3633
+ if (typeof Slot === "function") {
3634
+ slotContent[slot.name] = /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
3635
+ Slot,
3636
+ {
3637
+ style: slot.style ? parseStyleString(slot.style) : void 0,
3638
+ className: slot.className || void 0
3639
+ }
3640
+ );
3641
+ }
3642
+ }
3643
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_jsx_runtime7.Fragment, { children: [
3644
+ styles && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("style", { children: styles }),
3645
+ style && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("style", { children: style }),
3646
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { ref: setEntryEl, ...fieldValueAttrs, children: htmlToReactTree(patchedHtml, slotContent) })
3647
+ ] });
3648
+ }
3649
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_jsx_runtime7.Fragment, { children: [
3650
+ styles && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("style", { children: styles }),
3651
+ style && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("style", { children: style }),
3652
+ editorEntryNode,
3653
+ entryEl && annotations.slots.map((slot) => /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
3654
+ SlotPortal,
3655
+ {
3656
+ entry: entryEl,
3657
+ html,
3658
+ slotName: slot.name,
3659
+ slotStyle: slot.style,
3660
+ slotClassName: slot.className,
3661
+ SlotContent: props[slot.name]
3662
+ },
3663
+ slot.name
3664
+ ))
3665
+ ] });
3666
+ }
3667
+ }
3668
+
3669
+ // src/lib/design/globals.tsx
3670
+ init_react_import();
3671
+ var import_react15 = require("react");
3672
+ var import_jsx_runtime8 = require("react/jsx-runtime");
3673
+ function getDynamicConfigGlobals(dynamicConfig) {
3674
+ if (typeof dynamicConfig !== "object" || dynamicConfig === null) return {};
3675
+ const { styles, script } = dynamicConfig;
3676
+ return {
3677
+ ...typeof styles === "string" ? { styles } : {},
3678
+ ...typeof script === "string" ? { script } : {}
3679
+ };
3680
+ }
3681
+ var INLINE_EDIT_RESET = ":where([data-puck-design] [contenteditable]){overflow-wrap:inherit;line-break:inherit;-webkit-nbsp-mode:inherit}";
3682
+ function DesignGlobals({
3683
+ styles,
3684
+ script,
3685
+ isEditing
3686
+ }) {
3687
+ const scriptRef = (0, import_react15.useRef)(null);
3688
+ const hostRef = (0, import_react15.useRef)(null);
3689
+ (0, import_react15.useEffect)(() => {
3690
+ if (!script) return;
3691
+ scriptRef.current?.remove();
3692
+ const doc = hostRef.current?.ownerDocument ?? document;
3693
+ const el = doc.createElement("script");
3694
+ el.textContent = wrapScriptWithObserverGuard(script);
3695
+ doc.body.appendChild(el);
3696
+ scriptRef.current = el;
3697
+ return () => {
3698
+ el.remove();
3699
+ scriptRef.current = null;
3700
+ };
3701
+ }, [script]);
3702
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(import_jsx_runtime8.Fragment, { children: [
3703
+ isEditing && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("style", { children: INLINE_EDIT_RESET }),
3704
+ styles && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("style", { children: styles }),
3705
+ script && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { ref: hostRef, style: { display: "none" } })
3706
+ ] });
3707
+ }
3708
+ var WRAPPED = "__puckAiDesignGlobals";
3709
+ var isWrapped = (render) => typeof render === "function" && render[WRAPPED] === true;
3710
+ function withDesignGlobals(root) {
3711
+ if (isWrapped(root?.render)) return root;
3712
+ const userRender = root?.render;
3713
+ const render = (props) => {
3714
+ const { styles, script } = getDynamicConfigGlobals(props._dynamicConfig);
3715
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(import_jsx_runtime8.Fragment, { children: [
3716
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
3717
+ DesignGlobals,
3718
+ {
3719
+ styles,
3720
+ script,
3721
+ isEditing: props.puck?.isEditing
3722
+ }
3723
+ ),
3724
+ userRender ? userRender(props) : props.children
3725
+ ] });
3726
+ };
3727
+ render[WRAPPED] = true;
3728
+ return { ...root, render };
3729
+ }
3730
+ function ensureDesignGlobalsRoot(config) {
3731
+ if (!config.root) config.root = {};
3732
+ if (isWrapped(config.root.render)) return false;
3733
+ config.root.render = withDesignGlobals(config.root).render;
3734
+ return true;
3735
+ }
3736
+
3737
+ // src/lib/design/runtime.tsx
3738
+ var import_jsx_runtime9 = require("react/jsx-runtime");
3739
+ var cachedFieldMetadata;
3740
+ function detectFieldMetadata(config) {
3741
+ for (const comp of Object.values(config.components)) {
3742
+ for (const field of Object.values(comp.fields ?? {})) {
3743
+ const meta = field?.metadata;
3744
+ if (meta && typeof meta === "object" && Object.keys(meta).length > 0) {
3745
+ return { ...meta };
3746
+ }
3747
+ }
3748
+ }
3749
+ return null;
3750
+ }
3751
+ function addFieldMetadata(fields, metadata) {
3752
+ const out = {};
3753
+ for (const [key, field] of Object.entries(fields)) {
3754
+ out[key] = field && typeof field === "object" ? { ...field, metadata: { ...field.metadata, ...metadata } } : field;
3755
+ }
3756
+ return out;
3757
+ }
3758
+ function applyFieldMetadata(componentConfig, metadata) {
3759
+ const origResolveFields = componentConfig.resolveFields;
3760
+ componentConfig.resolveFields = async (data, params) => {
3761
+ const fields = origResolveFields ? await origResolveFields(data, params) : componentConfig.fields ?? {};
3762
+ return addFieldMetadata(fields, metadata);
3763
+ };
3764
+ }
3765
+ function applyConfigFieldMetadata(config, dynamicComponents) {
3766
+ const metadata = detectFieldMetadata(config);
3767
+ if (!metadata) return;
3768
+ for (const name of Object.keys(dynamicComponents)) {
3769
+ if (config.components[name]) {
3770
+ applyFieldMetadata(config.components[name], metadata);
3771
+ }
3772
+ }
3773
+ }
3774
+ var DESIGNED_CATEGORY = "dynamic";
3775
+ var dynamicConfigRootField = {
3776
+ type: "custom",
3777
+ render: () => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", {}),
3778
+ ai: {
3779
+ exclude: true
3780
+ }
3781
+ };
3782
+ function ensureDynamicConfigField(config) {
3783
+ if (!config.root) config.root = {};
3784
+ if (!config.root.fields) config.root.fields = {};
3785
+ if (!config.root.fields._dynamicConfig) {
3786
+ config.root.fields._dynamicConfig = dynamicConfigRootField;
3787
+ }
3788
+ }
3789
+ function getPersistedDynamicConfig(data) {
3790
+ return data?.root?.props?._dynamicConfig ?? {};
3791
+ }
3792
+ function getPersistedRegistrations(data) {
3793
+ return getPersistedDynamicConfig(data).components;
3794
+ }
3795
+ function getRequestComponentConfigs(data) {
3796
+ const registrations = getPersistedRegistrations(data);
3797
+ const components = {};
3798
+ if (!registrations) return components;
3799
+ for (const [name, registration] of Object.entries(registrations)) {
3800
+ components[name] = {
3801
+ ...registration.label ? { label: registration.label } : {},
3802
+ fields: { ...registration.fields ?? {} },
3803
+ ...registration.defaultProps ? { defaultProps: { ...registration.defaultProps } } : {},
3804
+ render: () => null
3805
+ };
3806
+ }
3807
+ return components;
3808
+ }
3809
+ function syncDesignedComponentsCategory(getPuck, designedComponents, hadRemovals) {
3810
+ const { appState, dispatch } = getPuck();
3811
+ const componentList = { ...appState.ui.componentList };
3812
+ const existing = componentList[DESIGNED_CATEGORY];
3813
+ const current = existing?.components ?? [];
3814
+ const unchanged = current.length === designedComponents.length && current.every((name, i) => name === designedComponents[i]);
3815
+ if (unchanged && !hadRemovals) return;
3816
+ componentList[DESIGNED_CATEGORY] = {
3817
+ title: "Generated",
3818
+ expanded: true,
3819
+ ...existing,
3820
+ components: designedComponents,
3821
+ visible: designedComponents.length > 0
3822
+ };
3823
+ dispatch({ type: "setUi", ui: { componentList } });
3824
+ }
3825
+ var lastSynced = /* @__PURE__ */ new Map();
3826
+ 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;
3827
+ function syncDesignComponents(getPuck) {
3828
+ const { config, appState, dispatch } = getPuck();
3829
+ const persisted = getPersistedRegistrations(appState.data) ?? {};
3830
+ if (cachedFieldMetadata === void 0) {
3831
+ cachedFieldMetadata = detectFieldMetadata(config);
3832
+ }
3833
+ let createdSettled = ensureDesignGlobalsRoot(config);
3834
+ ensureDynamicConfigField(config);
3835
+ for (const [name, persistedReg] of Object.entries(persisted)) {
3836
+ const prev = lastSynced.get(name);
3837
+ if (registrationStore.has(name) && config.components[name] && (prev === persistedReg || registrationContentEqual(prev, persistedReg))) {
3838
+ lastSynced.set(name, persistedReg);
3839
+ continue;
3840
+ }
3841
+ lastSynced.set(name, persistedReg);
3842
+ const registration = registrationStore.apply({ ...persistedReg, name });
3843
+ const isSettled = !registration.streaming;
3844
+ if (!config.components[name] || !prev) {
3845
+ ensureDynamicConfigField(config);
3846
+ const componentConfig = createDesignComponentConfig(registration);
3847
+ if (cachedFieldMetadata) {
3848
+ applyFieldMetadata(componentConfig, cachedFieldMetadata);
3849
+ }
3850
+ config.components[name] = componentConfig;
3851
+ if (isSettled) createdSettled = true;
3852
+ } else {
3853
+ if (registration.label)
3854
+ config.components[name].label = registration.label;
3855
+ if (isSettled) {
3856
+ config.components[name].defaultProps = {
3857
+ ...registration.defaultProps ?? {}
3858
+ };
3545
3859
  }
3546
- let deferredFocus = false;
3547
- for (const [arrayName, items] of arrayFields) {
3548
- const itemsHtml = renderHtmlArrayItems(html, arrayName, items);
3549
- if (itemsHtml === null) continue;
3550
- const container = findOwnArrayContainer(entryEl, arrayName);
3551
- if (!container) continue;
3552
- if (appliedArrayHtml.current.get(container) === itemsHtml) continue;
3553
- if (hasFocusWithin(container)) {
3554
- deferredFocus = true;
3555
- continue;
3556
- }
3557
- morphHtml(
3558
- container,
3559
- itemsHtml,
3560
- [],
3561
- (el) => el.hasAttribute("data-puck-slot")
3562
- );
3563
- appliedArrayHtml.current.set(container, itemsHtml);
3564
- const binding = annotations.fields.find(
3565
- (field) => field.binding === "array" && field.name === arrayName
3566
- );
3567
- const wiring = arrayItemWiring.current[arrayName] ?? (arrayItemWiring.current[arrayName] = /* @__PURE__ */ new Map());
3568
- if (binding) {
3569
- wireArrayItemEditing({
3570
- container,
3571
- arrayName,
3572
- itemFields: binding.itemFields,
3573
- componentId: id,
3574
- getPuck,
3575
- wiring
3576
- });
3577
- } else {
3578
- wiring.forEach(({ cleanup }) => cleanup());
3579
- wiring.clear();
3580
- }
3860
+ }
3861
+ config.components[name].fields = getSlotFields(registration.html ?? "");
3862
+ }
3863
+ let hasRemovals = false;
3864
+ for (const [name] of registrationStore.getAll()) {
3865
+ if (!(name in persisted)) {
3866
+ registrationStore.delete(name);
3867
+ lastSynced.delete(name);
3868
+ if (isDesignComponent(config.components[name])) {
3869
+ delete config.components[name];
3870
+ hasRemovals = true;
3581
3871
  }
3582
- appliedArrays.current = deferredFocus ? null : { el: entryEl, html, sig: arraySig };
3583
- }, [
3584
- arrayFields,
3585
- arraySig,
3586
- annotations,
3587
- entryEl,
3588
- html,
3589
- puck.isEditing,
3590
- id,
3591
- getPuck
3592
- ]);
3593
- (0, import_react14.useEffect)(
3594
- () => () => {
3595
- Object.values(arrayItemWiring.current).forEach(
3596
- (wiring) => wiring.forEach(({ cleanup }) => cleanup())
3597
- );
3598
- },
3599
- []
3872
+ }
3873
+ }
3874
+ if (createdSettled) {
3875
+ dispatch({ type: "setData", data: appState.data, recordHistory: false });
3876
+ }
3877
+ const designedComponents = Object.keys(persisted).filter(
3878
+ (name) => name in config.components
3879
+ );
3880
+ syncDesignedComponentsCategory(getPuck, designedComponents, hasRemovals);
3881
+ }
3882
+ function deleteDesignComponent(getPuck, name) {
3883
+ const { appState, config, dispatch } = getPuck();
3884
+ const filtered = (0, import_core4.walkTree)(
3885
+ appState.data,
3886
+ config,
3887
+ (content) => content.filter((item) => item.type !== name)
3888
+ );
3889
+ const dynamicConfig = getPersistedDynamicConfig(appState.data);
3890
+ const components = { ...dynamicConfig.components ?? {} };
3891
+ delete components[name];
3892
+ delete config.components[name];
3893
+ registrationStore.delete(name);
3894
+ const componentList = { ...appState.ui.componentList };
3895
+ const category = componentList[DESIGNED_CATEGORY];
3896
+ if (category) {
3897
+ const remaining = (category.components ?? []).filter(
3898
+ (c) => c !== name
3600
3899
  );
3601
- (0, import_react14.useEffect)(() => {
3602
- if (!script || !entryEl) return;
3603
- scriptRef.current?.remove();
3604
- const doc = entryEl.ownerDocument;
3605
- const el = doc.createElement("script");
3606
- el.textContent = wrapScriptWithObserverGuard(script);
3607
- doc.body.appendChild(el);
3608
- scriptRef.current = el;
3609
- return () => {
3610
- el.remove();
3611
- scriptRef.current = null;
3612
- };
3613
- }, [script, entryEl]);
3614
- if (!puck.isEditing) {
3615
- const slotContent = {};
3616
- for (const slot of annotations.slots) {
3617
- const Slot = props[slot.name];
3618
- if (typeof Slot === "function") {
3619
- slotContent[slot.name] = /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
3620
- Slot,
3621
- {
3622
- style: slot.style ? parseStyleString(slot.style) : void 0,
3623
- className: slot.className || void 0
3900
+ componentList[DESIGNED_CATEGORY] = {
3901
+ ...category,
3902
+ components: remaining,
3903
+ visible: remaining.length > 0
3904
+ };
3905
+ }
3906
+ dispatch({
3907
+ type: "set",
3908
+ state: {
3909
+ ...appState,
3910
+ data: {
3911
+ ...filtered,
3912
+ root: {
3913
+ ...filtered.root,
3914
+ props: {
3915
+ ...filtered.root.props ?? {},
3916
+ _dynamicConfig: {
3917
+ ...dynamicConfig,
3918
+ components
3624
3919
  }
3625
- );
3920
+ }
3626
3921
  }
3922
+ },
3923
+ ui: {
3924
+ ...appState.ui,
3925
+ itemSelector: null,
3926
+ componentList
3627
3927
  }
3628
- return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_jsx_runtime7.Fragment, { children: [
3629
- styles && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("style", { children: styles }),
3630
- style && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("style", { children: style }),
3631
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { ref: setEntryEl, ...fieldValueAttrs, children: htmlToReactTree(patchedHtml, slotContent) })
3632
- ] });
3633
3928
  }
3634
- return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_jsx_runtime7.Fragment, { children: [
3635
- styles && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("style", { children: styles }),
3636
- style && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("style", { children: style }),
3637
- editorEntryNode,
3638
- entryEl && annotations.slots.map((slot) => /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
3639
- SlotPortal,
3640
- {
3641
- entry: entryEl,
3642
- html,
3643
- slotName: slot.name,
3644
- slotStyle: slot.style,
3645
- slotClassName: slot.className,
3646
- SlotContent: props[slot.name]
3647
- },
3648
- slot.name
3649
- ))
3650
- ] });
3929
+ });
3930
+ }
3931
+
3932
+ // src/lib/wait-for-iframe-ready.ts
3933
+ init_react_import();
3934
+ var waitForNextPaint = (document2) => {
3935
+ const view = document2.defaultView;
3936
+ if (!view || document2.hidden) {
3937
+ return new Promise((resolve) => queueMicrotask(resolve));
3938
+ }
3939
+ return new Promise((resolve) => {
3940
+ let timeoutId;
3941
+ const frameId = view.requestAnimationFrame(() => {
3942
+ clearTimeout(timeoutId);
3943
+ resolve();
3944
+ });
3945
+ timeoutId = setTimeout(() => {
3946
+ view.cancelAnimationFrame(frameId);
3947
+ resolve();
3948
+ }, 100);
3949
+ });
3950
+ };
3951
+ var waitForImages = async (root, timeout) => {
3952
+ const pending = Array.from(root.querySelectorAll("img")).filter(
3953
+ (image) => !image.complete
3954
+ );
3955
+ if (pending.length === 0) return;
3956
+ let timeoutId;
3957
+ const cleanups = [];
3958
+ await Promise.race([
3959
+ Promise.allSettled(
3960
+ pending.map(
3961
+ (image) => new Promise((resolve) => {
3962
+ const cleanup = () => {
3963
+ image.removeEventListener("load", finish);
3964
+ image.removeEventListener("error", finish);
3965
+ };
3966
+ const finish = () => {
3967
+ cleanup();
3968
+ resolve();
3969
+ };
3970
+ cleanups.push(cleanup);
3971
+ image.addEventListener("load", finish);
3972
+ image.addEventListener("error", finish);
3973
+ })
3974
+ )
3975
+ ),
3976
+ new Promise((resolve) => {
3977
+ timeoutId = setTimeout(resolve, timeout);
3978
+ })
3979
+ ]);
3980
+ clearTimeout(timeoutId);
3981
+ cleanups.forEach((cleanup) => cleanup());
3982
+ };
3983
+ var waitForIframeReady = async (root, imageTimeout = 1e4) => {
3984
+ const document2 = root.ownerDocument;
3985
+ await waitForNextPaint(document2);
3986
+ await waitForNextPaint(document2);
3987
+ await waitForImages(root, imageTimeout);
3988
+ await waitForNextPaint(document2);
3989
+ };
3990
+
3991
+ // src/lib/to-serializable.ts
3992
+ init_react_import();
3993
+ function toSerializable(value, ancestors = []) {
3994
+ const json = typeof value === "object" && value !== null && "toJSON" in value && typeof value.toJSON === "function" ? value.toJSON() : value;
3995
+ if (typeof json !== "object" || json === null) {
3996
+ return typeof json === "function" || typeof json === "symbol" || typeof json === "bigint" ? void 0 : json;
3997
+ }
3998
+ if ("$$typeof" in json || ancestors.includes(json)) return void 0;
3999
+ ancestors.push(json);
4000
+ let copy;
4001
+ if (Array.isArray(json)) {
4002
+ copy = json.map((item) => toSerializable(item, ancestors) ?? null);
4003
+ } else {
4004
+ const record = json;
4005
+ const object = {};
4006
+ for (const key of Object.keys(record)) {
4007
+ const item = toSerializable(record[key], ancestors);
4008
+ if (item !== void 0) object[key] = item;
4009
+ }
4010
+ copy = object;
3651
4011
  }
4012
+ ancestors.pop();
4013
+ return copy;
3652
4014
  }
3653
4015
 
3654
- // src/lib/design/globals.tsx
4016
+ // src/lib/capture-screenshot.ts
3655
4017
  init_react_import();
3656
- var import_react15 = require("react");
3657
- var import_jsx_runtime8 = require("react/jsx-runtime");
3658
- function getDynamicConfigGlobals(dynamicConfig) {
3659
- if (typeof dynamicConfig !== "object" || dynamicConfig === null) return {};
3660
- const { styles, script } = dynamicConfig;
4018
+ var import_html2canvas_pro = __toESM(require("html2canvas-pro"));
4019
+
4020
+ // src/lib/screenshot-size.ts
4021
+ init_react_import();
4022
+ var MAX_WEBP_DIMENSION = 16383;
4023
+ var CAPTURE_SCALE = 2;
4024
+ var getFitRatio = (width, height, dimensionLimit = MAX_WEBP_DIMENSION) => {
4025
+ if (width <= 0 || height <= 0) return 1;
4026
+ return Math.min(1, dimensionLimit / Math.max(width, height));
4027
+ };
4028
+ var getCaptureScale = (width, height, scale) => scale * getFitRatio(width * scale, height * scale);
4029
+ var scaleDimension = (value, ratio) => Math.max(1, Math.floor(value * ratio));
4030
+ var getDocumentSize = (root) => {
4031
+ const { body, documentElement } = root.ownerDocument;
3661
4032
  return {
3662
- ...typeof styles === "string" ? { styles } : {},
3663
- ...typeof script === "string" ? { script } : {}
3664
- };
3665
- }
3666
- var INLINE_EDIT_RESET = ":where([data-puck-design] [contenteditable]){overflow-wrap:inherit;line-break:inherit;-webkit-nbsp-mode:inherit}";
3667
- function DesignGlobals({
3668
- styles,
3669
- script,
3670
- isEditing
3671
- }) {
3672
- const scriptRef = (0, import_react15.useRef)(null);
3673
- const hostRef = (0, import_react15.useRef)(null);
3674
- (0, import_react15.useEffect)(() => {
3675
- if (!script) return;
3676
- scriptRef.current?.remove();
3677
- const doc = hostRef.current?.ownerDocument ?? document;
3678
- const el = doc.createElement("script");
3679
- el.textContent = wrapScriptWithObserverGuard(script);
3680
- doc.body.appendChild(el);
3681
- scriptRef.current = el;
3682
- return () => {
3683
- el.remove();
3684
- scriptRef.current = null;
3685
- };
3686
- }, [script]);
3687
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(import_jsx_runtime8.Fragment, { children: [
3688
- isEditing && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("style", { children: INLINE_EDIT_RESET }),
3689
- styles && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("style", { children: styles }),
3690
- script && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { ref: hostRef, style: { display: "none" } })
3691
- ] });
3692
- }
3693
- var WRAPPED = "__puckAiDesignGlobals";
3694
- var isWrapped = (render) => typeof render === "function" && render[WRAPPED] === true;
3695
- function withDesignGlobals(root) {
3696
- if (isWrapped(root?.render)) return root;
3697
- const userRender = root?.render;
3698
- const render = (props) => {
3699
- const { styles, script } = getDynamicConfigGlobals(props._dynamicConfig);
3700
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(import_jsx_runtime8.Fragment, { children: [
3701
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
3702
- DesignGlobals,
3703
- {
3704
- styles,
3705
- script,
3706
- isEditing: props.puck?.isEditing
3707
- }
3708
- ),
3709
- userRender ? userRender(props) : props.children
3710
- ] });
4033
+ width: Math.max(
4034
+ body?.scrollWidth ?? 0,
4035
+ body?.offsetWidth ?? 0,
4036
+ body?.clientWidth ?? 0,
4037
+ documentElement?.scrollWidth ?? 0,
4038
+ documentElement?.offsetWidth ?? 0,
4039
+ documentElement?.clientWidth ?? 0
4040
+ ),
4041
+ height: Math.max(
4042
+ body?.scrollHeight ?? 0,
4043
+ body?.offsetHeight ?? 0,
4044
+ body?.clientHeight ?? 0,
4045
+ documentElement?.scrollHeight ?? 0,
4046
+ documentElement?.offsetHeight ?? 0,
4047
+ documentElement?.clientHeight ?? 0
4048
+ )
3711
4049
  };
3712
- render[WRAPPED] = true;
3713
- return { ...root, render };
3714
- }
3715
- function ensureDesignGlobalsRoot(config) {
3716
- if (!config.root) config.root = {};
3717
- if (isWrapped(config.root.render)) return false;
3718
- config.root.render = withDesignGlobals(config.root).render;
3719
- return true;
4050
+ };
4051
+
4052
+ // src/lib/screenshot-overflow.ts
4053
+ init_react_import();
4054
+ var applyBrowserOverflowStylesTo = (document2) => {
4055
+ for (const element of [document2.documentElement, document2.body]) {
4056
+ element?.style.setProperty("overflow", "visible", "important");
4057
+ }
4058
+ };
4059
+
4060
+ // src/lib/capture-screenshot.ts
4061
+ var editorOnlyClassPrefixes = ["_DraggableComponent--hover", "_ActionBar"];
4062
+ var releaseCanvas = (canvas) => {
4063
+ canvas.width = 0;
4064
+ canvas.height = 0;
4065
+ };
4066
+ var drawScaled = (source, ratio) => {
4067
+ const target = document.createElement("canvas");
4068
+ target.width = scaleDimension(source.width, ratio);
4069
+ target.height = scaleDimension(source.height, ratio);
4070
+ const ctx = target.getContext("2d");
4071
+ if (!ctx) {
4072
+ releaseCanvas(target);
4073
+ return source;
4074
+ }
4075
+ ctx.imageSmoothingEnabled = true;
4076
+ ctx.imageSmoothingQuality = "high";
4077
+ ctx.drawImage(source, 0, 0, target.width, target.height);
4078
+ return target;
4079
+ };
4080
+ var fitCanvas = (canvas) => {
4081
+ let remaining = getFitRatio(canvas.width, canvas.height);
4082
+ if (remaining >= 1) return canvas;
4083
+ let current = canvas;
4084
+ while (remaining < 0.5) {
4085
+ const next = drawScaled(current, 0.5);
4086
+ if (current !== canvas) releaseCanvas(current);
4087
+ current = next;
4088
+ remaining *= 2;
4089
+ }
4090
+ const fitted = drawScaled(current, remaining);
4091
+ if (current !== canvas) releaseCanvas(current);
4092
+ return fitted;
4093
+ };
4094
+ var toWebp = (canvas, quality) => new Promise((resolve, reject) => {
4095
+ canvas.toBlob(
4096
+ (blob) => {
4097
+ if (blob && blob.size > 0) {
4098
+ resolve(blob);
4099
+ return;
4100
+ }
4101
+ reject(
4102
+ new Error(
4103
+ `Could not encode a ${canvas.width}x${canvas.height} canvas as WebP`
4104
+ )
4105
+ );
4106
+ },
4107
+ "image/webp",
4108
+ quality
4109
+ );
4110
+ });
4111
+ var captureScreenshot = async (root, { scale = CAPTURE_SCALE, quality = 0.8, width } = {}) => {
4112
+ const documentSize = getDocumentSize(root);
4113
+ const safeWebPScale = getCaptureScale(
4114
+ width ?? documentSize.width,
4115
+ documentSize.height,
4116
+ scale
4117
+ );
4118
+ const canvas = await (0, import_html2canvas_pro.default)(root, {
4119
+ scale: safeWebPScale,
4120
+ backgroundColor: "#ffffff",
4121
+ ...width === void 0 ? {} : { width, windowWidth: width },
4122
+ foreignObjectRendering: false,
4123
+ imageTimeout: 3e4,
4124
+ logging: false,
4125
+ allowTaint: false,
4126
+ useCORS: true,
4127
+ scrollY: 0,
4128
+ onclone: applyBrowserOverflowStylesTo,
4129
+ ignoreElements: (el) => Array.from(el.classList).some(
4130
+ (c) => editorOnlyClassPrefixes.some((prefix) => c.startsWith(prefix))
4131
+ )
4132
+ });
4133
+ const fitted = fitCanvas(canvas);
4134
+ try {
4135
+ return await toWebp(fitted, quality);
4136
+ } finally {
4137
+ if (fitted !== canvas) releaseCanvas(fitted);
4138
+ releaseCanvas(canvas);
4139
+ }
4140
+ };
4141
+
4142
+ // src/lib/client-tool-response.ts
4143
+ init_react_import();
4144
+ async function postClientToolResponse(host, body, {
4145
+ headers,
4146
+ credentials,
4147
+ signal
4148
+ } = {}) {
4149
+ const response = await fetch(`${host.replace(/\/+$/, "")}/tool`, {
4150
+ method: "POST",
4151
+ headers: { "Content-Type": "application/json", ...headers },
4152
+ credentials,
4153
+ body: JSON.stringify(body),
4154
+ signal
4155
+ });
4156
+ if (!response.ok) {
4157
+ throw new Error(
4158
+ `Client tool endpoint returned ${response.status} ${response.statusText}`.trim()
4159
+ );
4160
+ }
3720
4161
  }
3721
4162
 
3722
- // src/lib/design/runtime.tsx
3723
- var import_jsx_runtime9 = require("react/jsx-runtime");
3724
- var cachedFieldMetadata;
3725
- function detectFieldMetadata(config) {
3726
- for (const comp of Object.values(config.components)) {
3727
- for (const field of Object.values(comp.fields ?? {})) {
3728
- const meta = field?.metadata;
3729
- if (meta && typeof meta === "object" && Object.keys(meta).length > 0) {
3730
- return { ...meta };
4163
+ // ../utils/lib/iterate-sse.ts
4164
+ init_react_import();
4165
+ async function* iterateSSE(body) {
4166
+ const reader = body.getReader();
4167
+ const dec = new TextDecoder();
4168
+ let buf = "";
4169
+ try {
4170
+ while (true) {
4171
+ const { done, value } = await reader.read();
4172
+ if (done) break;
4173
+ buf += dec.decode(value, { stream: true });
4174
+ let idx;
4175
+ while ((idx = buf.indexOf("\n\n")) >= 0) {
4176
+ const chunk = buf.slice(0, idx).trim();
4177
+ buf = buf.slice(idx + 2);
4178
+ if (!chunk) continue;
4179
+ const line = chunk.startsWith("data: ") ? chunk.slice(6) : chunk;
4180
+ try {
4181
+ yield JSON.parse(line);
4182
+ } catch {
4183
+ }
3731
4184
  }
3732
4185
  }
4186
+ } finally {
4187
+ reader.cancel().catch(() => {
4188
+ });
4189
+ reader.releaseLock();
3733
4190
  }
3734
- return null;
3735
- }
3736
- function addFieldMetadata(fields, metadata) {
3737
- const out = {};
3738
- for (const [key, field] of Object.entries(fields)) {
3739
- out[key] = field && typeof field === "object" ? { ...field, metadata: { ...field.metadata, ...metadata } } : field;
3740
- }
3741
- return out;
3742
4191
  }
3743
- function applyFieldMetadata(componentConfig, metadata) {
3744
- const origResolveFields = componentConfig.resolveFields;
3745
- componentConfig.resolveFields = async (data, params) => {
3746
- const fields = origResolveFields ? await origResolveFields(data, params) : componentConfig.fields ?? {};
3747
- return addFieldMetadata(fields, metadata);
4192
+
4193
+ // src/lib/use-puck-ai.ts
4194
+ var q = (0, import_qler.default)();
4195
+ var usePuck2 = (0, import_core5.createUsePuck)();
4196
+ var DEFAULT_API_VERSION = "v2";
4197
+ var BUILD_OP_DEBOUNCE_MS = 1e3 / 60;
4198
+ 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.";
4199
+ var PLUGIN_AI_VERSION = true ? "0.9.0-canary.e72fdf32" : "unknown";
4200
+ var prefixedUlid = (prefix = "") => `${prefix ? `${prefix}_` : ""}${(0, import_ulid.ulid)()}`;
4201
+ async function prepareRequestOptions(defaults, prepareRequest) {
4202
+ if (!prepareRequest) return defaults;
4203
+ const userOptions = await prepareRequest(defaults);
4204
+ return {
4205
+ headers: { ...defaults.headers, ...userOptions.headers },
4206
+ credentials: userOptions.credentials ?? defaults.credentials,
4207
+ body: { ...defaults.body, ...userOptions.body }
3748
4208
  };
3749
4209
  }
3750
- function applyConfigFieldMetadata(config, dynamicComponents) {
3751
- const metadata = detectFieldMetadata(config);
3752
- if (!metadata) return;
3753
- for (const name of Object.keys(dynamicComponents)) {
3754
- if (config.components[name]) {
3755
- applyFieldMetadata(config.components[name], metadata);
3756
- }
3757
- }
3758
- }
3759
- var DESIGNED_CATEGORY = "dynamic";
3760
- var dynamicConfigRootField = {
3761
- type: "custom",
3762
- render: () => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", {}),
3763
- ai: {
3764
- exclude: true
3765
- }
3766
- };
3767
- function ensureDynamicConfigField(config) {
3768
- if (!config.root) config.root = {};
3769
- if (!config.root.fields) config.root.fields = {};
3770
- if (!config.root.fields._dynamicConfig) {
3771
- config.root.fields._dynamicConfig = dynamicConfigRootField;
3772
- }
3773
- }
3774
- function getPersistedDynamicConfig(data) {
3775
- return data?.root?.props?._dynamicConfig ?? {};
3776
- }
3777
- function getPersistedRegistrations(data) {
3778
- return getPersistedDynamicConfig(data).components;
3779
- }
3780
- function getRequestComponentConfigs(data) {
3781
- const registrations = getPersistedRegistrations(data);
3782
- const components = {};
3783
- if (!registrations) return components;
3784
- for (const [name, registration] of Object.entries(registrations)) {
3785
- components[name] = {
3786
- ...registration.label ? { label: registration.label } : {},
3787
- fields: { ...registration.fields ?? {} },
3788
- ...registration.defaultProps ? { defaultProps: { ...registration.defaultProps } } : {},
3789
- render: () => null
4210
+ var abortError = () => new DOMException("The generation was cancelled.", "AbortError");
4211
+ var untilAborted = (promise, signal) => new Promise((resolve, reject) => {
4212
+ const onAbort = () => reject(abortError());
4213
+ if (signal.aborted) return onAbort();
4214
+ signal.addEventListener("abort", onAbort, { once: true });
4215
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
4216
+ });
4217
+ function usePuckAiInternal({
4218
+ host = "/api/puck/chat",
4219
+ mode = "assembly",
4220
+ apiVersion = DEFAULT_API_VERSION,
4221
+ prepareRequest,
4222
+ onFinish,
4223
+ onError
4224
+ } = {}) {
4225
+ const puckDispatch = usePuck2((s) => s.dispatch);
4226
+ const getPuck = (0, import_core5.useGetPuck)();
4227
+ const localChatId = (0, import_react17.useRef)("");
4228
+ const pendingBuildOpsRef = (0, import_react17.useRef)([]);
4229
+ const clientToolEndpointUnavailableRef = (0, import_react17.useRef)(false);
4230
+ const stopRef = (0, import_react17.useRef)(null);
4231
+ const generateAbortRef = (0, import_react17.useRef)(null);
4232
+ const unmountedRef = (0, import_react17.useRef)(false);
4233
+ const lastStreamActivityRef = (0, import_react17.useRef)(0);
4234
+ const hiddenSinceRef = (0, import_react17.useRef)(null);
4235
+ const [error, setError] = (0, import_react17.useState)();
4236
+ const [toolStatus, setToolStatus] = (0, import_react17.useState)({});
4237
+ const [subagentState, setSubagentState] = (0, import_react17.useState)({});
4238
+ const modeRef = (0, import_react17.useRef)(mode);
4239
+ const onErrorRef = (0, import_react17.useRef)(onError);
4240
+ (0, import_react17.useEffect)(() => {
4241
+ onErrorRef.current = onError;
4242
+ }, [onError]);
4243
+ (0, import_react17.useEffect)(() => {
4244
+ modeRef.current = mode;
4245
+ }, [mode]);
4246
+ const puckData = usePuck2((s) => s.appState.data);
4247
+ (0, import_react17.useEffect)(() => {
4248
+ syncDesignComponents(getPuck);
4249
+ }, [puckData, getPuck]);
4250
+ const debouncedFlushBuildOps = (0, import_use_debounce.useDebouncedCallback)(
4251
+ () => {
4252
+ const operations = pendingBuildOpsRef.current;
4253
+ pendingBuildOpsRef.current = [];
4254
+ if (operations.length === 0) return;
4255
+ q.queue(
4256
+ () => new Promise((resolve) => {
4257
+ nextFrame(() => {
4258
+ const { dispatch, config, resolveDataById } = getPuck();
4259
+ operations.forEach((queuedOperation) => {
4260
+ (0, import_reducer.dispatchOp)(queuedOperation, {
4261
+ getState: () => {
4262
+ const { __private } = getPuck();
4263
+ return __private.appState;
4264
+ },
4265
+ dispatchAction: dispatch,
4266
+ config
4267
+ });
4268
+ if (queuedOperation.op === "add" || queuedOperation.op === "update") {
4269
+ resolveDataById(queuedOperation.id, "replace");
4270
+ }
4271
+ if (queuedOperation.op === "updateRoot") {
4272
+ syncDesignComponents(getPuck);
4273
+ }
4274
+ });
4275
+ resolve();
4276
+ });
4277
+ })
4278
+ );
4279
+ },
4280
+ BUILD_OP_DEBOUNCE_MS,
4281
+ { maxWait: BUILD_OP_DEBOUNCE_MS }
4282
+ );
4283
+ const queueBuildOp = (0, import_react17.useCallback)(
4284
+ (operation) => {
4285
+ pendingBuildOpsRef.current.push(operation);
4286
+ debouncedFlushBuildOps();
4287
+ },
4288
+ [debouncedFlushBuildOps]
4289
+ );
4290
+ const handleClientToolEndpointUnavailable = (0, import_react17.useCallback)(() => {
4291
+ if (clientToolEndpointUnavailableRef.current) return;
4292
+ clientToolEndpointUnavailableRef.current = true;
4293
+ setError(CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE);
4294
+ console.error(CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE);
4295
+ onErrorRef.current?.(
4296
+ new Error(CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE)
4297
+ );
4298
+ setToolStatus(
4299
+ (current) => finishLoadingTools(current, "Verification unavailable")
4300
+ );
4301
+ stopRef.current?.();
4302
+ }, []);
4303
+ const prepare = (0, import_react17.useCallback)(
4304
+ (defaults) => prepareRequestOptions(defaults, prepareRequest),
4305
+ [prepareRequest]
4306
+ );
4307
+ const sendClientToolResponse = (0, import_react17.useCallback)(
4308
+ async (body, signal) => {
4309
+ const request = await prepare({ body });
4310
+ try {
4311
+ await postClientToolResponse(host, request.body, {
4312
+ headers: request.headers,
4313
+ credentials: request.credentials,
4314
+ signal
4315
+ });
4316
+ } catch (e) {
4317
+ if (signal?.aborted) throw e;
4318
+ throw new Error(CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE);
4319
+ }
4320
+ },
4321
+ [host, prepare]
4322
+ );
4323
+ const clearError = (0, import_react17.useCallback)(() => {
4324
+ clientToolEndpointUnavailableRef.current = false;
4325
+ setError(void 0);
4326
+ }, []);
4327
+ const applyToEditor = (0, import_react17.useCallback)(
4328
+ async (dataPart, { chatId, signal } = {}) => {
4329
+ if (dataPart.type.indexOf("data-") !== 0) {
4330
+ return;
4331
+ }
4332
+ switch (dataPart.type) {
4333
+ case "data-puck-actions": {
4334
+ dataPart.data.forEach((action) => {
4335
+ try {
4336
+ puckDispatch(action);
4337
+ } catch (e) {
4338
+ console.error("Bad action: ", action);
4339
+ console.error(e);
4340
+ }
4341
+ });
4342
+ return;
4343
+ }
4344
+ case "data-build-op": {
4345
+ const { pageId, ...operation } = dataPart.data;
4346
+ if (pageId) {
4347
+ return;
4348
+ }
4349
+ queueBuildOp(operation);
4350
+ return;
4351
+ }
4352
+ case "data-client-request": {
4353
+ const request = dataPart.data;
4354
+ debouncedFlushBuildOps.flush();
4355
+ await q.wait();
4356
+ if (signal?.aborted) return;
4357
+ let output;
4358
+ if (request.action === "getPageData") {
4359
+ output = getPuck().appState.data;
4360
+ } else {
4361
+ const blob = await uploadPreviewScreenshot(request.params.putUrl, {
4362
+ signal
4363
+ }).catch((e) => {
4364
+ console.error("Failed to capture the screenshot:", e);
4365
+ return null;
4366
+ });
4367
+ output = { sizeBytes: blob?.size ?? 0 };
4368
+ }
4369
+ if (signal?.aborted) return;
4370
+ await sendClientToolResponse(
4371
+ {
4372
+ id: request.requestId,
4373
+ chatId,
4374
+ responses: [{ action: request.action, output }]
4375
+ },
4376
+ signal
4377
+ );
4378
+ return;
4379
+ }
4380
+ case "data-send-screenshot": {
4381
+ dataPart.data.urls.forEach((obj) => {
4382
+ const [entry] = Object.entries(obj);
4383
+ if (!entry) return;
4384
+ const [key, value] = entry;
4385
+ uploadPreviewScreenshot(value, { width: Number(key) }).catch(
4386
+ (e) => console.error("Failed to upload screenshot", e)
4387
+ );
4388
+ });
4389
+ return;
4390
+ }
4391
+ case "data-finish": {
4392
+ debouncedFlushBuildOps.flush();
4393
+ return;
4394
+ }
4395
+ case "data-page": {
4396
+ return;
4397
+ }
4398
+ case "data-version-notice": {
4399
+ console.warn(dataPart.data.message);
4400
+ return;
4401
+ }
4402
+ // The chat's progress, which only its own UI shows
4403
+ case "data-new-chat-created":
4404
+ case "data-tool-status":
4405
+ case "data-subagent-event": {
4406
+ return;
4407
+ }
4408
+ default:
4409
+ console.warn("dataPart without case:", dataPart);
4410
+ return;
4411
+ }
4412
+ },
4413
+ [
4414
+ debouncedFlushBuildOps,
4415
+ getPuck,
4416
+ puckDispatch,
4417
+ queueBuildOp,
4418
+ sendClientToolResponse
4419
+ ]
4420
+ );
4421
+ const applyChatPart = (0, import_react17.useCallback)(
4422
+ (dataPart) => {
4423
+ lastStreamActivityRef.current = Date.now();
4424
+ switch (dataPart.type) {
4425
+ case "data-new-chat-created": {
4426
+ localChatId.current = dataPart.data.chatId;
4427
+ return;
4428
+ }
4429
+ case "data-tool-status": {
4430
+ setToolStatus((s) => ({
4431
+ ...s,
4432
+ [dataPart.data.toolCallId]: dataPart.data.status
4433
+ }));
4434
+ return;
4435
+ }
4436
+ case "data-subagent-event": {
4437
+ setSubagentState(
4438
+ (current) => reduceSubagentEvent(current, dataPart.data)
4439
+ );
4440
+ return;
4441
+ }
4442
+ }
4443
+ applyToEditor(dataPart, {
4444
+ chatId: localChatId.current || void 0
4445
+ }).catch(handleClientToolEndpointUnavailable);
4446
+ },
4447
+ [applyToEditor, handleClientToolEndpointUnavailable]
4448
+ );
4449
+ const getRequestConfig = (0, import_react17.useCallback)(() => {
4450
+ const { config, appState } = getPuck();
4451
+ const root = config.root ?? {
4452
+ fields: {
4453
+ title: {
4454
+ type: "text",
4455
+ ai: { instructions: "The title for the page" }
4456
+ }
4457
+ }
3790
4458
  };
3791
- }
3792
- return components;
3793
- }
3794
- function syncDesignedComponentsCategory(getPuck, designedComponents, hadRemovals) {
3795
- const { appState, dispatch } = getPuck();
3796
- const componentList = { ...appState.ui.componentList };
3797
- const existing = componentList[DESIGNED_CATEGORY];
3798
- const current = existing?.components ?? [];
3799
- const unchanged = current.length === designedComponents.length && current.every((name, i) => name === designedComponents[i]);
3800
- if (unchanged && !hadRemovals) return;
3801
- componentList[DESIGNED_CATEGORY] = {
3802
- title: "Generated",
3803
- expanded: true,
3804
- ...existing,
3805
- components: designedComponents,
3806
- visible: designedComponents.length > 0
3807
- };
3808
- dispatch({ type: "setUi", ui: { componentList } });
3809
- }
3810
- var lastSynced = /* @__PURE__ */ new Map();
3811
- 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;
3812
- function syncDesignComponents(getPuck) {
3813
- const { config, appState, dispatch } = getPuck();
3814
- const persisted = getPersistedRegistrations(appState.data) ?? {};
3815
- if (cachedFieldMetadata === void 0) {
3816
- cachedFieldMetadata = detectFieldMetadata(config);
3817
- }
3818
- let createdSettled = ensureDesignGlobalsRoot(config);
3819
- ensureDynamicConfigField(config);
3820
- for (const [name, persistedReg] of Object.entries(persisted)) {
3821
- const prev = lastSynced.get(name);
3822
- if (registrationStore.has(name) && config.components[name] && (prev === persistedReg || registrationContentEqual(prev, persistedReg))) {
3823
- lastSynced.set(name, persistedReg);
3824
- continue;
3825
- }
3826
- lastSynced.set(name, persistedReg);
3827
- const registration = registrationStore.apply({ ...persistedReg, name });
3828
- const isSettled = !registration.streaming;
3829
- if (!config.components[name] || !prev) {
3830
- ensureDynamicConfigField(config);
3831
- const componentConfig = createDesignComponentConfig(registration);
3832
- if (cachedFieldMetadata) {
3833
- applyFieldMetadata(componentConfig, cachedFieldMetadata);
4459
+ return toSerializable({
4460
+ ...config,
4461
+ root,
4462
+ components: {
4463
+ ...config.components,
4464
+ ...getRequestComponentConfigs(appState.data)
3834
4465
  }
3835
- config.components[name] = componentConfig;
3836
- if (isSettled) createdSettled = true;
3837
- } else {
3838
- if (registration.label)
3839
- config.components[name].label = registration.label;
3840
- if (isSettled) {
3841
- config.components[name].defaultProps = {
3842
- ...registration.defaultProps ?? {}
3843
- };
4466
+ });
4467
+ }, [getPuck]);
4468
+ const settle = (0, import_react17.useCallback)(
4469
+ async ({ recordHistory = true } = {}) => {
4470
+ debouncedFlushBuildOps.flush();
4471
+ await q.wait();
4472
+ if (recordHistory && !unmountedRef.current) {
4473
+ puckDispatch({
4474
+ type: "set",
4475
+ state: getPuck().appState,
4476
+ recordHistory: true
4477
+ });
3844
4478
  }
3845
- }
3846
- config.components[name].fields = getSlotFields(registration.html ?? "");
3847
- }
3848
- let hasRemovals = false;
3849
- for (const [name] of registrationStore.getAll()) {
3850
- if (!(name in persisted)) {
3851
- registrationStore.delete(name);
3852
- lastSynced.delete(name);
3853
- if (isDesignComponent(config.components[name])) {
3854
- delete config.components[name];
3855
- hasRemovals = true;
4479
+ },
4480
+ [debouncedFlushBuildOps, getPuck, puckDispatch]
4481
+ );
4482
+ const {
4483
+ messages,
4484
+ status: chatStatus,
4485
+ sendMessage: chatSendMessage,
4486
+ regenerate,
4487
+ setMessages,
4488
+ stop
4489
+ } = useChat({
4490
+ generateId: () => prefixedUlid("msg"),
4491
+ messages: [],
4492
+ transport: new import_ai5.DefaultChatTransport({
4493
+ api: host,
4494
+ prepareSendMessagesRequest: async (opts) => {
4495
+ const { appState } = getPuck();
4496
+ const configWithRoot = getRequestConfig();
4497
+ return prepare({
4498
+ headers: {
4499
+ ...opts.headers,
4500
+ "puck-api-version": apiVersion,
4501
+ "x-puck-plugin-ai-version": PLUGIN_AI_VERSION
4502
+ },
4503
+ credentials: opts.credentials,
4504
+ body: {
4505
+ ...opts.body,
4506
+ chatId: localChatId.current,
4507
+ trigger: opts.trigger,
4508
+ messages: opts.messages,
4509
+ pageData: appState.data,
4510
+ config: configWithRoot,
4511
+ mode: opts.body?.mode ?? modeRef.current
4512
+ }
4513
+ });
4514
+ }
4515
+ }),
4516
+ onData: applyChatPart,
4517
+ onError: (e) => {
4518
+ console.error(e);
4519
+ if (!clientToolEndpointUnavailableRef.current) {
4520
+ setError(e.message);
4521
+ }
4522
+ onError?.(e);
4523
+ },
4524
+ onFinish: (options) => {
4525
+ if (options.isAbort || options.isDisconnect || options.isError) {
4526
+ setToolStatus((current) => finishLoadingTools(current, "Interrupted"));
3856
4527
  }
4528
+ settle().then(() => onFinish?.(options));
3857
4529
  }
3858
- }
3859
- if (createdSettled) {
3860
- dispatch({ type: "setData", data: appState.data, recordHistory: false });
3861
- }
3862
- const designedComponents = Object.keys(persisted).filter(
3863
- (name) => name in config.components
4530
+ });
4531
+ const sendMessage = (0, import_react17.useCallback)(
4532
+ async (prompt, opts = {}) => {
4533
+ const text = prompt.trim();
4534
+ const files = opts.files ?? [];
4535
+ if (!text && files.length === 0) return;
4536
+ clearError();
4537
+ await chatSendMessage(
4538
+ {
4539
+ role: "user",
4540
+ parts: [...text ? [{ type: "text", text }] : [], ...files]
4541
+ },
4542
+ opts.mode ? { body: { mode: opts.mode } } : void 0
4543
+ );
4544
+ },
4545
+ [chatSendMessage, clearError]
3864
4546
  );
3865
- syncDesignedComponentsCategory(getPuck, designedComponents, hasRemovals);
3866
- }
3867
- function deleteDesignComponent(getPuck, name) {
3868
- const { appState, config, dispatch } = getPuck();
3869
- const filtered = (0, import_core4.walkTree)(
3870
- appState.data,
3871
- config,
3872
- (content) => content.filter((item) => item.type !== name)
4547
+ const regenerateTurn = (0, import_react17.useCallback)(
4548
+ (...args) => {
4549
+ clearError();
4550
+ return regenerate(...args);
4551
+ },
4552
+ [clearError, regenerate]
3873
4553
  );
3874
- const dynamicConfig = getPersistedDynamicConfig(appState.data);
3875
- const components = { ...dynamicConfig.components ?? {} };
3876
- delete components[name];
3877
- delete config.components[name];
3878
- registrationStore.delete(name);
3879
- const componentList = { ...appState.ui.componentList };
3880
- const category = componentList[DESIGNED_CATEGORY];
3881
- if (category) {
3882
- const remaining = (category.components ?? []).filter(
3883
- (c) => c !== name
3884
- );
3885
- componentList[DESIGNED_CATEGORY] = {
3886
- ...category,
3887
- components: remaining,
3888
- visible: remaining.length > 0
3889
- };
3890
- }
3891
- dispatch({
3892
- type: "set",
3893
- state: {
3894
- ...appState,
3895
- data: {
3896
- ...filtered,
3897
- root: {
3898
- ...filtered.root,
3899
- props: {
3900
- ...filtered.root.props ?? {},
3901
- _dynamicConfig: {
3902
- ...dynamicConfig,
3903
- components
4554
+ const applyPart = (0, import_react17.useCallback)(
4555
+ async (part, { recordHistory = false } = {}) => {
4556
+ await applyToEditor(part);
4557
+ if (recordHistory) await settle();
4558
+ },
4559
+ [applyToEditor, settle]
4560
+ );
4561
+ const generate = (0, import_react17.useCallback)(
4562
+ async (prompt, opts = {}) => {
4563
+ const text = prompt.trim();
4564
+ if (!text) return getPuck().appState.data;
4565
+ generateAbortRef.current?.abort();
4566
+ const controller = new AbortController();
4567
+ const cancel = () => controller.abort();
4568
+ generateAbortRef.current = controller;
4569
+ let changed = false;
4570
+ if (opts.signal?.aborted) cancel();
4571
+ opts.signal?.addEventListener("abort", cancel, { once: true });
4572
+ try {
4573
+ debouncedFlushBuildOps.flush();
4574
+ await q.wait();
4575
+ const { appState } = getPuck();
4576
+ const request = await untilAborted(
4577
+ prepare({
4578
+ headers: {
4579
+ "Content-Type": "application/json",
4580
+ "puck-api-version": apiVersion,
4581
+ "x-puck-plugin-ai-version": PLUGIN_AI_VERSION
4582
+ },
4583
+ body: {
4584
+ prompt: text,
4585
+ config: getRequestConfig(),
4586
+ pageData: appState.data,
4587
+ mode: opts.mode ?? modeRef.current
3904
4588
  }
4589
+ }),
4590
+ controller.signal
4591
+ );
4592
+ const response = await fetch(`${host.replace(/\/+$/, "")}/generate`, {
4593
+ method: "POST",
4594
+ headers: request.headers,
4595
+ credentials: request.credentials,
4596
+ body: JSON.stringify(request.body),
4597
+ signal: controller.signal
4598
+ });
4599
+ if (!response.ok || !response.body) {
4600
+ const body = await response.json().catch(() => null);
4601
+ throw new Error(
4602
+ body?.error ?? `Puck AI request failed: ${response.status} ${response.statusText}`
4603
+ );
4604
+ }
4605
+ for await (const part of iterateSSE(response.body)) {
4606
+ if (controller.signal.aborted) throw abortError();
4607
+ if (part.type === "error") throw new Error(part.errorText);
4608
+ if (part.type === "data-build-op" || part.type === "data-puck-actions") {
4609
+ changed = true;
3905
4610
  }
4611
+ await untilAborted(
4612
+ applyToEditor(part, { signal: controller.signal }),
4613
+ controller.signal
4614
+ );
4615
+ }
4616
+ if (controller.signal.aborted) throw abortError();
4617
+ await settle();
4618
+ return getPuck().appState.data;
4619
+ } catch (e) {
4620
+ await settle({ recordHistory: changed });
4621
+ throw controller.signal.aborted ? abortError() : e;
4622
+ } finally {
4623
+ opts.signal?.removeEventListener("abort", cancel);
4624
+ controller.abort();
4625
+ if (generateAbortRef.current === controller) {
4626
+ generateAbortRef.current = null;
3906
4627
  }
3907
- },
3908
- ui: {
3909
- ...appState.ui,
3910
- itemSelector: null,
3911
- componentList
3912
4628
  }
3913
- }
3914
- });
3915
- }
3916
-
3917
- // src/lib/wait-for-iframe-ready.ts
3918
- init_react_import();
3919
- var waitForNextPaint = (document2) => {
3920
- const view = document2.defaultView;
3921
- if (!view || document2.hidden) {
3922
- return new Promise((resolve) => queueMicrotask(resolve));
3923
- }
3924
- return new Promise((resolve) => {
3925
- let timeoutId;
3926
- const frameId = view.requestAnimationFrame(() => {
3927
- clearTimeout(timeoutId);
3928
- resolve();
3929
- });
3930
- timeoutId = setTimeout(() => {
3931
- view.cancelAnimationFrame(frameId);
3932
- resolve();
3933
- }, 100);
3934
- });
3935
- };
3936
- var waitForImages = async (root, timeout) => {
3937
- const pending = Array.from(root.querySelectorAll("img")).filter(
3938
- (image) => !image.complete
4629
+ },
4630
+ [
4631
+ apiVersion,
4632
+ applyToEditor,
4633
+ debouncedFlushBuildOps,
4634
+ getPuck,
4635
+ host,
4636
+ getRequestConfig,
4637
+ prepare,
4638
+ settle
4639
+ ]
4640
+ );
4641
+ (0, import_react17.useEffect)(() => {
4642
+ unmountedRef.current = false;
4643
+ stopRef.current = stop;
4644
+ return () => {
4645
+ unmountedRef.current = true;
4646
+ stopRef.current = null;
4647
+ generateAbortRef.current?.abort();
4648
+ stop();
4649
+ };
4650
+ }, [stop]);
4651
+ const chatStatusRef = (0, import_react17.useRef)(chatStatus);
4652
+ (0, import_react17.useEffect)(() => {
4653
+ chatStatusRef.current = chatStatus;
4654
+ }, [chatStatus]);
4655
+ (0, import_react17.useEffect)(() => {
4656
+ lastStreamActivityRef.current = Date.now();
4657
+ }, [messages]);
4658
+ (0, import_react17.useEffect)(() => {
4659
+ const FROZEN_HIDDEN_MS = 3 * 6e4;
4660
+ const RESUME_GRACE_MS = 12e3;
4661
+ const isStreaming = () => chatStatusRef.current === "streaming" || chatStatusRef.current === "submitted";
4662
+ let graceTimer;
4663
+ const recoverIfSevered = () => {
4664
+ if (!isStreaming()) return;
4665
+ if (Date.now() - lastStreamActivityRef.current < RESUME_GRACE_MS) return;
4666
+ stop();
4667
+ setToolStatus((current) => finishLoadingTools(current, "Interrupted"));
4668
+ };
4669
+ const onVisibilityChange = () => {
4670
+ if (document.hidden) {
4671
+ hiddenSinceRef.current = isStreaming() ? Date.now() : null;
4672
+ return;
4673
+ }
4674
+ const hiddenSince = hiddenSinceRef.current;
4675
+ hiddenSinceRef.current = null;
4676
+ if (graceTimer) clearTimeout(graceTimer);
4677
+ if (hiddenSince === null || Date.now() - hiddenSince < FROZEN_HIDDEN_MS) {
4678
+ return;
4679
+ }
4680
+ lastStreamActivityRef.current = 0;
4681
+ graceTimer = setTimeout(recoverIfSevered, RESUME_GRACE_MS);
4682
+ };
4683
+ document.addEventListener("visibilitychange", onVisibilityChange);
4684
+ return () => {
4685
+ document.removeEventListener("visibilitychange", onVisibilityChange);
4686
+ if (graceTimer) clearTimeout(graceTimer);
4687
+ };
4688
+ }, [stop]);
4689
+ const chat = (0, import_react17.useMemo)(
4690
+ () => ({
4691
+ /** Send a new message to the agent. */
4692
+ sendMessage,
4693
+ /** Run the conversation's last turn again. */
4694
+ regenerate: regenerateTurn,
4695
+ /** Stop the running turn. */
4696
+ stop,
4697
+ /** The conversation's AI SDK status. */
4698
+ status: chatStatus,
4699
+ /** The last chat error's message, or `undefined`. Also passed to `onError`. */
4700
+ error,
4701
+ /** The conversation, as AI SDK `UIMessage`s. */
4702
+ messages,
4703
+ /** The live progress of the agent's tools, keyed by tool call id. */
4704
+ toolStatus
4705
+ }),
4706
+ [chatStatus, error, messages, regenerateTurn, sendMessage, stop, toolStatus]
3939
4707
  );
3940
- if (pending.length === 0) return;
3941
- let timeoutId;
3942
- const cleanups = [];
3943
- await Promise.race([
3944
- Promise.allSettled(
3945
- pending.map(
3946
- (image) => new Promise((resolve) => {
3947
- const cleanup = () => {
3948
- image.removeEventListener("load", finish);
3949
- image.removeEventListener("error", finish);
3950
- };
3951
- const finish = () => {
3952
- cleanup();
3953
- resolve();
3954
- };
3955
- cleanups.push(cleanup);
3956
- image.addEventListener("load", finish);
3957
- image.addEventListener("error", finish);
3958
- })
3959
- )
3960
- ),
3961
- new Promise((resolve) => {
3962
- timeoutId = setTimeout(resolve, timeout);
3963
- })
3964
- ]);
3965
- clearTimeout(timeoutId);
3966
- cleanups.forEach((cleanup) => cleanup());
3967
- };
3968
- var waitForIframeReady = async (root, imageTimeout = 1e4) => {
3969
- const document2 = root.ownerDocument;
3970
- await waitForNextPaint(document2);
3971
- await waitForNextPaint(document2);
3972
- await waitForImages(root, imageTimeout);
3973
- await waitForNextPaint(document2);
3974
- };
3975
-
3976
- // src/lib/capture-screenshot.ts
3977
- init_react_import();
3978
- var import_html2canvas_pro = __toESM(require("html2canvas-pro"));
3979
-
3980
- // src/lib/screenshot-size.ts
3981
- init_react_import();
3982
- var MAX_WEBP_DIMENSION = 16383;
3983
- var CAPTURE_SCALE = 2;
3984
- var getFitRatio = (width, height, dimensionLimit = MAX_WEBP_DIMENSION) => {
3985
- if (width <= 0 || height <= 0) return 1;
3986
- return Math.min(1, dimensionLimit / Math.max(width, height));
3987
- };
3988
- var getCaptureScale = (width, height, scale) => scale * getFitRatio(width * scale, height * scale);
3989
- var scaleDimension = (value, ratio) => Math.max(1, Math.floor(value * ratio));
3990
- var getDocumentSize = (root) => {
3991
- const { body, documentElement } = root.ownerDocument;
3992
4708
  return {
3993
- width: Math.max(
3994
- body?.scrollWidth ?? 0,
3995
- body?.offsetWidth ?? 0,
3996
- body?.clientWidth ?? 0,
3997
- documentElement?.scrollWidth ?? 0,
3998
- documentElement?.offsetWidth ?? 0,
3999
- documentElement?.clientWidth ?? 0
4000
- ),
4001
- height: Math.max(
4002
- body?.scrollHeight ?? 0,
4003
- body?.offsetHeight ?? 0,
4004
- body?.clientHeight ?? 0,
4005
- documentElement?.scrollHeight ?? 0,
4006
- documentElement?.offsetHeight ?? 0,
4007
- documentElement?.clientHeight ?? 0
4008
- )
4709
+ chat,
4710
+ generate,
4711
+ applyPart,
4712
+ /** Live subagent progress, keyed by tool call id */
4713
+ subagentState,
4714
+ /** Apply a part as part of the chat, as its own turns do */
4715
+ applyChatPart,
4716
+ /** Replace the conversation's messages, for the homepage demo's replay */
4717
+ setMessages
4009
4718
  };
4010
- };
4011
-
4012
- // src/lib/screenshot-overflow.ts
4013
- init_react_import();
4014
- var applyBrowserOverflowStylesTo = (document2) => {
4015
- for (const element of [document2.documentElement, document2.body]) {
4016
- element?.style.setProperty("overflow", "visible", "important");
4719
+ }
4720
+ function usePuckAi(options = {}) {
4721
+ const { chat, generate, applyPart } = usePuckAiInternal(options);
4722
+ return {
4723
+ chat,
4724
+ /**
4725
+ * Run a generation against the current page. Returns the page's Data once
4726
+ * it's applied. Iterates once, unless the handler's `ai.maxIterations`
4727
+ * allows more.
4728
+ */
4729
+ generate,
4730
+ /** Apply and process an AI Part. */
4731
+ applyPart
4732
+ };
4733
+ }
4734
+ async function uploadPreviewScreenshot(url, { signal, ...captureOptions } = {}) {
4735
+ const iframeDocument = document?.getElementById("preview-frame")?.contentDocument?.documentElement ?? null;
4736
+ if (!iframeDocument) {
4737
+ throw new Error("Preview frame not found");
4738
+ }
4739
+ await waitForIframeReady(iframeDocument);
4740
+ const blob = await captureScreenshot(iframeDocument, captureOptions);
4741
+ if (signal?.aborted) throw abortError();
4742
+ const uploadResponse = await fetch(url, {
4743
+ method: "PUT",
4744
+ body: blob,
4745
+ signal
4746
+ });
4747
+ if (!uploadResponse.ok) {
4748
+ throw new Error(`Upload failed with status ${uploadResponse.status}`);
4017
4749
  }
4018
- };
4019
-
4020
- // src/lib/capture-screenshot.ts
4021
- var editorOnlyClassPrefixes = ["_DraggableComponent--hover", "_ActionBar"];
4022
- var releaseCanvas = (canvas) => {
4023
- canvas.width = 0;
4024
- canvas.height = 0;
4025
- };
4026
- var drawScaled = (source, ratio) => {
4027
- const target = document.createElement("canvas");
4028
- target.width = scaleDimension(source.width, ratio);
4029
- target.height = scaleDimension(source.height, ratio);
4030
- const ctx = target.getContext("2d");
4031
- if (!ctx) {
4032
- releaseCanvas(target);
4033
- return source;
4750
+ return blob;
4751
+ }
4752
+ function finishLoadingTools(current, label) {
4753
+ let changed = false;
4754
+ const next = {};
4755
+ for (const [id, toolState] of Object.entries(current)) {
4756
+ if (toolState.loading) {
4757
+ changed = true;
4758
+ next[id] = { ...toolState, loading: false, label };
4759
+ } else {
4760
+ next[id] = toolState;
4761
+ }
4034
4762
  }
4035
- ctx.imageSmoothingEnabled = true;
4036
- ctx.imageSmoothingQuality = "high";
4037
- ctx.drawImage(source, 0, 0, target.width, target.height);
4038
- return target;
4039
- };
4040
- var fitCanvas = (canvas) => {
4041
- let remaining = getFitRatio(canvas.width, canvas.height);
4042
- if (remaining >= 1) return canvas;
4043
- let current = canvas;
4044
- while (remaining < 0.5) {
4045
- const next = drawScaled(current, 0.5);
4046
- if (current !== canvas) releaseCanvas(current);
4047
- current = next;
4048
- remaining *= 2;
4763
+ return changed ? next : current;
4764
+ }
4765
+ function finalizeReasoningParts(parts) {
4766
+ return parts.map(
4767
+ (part) => part.kind === "reasoning" && part.state !== "done" ? { ...part, state: "done" } : part
4768
+ );
4769
+ }
4770
+ function reduceSubagentEvent(current, event) {
4771
+ if (event.kind === "start") {
4772
+ if (current[event.toolCallId]) return current;
4773
+ return {
4774
+ ...current,
4775
+ [event.toolCallId]: {
4776
+ toolCallId: event.toolCallId,
4777
+ parentToolCallId: event.parentToolCallId,
4778
+ agentType: event.agentType,
4779
+ depth: event.depth,
4780
+ label: event.label,
4781
+ state: "running",
4782
+ parts: []
4783
+ }
4784
+ };
4049
4785
  }
4050
- const fitted = drawScaled(current, remaining);
4051
- if (current !== canvas) releaseCanvas(current);
4052
- return fitted;
4053
- };
4054
- var toWebp = (canvas, quality) => new Promise((resolve, reject) => {
4055
- canvas.toBlob(
4056
- (blob) => {
4057
- if (blob && blob.size > 0) {
4058
- resolve(blob);
4059
- return;
4786
+ const existing = current[event.toolCallId];
4787
+ if (!existing) return current;
4788
+ if (event.kind === "finish") {
4789
+ return {
4790
+ ...current,
4791
+ [event.toolCallId]: {
4792
+ ...existing,
4793
+ state: "done",
4794
+ parts: finalizeReasoningParts(existing.parts)
4060
4795
  }
4061
- reject(
4062
- new Error(
4063
- `Could not encode a ${canvas.width}x${canvas.height} canvas as WebP`
4064
- )
4065
- );
4066
- },
4067
- "image/webp",
4068
- quality
4069
- );
4070
- });
4071
- var captureScreenshot = async (root, { scale = CAPTURE_SCALE, quality = 0.8, width } = {}) => {
4072
- const documentSize = getDocumentSize(root);
4073
- const safeWebPScale = getCaptureScale(
4074
- width ?? documentSize.width,
4075
- documentSize.height,
4076
- scale
4077
- );
4078
- const canvas = await (0, import_html2canvas_pro.default)(root, {
4079
- scale: safeWebPScale,
4080
- backgroundColor: "#ffffff",
4081
- ...width === void 0 ? {} : { width, windowWidth: width },
4082
- foreignObjectRendering: false,
4083
- imageTimeout: 3e4,
4084
- logging: false,
4085
- allowTaint: false,
4086
- useCORS: true,
4087
- scrollY: 0,
4088
- onclone: applyBrowserOverflowStylesTo,
4089
- ignoreElements: (el) => Array.from(el.classList).some(
4090
- (c) => editorOnlyClassPrefixes.some((prefix) => c.startsWith(prefix))
4091
- )
4092
- });
4093
- const fitted = fitCanvas(canvas);
4094
- try {
4095
- return await toWebp(fitted, quality);
4096
- } finally {
4097
- if (fitted !== canvas) releaseCanvas(fitted);
4098
- releaseCanvas(canvas);
4796
+ };
4797
+ }
4798
+ if (event.kind === "reasoning-delta") {
4799
+ const parts = [...existing.parts];
4800
+ const last = parts[parts.length - 1];
4801
+ if (last && last.kind === "reasoning" && last.state !== "done") {
4802
+ const separator = last.blockId !== event.blockId ? "\n\n" : "";
4803
+ parts[parts.length - 1] = {
4804
+ ...last,
4805
+ blockId: event.blockId,
4806
+ text: last.text + separator + event.text
4807
+ };
4808
+ } else {
4809
+ parts.push({
4810
+ kind: "reasoning",
4811
+ blockId: event.blockId,
4812
+ text: event.text,
4813
+ state: "streaming"
4814
+ });
4815
+ }
4816
+ return {
4817
+ ...current,
4818
+ [event.toolCallId]: { ...existing, parts }
4819
+ };
4820
+ }
4821
+ if (event.kind === "text-delta") {
4822
+ const parts = finalizeReasoningParts(existing.parts);
4823
+ const last = parts[parts.length - 1];
4824
+ if (last && last.kind === "text" && last.blockId === event.blockId) {
4825
+ parts[parts.length - 1] = { ...last, text: last.text + event.text };
4826
+ } else {
4827
+ parts.push({ kind: "text", blockId: event.blockId, text: event.text });
4828
+ }
4829
+ return {
4830
+ ...current,
4831
+ [event.toolCallId]: { ...existing, parts }
4832
+ };
4833
+ }
4834
+ if (event.kind === "tool-call") {
4835
+ return {
4836
+ ...current,
4837
+ [event.toolCallId]: {
4838
+ ...existing,
4839
+ parts: [
4840
+ ...finalizeReasoningParts(existing.parts),
4841
+ {
4842
+ kind: "tool",
4843
+ childToolCallId: event.childToolCallId,
4844
+ toolName: event.toolName,
4845
+ input: event.input
4846
+ }
4847
+ ]
4848
+ }
4849
+ };
4099
4850
  }
4100
- };
4101
-
4102
- // src/lib/client-tool-response.ts
4103
- init_react_import();
4104
- async function postClientToolResponse(host, body) {
4105
- const response = await fetch(`${host.replace(/\/+$/, "")}/tool`, {
4106
- method: "POST",
4107
- headers: { "Content-Type": "application/json" },
4108
- body: JSON.stringify(body)
4109
- });
4110
- if (!response.ok) {
4111
- throw new Error(
4112
- `Client tool endpoint returned ${response.status} ${response.statusText}`.trim()
4113
- );
4851
+ if (event.kind === "tool-result") {
4852
+ return {
4853
+ ...current,
4854
+ [event.toolCallId]: {
4855
+ ...existing,
4856
+ parts: existing.parts.map(
4857
+ (part) => part.kind === "tool" && part.childToolCallId === event.childToolCallId ? { ...part, output: event.output } : part
4858
+ )
4859
+ }
4860
+ };
4114
4861
  }
4862
+ return current;
4115
4863
  }
4116
-
4117
- // src/lib/to-serializable.ts
4118
- init_react_import();
4119
- function toSerializable(value, ancestors = []) {
4120
- const json = typeof value === "object" && value !== null && "toJSON" in value && typeof value.toJSON === "function" ? value.toJSON() : value;
4121
- if (typeof json !== "object" || json === null) {
4122
- return typeof json === "function" || typeof json === "symbol" || typeof json === "bigint" ? void 0 : json;
4123
- }
4124
- if ("$$typeof" in json || ancestors.includes(json)) return void 0;
4125
- ancestors.push(json);
4126
- let copy;
4127
- if (Array.isArray(json)) {
4128
- copy = json.map((item) => toSerializable(item, ancestors) ?? null);
4129
- } else {
4130
- const record = json;
4131
- const object = {};
4132
- for (const key of Object.keys(record)) {
4133
- const item = toSerializable(record[key], ancestors);
4134
- if (item !== void 0) object[key] = item;
4135
- }
4136
- copy = object;
4864
+ function nextFrame(cb) {
4865
+ let ran = false;
4866
+ const run = () => {
4867
+ if (ran) return;
4868
+ ran = true;
4869
+ cb();
4870
+ };
4871
+ if (typeof document !== "undefined" && document.hidden) {
4872
+ queueMicrotask(run);
4873
+ return;
4137
4874
  }
4138
- ancestors.pop();
4139
- return copy;
4875
+ requestAnimationFrame(run);
4876
+ setTimeout(run, 100);
4140
4877
  }
4141
4878
 
4142
- // src/components/PluginTheme/index.ts
4143
- init_react_import();
4144
-
4145
- // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/PluginTheme/styles.module.css#css-module
4146
- init_react_import();
4147
- var styles_module_default6 = { "PluginTheme": "_PluginTheme_u3emj_8" };
4148
-
4149
- // src/components/PluginTheme/index.ts
4150
- var cx4 = getClassNameFactory("PluginTheme", styles_module_default6);
4151
- var pluginThemeClassName = cx4();
4152
-
4153
4879
  // src/components/Chat/index.tsx
4154
4880
  var import_jsx_runtime10 = require("react/jsx-runtime");
4155
- var q = (0, import_qler.default)();
4156
- var DEFAULT_API_VERSION = "v2";
4157
- var BUILD_OP_DEBOUNCE_MS = 1e3 / 60;
4158
- 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.";
4159
- var PLUGIN_AI_VERSION = true ? "0.9.0-canary.e2b15643" : "unknown";
4160
- var BENCHMARK = false;
4161
- var prefixedUlid = (prefix = "") => `${prefix ? `${prefix}_` : ""}${(0, import_ulid.ulid)()}`;
4162
4881
  var getClassName3 = getClassNameFactory("Chat", styles_module_default);
4163
- var usePuck2 = (0, import_core5.createUsePuck)();
4882
+ var usePuck3 = (0, import_core6.createUsePuck)();
4164
4883
  function Chat2(props) {
4165
4884
  const {
4166
4885
  apiVersion = DEFAULT_API_VERSION,
@@ -4177,35 +4896,19 @@ function Chat2(props) {
4177
4896
  actions: chatActions,
4178
4897
  placeholder
4179
4898
  } = chat ?? {};
4180
- const puckDispatch = usePuck2((s) => s.dispatch);
4181
- const getPuck = (0, import_core5.useGetPuck)();
4899
+ const puckDispatch = usePuck3((s) => s.dispatch);
4900
+ const getPuck = (0, import_core6.useGetPuck)();
4182
4901
  const t = (key, params) => getMessage(getPuck().dictionary, key, params);
4183
- const localChatId = (0, import_react17.useRef)("");
4184
- const inputRef = (0, import_react17.useRef)(null);
4185
- const pluginRef = (0, import_react17.useRef)(null);
4186
- const [mode, setMode] = (0, import_react17.useState)(defaultMode);
4187
- const modeRef = (0, import_react17.useRef)(mode);
4902
+ const inputRef = (0, import_react18.useRef)(null);
4903
+ const pluginRef = (0, import_react18.useRef)(null);
4904
+ const [mode, setMode] = (0, import_react18.useState)(defaultMode);
4188
4905
  const designModeVisible = typeof designMode === "boolean" ? designMode : designMode.visible ?? false;
4189
- (0, import_react17.useEffect)(() => {
4190
- modeRef.current = mode;
4191
- }, [mode]);
4192
- const puckData = usePuck2((s) => s.appState.data);
4193
- (0, import_react17.useEffect)(() => {
4194
- syncDesignComponents(getPuck);
4195
- }, [puckData, getPuck]);
4196
- const [error, setError] = (0, import_react17.useState)();
4197
- const [userError, setUserError] = (0, import_react17.useState)();
4198
- const clientToolEndpointUnavailableRef = (0, import_react17.useRef)(false);
4199
- const stopChatRef = (0, import_react17.useRef)(null);
4200
- const [composerAttachments, setComposerAttachments] = (0, import_react17.useState)([]);
4201
- const removedAttachmentClientIdsRef = (0, import_react17.useRef)(/* @__PURE__ */ new Set());
4202
- const uploadControllersRef = (0, import_react17.useRef)(/* @__PURE__ */ new Map());
4203
- const pendingBuildOpsRef = (0, import_react17.useRef)([]);
4204
- const lastStreamActivityRef = (0, import_react17.useRef)(0);
4205
- const hiddenSinceRef = (0, import_react17.useRef)(null);
4206
- const [toolStatus, setToolStatus] = (0, import_react17.useState)({});
4207
- const [subagentState, setSubagentState] = (0, import_react17.useState)({});
4208
- const attachmentConfig = (0, import_react17.useMemo)(
4906
+ const [error, setError] = (0, import_react18.useState)();
4907
+ const [userError, setUserError] = (0, import_react18.useState)();
4908
+ const [composerAttachments, setComposerAttachments] = (0, import_react18.useState)([]);
4909
+ const removedAttachmentClientIdsRef = (0, import_react18.useRef)(/* @__PURE__ */ new Set());
4910
+ const uploadControllersRef = (0, import_react18.useRef)(/* @__PURE__ */ new Map());
4911
+ const attachmentConfig = (0, import_react18.useMemo)(
4209
4912
  () => ({
4210
4913
  accept: attachments?.accept ?? defaultAttachmentAccept,
4211
4914
  enabled: attachments?.enabled ?? true,
@@ -4214,396 +4917,51 @@ function Chat2(props) {
4214
4917
  maxSizeBytes: attachments?.maxSizeBytes ?? defaultAttachmentConfig.maxSizeBytes
4215
4918
  }),
4216
4919
  [attachments, host]
4217
- );
4218
- (0, import_react17.useEffect)(
4219
- () => () => {
4220
- uploadControllersRef.current.forEach((controller) => controller.abort());
4221
- uploadControllersRef.current.clear();
4222
- },
4223
- []
4224
- );
4225
- const deleteAttachment = (0, import_react17.useCallback)(
4226
- async (attachmentId) => {
4227
- try {
4228
- await fetch(`${attachmentConfig.endpoint}/${attachmentId}`, {
4229
- method: "DELETE"
4230
- });
4231
- } catch (e) {
4232
- console.error(e);
4233
- }
4234
- },
4235
- [attachmentConfig.endpoint]
4236
- );
4237
- const uploadScreenshot = (0, import_react17.useCallback)(
4238
- async (width, bucketUrl) => {
4239
- try {
4240
- const iframeDocument = document?.getElementById("preview-frame")?.contentDocument?.documentElement ?? null;
4241
- if (!iframeDocument) {
4242
- throw new Error("Preview frame not found");
4243
- }
4244
- await waitForIframeReady(iframeDocument);
4245
- const blob = await captureScreenshot(iframeDocument, { width });
4246
- const uploadResponse = await fetch(bucketUrl, {
4247
- method: "PUT",
4248
- body: blob
4249
- });
4250
- if (!uploadResponse.ok) {
4251
- throw new Error(`Upload failed with status ${uploadResponse.status}`);
4252
- }
4253
- } catch (e) {
4254
- console.error("Failed to upload screenshot", e);
4255
- }
4256
- },
4257
- []
4258
- );
4259
- const debouncedFlushBuildOps = (0, import_use_debounce.useDebouncedCallback)(
4260
- () => {
4261
- const operations = pendingBuildOpsRef.current;
4262
- pendingBuildOpsRef.current = [];
4263
- if (operations.length === 0) return;
4264
- q.queue(
4265
- () => new Promise((resolve) => {
4266
- nextFrame(() => {
4267
- const { dispatch, config, resolveDataById } = getPuck();
4268
- operations.forEach((queuedOperation) => {
4269
- (0, import_reducer.dispatchOp)(queuedOperation, {
4270
- getState: () => {
4271
- const { __private } = getPuck();
4272
- return __private.appState;
4273
- },
4274
- dispatchAction: dispatch,
4275
- config
4276
- });
4277
- if (queuedOperation.op === "add" || queuedOperation.op === "update") {
4278
- resolveDataById(queuedOperation.id, "replace");
4279
- }
4280
- if (queuedOperation.op === "updateRoot") {
4281
- syncDesignComponents(getPuck);
4282
- }
4283
- });
4284
- resolve();
4285
- });
4286
- })
4287
- );
4288
- },
4289
- BUILD_OP_DEBOUNCE_MS,
4290
- { maxWait: BUILD_OP_DEBOUNCE_MS }
4291
- );
4292
- const queueBuildOp = (0, import_react17.useCallback)(
4293
- (operation) => {
4294
- pendingBuildOpsRef.current.push(operation);
4295
- debouncedFlushBuildOps();
4296
- },
4297
- [debouncedFlushBuildOps]
4298
- );
4299
- const handleClientToolEndpointUnavailable = (0, import_react17.useCallback)(() => {
4300
- if (clientToolEndpointUnavailableRef.current) return;
4301
- clientToolEndpointUnavailableRef.current = true;
4302
- setError(CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE);
4303
- console.error(CLIENT_TOOL_ENDPOINT_UNAVAILABLE_ERROR_MESSAGE);
4304
- setToolStatus((current) => {
4305
- let changed = false;
4306
- const next = {};
4307
- for (const [id, toolState] of Object.entries(current)) {
4308
- if (toolState.loading) {
4309
- changed = true;
4310
- next[id] = {
4311
- ...toolState,
4312
- loading: false,
4313
- label: "Verification unavailable"
4314
- };
4315
- } else {
4316
- next[id] = toolState;
4317
- }
4318
- }
4319
- return changed ? next : current;
4320
- });
4321
- stopChatRef.current?.();
4322
- }, []);
4323
- const sendClientToolResponse = (0, import_react17.useCallback)(
4324
- async (body) => {
4325
- try {
4326
- await postClientToolResponse(host, body);
4327
- } catch {
4328
- handleClientToolEndpointUnavailable();
4329
- }
4330
- },
4331
- [handleClientToolEndpointUnavailable, host]
4332
- );
4333
- const processData = (0, import_react17.useCallback)(
4334
- (dataPart) => {
4335
- lastStreamActivityRef.current = Date.now();
4336
- switch (dataPart.type) {
4337
- case "data-new-chat-created": {
4338
- localChatId.current = dataPart.data.chatId;
4339
- return;
4340
- }
4341
- case "data-puck-actions": {
4342
- dataPart.data.forEach((action) => {
4343
- try {
4344
- puckDispatch(action);
4345
- } catch (e) {
4346
- console.error("Bad action: ", action);
4347
- console.error(e);
4348
- }
4349
- });
4350
- return;
4351
- }
4352
- case "data-build-op": {
4353
- const { pageId, ...operation } = dataPart.data;
4354
- if (pageId) {
4355
- return;
4356
- }
4357
- queueBuildOp(operation);
4358
- return;
4359
- }
4360
- case "data-client-request": {
4361
- const { requestId, action } = dataPart.data;
4362
- const chatId = localChatId.current || void 0;
4363
- if (action === "getPageData") {
4364
- debouncedFlushBuildOps.flush();
4365
- q.wait().then(() => {
4366
- const { appState } = getPuck();
4367
- return sendClientToolResponse({
4368
- id: requestId,
4369
- chatId,
4370
- responses: [{ action, output: appState.data }]
4371
- });
4372
- }).catch((e) => {
4373
- console.error("Failed to respond to client request:", e);
4374
- });
4375
- }
4376
- if (action === "takeScreenshot") {
4377
- const { putUrl } = dataPart.data.params ?? {};
4378
- debouncedFlushBuildOps.flush();
4379
- q.wait().then(async () => {
4380
- const iframeDocument = document?.getElementById(
4381
- "preview-frame"
4382
- )?.contentDocument?.documentElement ?? null;
4383
- if (!iframeDocument) {
4384
- throw new Error("Preview frame not found");
4385
- }
4386
- await waitForIframeReady(iframeDocument);
4387
- const blob = await captureScreenshot(iframeDocument);
4388
- const uploadResponse = await fetch(putUrl, {
4389
- method: "PUT",
4390
- body: blob
4391
- });
4392
- if (!uploadResponse.ok) {
4393
- throw new Error(
4394
- `Upload failed with status ${uploadResponse.status}`
4395
- );
4396
- }
4397
- return sendClientToolResponse({
4398
- id: requestId,
4399
- chatId,
4400
- responses: [{ action, output: { sizeBytes: blob.size } }]
4401
- });
4402
- }).catch((e) => {
4403
- console.error("Failed to respond to client request:", e);
4404
- return sendClientToolResponse({
4405
- id: requestId,
4406
- chatId,
4407
- responses: [{ action, output: { sizeBytes: 0 } }]
4408
- });
4409
- });
4410
- }
4411
- return;
4412
- }
4413
- case "data-tool-status": {
4414
- setToolStatus((s) => ({
4415
- ...s,
4416
- [dataPart.data.toolCallId]: dataPart.data.status
4417
- }));
4418
- return;
4419
- }
4420
- case "data-subagent-event": {
4421
- setSubagentState(
4422
- (current) => reduceSubagentEvent(current, dataPart.data)
4423
- );
4424
- return;
4425
- }
4426
- case "data-send-screenshot": {
4427
- dataPart.data.urls.forEach((obj) => {
4428
- const [[key, value]] = Object.entries(obj);
4429
- const breakpoint = Number(key);
4430
- uploadScreenshot(breakpoint, value);
4431
- });
4432
- return;
4433
- }
4434
- case "data-finish": {
4435
- debouncedFlushBuildOps.flush();
4436
- return;
4437
- }
4438
- case "data-version-notice": {
4439
- console.warn(dataPart.data.message);
4440
- return;
4441
- }
4442
- default:
4443
- console.warn("dataPart without case:", dataPart);
4444
- return;
4445
- }
4920
+ );
4921
+ (0, import_react18.useEffect)(
4922
+ () => () => {
4923
+ uploadControllersRef.current.forEach((controller) => controller.abort());
4924
+ uploadControllersRef.current.clear();
4446
4925
  },
4447
- [
4448
- debouncedFlushBuildOps,
4449
- getPuck,
4450
- puckDispatch,
4451
- queueBuildOp,
4452
- sendClientToolResponse,
4453
- uploadScreenshot
4454
- ]
4926
+ []
4455
4927
  );
4456
- const { messages, status, sendMessage, regenerate, setMessages, stop } = useChat({
4457
- generateId: () => prefixedUlid("msg"),
4458
- messages: [],
4459
- transport: new import_ai5.DefaultChatTransport({
4460
- api: host,
4461
- prepareSendMessagesRequest: async (opts) => {
4462
- const { config, appState } = getPuck();
4463
- if (BENCHMARK) {
4464
- console.time("chat");
4465
- }
4466
- const root = config.root ?? {
4467
- fields: {
4468
- title: {
4469
- type: "text",
4470
- ai: { instructions: "The title for the page" }
4471
- }
4472
- }
4473
- };
4474
- const configWithRoot = toSerializable({
4475
- ...config,
4476
- root,
4477
- components: {
4478
- ...config.components,
4479
- ...getRequestComponentConfigs(appState.data)
4480
- }
4928
+ const deleteAttachment = (0, import_react18.useCallback)(
4929
+ async (attachmentId) => {
4930
+ try {
4931
+ await fetch(`${attachmentConfig.endpoint}/${attachmentId}`, {
4932
+ method: "DELETE"
4481
4933
  });
4482
- const defaultOptions = {
4483
- headers: {
4484
- ...opts.headers,
4485
- "puck-api-version": apiVersion,
4486
- "x-puck-plugin-ai-version": PLUGIN_AI_VERSION
4487
- },
4488
- credentials: opts.credentials,
4489
- body: {
4490
- ...opts.body,
4491
- chatId: localChatId.current,
4492
- trigger: opts.trigger,
4493
- messages: opts.messages,
4494
- pageData: appState.data,
4495
- config: configWithRoot,
4496
- mode: modeRef.current
4497
- }
4498
- };
4499
- if (prepareRequest) {
4500
- const userOptions = await prepareRequest(defaultOptions);
4501
- return {
4502
- headers: {
4503
- ...defaultOptions.headers,
4504
- ...userOptions.headers
4505
- },
4506
- credentials: userOptions.credentials ?? defaultOptions.credentials,
4507
- body: {
4508
- ...defaultOptions.body,
4509
- ...userOptions.body
4510
- }
4511
- };
4512
- }
4513
- return defaultOptions;
4514
- }
4515
- }),
4516
- onData: processData,
4517
- onError: (e) => {
4518
- console.error(e);
4519
- if (BENCHMARK) {
4520
- console.timeEnd("chat");
4521
- }
4522
- if (!clientToolEndpointUnavailableRef.current) {
4523
- setError(e.message);
4934
+ } catch (e) {
4935
+ console.error(e);
4524
4936
  }
4525
4937
  },
4526
- onFinish: (options) => {
4527
- debouncedFlushBuildOps.flush();
4528
- q.wait().then(() => {
4529
- if (!options.isAbort || clientToolEndpointUnavailableRef.current) {
4530
- puckDispatch({
4531
- type: "set",
4532
- state: getPuck().appState,
4533
- recordHistory: true
4534
- });
4535
- }
4536
- chat?.onFinish?.(options);
4537
- }).finally(() => {
4538
- if (BENCHMARK) {
4539
- console.timeEnd("chat");
4540
- }
4541
- });
4542
- }
4938
+ [attachmentConfig.endpoint]
4939
+ );
4940
+ const {
4941
+ chat: {
4942
+ sendMessage,
4943
+ status,
4944
+ messages,
4945
+ regenerate,
4946
+ error: aiError,
4947
+ toolStatus
4948
+ },
4949
+ subagentState,
4950
+ applyChatPart,
4951
+ setMessages
4952
+ } = usePuckAiInternal({
4953
+ host,
4954
+ mode,
4955
+ apiVersion,
4956
+ prepareRequest,
4957
+ onFinish: chat?.onFinish
4543
4958
  });
4544
- (0, import_react17.useEffect)(() => {
4545
- stopChatRef.current = stop;
4546
- return () => {
4547
- stopChatRef.current = null;
4548
- stop();
4549
- };
4550
- }, [stop]);
4551
- const statusRef = (0, import_react17.useRef)(status);
4552
- (0, import_react17.useEffect)(() => {
4553
- statusRef.current = status;
4554
- }, [status]);
4555
- (0, import_react17.useEffect)(() => {
4556
- lastStreamActivityRef.current = Date.now();
4557
- }, [messages]);
4558
- (0, import_react17.useEffect)(() => {
4559
- const FROZEN_HIDDEN_MS = 3 * 6e4;
4560
- const RESUME_GRACE_MS = 12e3;
4561
- const isStreaming = () => statusRef.current === "streaming" || statusRef.current === "submitted";
4562
- let graceTimer;
4563
- const recoverIfSevered = () => {
4564
- if (!isStreaming()) return;
4565
- if (Date.now() - lastStreamActivityRef.current < RESUME_GRACE_MS) return;
4566
- stop();
4567
- setToolStatus((current) => {
4568
- let changed = false;
4569
- const next = {};
4570
- for (const [id, toolState] of Object.entries(current)) {
4571
- if (toolState.loading) {
4572
- changed = true;
4573
- next[id] = { ...toolState, loading: false, label: "Interrupted" };
4574
- } else {
4575
- next[id] = toolState;
4576
- }
4577
- }
4578
- return changed ? next : current;
4579
- });
4580
- };
4581
- const onVisibilityChange = () => {
4582
- if (document.hidden) {
4583
- hiddenSinceRef.current = isStreaming() ? Date.now() : null;
4584
- return;
4585
- }
4586
- const hiddenSince = hiddenSinceRef.current;
4587
- hiddenSinceRef.current = null;
4588
- if (graceTimer) clearTimeout(graceTimer);
4589
- if (hiddenSince === null || Date.now() - hiddenSince < FROZEN_HIDDEN_MS) {
4590
- return;
4591
- }
4592
- lastStreamActivityRef.current = 0;
4593
- graceTimer = setTimeout(recoverIfSevered, RESUME_GRACE_MS);
4594
- };
4595
- document.addEventListener("visibilitychange", onVisibilityChange);
4596
- return () => {
4597
- document.removeEventListener("visibilitychange", onVisibilityChange);
4598
- if (graceTimer) clearTimeout(graceTimer);
4599
- };
4600
- }, [stop]);
4601
- const [forcedStatus, setForcedStatus] = (0, import_react17.useState)();
4602
- const resolvedStatus = (0, import_react17.useMemo)(
4959
+ const [forcedStatus, setForcedStatus] = (0, import_react18.useState)();
4960
+ const resolvedStatus = (0, import_react18.useMemo)(
4603
4961
  () => forcedStatus ?? status,
4604
4962
  [status, forcedStatus]
4605
4963
  );
4606
- (0, import_react17.useEffect)(() => {
4964
+ (0, import_react18.useEffect)(() => {
4607
4965
  if (!scrollTrackingId) return;
4608
4966
  dispatchScrollTrackingEvent({
4609
4967
  id: scrollTrackingId,
@@ -4616,15 +4974,19 @@ function Chat2(props) {
4616
4974
  });
4617
4975
  };
4618
4976
  }, [resolvedStatus, scrollTrackingId]);
4619
- (0, import_react17.useEffect)(() => {
4977
+ (0, import_react18.useEffect)(() => {
4620
4978
  window.__PUCK_AI = {
4621
- processData,
4979
+ processData: applyChatPart,
4622
4980
  setMessages,
4623
4981
  setStatus: setForcedStatus,
4624
- sendMessage,
4982
+ sendMessage: (message) => sendMessage(
4983
+ message.parts.filter(
4984
+ (part) => Boolean(part && part.type === "text")
4985
+ ).map((part) => part.text).join("")
4986
+ ),
4625
4987
  focus: () => inputRef?.current?.focus()
4626
4988
  };
4627
- }, [processData]);
4989
+ }, [applyChatPart]);
4628
4990
  const handleSubmit = async (prompt) => {
4629
4991
  const text = prompt.trim();
4630
4992
  const readyAttachments = composerAttachments.filter(
@@ -4648,8 +5010,7 @@ function Chat2(props) {
4648
5010
  if (!text && readyAttachments.length === 0) {
4649
5011
  return false;
4650
5012
  }
4651
- clientToolEndpointUnavailableRef.current = false;
4652
- setError("");
5013
+ setError(void 0);
4653
5014
  setUserError("");
4654
5015
  if (chat?.onSubmit) {
4655
5016
  try {
@@ -4665,13 +5026,7 @@ function Chat2(props) {
4665
5026
  }
4666
5027
  setComposerAttachments([]);
4667
5028
  removedAttachmentClientIdsRef.current.clear();
4668
- sendMessage({
4669
- role: "user",
4670
- parts: [
4671
- ...text ? [{ type: "text", text }] : [],
4672
- ...readyAttachments
4673
- ]
4674
- }).catch((e) => {
5029
+ sendMessage(text, { files: readyAttachments }).catch((e) => {
4675
5030
  console.error(e);
4676
5031
  setError("Failed to send message.");
4677
5032
  setComposerAttachments(composerAttachments);
@@ -4834,7 +5189,7 @@ function Chat2(props) {
4834
5189
  if (!target?.attachmentId) return;
4835
5190
  await deleteAttachment(target.attachmentId);
4836
5191
  };
4837
- const messagesWithStatuses = (0, import_react17.useMemo)(() => {
5192
+ const messagesWithStatuses = (0, import_react18.useMemo)(() => {
4838
5193
  return messages.map((msg) => {
4839
5194
  return {
4840
5195
  ...msg,
@@ -4899,10 +5254,9 @@ function Chat2(props) {
4899
5254
  label
4900
5255
  )
4901
5256
  ),
4902
- error,
5257
+ error: error || aiError,
4903
5258
  handleRetry: () => {
4904
- clientToolEndpointUnavailableRef.current = false;
4905
- setError("");
5259
+ setError(void 0);
4906
5260
  regenerate();
4907
5261
  },
4908
5262
  userError,
@@ -4920,105 +5274,6 @@ function Chat2(props) {
4920
5274
  }
4921
5275
  );
4922
5276
  }
4923
- function finalizeReasoningParts(parts) {
4924
- return parts.map(
4925
- (part) => part.kind === "reasoning" && part.state !== "done" ? { ...part, state: "done" } : part
4926
- );
4927
- }
4928
- function reduceSubagentEvent(current, event) {
4929
- if (event.kind === "start") {
4930
- if (current[event.toolCallId]) return current;
4931
- return {
4932
- ...current,
4933
- [event.toolCallId]: {
4934
- toolCallId: event.toolCallId,
4935
- parentToolCallId: event.parentToolCallId,
4936
- agentType: event.agentType,
4937
- depth: event.depth,
4938
- label: event.label,
4939
- state: "running",
4940
- parts: []
4941
- }
4942
- };
4943
- }
4944
- const existing = current[event.toolCallId];
4945
- if (!existing) return current;
4946
- if (event.kind === "finish") {
4947
- return {
4948
- ...current,
4949
- [event.toolCallId]: {
4950
- ...existing,
4951
- state: "done",
4952
- parts: finalizeReasoningParts(existing.parts)
4953
- }
4954
- };
4955
- }
4956
- if (event.kind === "reasoning-delta") {
4957
- const parts = [...existing.parts];
4958
- const last = parts[parts.length - 1];
4959
- if (last && last.kind === "reasoning" && last.state !== "done") {
4960
- const separator = last.blockId !== event.blockId ? "\n\n" : "";
4961
- parts[parts.length - 1] = {
4962
- ...last,
4963
- blockId: event.blockId,
4964
- text: last.text + separator + event.text
4965
- };
4966
- } else {
4967
- parts.push({
4968
- kind: "reasoning",
4969
- blockId: event.blockId,
4970
- text: event.text,
4971
- state: "streaming"
4972
- });
4973
- }
4974
- return {
4975
- ...current,
4976
- [event.toolCallId]: { ...existing, parts }
4977
- };
4978
- }
4979
- if (event.kind === "text-delta") {
4980
- const parts = finalizeReasoningParts(existing.parts);
4981
- const last = parts[parts.length - 1];
4982
- if (last && last.kind === "text" && last.blockId === event.blockId) {
4983
- parts[parts.length - 1] = { ...last, text: last.text + event.text };
4984
- } else {
4985
- parts.push({ kind: "text", blockId: event.blockId, text: event.text });
4986
- }
4987
- return {
4988
- ...current,
4989
- [event.toolCallId]: { ...existing, parts }
4990
- };
4991
- }
4992
- if (event.kind === "tool-call") {
4993
- return {
4994
- ...current,
4995
- [event.toolCallId]: {
4996
- ...existing,
4997
- parts: [
4998
- ...finalizeReasoningParts(existing.parts),
4999
- {
5000
- kind: "tool",
5001
- childToolCallId: event.childToolCallId,
5002
- toolName: event.toolName,
5003
- input: event.input
5004
- }
5005
- ]
5006
- }
5007
- };
5008
- }
5009
- if (event.kind === "tool-result") {
5010
- return {
5011
- ...current,
5012
- [event.toolCallId]: {
5013
- ...existing,
5014
- parts: existing.parts.map(
5015
- (part) => part.kind === "tool" && part.childToolCallId === event.childToolCallId ? { ...part, output: event.output } : part
5016
- )
5017
- }
5018
- };
5019
- }
5020
- return current;
5021
- }
5022
5277
  function AttachmentComposer({
5023
5278
  accept,
5024
5279
  attachments,
@@ -5026,8 +5281,8 @@ function AttachmentComposer({
5026
5281
  maxFiles,
5027
5282
  onChange
5028
5283
  }) {
5029
- const id = (0, import_react17.useId)();
5030
- const inputId = (0, import_react17.useMemo)(() => `attachment-input-${id}`, []);
5284
+ const id = (0, import_react18.useId)();
5285
+ const inputId = (0, import_react18.useMemo)(() => `attachment-input-${id}`, []);
5031
5286
  const attachLabel = useMessage("plugin-ai-prompt-attachment-attach");
5032
5287
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: getClassName3("attachmentControls"), children: [
5033
5288
  /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
@@ -5109,20 +5364,6 @@ function Placeholder({
5109
5364
  ] })
5110
5365
  ] });
5111
5366
  }
5112
- function nextFrame(cb) {
5113
- let ran = false;
5114
- const run = () => {
5115
- if (ran) return;
5116
- ran = true;
5117
- cb();
5118
- };
5119
- if (typeof document !== "undefined" && document.hidden) {
5120
- queueMicrotask(run);
5121
- return;
5122
- }
5123
- requestAnimationFrame(run);
5124
- setTimeout(run, 100);
5125
- }
5126
5367
  function isScrolledIntoView(el) {
5127
5368
  const rect = el.getBoundingClientRect();
5128
5369
  const elemTop = rect.top;
@@ -5132,7 +5373,7 @@ function isScrolledIntoView(el) {
5132
5373
 
5133
5374
  // src/components/ScrollTracking/ScrollTracking.tsx
5134
5375
  init_react_import();
5135
- var import_react19 = require("react");
5376
+ var import_react20 = require("react");
5136
5377
 
5137
5378
  // src/lib/scroll-into-view-local.ts
5138
5379
  init_react_import();
@@ -5155,9 +5396,9 @@ function scrollIntoViewLocal(el, win, behavior = "smooth") {
5155
5396
 
5156
5397
  // src/lib/use-frame-mutation-observer.ts
5157
5398
  init_react_import();
5158
- var import_react18 = require("react");
5399
+ var import_react19 = require("react");
5159
5400
  function useFrameMutationObserver(callback) {
5160
- return (0, import_react18.useCallback)(() => {
5401
+ return (0, import_react19.useCallback)(() => {
5161
5402
  const frame = document?.getElementById(
5162
5403
  "preview-frame"
5163
5404
  );
@@ -5202,9 +5443,9 @@ var ScrollTracking = ({
5202
5443
  children,
5203
5444
  trackingId
5204
5445
  }) => {
5205
- const followedRefs = (0, import_react19.useRef)([]);
5206
- const enabledRef = (0, import_react19.useRef)(false);
5207
- (0, import_react19.useEffect)(() => {
5446
+ const followedRefs = (0, import_react20.useRef)([]);
5447
+ const enabledRef = (0, import_react20.useRef)(false);
5448
+ (0, import_react20.useEffect)(() => {
5208
5449
  return subscribeToScrollTrackingEvents(({ id, enabled }) => {
5209
5450
  if (id !== trackingId) return;
5210
5451
  enabledRef.current = enabled;
@@ -5223,7 +5464,7 @@ var ScrollTracking = ({
5223
5464
  });
5224
5465
  }
5225
5466
  });
5226
- (0, import_react19.useEffect)(() => {
5467
+ (0, import_react20.useEffect)(() => {
5227
5468
  follow();
5228
5469
  }, [follow]);
5229
5470
  return children;
@@ -5231,12 +5472,12 @@ var ScrollTracking = ({
5231
5472
 
5232
5473
  // src/components/Drawer/index.tsx
5233
5474
  init_react_import();
5234
- var import_core7 = require("@puckeditor/core");
5475
+ var import_core8 = require("@puckeditor/core");
5235
5476
 
5236
5477
  // src/components/ManageComponents/index.tsx
5237
5478
  init_react_import();
5238
- var import_core6 = require("@puckeditor/core");
5239
- var import_react23 = require("react");
5479
+ var import_core7 = require("@puckeditor/core");
5480
+ var import_react24 = require("react");
5240
5481
 
5241
5482
  // ../platform-client/components/ActionModal/index.ts
5242
5483
  init_react_import();
@@ -5256,15 +5497,15 @@ init_react_import();
5256
5497
  var Modal_module_default = { "Modal-background": "_Modal-background_10jdm_1", "Modal--visible": "_Modal--visible_10jdm_16", "Modal-modal": "_Modal-modal_10jdm_22" };
5257
5498
 
5258
5499
  // ../platform-client/components/Modal/Modal.tsx
5259
- var import_react22 = require("react");
5500
+ var import_react23 = require("react");
5260
5501
 
5261
5502
  // ../platform-client/lib/use-modal-visible.ts
5262
5503
  init_react_import();
5263
- var import_react20 = require("react");
5504
+ var import_react21 = require("react");
5264
5505
  var useModalVisible = (defaultVisible) => {
5265
- const [visible, setVisible] = (0, import_react20.useState)(defaultVisible ?? false);
5266
- const ref = (0, import_react20.useRef)(null);
5267
- (0, import_react20.useEffect)(() => {
5506
+ const [visible, setVisible] = (0, import_react21.useState)(defaultVisible ?? false);
5507
+ const ref = (0, import_react21.useRef)(null);
5508
+ (0, import_react21.useEffect)(() => {
5268
5509
  if (!visible) {
5269
5510
  return;
5270
5511
  }
@@ -5286,7 +5527,7 @@ init_react_import();
5286
5527
 
5287
5528
  // ../platform-client/components/Button/Button.tsx
5288
5529
  init_react_import();
5289
- var import_react21 = require("react");
5530
+ var import_react22 = require("react");
5290
5531
 
5291
5532
  // css-module:/home/runner/work/platform/platform/packages/platform-client/components/Button/Button.module.css#css-module
5292
5533
  init_react_import();
@@ -5309,8 +5550,8 @@ var Button = ({
5309
5550
  size = "medium",
5310
5551
  loading: loadingProp = false
5311
5552
  }) => {
5312
- const [loading, setLoading] = (0, import_react21.useState)(loadingProp);
5313
- (0, import_react21.useEffect)(() => {
5553
+ const [loading, setLoading] = (0, import_react22.useState)(loadingProp);
5554
+ (0, import_react22.useEffect)(() => {
5314
5555
  const resetLoading = () => setLoading(loadingProp);
5315
5556
  resetLoading();
5316
5557
  window.addEventListener("pageshow", resetLoading);
@@ -5361,7 +5602,7 @@ var Button = ({
5361
5602
  // ../platform-client/components/Modal/Modal.tsx
5362
5603
  var import_jsx_runtime12 = require("react/jsx-runtime");
5363
5604
  var getClassName5 = getClassNameFactory("Modal", Modal_module_default);
5364
- var modalContext = (0, import_react22.createContext)({
5605
+ var modalContext = (0, import_react23.createContext)({
5365
5606
  buttonVariant: "primary",
5366
5607
  buttonSize: "medium",
5367
5608
  visible: false,
@@ -5385,7 +5626,7 @@ var ModalProvider = ({
5385
5626
  );
5386
5627
  };
5387
5628
  var useModal = () => {
5388
- const { visible, setVisible } = (0, import_react22.useContext)(modalContext);
5629
+ const { visible, setVisible } = (0, import_react23.useContext)(modalContext);
5389
5630
  return { visible, setVisible };
5390
5631
  };
5391
5632
  var Modal = ({
@@ -5393,7 +5634,7 @@ var Modal = ({
5393
5634
  children,
5394
5635
  hideButton = false
5395
5636
  }) => {
5396
- const { visible, setVisible, buttonVariant, buttonSize, ref } = (0, import_react22.useContext)(modalContext);
5637
+ const { visible, setVisible, buttonVariant, buttonSize, ref } = (0, import_react23.useContext)(modalContext);
5397
5638
  return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: getClassName5({ visible }), children: [
5398
5639
  !hideButton && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: getClassName5("button"), children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
5399
5640
  Button,
@@ -5529,13 +5770,13 @@ var styles_module_default7 = { "ManageComponents-cta": "_ManageComponents-cta_ie
5529
5770
  // src/components/ManageComponents/index.tsx
5530
5771
  var import_jsx_runtime16 = require("react/jsx-runtime");
5531
5772
  var cx5 = getClassNameFactory("ManageComponents", styles_module_default7);
5532
- var useRegistrations = () => (0, import_react23.useSyncExternalStore)(
5773
+ var useRegistrations = () => (0, import_react24.useSyncExternalStore)(
5533
5774
  registrationStore.subscribe,
5534
5775
  () => registrationStore.getAll(),
5535
5776
  () => registrationStore.getAll()
5536
5777
  );
5537
5778
  function ManageModalContent({ onClose }) {
5538
- const getPuck = (0, import_core6.useGetPuck)();
5779
+ const getPuck = (0, import_core7.useGetPuck)();
5539
5780
  const deleteTitle = useMessage("plugin-ai-components-delete-title");
5540
5781
  const cancelLabel = useMessage("plugin-ai-components-delete-cancel");
5541
5782
  const deleteLabel = useMessage("plugin-ai-components-delete");
@@ -5543,9 +5784,9 @@ function ManageModalContent({ onClose }) {
5543
5784
  const manageTitle = useMessage("plugin-ai-components-manage");
5544
5785
  const emptyLabel = useMessage("plugin-ai-components-manage-empty");
5545
5786
  const { visible, setVisible } = useModal();
5546
- const [confirmTarget, setConfirmTarget] = (0, import_react23.useState)(null);
5787
+ const [confirmTarget, setConfirmTarget] = (0, import_react24.useState)(null);
5547
5788
  const entries = useRegistrations();
5548
- (0, import_react23.useEffect)(() => {
5789
+ (0, import_react24.useEffect)(() => {
5549
5790
  if (!visible) onClose();
5550
5791
  }, [visible, onClose]);
5551
5792
  const handleDelete = (name) => {
@@ -5572,7 +5813,7 @@ function ManageModalContent({ onClose }) {
5572
5813
  }
5573
5814
  )
5574
5815
  ] }),
5575
- children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("p", { className: cx5("confirmation"), children: deleteConfirm.split("{label}").map((part, i) => /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(import_react23.Fragment, { children: [
5816
+ children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("p", { className: cx5("confirmation"), children: deleteConfirm.split("{label}").map((part, i) => /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(import_react24.Fragment, { children: [
5576
5817
  i > 0 && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("b", { children: confirmTarget.label }),
5577
5818
  part
5578
5819
  ] }, i)) })
@@ -5599,10 +5840,10 @@ function ManageModalContent({ onClose }) {
5599
5840
  ] }) });
5600
5841
  }
5601
5842
  function ManageComponentsCta() {
5602
- const [open, setOpen] = (0, import_react23.useState)(false);
5843
+ const [open, setOpen] = (0, import_react24.useState)(false);
5603
5844
  const entries = useRegistrations();
5604
5845
  const manageLabel = useMessage("plugin-ai-components-manage");
5605
- const handleClose = (0, import_react23.useCallback)(() => setOpen(false), []);
5846
+ const handleClose = (0, import_react24.useCallback)(() => setOpen(false), []);
5606
5847
  if (entries.length === 0) return null;
5607
5848
  return /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(import_jsx_runtime16.Fragment, { children: [
5608
5849
  /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)("button", { className: cx5("cta"), onClick: () => setOpen(true), type: "button", children: [
@@ -5619,10 +5860,10 @@ var styles_module_default8 = { "Drawer": "_Drawer_1mu8g_1", "Drawer--empty": "_D
5619
5860
 
5620
5861
  // src/components/Drawer/index.tsx
5621
5862
  var import_jsx_runtime17 = require("react/jsx-runtime");
5622
- var usePuck3 = (0, import_core7.createUsePuck)();
5863
+ var usePuck4 = (0, import_core8.createUsePuck)();
5623
5864
  var cx6 = getClassNameFactory("Drawer", styles_module_default8);
5624
5865
  var createDrawer = (designModeVisible) => function Drawer({ children }) {
5625
- const config = usePuck3((s) => s.config);
5866
+ const config = usePuck4((s) => s.config);
5626
5867
  if (Object.keys(config.components).length === 0) {
5627
5868
  return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)("div", { className: `${cx6({ empty: true })} ${pluginThemeClassName}`, children: "No blocks" });
5628
5869
  }
@@ -5632,8 +5873,8 @@ var createDrawer = (designModeVisible) => function Drawer({ children }) {
5632
5873
  ] });
5633
5874
  };
5634
5875
 
5635
- // src/index.tsx
5636
- var import_jsx_runtime18 = require("react/jsx-runtime");
5876
+ // src/lib/design/with-dynamic-config.ts
5877
+ init_react_import();
5637
5878
  function withDynamicConfig(config, data) {
5638
5879
  const registrations = getPersistedRegistrations(data);
5639
5880
  const dynamicConfig = {};
@@ -5663,6 +5904,9 @@ function withDynamicConfig(config, data) {
5663
5904
  applyConfigFieldMetadata(result, dynamicConfig);
5664
5905
  return result;
5665
5906
  }
5907
+
5908
+ // src/index.tsx
5909
+ var import_jsx_runtime18 = require("react/jsx-runtime");
5666
5910
  function createAiPlugin(opts) {
5667
5911
  const { label = "AI", scrollTracking = true, ...rest } = opts || {};
5668
5912
  const scrollTrackingId = `puck-ai-scroll-${(0, import_ulid2.ulid)()}`;
@@ -5688,6 +5932,7 @@ function createAiPlugin(opts) {
5688
5932
  0 && (module.exports = {
5689
5933
  createAiPlugin,
5690
5934
  defaultDictionary,
5935
+ usePuckAi,
5691
5936
  withDynamicConfig
5692
5937
  });
5693
5938
  /*! Bundled license information: