@chaibuilder/sdk 3.2.6 → 3.2.8

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.
@@ -0,0 +1,241 @@
1
+ import { jsx as e, jsxs as a, Fragment as Q } from "react/jsx-runtime";
2
+ import { e as _, f as H, M as K, o as X, r as q } from "./index-DvdOXKUE.js";
3
+ import { D as J } from "./apply-binding-DLaiD20q.js";
4
+ import { v as u, au as Y, at as z, az as ee } from "./tooltip-DUosa-uC.js";
5
+ import { ArrowLeftIcon as te, MagnifyingGlassIcon as L, PlusIcon as M, TokensIcon as ne, EyeOpenIcon as se, Pencil1Icon as re, TrashIcon as ae } from "@radix-ui/react-icons";
6
+ import { useAtom as oe } from "jotai";
7
+ import { nanoid as ie } from "nanoid";
8
+ import { lazy as S, useState as g, useRef as le, useMemo as ce, useEffect as de, useCallback as me, Suspense as O } from "react";
9
+ import { useTranslation as ue } from "react-i18next";
10
+ import { toast as N } from "sonner";
11
+ import { twMerge as he } from "tailwind-merge";
12
+ const R = (n) => {
13
+ const s = n.trim();
14
+ return s.length === 0 || s.length > 25 ? !1 : /^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/.test(s);
15
+ }, fe = (n, s, o, d = !1, i) => {
16
+ const m = n.trim();
17
+ return m.length === 0 ? "" : m.length > 25 ? o("Token name must be 25 characters or less") : /^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/.test(m) ? Object.entries(s).find(
18
+ ([l, v]) => v.name === m && (!d || l !== i)
19
+ ) ? o("Token name already exists") : "" : o("Only alphanumeric characters and hyphens allowed");
20
+ }, xe = (n) => n.replace(/\s+/g, "-"), ge = S(() => import("./delete-design-token-BjMakV-b.js")), pe = S(() => import("./design-token-usage-BDArZ38H.js")), ve = ({ tokenId: n, token: s, isDisabled: o, onEdit: d, onDelete: i }) => /* @__PURE__ */ a("div", { className: "group relative flex items-center justify-between overflow-hidden rounded border p-2 transition-all duration-150 hover:bg-muted/90", children: [
21
+ /* @__PURE__ */ a("div", { className: "min-w-0 flex-1 overflow-hidden", children: [
22
+ /* @__PURE__ */ e("div", { className: "text-xs font-semibold", children: s.name }),
23
+ /* @__PURE__ */ e("div", { className: "w-full max-w-52 truncate text-[10px] font-light", children: s.value })
24
+ ] }),
25
+ /* @__PURE__ */ a("div", { className: "absolute right-1 top-1 flex flex-shrink-0 items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100", children: [
26
+ /* @__PURE__ */ e(O, { fallback: null, children: /* @__PURE__ */ e(pe, { tokenId: n, tokenName: s.name, children: /* @__PURE__ */ e(
27
+ u,
28
+ {
29
+ variant: "ghost",
30
+ size: "sm",
31
+ className: "h-6 w-6 rounded-full p-0 hover:bg-primary/10 hover:text-primary",
32
+ children: /* @__PURE__ */ e(se, { className: "h-3 w-3" })
33
+ }
34
+ ) }) }),
35
+ /* @__PURE__ */ e(
36
+ u,
37
+ {
38
+ variant: "ghost",
39
+ size: "sm",
40
+ onClick: () => d(n),
41
+ disabled: o,
42
+ className: "h-6 w-6 rounded-full p-0 hover:bg-primary/10 hover:text-primary",
43
+ children: /* @__PURE__ */ e(re, { className: "h-3 w-3" })
44
+ }
45
+ ),
46
+ /* @__PURE__ */ e(O, { fallback: null, children: /* @__PURE__ */ e(ge, { tokenName: s.name, tokenValue: s.value, onDelete: () => i(n), children: /* @__PURE__ */ e(
47
+ u,
48
+ {
49
+ variant: "ghost",
50
+ size: "sm",
51
+ disabled: o,
52
+ className: "h-6 w-6 rounded-full p-0 hover:bg-destructive/10",
53
+ children: /* @__PURE__ */ e(ae, { className: "h-3 w-3 text-destructive" })
54
+ }
55
+ ) }) })
56
+ ] })
57
+ ] }), Le = ({}) => {
58
+ const { t: n } = ue(), [s, o] = oe(_), d = H(), [i, m] = g("view"), [p, k] = g(null), [l, v] = g(""), [h, b] = g(""), [T, y] = g(""), [w, P] = g(""), [F, C] = g(!1), f = le(null), D = ce(() => Object.entries(s).filter(
59
+ ([, t]) => t.name.toLowerCase().includes(w.toLowerCase()) || t.value.toLowerCase().includes(w.toLowerCase())
60
+ ), [s, w]);
61
+ de(() => () => {
62
+ f.current && clearTimeout(f.current);
63
+ }, []);
64
+ const j = me(
65
+ (t, r) => {
66
+ !p || i !== "edit" || !t.trim() || !r.trim() || !R(t) || Object.entries(s).find(
67
+ ([x, U]) => U.name === t.trim() && x !== p
68
+ ) || (C(!0), f.current && clearTimeout(f.current), f.current = setTimeout(() => {
69
+ const x = {
70
+ ...s,
71
+ [p]: {
72
+ name: t.trim(),
73
+ value: r.trim()
74
+ }
75
+ };
76
+ o(x), d(), C(!1);
77
+ }, 250));
78
+ },
79
+ [p, i, s, o, d]
80
+ ), B = () => {
81
+ if (!l.trim() || !h.trim()) {
82
+ N.error(n("Please fill in both token name and classes"));
83
+ return;
84
+ }
85
+ if (!R(l)) {
86
+ N.error(n("Invalid design token name format"));
87
+ return;
88
+ }
89
+ if (Object.values(s).find((x) => x.name === l.trim())) {
90
+ N.error(n("Token already exists"));
91
+ return;
92
+ }
93
+ const r = `${J}${ie(12)}`, c = {
94
+ ...s,
95
+ [r]: {
96
+ name: l.trim(),
97
+ value: h.trim()
98
+ }
99
+ };
100
+ o(c), d(), N.success(n("Token added successfully")), A();
101
+ }, V = (t) => {
102
+ const r = { ...s };
103
+ delete r[t], o(r), d(), N.success(n("Token deleted successfully"));
104
+ }, W = (t) => {
105
+ const r = s[t];
106
+ r && (k(t), v(r.name), b(r.value), y(""), m("edit"));
107
+ }, E = () => {
108
+ k(null), v(""), b(""), y(""), m("add");
109
+ }, A = () => {
110
+ f.current && clearTimeout(f.current), k(null), v(""), b(""), y(""), C(!1), m("view");
111
+ }, Z = (t) => {
112
+ const r = xe(t);
113
+ v(r);
114
+ const c = fe(r, s, n, i === "edit", p || void 0);
115
+ y(c), i === "edit" && !c && j(r, h);
116
+ }, I = (t) => {
117
+ b(t), i === "edit" && !T && l.trim() && j(l, t);
118
+ }, $ = (t) => {
119
+ const r = X(q(he(h, t)));
120
+ I(r);
121
+ }, G = (t) => {
122
+ const r = h.split(" ").filter((c) => c !== t).join(" ");
123
+ I(r);
124
+ };
125
+ return /* @__PURE__ */ e("div", { className: "flex h-full w-full flex-col", children: i === "view" ? /* @__PURE__ */ a(Q, { children: [
126
+ Object.entries(s).length > 0 && /* @__PURE__ */ a("div", { className: "flex items-center justify-between gap-x-2", children: [
127
+ /* @__PURE__ */ a("div", { className: "relative flex-1", children: [
128
+ /* @__PURE__ */ e(L, { className: "absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-muted-foreground" }),
129
+ /* @__PURE__ */ e(
130
+ z,
131
+ {
132
+ placeholder: n("Search tokens"),
133
+ value: w,
134
+ onChange: (t) => P(t.target.value),
135
+ className: "h-6 pl-7 text-xs"
136
+ }
137
+ )
138
+ ] }),
139
+ /* @__PURE__ */ a(
140
+ u,
141
+ {
142
+ variant: "outline",
143
+ onClick: E,
144
+ size: "sm",
145
+ className: "h-6 border-primary text-xs text-primary hover:bg-primary/10 hover:text-primary",
146
+ children: [
147
+ /* @__PURE__ */ e(M, { className: "h-3 w-3" }),
148
+ n("Add")
149
+ ]
150
+ }
151
+ )
152
+ ] }),
153
+ /* @__PURE__ */ e("div", { className: "no-scrollbar flex flex-1 flex-col overflow-hidden pt-2", children: /* @__PURE__ */ e(ee, { className: "h-full flex-1", children: /* @__PURE__ */ a("div", { className: "space-y-1", children: [
154
+ Object.entries(s).length === 0 ? /* @__PURE__ */ a("div", { className: "flex flex-col items-center justify-center rounded-lg border border-dashed border-muted bg-muted/20 py-8", children: [
155
+ /* @__PURE__ */ e("div", { className: "mb-2 text-3xl", children: /* @__PURE__ */ e(ne, { className: "h-12 w-12 text-muted-foreground" }) }),
156
+ /* @__PURE__ */ e("p", { className: "mb-1 text-sm font-medium text-foreground", children: n("No design tokens yet") }),
157
+ /* @__PURE__ */ e("p", { className: "text-center text-xs text-muted-foreground", children: n("Create reusable design tokens to streamline your styling") }),
158
+ /* @__PURE__ */ a(u, { variant: "default", onClick: E, size: "sm", className: "mt-4 h-7 text-xs leading-tight", children: [
159
+ /* @__PURE__ */ e(M, { className: "mr-1 h-3 w-3" }),
160
+ n("Add first design token")
161
+ ] })
162
+ ] }) : D.length === 0 ? /* @__PURE__ */ a("div", { className: "flex flex-col items-center justify-center rounded-lg border border-dashed border-muted bg-muted/20 py-8", children: [
163
+ /* @__PURE__ */ e("div", { className: "mb-2", children: /* @__PURE__ */ e(L, { className: "h-10 w-10 text-muted-foreground" }) }),
164
+ /* @__PURE__ */ e("p", { className: "mb-1 text-sm font-medium text-foreground", children: n("No tokens found") }),
165
+ /* @__PURE__ */ e("p", { className: "text-center text-xs text-muted-foreground", children: n("No design tokens match your search") })
166
+ ] }) : D.map(([t, r]) => /* @__PURE__ */ e(
167
+ ve,
168
+ {
169
+ token: r,
170
+ tokenId: t,
171
+ onEdit: W,
172
+ onDelete: V,
173
+ isDisabled: !1
174
+ },
175
+ t
176
+ )),
177
+ /* @__PURE__ */ e("div", { className: "h-44" })
178
+ ] }) }) })
179
+ ] }) : (() => {
180
+ const t = i === "edit", r = n(t ? "Edit Design Token" : "Add Design Token"), c = n(t ? "Update design token. Auto-saved." : "Create a reusable design token");
181
+ return /* @__PURE__ */ a("div", { className: "flex h-full flex-col", children: [
182
+ /* @__PURE__ */ a("div", { className: "mb-3 flex items-center gap-2 rounded-md border border-border/50 bg-muted p-1.5", children: [
183
+ /* @__PURE__ */ e(
184
+ u,
185
+ {
186
+ variant: "ghost",
187
+ size: "sm",
188
+ onClick: A,
189
+ className: "h-6 w-6 rounded-full p-0 hover:bg-muted",
190
+ children: /* @__PURE__ */ e(te, { className: "h-3 w-3" })
191
+ }
192
+ ),
193
+ /* @__PURE__ */ a("div", { className: "flex-1", children: [
194
+ /* @__PURE__ */ e("h3", { className: "text-xs font-semibold text-foreground", children: r }),
195
+ /* @__PURE__ */ e("p", { className: "text-[10px] text-muted-foreground", children: c })
196
+ ] }),
197
+ t && F && /* @__PURE__ */ e("div", { className: "flex items-center gap-1 text-[10px] text-muted-foreground", children: /* @__PURE__ */ e("div", { className: "h-1.5 w-1.5 animate-pulse rounded-full bg-primary" }) })
198
+ ] }),
199
+ /* @__PURE__ */ a("div", { className: "flex-1 space-y-3 overflow-y-auto", children: [
200
+ /* @__PURE__ */ a("div", { className: "space-y-1.5", children: [
201
+ /* @__PURE__ */ e(Y, { htmlFor: "token-name", className: "text-xs font-medium", children: n("Token Name") }),
202
+ /* @__PURE__ */ e(
203
+ z,
204
+ {
205
+ id: "token-name",
206
+ placeholder: "Button-Primary",
207
+ value: l,
208
+ onChange: (x) => Z(x.target.value),
209
+ className: "h-7 text-xs"
210
+ }
211
+ ),
212
+ T ? /* @__PURE__ */ e("span", { className: "text-[10px] text-destructive", children: T }) : /* @__PURE__ */ e("span", { className: "text-[10px] font-light text-muted-foreground", children: n("Button-Primary, Card-Header, Text-Large etc.") })
213
+ ] }),
214
+ /* @__PURE__ */ e(
215
+ K,
216
+ {
217
+ from: "designToken",
218
+ classFromProps: h,
219
+ onAddNew: $,
220
+ onRemove: G
221
+ }
222
+ ),
223
+ !t && /* @__PURE__ */ a("div", { className: "mt-3 flex items-center justify-end gap-2 pt-3", children: [
224
+ /* @__PURE__ */ e(u, { variant: "outline", onClick: A, className: "h-7 text-xs", children: n("Cancel") }),
225
+ /* @__PURE__ */ e(
226
+ u,
227
+ {
228
+ onClick: B,
229
+ disabled: !l.trim() || !h.trim() || !!T,
230
+ className: "h-7 text-xs",
231
+ children: n("Add Token")
232
+ }
233
+ )
234
+ ] })
235
+ ] })
236
+ ] });
237
+ })() });
238
+ };
239
+ export {
240
+ Le as default
241
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),N=require("./index-CuANr9iH.cjs"),Z=require("./apply-binding-Bn1KC8uC.cjs"),i=require("./tooltip-Ba1-8jmj.cjs"),u=require("@radix-ui/react-icons"),$=require("jotai"),U=require("nanoid"),a=require("react"),Q=require("react-i18next"),p=require("sonner"),_=require("tailwind-merge"),B=t=>{const n=t.trim();return n.length===0||n.length>25?!1:/^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/.test(n)},H=(t,n,o,m=!1,l)=>{const x=t.trim();return x.length===0?"":x.length>25?o("Token name must be 25 characters or less"):/^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/.test(x)?Object.entries(n).find(([c,j])=>j.name===x&&(!m||c!==l))?o("Token name already exists"):"":o("Only alphanumeric characters and hyphens allowed")},K=t=>t.replace(/\s+/g,"-"),X=a.lazy(()=>Promise.resolve().then(()=>require("./delete-design-token-Bzxspf8D.cjs"))),J=a.lazy(()=>Promise.resolve().then(()=>require("./design-token-usage-CCv4XltM.cjs"))),Y=({tokenId:t,token:n,isDisabled:o,onEdit:m,onDelete:l})=>e.jsxs("div",{className:"group relative flex items-center justify-between overflow-hidden rounded border p-2 transition-all duration-150 hover:bg-muted/90",children:[e.jsxs("div",{className:"min-w-0 flex-1 overflow-hidden",children:[e.jsx("div",{className:"text-xs font-semibold",children:n.name}),e.jsx("div",{className:"w-full max-w-52 truncate text-[10px] font-light",children:n.value})]}),e.jsxs("div",{className:"absolute right-1 top-1 flex flex-shrink-0 items-center opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:[e.jsx(a.Suspense,{fallback:null,children:e.jsx(J,{tokenId:t,tokenName:n.name,children:e.jsx(i.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 rounded-full p-0 hover:bg-primary/10 hover:text-primary",children:e.jsx(u.EyeOpenIcon,{className:"h-3 w-3"})})})}),e.jsx(i.Button,{variant:"ghost",size:"sm",onClick:()=>m(t),disabled:o,className:"h-6 w-6 rounded-full p-0 hover:bg-primary/10 hover:text-primary",children:e.jsx(u.Pencil1Icon,{className:"h-3 w-3"})}),e.jsx(a.Suspense,{fallback:null,children:e.jsx(X,{tokenName:n.name,tokenValue:n.value,onDelete:()=>l(t),children:e.jsx(i.Button,{variant:"ghost",size:"sm",disabled:o,className:"h-6 w-6 rounded-full p-0 hover:bg-destructive/10",children:e.jsx(u.TrashIcon,{className:"h-3 w-3 text-destructive"})})})})]})]}),ee=({})=>{const{t}=Q.useTranslation(),[n,o]=$.useAtom(N.chaiDesignTokensAtom),m=N.useIncrementActionsCount(),[l,x]=a.useState("view"),[v,k]=a.useState(null),[c,j]=a.useState(""),[h,b]=a.useState(""),[T,y]=a.useState(""),[w,E]=a.useState(""),[z,C]=a.useState(!1),f=a.useRef(null),I=a.useMemo(()=>Object.entries(n).filter(([,s])=>s.name.toLowerCase().includes(w.toLowerCase())||s.value.toLowerCase().includes(w.toLowerCase())),[n,w]);a.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const S=a.useCallback((s,r)=>{!v||l!=="edit"||!s.trim()||!r.trim()||!B(s)||Object.entries(n).find(([g,W])=>W.name===s.trim()&&g!==v)||(C(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{const g={...n,[v]:{name:s.trim(),value:r.trim()}};o(g),m(),C(!1)},250))},[v,l,n,o,m]),M=()=>{if(!c.trim()||!h.trim()){p.toast.error(t("Please fill in both token name and classes"));return}if(!B(c)){p.toast.error(t("Invalid design token name format"));return}if(Object.values(n).find(g=>g.name===c.trim())){p.toast.error(t("Token already exists"));return}const r=`${Z.DESIGN_TOKEN_PREFIX}${U.nanoid(12)}`,d={...n,[r]:{name:c.trim(),value:h.trim()}};o(d),m(),p.toast.success(t("Token added successfully")),A()},P=s=>{const r={...n};delete r[s],o(r),m(),p.toast.success(t("Token deleted successfully"))},R=s=>{const r=n[s];r&&(k(s),j(r.name),b(r.value),y(""),x("edit"))},D=()=>{k(null),j(""),b(""),y(""),x("add")},A=()=>{f.current&&clearTimeout(f.current),k(null),j(""),b(""),y(""),C(!1),x("view")},O=s=>{const r=K(s);j(r);const d=H(r,n,t,l==="edit",v||void 0);y(d),l==="edit"&&!d&&S(r,h)},q=s=>{b(s),l==="edit"&&!T&&c.trim()&&S(c,s)},L=s=>{const r=N.orderClassesByBreakpoint(N.removeDuplicateClasses(_.twMerge(h,s)));q(r)},F=s=>{const r=h.split(" ").filter(d=>d!==s).join(" ");q(r)},G=()=>{const s=l==="edit",r=t(s?"Edit Design Token":"Add Design Token"),d=t(s?"Update design token. Auto-saved.":"Create a reusable design token");return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-md border border-border/50 bg-muted p-1.5",children:[e.jsx(i.Button,{variant:"ghost",size:"sm",onClick:A,className:"h-6 w-6 rounded-full p-0 hover:bg-muted",children:e.jsx(u.ArrowLeftIcon,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-xs font-semibold text-foreground",children:r}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:d})]}),s&&z&&e.jsx("div",{className:"flex items-center gap-1 text-[10px] text-muted-foreground",children:e.jsx("div",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-primary"})})]}),e.jsxs("div",{className:"flex-1 space-y-3 overflow-y-auto",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(i.Label,{htmlFor:"token-name",className:"text-xs font-medium",children:t("Token Name")}),e.jsx(i.Input,{id:"token-name",placeholder:"Button-Primary",value:c,onChange:g=>O(g.target.value),className:"h-7 text-xs"}),T?e.jsx("span",{className:"text-[10px] text-destructive",children:T}):e.jsx("span",{className:"text-[10px] font-light text-muted-foreground",children:t("Button-Primary, Card-Header, Text-Large etc.")})]}),e.jsx(N.ManualClasses,{from:"designToken",classFromProps:h,onAddNew:L,onRemove:F}),!s&&e.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2 pt-3",children:[e.jsx(i.Button,{variant:"outline",onClick:A,className:"h-7 text-xs",children:t("Cancel")}),e.jsx(i.Button,{onClick:M,disabled:!c.trim()||!h.trim()||!!T,className:"h-7 text-xs",children:t("Add Token")})]})]})]})},V=()=>e.jsxs(e.Fragment,{children:[Object.entries(n).length>0&&e.jsxs("div",{className:"flex items-center justify-between gap-x-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(u.MagnifyingGlassIcon,{className:"absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-muted-foreground"}),e.jsx(i.Input,{placeholder:t("Search tokens"),value:w,onChange:s=>E(s.target.value),className:"h-6 pl-7 text-xs"})]}),e.jsxs(i.Button,{variant:"outline",onClick:D,size:"sm",className:"h-6 border-primary text-xs text-primary hover:bg-primary/10 hover:text-primary",children:[e.jsx(u.PlusIcon,{className:"h-3 w-3"}),t("Add")]})]}),e.jsx("div",{className:"no-scrollbar flex flex-1 flex-col overflow-hidden pt-2",children:e.jsx(i.ScrollArea,{className:"h-full flex-1",children:e.jsxs("div",{className:"space-y-1",children:[Object.entries(n).length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center rounded-lg border border-dashed border-muted bg-muted/20 py-8",children:[e.jsx("div",{className:"mb-2 text-3xl",children:e.jsx(u.TokensIcon,{className:"h-12 w-12 text-muted-foreground"})}),e.jsx("p",{className:"mb-1 text-sm font-medium text-foreground",children:t("No design tokens yet")}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:t("Create reusable design tokens to streamline your styling")}),e.jsxs(i.Button,{variant:"default",onClick:D,size:"sm",className:"mt-4 h-7 text-xs leading-tight",children:[e.jsx(u.PlusIcon,{className:"mr-1 h-3 w-3"}),t("Add first design token")]})]}):I.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center rounded-lg border border-dashed border-muted bg-muted/20 py-8",children:[e.jsx("div",{className:"mb-2",children:e.jsx(u.MagnifyingGlassIcon,{className:"h-10 w-10 text-muted-foreground"})}),e.jsx("p",{className:"mb-1 text-sm font-medium text-foreground",children:t("No tokens found")}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:t("No design tokens match your search")})]}):I.map(([s,r])=>e.jsx(Y,{token:r,tokenId:s,onEdit:R,onDelete:P,isDisabled:!1},s)),e.jsx("div",{className:"h-44"})]})})})]});return e.jsx("div",{className:"flex h-full w-full flex-col",children:l==="view"?V():G()})};exports.default=ee;
@@ -5,24 +5,23 @@
5
5
  * Mock Service Worker.
6
6
  * @see https://github.com/mswjs/msw
7
7
  * - Please do NOT modify this file.
8
- * - Please do NOT serve this file on production.
9
8
  */
10
9
 
11
- const PACKAGE_VERSION = '2.7.4'
12
- const INTEGRITY_CHECKSUM = '00729d72e3b82faf54ca8b9621dbb96f'
10
+ const PACKAGE_VERSION = '2.12.4'
11
+ const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
13
12
  const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
14
13
  const activeClientIds = new Set()
15
14
 
16
- self.addEventListener('install', function () {
15
+ addEventListener('install', function () {
17
16
  self.skipWaiting()
18
17
  })
19
18
 
20
- self.addEventListener('activate', function (event) {
19
+ addEventListener('activate', function (event) {
21
20
  event.waitUntil(self.clients.claim())
22
21
  })
23
22
 
24
- self.addEventListener('message', async function (event) {
25
- const clientId = event.source.id
23
+ addEventListener('message', async function (event) {
24
+ const clientId = Reflect.get(event.source || {}, 'id')
26
25
 
27
26
  if (!clientId || !self.clients) {
28
27
  return
@@ -72,11 +71,6 @@ self.addEventListener('message', async function (event) {
72
71
  break
73
72
  }
74
73
 
75
- case 'MOCK_DEACTIVATE': {
76
- activeClientIds.delete(clientId)
77
- break
78
- }
79
-
80
74
  case 'CLIENT_CLOSED': {
81
75
  activeClientIds.delete(clientId)
82
76
 
@@ -94,69 +88,92 @@ self.addEventListener('message', async function (event) {
94
88
  }
95
89
  })
96
90
 
97
- self.addEventListener('fetch', function (event) {
98
- const { request } = event
91
+ addEventListener('fetch', function (event) {
92
+ const requestInterceptedAt = Date.now()
99
93
 
100
94
  // Bypass navigation requests.
101
- if (request.mode === 'navigate') {
95
+ if (event.request.mode === 'navigate') {
102
96
  return
103
97
  }
104
98
 
105
99
  // Opening the DevTools triggers the "only-if-cached" request
106
100
  // that cannot be handled by the worker. Bypass such requests.
107
- if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
101
+ if (
102
+ event.request.cache === 'only-if-cached' &&
103
+ event.request.mode !== 'same-origin'
104
+ ) {
108
105
  return
109
106
  }
110
107
 
111
108
  // Bypass all requests when there are no active clients.
112
109
  // Prevents the self-unregistered worked from handling requests
113
- // after it's been deleted (still remains active until the next reload).
110
+ // after it's been terminated (still remains active until the next reload).
114
111
  if (activeClientIds.size === 0) {
115
112
  return
116
113
  }
117
114
 
118
- // Generate unique request ID.
119
115
  const requestId = crypto.randomUUID()
120
- event.respondWith(handleRequest(event, requestId))
116
+ event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
121
117
  })
122
118
 
123
- async function handleRequest(event, requestId) {
119
+ /**
120
+ * @param {FetchEvent} event
121
+ * @param {string} requestId
122
+ * @param {number} requestInterceptedAt
123
+ */
124
+ async function handleRequest(event, requestId, requestInterceptedAt) {
124
125
  const client = await resolveMainClient(event)
125
- const response = await getResponse(event, client, requestId)
126
+ const requestCloneForEvents = event.request.clone()
127
+ const response = await getResponse(
128
+ event,
129
+ client,
130
+ requestId,
131
+ requestInterceptedAt,
132
+ )
126
133
 
127
134
  // Send back the response clone for the "response:*" life-cycle events.
128
135
  // Ensure MSW is active and ready to handle the message, otherwise
129
136
  // this message will pend indefinitely.
130
137
  if (client && activeClientIds.has(client.id)) {
131
- ;(async function () {
132
- const responseClone = response.clone()
133
-
134
- sendToClient(
135
- client,
136
- {
137
- type: 'RESPONSE',
138
- payload: {
139
- requestId,
140
- isMockedResponse: IS_MOCKED_RESPONSE in response,
138
+ const serializedRequest = await serializeRequest(requestCloneForEvents)
139
+
140
+ // Clone the response so both the client and the library could consume it.
141
+ const responseClone = response.clone()
142
+
143
+ sendToClient(
144
+ client,
145
+ {
146
+ type: 'RESPONSE',
147
+ payload: {
148
+ isMockedResponse: IS_MOCKED_RESPONSE in response,
149
+ request: {
150
+ id: requestId,
151
+ ...serializedRequest,
152
+ },
153
+ response: {
141
154
  type: responseClone.type,
142
155
  status: responseClone.status,
143
156
  statusText: responseClone.statusText,
144
- body: responseClone.body,
145
157
  headers: Object.fromEntries(responseClone.headers.entries()),
158
+ body: responseClone.body,
146
159
  },
147
160
  },
148
- [responseClone.body],
149
- )
150
- })()
161
+ },
162
+ responseClone.body ? [serializedRequest.body, responseClone.body] : [],
163
+ )
151
164
  }
152
165
 
153
166
  return response
154
167
  }
155
168
 
156
- // Resolve the main client for the given event.
157
- // Client that issues a request doesn't necessarily equal the client
158
- // that registered the worker. It's with the latter the worker should
159
- // communicate with during the response resolving phase.
169
+ /**
170
+ * Resolve the main client for the given event.
171
+ * Client that issues a request doesn't necessarily equal the client
172
+ * that registered the worker. It's with the latter the worker should
173
+ * communicate with during the response resolving phase.
174
+ * @param {FetchEvent} event
175
+ * @returns {Promise<Client | undefined>}
176
+ */
160
177
  async function resolveMainClient(event) {
161
178
  const client = await self.clients.get(event.clientId)
162
179
 
@@ -184,12 +201,17 @@ async function resolveMainClient(event) {
184
201
  })
185
202
  }
186
203
 
187
- async function getResponse(event, client, requestId) {
188
- const { request } = event
189
-
204
+ /**
205
+ * @param {FetchEvent} event
206
+ * @param {Client | undefined} client
207
+ * @param {string} requestId
208
+ * @param {number} requestInterceptedAt
209
+ * @returns {Promise<Response>}
210
+ */
211
+ async function getResponse(event, client, requestId, requestInterceptedAt) {
190
212
  // Clone the request because it might've been already used
191
213
  // (i.e. its body has been read and sent to the client).
192
- const requestClone = request.clone()
214
+ const requestClone = event.request.clone()
193
215
 
194
216
  function passthrough() {
195
217
  // Cast the request headers to a new Headers instance
@@ -230,29 +252,18 @@ async function getResponse(event, client, requestId) {
230
252
  }
231
253
 
232
254
  // Notify the client that a request has been intercepted.
233
- const requestBuffer = await request.arrayBuffer()
255
+ const serializedRequest = await serializeRequest(event.request)
234
256
  const clientMessage = await sendToClient(
235
257
  client,
236
258
  {
237
259
  type: 'REQUEST',
238
260
  payload: {
239
261
  id: requestId,
240
- url: request.url,
241
- mode: request.mode,
242
- method: request.method,
243
- headers: Object.fromEntries(request.headers.entries()),
244
- cache: request.cache,
245
- credentials: request.credentials,
246
- destination: request.destination,
247
- integrity: request.integrity,
248
- redirect: request.redirect,
249
- referrer: request.referrer,
250
- referrerPolicy: request.referrerPolicy,
251
- body: requestBuffer,
252
- keepalive: request.keepalive,
262
+ interceptedAt: requestInterceptedAt,
263
+ ...serializedRequest,
253
264
  },
254
265
  },
255
- [requestBuffer],
266
+ [serializedRequest.body],
256
267
  )
257
268
 
258
269
  switch (clientMessage.type) {
@@ -268,6 +279,12 @@ async function getResponse(event, client, requestId) {
268
279
  return passthrough()
269
280
  }
270
281
 
282
+ /**
283
+ * @param {Client} client
284
+ * @param {any} message
285
+ * @param {Array<Transferable>} transferrables
286
+ * @returns {Promise<any>}
287
+ */
271
288
  function sendToClient(client, message, transferrables = []) {
272
289
  return new Promise((resolve, reject) => {
273
290
  const channel = new MessageChannel()
@@ -280,14 +297,18 @@ function sendToClient(client, message, transferrables = []) {
280
297
  resolve(event.data)
281
298
  }
282
299
 
283
- client.postMessage(
284
- message,
285
- [channel.port2].concat(transferrables.filter(Boolean)),
286
- )
300
+ client.postMessage(message, [
301
+ channel.port2,
302
+ ...transferrables.filter(Boolean),
303
+ ])
287
304
  })
288
305
  }
289
306
 
290
- async function respondWithMock(response) {
307
+ /**
308
+ * @param {Response} response
309
+ * @returns {Response}
310
+ */
311
+ function respondWithMock(response) {
291
312
  // Setting response status code to 0 is a no-op.
292
313
  // However, when responding with a "Response.error()", the produced Response
293
314
  // instance will have status code set to 0. Since it's not possible to create
@@ -305,3 +326,24 @@ async function respondWithMock(response) {
305
326
 
306
327
  return mockedResponse
307
328
  }
329
+
330
+ /**
331
+ * @param {Request} request
332
+ */
333
+ async function serializeRequest(request) {
334
+ return {
335
+ url: request.url,
336
+ mode: request.mode,
337
+ method: request.method,
338
+ headers: Object.fromEntries(request.headers.entries()),
339
+ cache: request.cache,
340
+ credentials: request.credentials,
341
+ destination: request.destination,
342
+ integrity: request.integrity,
343
+ redirect: request.redirect,
344
+ referrer: request.referrer,
345
+ referrerPolicy: request.referrerPolicy,
346
+ body: await request.arrayBuffer(),
347
+ keepalive: request.keepalive,
348
+ }
349
+ }
package/dist/render.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("./plugin-CSgw-f78.cjs"),d=require("./apply-binding-DWIWrG2P.cjs"),m=require("react/jsx-runtime"),b=require("@chaibuilder/runtime"),t=require("lodash-es"),g=require("react"),D=require("@tailwindcss/aspect-ratio"),F=require("@tailwindcss/forms"),q=require("@tailwindcss/typography");require("tailwindcss-animate");const j=require("./get-chai-builder-theme-B1tr_NJB.cjs"),K=require("@mhsdesign/jit-browser-tailwindcss"),M=require("@tailwindcss/container-queries");async function O(e){const a={pageProps:e.pageProps,block:e.block,lang:e.lang,draft:e.draft,inBuilder:!1},n=await e.dataProvider(a);return t.has(n,"$metadata")&&t.isFunction(e.dataProviderMetadataCallback)&&e.dataProviderMetadataCallback(e.block,n.$metadata),e.children({...t.omit(n,"$metadata")})}const N=()=>m.jsx("div",{}),H=e=>{const{block:a,lang:n,fallbackLang:s,children:i,externalData:o,blocks:l,draft:r,pageProps:c,dataProviderMetadataCallback:k}=e,u=b.getRegisteredChaiBlock(a._type),p=t.get(u,"component",null),P=t.get(e.repeaterData,"index",-1),f=t.get(e.repeaterData,"dataKey",""),I=n===s?"":n,y=d.applyBindingToBlockProps(d.applyLanguage(a,I,u),o,{index:P,key:f}),h=d.getBlockTagAttributes(a,!1),T=L(l,a._id,d.getBlockRuntimeProps(a._type)),S=t.has(u,"dataProvider")&&t.isFunction(u.dataProvider),B={...y,...h,...T},_={blockProps:{},inBuilder:!1,lang:n||s,...B},v=t.get(B,"_show",!0);if(t.isNull(p)||!v)return null;if(S){const $=t.get(u,"suspenseFallback",N);return m.jsx(g.Suspense,{fallback:g.createElement($),children:m.jsx(O,{lang:n,pageProps:c,block:B,dataProvider:u.dataProvider,...k?{dataProviderMetadataCallback:k}:{},draft:r,children:x=>g.createElement(p,{..._,...x,children:i({_id:a._id,_type:a._type,...t.isArray(y.repeaterItems)?{repeaterItems:d.applyLimit(y.repeaterItems,a),$repeaterItemsKey:y.$repeaterItemsKey,repeaterTotalItems:y.repeaterTotalItems??-1}:{}})})})})}return m.jsx(g.Suspense,{children:g.createElement(p,{..._,children:i({_id:a._id,_type:a._type,...t.isArray(y.repeaterItems)?{repeaterItems:d.applyLimit(y.repeaterItems,a),$repeaterItemsKey:y.$repeaterItemsKey,repeaterTotalItems:y.repeaterTotalItems??-1}:{}})})})},E=e=>{const{blocks:a,parent:n,repeaterData:s,type:i}=e;let o=t.uniqBy(t.filter(a,r=>t.has(r,"_id")&&(t.isEmpty(n)?!r._parent:r._parent===n)),"_id");const l=r=>t.filter(a,c=>c._parent===r).length>0;return(i==="Heading"||i==="Paragraph"||i==="Link"||i==="Span")&&(o=d.adjustSpacingInContentBlocks(o)),t.map(o,r=>r?g.createElement(H,{...e,key:r._id,block:r},({_id:c,_type:k,repeaterItems:u,$repeaterItemsKey:p})=>k==="Repeater"?t.isArray(u)&&u.map((P,f)=>g.createElement(E,{...e,parent:r._id,key:`${t.get(r,"_parent","root")}-${r._id}-${f}`,repeaterData:{index:f,dataKey:p}})):l(c)?g.createElement(E,{...e,parent:r._id,key:`${t.get(r,"_parent","root")}-${r._id}`,repeaterData:s,type:r._type}):null):null)},L=(e,a,n)=>t.isEmpty(n)?{}:Object.entries(n).reduce((s,[i,o])=>{const l=[];let r=t.find(e,{_id:a});for(;r;)l.push(r),r=t.find(e,{_id:r._parent});const c=t.find(l,{_type:o.block});return c&&(s[i]=t.get(c,t.get(o,"prop"),null)),s},{});function J(e){if(t.isEmpty(e.lang)&&!t.isEmpty(e.fallbackLang))throw new Error("lang prop is required when fallbackLang is provided");if(t.isEmpty(e.blocks))return null;const a=e.lang??"en",n=e.fallbackLang??a;return m.jsx(E,{...e,lang:a,fallbackLang:n})}async function V(e){const a=await e.dataProvider;return t.has(a,"$metadata")&&t.isFunction(e.dataProviderMetadataCallback)&&e.dataProviderMetadataCallback(e.block,a.$metadata),e.children({...t.omit(a,"$metadata")})}const W=()=>m.jsx("div",{}),U=async e=>{const{block:a,lang:n,fallbackLang:s,children:i,externalData:o,blocks:l,draft:r,pageProps:c,dataProviderMetadataCallback:k,dataProviders:u}=e,p=b.getRegisteredChaiBlock(a._type),P=t.get(p,"component",null),f=t.get(e.repeaterData,"index",-1),I=t.get(e.repeaterData,"dataKey",""),y=n===s?"":n,h=d.applyBindingToBlockProps(d.applyLanguage(a,y,p),o,{index:f,key:I}),T=d.getBlockTagAttributes(a,!1),S=L(l,a._id,d.getBlockRuntimeProps(a._type)),B=t.has(p,"dataProvider")&&t.isFunction(p.dataProvider),_={...h,...T,...S},v={blockProps:{},inBuilder:!1,lang:n||s,..._},$=t.get(_,"_show",!0);if(t.isNull(P)||!$)return null;if(B){const x=t.get(u,a._id,Promise.resolve({})),R=t.get(p,"suspenseFallback",W);return m.jsx(g.Suspense,{fallback:g.createElement(R),children:m.jsx(V,{lang:n,pageProps:c,block:_,dataProvider:x,...k?{dataProviderMetadataCallback:k}:{},draft:r,children:A=>g.createElement(P,{...v,draft:r,...A,children:i({_id:a._id,_type:a._type,...t.isArray(h.repeaterItems)?{repeaterItems:d.applyLimit(h.repeaterItems,a),$repeaterItemsKey:h.$repeaterItemsKey,repeaterTotalItems:h.repeaterTotalItems??-1}:{}})})})})}return g.createElement(P,{...v,draft:r,children:i({_id:a._id,_type:a._type,...t.isArray(h.repeaterItems)?{repeaterItems:d.applyLimit(h.repeaterItems,a),$repeaterItemsKey:h.$repeaterItemsKey,repeaterTotalItems:h.repeaterTotalItems??-1}:{}})})},C=async e=>{const{blocks:a,parent:n,repeaterData:s,type:i}=e;let o=t.uniqBy(t.filter(a,r=>t.has(r,"_id")&&(t.isEmpty(n)?!r._parent:r._parent===n)),"_id");const l=r=>t.filter(a,c=>c._parent===r).length>0;return(i==="Heading"||i==="Paragraph"||i==="Link")&&(o=d.adjustSpacingInContentBlocks(o)),t.map(o,r=>r?g.createElement(U,{dataProviders:e.dataProviders,...e,key:r._id,block:r},({_id:c,_type:k,repeaterItems:u,$repeaterItemsKey:p})=>k==="Repeater"?t.isArray(u)&&u.map((P,f)=>g.createElement(C,{...e,parent:r._id,key:`${t.get(r,"_parent","root")}-${r._id}-${f}`,repeaterData:{index:f,dataKey:p}})):l(c)?g.createElement(C,{...e,parent:r._id,key:`${t.get(r,"_parent","root")}-${r._id}`,repeaterData:s,type:r._type}):null):null)};async function G(e){if(t.isEmpty(e.lang)&&!t.isEmpty(e.fallbackLang))throw new Error("lang prop is required when fallbackLang is provided");if(t.isEmpty(e.blocks))return null;const a=e.lang??"en",n=e.fallbackLang??a;if(e.dataProviders)return m.jsx(C,{...e,lang:a,fallbackLang:n,dataProviders:e.dataProviders});const i=e.blocks.filter(o=>{const l=b.getRegisteredChaiBlock(o._type);return!!(t.has(l,"dataProvider")&&t.isFunction(l.dataProvider))}).reduce((o,l)=>{const r=b.getRegisteredChaiBlock(l._type),c={pageProps:e.pageProps,block:l,lang:e.lang,draft:e.draft,inBuilder:!1};return o[l._id]=r.dataProvider(c),o},{});return m.jsx(C,{...e,lang:a,fallbackLang:n,dataProviders:i})}function z(e,a){const n=e.filter(({_type:s})=>s==="GlobalBlock"||s==="PartialBlock");for(let s=0;s<n.length;s++){const i=n[s],o=t.get(i,"partialBlockId",t.get(i,"globalBlock",""));if(o==="")continue;let l=t.cloneDeep(t.get(a,o,[]));i._parent&&(l==null?void 0:l.length)>0&&(l=l.map(c=>(t.isEmpty(c._parent)&&(c._parent=i._parent),c)));const r=e.indexOf(i);e.splice(r,1,...l)}return e}const Q=e=>{if(!e)return[];try{return JSON.parse(X(e)).filter(n=>!n._type.startsWith("@chai"))}catch{return[{_type:"Paragraph",_id:"error",content:"Invalid JSON. Please check the JSON string."}]}};function X(e){const a=/(asset:\/\/|https:\/\/asset\.localhost\/)(?:localhost\/)?[^"']+/g;return e.replace(a,n=>{const s=decodeURIComponent(n),i=s.indexOf("public");return i!==-1?s.substring(i+6):s})}async function Y(e,a=[],n=!1){return await K.createTailwindcss({tailwindConfig:{darkMode:"class",safelist:a,theme:{extend:{...j.getChaiBuilderTheme(),keyframes:{"accordion-down":{from:{height:"0"},to:{height:"var(--radix-accordion-content-height)"}},"accordion-up":{from:{height:"var(--radix-accordion-content-height)"},to:{height:"0"}}},animation:{"accordion-down":"accordion-down 0.2s ease-out","accordion-up":"accordion-up 0.2s ease-out"}}},plugins:[F,q,D,M,w.chaiBuilderPlugin],corePlugins:{preflight:n}}}).generateStylesFromContent(` ${n?"@tailwind base;":""}
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("./plugin-CSgw-f78.cjs"),d=require("./apply-binding-Bn1KC8uC.cjs"),m=require("react/jsx-runtime"),b=require("@chaibuilder/runtime"),t=require("lodash-es"),g=require("react"),A=require("@tailwindcss/aspect-ratio"),F=require("@tailwindcss/forms"),q=require("@tailwindcss/typography");require("tailwindcss-animate");const j=require("./get-chai-builder-theme-B1tr_NJB.cjs"),K=require("@mhsdesign/jit-browser-tailwindcss"),M=require("@tailwindcss/container-queries");async function O(e){const a={pageProps:e.pageProps,block:e.block,lang:e.lang,draft:e.draft,inBuilder:!1},n=await e.dataProvider(a);return t.has(n,"$metadata")&&t.isFunction(e.dataProviderMetadataCallback)&&e.dataProviderMetadataCallback(e.block,n.$metadata),e.children({...t.omit(n,"$metadata")})}const N=()=>m.jsx("div",{}),H=e=>{const{block:a,lang:n,fallbackLang:s,children:i,externalData:l,blocks:o,draft:r,pageProps:c,dataProviderMetadataCallback:k}=e,u=b.getRegisteredChaiBlock(a._type),p=t.get(u,"component",null),P=t.get(e.repeaterData,"index",-1),f=t.get(e.repeaterData,"dataKey",""),I=n===s?"":n,y=d.applyBindingToBlockProps(d.applyLanguage(a,I,u),l,{index:P,key:f}),h=d.getBlockTagAttributes(a,!1),T=L(o,a._id,d.getBlockRuntimeProps(a._type)),S=t.has(u,"dataProvider")&&t.isFunction(u.dataProvider),B={...y,...h,...T},_={blockProps:{},inBuilder:!1,lang:n||s,pageData:l,...B},v=t.get(B,"_show",!0);if(t.isNull(p)||!v)return null;if(S){const $=t.get(u,"suspenseFallback",N);return m.jsx(g.Suspense,{fallback:g.createElement($),children:m.jsx(O,{lang:n,pageProps:c,block:B,dataProvider:u.dataProvider,...k?{dataProviderMetadataCallback:k}:{},draft:r,children:x=>g.createElement(p,{..._,...x,children:i({_id:a._id,_type:a._type,...t.isArray(y.repeaterItems)?{repeaterItems:d.applyLimit(y.repeaterItems,a),$repeaterItemsKey:y.$repeaterItemsKey,repeaterTotalItems:y.repeaterTotalItems??-1}:{}})})})})}return m.jsx(g.Suspense,{children:g.createElement(p,{..._,children:i({_id:a._id,_type:a._type,...t.isArray(y.repeaterItems)?{repeaterItems:d.applyLimit(y.repeaterItems,a),$repeaterItemsKey:y.$repeaterItemsKey,repeaterTotalItems:y.repeaterTotalItems??-1}:{}})})})},E=e=>{const{blocks:a,parent:n,repeaterData:s,type:i}=e;let l=t.uniqBy(t.filter(a,r=>t.has(r,"_id")&&(t.isEmpty(n)?!r._parent:r._parent===n)),"_id");const o=r=>t.filter(a,c=>c._parent===r).length>0;return(i==="Heading"||i==="Paragraph"||i==="Link"||i==="Span")&&(l=d.adjustSpacingInContentBlocks(l)),t.map(l,r=>r?g.createElement(H,{...e,key:r._id,block:r},({_id:c,_type:k,repeaterItems:u,$repeaterItemsKey:p})=>k==="Repeater"?t.isArray(u)&&u.map((P,f)=>g.createElement(E,{...e,parent:r._id,key:`${t.get(r,"_parent","root")}-${r._id}-${f}`,repeaterData:{index:f,dataKey:p}})):o(c)?g.createElement(E,{...e,parent:r._id,key:`${t.get(r,"_parent","root")}-${r._id}`,repeaterData:s,type:r._type}):null):null)},L=(e,a,n)=>t.isEmpty(n)?{}:Object.entries(n).reduce((s,[i,l])=>{const o=[];let r=t.find(e,{_id:a});for(;r;)o.push(r),r=t.find(e,{_id:r._parent});const c=t.find(o,{_type:l.block});return c&&(s[i]=t.get(c,t.get(l,"prop"),null)),s},{});function J(e){if(t.isEmpty(e.lang)&&!t.isEmpty(e.fallbackLang))throw new Error("lang prop is required when fallbackLang is provided");if(t.isEmpty(e.blocks))return null;const a=e.lang??"en",n=e.fallbackLang??a;return m.jsx(E,{...e,lang:a,fallbackLang:n})}async function V(e){const a=await e.dataProvider;return t.has(a,"$metadata")&&t.isFunction(e.dataProviderMetadataCallback)&&e.dataProviderMetadataCallback(e.block,a.$metadata),e.children({...t.omit(a,"$metadata")})}const W=()=>m.jsx("div",{}),U=async e=>{const{block:a,lang:n,fallbackLang:s,children:i,externalData:l,blocks:o,draft:r,pageProps:c,dataProviderMetadataCallback:k,dataProviders:u}=e,p=b.getRegisteredChaiBlock(a._type),P=t.get(p,"component",null),f=t.get(e.repeaterData,"index",-1),I=t.get(e.repeaterData,"dataKey",""),y=n===s?"":n,h=d.applyBindingToBlockProps(d.applyLanguage(a,y,p),l,{index:f,key:I}),T=d.getBlockTagAttributes(a,!1),S=L(o,a._id,d.getBlockRuntimeProps(a._type)),B=t.has(p,"dataProvider")&&t.isFunction(p.dataProvider),_={...h,...T,...S},v={blockProps:{},inBuilder:!1,lang:n||s,pageData:l,..._},$=t.get(_,"_show",!0);if(t.isNull(P)||!$)return null;if(B){const x=t.get(u,a._id,Promise.resolve({})),D=t.get(p,"suspenseFallback",W);return m.jsx(g.Suspense,{fallback:g.createElement(D),children:m.jsx(V,{lang:n,pageProps:c,block:_,dataProvider:x,...k?{dataProviderMetadataCallback:k}:{},draft:r,children:R=>g.createElement(P,{...v,draft:r,...R,children:i({_id:a._id,_type:a._type,...t.isArray(h.repeaterItems)?{repeaterItems:d.applyLimit(h.repeaterItems,a),$repeaterItemsKey:h.$repeaterItemsKey,repeaterTotalItems:h.repeaterTotalItems??-1}:{}})})})})}return g.createElement(P,{...v,draft:r,children:i({_id:a._id,_type:a._type,...t.isArray(h.repeaterItems)?{repeaterItems:d.applyLimit(h.repeaterItems,a),$repeaterItemsKey:h.$repeaterItemsKey,repeaterTotalItems:h.repeaterTotalItems??-1}:{}})})},C=async e=>{const{blocks:a,parent:n,repeaterData:s,type:i}=e;let l=t.uniqBy(t.filter(a,r=>t.has(r,"_id")&&(t.isEmpty(n)?!r._parent:r._parent===n)),"_id");const o=r=>t.filter(a,c=>c._parent===r).length>0;return(i==="Heading"||i==="Paragraph"||i==="Link")&&(l=d.adjustSpacingInContentBlocks(l)),t.map(l,r=>r?g.createElement(U,{dataProviders:e.dataProviders,...e,key:r._id,block:r},({_id:c,_type:k,repeaterItems:u,$repeaterItemsKey:p})=>k==="Repeater"?t.isArray(u)&&u.map((P,f)=>g.createElement(C,{...e,parent:r._id,key:`${t.get(r,"_parent","root")}-${r._id}-${f}`,repeaterData:{index:f,dataKey:p}})):o(c)?g.createElement(C,{...e,parent:r._id,key:`${t.get(r,"_parent","root")}-${r._id}`,repeaterData:s,type:r._type}):null):null)};async function G(e){if(t.isEmpty(e.lang)&&!t.isEmpty(e.fallbackLang))throw new Error("lang prop is required when fallbackLang is provided");if(t.isEmpty(e.blocks))return null;const a=e.lang??"en",n=e.fallbackLang??a;if(e.dataProviders)return m.jsx(C,{...e,lang:a,fallbackLang:n,dataProviders:e.dataProviders});const i=e.blocks.filter(l=>{const o=b.getRegisteredChaiBlock(l._type);return!!(t.has(o,"dataProvider")&&t.isFunction(o.dataProvider))}).reduce((l,o)=>{const r=b.getRegisteredChaiBlock(o._type),c={pageProps:e.pageProps,block:o,lang:e.lang,draft:e.draft,inBuilder:!1};return l[o._id]=r.dataProvider(c),l},{});return m.jsx(C,{...e,lang:a,fallbackLang:n,dataProviders:i})}function z(e,a){const n=e.filter(({_type:s})=>s==="GlobalBlock"||s==="PartialBlock");for(let s=0;s<n.length;s++){const i=n[s],l=t.get(i,"partialBlockId",t.get(i,"globalBlock",""));if(l==="")continue;let o=t.cloneDeep(t.get(a,l,[]));i._parent&&(o==null?void 0:o.length)>0&&(o=o.map(c=>(t.isEmpty(c._parent)&&(c._parent=i._parent),c)));const r=e.indexOf(i);e.splice(r,1,...o)}return e}const Q=e=>{if(!e)return[];try{return JSON.parse(X(e)).filter(n=>!n._type.startsWith("@chai"))}catch{return[{_type:"Paragraph",_id:"error",content:"Invalid JSON. Please check the JSON string."}]}};function X(e){const a=/(asset:\/\/|https:\/\/asset\.localhost\/)(?:localhost\/)?[^"']+/g;return e.replace(a,n=>{const s=decodeURIComponent(n),i=s.indexOf("public");return i!==-1?s.substring(i+6):s})}async function Y(e,a=[],n=!1){return await K.createTailwindcss({tailwindConfig:{darkMode:"class",safelist:a,theme:{extend:{...j.getChaiBuilderTheme(),keyframes:{"accordion-down":{from:{height:"0"},to:{height:"var(--radix-accordion-content-height)"}},"accordion-up":{from:{height:"var(--radix-accordion-content-height)"},to:{height:"0"}}},animation:{"accordion-down":"accordion-down 0.2s ease-out","accordion-up":"accordion-up 0.2s ease-out"}}},plugins:[F,q,A,M,w.chaiBuilderPlugin],corePlugins:{preflight:n}}}).generateStylesFromContent(` ${n?"@tailwind base;":""}
2
2
  @tailwind components;
3
3
  @tailwind utilities;`,e)}const Z=(e,a)=>{const n=JSON.stringify(e).replace(/#styles:([^"]*)/g,(s,i)=>`#styles:${i.replace(/,/g," ")}`.replace(/#styles:/g,""));return Y([n],[],a)},ee=async(e,a=!1)=>await Z(e,a);exports.getChaiThemeCssVariables=w.getChaiThemeCssVariables;exports.getThemeFontsCSSImport=w.getThemeFontsCSSImport;exports.getThemeFontsLinkMarkup=w.getThemeFontsLinkMarkup;exports.applyChaiDataBinding=d.applyChaiDataBinding;exports.applyDesignTokens=d.applyDesignTokens;exports.convertHTMLToChaiBlocks=d.getBlocksFromHTML;exports.AsyncRenderChaiBlocks=G;exports.RenderChaiBlocks=J;exports.convertToBlocks=Q;exports.getMergedPartialBlocks=z;exports.getStylesForBlocks=ee;
package/dist/render.d.ts CHANGED
@@ -104,7 +104,7 @@ declare type RenderChaiBlocksProps = {
104
104
  declare type RenderChaiBlocksProps_2 = {
105
105
  blocks: ChaiBlock[];
106
106
  parent?: string;
107
- externalData?: Record<string, any>;
107
+ externalData?: Record<string, unknown>;
108
108
  lang?: string;
109
109
  fallbackLang?: string;
110
110
  pageProps?: ChaiPageProps;