@usefillo/dom 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Fillo=(()=>{var pt=Object.defineProperty;var eo=Object.getOwnPropertyDescriptor;var to=Object.getOwnPropertyNames;var ro=Object.prototype.hasOwnProperty;var no=(e,t)=>{for(var r in t)pt(e,r,{get:t[r],enumerable:!0})},oo=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of to(t))!ro.call(e,n)&&n!==r&&pt(e,n,{get:()=>t[n],enumerable:!(o=eo(t,n))||o.enumerable});return e};var io=e=>oo(pt({},"__esModule",{value:!0}),e);var rs={};no(rs,{FilloClient:()=>st,FilloError:()=>x,createClient:()=>Te,createFormElement:()=>Vn,defineForm:()=>Qt,registerFilloElement:()=>ir,renderForm:()=>lt});var ur;function k(e,t,r){function o(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let u=s.prototype,c=Object.keys(u);for(let p=0;p<c.length;p++){let f=c[p];f in a||(a[f]=u[f].bind(a))}}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function s(a){var l;let u=r?.Parent?new i:this;o(u,a),(l=u._zod).deferred??(l.deferred=[]);for(let c of u._zod.deferred)c();return u}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var te=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(ur=globalThis).__zod_globalConfig??(ur.__zod_globalConfig={});var ft=globalThis.__zod_globalConfig;function le(e){return e&&Object.assign(ft,e),ft}function dr(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function pr(e,t){return typeof t=="bigint"?t.toString():t}function fr(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function mt(e){return e==null}function hr(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}var cr=Symbol("evaluating");function ue(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==cr)return o===void 0&&(o=cr,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}var gt="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bt(e){if(Be(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Be(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function yt(e){return bt(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var mr=new Set(["string","number","symbol"]);function Ee(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vt(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function L(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function gr(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var so={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ae(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function br(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function ce(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function je(e){return typeof e=="string"?e:e?.message}function de(e,t,r){let o=e.message?e.message:je(e.inst?._zod.def?.error?.(e))??je(t?.error?.(e))??je(r.customError?.(e))??je(r.localeError?.(e))??"Invalid input",{inst:n,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=o,t?.reportInput&&(a.input=s),a}function _t(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}var yr=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,pr,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},vr=k("$ZodError",yr),Ce=k("$ZodError",yr,{Parent:Error});var lo=e=>(t,r,o,n)=>{let i=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new te;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map(l=>de(l,i,le())));throw gt(a,n?.callee),a}return s.value},Ve=lo(Ce),uo=e=>async(t,r,o,n)=>{let i=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(n?.Err??e)(s.issues.map(l=>de(l,i,le())));throw gt(a,n?.callee),a}return s.value},He=uo(Ce),co=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new te;return i.issues.length?{success:!1,error:new(e??vr)(i.issues.map(s=>de(s,n,le())))}:{success:!0,data:i.value}},Fe=co(Ce),po=e=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>de(s,n,le())))}:{success:!0,data:i.value}},Ie=po(Ce);var _r=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var fo="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",ho=new RegExp(`^${fo}$`);var wr=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var wt=/^-?\d+(?:\.\d+)?$/;var ge=k("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),mo={number:"number",bigint:"bigint",object:"date"};var $r=k("$ZodCheckGreaterThan",(e,t)=>{ge.init(e,t);let r=mo[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}});var kr=k("$ZodCheckMaxLength",(e,t)=>{var r;ge.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!mt(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;if(n.length<=t.maximum)return;let s=_t(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),zr=k("$ZodCheckMinLength",(e,t)=>{var r;ge.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!mt(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;if(n.length>=t.minimum)return;let s=_t(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}});var Sr=k("$ZodCheckStringFormat",(e,t)=>{var r,o;ge.init(e,t),e._zod.onattach.push(n=>{let i=n._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})});var Ar={major:4,minor:4,patch:3};var V=k("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ar;let o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(let n of o)for(let i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(s,a,l)=>{let u=Ae(s),c;for(let p of a){if(p._zod.def.when){if(br(s)||!p._zod.def.when(s))continue}else if(u)continue;let f=s.issues.length,h=p._zod.check(s);if(h instanceof Promise&&l?.async===!1)throw new te;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,s.issues.length!==f&&(u||(u=Ae(s,f)))});else{if(s.issues.length===f)continue;u||(u=Ae(s,f))}}return c?c.then(()=>s):s},i=(s,a,l)=>{if(Ae(s))return s.aborted=!0,s;let u=n(a,o,l);if(u instanceof Promise){if(l.async===!1)throw new te;return u.then(c=>e._zod.parse(c,l))}return e._zod.parse(u,l)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let u=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(c=>i(c,s,a)):i(u,s,a)}let l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new te;return l.then(u=>n(u,o,a))}return n(l,o,a)}}ue(e,"~standard",()=>({validate:n=>{try{let i=Fe(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Ie(e,n).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),xt=k("$ZodString",(e,t)=>{V.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??wr(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),$t=k("$ZodStringFormat",(e,t)=>{Sr.init(e,t),xt.init(e,t)});var Pr=k("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=_r),$t.init(e,t)});var Zr=k("$ZodNumber",(e,t)=>{V.init(e,t),e._zod.pattern=e._zod.bag.pattern??wt,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}});var Nr=k("$ZodUnknown",(e,t)=>{V.init(e,t),e._zod.parse=r=>r});function Cr(e,t,r){e.issues.length&&t.issues.push(...ce(r,e.issues)),t.value[r]=e.value}var Mr=k("$ZodArray",(e,t)=>{V.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let s=0;s<n.length;s++){let a=n[s],l=t.element._zod.run({value:a,issues:[]},o);l instanceof Promise?i.push(l.then(u=>Cr(u,r,s))):Cr(l,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function qe(e,t,r,o,n,i){let s=r in o;if(e.issues.length){if(n&&i&&!s)return;t.issues.push(...ce(r,e.issues))}if(!s&&!n){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?s&&(t.value[r]=void 0):t.value[r]=e.value}function bo(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);let r=gr(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function yo(e,t,r,o,n,i){let s=[],a=n.keySet,l=n.catchall._zod,u=l.def.type,c=l.optin==="optional",p=l.optout==="optional";for(let f in t){if(f==="__proto__"||a.has(f))continue;if(u==="never"){s.push(f);continue}let h=l.run({value:t[f],issues:[]},o);h instanceof Promise?e.push(h.then(m=>qe(m,r,f,t,c,p))):qe(h,r,f,t,c,p)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}var Lr=k("$ZodObject",(e,t)=>{if(V.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let o=fr(()=>bo(t));ue(e._zod,"propValues",()=>{let a=t.shape,l={};for(let u in a){let c=a[u]._zod;if(c.values){l[u]??(l[u]=new Set);for(let p of c.values)l[u].add(p)}}return l});let n=Be,i=t.catchall,s;e._zod.parse=(a,l)=>{s??(s=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let c=[],p=s.shape;for(let f of s.keys){let h=p[f],m=h._zod.optin==="optional",y=h._zod.optout==="optional",S=h._zod.run({value:u[f],issues:[]},l);S instanceof Promise?c.push(S.then(ie=>qe(ie,a,f,u,m,y))):qe(S,a,f,u,m,y)}return i?yo(c,u,a,l,o.value,e):c.length?Promise.all(c).then(()=>a):a}});var Tr=k("$ZodRecord",(e,t)=>{V.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!bt(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let i=[],s=t.keyType._zod.values;if(s){r.value={};let a=new Set;for(let u of s)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let c=t.keyType._zod.run({value:u,issues:[]},o);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(h=>de(h,o,le())),input:u,path:[u],inst:e});continue}let p=c.value,f=t.valueType._zod.run({value:n[u],issues:[]},o);f instanceof Promise?i.push(f.then(h=>{h.issues.length&&r.issues.push(...ce(u,h.issues)),r.value[p]=h.value})):(f.issues.length&&r.issues.push(...ce(u,f.issues)),r.value[p]=f.value)}let l;for(let u in n)a.has(u)||(l=l??[],l.push(u));l&&l.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:l})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(n,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},o);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&wt.test(a)&&l.issues.length){let p=t.keyType._zod.run({value:Number(a),issues:[]},o);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(l=p)}if(l.issues.length){t.mode==="loose"?r.value[a]=n[a]:r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(p=>de(p,o,le())),input:a,path:[a],inst:e});continue}let c=t.valueType._zod.run({value:n[a],issues:[]},o);c instanceof Promise?i.push(c.then(p=>{p.issues.length&&r.issues.push(...ce(a,p.issues)),r.value[l.value]=p.value})):(c.issues.length&&r.issues.push(...ce(a,c.issues)),r.value[l.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Rr=k("$ZodEnum",(e,t)=>{V.init(e,t);let r=dr(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter(n=>mr.has(typeof n)).map(n=>typeof n=="string"?Ee(n):n.toString()).join("|")})$`),e._zod.parse=(n,i)=>{let s=n.value;return o.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),Or=k("$ZodLiteral",(e,t)=>{if(V.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(o=>typeof o=="string"?Ee(o):o?Ee(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),o}});function Fr(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Dr=k("$ZodOptional",(e,t)=>{V.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ue(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ue(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${hr(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,i=t.innerType._zod.run(r,o);return i instanceof Promise?i.then(s=>Fr(s,n)):Fr(i,n)}return r.value===void 0?r:t.innerType._zod.run(r,o)}});var Ur=k("$ZodDefault",(e,t)=>{V.init(e,t),e._zod.optin="optional",ue(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>Ir(i,t)):Ir(n,t)}});function Ir(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function jr(e,t){return new e({type:"string",...L(t)})}function Br(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...L(t)})}function Vr(e,t){return new e({type:"number",checks:[],...L(t)})}function Hr(e){return new e({type:"unknown"})}function kt(e,t){return new $r({check:"greater_than",...L(t),value:e,inclusive:!0})}function zt(e){return kt(0,e)}function R(e,t){return new kr({check:"max_length",...L(t),maximum:e})}function xe(e,t){return new zr({check:"min_length",...L(t),minimum:e})}var Y=k("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");V.init(e,t),e.def=t,e.type=t.type,e.parse=(r,o)=>Ve(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Fe(e,r,o),e.parseAsync=async(r,o)=>He(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>Ie(e,r,o),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]},{parent:!0}),e.with=e.check,e.clone=(r,o)=>vt(e,r,o),e.brand=()=>e,e.register=((r,o)=>(r.add(e,o),e)),e.apply=r=>r(e)}),Kr=k("ZodMiniString",(e,t)=>{xt.init(e,t),Y.init(e,t)});function O(e){return jr(Kr,e)}var _o=k("ZodMiniStringFormat",(e,t)=>{$t.init(e,t),Kr.init(e,t)}),wo=k("ZodMiniEmail",(e,t)=>{Pr.init(e,t),_o.init(e,t)});function Ke(e){return Br(wo,e)}var xo=k("ZodMiniNumber",(e,t)=>{Zr.init(e,t),Y.init(e,t)});function Wr(e){return Vr(xo,e)}var $o=k("ZodMiniUnknown",(e,t)=>{Nr.init(e,t),Y.init(e,t)});function We(){return Hr($o)}var ko=k("ZodMiniArray",(e,t)=>{Mr.init(e,t),Y.init(e,t)});function pe(e,t){return new ko({type:"array",element:e,...L(t)})}var Gr=k("ZodMiniObject",(e,t)=>{Lr.init(e,t),Y.init(e,t),ue(e,"shape",()=>t.shape)});function Pe(e,t){let r={type:"object",shape:e??{},...L(t)};return new Gr(r)}function St(e,t){return new Gr({type:"object",shape:e,catchall:We(),...L(t)})}var qr=k("ZodMiniRecord",(e,t)=>{Tr.init(e,t),Y.init(e,t)});function Jr(e,t,r){return!t||!t._zod?new qr({type:"record",keyType:O(),valueType:e,...L(t)}):new qr({type:"record",keyType:e,valueType:t,...L(r)})}var zo=k("ZodMiniEnum",(e,t)=>{Rr.init(e,t),Y.init(e,t),e.options=Object.values(t.entries)});function Xr(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new zo({type:"enum",entries:r,...L(t)})}var So=k("ZodMiniLiteral",(e,t)=>{Or.init(e,t),Y.init(e,t)});function Yr(e,t){return new So({type:"literal",values:Array.isArray(e)?e:[e],...L(t)})}var Eo=k("ZodMiniOptional",(e,t)=>{Dr.init(e,t),Y.init(e,t)});function H(e){return new Eo({type:"optional",innerType:e})}var Ao=k("ZodMiniDefault",(e,t)=>{Ur.init(e,t),Y.init(e,t)});function Et(e,t){return new Ao({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():yt(t)}})}var Io=["heading","paragraph","divider"];function he(e){return!Io.includes(e.kind)}function At(e){return e==null?!1:typeof e=="string"?e.trim()!=="":Array.isArray(e)?e.length>0:typeof e=="boolean"?e:typeof e=="object"?Object.keys(e).length>0:!0}function Qr(e,t){return e===t?!0:typeof e=="number"&&typeof t=="string"&&t.trim()!==""?Number(t)===e:typeof t=="number"&&typeof e=="string"&&e.trim()!==""?Number(e)===t:!1}function en(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;let t=Number(e);return Number.isFinite(t)?t:null}function Po(e,t){let r=t(e.fieldId);switch(e.op){case"answered":return At(r);case"not_answered":return!At(r);case"eq":return Array.isArray(r)?r.some(o=>o===e.value):Qr(r,e.value);case"neq":return At(r)?Array.isArray(r)?!r.some(o=>o===e.value):!Qr(r,e.value):!1;case"contains":return typeof r=="string"?r.toLowerCase().includes(String(e.value??"").toLowerCase()):Array.isArray(r)?r.some(o=>o===e.value):!1;case"gt":case"lt":{let o=en(r),n=en(e.value);return o!==null&&n!==null&&(e.op==="gt"?o>n:o<n)}}}function hn(e,t){return!e.visibleIf||e.visibleIf.length===0?!0:e.visibleIf.every(r=>Po(r,t))}function mn(e,t,r){return o=>t.has(o)&&!r.has(o)?void 0:e[o]}function gn(e,t){let r=new Set(e.map(n=>n.id)),o=r;for(let n=0;n<=e.length;n++){let i=mn(t,r,o),s=new Set;for(let a of e)hn(a,i)&&s.add(a.id);if(s.size===o.size&&[...s].every(a=>o.has(a)))return s;o=s}return o}function Ge(e,t,r){let o=tt(e),n=new Set(o.map(a=>a.id)),i=gn(o,r),s=mn(r,n,i);return t.blocks.filter(a=>he(a)?i.has(a.id):hn(a,s))}function tt(e){return e.pages.flatMap(t=>t.blocks.filter(he))}function bn(e,t){let r=e.responseLimit?.scopeField;if(!r)return null;let o=t[r];return typeof o=="number"?Number.isFinite(o)?String(o):null:typeof o!="string"?null:o.trim()||null}function rt(e,t){let r=tt(e),o=gn(r,t);return r.filter(n=>o.has(n.id))}var g=(e,t,r,o=[],n=[],i="")=>({iso2:e,name:t,dialCode:r,lengths:o,groups:n,example:i}),ne=[g("US","United States","1",[10],[3,3,4],"2015550123"),g("CA","Canada","1",[10],[3,3,4],"5145550123"),g("GB","United Kingdom","44",[10],[4,6],"7400123456"),g("AU","Australia","61",[9],[3,3,3],"412345678"),g("DE","Germany","49",[10,11],[4,7],"15123456789"),g("FR","France","33",[9],[1,2,2,2,2],"612345678"),g("IN","India","91",[10],[5,5],"8123456789"),g("DK","Denmark","45",[8],[2,2,2,2],"32123456"),g("SE","Sweden","46",[9],[2,3,4],"701234567"),g("NO","Norway","47",[8],[3,2,3],"40612345"),g("FI","Finland","358",[9,10],[2,3,4],"412345678"),g("NL","Netherlands","31",[9],[1,4,4],"612345678"),g("BE","Belgium","32",[9],[3,2,2,2],"470123456"),g("ES","Spain","34",[9],[3,3,3],"612345678"),g("IT","Italy","39",[9,10],[3,3,4],"3123456789"),g("PT","Portugal","351",[9],[3,3,3],"912345678"),g("IE","Ireland","353",[9],[2,3,4],"851234567"),g("CH","Switzerland","41",[9],[2,3,2,2],"781234567"),g("AT","Austria","43",[10,11],[3,7],"6641234567"),g("PL","Poland","48",[9],[3,3,3],"512345678"),g("CZ","Czechia","420",[9],[3,3,3],"601123456"),g("GR","Greece","30",[10],[3,3,4],"6912345678"),g("RO","Romania","40",[9],[3,3,3],"712345678"),g("HU","Hungary","36",[9],[2,3,4],"201234567"),g("UA","Ukraine","380",[9],[2,3,2,2],"501234567"),g("RU","Russia","7",[10],[3,3,2,2],"9123456789"),g("TR","Turkey","90",[10],[3,3,2,2],"5012345678"),g("IL","Israel","972",[9],[2,3,4],"501234567"),g("AE","United Arab Emirates","971",[9],[2,3,4],"501234567"),g("SA","Saudi Arabia","966",[9],[2,3,4],"512345678"),g("ZA","South Africa","27",[9],[2,3,4],"711234567"),g("NG","Nigeria","234",[10],[3,3,4],"8021234567"),g("KE","Kenya","254",[9],[3,3,3],"712123456"),g("EG","Egypt","20",[10],[3,3,4],"1001234567"),g("BR","Brazil","55",[10,11],[2,5,4],"11961234567"),g("MX","Mexico","52",[10],[3,3,4],"2221234567"),g("AR","Argentina","54",[10],[4,6],"1123456789"),g("CL","Chile","56",[9],[1,4,4],"221234567"),g("CO","Colombia","57",[10],[3,3,4],"3211234567"),g("PE","Peru","51",[9],[3,3,3],"912345678"),g("CN","China","86",[11],[3,4,4],"13123456789"),g("JP","Japan","81",[10],[2,4,4],"9012345678"),g("KR","South Korea","82",[9,10],[2,4,4],"1023456789"),g("SG","Singapore","65",[8],[4,4],"81234567"),g("HK","Hong Kong","852",[8],[4,4],"51234567"),g("TW","Taiwan","886",[9],[3,3,3],"912345678"),g("MY","Malaysia","60",[9,10],[2,3,4],"123456789"),g("ID","Indonesia","62",[10,11],[3,4,4],"81234567890"),g("TH","Thailand","66",[9],[2,3,4],"812345678"),g("PH","Philippines","63",[10],[3,3,4],"9171234567"),g("VN","Vietnam","84",[9],[3,3,3],"912345678"),g("PK","Pakistan","92",[10],[3,3,4],"3012345678"),g("BD","Bangladesh","880",[10],[2,4,4],"1812345678"),g("NZ","New Zealand","64",[9,10],[2,3,4],"211234567"),g("SK","Slovakia","421",[9],[3,3,3],"912123456"),g("BG","Bulgaria","359",[9],[2,3,4],"481234567"),g("HR","Croatia","385",[8,9],[2,3,4],"921234567"),g("RS","Serbia","381",[8,9],[2,3,4],"601234567"),g("SI","Slovenia","386",[8],[2,3,3],"31234567"),g("LT","Lithuania","370",[8],[3,2,3],"61234567"),g("LV","Latvia","371",[8],[2,3,3],"21234567"),g("EE","Estonia","372",[7,8],[3,4],"51234567"),g("IS","Iceland","354",[7],[3,4],"6111234"),g("LU","Luxembourg","352",[9],[3,3,3],"628123456"),g("MA","Morocco","212",[9],[3,3,3],"650123456"),g("CR","Costa Rica","506",[8],[4,4],"83123456"),g("EC","Ecuador","593",[9],[2,3,4],"991234567"),g("UY","Uruguay","598",[8],[1,3,4],"94231234"),g("QA","Qatar","974",[8],[4,4],"33123456"),g("KW","Kuwait","965",[8],[4,4],"50012345")],Zo=new Map(ne.map(e=>[e.iso2,e])),No={"Africa/Cairo":"EG","Africa/Casablanca":"MA","Africa/Johannesburg":"ZA","Africa/Lagos":"NG","Africa/Nairobi":"KE","America/Adak":"US","America/Anchorage":"US","America/Argentina/Buenos_Aires":"AR","America/Argentina/Cordoba":"AR","America/Argentina/Mendoza":"AR","America/Bahia":"BR","America/Belem":"BR","America/Bogota":"CO","America/Boise":"US","America/Boa_Vista":"BR","America/Cancun":"MX","America/Chicago":"US","America/Chihuahua":"MX","America/Campo_Grande":"BR","America/Costa_Rica":"CR","America/Cuiaba":"BR","America/Denver":"US","America/Detroit":"US","America/Edmonton":"CA","America/Fortaleza":"BR","America/Guayaquil":"EC","America/Halifax":"CA","America/Hermosillo":"MX","America/Indiana/Indianapolis":"US","America/Indianapolis":"US","America/Juneau":"US","America/Kentucky/Louisville":"US","America/Lima":"PE","America/Los_Angeles":"US","America/Maceio":"BR","America/Manaus":"BR","America/Matamoros":"MX","America/Mazatlan":"MX","America/Merida":"MX","America/Mexico_City":"MX","America/Moncton":"CA","America/Monterrey":"MX","America/Montevideo":"UY","America/New_York":"US","America/Noronha":"BR","America/Nome":"US","America/North_Dakota/Center":"US","America/Ojinaga":"MX","America/Phoenix":"US","America/Porto_Velho":"BR","America/Punta_Arenas":"CL","America/Recife":"BR","America/Regina":"CA","America/Rio_Branco":"BR","America/Santiago":"CL","America/Sao_Paulo":"BR","America/Sitka":"US","America/St_Johns":"CA","America/Tijuana":"MX","America/Toronto":"CA","America/Vancouver":"CA","America/Whitehorse":"CA","America/Winnipeg":"CA","America/Yakutat":"US","Asia/Bangkok":"TH","Asia/Calcutta":"IN","Asia/Dacca":"BD","Asia/Dhaka":"BD","Asia/Dubai":"AE","Asia/Hong_Kong":"HK","Asia/Ho_Chi_Minh":"VN","Asia/Jakarta":"ID","Asia/Jerusalem":"IL","Asia/Karachi":"PK","Asia/Kolkata":"IN","Asia/Kuala_Lumpur":"MY","Asia/Kuwait":"KW","Asia/Manila":"PH","Asia/Qatar":"QA","Asia/Riyadh":"SA","Asia/Seoul":"KR","Asia/Shanghai":"CN","Asia/Saigon":"VN","Asia/Singapore":"SG","Asia/Taipei":"TW","Asia/Tel_Aviv":"IL","Asia/Tokyo":"JP","Asia/Urumqi":"CN","Atlantic/Reykjavik":"IS","Australia/Adelaide":"AU","Australia/Brisbane":"AU","Australia/Darwin":"AU","Australia/Hobart":"AU","Australia/Melbourne":"AU","Australia/Perth":"AU","Australia/Sydney":"AU","Europe/Amsterdam":"NL","Europe/Athens":"GR","Europe/Belgrade":"RS","Europe/Berlin":"DE","Europe/Bratislava":"SK","Europe/Brussels":"BE","Europe/Bucharest":"RO","Europe/Budapest":"HU","Europe/Copenhagen":"DK","Europe/Dublin":"IE","Europe/Helsinki":"FI","Europe/Zagreb":"HR","Europe/Istanbul":"TR","Europe/Kiev":"UA","Europe/Kyiv":"UA","Europe/Lisbon":"PT","Europe/Ljubljana":"SI","Europe/London":"GB","Europe/Luxembourg":"LU","Europe/Madrid":"ES","Europe/Moscow":"RU","Europe/Oslo":"NO","Europe/Paris":"FR","Europe/Prague":"CZ","Europe/Riga":"LV","Europe/Rome":"IT","Europe/Sofia":"BG","Europe/Stockholm":"SE","Europe/Tallinn":"EE","Europe/Vienna":"AT","Europe/Vilnius":"LT","Europe/Warsaw":"PL","Europe/Zurich":"CH","Pacific/Auckland":"NZ"};function Vt(e){let t=e.toUpperCase();return/^[A-Z]{2}$/.test(t)?String.fromCodePoint(...[...t].map(r=>127462+r.charCodeAt(0)-65)):"\u{1F3F3}\uFE0F"}function nt(e){return e?Zo.get(e.toUpperCase()):void 0}function yn(e){return nt(e?No[e]:void 0)}function Mo(e){let t;for(let r of ne)e.startsWith(r.dialCode)&&(!t||r.dialCode.length>t.dialCode.length)&&(t=r);return t}function oe(e){return e.replace(/[^\d]/g,"")}function ot(e,t){let r=oe(t);if(!r)return"";let o=e?.groups?.length?e.groups:[],n=[],i=0;for(let s of o){if(i>=r.length)break;n.push(r.slice(i,i+s)),i+=s}for(;i<r.length;)n.push(r.slice(i,i+3)),i+=3;return n.join(" ")}function vn(e,t){let r=oe(t);return r?`+${e.dialCode}${r}`:""}function it(e,t){let r=(e??"").trim(),o=r.startsWith("+"),n=oe(r);if(!n)return{country:t,national:"",e164:""};if(o){let i=Mo(n);if(i){let s=n.slice(i.dialCode.length);return{country:i,national:s,e164:`+${n}`}}return{national:n,e164:`+${n}`}}if(t){let i=n.startsWith(t.dialCode)?n.slice(t.dialCode.length):n;return{country:t,national:i,e164:`+${t.dialCode}${i}`}}return{national:n,e164:`+${n}`}}function Lo(e){let{country:t,national:r,e164:o}=it(e);if(!o)return!1;let n=oe(o).length;return n<8||n>15?!1:t?.lengths.length?t.lengths.includes(r.length):r.length>=4}var To=8;function _n(e,t){if(!e||!t||typeof window>"u")return"below";let r=To,o=document.documentElement.clientWidth||window.innerWidth,n=document.documentElement.clientHeight||window.innerHeight,i=e.getBoundingClientRect(),s=Math.max(0,n-i.bottom-r),a=Math.max(0,i.top-r),l=s<t.scrollHeight&&a>s?"above":"below",c=Math.max(0,Math.min(l==="above"?a:s,n-r*2)),p=Math.max(0,o-r*2);t.style.setProperty("--fillo-phone-popover-max-height",`${Math.floor(c)}px`),t.style.setProperty("--fillo-phone-popover-max-width",`${Math.floor(p)}px`),t.style.setProperty("--fillo-phone-popover-offset-x","0px");let f=Math.min(t.offsetWidth,p),h=0,m=i.left+f-(o-r);m>0&&(h-=m);let y=r-(i.left+h);return y>0&&(h+=y),t.style.setProperty("--fillo-phone-popover-offset-x",`${Math.round(h)}px`),l}var Ro="This field is required";var Oo=Pe({fileId:O().check(xe(1)),name:O(),size:Wr().check(zt()),mime:O(),url:H(O())});function wn(e){return e==null?!0:typeof e=="string"?e.trim()==="":Array.isArray(e)?e.length===0:typeof e=="boolean"?e===!1:typeof e=="object"?Object.keys(e).length===0:!1}function xn(e,t){if(wn(t))return e.required?Ro:null;switch(e.kind){case"short_text":case"long_text":{if(typeof t!="string")return"Expected text";if(e.maxLength&&t.length>e.maxLength)return`Must be at most ${e.maxLength} characters`;let r=e.kind==="long_text"?2e4:2e3;return!e.maxLength&&t.length>r?"Answer is too long":null}case"email":return typeof t!="string"?"Enter a valid email address":e.maxLength&&t.length>e.maxLength?`Must be at most ${e.maxLength} characters`:Ke().safeParse(t).success?null:"Enter a valid email address";case"url":{if(typeof t!="string")return"Enter a valid URL (including https://)";if(e.maxLength&&t.length>e.maxLength)return`Must be at most ${e.maxLength} characters`;try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:")return"Enter an http(s) URL"}catch{return"Enter a valid URL (including https://)"}return null}case"phone":return typeof t!="string"||!Lo(t)?"Enter a valid phone number":null;case"number":{let r=typeof t=="string"?Number(t):t;return typeof r!="number"||!Number.isFinite(r)?"Enter a number":e.min!==void 0&&r<e.min?`Must be at least ${e.min}`:e.max!==void 0&&r>e.max?`Must be at most ${e.max}`:null}case"select":case"dropdown":return typeof t!="string"||t===""?"Pick an option":e.options.some(r=>r.id===t)||e.allowOther&&t.length<=500?null:"Pick a valid option";case"multi_select":{if(!Array.isArray(t))return"Pick at least one option";let r=new Set(e.options.map(s=>s.id)),o=t,n=0,i=new Set;for(let s of o){if(typeof s!="string")return"Pick valid options";if(i.has(s))return"Pick each option only once";if(i.add(s),!r.has(s)){if(e.allowOther!==!0||s.length===0||s.length>500)return"Pick valid options";if(++n>1)return"Only one 'Other' answer is allowed"}}return null}case"checkbox":return typeof t=="boolean"?null:"Invalid value";case"rating":{let r=e.max??5,o=typeof t=="string"?Number(t):t;return typeof o!="number"||!Number.isInteger(o)||o<1||o>r?`Pick a rating between 1 and ${r}`:null}case"linear_scale":{let r=e.min??1,o=e.max??10,n=typeof t=="string"?Number(t):t;return typeof n!="number"||!Number.isInteger(n)||n<r||n>o?`Pick a value between ${r} and ${o}`:null}case"ranking":{if(!Array.isArray(t))return"Drag the options into order";let r=e.options.map(n=>n.id).sort(),o=[...t].sort();return r.length!==o.length||r.some((n,i)=>n!==o[i])?"Rank every option":null}case"matrix":{if(typeof t!="object"||t===null||Array.isArray(t))return"Answer the grid";let r=t,o=new Set(e.columns.map(i=>i.id)),n=new Set(e.rows.map(i=>i.id));for(let[i,s]of Object.entries(r))if(!n.has(i)||!o.has(s))return"Invalid grid answer";return e.required&&Object.keys(r).length<e.rows.length?"Answer every row":null}case"signature":return typeof t!="string"||!t.startsWith("data:image/")?"Sign in the box":null;case"hidden":return typeof t=="string"?null:"Invalid value";case"custom":return null;case"date":{if(typeof t!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(t))return"Enter a valid date";let[r,o,n]=t.split("-").map(Number),i=new Date(Date.UTC(r,o-1,n));return i.getUTCFullYear()!==r||i.getUTCMonth()!==o-1||i.getUTCDate()!==n?"Enter a valid date":null}case"file_upload":{let r=pe(Oo).safeParse(t);if(!r.success)return"Upload did not complete";let o=e.maxFiles??1;return r.data.length>o?`At most ${o} file${o===1?"":"s"}`:null}}}function $n(e,t){let r=rt(e,t),o={},n={};for(let i of r){let s=Do(i,t[i.id]),a=xn(i,s);a?o[i.id]=a:wn(s)||(n[i.id]=s)}return{ok:Object.keys(o).length===0,errors:o,data:n}}function Do(e,t){if(t==null||e.kind==="custom")return t;if(e.kind==="number"&&typeof t=="string"&&t.trim()!==""){let r=Number(t);return Number.isNaN(r)?t:r}if((e.kind==="rating"||e.kind==="linear_scale")&&typeof t=="string"){let r=Number(t);return Number.isNaN(r)?t:r}return typeof t=="string"?t.trim():t}var Uo=["short_text","long_text","email","url","phone","number","select","multi_select","dropdown","checkbox","rating","linear_scale","ranking","matrix","signature","date","file_upload","hidden","custom"],jo=["heading","paragraph","divider"],Bo=[...Uo,...jo],Ht=O().check(xe(1),R(128)),Ct=St({id:Ht,label:O().check(R(1e3)),icon:H(We())}),Vo=St({id:Ht,kind:Xr(Bo),label:H(O().check(R(2e3))),options:H(pe(Ct).check(R(200))),rows:H(pe(Ct).check(R(200))),columns:H(pe(Ct).check(R(200)))}),Ho=Pe({id:Ht,title:H(O().check(R(500))),blocks:pe(Vo).check(R(500))}),qo=Pe({version:Yr(1),title:Et(H(O().check(R(2e3))),""),description:H(O().check(R(5e3))),pages:pe(Ho).check(xe(1),R(50)),settings:Et(H(Jr(O(),We())),{})}),Ko=1,Ot=1,Dt="0.8.0";function W(e,t,r=""){return typeof e=="string"?e.trim().slice(0,t):r}function N(e,t){let r=W(e,t);return r===""?void 0:r}function re(e){return typeof e=="boolean"?e:void 0}function Le(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function be(e,t,r,o){let n=Le(e);return n===void 0?o:Math.max(t,Math.min(r,Math.round(n)))}function Je(e,t=200){return Array.isArray(e)?e.slice(0,t).flatMap(r=>{if(!r||typeof r!="object")return[];let o=r,n=W(o.id,128),i=W(o.label,1e3),s=o.icon==="thumbs_up"||o.icon==="thumbs_down"?o.icon:void 0;return n&&i?[I({id:n,label:i,icon:s})]:[]}):[]}function Ft(e){let t=new Set;for(let{id:r}of e){if(t.has(r))return r;t.add(r)}}function Wo(e){if(!Array.isArray(e))return;let t=e.slice(0,20).flatMap(r=>{if(!r||typeof r!="object")return[];let o=r,n=o.op;if(n!=="eq"&&n!=="neq"&&n!=="contains"&&n!=="gt"&&n!=="lt"&&n!=="answered"&&n!=="not_answered")return[];let i=W(o.fieldId,128);if(!i)return[];let s=o.value,a=typeof s=="string"||typeof s=="number"||typeof s=="boolean"?s:void 0;return[{fieldId:i,op:n,...a!==void 0?{value:a}:{}}]});return t.length?t:void 0}function kn(e){return{id:W(e.id,128),visibleIf:Wo(e.visibleIf)}}function D(e,t){return{...kn(e),kind:t,label:W(e.label,2e3,"Untitled field"),description:N(e.description,5e3),required:re(e.required),placeholder:N(e.placeholder,500)}}function tn(e){let t=N(e,2e3);if(t)try{let r=new URL(t);return r.protocol==="http:"||r.protocol==="https:"?t:void 0}catch{return}}function Go(e){if(!e||typeof e!="object")return;let t=e,r=t.by==="browser"||t.by==="field"||t.by==="identify"?t.by:void 0;if(!r)return;let o=r==="field"?N(t.field,128):void 0;if(r==="field"&&!o)return;let n=N(t.scopeField,128),i=t.onRepeat==="update"&&r==="identify"?"update":"keep";return{by:r,...o?{field:o}:{},...n?{scopeField:n}:{},onRepeat:i}}function Jo(e){let t=e&&typeof e=="object"?e:{};return{submitMode:t.submitMode==="button"||t.submitMode==="auto"?t.submitMode:void 0,submitLabel:N(t.submitLabel,100),successTitle:N(t.successTitle,200),successMessage:N(t.successMessage,5e3),redirectUrl:tn(t.redirectUrl),showProgress:re(t.showProgress),responseLimit:Go(t.responseLimit),notifyEmail:Ke().check(R(254)).safeParse(t.notifyEmail).success?t.notifyEmail:void 0,sendReceipt:re(t.sendReceipt),saveProgress:re(t.saveProgress),draftAnswersVisible:re(t.draftAnswersVisible),resumeEmails:re(t.resumeEmails),resumeUrl:tn(t.resumeUrl),draftDigest:re(t.draftDigest)}}function I(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Xo(e){if(!e||typeof e!="object")return null;let t=e,r=t.kind,o=kn(t);if(!o.id||typeof r!="string")return null;switch(r){case"heading":return I({...o,kind:r,text:W(t.text,2e3,"Section")});case"paragraph":return I({...o,kind:r,text:W(t.text,5e3)});case"divider":return I({...o,kind:r});case"short_text":case"email":case"url":return I({...D(t,r),maxLength:Le(t.maxLength)===void 0?void 0:be(t.maxLength,1,2e3,2e3)});case"phone":{let n=N(t.defaultCountry,2)?.toUpperCase();return I({...D(t,r),defaultCountry:n&&/^[A-Z]{2}$/.test(n)?n:void 0})}case"long_text":return I({...D(t,r),maxLength:Le(t.maxLength)===void 0?void 0:be(t.maxLength,1,2e4,2e4)});case"number":return I({...D(t,r),min:Le(t.min),max:Le(t.max)});case"select":case"multi_select":case"dropdown":{let n=Je(t.options);return n.length===0?null:I({...D(t,r),options:n,allowOther:re(t.allowOther),shuffleOptions:re(t.shuffleOptions)})}case"checkbox":{let n=t.appearance==="toggle"?"toggle":void 0;return I({...D(t,r),appearance:n})}case"signature":case"date":return I(D(t,r));case"rating":{let n=be(t.max,1,10,5);return I({...D(t,r),max:n,insightsMetric:t.insightsMetric==="csat"&&n===5?"csat":void 0})}case"linear_scale":{let n=be(t.min,0,9,1),i=be(t.max,n+1,10,10),s=t.insightsMetric==="nps"&&n===0&&i===10?"nps":t.insightsMetric==="csat"&&n===1&&i===5?"csat":void 0;return I({...D(t,r),min:n,max:i,minLabel:N(t.minLabel,100),maxLabel:N(t.maxLabel,100),insightsMetric:s})}case"ranking":{let n=Je(t.options);return n.length<2?null:I({...D(t,r),options:n})}case"matrix":{let n=Je(t.rows),i=Je(t.columns);return n.length===0||i.length===0?null:I({...D(t,r),rows:n,columns:i})}case"hidden":return I({...D(t,r),required:!1,paramName:N(t.paramName,128),defaultValue:N(t.defaultValue,1e3)});case"file_upload":return I({...D(t,r),maxFiles:be(t.maxFiles,1,20,1),maxFileSizeMb:be(t.maxFileSizeMb,1,5e3,500),accept:Array.isArray(t.accept)?t.accept.flatMap(n=>{let i=N(n,100);return i?[i]:[]}).slice(0,50):void 0});case"custom":return I({...D(t,r),component:W(t.component,128),config:t.config&&typeof t.config=="object"&&!Array.isArray(t.config)?t.config:void 0});default:return null}}function ye(e){let t=qo.safeParse(e);if(!t.success){let a=t.error.issues[0],l=a?.path.join(".");return{ok:!1,error:a?`${l?`${l}: `:""}${a.message}`:"Invalid schema"}}if(t.data.version>Ko)return{ok:!1,error:`Unsupported schema version: ${t.data.version}`};let r=t.data.pages.map(a=>{let l=a.blocks.flatMap(u=>{let c=Xo(u);return c?[c]:[]});return I({id:W(a.id,128),title:N(a.title,500),blocks:l})}),o=new Set,n=new Set;for(let a of r){if(!a.id)return{ok:!1,error:"Page ids cannot be blank"};if(o.has(a.id))return{ok:!1,error:`Duplicate page id: ${a.id}`};o.add(a.id);for(let l of a.blocks){if(n.has(l.id))return{ok:!1,error:`Duplicate block id: ${l.id}`};if(n.add(l.id),l.kind==="number"&&l.min!==void 0&&l.max!==void 0&&l.min>l.max)return{ok:!1,error:`Field ${l.id} has min greater than max`};if(l.kind==="select"||l.kind==="multi_select"||l.kind==="dropdown"||l.kind==="ranking"){let u=Ft(l.options);if(u)return{ok:!1,error:`Duplicate option id in field ${l.id}: ${u}`}}else if(l.kind==="matrix"){let u=Ft(l.rows);if(u)return{ok:!1,error:`Duplicate matrix row id in field ${l.id}: ${u}`};let c=Ft(l.columns);if(c)return{ok:!1,error:`Duplicate matrix column id in field ${l.id}: ${c}`}}}}if(r.every(a=>a.blocks.length===0))return{ok:!1,error:"Schema must contain at least one valid block"};let i={version:Ot,title:W(t.data.title,2e3),pages:r,settings:Jo(t.data.settings)},s=N(t.data.description,5e3);return s&&(i.description=s),{ok:!0,schema:i}}function Ze(e,t){let r=N(e,t);if(r&&!(/[;{}<>]/.test(r)||/url\s*\(/i.test(r)))return r}function qt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=t.colorScheme==="light"||t.colorScheme==="dark"||t.colorScheme==="auto"?t.colorScheme:void 0,o=I({colorScheme:r,primary:Ze(t.primary,200),background:Ze(t.background,200),text:Ze(t.text,200),radius:Ze(t.radius,64),fontFamily:Ze(t.fontFamily,200)});return Object.keys(o).length>0?o:null}var Ut="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",Yo=256-256%Ut.length;function rn(e=12){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError("createId size must be a positive safe integer");let t=globalThis.crypto;if(typeof t>"u"||typeof t.getRandomValues!="function")throw new Error("createId requires Web Crypto (globalThis.crypto.getRandomValues)");let r="";for(;r.length<e;){let o=new Uint8Array(e);t.getRandomValues(o);for(let n=0;n<e&&r.length<e;n++){let i=o[n];i<Yo&&(r+=Ut[i%Ut.length])}}return r}var zn=class{h0=1732584193;h1=4023233417;h2=2562383102;h3=271733878;h4=3285377520;block=new Uint8Array(64);blockLen=0;totalLen=0;w=new Int32Array(80);update(e){this.totalLen+=e.length;let t=0;if(this.blockLen>0){for(;t<e.length&&this.blockLen<64;)this.block[this.blockLen++]=e[t++];this.blockLen===64&&(this.process(this.block),this.blockLen=0)}for(;t+64<=e.length;)this.process(e.subarray(t,t+64)),t+=64;for(;t<e.length;)this.block[this.blockLen++]=e[t++];return this}digest(){let e=Math.floor(this.totalLen/536870912),t=this.totalLen*8>>>0,r=[128],o=this.blockLen+1;for(;o%64!==56;)r.push(0),o++;r.push(e>>>24&255,e>>>16&255,e>>>8&255,e&255),r.push(t>>>24&255,t>>>16&255,t>>>8&255,t&255),this.update(new Uint8Array(r));let n=new Uint8Array(20),i=[this.h0,this.h1,this.h2,this.h3,this.h4];for(let s=0;s<5;s++)n[s*4]=i[s]>>>24&255,n[s*4+1]=i[s]>>>16&255,n[s*4+2]=i[s]>>>8&255,n[s*4+3]=i[s]&255;return n}process(e){let t=this.w;for(let a=0;a<16;a++)t[a]=e[a*4]<<24|e[a*4+1]<<16|e[a*4+2]<<8|e[a*4+3];for(let a=16;a<80;a++){let l=t[a-3]^t[a-8]^t[a-14]^t[a-16];t[a]=l<<1|l>>>31}let r=this.h0,o=this.h1,n=this.h2,i=this.h3,s=this.h4;for(let a=0;a<80;a++){let l,u;a<20?(l=o&n|~o&i,u=1518500249):a<40?(l=o^n^i,u=1859775393):a<60?(l=o&n|o&i|n&i,u=2400959708):(l=o^n^i,u=3395469782);let c=(r<<5|r>>>27)+l+s+u+t[a]|0;s=i,i=n,n=o<<30|o>>>2,o=r,r=c}this.h0=this.h0+r|0,this.h1=this.h1+o|0,this.h2=this.h2+n|0,this.h3=this.h3+i|0,this.h4=this.h4+s|0}},Xe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Kt(e){let t="";for(let r=0;r<e.length;r+=3){let o=e[r],n=r+1<e.length?e[r+1]:0,i=r+2<e.length?e[r+2]:0;t+=Xe[o>>2],t+=Xe[(o&3)<<4|n>>4],t+=r+1<e.length?Xe[(n&15)<<2|i>>6]:"=",t+=r+2<e.length?Xe[i&63]:"="}return t}var Qo=e=>Kt(new zn().update(e).digest()),x=class extends Error{constructor(e,t,r,o){super(e),this.status=t,this.retryAfterSec=r,this.code=o,this.name="FilloError"}status;retryAfterSec;code};function q(e){return e instanceof Error&&e.name==="FilloError"}async function nn(e,t){try{let r=await e.json();return{message:typeof r.error=="string"&&r.error?r.error:t,code:typeof r.code=="string"&&r.code?r.code:void 0}}catch{}return{message:t}}function on(e){let t=Number(e.headers.get("retry-after"));return Number.isFinite(t)&&t>0?t:void 0}var Ne=3,Me=3e4,ei=5*6e4,Q=10*6e4;function sn(e,t){return t?.throwIfAborted(),new Promise((r,o)=>{let n=()=>{clearTimeout(i),o(t?.reason)},i=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function It(e,t=!1){let r=q(e)?e.status??0:0;return r===0||r===503||r===504||t&&r===409&&q(e)&&e.retryAfterSec!==void 0}function Ye(e){return e>=500||e===429||e===408}function an(e){return typeof DOMException<"u"&&e instanceof DOMException&&e.name==="TimeoutError"?new x("Request timed out",0):e}function ti(e,t){let r=e.split(".").map(n=>Number(n)||0),o=t.split(".").map(n=>Number(n)||0);for(let n=0;n<Math.max(r.length,o.length);n++){let i=(r[n]??0)-(o[n]??0);if(i!==0)return i}return 0}function ri(e){if(e.schemaVersion!==void 0&&e.schemaVersion!==Ot)throw new x(`This form uses schema version ${e.schemaVersion}; this SDK supports version ${Ot}. Update @usefillo/* to render it.`,426);if(e.minSdkVersion&&ti(Dt,e.minSdkVersion)<0)throw new x(`This form requires @usefillo/* ${e.minSdkVersion} or newer. Current SDK is ${Dt}.`,426)}function Qe(e,t){return r=>t.onProgress?.({uploadedBytes:r,totalBytes:e,fraction:e===0?1:r/e})}async function ni(e){let t=globalThis.crypto?.subtle;if(t){let r=await t.digest("SHA-1",e);return Kt(new Uint8Array(r))}return Qo(e)}var oi="https://fillo.so",ln={"X-Fillo-Client":`@usefillo/core@${Dt}`},st=class{baseUrl;fetch;key;constructor(e={}){this.baseUrl=e.baseUrl?e.baseUrl.replace(/\/$/,""):e.sameOrigin?"":oi,this.key=e.key,this.fetch=e.fetch??((...t)=>globalThis.fetch(...t))}url(e){return`${this.baseUrl}/api/v1${e}`}async json(e,t){let r=t?.body!=null?{"Content-Type":"application/json",...ln,...t?.headers}:t?.headers,o;try{o=await this.fetch(this.url(e),{...t,headers:r,signal:t?.signal??AbortSignal.timeout(Me)})}catch(n){throw an(n)}if(!o.ok){let{message:n,code:i}=await nn(o,`Request failed: ${o.status}`);throw new x(n,o.status,on(o),i)}return await o.json()}async getForm(e){let t=await this.json(`/forms/${encodeURIComponent(e)}`);return ri(t),t}syncForm(e,t,r){if(!this.key)return Promise.reject(new x("createClient needs a `key` (pk_\u2026) to sync code-defined forms",401));let o=ye(t);return o.ok?this.json("/forms/sync",{method:"POST",body:JSON.stringify({key:this.key,id:e,schema:o.schema,theme:qt(r)})}):Promise.reject(new x(`Invalid form schema: ${o.error}`,400))}async submit(e,t,r){let o;try{o=await this.fetch(this.url(`/forms/${encodeURIComponent(e)}/responses`),{method:"POST",headers:{"Content-Type":"application/json",...ln},body:JSON.stringify({data:t,meta:r}),signal:AbortSignal.timeout(Me)})}catch(i){throw an(i)}if(o.status===422)return{ok:!1,errors:(await o.json()).errors};if(!o.ok){let{message:i,code:s}=await nn(o,`Submit failed: ${o.status}`);throw new x(i,o.status,on(o),s)}let n=await o.json();return{ok:!0,responseId:n.id,duplicate:n.duplicate,updated:n.updated}}async fetchOwnResponse(e,t,r){try{return await this.json(`/forms/${encodeURIComponent(e)}/respondent-response`,{method:"POST",body:JSON.stringify({respondent:t,scopeValue:r})})}catch(o){if(q(o)&&(o.status===404||o.status===403))return null;throw o}}async startSession(e,t){try{let r=await this.fetch(this.url(`/forms/${encodeURIComponent(e)}/sessions`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pageCount:t}),signal:AbortSignal.timeout(Me)});return r.ok?(await r.json()).id:null}catch{return null}}reportProgress(e,t){try{this.fetch(this.url(`/sessions/${encodeURIComponent(e)}/progress`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0,signal:AbortSignal.timeout(Me)}).catch(()=>{})}catch{}}createDraft(e,t){return this.json(`/forms/${encodeURIComponent(e)}/drafts`,{method:"POST",body:JSON.stringify(t)})}getDraft(e,t,r){return this.json(`/drafts/${encodeURIComponent(e)}`,{headers:r?{"X-Fillo-Draft-Token":t,"X-Fillo-Draft-Adopt":"1"}:{"X-Fillo-Draft-Token":t}})}async saveDraft(e,t,r,o){await this.json(`/drafts/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"X-Fillo-Draft-Token":t},body:JSON.stringify(r),...o?.keepalive?{keepalive:!0}:{}})}async deleteDraft(e,t){await this.json(`/drafts/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-Fillo-Draft-Token":t}})}getUploadSession(e,t,r=AbortSignal.timeout(Q)){return this.json(`/uploads/${encodeURIComponent(e)}`,{...t?{headers:{"X-Fillo-Upload-Token":t}}:{},signal:r})}async uploadFile(e,t,r){let o=typeof File<"u"&&t instanceof File?t.name:"upload.bin",n=(t.type||"application/octet-stream").trim().toLowerCase(),i;if(r.sessionId){let u=await this.getUploadSession(r.sessionId,r.uploadToken,this.uploadSignal(r,Q));if(u.formId!==e||u.fieldId!==r.fieldId||u.fileName!==o||u.size!==t.size||u.mime.trim().toLowerCase()!==n)throw new x("File does not match this upload session",400);i=u,i.token||=r.uploadToken}else{let u=rn(24),c=rn(32),p=()=>this.json(`/forms/${encodeURIComponent(e)}/uploads`,{method:"POST",body:JSON.stringify({requestId:u,uploadToken:c,fieldId:r.fieldId,fileName:o,size:t.size,mime:n}),signal:this.uploadSignal(r,Q)}),f=Date.now()+Q,h=250;for(;;)try{i=await p();break}catch(m){if(r.signal?.aborted||!It(m,!0))throw m;let y=f-Date.now();if(y<=0)throw m;await sn(Math.min(h,y),r.signal),h=Math.min(h*2,5e3)}}if(r.onSession?.({sessionId:i.id,uploadToken:i.token}),i.status==="complete"&&i.file)return i.file;if(i.status==="aborted")throw new x("This upload session was cancelled",409);let s;if(i.transport?.type==="gdrive")await this.driveUploadLoop(i,i.transport.uploadUrl,t,r);else if(i.transport?.type==="s3-multipart")await this.s3MultipartUploadLoop(i,t,r);else if(i.transport?.type==="s3-put")await this.s3PutUpload(i.transport.uploadUrl,t,r);else if(i.transport?.type==="box")s=await this.boxUpload(i.transport,t,r);else throw new x("This form's storage doesn't support uploads \u2014 connect Drive, S3, or Box.");let a=()=>this.json(`/uploads/${encodeURIComponent(i.id)}/complete`,{method:"POST",headers:i.token?{"X-Fillo-Upload-Token":i.token}:void 0,...s?{body:JSON.stringify(s)}:{},signal:this.uploadSignal(r,Q)}),l;try{l=await a()}catch(u){if(r.signal?.aborted||!It(u))throw u;let c=Date.now()+Q,p=250;for(;;){let f=await this.getUploadSession(i.id,i.token,this.uploadSignal(r,Math.max(1,c-Date.now())));if(f.status==="complete"&&f.file)return f.file;if(f.status==="aborted")throw u;try{l=await a();break}catch(m){if(r.signal?.aborted||!It(m,!0))throw m}let h=c-Date.now();if(h<=0)throw u;await sn(Math.min(p,h),r.signal),p=Math.min(p*2,5e3)}}if(!l.file)throw new x("Upload completed but no file was returned");return l.file}async boxUpload(e,t,r){let o=Qe(t.size,r);o(0);let n={Authorization:`Bearer ${e.token}`};if(e.mode==="simple"){let f=new FormData;f.append("attributes",JSON.stringify({name:e.fileName,parent:{id:e.folderId}})),f.append("file",t,e.fileName);let h=await this.retry(r,async()=>{let y=await this.fetch(e.uploadUrl,{method:"POST",headers:n,body:f,signal:this.uploadSignal(r)});if(!y.ok&&Ye(y.status))throw new x(`Box upload failed: ${y.status}`,y.status);return y});if(!h.ok)throw new x(`Box upload failed: ${h.status}`,h.status);let m=await h.json();return o(t.size),{providerFileId:m.entries?.[0]?.id}}if(e.size!==t.size)throw new x(`File size changed since the upload was requested (${t.size} vs ${e.size}).`,400);let i=await this.retry(r,async()=>{let f=await this.fetch(e.sessionUrl,{method:"POST",headers:{...n,"Content-Type":"application/json"},body:JSON.stringify({folder_id:e.folderId,file_size:e.size,file_name:e.fileName}),signal:this.uploadSignal(r)});if(!f.ok&&Ye(f.status))throw new x(`Box session failed: ${f.status}`,f.status);return f});if(!i.ok)throw new x(`Box session failed: ${i.status}`,i.status);let s=await i.json(),a=new zn,l=[],u=0;for(;u<t.size;){r.signal?.throwIfAborted();let f=Math.min(u+s.part_size,t.size),h=new Uint8Array(await t.slice(u,f).arrayBuffer());a.update(h);let m=await ni(h),y=await this.retry(r,async()=>{let S=await this.fetch(s.session_endpoints.upload_part,{method:"PUT",headers:{...n,"Content-Type":"application/octet-stream",Digest:`sha=${m}`,"Content-Range":`bytes ${u}-${f-1}/${t.size}`},body:h,signal:this.uploadSignal(r)});if(!S.ok&&Ye(S.status))throw new x(`Box part failed: ${S.status}`,S.status);return S});if(!y.ok)throw new x(`Box part failed: ${y.status}`,y.status);l.push((await y.json()).part),u=f,o(u)}let c=await this.retry(r,async()=>{let f=await this.fetch(s.session_endpoints.commit,{method:"POST",headers:{...n,"Content-Type":"application/json",Digest:`sha=${Kt(a.digest())}`},body:JSON.stringify({parts:l}),signal:this.uploadSignal(r)});if(!f.ok&&Ye(f.status))throw new x(`Box commit failed: ${f.status}`,f.status);return f});if(!c.ok)throw new x(`Box commit failed: ${c.status}`,c.status);return{providerFileId:(await c.json()).entries?.[0]?.id}}uploadSignal(e,t=Me){let r=AbortSignal.timeout(t);return e.signal?AbortSignal.any([e.signal,r]):r}async retry(e,t){let r=0;for(;;)try{return await t()}catch(o){if(e.signal?.aborted||(r+=1,r>=Ne))throw o;await new Promise(n=>setTimeout(n,500*2**r))}}async driveUploadLoop(e,t,r,o){let n=e.uploadedBytes,i=Qe(r.size,o);i(n);let s=0;for(;n<r.size;){o.signal?.throwIfAborted();let a=n,l=Math.min(n+e.chunkSize,r.size),u=r.slice(n,l),c=0;for(;;)try{let p=await this.fetch(t,{method:"PUT",headers:{"Content-Range":`bytes ${n}-${l-1}/${r.size}`},body:u,signal:this.uploadSignal(o)});if(p.status===308){let f=p.headers.get("Range")??p.headers.get("range"),h=f?.match(/bytes=0-(\d+)/);h?n=Number(h[1])+1:f==null?n=0:n=(await this.getUploadSession(e.id,e.token,this.uploadSignal(o,Q))).uploadedBytes;break}if(p.ok){n=r.size;break}throw new x(`Drive chunk failed: ${p.status}`,p.status)}catch(p){if(o.signal?.aborted||(c+=1,c>=Ne))throw p;if(await new Promise(h=>setTimeout(h,500*2**c)),n=(await this.getUploadSession(e.id,e.token,this.uploadSignal(o,Q))).uploadedBytes,n>=r.size)break;l=Math.min(n+e.chunkSize,r.size),u=r.slice(n,l)}if(i(n),n<=a){if(++s>=Ne)throw new x("Drive upload stalled \u2014 the storage endpoint stopped accepting progress",0)}else s=0}}async s3MultipartUploadLoop(e,t,r){if(!Number.isSafeInteger(e.chunkSize)||e.chunkSize<=0||!Number.isSafeInteger(e.uploadedBytes)||e.uploadedBytes<0||e.uploadedBytes>t.size||e.uploadedBytes<t.size&&e.uploadedBytes%e.chunkSize!==0)throw new x("S3 upload session returned invalid progress",502);let o=Qe(t.size,r),n=e.uploadedBytes;for(o(n);n<t.size;){r.signal?.throwIfAborted();let i=Math.floor(n/e.chunkSize)+1;if(i>1e4)throw new x("S3 upload needs too many parts",413);let s=Math.min(n+e.chunkSize,t.size),a=t.slice(n,s),l=0;for(;;){let u;try{let c=await this.json(`/uploads/${encodeURIComponent(e.id)}/parts`,{method:"POST",headers:e.token?{"X-Fillo-Upload-Token":e.token}:void 0,body:JSON.stringify({partNumber:i}),signal:this.uploadSignal(r,Q)});if(typeof c.uploadUrl!="string"||!c.uploadUrl)throw new x("S3 part URL was unavailable",502);u=c.uploadUrl;let p=await this.fetch(u,{method:"PUT",body:a,signal:this.uploadSignal(r,ei)});if(!p.ok)throw new x(`S3 part upload failed: ${p.status}`,p.status);n=s,o(n);break}catch(c){if(r.signal?.aborted)throw c;let p=await this.getUploadSession(e.id,e.token,this.uploadSignal(r,Q));if(p.status==="aborted")throw new x("This upload session was cancelled",409);if(!Number.isSafeInteger(p.uploadedBytes)||p.uploadedBytes<n||p.uploadedBytes>t.size||p.uploadedBytes<t.size&&p.uploadedBytes%e.chunkSize!==0)throw new x("S3 upload session returned invalid progress",502);if(p.uploadedBytes>n){n=p.uploadedBytes,o(n);break}if(l+=1,l>=Ne)throw c;await new Promise(f=>setTimeout(f,500*2**l))}}}}async s3PutUpload(e,t,r){let o=Qe(t.size,r);o(0);let n=0;for(;;)try{let i=await this.fetch(e,{method:"PUT",headers:{"Content-Type":t.type||"application/octet-stream"},body:t,signal:this.uploadSignal(r)});if(!i.ok)throw new x(`S3 upload failed: ${i.status}`,i.status);o(t.size);return}catch(i){if(r.signal?.aborted||(n+=1,n>=Ne))throw i;await new Promise(s=>setTimeout(s,500*2**n))}}};function Te(e={}){return new st(e)}function Pt(e){let t=e.trim();if(!/^-?\d*\.?\d+$/.test(t))return null;let r=Number(t);return Number.isFinite(r)?r:null}function un(e,t){let r={};for(let o of tt(e)){let n=o.kind==="hidden"?t[o.paramName??o.id]??o.defaultValue:t[o.id];if(!(n===void 0||n===""))switch(o.kind){case"number":{let i=Pt(n);if(i===null||o.min!==void 0&&i<o.min||o.max!==void 0&&i>o.max)break;r[o.id]=i;break}case"rating":{let i=Pt(n);i!==null&&Number.isInteger(i)&&i>=1&&i<=(o.max??5)&&(r[o.id]=i);break}case"linear_scale":{let i=Pt(n),s=o.min??1,a=o.max??10;i!==null&&Number.isInteger(i)&&i>=s&&i<=a&&(r[o.id]=i);break}case"checkbox":r[o.id]=n==="true"||n==="1"||n==="yes";break;case"select":case"dropdown":{o.options.some(i=>i.id===n)&&(r[o.id]=n);break}case"multi_select":{let i=new Set(o.options.map(a=>a.id)),s=[...new Set(n.split(",").filter(a=>i.has(a)))];s.length>0&&(r[o.id]=s);break}case"file_upload":case"ranking":case"matrix":case"signature":case"custom":break;default:r[o.id]=n}}return r}var ii={id:"empty",blocks:[]},cn=!1,dn=!1;function si(){dn||(dn=!0,console.warn("[fillo] This form has a client but no submission target \u2014 a bare schema can't sync. Wrap it in defineForm({ id, pages }) (or author it with <Fillo.Form id=\u2026>) so it gets a workspace handle, or pass formId for a dashboard-built form: https://fillo.so/docs"))}function ai(){cn||(cn=!0,console.warn("[fillo] This form has no `client`, so responses can't be submitted \u2014 it's render-only. Pass a client (createClient) to collect responses in Fillo, or forward them to your own backend with webhooks: https://fillo.so/docs"))}var Sn=new Map;function Wt(){try{return globalThis.localStorage??null}catch{return null}}function En(e){return`fillo:submission:${e}`}function Gt(){let e=globalThis.crypto;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);return e?.getRandomValues?(e.getRandomValues(t),Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")):`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function An(e,t,r,o){let n=Wt();if(!n)return e.get(r)??null;try{let i=JSON.parse(n.getItem(t)??"null");if(i&&o(i))return i}catch{}return null}function Cn(e,t,r,o){e.set(r,o);let n=Wt();if(n)try{n.setItem(t,JSON.stringify(o))}catch{}}function Jt(e){return An(Sn,En(e),e,t=>typeof t.key=="string")}function Fn(e,t){Cn(Sn,En(e),e,t)}function li(e){let t=Jt(e);if(t?.key)return t.key;let r={key:Gt()};return Fn(e,r),r.key}function ui(e,t){let r=Jt(e);Fn(e,{key:r?.key??Gt(),submittedAt:new Date().toISOString(),responseId:t})}function jt(e,t,r){let o=bn(e.settings,r);return o===null?t:`${t}::${o}`}function pn(e,t,r){return e.settings.responseLimit?.by!=="browser"||!t?!1:!!Jt(jt(e,t,r))?.submittedAt}var Xt=new Map;function Yt(e){return`fillo:draft:${e}`}function et(e){return An(Xt,Yt(e),e,t=>{let r=t;return typeof r.id=="string"&&typeof r.token=="string"})}function Zt(e,t){Cn(Xt,Yt(e),e,t)}function Nt(e){Xt.delete(e);let t=Wt();if(t)try{t.removeItem(Yt(e))}catch{}}function Mt(e){return q(e)&&(e.status===401||e.status===403||e.status===404)}var ci=1500;function In(e){return q(e)&&e.status&&e.status>0&&e.message?e.message:"Couldn't reach the server \u2014 check your connection and try again. If this keeps happening, a browser extension, firewall, or the site's Content-Security-Policy may be blocking the request."}function di(e){if(q(e)){let t=e.status??0;if(t>0&&t<500&&t!==408&&t!==429)return"This form is unavailable."}return In(e)}function Pn(e){let{onChange:t,onSubmitted:r}=e,o=ye(e.form);if(!o.ok)throw new Error(`Invalid form schema: ${o.error}`);let n=o.schema,i=e.formId,s=e.client,a=e.respondent,l={...e.initialData??{}},u={},c=0,p="idle",f=!1,h=!1;queueMicrotask(()=>{if(typeof location<"u"&&location.search){let _=Object.fromEntries(new URLSearchParams(location.search)),v=null;for(let[$,E]of Object.entries(un(n,_)))l[$]===void 0&&(v=v??{...l},v[$]=E);v&&p==="idle"&&(l=v,z())}p==="idle"&&pn(n,i,l)&&(p="submitted",f=!0,z());let b=!1;if(n.settings.saveProgress&&i&&s&&typeof location<"u"&&location.hash.includes("fillo-draft=")){let _=/fillo-draft=([^&]+)/.exec(location.hash),v=_?.[1]?decodeURIComponent(_[1]):"",$=v.indexOf(".");if($>0){b=!0;let E=v.slice(0,$),C=v.slice($+1);s.getDraft(E,C,!0).then(X=>{Zt(i,{id:E,token:X.token??C});try{history.replaceState(null,"",location.pathname+location.search)}catch{}}).catch(X=>{Mt(X)&&(h=!0,z())}).finally(()=>ct())}}b||ct()});let m,y=new Set,S=new Set,ie=Date.now(),ke=Gt(),j=null,G=!1,se=!1,ee=!1,_e="created",ze=!1,Z=null,w=null,T=Promise.resolve(),M=!1,J=!1,me=!1,Se=!1;function F(){let b=n.pages.length,_=Math.min(c,Math.max(b-1,0)),v=n.pages[_]??ii;return{data:l,errors:u,status:p,pageIndex:_,pageCount:b,page:v,blocks:Ge(n,v,l),isFirstPage:_===0,isLastPage:_===b-1,uploading:y.size>0,submitError:m,restoredSubmission:f,resumedDraft:se,editingPrevious:ee,duplicateSubmission:_e==="duplicate",updatedSubmission:_e==="updated",resumeLinkFailed:h}}let B=F();function z(){B=F();for(let b of S)b()}function ae(b,_){try{r?.(b,_)}catch(v){console.error("[fillo] onSubmitted handler threw:",v)}}function Hn(b){let _=n.pages[b];if(!_)return{};let v={};for(let $ of Ge(n,_,l)){if(!he($))continue;let E=xn($,l[$.id]);E&&(v[$.id]=E)}return v}function Ue(){return!!(n.settings.saveProgress&&s&&i&&!J)}function qn(){let b=new Set;for(let _ of n.pages)for(let v of _.blocks)he(v)&&b.add(v.id);return b}function ut(b){if(p!=="idle"||G)return;let _=qn(),v=null;for(let[C,X]of Object.entries(b.data??{}))l[C]===void 0&&_.has(C)&&(v=v??{...l},v[C]=X);let $=typeof b.page=="number"&&Number.isFinite(b.page)?Math.max(0,Math.min(Math.floor(b.page),n.pages.length-1)):0,E=$>0&&c===0;!v&&!E||(v&&(l=v),E&&(c=$),se=!0,z())}function ct(){if(p!=="idle")return;if(!Ue()){sr();return}let b=i,_=s,v=Z??et(b);if(v&&!me){me=!0,Z=v,_.getDraft(v.id,v.token).then(ut).catch($=>{Mt($)&&(Nt(b),Z=null)});return}!v&&!Se&&a?.hash&&(Se=!0,_.createDraft(b,{data:{},page:0,respondent:a}).then($=>{if(!Z){if(Z={id:$.id,token:$.token},Zt(b,Z),$.existing)return _.getDraft($.id,$.token).then(ut);sr()}}).catch($=>{q($)&&$.status!==void 0&&$.status>=400&&$.status<500||(Se=!1)}))}function sr(){if(ze||n.settings.responseLimit?.onRepeat!=="update"||!s||!i||!a?.hash||p!=="idle")return;ze=!0;let b=s,_=bn(n.settings,l)??void 0;b.fetchOwnResponse(i,a,_).then(v=>{!v||p!=="idle"||G||se||(ut({data:v.data,page:0}),se&&(se=!1,ee=!0,z()))}).catch(()=>{})}function dt(b=!1){if(w&&(clearTimeout(w),w=null),!Ue()||p!=="idle"||!M)return;let _=i,v=s;M=!1,T=T.then(async()=>{let $={data:l,page:Math.max(0,Math.min(c,n.pages.length-1))},E=Z??et(_);try{if(E)try{await v.saveDraft(E.id,E.token,$,b?{keepalive:!0}:void 0),Z=E;return}catch(X){if(!Mt(X))throw X;Nt(_),Z=null}let C=await v.createDraft(_,a?.hash?{...$,respondent:a}:$);Z={id:C.id,token:C.token},Zt(_,Z),C.existing&&(M=!0)}catch(C){q(C)&&C.status!==void 0&&C.status>=400&&C.status<500&&C.status!==429?J=!0:M=!0}})}function Kn(){!Ue()||p!=="idle"||(M=!0,w&&clearTimeout(w),w=setTimeout(()=>{w=null,dt()},ci))}function ar(){!Ue()||!G&&!Z||(M=!0,dt())}function lr(){w&&(clearTimeout(w),w=null),M=!1,i&&Nt(i),Z=null}function Wn(b,_){!G&&s&&i&&(G=!0,s.startSession(i,n.pages.length).then(v=>j=v)),l={...l,[b]:_},t?.(l),m=void 0,b in u&&(u=Object.fromEntries(Object.entries(u).filter(([v])=>v!==b))),z(),Kn()}function Gn(b,_){_?y.add(b):y.delete(b),z()}function Jn(){let b=n.pages.length,_=Math.min(c,Math.max(b-1,0));if(!e.skipValidation){let v=Hn(_);if(u=v,Object.keys(v).length>0){z();return}}c=Math.min(_+1,b-1),j&&s&&s.reportProgress(j,{furthestPage:c}),z(),ar()}function Xn(){u={},c=Math.max(Math.min(c,n.pages.length-1)-1,0),z(),ar()}async function Yn(){if(p==="submitting"||p==="submitted")return;let b=$n(n,l);if(!b.ok){u=b.errors;let _=n.pages.findIndex(v=>Ge(n,v,l).some($=>$.id in b.errors));_>=0&&(c=_),z();return}if(s&&e.resolveFormId){p="submitting",m=void 0,z();try{i=await e.resolveFormId()}catch(_){throw p="idle",m=di(_),z(),_}}if(s&&i){let _=n.settings.responseLimit?.by==="browser"?li(jt(n,i,b.data)):void 0,v=_??ke,$=n.settings.saveProgress?Z??et(i):null;p="submitting",m=void 0,z();let E;try{E=await s.submit(i,b.data,{hp:e.getHoneypot?.()??"",elapsedMs:Date.now()-ie,surface:e.surface??"headless",submissionKey:v,draft:$?{id:$.id,token:$.token}:void 0,respondent:a})}catch(C){throw p="idle",m=In(C),z(),C}if(!E.ok){u=E.errors??{};let C=n.pages.findIndex(X=>Ge(n,X,l).some(Qn=>Qn.id in u));C>=0?c=C:m="We couldn't submit \u2014 please review your answers.",p="idle",z();return}_e=E.duplicate?"duplicate":E.updated?"updated":"created",j&&s.reportProgress(j,{completed:!0}),_&&ui(jt(n,i,b.data),E.responseId),lr(),p="submitted",z(),ae(E.responseId,b.data);return}if(e.skipValidation){p="submitted",z(),ae(void 0,b.data);return}s&&!i?si():ai(),p="error",z()}return{getState:()=>B,subscribe(b){return S.add(b),()=>{S.delete(b)}},setValue:Wn,setUploading:Gn,next:Jn,back:Xn,submit:Yn,setContext(b){if("formId"in b&&(i=b.formId),"client"in b&&(s=b.client),"respondent"in b&&(a=b.respondent),b.form&&b.form!==n){let _=ye(b.form);if(!_.ok)throw new Error(`Invalid form schema: ${_.error}`);n=_.schema}p==="idle"&&pn(n,i,l)&&(p="submitted",f=!0),ct(),z()},flushDraft(){dt(!0)},resetDraft(){if(p==="submitting")return;let b=Z??(i?et(i):null);if(lr(),b&&s&&s.deleteDraft(b.id,b.token).catch(()=>{}),l={...e.initialData??{}},typeof location<"u"&&location.search){let _=Object.fromEntries(new URLSearchParams(location.search));for(let[v,$]of Object.entries(un(n,_)))l[v]===void 0&&(l[v]=$)}u={},c=0,m=void 0,se=!1,ee=!1,z()},destroy(){w&&(clearTimeout(w),w=null),S.clear()}}}function pi(e){return he(e)&&(e.kind==="select"||e.kind==="dropdown"||e.kind==="checkbox"||e.kind==="rating"||e.kind==="linear_scale")}function Zn(e){let t=e.filter(r=>he(r)&&r.kind!=="hidden");return t.length!==1?!0:!pi(t[0])}function Nn(e,t,r){if(r.form.settings.submitMode!=="auto"||!r.isLastPage||r.status!=="idle"||r.uploading||!(()=>{switch(e.kind){case"select":case"dropdown":return typeof t=="string"&&e.options.some(s=>s.id===t);case"checkbox":return t===!0;case"rating":case"linear_scale":return typeof t=="number";default:return!1}})()||t===r.data[e.id])return!1;let n={...r.data,[e.id]:t},i=rt(r.form,n).filter(s=>s.kind!=="hidden");return i.length!==1||i[0]?.id!==e.id?!1:$n(r.form,n).ok}function Qt(e){return{id:e.id,theme:e.theme,schema:{version:1,title:e.title??"",description:e.description,pages:e.pages,settings:e.settings??{}},__filloCodeForm:!0}}function er(e){return typeof e=="object"&&e!==null&&"__filloCodeForm"in e}var fe=new Map,fi=e=>new Promise(t=>setTimeout(t,e));function hi(e){if(!q(e))return!0;let t=e.status??0;return t===0||t===408||t===429||t>=500}async function mi(e,t){let r=800;for(let o=0;;o++)try{return await e.syncForm(t.id,t.schema,t.theme??null)}catch(n){if(!hi(n)||o>=2)throw n;let i=q(n)?n.retryAfterSec:void 0;await fi(Math.min(i?i*1e3:r*(1+Math.random()*.5),15e3)),r*=2}}function gi(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)|0;return(t>>>0).toString(36)}function Mn(e,t){let r=o=>{if(Array.isArray(o))return o.map(r);if(o&&typeof o=="object"){let n=o;return Object.fromEntries(Object.keys(n).sort().map(i=>[i,r(n[i])]))}return o};return JSON.stringify(r(e))===JSON.stringify(r(t))}var Bt=e=>e==="published"?36e5:6e4,bi=e=>!!(e.staged||e.resolvedSchema||e.syncError);function Ln(e,t){return`fillo:sync:v2:${e.baseUrl}|${e.key}|${t}`}function yi(e,t,r){try{let o=globalThis.localStorage?.getItem(Ln(e,t));if(!o)return null;let n=JSON.parse(o);if(typeof n.formId!="string"||typeof n.slug!="string"||n.hash!==r||typeof n.ts!="number"||n.status!==void 0&&n.status!=="draft"&&n.status!=="published")return null;let i=Bt(n.status);return Date.now()-n.ts>i?null:n}catch{return null}}function vi(e,t,r,o){if(!(o.staged||o.resolvedSchema||o.syncError))try{globalThis.localStorage?.setItem(Ln(e,t),JSON.stringify({formId:o.formId,slug:o.slug,status:o.status,hash:r,ts:Date.now()}))}catch{}}function tr(e,t,r){let o=JSON.stringify(t.schema)+JSON.stringify(t.theme??null),n=gi(o),i=`${e.baseUrl}:${e.key}:${t.id}:${n}`,s=fe.get(i);if(s&&!r?.bypassCache){if(s.expiresAt===null||s.expiresAt>Date.now())return s.promise;fe.delete(i)}if(!r?.bypassCache){let u=yi(e,t.id,n);if(u){let c=Promise.resolve({formId:u.formId,slug:u.slug,status:u.status});return fe.set(i,{promise:c,expiresAt:u.ts+Bt(u.status)}),c}}let a=mi(e,t),l={promise:a,expiresAt:null};return fe.set(i,l),a.then(u=>{if(fe.get(i)===l){if(bi(u)){fe.delete(i);return}l.expiresAt=Date.now()+Bt(u.status),vi(e,t.id,n,u)}},()=>{fe.get(i)===l&&fe.delete(i)}),a}var _i=class extends Error{constructor(e,t){super(`[fillo] ${t} \u2014 https://fillo.so/docs/troubleshooting#jsx-${e.toLowerCase()}`),this.code=e,this.name="FilloJsxError"}code},wi=Symbol.for("fillo.block");var xi=["label","description","required","placeholder"],P=(e,t,r,o={})=>({name:e,kind:t,props:[...xi,...r],...o}),fn=(e,t,r)=>({name:e,kind:t,props:r?["text"]:[],textChildren:r,content:!0}),Lt=["options","allowOther","shuffleOptions"],$i=[P("Text","short_text",["maxLength"]),P("LongText","long_text",["maxLength"]),P("Email","email",["maxLength"]),P("Url","url",["maxLength"]),P("Phone","phone",["defaultCountry"]),P("Number","number",["min","max"]),P("Select","select",Lt,{optionChildren:!0}),P("MultiSelect","multi_select",Lt,{optionChildren:!0}),P("Dropdown","dropdown",Lt,{optionChildren:!0}),P("Checkbox","checkbox",["appearance"]),P("Rating","rating",["max","insightsMetric"]),P("Scale","linear_scale",["min","max","minLabel","maxLabel","insightsMetric"]),P("Ranking","ranking",["options"],{optionChildren:!0}),P("Matrix","matrix",["rows","columns"]),P("Signature","signature",[]),P("Date","date",[]),P("FileUpload","file_upload",["maxFiles","maxFileSizeMb","accept"]),P("Hidden","hidden",["paramName","defaultValue"]),P("Custom","custom",["component","config"]),fn("Heading","heading",!0),fn("Paragraph","paragraph",!0),{name:"Divider",kind:"divider",props:[],content:!0}],ki={name:"Page",kind:"__page",props:["title"]},zi={name:"Option",kind:"__option",props:["label","icon"]};function Tt(e){let t=()=>{throw new _i("RENDERED_INERT",`<Fillo.${e.name}> was rendered by React. Fillo fields are schema declarations, valid only inside <Fillo.Form> or Fillo.defineForm(). If this form lives in a server component, move it to a client module ("use client")`)};return t[wi]=e,t}var Vu=Object.fromEntries([...$i.map(e=>[e.name,Tt(e)]),["Page",Tt(ki)],["Option",Tt(zi)]]);var Si=/\{\{\s*([\w-]+)\s*\}\}/g;function Rt(e,t,r){if(!e.includes("{{"))return e;let o=tt(r);return e.replace(Si,(n,i)=>{let s=o.find(u=>u.id===i),a=t[i];if(a==null||a==="")return"";let l=u=>s&&"options"in s?s.options.find(c=>c.id===u)?.label??u:u;return Array.isArray(a)?a.map(u=>l(String(u))).join(", "):typeof a=="string"?l(a):String(a)})}function Tn(e,t,r){let o=n=>n===void 0?n:Rt(n,t,r);switch(e.kind){case"heading":case"paragraph":return{...e,text:Rt(e.text,t,r)};case"divider":return e;default:return{...e,label:Rt(e.label,t,r),description:o(e.description)}}}var Ei="fillo-",Ai=0,at='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Ci(e,t){let r=`${Ei}${e}-${t}`;return{inputId:r,labelId:`${r}-label`,descriptionId:`${r}-desc`,errorId:`${r}-error`,name:r}}function d(e,t={}){let r=document.createElement(e);t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text);for(let[o,n]of Object.entries(t.attrs??{}))r.setAttribute(o,n);return r}function $e(e,t){let r=qt(t);r&&(r.colorScheme&&e.setAttribute("data-fillo-color-scheme",r.colorScheme),r.primary&&e.style.setProperty("--fillo-primary",r.primary),r.background&&e.style.setProperty("--fillo-bg",r.background),r.text&&e.style.setProperty("--fillo-text",r.text),r.radius&&e.style.setProperty("--fillo-radius",r.radius),r.fontFamily&&e.style.setProperty("--fillo-font",r.fontFamily),(r.primary||r.background||r.text)&&e.setAttribute("data-fillo-has-color-theme",""))}function Un(e){try{if(!e)return null;let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.toString()}catch{return null}}function Fi(e){let t=new URL(Un(e)??"https://fillo.so");return t.searchParams.set("utm_source","form_badge"),t.toString()}function rr(e){return typeof e=="string"||typeof e=="number"?String(e):""}function A(e,t){for(let r of t)r&&e.appendChild(r);return e}var Rn="http://www.w3.org/2000/svg",Ii={thumbs_up:"M7 10v10M7 10l4.8-6.1a2 2 0 0 1 3.5 1.7L14.6 10h4.8a2.1 2.1 0 0 1 2 2.5l-1.1 5.4A3 3 0 0 1 17.4 20H7M3 10h4v10H3z",thumbs_down:"M7 14V4M7 14l4.8 6.1a2 2 0 0 0 3.5-1.7L14.6 14h4.8a2.1 2.1 0 0 0 2-2.5l-1.1-5.4A3 3 0 0 0 17.4 4H7M3 4h4v10H3z"};function jn(e){if(!e)return null;let t=document.createElementNS(Rn,"svg");t.setAttribute("class","fillo-option-icon"),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true");let r=document.createElementNS(Rn,"path");return r.setAttribute("d",Ii[e]),t.appendChild(r),t}function U(e,t,r,o){r&&e.setAttribute("aria-invalid","true"),t.required&&e.setAttribute("aria-required","true");let n=[t.description?o.descriptionId:null,r?o.errorId:null].filter(Boolean).join(" ");n&&e.setAttribute("aria-describedby",n)}function Bn(e,t,r,o){e.addEventListener("keydown",n=>{let i=n.key==="ArrowRight"||n.key==="ArrowDown",s=n.key==="ArrowLeft"||n.key==="ArrowUp";if(!i&&!s)return;n.preventDefault();let a=r===null?-1:t.indexOf(r),l=a===-1?i?0:t.length-1:(a+(i?1:-1)+t.length)%t.length,u=t[l];u!==void 0&&(o(u),e.querySelectorAll('[role="radio"]')[l]?.focus())})}function K(e,t,r,o){let n=d("div",{className:`fillo-field fillo-field--${e.kind}${t?" fillo-field--error":""}`,attrs:{"data-fillo":"field","data-field":e.id,"data-kind":e.kind}});n.toggleAttribute("data-invalid",!!t),n.toggleAttribute("data-required",!!e.required);let i=d("label",{className:"fillo-label",text:e.label,attrs:{id:o.labelId,for:o.inputId,"data-fillo":"label"}});return e.required||i.appendChild(d("span",{className:"fillo-optional",text:" (optional)"})),n.appendChild(i),e.description&&n.appendChild(d("p",{className:"fillo-description",text:e.description,attrs:{id:o.descriptionId,"data-fillo":"fieldDescription"}})),n.appendChild(r),t&&n.appendChild(d("p",{className:"fillo-error",text:t,attrs:{role:"alert",id:o.errorId,"data-fillo":"error"}})),n}function Re(e,t){let r=d("input",{className:"fillo-input",attrs:{id:t.ids.inputId,type:e,"data-fillo":"control"}});return r.value=rr(t.value),t.field.placeholder&&(r.placeholder=t.field.placeholder),"maxLength"in t.field&&t.field.maxLength!==void 0&&(r.maxLength=t.field.maxLength),t.field.kind==="number"&&(t.field.min!==void 0&&(r.min=String(t.field.min)),t.field.max!==void 0&&(r.max=String(t.field.max))),r.addEventListener("input",()=>t.setValue(r.value,{render:!1})),r.addEventListener("change",()=>t.setValue(r.value)),U(r,t.field,t.error,t.ids),K(t.field,t.error,r,t.ids)}function Pi(){if(typeof navigator>"u")return;let t=(navigator.languages?.[0]||navigator.language||"").split("-")[1];return t&&/^[A-Za-z]{2}$/.test(t)?t.toUpperCase():void 0}function Zi(){if(!(typeof Intl>"u"))try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof e=="string"&&e?e:void 0}catch{return}}function Ni(e,t){if(t<=0)return e.setSelectionRange(0,0);let r=e.value,o=0,n=r.length;for(let i=0;i<r.length;i++)if(/\d/.test(r[i])&&++o===t){n=i+1;break}e.setSelectionRange(n,n)}function Mi(e){let t=e.field,r=it(rr(e.value)).country??nt(t.defaultCountry)??yn(Zi())??nt(Pi())??ne[0],o=d("div",{className:"fillo-phone"}),n=d("div",{className:"fillo-phone-country"}),i=d("button",{className:"fillo-phone-flag",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false"}}),s=d("span",{className:"fillo-phone-flag-emoji",attrs:{"aria-hidden":"true"}}),a=d("span",{className:"fillo-phone-dial"});A(i,[s,a,d("span",{className:"fillo-phone-caret",text:"\u25BE",attrs:{"aria-hidden":"true"}})]),A(n,[i]);let l=d("input",{className:"fillo-input fillo-phone-input",attrs:{id:e.ids.inputId,type:"tel",inputmode:"tel",autocomplete:"tel-national","data-fillo":"control"}});U(l,e.field,e.error,e.ids);let u=()=>{let w=oe(rr(e.value));return w.startsWith(r.dialCode)?w.slice(r.dialCode.length):w},c=()=>{s.textContent=Vt(r.iso2),a.textContent=`+${r.dialCode}`,i.setAttribute("aria-label",`Country: ${r.name} (+${r.dialCode})`)},p=()=>{l.value=ot(r,u()),l.placeholder=ot(r,r.example)},f=w=>e.setValue(w?vn(r,w):"",{render:!1});c(),p(),l.addEventListener("input",()=>{let w=l.value,T=l.selectionStart??w.length,M=oe(w.slice(0,T)).length;if(w.trimStart().startsWith("+")){let J=it(w);J.country&&(r=J.country,c()),f(J.country?J.national:oe(w))}else f(oe(w));l.value=ot(r,u()),Ni(l,M)});let h=e.registerOverlay,m=null,y=0,S=ne,ie=null,ke=null,j=`${e.ids.inputId}-countries`,G=()=>{if(!m)return;let w=_n(n,m);m.classList.toggle("fillo-phone-popover--above",w==="above"),m.classList.toggle("fillo-phone-popover--below",w==="below")},se=()=>{ie?.();let w=()=>G();G(),window.addEventListener("resize",w),window.addEventListener("scroll",w,!0),ie=()=>{window.removeEventListener("resize",w),window.removeEventListener("scroll",w,!0)}},ee=()=>{ie?.(),ie=null,m?.remove(),m=null,i.setAttribute("aria-expanded","false"),document.removeEventListener("mousedown",_e),ke?.(),ke=null},_e=w=>{n.contains(w.target)||ee()},ze=w=>{w&&(r=w,c(),f(u()),p(),ee(),l.focus())},Z=()=>{let w=d("div",{className:"fillo-phone-popover fillo-phone-popover--below"}),T=d("input",{className:"fillo-phone-search",attrs:{type:"text",role:"combobox","aria-expanded":"true","aria-controls":j,"aria-autocomplete":"list",placeholder:"Search country or code"}}),M=d("ul",{className:"fillo-phone-list",attrs:{role:"listbox",id:j,"aria-label":"Country"}}),J=()=>{if(M.replaceChildren(),S.length===0){M.appendChild(d("li",{className:"fillo-phone-empty",text:"No matches"})),G();return}S.forEach((F,B)=>{let z=d("li",{className:`fillo-phone-option${B===y?" fillo-phone-option--active":""}`,attrs:{id:`${j}-opt-${B}`,role:"option","aria-selected":String(F.iso2===r.iso2)}});A(z,[d("span",{className:"fillo-phone-flag-emoji",text:Vt(F.iso2),attrs:{"aria-hidden":"true"}}),d("span",{className:"fillo-phone-option-name",text:F.name}),d("span",{className:"fillo-phone-option-dial",text:`+${F.dialCode}`})]),z.addEventListener("mouseenter",()=>{y=B,T.setAttribute("aria-activedescendant",z.id),me()}),z.addEventListener("mousedown",ae=>{ae.preventDefault(),ze(F)}),M.appendChild(z)}),T.setAttribute("aria-activedescendant",`${j}-opt-${y}`),G()},me=()=>{[...M.children].forEach((F,B)=>F.classList.toggle("fillo-phone-option--active",B===y)),document.getElementById(`${j}-opt-${y}`)?.scrollIntoView({block:"nearest"})},Se=F=>{let B=F.trim().toLowerCase(),z=B.replace(/[^\d]/g,"");S=B?ne.filter(ae=>ae.name.toLowerCase().includes(B)||ae.iso2.toLowerCase()===B||z.length>0&&ae.dialCode.startsWith(z)):ne,y=0,J()};T.addEventListener("input",()=>Se(T.value)),T.addEventListener("keydown",F=>{F.key==="ArrowDown"?(F.preventDefault(),y=Math.min(y+1,S.length-1),me(),T.setAttribute("aria-activedescendant",`${j}-opt-${y}`)):F.key==="ArrowUp"?(F.preventDefault(),y=Math.max(y-1,0),me(),T.setAttribute("aria-activedescendant",`${j}-opt-${y}`)):F.key==="Enter"?(F.preventDefault(),ze(S[y])):F.key==="Escape"&&(F.preventDefault(),ee(),i.focus())}),A(w,[T,M]),m=w,n.appendChild(w),i.setAttribute("aria-expanded","true"),S=ne,y=Math.max(0,ne.indexOf(r)),J(),se(),me(),document.addEventListener("mousedown",_e),ke=h?.(ee)??null,requestAnimationFrame(()=>T.focus())};return i.addEventListener("click",()=>m?ee():Z()),A(o,[n,l]),K(e.field,e.error,o,e.ids)}function Li(e){let t=d("textarea",{className:"fillo-input fillo-textarea",attrs:{id:e.ids.inputId,rows:"4","data-fillo":"control"}});return t.value=typeof e.value=="string"?e.value:"",e.field.placeholder&&(t.placeholder=e.field.placeholder),"maxLength"in e.field&&e.field.maxLength!==void 0&&(t.maxLength=e.field.maxLength),t.addEventListener("input",()=>e.setValue(t.value,{render:!1})),t.addEventListener("change",()=>e.setValue(t.value)),U(t,e.field,e.error,e.ids),K(e.field,e.error,t,e.ids)}function Ti(e){let t=e.field,r=or(t),o=typeof e.value=="string"?e.value:"",n=e.activeOtherFields,i=o!==""&&!t.options.some(l=>l.id===o),s=i||o===""&&n?.has(t.id)===!0,a=d("div",{className:"fillo-options",attrs:{role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"options"}});U(a,t,e.error,e.ids);for(let l of r){let u=d("label",{className:`fillo-option${l.icon?" fillo-option--has-icon":""}${o===l.id?" fillo-option--selected":""}`,attrs:{"data-option":l.id,"data-fillo":"option"}});u.toggleAttribute("data-selected",o===l.id);let c=d("input",{className:"fillo-option-input",attrs:{type:"radio",name:e.ids.name}});c.checked=o===l.id,c.addEventListener("change",()=>{n?.delete(t.id),e.setValue(l.id)}),A(u,[c,jn(l.icon),d("span",{className:"fillo-option-label",text:l.label,attrs:{"data-fillo":"optionLabel"}})]),a.appendChild(u)}if(t.allowOther){let l=d("label",{className:`fillo-option fillo-option--other${s?" fillo-option--selected fillo-option--with-other":""}`,attrs:{"data-fillo":"option"}});l.toggleAttribute("data-selected",s);let u=d("input",{className:"fillo-option-input",attrs:{type:"radio",name:e.ids.name}});if(u.checked=s,u.addEventListener("change",()=>{n?.add(t.id),e.setValue("",{render:!0})}),A(l,[A(d("span",{className:"fillo-option-main"}),[u,d("span",{className:"fillo-option-label",text:"Other",attrs:{"data-fillo":"optionLabel"}})])]),s){let c=d("input",{className:"fillo-input fillo-other-input",attrs:{type:"text"}});c.value=i?o:"",c.placeholder="Your answer",c.addEventListener("input",()=>{n?.add(t.id),e.setValue(c.value,{render:!1})}),c.addEventListener("change",()=>{n?.add(t.id),e.setValue(c.value)}),l.appendChild(c),i||queueMicrotask(()=>c.focus())}a.appendChild(l)}return K(t,e.error,a,e.ids)}function Ri(e){let t=e.field,r=or(t),o=Array.isArray(e.value)?e.value:[],n=new Set(t.options.map(c=>c.id)),i=o.find(c=>!n.has(c)),s=e.activeOtherFields,a=()=>{let c=e.getValue?.()??e.value;return Array.isArray(c)?c:[]},l=d("div",{className:"fillo-options",attrs:{role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"options"}});U(l,t,e.error,e.ids);let u=c=>e.setValue(c);for(let c of r){let p=d("label",{className:`fillo-option${c.icon?" fillo-option--has-icon":""}${o.includes(c.id)?" fillo-option--selected":""}`,attrs:{"data-option":c.id,"data-fillo":"option"}});p.toggleAttribute("data-selected",o.includes(c.id));let f=d("input",{className:"fillo-option-input",attrs:{type:"checkbox"}});f.checked=o.includes(c.id),f.addEventListener("change",()=>{let h=a();u(f.checked?[...h,c.id]:h.filter(m=>m!==c.id))}),A(p,[f,jn(c.icon),d("span",{className:"fillo-option-label",text:c.label,attrs:{"data-fillo":"optionLabel"}})]),l.appendChild(p)}if(t.allowOther){let c=i!==void 0||s?.has(t.id)===!0,p=d("label",{className:`fillo-option fillo-option--other${c?" fillo-option--selected fillo-option--with-other":""}`,attrs:{"data-fillo":"option"}});p.toggleAttribute("data-selected",c);let f=d("input",{className:"fillo-option-input",attrs:{type:"checkbox"}});if(f.checked=c,f.addEventListener("change",()=>{let h=a().filter(m=>n.has(m));f.checked?(s?.add(t.id),u(h)):(s?.delete(t.id),u(h))}),A(p,[A(d("span",{className:"fillo-option-main"}),[f,d("span",{className:"fillo-option-label",text:"Other",attrs:{"data-fillo":"optionLabel"}})])]),c){let h=d("input",{className:"fillo-input fillo-other-input",attrs:{type:"text"}});h.value=i??"",h.placeholder="Your answer",h.addEventListener("input",()=>{s?.add(t.id);let m=a().filter(y=>n.has(y));e.setValue(h.value?[...m,h.value]:m,{render:!1})}),h.addEventListener("change",()=>{s?.add(t.id);let m=a().filter(y=>n.has(y));e.setValue(h.value?[...m,h.value]:m)}),p.appendChild(h),i===void 0&&queueMicrotask(()=>h.focus())}l.appendChild(p)}return K(t,e.error,l,e.ids)}function Oi(e){let t="__fillo_other__",r=new Set(e.options.map(o=>o.id));for(;r.has(t);)t+="_";return t}function Di(e){let t=e.field,r=typeof e.value=="string"?e.value:"",o=Oi(t),n=e.activeOtherFields,i=r!==""&&!t.options.some(c=>c.id===r),s=i||r===""&&n?.has(t.id)===!0,a=d("div"),l=d("div",{className:"fillo-select-wrap"}),u=d("select",{className:"fillo-input fillo-select",attrs:{id:e.ids.inputId,"data-fillo":"control"}});u.appendChild(d("option",{text:t.placeholder??"Choose...",attrs:{value:""}}));for(let c of or(t))u.appendChild(d("option",{text:c.label,attrs:{value:c.id}}));if(t.allowOther&&u.appendChild(d("option",{text:"Other...",attrs:{value:o}})),u.value=s?o:r,u.addEventListener("change",()=>{u.value===o?(n?.add(t.id),e.setValue("",{render:!0})):(n?.delete(t.id),e.setValue(u.value||null))}),U(u,t,e.error,e.ids),A(l,[u,d("span",{className:"fillo-select-icon",attrs:{"aria-hidden":"true"}})]),a.appendChild(l),s){let c=d("input",{className:"fillo-input fillo-other-input fillo-other-input--block",attrs:{type:"text"}});c.value=i?r:"",c.placeholder="Your answer",c.addEventListener("input",()=>{n?.add(t.id),e.setValue(c.value,{render:!1})}),c.addEventListener("change",()=>{n?.add(t.id),e.setValue(c.value)}),a.appendChild(c),i||queueMicrotask(()=>c.focus())}return K(t,e.error,a,e.ids)}function Ui(e){if(e.field.kind==="checkbox"&&e.field.appearance==="toggle"){let i=d("div",{className:`fillo-field fillo-field--checkbox fillo-field--toggle${e.error?" fillo-field--error":""}`,attrs:{"data-fillo":"field","data-field":e.field.id,"data-kind":e.field.kind}});i.toggleAttribute("data-invalid",!!e.error),i.toggleAttribute("data-required",!!e.field.required);let s=d("label",{className:"fillo-toggle",attrs:{"data-fillo":"option"}});s.toggleAttribute("data-checked",e.value===!0);let a=d("span",{className:"fillo-option-label",text:e.field.label,attrs:{"data-fillo":"optionLabel"}});e.field.required||a.appendChild(d("span",{className:"fillo-optional",text:" (optional)"}));let l=d("span",{className:"fillo-toggle-copy"});l.appendChild(a);let u=d("input",{className:"fillo-toggle-input",attrs:{id:e.ids.inputId,type:"checkbox",role:"switch","aria-checked":String(e.value===!0)}});return u.checked=e.value===!0,u.addEventListener("change",()=>{u.setAttribute("aria-checked",String(u.checked)),e.setValue(u.checked)}),U(u,e.field,e.error,e.ids),A(s,[l,u,A(d("span",{className:"fillo-toggle-track",attrs:{"aria-hidden":"true"}}),[d("span",{className:"fillo-toggle-thumb"})])]),i.appendChild(s),e.field.description&&i.appendChild(d("p",{className:"fillo-description",text:e.field.description,attrs:{id:e.ids.descriptionId,"data-fillo":"fieldDescription"}})),e.error&&i.appendChild(d("p",{className:"fillo-error",text:e.error,attrs:{role:"alert",id:e.ids.errorId,"data-fillo":"error"}})),i}let t=d("div",{className:`fillo-field fillo-field--checkbox${e.error?" fillo-field--error":""}`,attrs:{"data-fillo":"field","data-field":e.field.id,"data-kind":e.field.kind}});t.toggleAttribute("data-invalid",!!e.error),t.toggleAttribute("data-required",!!e.field.required);let r=d("label",{className:"fillo-option",attrs:{"data-fillo":"option"}});r.toggleAttribute("data-checked",e.value===!0);let o=d("input",{className:"fillo-option-input",attrs:{id:e.ids.inputId,type:"checkbox"}});o.checked=e.value===!0,o.addEventListener("change",()=>e.setValue(o.checked)),U(o,e.field,e.error,e.ids);let n=d("span",{className:"fillo-option-label",text:e.field.label,attrs:{"data-fillo":"optionLabel"}});return e.field.required||n.appendChild(d("span",{className:"fillo-optional",text:" (optional)"})),A(r,[o,n]),t.appendChild(r),e.field.description&&t.appendChild(d("p",{className:"fillo-description",text:e.field.description,attrs:{id:e.ids.descriptionId,"data-fillo":"fieldDescription"}})),e.error&&t.appendChild(d("p",{className:"fillo-error",text:e.error,attrs:{role:"alert",id:e.ids.errorId,"data-fillo":"error"}})),t}function ji(e){if(e.field.kind!=="rating")return d("div");let t=typeof e.field.max=="number"?e.field.max:5,r=typeof e.value=="number"?e.value:0,o=Array.from({length:t},(a,l)=>l+1),n=r>0?r:null,i=n===null?0:Math.max(0,o.indexOf(n)),s=d("div",{className:"fillo-rating",attrs:{id:e.ids.inputId,role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});U(s,e.field,e.error,e.ids);for(let[a,l]of o.entries()){let u=d("button",{className:`fillo-star${l<=r?" fillo-star--active":""}`,text:"\u2605",attrs:{type:"button",role:"radio","aria-label":`${l} of ${t}`,"aria-checked":String(l===r),tabindex:String(a===i?0:-1),"data-fillo":"option"}});u.toggleAttribute("data-selected",l<=r),u.addEventListener("click",()=>e.setValue(l===r?null:l)),s.appendChild(u)}return Bn(s,o,n,a=>e.setValue(a)),K(e.field,e.error,s,e.ids)}function Bi(e){if(e.field.kind!=="linear_scale")return d("div");let t=typeof e.field.min=="number"?e.field.min:1,r=typeof e.field.max=="number"?e.field.max:10,o=typeof e.value=="number"?e.value:null,n=Array.from({length:r-t+1},(p,f)=>t+f),i=o===null?0:Math.max(0,n.indexOf(o)),s=`${e.ids.inputId}-min`,a=`${e.ids.inputId}-max`,l=d("div"),u=d("div",{className:"fillo-scale",attrs:{id:e.ids.inputId,role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});U(u,e.field,e.error,e.ids);let c=[e.field.minLabel?s:null,e.field.maxLabel?a:null,u.getAttribute("aria-describedby")].filter(Boolean).join(" ");c&&u.setAttribute("aria-describedby",c);for(let[p,f]of n.entries()){let h=d("button",{className:`fillo-scale-step${e.value===f?" fillo-scale-step--active":""}`,text:String(f),attrs:{type:"button",role:"radio","aria-label":String(f),"aria-checked":String(e.value===f),tabindex:String(p===i?0:-1),"data-fillo":"option"}});h.toggleAttribute("data-selected",e.value===f),h.addEventListener("click",()=>e.setValue(e.value===f?null:f)),u.appendChild(h)}return Bn(u,n,o,p=>e.setValue(p)),l.appendChild(u),("minLabel"in e.field||"maxLabel"in e.field)&&A(l,[A(d("div",{className:"fillo-scale-labels"}),[d("span",{text:String(e.field.minLabel??""),attrs:{id:s}}),d("span",{text:String(e.field.maxLabel??""),attrs:{id:a}})])]),K(e.field,e.error,l,e.ids)}function Vi(e){let t=e.field;if(t.kind!=="ranking")return null;let r=Array.isArray(e.value)?e.value:[],o=[...r.filter(s=>t.options.some(a=>a.id===s)),...t.options.map(s=>s.id).filter(s=>!r.includes(s))],n=d("div",{attrs:{id:e.ids.inputId,role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});U(n,e.field,e.error,e.ids);let i=d("ol",{className:"fillo-ranking"});for(let[s,a]of o.entries()){let l=t.options.find(m=>m.id===a);if(!l)continue;let u=d("li",{className:"fillo-ranking-item"}),c=d("span",{className:"fillo-ranking-controls"}),p=m=>{let y=s+m;if(y<0||y>=o.length)return;let S=[...o];[S[s],S[y]]=[S[y],S[s]],e.setValue(S)},f=d("button",{className:"fillo-ranking-move",text:"Up",attrs:{type:"button","data-fillo-rank-opt":a,"data-fillo-rank-dir":"up"}});f.toggleAttribute("disabled",s===0),f.addEventListener("click",()=>p(-1));let h=d("button",{className:"fillo-ranking-move",text:"Down",attrs:{type:"button","data-fillo-rank-opt":a,"data-fillo-rank-dir":"down"}});h.toggleAttribute("disabled",s===o.length-1),h.addEventListener("click",()=>p(1)),A(c,[f,h]),A(u,[d("span",{className:"fillo-ranking-index",text:String(s+1)}),d("span",{className:"fillo-ranking-label",text:l.label}),c]),i.appendChild(u)}return n.appendChild(i),K(e.field,e.error,n,e.ids)}function Hi(e){let t=e.field;if(t.kind!=="matrix")return null;let r=e.value&&typeof e.value=="object"&&!Array.isArray(e.value)?e.value:{},o=d("table",{className:"fillo-matrix"}),n=document.createElement("thead"),i=document.createElement("tr");i.appendChild(document.createElement("th"));for(let l of t.columns)i.appendChild(d("th",{text:l.label,attrs:{scope:"col"}}));n.appendChild(i),o.appendChild(n);let s=document.createElement("tbody");for(let l of t.rows){let u=document.createElement("tr");u.appendChild(d("th",{text:l.label,attrs:{scope:"row"}}));for(let c of t.columns){let p=document.createElement("td"),f=d("input",{className:"fillo-option-input",attrs:{type:"radio",name:`${e.ids.name}-${l.id}`,"aria-label":`${l.label}: ${c.label}`}});f.checked=r[l.id]===c.id,f.addEventListener("change",()=>e.setValue({...r,[l.id]:c.id})),p.appendChild(f),u.appendChild(p)}s.appendChild(u)}o.appendChild(s);let a=d("div",{className:"fillo-matrix-wrap",attrs:{id:e.ids.inputId,role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});return U(a,e.field,e.error,e.ids),a.appendChild(o),K(e.field,e.error,a,e.ids)}function qi(e){let t=d("div",{className:"fillo-signature-field"}),r=d("div",{className:"fillo-signature",attrs:{"data-fillo":"control"}}),o=d("canvas",{className:"fillo-signature-canvas",attrs:{"aria-hidden":"true"}}),n=d("button",{className:"fillo-signature-clear",text:"Clear",attrs:{type:"button"}}),i=d("div",{className:"fillo-signature-hint",text:"Sign here",attrs:{"aria-hidden":"true"}});o.width=720,o.height=220;let s=o.getContext("2d"),a=!1,l=typeof e.value=="string"&&e.value.startsWith("data:image/");if(l&&s){let m=new Image;m.onload=()=>s.drawImage(m,0,0,o.width,o.height),m.src=String(e.value),i.style.display="none"}let u=d("input",{className:"fillo-input fillo-signature-type-input",attrs:{id:e.ids.inputId,type:"text",autocomplete:"name",placeholder:"Type your full name to sign"}});U(u,e.field,e.error,e.ids);let c=m=>{s&&(s.clearRect(0,0,o.width,o.height),m.trim()?(s.fillStyle=getComputedStyle(o).color||"#18181b",s.font=`italic ${Math.min(96,o.height*.45)}px "Segoe Script", "Brush Script MT", cursive`,s.textBaseline="middle",s.fillText(m,24,o.height/2),l=!0,i.style.display="none",e.setValue(o.toDataURL("image/png"),{render:!1})):(l=!1,i.style.display="",e.setValue(null,{render:!1})))};u.addEventListener("input",()=>c(u.value));let p=m=>{let y=o.getBoundingClientRect();return{x:(m.clientX-y.left)/y.width*o.width,y:(m.clientY-y.top)/y.height*o.height}};o.addEventListener("pointerdown",m=>{if(!s)return;a=!0,l=!0,i.style.display="none",u.value&&(u.value=""),o.setPointerCapture(m.pointerId);let y=p(m);s.beginPath(),s.moveTo(y.x,y.y)}),o.addEventListener("pointermove",m=>{if(!a||!s)return;let y=p(m);s.lineWidth=2.4,s.lineCap="round",s.strokeStyle=getComputedStyle(o).color||"#18181b",s.lineTo(y.x,y.y),s.stroke()});let f=()=>{a&&(a=!1,l&&e.setValue(o.toDataURL("image/png"),{render:!1}))};o.addEventListener("pointerup",f),o.addEventListener("pointercancel",f),n.addEventListener("click",()=>{s?.clearRect(0,0,o.width,o.height),l=!1,i.style.display="",u.value="",e.setValue(null,{render:!1})}),A(r,[o,i,n]);let h=d("div",{className:"fillo-signature-type"});return h.appendChild(u),A(t,[r,h]),K(e.field,e.error,t,e.ids)}function Ki(e){let t=e.field;if(t.kind!=="file_upload")return null;let r=d("input",{className:"fillo-input",attrs:{id:e.ids.inputId,type:"file","data-fillo":"control"}});(t.maxFiles??1)>1&&(r.multiple=!0),t.accept?.length&&(r.accept=t.accept.join(","));let o=e.uploadProgress?.get(t.id);r.disabled=o!==void 0,U(r,t,e.error,e.ids),r.addEventListener("change",()=>{let a=Array.from(r.files??[]);e.uploadFiles?.(t,a)});let n=d("div");if(n.appendChild(r),o!==void 0){let a=d("div",{className:"fillo-upload-progress",attrs:{role:"progressbar","aria-label":`Uploading ${t.label}`,"aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":String(Math.round(o*100))}});a.appendChild(d("div",{className:"fillo-upload-progress-fill"})),a.firstElementChild?.style.setProperty("width",`${Math.round(o*100)}%`),n.appendChild(a)}let i=Array.isArray(e.value)?e.value:[];for(let a of i)n.appendChild(d("p",{className:"fillo-description",text:`${a.name} (${Math.round(a.size/1024)} KB)`}));let s=e.uploadNotice;return s&&n.appendChild(d("p",{className:"fillo-upload-notice",text:s,attrs:{role:"status"}})),K(t,e.error,n,e.ids)}var On=new Map;function or(e){if(!e.shuffleOptions)return e.options;let t=`${e.id}|${e.options.map(i=>i.id).join(",")}`,r=On.get(t);if(!r){r=e.options.map(i=>i.id);for(let i=r.length-1;i>0;i--){let s=Math.floor(Math.random()*(i+1));[r[i],r[s]]=[r[s],r[i]]}On.set(t,r)}let o=new Map(e.options.map(i=>[i.id,i])),n=r.flatMap(i=>o.get(i)??[]);return n.length===e.options.length?n:e.options}var Wi={short_text:e=>Re("text",e),email:e=>Re("email",e),url:e=>Re("url",e),phone:Mi,number:e=>Re("number",e),date:e=>Re("date",e),long_text:Li,select:Ti,multi_select:Ri,dropdown:Di,checkbox:Ui,rating:ji,linear_scale:Bi,ranking:Vi,matrix:Hi,signature:qi,file_upload:Ki};function Gi(e){if(e.field.kind==="hidden"||e.field.kind==="custom")return null;let t=Wi[e.field.kind];return t?t(e):null}var De=class{constructor(t,r){this.target=t;this.options=r;this.element.className="fillo-dom-root",t.replaceChildren(this.element),this.resolve()}target;options;element=d("div");instanceId=`d${++Ai}`;schema=null;theme;formId;closed=!1;fetchedPoweredBy=null;fetchedBrandLabel;fetchedBrandHref;phase="loading";engine=null;destroyed=!1;renderQueued=!1;hpValue="";liveSubmissionHandled=!1;activeOtherFields=new Set;uploadProgress=new Map;uploadControllers=new Map;uploadNotices=new Map;focusIntent=null;overlays=new Set;get status(){return this.phase==="ready"?this.engine?.getState().status??"idle":this.phase}get data(){return this.engine?.getState().data??this.options.initialData??{}}get form(){return this.schema}get mutableData(){return this.engine?.getState().data??this.options.initialData??{}}api(){let t=this.schema??{version:1,title:"",pages:[],settings:{}},r=this.engine?.getState(),o=r?.pageCount??t.pages.length;return{form:t,formId:this.formId,client:this.options.client,data:r?.data??this.mutableData,errors:r?.errors??{},status:this.status,pageIndex:r?.pageIndex??0,pageCount:o,page:r?.page??t.pages[0]??{id:"empty",blocks:[]},blocks:r?.blocks??[],isFirstPage:r?.isFirstPage??!0,isLastPage:r?.isLastPage??o<=1,setValue:(n,i,s)=>this.setValueInternal(n,i,s),next:()=>this.next(),back:()=>this.back(),submit:()=>this.submit()}}resolveFormIdFn;notLive=!1;fatalError=null;genericUnavailable=!1;syncErrorNotice=null;stagedNotice=!1;async resolve(){try{let t=er(this.options.form)?this.options.form:null;if(t){let n=this.options.client;if(n?.key&&(this.resolveFormIdFn=async()=>{try{let i=await tr(n,t,{bypassCache:!0});if(i.status==="draft")throw new x("This form is no longer published. Submission was stopped before sending answers.",403,void 0,"form_not_published");let s=ye(i.resolvedSchema??t.schema);if(!s.ok)throw new x(`The canonical form schema was invalid: ${s.error}`,502,void 0,"invalid_sync_schema");if(this.schema&&!Mn(this.schema,s.schema))throw new x("The live form changed after this page loaded. Submission stopped before incompatible answers were sent. Reload to use the published schema.",409,void 0,"form_schema_changed");return i.syncError&&this.reportSyncNotice(new x(i.syncError.message,403,void 0,i.syncError.code)),i.formId}catch(i){let s=Oe(i);throw this.reportSubmitSyncFailure(s),s}}),n?.key||this.setSchema(t.schema,this.options.theme??t.theme,this.options.formId),n&&!n.key&&!this.options.formId){this.reportSyncFailure(new x('Code forms need createClient({ key: "pk_\u2026" }) to resolve the live form. Pass a publishable key or a published formId.',401,void 0,"sync_key_required"));return}if(!n?.key)return;ve()?this.setSchema(t.schema,this.options.theme??t.theme,this.options.formId):(this.theme=this.options.theme??t.theme,this.render());try{let i=await tr(n,t);if(this.destroyed)return;if((i.staged||i.syncError)&&!i.resolvedSchema)throw new x("Sync did not return the live schema needed to render safely. Publish changes before deploy, and update @usefillo/* or your API.",409,void 0,"sync_snapshot_required");let s=ve();if(this.notLive=i.status==="draft"&&!s,this.stagedNotice=!!i.staged,i.branding&&(this.fetchedPoweredBy=i.branding.poweredBy,this.fetchedBrandLabel=i.branding.label,this.fetchedBrandHref=i.branding.href),s&&i.resolvedSchema)this.formId=i.formId,this.engine?.setContext({formId:i.formId}),this.render();else{let a=i.resolvedSchema??t.schema,l=this.options.theme??(i.resolvedSchema?i.resolvedTheme??void 0:t.theme);this.applyCanonicalSchema(a,l,i.formId)}i.warning&&console.warn(`[fillo] ${i.warning}`),i.syncError&&this.reportSyncNotice(new x(i.syncError.message,403,void 0,i.syncError.code)),i.staged?console.info(`[fillo] "${t.id}" changes staged as a draft \u2014 rendering the live version until you publish them in your Fillo dashboard`):i.status==="draft"&&console.info(`[fillo] "${t.id}" is a draft \u2014 it renders here but won't accept responses until published`)}catch(i){if(this.destroyed)return;this.reportSyncFailure(Oe(i))}return}let r=this.options.form&&!er(this.options.form)?this.options.form:null;if(r){this.setSchema(r,this.options.theme,this.options.formId);return}if(!this.options.formId)throw new x("Provide either `form`, or a `formId`.",0);this.options.client??=Te(),this.render();let o=await this.options.client.getForm(this.options.formId);if(this.destroyed)return;this.closed=!!o.closed,this.fetchedPoweredBy=o.branding?.poweredBy??null,this.fetchedBrandLabel=o.branding?.label,this.fetchedBrandHref=o.branding?.href,this.setSchema(o.schema,this.options.theme??o.theme??void 0,o.id)}catch(t){if(this.destroyed)return;this.handleError(Oe(t))}}setSchema(t,r,o){if(this.destroyed)return;let n=ye(t);if(!n.ok)throw new x(`This form could not be rendered: ${n.error}`,422);let i=n.schema;this.schema=i,this.theme=r,this.formId=o,this.engine=Pn({form:i,formId:o,client:this.options.client,initialData:this.options.initialData,onChange:this.options.onChange,onSubmitted:this.options.onSubmitted,getHoneypot:()=>this.element.querySelector('input[name="fillo_hp_field"]')?.value??this.hpValue,surface:"default",resolveFormId:this.resolveFormIdFn,respondent:this.options.respondent});let s=this.engine.getState().status,a=this.engine.getState().resumedDraft,l=this.engine.getState().editingPrevious;this.engine.subscribe(()=>{let u=this.engine?.getState();u&&(u.status!==s||u.resumedDraft!==a||u.editingPrevious!==l)&&(s=u.status,a=u.resumedDraft,l=u.editingPrevious,this.queueRender())}),this.configureDraftFlush(i),this.phase=this.closed?"closed":"ready",this.render()}applyCanonicalSchema(t,r,o){if(!this.engine){this.setSchema(t,r,o);return}let n=ye(t);if(!n.ok)throw new x(`This form could not be rendered: ${n.error}`,422);let i=n.schema;this.schema=i,this.theme=r,this.formId=o,this.engine.setContext({form:i,formId:o}),this.configureDraftFlush(i),this.phase=this.closed?"closed":"ready",this.render()}draftFlushWired=!1;flushDraftBound=()=>this.engine?.flushDraft();visibilityFlushBound=()=>{document.visibilityState==="hidden"&&this.engine?.flushDraft()};configureDraftFlush(t){this.teardownDraftFlush(),t.settings.saveProgress&&typeof window<"u"&&(window.addEventListener("pagehide",this.flushDraftBound),document.addEventListener("visibilitychange",this.visibilityFlushBound),this.draftFlushWired=!0)}teardownDraftFlush(){!this.draftFlushWired||typeof window>"u"||(window.removeEventListener("pagehide",this.flushDraftBound),document.removeEventListener("visibilitychange",this.visibilityFlushBound),this.draftFlushWired=!1)}flushDraft(){this.engine?.flushDraft()}resetDraft(){this.engine?.resetDraft(),this.queueRender()}setValue(t,r){this.setValueInternal(t,r)}setValueInternal(t,r,o={}){this.engine?.setValue(t,r),o.render!==!1&&this.queueRender()}next(){if(!this.engine)return;let t=this.engine.getState().pageIndex;this.engine.next(),this.focusIntent=this.engine.getState().pageIndex!==t?"page":"error",this.render()}back(){this.engine&&(this.engine.back(),this.focusIntent="page",this.render())}async submit(){if(!this.engine||this.phase!=="ready")return;let t=this.engine.submit();this.hasErrors()&&(this.focusIntent="error"),this.render();try{await t}catch(r){this.options.onError?.(Oe(r)),this.focusIntent="error",this.render();return}this.hasErrors()&&(this.focusIntent="error"),this.render()}hasErrors(){return Object.keys(this.engine?.getState().errors??{}).length>0}setTheme(t){this.options.theme=t,this.theme=t,this.render()}setClient(t){this.options.client=t,this.engine?.setContext({client:t}),this.render()}setRespondent(t){this.options.respondent=t,this.engine?.setContext({respondent:t})}async uploadFiles(t,r){if(!this.schema)return;if(this.uploadProgress.has(t.id)){this.uploadNotices.set(t.id,"Wait for the current upload to finish before adding more files."),this.queueRender();return}let o=t.maxFiles??1,n=o>1&&Array.isArray(this.mutableData[t.id])?[...this.mutableData[t.id]]:[],i=Math.max(0,o-n.length),s=r.slice(0,i),a=(t.maxFileSizeMb??500)*1024*1024,l=s.filter(f=>f.size<=a),u=r.length-s.length,c=s.length-l.length;if(u>0||c>0){let f=[];u>0&&f.push(`You can attach up to ${o} file${o===1?"":"s"}. ${u} ${u===1?"file was":"files were"} not added.`),c>0&&f.push(`${c} ${c===1?"file exceeds":"files exceed"} the ${t.maxFileSizeMb??500} MB limit.`),this.uploadNotices.set(t.id,f.join(" "))}else this.uploadNotices.delete(t.id);if(l.length===0){this.queueRender();return}let p=new AbortController;this.uploadControllers.set(t.id,p),this.uploadProgress.set(t.id,0),this.engine?.setUploading(t.id,!0),this.queueRender();try{let f=[];for(let[h,m]of l.entries())this.options.client&&this.formId?f.push(await this.options.client.uploadFile(this.formId,m,{fieldId:t.id,signal:p.signal,onProgress:y=>{this.uploadProgress.set(t.id,(h+y.fraction)/l.length),this.queueRender()}})):f.push({fileId:`local:${m.name}:${m.size}`,name:m.name,size:m.size,mime:m.type||"application/octet-stream"});if(this.destroyed)return;this.setValueInternal(t.id,[...n,...f])}catch(f){if(!this.destroyed&&!p.signal.aborted){let h=Oe(f);this.uploadNotices.set(t.id,h.message||"Upload failed \u2014 try again"),this.options.onError?.(h)}}finally{this.uploadControllers.get(t.id)===p&&this.uploadControllers.delete(t.id),this.uploadProgress.delete(t.id),this.engine?.setUploading(t.id,!1),this.queueRender()}}destroy(){this.destroyed=!0,this.teardownDraftFlush(),this.closeOverlays(),this.uploadControllers.forEach(t=>t.abort()),this.uploadControllers.clear(),this.uploadProgress.clear(),this.engine?.destroy(),this.engine=null,this.target.replaceChildren()}registerOverlay=t=>(this.overlays.add(t),()=>this.overlays.delete(t));closeOverlays(){if(this.overlays.size!==0){for(let t of Array.from(this.overlays))try{t()}catch{}this.overlays.clear()}}captureFocus(){if(typeof document>"u")return null;let t=document.activeElement;if(!t||!this.element.contains(t))return null;let r={};t.id&&(r.id=t.id);let o=t.getAttribute("data-fillo-rank-opt");o&&(r.rankOpt=o,r.rankDir=t.getAttribute("data-fillo-rank-dir")??void 0);let n=t.closest("[data-field]");if(n&&(r.fieldId=n.getAttribute("data-field")??void 0,r.controlIndex=Array.from(n.querySelectorAll(at)).indexOf(t)),t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)try{r.selStart=t.selectionStart,r.selEnd=t.selectionEnd}catch{}return r.id||r.rankOpt||r.fieldId?r:null}restoreFocus(t){if(typeof document>"u")return;let r=null;if(t.rankOpt){let o=Array.from(this.element.querySelectorAll("[data-fillo-rank-opt]")).filter(n=>n.getAttribute("data-fillo-rank-opt")===t.rankOpt);r=o.find(n=>n.getAttribute("data-fillo-rank-dir")===t.rankDir&&!n.disabled)??o.find(n=>!n.disabled)??null}if(!r&&t.id&&(r=document.getElementById(t.id)),!r&&t.fieldId!=null&&t.controlIndex!=null&&t.controlIndex>=0){let o=Array.from(this.element.querySelectorAll("[data-field]")).find(n=>n.getAttribute("data-field")===t.fieldId);o&&(r=Array.from(o.querySelectorAll(at))[t.controlIndex]??null)}if(!(!r||typeof r.focus!="function")&&(r.focus(),(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement)&&t.selStart!=null))try{r.setSelectionRange(t.selStart,t.selEnd??t.selStart)}catch{}}applyFocus(t,r){if(!(typeof document>"u")){if(t==="error"){let o=this.element.querySelector('[aria-invalid="true"]');(o?.matches(at)?o:o?.querySelector(at))?.focus?.();return}if(t==="page"){let n=this.element.querySelector(".fillo-page-title, .fillo-title")??this.element.querySelector(".fillo-blocks");n&&(n.hasAttribute("tabindex")||n.setAttribute("tabindex","-1"),n.focus?.());return}r&&this.restoreFocus(r)}}handleError(t){this.destroyed||(this.fatalError=t,this.phase="error",this.options.onError?.(t),this.render(t))}reportSyncFailure(t){if(this.destroyed)return;console.warn(`[fillo] form sync failed${t.code?` (${t.code})`:""}: ${t.message}`),this.syncErrorNotice=t;let r=ve();if(!r||this.options.renderError){this.genericUnavailable=!r,this.handleError(t);return}this.options.onError?.(t),r&&this.render()}reportSyncNotice(t){this.destroyed||(console.warn(`[fillo] form sync needs attention${t.code?` (${t.code})`:""}: ${t.message}`),this.syncErrorNotice=t,this.options.onError?.(t),ve()&&this.render())}reportSubmitSyncFailure(t){this.destroyed||(console.warn(`[fillo] form sync failed${t.code?` (${t.code})`:""}: ${t.message}`),this.syncErrorNotice=t)}queueRender(){this.renderQueued||this.destroyed||(this.renderQueued=!0,queueMicrotask(()=>{this.renderQueued=!1,this.render()}))}render(t){if(this.destroyed)return;let r=this.focusIntent;this.focusIntent=null;let o=r?null:this.captureFocus();if(this.closeOverlays(),this.element.replaceChildren(),this.phase==="loading"){let i=d("div",{className:`fillo-form fillo-form--loading ${this.options.className??""}`,attrs:{"aria-busy":"true","data-fillo":"root","data-state":"loading"}});$e(i,this.theme),A(i,[d("div",{className:"fillo-skeleton"}),d("div",{className:"fillo-skeleton"}),d("div",{className:"fillo-skeleton fillo-skeleton--short"})]),this.element.appendChild(i);return}let n=t??this.fatalError;if(this.phase==="error"&&n){let i=this.options.renderError?.(n)??d("div",{className:"fillo-form fillo-form--error",text:this.genericUnavailable?"This form is unavailable.":n.message});i.hasAttribute("data-fillo")||i.setAttribute("data-fillo","root"),i.hasAttribute("data-state")||i.setAttribute("data-state","error"),i.hasAttribute("role")||i.setAttribute("role","alert"),$e(i,this.theme),this.element.appendChild(i);return}if(this.phase==="closed"){let i=d("div",{className:`fillo-form fillo-form--closed ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":"closed"}});$e(i,this.theme),i.appendChild(d("p",{className:"fillo-closed",text:"This form is no longer accepting responses."})),this.element.appendChild(i);return}if(this.notLive){let i=d("div",{className:`fillo-form fillo-form--closed ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":"closed"}});$e(i,this.theme),i.appendChild(d("p",{className:"fillo-closed",text:"This form isn't live yet."})),this.element.appendChild(i);return}if(this.schema){if(this.engine?.getState().status==="submitted"){let i=this.api(),s=this.engine.getState(),a=this.options.renderSuccess?.(i)??Xi(this.schema);if(a.setAttribute("data-fillo",a.getAttribute("data-fillo")??"root"),a.setAttribute("data-state",a.getAttribute("data-state")??"submitted"),a.setAttribute("role",a.getAttribute("role")??"status"),a.setAttribute("aria-live",a.getAttribute("aria-live")??"polite"),a.hasAttribute("tabindex")||a.setAttribute("tabindex","-1"),$e(a,this.theme),this.element.appendChild(a),this.brandingVisible()&&this.element.appendChild(Dn(this.fetchedBrandLabel,this.fetchedBrandHref)),!s.restoredSubmission&&!this.liveSubmissionHandled){this.liveSubmissionHandled=!0;let l=Un(this.schema.settings.redirectUrl);l&&typeof window<"u"?window.location.assign(l):a.focus()}return}!this.options.client&&ve()&&this.element.appendChild(Yi()),this.syncErrorNotice&&ve()&&this.element.appendChild(Qi(this.syncErrorNotice)),this.stagedNotice&&ve()&&this.element.appendChild(es()),this.element.appendChild(this.renderForm()),this.brandingVisible()&&this.element.appendChild(Dn(this.fetchedBrandLabel,this.fetchedBrandHref)),this.applyFocus(r,o)}}brandingVisible(){return this.fetchedPoweredBy??!0}renderForm(){let t=this.api(),r=d("form",{className:`fillo-form ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":t.status,"data-page":String(t.pageIndex+1)}});r.toggleAttribute("data-last-page",t.isLastPage),$e(r,this.theme),r.noValidate=!0;let o=()=>{t.isLastPage?this.submit():this.next()};r.addEventListener("submit",p=>{p.preventDefault(),o()});let n=this.engine?.getState();if(n?.resumedDraft||n?.editingPrevious){let p=d("div",{className:"fillo-resume",attrs:{role:"status","data-fillo":"resume"}});p.appendChild(d("span",{className:"fillo-resume-text",text:n.editingPrevious?"You're updating your earlier response.":"Picked up where you left off."}));let f=d("button",{className:"fillo-resume-clear",text:"Start over",attrs:{type:"button"}});f.addEventListener("click",()=>this.resetDraft()),p.appendChild(f),r.appendChild(p)}if(t.pageCount>1&&this.schema?.settings.showProgress!==!1){let p=d("div",{className:"fillo-progress-track",attrs:{role:"progressbar","data-fillo":"progress","aria-label":t.form.title||"Form progress","aria-valuemin":"1","aria-valuemax":String(t.pageCount),"aria-valuenow":String(t.pageIndex+1)}});p.appendChild(d("div",{className:"fillo-progress-fill",attrs:{"data-fillo":"progressFill"}})),p.firstElementChild?.style.setProperty("--fillo-progress-value",`${(t.pageIndex+1)/t.pageCount*100}%`),r.appendChild(p)}if(t.pageIndex===0){let p=d("header",{className:"fillo-header",attrs:{"data-fillo":"header"}});t.form.title&&p.appendChild(d("h1",{className:"fillo-title",text:t.form.title,attrs:{"data-fillo":"title"}})),t.form.description&&p.appendChild(d("p",{className:"fillo-form-description",text:t.form.description,attrs:{"data-fillo":"description"}})),r.appendChild(p)}else t.page.title&&r.appendChild(d("h2",{className:"fillo-page-title",text:t.page.title,attrs:{"data-fillo":"pageTitle"}}));let i=d("div",{className:"fillo-blocks",attrs:{"data-fillo":"blocks"}});for(let p of t.blocks){let f=this.renderBlock(Tn(p,this.mutableData,t.form),t);f&&i.appendChild(f)}r.appendChild(i);let s=d("input",{className:"fillo-hp",attrs:{type:"text",name:"fillo_hp_field",tabindex:"-1",autocomplete:"off","aria-hidden":"true"}});s.style.position="absolute",s.style.left="-9999px",s.style.top="auto",s.style.width="1px",s.style.height="1px",s.style.opacity="0",s.style.overflow="hidden",s.style.pointerEvents="none",s.addEventListener("input",()=>{this.hpValue=s.value}),r.appendChild(s);let a=t.status==="error"?"This form can't submit right now. Please try again in a moment.":this.engine?.getState().submitError;a&&r.appendChild(d("p",{className:"fillo-submit-error",attrs:{role:"alert"},text:a}));let u=!(t.form.settings.submitMode==="auto")||!t.isLastPage||Zn(rt(t.form,t.data));if(u||t.pageCount>1&&!t.isFirstPage){let p=d("footer",{className:"fillo-footer",attrs:{"data-fillo":"footer"}});if(t.pageCount>1&&!t.isFirstPage){let f=d("button",{className:"fillo-button fillo-button--ghost",text:"Back",attrs:{type:"button","data-fillo":"button"}});f.addEventListener("click",()=>this.back()),p.appendChild(f)}if(u){let f=d("button",{className:"fillo-button fillo-button--primary",text:t.status==="submitting"?"Submitting...":t.isLastPage?t.form.settings.submitLabel??"Submit":"Next",attrs:{type:"submit","data-fillo":"button"}});f.toggleAttribute("disabled",t.status==="submitting"||this.uploadProgress.size>0),f.addEventListener("click",h=>{h.preventDefault(),o()}),p.appendChild(f)}r.appendChild(p)}return r}renderBlock(t,r){if(!he(t))return Ji(t);let o=(s,a)=>{if(this.setValueInternal(t.id,s,a),a?.render===!1)return;let l={form:r.form,data:r.data,status:r.status,isLastPage:r.isLastPage,uploading:this.uploadProgress.size>0};Nn(t,s,l)&&this.submit()},n={field:t,value:r.data[t.id],error:r.errors[t.id],ids:Ci(this.instanceId,t.id),api:r,setValue:o,uploadFiles:(s,a)=>this.uploadFiles(s,a),uploadProgress:this.uploadProgress,activeOtherFields:this.activeOtherFields,getValue:()=>this.engine?.getState().data[t.id],registerOverlay:this.registerOverlay,uploadNotice:this.uploadNotices.get(t.id)};return(t.kind==="custom"?this.options.customComponents?.[t.component]??this.options.components?.custom:this.options.components?.[t.kind]??Gi)?.(n)??null}};function Ji(e){switch(e.kind){case"heading":return d("h3",{className:"fillo-heading",text:e.text});case"paragraph":return d("p",{className:"fillo-paragraph",text:e.text});case"divider":return d("hr",{className:"fillo-divider"})}return d("div")}function Xi(e){let t=d("div",{className:"fillo-form fillo-form--success"}),r=d("div",{className:"fillo-success"});return A(r,[d("div",{className:"fillo-success-mark",text:"\u2713",attrs:{"aria-hidden":"true"}}),d("h2",{className:"fillo-success-title",text:e.settings.successTitle??"Thanks!"}),d("p",{className:"fillo-success-message",text:e.settings.successMessage??"Your response has been recorded."})]),t.appendChild(r),t}function Dn(e,t){return d("a",{className:"fillo-powered",text:e??"Powered by Fillo",attrs:{href:Fi(t),target:"_blank",rel:"noopener noreferrer"}})}function ve(){return typeof process<"u"&&process.env?.NODE_ENV!=="production"}function Yi(){return d("div",{className:"fillo-devwarning",text:"No Fillo client connected \u2014 this form is render-only and won't save responses. Pass a client to collect them in Fillo, or forward with webhooks. (Shown only in development.)",attrs:{role:"alert"}})}function Qi(e){return d("div",{className:"fillo-devwarning",text:`Form sync needs attention${e.code?` (${e.code})`:""}: ${e.message} The safe form remains available for development.`,attrs:{role:"alert"}})}function es(){return d("div",{className:"fillo-devwarning",text:"Code changes are staged. Local preview only. Publish in Fillo before deploying for respondents.",attrs:{role:"alert"}})}function Oe(e){return q(e)?e:new x(e instanceof Error?e.message:String(e),0)}function lt(e,t){let r=typeof e=="string"?document.querySelector(e):e;if(!r)throw new x(`Fillo mount target not found: ${String(e)}`,0);return new De(r,{...t,initialData:t.initialData??{}})}function Vn(e){let t=d("div");return lt(t,e),t}var ts=typeof HTMLElement<"u"?HTMLElement:class{},nr=class extends ts{instance=null;assignedForm;assignedClient;assignedTheme;assignedInitialData;mounted=!1;mountScheduled=!1;static get observedAttributes(){return["publishable-key","form-id"]}connectedCallback(){this.scheduleMount()}disconnectedCallback(){this.instance?.destroy(),this.instance=null,this.mounted=!1}attributeChangedCallback(){this.mounted&&this.isConnected&&this.scheduleMount()}set form(t){this.assignedForm=t,this.mounted&&this.scheduleMount()}get form(){return this.assignedForm}set client(t){this.assignedClient=t,this.mounted&&this.instance instanceof De&&this.instance.setClient(t)}set theme(t){this.assignedTheme=t,this.mounted&&this.instance instanceof De&&this.instance.setTheme(t)}set initialData(t){this.assignedInitialData=t,this.mounted&&this.scheduleMount()}scheduleMount(){this.mountScheduled||(this.mountScheduled=!0,queueMicrotask(()=>{this.mountScheduled=!1,this.isConnected&&this.mount()}))}mount(){this.instance?.destroy();let t=this.getAttribute("publishable-key")??void 0,r=this.getAttribute("form-id")??void 0,o=this.assignedClient??(r||t?Te({key:t}):void 0);this.instance=lt(this,{form:this.assignedForm,client:o,formId:r,theme:this.assignedTheme,initialData:this.assignedInitialData,onChange:n=>this.dispatchEvent(new CustomEvent("fillo-change",{detail:{data:n}})),onSubmitted:(n,i)=>this.dispatchEvent(new CustomEvent("fillo-submit",{detail:{responseId:n,data:i}})),onError:n=>this.dispatchEvent(new CustomEvent("fillo-error",{detail:{error:n}}))}),this.mounted=!0}};function ir(e="fillo-form"){typeof customElements>"u"||customElements.get(e)||customElements.define(e,nr)}typeof customElements<"u"&&ir();return io(rs);})();
|
|
1
|
+
"use strict";var Fillo=(()=>{var mt=Object.defineProperty;var lo=Object.getOwnPropertyDescriptor;var co=Object.getOwnPropertyNames;var uo=Object.prototype.hasOwnProperty;var po=(e,t)=>{for(var r in t)mt(e,r,{get:t[r],enumerable:!0})},fo=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of co(t))!uo.call(e,n)&&n!==r&&mt(e,n,{get:()=>t[n],enumerable:!(o=lo(t,n))||o.enumerable});return e};var ho=e=>fo(mt({},"__esModule",{value:!0}),e);var gs={};po(gs,{FilloClient:()=>lt,FilloError:()=>k,createClient:()=>De,createFormElement:()=>eo,defineForm:()=>or,registerFilloElement:()=>ur,renderForm:()=>ut});var gr;function $(e,t,r){function o(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let c=s.prototype,u=Object.keys(c);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=c[f].bind(a))}}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function s(a){var l;let c=r?.Parent?new i:this;o(c,a),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var ne=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(gr=globalThis).__zod_globalConfig??(gr.__zod_globalConfig={});var gt=globalThis.__zod_globalConfig;function ue(e){return e&&Object.assign(gt,e),gt}function yr(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function vr(e,t){return typeof t=="bigint"?t.toString():t}function _r(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function yt(e){return e==null}function wr(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}var br=Symbol("evaluating");function de(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==br)return o===void 0&&(o=br,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}var vt="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _t(e){if(qe(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(qe(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function wt(e){return _t(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var xr=new Set(["string","number","symbol"]);function Ce(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xt(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function T(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function kr(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var mo={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Fe(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function $r(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function pe(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function He(e){return typeof e=="string"?e:e?.message}function fe(e,t,r){let o=e.message?e.message:He(e.inst?._zod.def?.error?.(e))??He(t?.error?.(e))??He(r.customError?.(e))??He(r.localeError?.(e))??"Invalid input",{inst:n,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=o,t?.reportInput&&(a.input=s),a}function kt(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}var zr=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,vr,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Sr=$("$ZodError",zr),Ie=$("$ZodError",zr,{Parent:Error});var bo=e=>(t,r,o,n)=>{let i=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new ne;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map(l=>fe(l,i,ue())));throw vt(a,n?.callee),a}return s.value},Ke=bo(Ie),yo=e=>async(t,r,o,n)=>{let i=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(n?.Err??e)(s.issues.map(l=>fe(l,i,ue())));throw vt(a,n?.callee),a}return s.value},We=yo(Ie),vo=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new ne;return i.issues.length?{success:!1,error:new(e??Sr)(i.issues.map(s=>fe(s,n,ue())))}:{success:!0,data:i.value}},Pe=vo(Ie),_o=e=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>fe(s,n,ue())))}:{success:!0,data:i.value}},Ze=_o(Ie);var Er=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var wo="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",xo=new RegExp(`^${wo}$`);var Ar=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var $t=/^-?\d+(?:\.\d+)?$/;var be=$("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),ko={number:"number",bigint:"bigint",object:"date"};var Fr=$("$ZodCheckGreaterThan",(e,t)=>{be.init(e,t);let r=ko[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}});var Ir=$("$ZodCheckMaxLength",(e,t)=>{var r;be.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!yt(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;if(n.length<=t.maximum)return;let s=kt(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Pr=$("$ZodCheckMinLength",(e,t)=>{var r;be.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!yt(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;if(n.length>=t.minimum)return;let s=kt(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}});var Zr=$("$ZodCheckStringFormat",(e,t)=>{var r,o;be.init(e,t),e._zod.onattach.push(n=>{let i=n._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})});var Mr={major:4,minor:4,patch:3};var K=$("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Mr;let o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(let n of o)for(let i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(s,a,l)=>{let c=Fe(s),u;for(let d of a){if(d._zod.def.when){if($r(s)||!d._zod.def.when(s))continue}else if(c)continue;let f=s.issues.length,h=d._zod.check(s);if(h instanceof Promise&&l?.async===!1)throw new ne;if(u||h instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await h,s.issues.length!==f&&(c||(c=Fe(s,f)))});else{if(s.issues.length===f)continue;c||(c=Fe(s,f))}}return u?u.then(()=>s):s},i=(s,a,l)=>{if(Fe(s))return s.aborted=!0,s;let c=n(a,o,l);if(c instanceof Promise){if(l.async===!1)throw new ne;return c.then(u=>e._zod.parse(u,l))}return e._zod.parse(c,l)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let c=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(u=>i(u,s,a)):i(c,s,a)}let l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new ne;return l.then(c=>n(c,o,a))}return n(l,o,a)}}de(e,"~standard",()=>({validate:n=>{try{let i=Pe(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Ze(e,n).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),zt=$("$ZodString",(e,t)=>{K.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ar(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),St=$("$ZodStringFormat",(e,t)=>{Zr.init(e,t),zt.init(e,t)});var Or=$("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Er),St.init(e,t)});var Dr=$("$ZodNumber",(e,t)=>{K.init(e,t),e._zod.pattern=e._zod.bag.pattern??$t,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}});var Ur=$("$ZodUnknown",(e,t)=>{K.init(e,t),e._zod.parse=r=>r});function Lr(e,t,r){e.issues.length&&t.issues.push(...pe(r,e.issues)),t.value[r]=e.value}var jr=$("$ZodArray",(e,t)=>{K.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let s=0;s<n.length;s++){let a=n[s],l=t.element._zod.run({value:a,issues:[]},o);l instanceof Promise?i.push(l.then(c=>Lr(c,r,s))):Lr(l,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function Ge(e,t,r,o,n,i){let s=r in o;if(e.issues.length){if(n&&i&&!s)return;t.issues.push(...pe(r,e.issues))}if(!s&&!n){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?s&&(t.value[r]=void 0):t.value[r]=e.value}function zo(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);let r=kr(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function So(e,t,r,o,n,i){let s=[],a=n.keySet,l=n.catchall._zod,c=l.def.type,u=l.optin==="optional",d=l.optout==="optional";for(let f in t){if(f==="__proto__"||a.has(f))continue;if(c==="never"){s.push(f);continue}let h=l.run({value:t[f],issues:[]},o);h instanceof Promise?e.push(h.then(m=>Ge(m,r,f,t,u,d))):Ge(h,r,f,t,u,d)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}var Br=$("$ZodObject",(e,t)=>{if(K.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let o=_r(()=>zo(t));de(e._zod,"propValues",()=>{let a=t.shape,l={};for(let c in a){let u=a[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(let d of u.values)l[c].add(d)}}return l});let n=qe,i=t.catchall,s;e._zod.parse=(a,l)=>{s??(s=o.value);let c=a.value;if(!n(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),a;a.value={};let u=[],d=s.shape;for(let f of s.keys){let h=d[f],m=h._zod.optin==="optional",v=h._zod.optout==="optional",E=h._zod.run({value:c[f],issues:[]},l);E instanceof Promise?u.push(E.then(ae=>Ge(ae,a,f,c,m,v))):Ge(E,a,f,c,m,v)}return i?So(u,c,a,l,o.value,e):u.length?Promise.all(u).then(()=>a):a}});var Vr=$("$ZodRecord",(e,t)=>{K.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!_t(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let i=[],s=t.keyType._zod.values;if(s){r.value={};let a=new Set;for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);let u=t.keyType._zod.run({value:c,issues:[]},o);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(h=>fe(h,o,ue())),input:c,path:[c],inst:e});continue}let d=u.value,f=t.valueType._zod.run({value:n[c],issues:[]},o);f instanceof Promise?i.push(f.then(h=>{h.issues.length&&r.issues.push(...pe(c,h.issues)),r.value[d]=h.value})):(f.issues.length&&r.issues.push(...pe(c,f.issues)),r.value[d]=f.value)}let l;for(let c in n)a.has(c)||(l=l??[],l.push(c));l&&l.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:l})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(n,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},o);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&$t.test(a)&&l.issues.length){let d=t.keyType._zod.run({value:Number(a),issues:[]},o);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(l=d)}if(l.issues.length){t.mode==="loose"?r.value[a]=n[a]:r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(d=>fe(d,o,ue())),input:a,path:[a],inst:e});continue}let u=t.valueType._zod.run({value:n[a],issues:[]},o);u instanceof Promise?i.push(u.then(d=>{d.issues.length&&r.issues.push(...pe(a,d.issues)),r.value[l.value]=d.value})):(u.issues.length&&r.issues.push(...pe(a,u.issues)),r.value[l.value]=u.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Hr=$("$ZodEnum",(e,t)=>{K.init(e,t);let r=yr(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter(n=>xr.has(typeof n)).map(n=>typeof n=="string"?Ce(n):n.toString()).join("|")})$`),e._zod.parse=(n,i)=>{let s=n.value;return o.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),qr=$("$ZodLiteral",(e,t)=>{if(K.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(o=>typeof o=="string"?Ce(o):o?Ce(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),o}});function Tr(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Kr=$("$ZodOptional",(e,t)=>{K.init(e,t),e._zod.optin="optional",e._zod.optout="optional",de(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),de(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${wr(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,i=t.innerType._zod.run(r,o);return i instanceof Promise?i.then(s=>Tr(s,n)):Tr(i,n)}return r.value===void 0?r:t.innerType._zod.run(r,o)}});var Wr=$("$ZodDefault",(e,t)=>{K.init(e,t),e._zod.optin="optional",de(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(i=>Rr(i,t)):Rr(n,t)}});function Rr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function Gr(e,t){return new e({type:"string",...T(t)})}function Jr(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...T(t)})}function Xr(e,t){return new e({type:"number",checks:[],...T(t)})}function Yr(e){return new e({type:"unknown"})}function Et(e,t){return new Fr({check:"greater_than",...T(t),value:e,inclusive:!0})}function At(e){return Et(0,e)}function O(e,t){return new Ir({check:"max_length",...T(t),maximum:e})}function $e(e,t){return new Pr({check:"min_length",...T(t),minimum:e})}var Y=$("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");K.init(e,t),e.def=t,e.type=t.type,e.parse=(r,o)=>Ke(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Pe(e,r,o),e.parseAsync=async(r,o)=>We(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>Ze(e,r,o),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]},{parent:!0}),e.with=e.check,e.clone=(r,o)=>xt(e,r,o),e.brand=()=>e,e.register=((r,o)=>(r.add(e,o),e)),e.apply=r=>r(e)}),en=$("ZodMiniString",(e,t)=>{zt.init(e,t),Y.init(e,t)});function D(e){return Gr(en,e)}var Ao=$("ZodMiniStringFormat",(e,t)=>{St.init(e,t),en.init(e,t)}),Co=$("ZodMiniEmail",(e,t)=>{Or.init(e,t),Ao.init(e,t)});function Je(e){return Jr(Co,e)}var Fo=$("ZodMiniNumber",(e,t)=>{Dr.init(e,t),Y.init(e,t)});function tn(e){return Xr(Fo,e)}var Io=$("ZodMiniUnknown",(e,t)=>{Ur.init(e,t),Y.init(e,t)});function Ne(){return Yr(Io)}var Po=$("ZodMiniArray",(e,t)=>{jr.init(e,t),Y.init(e,t)});function he(e,t){return new Po({type:"array",element:e,...T(t)})}var rn=$("ZodMiniObject",(e,t)=>{Br.init(e,t),Y.init(e,t),de(e,"shape",()=>t.shape)});function Me(e,t){let r={type:"object",shape:e??{},...T(t)};return new rn(r)}function Ct(e,t){return new rn({type:"object",shape:e,catchall:Ne(),...T(t)})}var Qr=$("ZodMiniRecord",(e,t)=>{Vr.init(e,t),Y.init(e,t)});function nn(e,t,r){return!t||!t._zod?new Qr({type:"record",keyType:D(),valueType:e,...T(t)}):new Qr({type:"record",keyType:e,valueType:t,...T(r)})}var Zo=$("ZodMiniEnum",(e,t)=>{Hr.init(e,t),Y.init(e,t),e.options=Object.values(t.entries)});function on(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new Zo({type:"enum",entries:r,...T(t)})}var No=$("ZodMiniLiteral",(e,t)=>{qr.init(e,t),Y.init(e,t)});function sn(e,t){return new No({type:"literal",values:Array.isArray(e)?e:[e],...T(t)})}var Mo=$("ZodMiniOptional",(e,t)=>{Kr.init(e,t),Y.init(e,t)});function H(e){return new Mo({type:"optional",innerType:e})}var Lo=$("ZodMiniDefault",(e,t)=>{Wr.init(e,t),Y.init(e,t)});function Ft(e,t){return new Lo({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():wt(t)}})}var Oo=["heading","paragraph","divider"];function ee(e){return!Oo.includes(e.kind)}function It(e){return e==null?!1:typeof e=="string"?e.trim()!=="":Array.isArray(e)?e.length>0:typeof e=="boolean"?e:typeof e=="object"?Object.keys(e).length>0:!0}function an(e,t){return e===t?!0:typeof e=="number"&&typeof t=="string"&&t.trim()!==""?Number(t)===e:typeof t=="number"&&typeof e=="string"&&e.trim()!==""?Number(e)===t:!1}function ln(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;let t=Number(e);return Number.isFinite(t)?t:null}function Do(e,t){let r=t(e.fieldId);switch(e.op){case"answered":return It(r);case"not_answered":return!It(r);case"eq":return Array.isArray(r)?r.some(o=>o===e.value):an(r,e.value);case"neq":return It(r)?Array.isArray(r)?!r.some(o=>o===e.value):!an(r,e.value):!1;case"contains":return typeof r=="string"?r.toLowerCase().includes(String(e.value??"").toLowerCase()):Array.isArray(r)?r.some(o=>o===e.value):!1;case"gt":case"lt":{let o=ln(r),n=ln(e.value);return o!==null&&n!==null&&(e.op==="gt"?o>n:o<n)}}}function wn(e,t){return e.length===0?!0:e.every(r=>Do(r,t))}function xn(e,t){return!e.visibleIf||e.visibleIf.length===0?!0:wn(e.visibleIf,t)}function Wt(e,t,r){return o=>t.has(o)&&!r.has(o)?void 0:e[o]}function ot(e,t){let r=new Set(e.map(n=>n.id)),o=r;for(let n=0;n<=e.length;n++){let i=Wt(t,r,o),s=new Set;for(let a of e)xn(a,i)&&s.add(a.id);if(s.size===o.size&&[...s].every(a=>o.has(a)))return s;o=s}return o}function Xe(e,t,r){let o=_e(e),n=new Set(o.map(a=>a.id)),i=ot(o,r),s=Wt(r,n,i);return t.blocks.filter(a=>ee(a)?i.has(a.id):xn(a,s))}function _e(e){return e.pages.flatMap(t=>t.blocks.filter(ee))}function kn(e,t){let r=e.responseLimit?.scopeField;if(!r)return null;let o=t[r];return typeof o=="number"?Number.isFinite(o)?String(o):null:typeof o!="string"?null:o.trim()||null}function $n(e,t){let r=_e(e),o=ot(r,t);return r.filter(n=>o.has(n.id))}function Uo(e,t){let r=_e(e),o=new Set(r.map(n=>n.id));return Wt(t,o,ot(r,t))}function zn(e,t,r){let n=e.pages.find(s=>s.id===t)?.next;if(!n||n.length===0)return{linear:!0};let i=Uo(e,r);for(let s of n)if(wn(s.when,i))return s.to==="end"?{end:!0}:{to:s.to};return{linear:!0}}function nt(e,t){let r=[];if(e.pages.length===0)return r;let o=new Set,n=0;for(let i=0;i<=e.pages.length;i++){let s=e.pages[n];if(!s||o.has(s.id))break;o.add(s.id),r.push(s.id);let a=zn(e,s.id,t);if("end"in a)break;if("to"in a){let l=e.pages.findIndex(c=>c.id===a.to);if(l<0)break;n=l}else if(n+=1,n>=e.pages.length)break}return r}function jo(e,t){return new Set(nt(e,t))}function jt(e,t,r){if("end"in zn(e,t,r))return!0;let o=nt(e,r);return o.length>0&&o[o.length-1]===t}function Bo(e,t){let r=jo(e,t),o=ot(_e(e),t),n=new Set;for(let i of e.pages)if(r.has(i.id))for(let s of i.blocks)ee(s)&&o.has(s.id)&&n.add(s.id);return n}function Sn(e,t){let r=Bo(e,t);return _e(e).filter(o=>r.has(o.id))}var b=(e,t,r,o=[],n=[],i="")=>({iso2:e,name:t,dialCode:r,lengths:o,groups:n,example:i}),ie=[b("US","United States","1",[10],[3,3,4],"2015550123"),b("CA","Canada","1",[10],[3,3,4],"5145550123"),b("GB","United Kingdom","44",[10],[4,6],"7400123456"),b("AU","Australia","61",[9],[3,3,3],"412345678"),b("DE","Germany","49",[10,11],[4,7],"15123456789"),b("FR","France","33",[9],[1,2,2,2,2],"612345678"),b("IN","India","91",[10],[5,5],"8123456789"),b("DK","Denmark","45",[8],[2,2,2,2],"32123456"),b("SE","Sweden","46",[9],[2,3,4],"701234567"),b("NO","Norway","47",[8],[3,2,3],"40612345"),b("FI","Finland","358",[9,10],[2,3,4],"412345678"),b("NL","Netherlands","31",[9],[1,4,4],"612345678"),b("BE","Belgium","32",[9],[3,2,2,2],"470123456"),b("ES","Spain","34",[9],[3,3,3],"612345678"),b("IT","Italy","39",[9,10],[3,3,4],"3123456789"),b("PT","Portugal","351",[9],[3,3,3],"912345678"),b("IE","Ireland","353",[9],[2,3,4],"851234567"),b("CH","Switzerland","41",[9],[2,3,2,2],"781234567"),b("AT","Austria","43",[10,11],[3,7],"6641234567"),b("PL","Poland","48",[9],[3,3,3],"512345678"),b("CZ","Czechia","420",[9],[3,3,3],"601123456"),b("GR","Greece","30",[10],[3,3,4],"6912345678"),b("RO","Romania","40",[9],[3,3,3],"712345678"),b("HU","Hungary","36",[9],[2,3,4],"201234567"),b("UA","Ukraine","380",[9],[2,3,2,2],"501234567"),b("RU","Russia","7",[10],[3,3,2,2],"9123456789"),b("TR","Turkey","90",[10],[3,3,2,2],"5012345678"),b("IL","Israel","972",[9],[2,3,4],"501234567"),b("AE","United Arab Emirates","971",[9],[2,3,4],"501234567"),b("SA","Saudi Arabia","966",[9],[2,3,4],"512345678"),b("ZA","South Africa","27",[9],[2,3,4],"711234567"),b("NG","Nigeria","234",[10],[3,3,4],"8021234567"),b("KE","Kenya","254",[9],[3,3,3],"712123456"),b("EG","Egypt","20",[10],[3,3,4],"1001234567"),b("BR","Brazil","55",[10,11],[2,5,4],"11961234567"),b("MX","Mexico","52",[10],[3,3,4],"2221234567"),b("AR","Argentina","54",[10],[4,6],"1123456789"),b("CL","Chile","56",[9],[1,4,4],"221234567"),b("CO","Colombia","57",[10],[3,3,4],"3211234567"),b("PE","Peru","51",[9],[3,3,3],"912345678"),b("CN","China","86",[11],[3,4,4],"13123456789"),b("JP","Japan","81",[10],[2,4,4],"9012345678"),b("KR","South Korea","82",[9,10],[2,4,4],"1023456789"),b("SG","Singapore","65",[8],[4,4],"81234567"),b("HK","Hong Kong","852",[8],[4,4],"51234567"),b("TW","Taiwan","886",[9],[3,3,3],"912345678"),b("MY","Malaysia","60",[9,10],[2,3,4],"123456789"),b("ID","Indonesia","62",[10,11],[3,4,4],"81234567890"),b("TH","Thailand","66",[9],[2,3,4],"812345678"),b("PH","Philippines","63",[10],[3,3,4],"9171234567"),b("VN","Vietnam","84",[9],[3,3,3],"912345678"),b("PK","Pakistan","92",[10],[3,3,4],"3012345678"),b("BD","Bangladesh","880",[10],[2,4,4],"1812345678"),b("NZ","New Zealand","64",[9,10],[2,3,4],"211234567"),b("SK","Slovakia","421",[9],[3,3,3],"912123456"),b("BG","Bulgaria","359",[9],[2,3,4],"481234567"),b("HR","Croatia","385",[8,9],[2,3,4],"921234567"),b("RS","Serbia","381",[8,9],[2,3,4],"601234567"),b("SI","Slovenia","386",[8],[2,3,3],"31234567"),b("LT","Lithuania","370",[8],[3,2,3],"61234567"),b("LV","Latvia","371",[8],[2,3,3],"21234567"),b("EE","Estonia","372",[7,8],[3,4],"51234567"),b("IS","Iceland","354",[7],[3,4],"6111234"),b("LU","Luxembourg","352",[9],[3,3,3],"628123456"),b("MA","Morocco","212",[9],[3,3,3],"650123456"),b("CR","Costa Rica","506",[8],[4,4],"83123456"),b("EC","Ecuador","593",[9],[2,3,4],"991234567"),b("UY","Uruguay","598",[8],[1,3,4],"94231234"),b("QA","Qatar","974",[8],[4,4],"33123456"),b("KW","Kuwait","965",[8],[4,4],"50012345")],Vo=new Map(ie.map(e=>[e.iso2,e])),Ho={"Africa/Cairo":"EG","Africa/Casablanca":"MA","Africa/Johannesburg":"ZA","Africa/Lagos":"NG","Africa/Nairobi":"KE","America/Adak":"US","America/Anchorage":"US","America/Argentina/Buenos_Aires":"AR","America/Argentina/Cordoba":"AR","America/Argentina/Mendoza":"AR","America/Bahia":"BR","America/Belem":"BR","America/Bogota":"CO","America/Boise":"US","America/Boa_Vista":"BR","America/Cancun":"MX","America/Chicago":"US","America/Chihuahua":"MX","America/Campo_Grande":"BR","America/Costa_Rica":"CR","America/Cuiaba":"BR","America/Denver":"US","America/Detroit":"US","America/Edmonton":"CA","America/Fortaleza":"BR","America/Guayaquil":"EC","America/Halifax":"CA","America/Hermosillo":"MX","America/Indiana/Indianapolis":"US","America/Indianapolis":"US","America/Juneau":"US","America/Kentucky/Louisville":"US","America/Lima":"PE","America/Los_Angeles":"US","America/Maceio":"BR","America/Manaus":"BR","America/Matamoros":"MX","America/Mazatlan":"MX","America/Merida":"MX","America/Mexico_City":"MX","America/Moncton":"CA","America/Monterrey":"MX","America/Montevideo":"UY","America/New_York":"US","America/Noronha":"BR","America/Nome":"US","America/North_Dakota/Center":"US","America/Ojinaga":"MX","America/Phoenix":"US","America/Porto_Velho":"BR","America/Punta_Arenas":"CL","America/Recife":"BR","America/Regina":"CA","America/Rio_Branco":"BR","America/Santiago":"CL","America/Sao_Paulo":"BR","America/Sitka":"US","America/St_Johns":"CA","America/Tijuana":"MX","America/Toronto":"CA","America/Vancouver":"CA","America/Whitehorse":"CA","America/Winnipeg":"CA","America/Yakutat":"US","Asia/Bangkok":"TH","Asia/Calcutta":"IN","Asia/Dacca":"BD","Asia/Dhaka":"BD","Asia/Dubai":"AE","Asia/Hong_Kong":"HK","Asia/Ho_Chi_Minh":"VN","Asia/Jakarta":"ID","Asia/Jerusalem":"IL","Asia/Karachi":"PK","Asia/Kolkata":"IN","Asia/Kuala_Lumpur":"MY","Asia/Kuwait":"KW","Asia/Manila":"PH","Asia/Qatar":"QA","Asia/Riyadh":"SA","Asia/Seoul":"KR","Asia/Shanghai":"CN","Asia/Saigon":"VN","Asia/Singapore":"SG","Asia/Taipei":"TW","Asia/Tel_Aviv":"IL","Asia/Tokyo":"JP","Asia/Urumqi":"CN","Atlantic/Reykjavik":"IS","Australia/Adelaide":"AU","Australia/Brisbane":"AU","Australia/Darwin":"AU","Australia/Hobart":"AU","Australia/Melbourne":"AU","Australia/Perth":"AU","Australia/Sydney":"AU","Europe/Amsterdam":"NL","Europe/Athens":"GR","Europe/Belgrade":"RS","Europe/Berlin":"DE","Europe/Bratislava":"SK","Europe/Brussels":"BE","Europe/Bucharest":"RO","Europe/Budapest":"HU","Europe/Copenhagen":"DK","Europe/Dublin":"IE","Europe/Helsinki":"FI","Europe/Zagreb":"HR","Europe/Istanbul":"TR","Europe/Kiev":"UA","Europe/Kyiv":"UA","Europe/Lisbon":"PT","Europe/Ljubljana":"SI","Europe/London":"GB","Europe/Luxembourg":"LU","Europe/Madrid":"ES","Europe/Moscow":"RU","Europe/Oslo":"NO","Europe/Paris":"FR","Europe/Prague":"CZ","Europe/Riga":"LV","Europe/Rome":"IT","Europe/Sofia":"BG","Europe/Stockholm":"SE","Europe/Tallinn":"EE","Europe/Vienna":"AT","Europe/Vilnius":"LT","Europe/Warsaw":"PL","Europe/Zurich":"CH","Pacific/Auckland":"NZ"};function Gt(e){let t=e.toUpperCase();return/^[A-Z]{2}$/.test(t)?String.fromCodePoint(...[...t].map(r=>127462+r.charCodeAt(0)-65)):"\u{1F3F3}\uFE0F"}function it(e){return e?Vo.get(e.toUpperCase()):void 0}function En(e){return it(e?Ho[e]:void 0)}function qo(e){let t;for(let r of ie)e.startsWith(r.dialCode)&&(!t||r.dialCode.length>t.dialCode.length)&&(t=r);return t}function se(e){return e.replace(/[^\d]/g,"")}function st(e,t){let r=se(t);if(!r)return"";let o=e?.groups?.length?e.groups:[],n=[],i=0;for(let s of o){if(i>=r.length)break;n.push(r.slice(i,i+s)),i+=s}for(;i<r.length;)n.push(r.slice(i,i+3)),i+=3;return n.join(" ")}function An(e,t){let r=se(t);return r?`+${e.dialCode}${r}`:""}function at(e,t){let r=(e??"").trim(),o=r.startsWith("+"),n=se(r);if(!n)return{country:t,national:"",e164:""};if(o){let i=qo(n);if(i){let s=n.slice(i.dialCode.length);return{country:i,national:s,e164:`+${n}`}}return{national:n,e164:`+${n}`}}if(t){let i=n.startsWith(t.dialCode)?n.slice(t.dialCode.length):n;return{country:t,national:i,e164:`+${t.dialCode}${i}`}}return{national:n,e164:`+${n}`}}function Ko(e){let{country:t,national:r,e164:o}=at(e);if(!o)return!1;let n=se(o).length;return n<8||n>15?!1:t?.lengths.length?t.lengths.includes(r.length):r.length>=4}var Wo=8;function Cn(e,t){if(!e||!t||typeof window>"u")return"below";let r=Wo,o=document.documentElement.clientWidth||window.innerWidth,n=document.documentElement.clientHeight||window.innerHeight,i=e.getBoundingClientRect(),s=Math.max(0,n-i.bottom-r),a=Math.max(0,i.top-r),l=s<t.scrollHeight&&a>s?"above":"below",u=Math.max(0,Math.min(l==="above"?a:s,n-r*2)),d=Math.max(0,o-r*2);t.style.setProperty("--fillo-phone-popover-max-height",`${Math.floor(u)}px`),t.style.setProperty("--fillo-phone-popover-max-width",`${Math.floor(d)}px`),t.style.setProperty("--fillo-phone-popover-offset-x","0px");let f=Math.min(t.offsetWidth,d),h=0,m=i.left+f-(o-r);m>0&&(h-=m);let v=r-(i.left+h);return v>0&&(h+=v),t.style.setProperty("--fillo-phone-popover-offset-x",`${Math.round(h)}px`),l}var Go="This field is required";var Jo=Me({fileId:D().check($e(1)),name:D(),size:tn().check(At()),mime:D(),url:H(D())});function Fn(e){return e==null?!0:typeof e=="string"?e.trim()==="":Array.isArray(e)?e.length===0:typeof e=="boolean"?e===!1:typeof e=="object"?Object.keys(e).length===0:!1}function In(e,t){if(Fn(t))return e.required?Go:null;switch(e.kind){case"short_text":case"long_text":{if(typeof t!="string")return"Expected text";if(e.maxLength&&t.length>e.maxLength)return`Must be at most ${e.maxLength} characters`;let r=e.kind==="long_text"?2e4:2e3;return!e.maxLength&&t.length>r?"Answer is too long":null}case"email":return typeof t!="string"?"Enter a valid email address":e.maxLength&&t.length>e.maxLength?`Must be at most ${e.maxLength} characters`:Je().safeParse(t).success?null:"Enter a valid email address";case"url":{if(typeof t!="string")return"Enter a valid URL (including https://)";if(e.maxLength&&t.length>e.maxLength)return`Must be at most ${e.maxLength} characters`;try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:")return"Enter an http(s) URL"}catch{return"Enter a valid URL (including https://)"}return null}case"phone":return typeof t!="string"||!Ko(t)?"Enter a valid phone number":null;case"number":{let r=typeof t=="string"?Number(t):t;return typeof r!="number"||!Number.isFinite(r)?"Enter a number":e.min!==void 0&&r<e.min?`Must be at least ${e.min}`:e.max!==void 0&&r>e.max?`Must be at most ${e.max}`:null}case"select":case"dropdown":return typeof t!="string"||t===""?"Pick an option":e.options.some(r=>r.id===t)||e.allowOther&&t.length<=500?null:"Pick a valid option";case"multi_select":{if(!Array.isArray(t))return"Pick at least one option";let r=new Set(e.options.map(s=>s.id)),o=t,n=0,i=new Set;for(let s of o){if(typeof s!="string")return"Pick valid options";if(i.has(s))return"Pick each option only once";if(i.add(s),!r.has(s)){if(e.allowOther!==!0||s.length===0||s.length>500)return"Pick valid options";if(++n>1)return"Only one 'Other' answer is allowed"}}return null}case"checkbox":return typeof t=="boolean"?null:"Invalid value";case"rating":{let r=e.max??5,o=typeof t=="string"?Number(t):t;return typeof o!="number"||!Number.isInteger(o)||o<1||o>r?`Pick a rating between 1 and ${r}`:null}case"linear_scale":{let r=e.min??1,o=e.max??10,n=typeof t=="string"?Number(t):t;return typeof n!="number"||!Number.isInteger(n)||n<r||n>o?`Pick a value between ${r} and ${o}`:null}case"ranking":{if(!Array.isArray(t))return"Drag the options into order";let r=e.options.map(n=>n.id).sort(),o=[...t].sort();return r.length!==o.length||r.some((n,i)=>n!==o[i])?"Rank every option":null}case"matrix":{if(typeof t!="object"||t===null||Array.isArray(t))return"Answer the grid";let r=t,o=new Set(e.columns.map(i=>i.id)),n=new Set(e.rows.map(i=>i.id));for(let[i,s]of Object.entries(r))if(!n.has(i)||!o.has(s))return"Invalid grid answer";return e.required&&Object.keys(r).length<e.rows.length?"Answer every row":null}case"signature":return typeof t!="string"||!t.startsWith("data:image/")?"Sign in the box":null;case"hidden":return typeof t=="string"?null:"Invalid value";case"custom":return null;case"date":{if(typeof t!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(t))return"Enter a valid date";let[r,o,n]=t.split("-").map(Number),i=new Date(Date.UTC(r,o-1,n));return i.getUTCFullYear()!==r||i.getUTCMonth()!==o-1||i.getUTCDate()!==n?"Enter a valid date":null}case"file_upload":{let r=he(Jo).safeParse(t);if(!r.success)return"Upload did not complete";let o=e.maxFiles??1;return r.data.length>o?`At most ${o} file${o===1?"":"s"}`:null}}}function Pn(e,t){let r=Sn(e,t),o={},n={};for(let i of r){let s=Xo(i,t[i.id]),a=In(i,s);a?o[i.id]=a:Fn(s)||(n[i.id]=s)}return{ok:Object.keys(o).length===0,errors:o,data:n}}function Xo(e,t){if(t==null||e.kind==="custom")return t;if(e.kind==="number"&&typeof t=="string"&&t.trim()!==""){let r=Number(t);return Number.isNaN(r)?t:r}if((e.kind==="rating"||e.kind==="linear_scale")&&typeof t=="string"){let r=Number(t);return Number.isNaN(r)?t:r}return typeof t=="string"?t.trim():t}var Yo=["short_text","long_text","email","url","phone","number","select","multi_select","dropdown","checkbox","rating","linear_scale","ranking","matrix","signature","date","file_upload","hidden","custom"],Qo=["heading","paragraph","divider"],ei=[...Yo,...Qo],Jt=D().check($e(1),O(128)),Pt=Ct({id:Jt,label:D().check(O(1e3)),icon:H(Ne())}),ti=Ct({id:Jt,kind:on(ei),label:H(D().check(O(2e3))),options:H(he(Pt).check(O(200))),rows:H(he(Pt).check(O(200))),columns:H(he(Pt).check(O(200)))}),ri=Me({id:Jt,title:H(D().check(O(500))),blocks:he(ti).check(O(500)),next:H(Ne())}),ni=Me({version:sn(1),title:Ft(H(D().check(O(2e3))),""),description:H(D().check(O(5e3))),pages:he(ri).check($e(1),O(50)),settings:Ft(H(nn(D(),Ne())),{})}),oi=1,Bt=1,Vt="0.9.0";function G(e,t,r=""){return typeof e=="string"?e.trim().slice(0,t):r}function M(e,t){let r=G(e,t);return r===""?void 0:r}function oe(e){return typeof e=="boolean"?e:void 0}function Oe(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function ye(e,t,r,o){let n=Oe(e);return n===void 0?o:Math.max(t,Math.min(r,Math.round(n)))}function Ye(e,t=200){return Array.isArray(e)?e.slice(0,t).flatMap(r=>{if(!r||typeof r!="object")return[];let o=r,n=G(o.id,128),i=G(o.label,1e3),s=o.icon==="thumbs_up"||o.icon==="thumbs_down"?o.icon:void 0;return n&&i?[P({id:n,label:i,icon:s})]:[]}):[]}function Zt(e){let t=new Set;for(let{id:r}of e){if(t.has(r))return r;t.add(r)}}function Zn(e){if(!Array.isArray(e))return;let t=e.slice(0,20).flatMap(r=>{if(!r||typeof r!="object")return[];let o=r,n=o.op;if(n!=="eq"&&n!=="neq"&&n!=="contains"&&n!=="gt"&&n!=="lt"&&n!=="answered"&&n!=="not_answered")return[];let i=G(o.fieldId,128);if(!i)return[];let s=o.value,a=typeof s=="string"||typeof s=="number"||typeof s=="boolean"?s:void 0;return[{fieldId:i,op:n,...a!==void 0?{value:a}:{}}]});return t.length?t:void 0}function ii(e,t,r,o){if(!Array.isArray(e))return;let n=e.slice(0,50).flatMap(i=>{if(!i||typeof i!="object")return[];let s=i,a=typeof s.to=="string"?s.to:void 0;if(!a||a!=="end"&&!t.has(a))return[];if(a===r)return[];let l=s.when;if(l!==void 0&&!Array.isArray(l))return[];let c=Zn(l);return Array.isArray(l)&&l.length>0&&c===void 0?[]:c&&c.some(u=>!o.has(u.fieldId))?[]:[{when:c??[],to:a}]});return n.length?n:void 0}function Nn(e){return{id:G(e.id,128),visibleIf:Zn(e.visibleIf)}}function U(e,t){return{...Nn(e),kind:t,label:G(e.label,2e3,"Untitled field"),description:M(e.description,5e3),required:oe(e.required),placeholder:M(e.placeholder,500)}}function cn(e){let t=M(e,2e3);if(t)try{let r=new URL(t);return r.protocol==="http:"||r.protocol==="https:"?t:void 0}catch{return}}function si(e){if(!e||typeof e!="object")return;let t=e,r=t.by==="browser"||t.by==="field"||t.by==="identify"?t.by:void 0;if(!r)return;let o=r==="field"?M(t.field,128):void 0;if(r==="field"&&!o)return;let n=M(t.scopeField,128),i=t.onRepeat==="update"&&r==="identify"?"update":"keep";return{by:r,...o?{field:o}:{},...n?{scopeField:n}:{},onRepeat:i}}function ai(e){if(!e||typeof e!="object")return;let t=e,r=t.unverified==="allow"||t.unverified==="quarantine"?t.unverified:void 0,o=t.challenge==="turnstile"?"turnstile":void 0;if(!(!r&&!o))return{...r?{unverified:r}:{},...o?{challenge:o}:{}}}function li(e){let t=e&&typeof e=="object"?e:{};return{submitMode:t.submitMode==="button"||t.submitMode==="auto"?t.submitMode:void 0,submitLabel:M(t.submitLabel,100),successTitle:M(t.successTitle,200),successMessage:M(t.successMessage,5e3),redirectUrl:cn(t.redirectUrl),showProgress:oe(t.showProgress),responseLimit:si(t.responseLimit),trust:ai(t.trust),notifyEmail:Je().check(O(254)).safeParse(t.notifyEmail).success?t.notifyEmail:void 0,sendReceipt:oe(t.sendReceipt),saveProgress:oe(t.saveProgress),draftAnswersVisible:oe(t.draftAnswersVisible),resumeEmails:oe(t.resumeEmails),resumeUrl:cn(t.resumeUrl),draftDigest:oe(t.draftDigest)}}function P(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ci(e){if(!e||typeof e!="object")return null;let t=e,r=t.kind,o=Nn(t);if(!o.id||typeof r!="string")return null;switch(r){case"heading":return P({...o,kind:r,text:G(t.text,2e3,"Section")});case"paragraph":return P({...o,kind:r,text:G(t.text,5e3)});case"divider":return P({...o,kind:r});case"short_text":case"email":case"url":return P({...U(t,r),maxLength:Oe(t.maxLength)===void 0?void 0:ye(t.maxLength,1,2e3,2e3)});case"phone":{let n=M(t.defaultCountry,2)?.toUpperCase();return P({...U(t,r),defaultCountry:n&&/^[A-Z]{2}$/.test(n)?n:void 0})}case"long_text":return P({...U(t,r),maxLength:Oe(t.maxLength)===void 0?void 0:ye(t.maxLength,1,2e4,2e4)});case"number":return P({...U(t,r),min:Oe(t.min),max:Oe(t.max)});case"select":case"multi_select":case"dropdown":{let n=Ye(t.options);return n.length===0?null:P({...U(t,r),options:n,allowOther:oe(t.allowOther),shuffleOptions:oe(t.shuffleOptions)})}case"checkbox":{let n=t.appearance==="toggle"?"toggle":void 0;return P({...U(t,r),appearance:n})}case"signature":case"date":return P(U(t,r));case"rating":{let n=ye(t.max,1,10,5);return P({...U(t,r),max:n,insightsMetric:t.insightsMetric==="csat"&&n===5?"csat":void 0})}case"linear_scale":{let n=ye(t.min,0,9,1),i=ye(t.max,n+1,10,10),s=t.insightsMetric==="nps"&&n===0&&i===10?"nps":t.insightsMetric==="csat"&&n===1&&i===5?"csat":void 0;return P({...U(t,r),min:n,max:i,minLabel:M(t.minLabel,100),maxLabel:M(t.maxLabel,100),insightsMetric:s})}case"ranking":{let n=Ye(t.options);return n.length<2?null:P({...U(t,r),options:n})}case"matrix":{let n=Ye(t.rows),i=Ye(t.columns);return n.length===0||i.length===0?null:P({...U(t,r),rows:n,columns:i})}case"hidden":return P({...U(t,r),required:!1,paramName:M(t.paramName,128),defaultValue:M(t.defaultValue,1e3)});case"file_upload":return P({...U(t,r),maxFiles:ye(t.maxFiles,1,20,1),maxFileSizeMb:ye(t.maxFileSizeMb,1,5e3,500),accept:Array.isArray(t.accept)?t.accept.flatMap(n=>{let i=M(n,100);return i?[i]:[]}).slice(0,50):void 0});case"custom":return P({...U(t,r),component:G(t.component,128),config:t.config&&typeof t.config=="object"&&!Array.isArray(t.config)?t.config:void 0});default:return null}}function ve(e){let t=ni.safeParse(e);if(!t.success){let u=t.error.issues[0],d=u?.path.join(".");return{ok:!1,error:u?`${d?`${d}: `:""}${u.message}`:"Invalid schema"}}if(t.data.version>oi)return{ok:!1,error:`Unsupported schema version: ${t.data.version}`};let r=t.data.pages.map(u=>{let d=u.blocks.flatMap(f=>{let h=ci(f);return h?[h]:[]});return{id:G(u.id,128),title:M(u.title,500),blocks:d,next:u.next}}),o=new Set(r.map(u=>u.id)),n=new Set,i=r.map(u=>{for(let d of u.blocks)ee(d)&&n.add(d.id);return P({id:u.id,title:u.title,blocks:u.blocks,next:ii(u.next,o,u.id,new Set(n))})}),s=new Set,a=new Set;for(let u of i){if(!u.id)return{ok:!1,error:"Page ids cannot be blank"};if(s.has(u.id))return{ok:!1,error:`Duplicate page id: ${u.id}`};s.add(u.id);for(let d of u.blocks){if(a.has(d.id))return{ok:!1,error:`Duplicate block id: ${d.id}`};if(a.add(d.id),d.kind==="number"&&d.min!==void 0&&d.max!==void 0&&d.min>d.max)return{ok:!1,error:`Field ${d.id} has min greater than max`};if(d.kind==="select"||d.kind==="multi_select"||d.kind==="dropdown"||d.kind==="ranking"){let f=Zt(d.options);if(f)return{ok:!1,error:`Duplicate option id in field ${d.id}: ${f}`}}else if(d.kind==="matrix"){let f=Zt(d.rows);if(f)return{ok:!1,error:`Duplicate matrix row id in field ${d.id}: ${f}`};let h=Zt(d.columns);if(h)return{ok:!1,error:`Duplicate matrix column id in field ${d.id}: ${h}`}}}}if(i.every(u=>u.blocks.length===0))return{ok:!1,error:"Schema must contain at least one valid block"};let l={version:Bt,title:G(t.data.title,2e3),pages:i,settings:li(t.data.settings)},c=M(t.data.description,5e3);return c&&(l.description=c),{ok:!0,schema:l}}function Le(e,t){let r=M(e,t);if(r&&!(/[;{}<>]/.test(r)||/url\s*\(/i.test(r)))return r}function Xt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=t.colorScheme==="light"||t.colorScheme==="dark"||t.colorScheme==="auto"?t.colorScheme:void 0,o=P({colorScheme:r,primary:Le(t.primary,200),background:Le(t.background,200),text:Le(t.text,200),radius:Le(t.radius,64),fontFamily:Le(t.fontFamily,200)});return Object.keys(o).length>0?o:null}var Ht="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",ui=256-256%Ht.length;function un(e=12){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError("createId size must be a positive safe integer");let t=globalThis.crypto;if(typeof t>"u"||typeof t.getRandomValues!="function")throw new Error("createId requires Web Crypto (globalThis.crypto.getRandomValues)");let r="";for(;r.length<e;){let o=new Uint8Array(e);t.getRandomValues(o);for(let n=0;n<e&&r.length<e;n++){let i=o[n];i<ui&&(r+=Ht[i%Ht.length])}}return r}var Mn=class{h0=1732584193;h1=4023233417;h2=2562383102;h3=271733878;h4=3285377520;block=new Uint8Array(64);blockLen=0;totalLen=0;w=new Int32Array(80);update(e){this.totalLen+=e.length;let t=0;if(this.blockLen>0){for(;t<e.length&&this.blockLen<64;)this.block[this.blockLen++]=e[t++];this.blockLen===64&&(this.process(this.block),this.blockLen=0)}for(;t+64<=e.length;)this.process(e.subarray(t,t+64)),t+=64;for(;t<e.length;)this.block[this.blockLen++]=e[t++];return this}digest(){let e=Math.floor(this.totalLen/536870912),t=this.totalLen*8>>>0,r=[128],o=this.blockLen+1;for(;o%64!==56;)r.push(0),o++;r.push(e>>>24&255,e>>>16&255,e>>>8&255,e&255),r.push(t>>>24&255,t>>>16&255,t>>>8&255,t&255),this.update(new Uint8Array(r));let n=new Uint8Array(20),i=[this.h0,this.h1,this.h2,this.h3,this.h4];for(let s=0;s<5;s++)n[s*4]=i[s]>>>24&255,n[s*4+1]=i[s]>>>16&255,n[s*4+2]=i[s]>>>8&255,n[s*4+3]=i[s]&255;return n}process(e){let t=this.w;for(let a=0;a<16;a++)t[a]=e[a*4]<<24|e[a*4+1]<<16|e[a*4+2]<<8|e[a*4+3];for(let a=16;a<80;a++){let l=t[a-3]^t[a-8]^t[a-14]^t[a-16];t[a]=l<<1|l>>>31}let r=this.h0,o=this.h1,n=this.h2,i=this.h3,s=this.h4;for(let a=0;a<80;a++){let l,c;a<20?(l=o&n|~o&i,c=1518500249):a<40?(l=o^n^i,c=1859775393):a<60?(l=o&n|o&i|n&i,c=2400959708):(l=o^n^i,c=3395469782);let u=(r<<5|r>>>27)+l+s+c+t[a]|0;s=i,i=n,n=o<<30|o>>>2,o=r,r=u}this.h0=this.h0+r|0,this.h1=this.h1+o|0,this.h2=this.h2+n|0,this.h3=this.h3+i|0,this.h4=this.h4+s|0}},Qe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Yt(e){let t="";for(let r=0;r<e.length;r+=3){let o=e[r],n=r+1<e.length?e[r+1]:0,i=r+2<e.length?e[r+2]:0;t+=Qe[o>>2],t+=Qe[(o&3)<<4|n>>4],t+=r+1<e.length?Qe[(n&15)<<2|i>>6]:"=",t+=r+2<e.length?Qe[i&63]:"="}return t}var di=e=>Yt(new Mn().update(e).digest()),k=class extends Error{constructor(e,t,r,o){super(e),this.status=t,this.retryAfterSec=r,this.code=o,this.name="FilloError"}status;retryAfterSec;code};function q(e){return e instanceof Error&&e.name==="FilloError"}async function dn(e,t){try{let r=await e.json();return{message:typeof r.error=="string"&&r.error?r.error:t,code:typeof r.code=="string"&&r.code?r.code:void 0}}catch{}return{message:t}}function pn(e){let t=Number(e.headers.get("retry-after"));return Number.isFinite(t)&&t>0?t:void 0}var Te=3,Re=3e4,pi=5*6e4,Q=10*6e4;function fn(e,t){return t?.throwIfAborted(),new Promise((r,o)=>{let n=()=>{clearTimeout(i),o(t?.reason)},i=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function Nt(e,t=!1){let r=q(e)?e.status??0:0;return r===0||r===503||r===504||t&&r===409&&q(e)&&e.retryAfterSec!==void 0}function et(e){return e>=500||e===429||e===408}function hn(e){return typeof DOMException<"u"&&e instanceof DOMException&&e.name==="TimeoutError"?new k("Request timed out",0):e}function fi(e,t){let r=e.split(".").map(n=>Number(n)||0),o=t.split(".").map(n=>Number(n)||0);for(let n=0;n<Math.max(r.length,o.length);n++){let i=(r[n]??0)-(o[n]??0);if(i!==0)return i}return 0}function hi(e){if(e.schemaVersion!==void 0&&e.schemaVersion!==Bt)throw new k(`This form uses schema version ${e.schemaVersion}; this SDK supports version ${Bt}. Update @usefillo/* to render it.`,426);if(e.minSdkVersion&&fi(Vt,e.minSdkVersion)<0)throw new k(`This form requires @usefillo/* ${e.minSdkVersion} or newer. Current SDK is ${Vt}.`,426)}function tt(e,t){return r=>t.onProgress?.({uploadedBytes:r,totalBytes:e,fraction:e===0?1:r/e})}async function mi(e){let t=globalThis.crypto?.subtle;if(t){let r=await t.digest("SHA-1",e);return Yt(new Uint8Array(r))}return di(e)}var gi="https://fillo.so",mn={"X-Fillo-Client":`@usefillo/core@${Vt}`},lt=class{baseUrl;fetch;key;constructor(e={}){this.baseUrl=e.baseUrl?e.baseUrl.replace(/\/$/,""):e.sameOrigin?"":gi,this.key=e.key,this.fetch=e.fetch??((...t)=>globalThis.fetch(...t))}url(e){return`${this.baseUrl}/api/v1${e}`}async json(e,t){let r=t?.body!=null?{"Content-Type":"application/json",...mn,...t?.headers}:t?.headers,o;try{o=await this.fetch(this.url(e),{...t,headers:r,signal:t?.signal??AbortSignal.timeout(Re)})}catch(n){throw hn(n)}if(!o.ok){let{message:n,code:i}=await dn(o,`Request failed: ${o.status}`);throw new k(n,o.status,pn(o),i)}return await o.json()}async getForm(e){let t=await this.json(`/forms/${encodeURIComponent(e)}`);return hi(t),t}syncForm(e,t,r){if(!this.key)return Promise.reject(new k("createClient needs a `key` (pk_\u2026) to sync code-defined forms",401));let o=ve(t);return o.ok?this.json("/forms/sync",{method:"POST",body:JSON.stringify({key:this.key,id:e,schema:o.schema,theme:Xt(r)})}):Promise.reject(new k(`Invalid form schema: ${o.error}`,400))}async submit(e,t,r){let o;try{o=await this.fetch(this.url(`/forms/${encodeURIComponent(e)}/responses`),{method:"POST",headers:{"Content-Type":"application/json",...mn},body:JSON.stringify({data:t,meta:r}),signal:AbortSignal.timeout(Re)})}catch(i){throw hn(i)}if(o.status===422)return{ok:!1,errors:(await o.json()).errors};if(!o.ok){let{message:i,code:s}=await dn(o,`Submit failed: ${o.status}`);throw new k(i,o.status,pn(o),s)}let n=await o.json();return{ok:!0,responseId:n.id,duplicate:n.duplicate,updated:n.updated}}async fetchOwnResponse(e,t,r){try{return await this.json(`/forms/${encodeURIComponent(e)}/respondent-response`,{method:"POST",body:JSON.stringify({respondent:t,scopeValue:r})})}catch(o){if(q(o)&&(o.status===404||o.status===403))return null;throw o}}async startSession(e,t){try{let r=await this.fetch(this.url(`/forms/${encodeURIComponent(e)}/sessions`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pageCount:t}),signal:AbortSignal.timeout(Re)});return r.ok?(await r.json()).id:null}catch{return null}}reportProgress(e,t){try{this.fetch(this.url(`/sessions/${encodeURIComponent(e)}/progress`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0,signal:AbortSignal.timeout(Re)}).catch(()=>{})}catch{}}createDraft(e,t){return this.json(`/forms/${encodeURIComponent(e)}/drafts`,{method:"POST",body:JSON.stringify(t)})}getDraft(e,t,r){return this.json(`/drafts/${encodeURIComponent(e)}`,{headers:r?{"X-Fillo-Draft-Token":t,"X-Fillo-Draft-Adopt":"1"}:{"X-Fillo-Draft-Token":t}})}async saveDraft(e,t,r,o){await this.json(`/drafts/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"X-Fillo-Draft-Token":t},body:JSON.stringify(r),...o?.keepalive?{keepalive:!0}:{}})}async deleteDraft(e,t){await this.json(`/drafts/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-Fillo-Draft-Token":t}})}getUploadSession(e,t,r=AbortSignal.timeout(Q)){return this.json(`/uploads/${encodeURIComponent(e)}`,{...t?{headers:{"X-Fillo-Upload-Token":t}}:{},signal:r})}async uploadFile(e,t,r){let o=typeof File<"u"&&t instanceof File?t.name:"upload.bin",n=(t.type||"application/octet-stream").trim().toLowerCase(),i;if(r.sessionId){let c=await this.getUploadSession(r.sessionId,r.uploadToken,this.uploadSignal(r,Q));if(c.formId!==e||c.fieldId!==r.fieldId||c.fileName!==o||c.size!==t.size||c.mime.trim().toLowerCase()!==n)throw new k("File does not match this upload session",400);i=c,i.token||=r.uploadToken}else{let c=un(24),u=un(32),d=()=>this.json(`/forms/${encodeURIComponent(e)}/uploads`,{method:"POST",body:JSON.stringify({requestId:c,uploadToken:u,fieldId:r.fieldId,fileName:o,size:t.size,mime:n}),signal:this.uploadSignal(r,Q)}),f=Date.now()+Q,h=250;for(;;)try{i=await d();break}catch(m){if(r.signal?.aborted||!Nt(m,!0))throw m;let v=f-Date.now();if(v<=0)throw m;await fn(Math.min(h,v),r.signal),h=Math.min(h*2,5e3)}}if(r.onSession?.({sessionId:i.id,uploadToken:i.token}),i.status==="complete"&&i.file)return i.file;if(i.status==="aborted")throw new k("This upload session was cancelled",409);let s;if(i.transport?.type==="gdrive")await this.driveUploadLoop(i,i.transport.uploadUrl,t,r);else if(i.transport?.type==="s3-multipart")await this.s3MultipartUploadLoop(i,t,r);else if(i.transport?.type==="s3-put")await this.s3PutUpload(i.transport.uploadUrl,t,r);else if(i.transport?.type==="box")s=await this.boxUpload(i.transport,t,r);else throw new k("This form's storage doesn't support uploads \u2014 connect Drive, S3, or Box.");let a=()=>this.json(`/uploads/${encodeURIComponent(i.id)}/complete`,{method:"POST",headers:i.token?{"X-Fillo-Upload-Token":i.token}:void 0,...s?{body:JSON.stringify(s)}:{},signal:this.uploadSignal(r,Q)}),l;try{l=await a()}catch(c){if(r.signal?.aborted||!Nt(c))throw c;let u=Date.now()+Q,d=250;for(;;){let f=await this.getUploadSession(i.id,i.token,this.uploadSignal(r,Math.max(1,u-Date.now())));if(f.status==="complete"&&f.file)return f.file;if(f.status==="aborted")throw c;try{l=await a();break}catch(m){if(r.signal?.aborted||!Nt(m,!0))throw m}let h=u-Date.now();if(h<=0)throw c;await fn(Math.min(d,h),r.signal),d=Math.min(d*2,5e3)}}if(!l.file)throw new k("Upload completed but no file was returned");return l.file}async boxUpload(e,t,r){let o=tt(t.size,r);o(0);let n={Authorization:`Bearer ${e.token}`};if(e.mode==="simple"){let f=new FormData;f.append("attributes",JSON.stringify({name:e.fileName,parent:{id:e.folderId}})),f.append("file",t,e.fileName);let h=await this.retry(r,async()=>{let v=await this.fetch(e.uploadUrl,{method:"POST",headers:n,body:f,signal:this.uploadSignal(r)});if(!v.ok&&et(v.status))throw new k(`Box upload failed: ${v.status}`,v.status);return v});if(!h.ok)throw new k(`Box upload failed: ${h.status}`,h.status);let m=await h.json();return o(t.size),{providerFileId:m.entries?.[0]?.id}}if(e.size!==t.size)throw new k(`File size changed since the upload was requested (${t.size} vs ${e.size}).`,400);let i=await this.retry(r,async()=>{let f=await this.fetch(e.sessionUrl,{method:"POST",headers:{...n,"Content-Type":"application/json"},body:JSON.stringify({folder_id:e.folderId,file_size:e.size,file_name:e.fileName}),signal:this.uploadSignal(r)});if(!f.ok&&et(f.status))throw new k(`Box session failed: ${f.status}`,f.status);return f});if(!i.ok)throw new k(`Box session failed: ${i.status}`,i.status);let s=await i.json(),a=new Mn,l=[],c=0;for(;c<t.size;){r.signal?.throwIfAborted();let f=Math.min(c+s.part_size,t.size),h=new Uint8Array(await t.slice(c,f).arrayBuffer());a.update(h);let m=await mi(h),v=await this.retry(r,async()=>{let E=await this.fetch(s.session_endpoints.upload_part,{method:"PUT",headers:{...n,"Content-Type":"application/octet-stream",Digest:`sha=${m}`,"Content-Range":`bytes ${c}-${f-1}/${t.size}`},body:h,signal:this.uploadSignal(r)});if(!E.ok&&et(E.status))throw new k(`Box part failed: ${E.status}`,E.status);return E});if(!v.ok)throw new k(`Box part failed: ${v.status}`,v.status);l.push((await v.json()).part),c=f,o(c)}let u=await this.retry(r,async()=>{let f=await this.fetch(s.session_endpoints.commit,{method:"POST",headers:{...n,"Content-Type":"application/json",Digest:`sha=${Yt(a.digest())}`},body:JSON.stringify({parts:l}),signal:this.uploadSignal(r)});if(!f.ok&&et(f.status))throw new k(`Box commit failed: ${f.status}`,f.status);return f});if(!u.ok)throw new k(`Box commit failed: ${u.status}`,u.status);return{providerFileId:(await u.json()).entries?.[0]?.id}}uploadSignal(e,t=Re){let r=AbortSignal.timeout(t);return e.signal?AbortSignal.any([e.signal,r]):r}async retry(e,t){let r=0;for(;;)try{return await t()}catch(o){if(e.signal?.aborted||(r+=1,r>=Te))throw o;await new Promise(n=>setTimeout(n,500*2**r))}}async driveUploadLoop(e,t,r,o){let n=e.uploadedBytes,i=tt(r.size,o);i(n);let s=0;for(;n<r.size;){o.signal?.throwIfAborted();let a=n,l=Math.min(n+e.chunkSize,r.size),c=r.slice(n,l),u=0;for(;;)try{let d=await this.fetch(t,{method:"PUT",headers:{"Content-Range":`bytes ${n}-${l-1}/${r.size}`},body:c,signal:this.uploadSignal(o)});if(d.status===308){let f=d.headers.get("Range")??d.headers.get("range"),h=f?.match(/bytes=0-(\d+)/);h?n=Number(h[1])+1:f==null?n=0:n=(await this.getUploadSession(e.id,e.token,this.uploadSignal(o,Q))).uploadedBytes;break}if(d.ok){n=r.size;break}throw new k(`Drive chunk failed: ${d.status}`,d.status)}catch(d){if(o.signal?.aborted||(u+=1,u>=Te))throw d;if(await new Promise(h=>setTimeout(h,500*2**u)),n=(await this.getUploadSession(e.id,e.token,this.uploadSignal(o,Q))).uploadedBytes,n>=r.size)break;l=Math.min(n+e.chunkSize,r.size),c=r.slice(n,l)}if(i(n),n<=a){if(++s>=Te)throw new k("Drive upload stalled \u2014 the storage endpoint stopped accepting progress",0)}else s=0}}async s3MultipartUploadLoop(e,t,r){if(!Number.isSafeInteger(e.chunkSize)||e.chunkSize<=0||!Number.isSafeInteger(e.uploadedBytes)||e.uploadedBytes<0||e.uploadedBytes>t.size||e.uploadedBytes<t.size&&e.uploadedBytes%e.chunkSize!==0)throw new k("S3 upload session returned invalid progress",502);let o=tt(t.size,r),n=e.uploadedBytes;for(o(n);n<t.size;){r.signal?.throwIfAborted();let i=Math.floor(n/e.chunkSize)+1;if(i>1e4)throw new k("S3 upload needs too many parts",413);let s=Math.min(n+e.chunkSize,t.size),a=t.slice(n,s),l=0;for(;;){let c;try{let u=await this.json(`/uploads/${encodeURIComponent(e.id)}/parts`,{method:"POST",headers:e.token?{"X-Fillo-Upload-Token":e.token}:void 0,body:JSON.stringify({partNumber:i}),signal:this.uploadSignal(r,Q)});if(typeof u.uploadUrl!="string"||!u.uploadUrl)throw new k("S3 part URL was unavailable",502);c=u.uploadUrl;let d=await this.fetch(c,{method:"PUT",body:a,signal:this.uploadSignal(r,pi)});if(!d.ok)throw new k(`S3 part upload failed: ${d.status}`,d.status);n=s,o(n);break}catch(u){if(r.signal?.aborted)throw u;let d=await this.getUploadSession(e.id,e.token,this.uploadSignal(r,Q));if(d.status==="aborted")throw new k("This upload session was cancelled",409);if(!Number.isSafeInteger(d.uploadedBytes)||d.uploadedBytes<n||d.uploadedBytes>t.size||d.uploadedBytes<t.size&&d.uploadedBytes%e.chunkSize!==0)throw new k("S3 upload session returned invalid progress",502);if(d.uploadedBytes>n){n=d.uploadedBytes,o(n);break}if(l+=1,l>=Te)throw u;await new Promise(f=>setTimeout(f,500*2**l))}}}}async s3PutUpload(e,t,r){let o=tt(t.size,r);o(0);let n=0;for(;;)try{let i=await this.fetch(e,{method:"PUT",headers:{"Content-Type":t.type||"application/octet-stream"},body:t,signal:this.uploadSignal(r)});if(!i.ok)throw new k(`S3 upload failed: ${i.status}`,i.status);o(t.size);return}catch(i){if(r.signal?.aborted||(n+=1,n>=Te))throw i;await new Promise(s=>setTimeout(s,500*2**n))}}};function De(e={}){return new lt(e)}function Mt(e){let t=e.trim();if(!/^-?\d*\.?\d+$/.test(t))return null;let r=Number(t);return Number.isFinite(r)?r:null}function gn(e,t){let r={};for(let o of _e(e)){let n=o.kind==="hidden"?t[o.paramName??o.id]??o.defaultValue:t[o.id];if(!(n===void 0||n===""))switch(o.kind){case"number":{let i=Mt(n);if(i===null||o.min!==void 0&&i<o.min||o.max!==void 0&&i>o.max)break;r[o.id]=i;break}case"rating":{let i=Mt(n);i!==null&&Number.isInteger(i)&&i>=1&&i<=(o.max??5)&&(r[o.id]=i);break}case"linear_scale":{let i=Mt(n),s=o.min??1,a=o.max??10;i!==null&&Number.isInteger(i)&&i>=s&&i<=a&&(r[o.id]=i);break}case"checkbox":r[o.id]=n==="true"||n==="1"||n==="yes";break;case"select":case"dropdown":{o.options.some(i=>i.id===n)&&(r[o.id]=n);break}case"multi_select":{let i=new Set(o.options.map(a=>a.id)),s=[...new Set(n.split(",").filter(a=>i.has(a)))];s.length>0&&(r[o.id]=s);break}case"file_upload":case"ranking":case"matrix":case"signature":case"custom":break;default:r[o.id]=n}}return r}var bi={id:"empty",blocks:[]},bn=!1,yn=!1;function yi(){yn||(yn=!0,console.warn("[fillo] This form has a client but no submission target \u2014 a bare schema can't sync. Wrap it in defineForm({ id, pages }) (or author it with <Fillo.Form id=\u2026>) so it gets a workspace handle, or pass formId for a dashboard-built form: https://fillo.so/docs"))}function vi(){bn||(bn=!0,console.warn("[fillo] This form has no `client`, so responses can't be submitted \u2014 it's render-only. Pass a client (createClient) to collect responses in Fillo, or forward them to your own backend with webhooks: https://fillo.so/docs"))}var Ln=new Map;function Qt(){try{return globalThis.localStorage??null}catch{return null}}function Tn(e){return`fillo:submission:${e}`}function er(){let e=globalThis.crypto;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);return e?.getRandomValues?(e.getRandomValues(t),Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")):`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function Rn(e,t,r,o){let n=Qt();if(!n)return e.get(r)??null;try{let i=JSON.parse(n.getItem(t)??"null");if(i&&o(i))return i}catch{}return null}function On(e,t,r,o){e.set(r,o);let n=Qt();if(n)try{n.setItem(t,JSON.stringify(o))}catch{}}function tr(e){return Rn(Ln,Tn(e),e,t=>typeof t.key=="string")}function Dn(e,t){On(Ln,Tn(e),e,t)}function _i(e){let t=tr(e);if(t?.key)return t.key;let r={key:er()};return Dn(e,r),r.key}function wi(e,t){let r=tr(e);Dn(e,{key:r?.key??er(),submittedAt:new Date().toISOString(),responseId:t})}function qt(e,t,r){let o=kn(e.settings,r);return o===null?t:`${t}::${o}`}function vn(e,t,r){return e.settings.responseLimit?.by!=="browser"||!t?!1:!!tr(qt(e,t,r))?.submittedAt}var rr=new Map;function nr(e){return`fillo:draft:${e}`}function rt(e){return Rn(rr,nr(e),e,t=>{let r=t;return typeof r.id=="string"&&typeof r.token=="string"})}function Lt(e,t){On(rr,nr(e),e,t)}function Tt(e){rr.delete(e);let t=Qt();if(t)try{t.removeItem(nr(e))}catch{}}function Rt(e){return q(e)&&(e.status===401||e.status===403||e.status===404)}var xi=1500,ki="Please complete the verification check, then submit.",$i="That verification didn't go through. Please complete the check again and resubmit.";function Un(e){return q(e)&&e.status&&e.status>0&&e.message?e.message:"Couldn't reach the server \u2014 check your connection and try again. If this keeps happening, a browser extension, firewall, or the site's Content-Security-Policy may be blocking the request."}function zi(e){if(q(e)){let t=e.status??0;if(t>0&&t<500&&t!==408&&t!==429)return"This form is unavailable."}return Un(e)}function jn(e){let{onChange:t,onSubmitted:r}=e,o=ve(e.form);if(!o.ok)throw new Error(`Invalid form schema: ${o.error}`);let n=o.schema,i=e.formId,s=e.client,a=e.respondent,l={...e.initialData??{}},c={},u=0,d="idle",f=!1,h=!1;queueMicrotask(()=>{if(typeof location<"u"&&location.search){let _=Object.fromEntries(new URLSearchParams(location.search)),y=null;for(let[w,A]of Object.entries(gn(n,_)))l[w]===void 0&&(y=y??{...l},y[w]=A);y&&d==="idle"&&(l=y,z())}d==="idle"&&vn(n,i,l)&&(d="submitted",f=!0,z());let g=!1;if(n.settings.saveProgress&&i&&s&&typeof location<"u"&&location.hash.includes("fillo-draft=")){let _=/fillo-draft=([^&]+)/.exec(location.hash),y=_?.[1]?decodeURIComponent(_[1]):"",w=y.indexOf(".");if(w>0){g=!0;let A=y.slice(0,w),S=y.slice(w+1);s.getDraft(A,S,!0).then(C=>{Lt(i,{id:A,token:C.token??S});try{history.replaceState(null,"",location.pathname+location.search)}catch{}}).catch(C=>{Rt(C)&&(h=!0,z())}).finally(()=>pt())}}g||pt()});let m,v=new Set,E=new Set,ae=Date.now(),Se=er(),B=null,J=!1,le=!1,te=!1,xe="created",Ee=!1,N=null,x=null,R=Promise.resolve(),L=!1,X=!1,ge=!1,Ae=!1;function I(){let g=n.pages.length,_=Math.min(u,Math.max(g-1,0)),y=n.pages[_]??bi;return{data:l,errors:c,status:d,pageIndex:_,pageCount:g,page:y,blocks:Xe(n,y,l),isFirstPage:_===0,isLastPage:jt(n,y.id,l),uploading:v.size>0,submitError:m,restoredSubmission:f,resumedDraft:le,editingPrevious:te,duplicateSubmission:xe==="duplicate",updatedSubmission:xe==="updated",resumeLinkFailed:h}}let V=I();function z(){V=I();for(let g of E)g()}function ce(g,_){try{r?.(g,_)}catch(y){console.error("[fillo] onSubmitted handler threw:",y)}}function to(g){let _=n.pages[g];if(!_)return{};let y={};for(let w of Xe(n,_,l)){if(!ee(w))continue;let A=In(w,l[w.id]);A&&(y[w.id]=A)}return y}function Ve(){return!!(n.settings.saveProgress&&s&&i&&!X)}function ro(){let g=new Set;for(let _ of n.pages)for(let y of _.blocks)ee(y)&&g.add(y.id);return g}function dt(g){if(d!=="idle"||J)return;let _=ro(),y=null;for(let[S,C]of Object.entries(g.data??{}))l[S]===void 0&&_.has(S)&&(y=y??{...l},y[S]=C);let w=typeof g.page=="number"&&Number.isFinite(g.page)?Math.max(0,Math.min(Math.floor(g.page),n.pages.length-1)):0,A=w>0&&u===0;!y&&!A||(y&&(l=y),A&&(u=w),le=!0,z())}function pt(){if(d!=="idle")return;if(!Ve()){dr();return}let g=i,_=s,y=N??rt(g);if(y&&!ge){ge=!0,N=y,_.getDraft(y.id,y.token).then(dt).catch(w=>{Rt(w)&&(Tt(g),N=null)});return}!y&&!Ae&&a?.hash&&(Ae=!0,_.createDraft(g,{data:{},page:0,respondent:a}).then(w=>{if(!N){if(N={id:w.id,token:w.token},Lt(g,N),w.existing)return _.getDraft(w.id,w.token).then(dt);dr()}}).catch(w=>{q(w)&&w.status!==void 0&&w.status>=400&&w.status<500||(Ae=!1)}))}function dr(){if(Ee||n.settings.responseLimit?.onRepeat!=="update"||!s||!i||!a?.hash||d!=="idle")return;Ee=!0;let g=s,_=kn(n.settings,l)??void 0;g.fetchOwnResponse(i,a,_).then(y=>{!y||d!=="idle"||J||le||(dt({data:y.data,page:0}),le&&(le=!1,te=!0,z()))}).catch(()=>{})}function ft(g=!1){if(x&&(clearTimeout(x),x=null),!Ve()||d!=="idle"||!L)return;let _=i,y=s;L=!1,R=R.then(async()=>{let w={data:l,page:Math.max(0,Math.min(u,n.pages.length-1))},A=N??rt(_);try{if(A)try{await y.saveDraft(A.id,A.token,w,g?{keepalive:!0}:void 0),N=A;return}catch(C){if(!Rt(C))throw C;Tt(_),N=null}let S=await y.createDraft(_,a?.hash?{...w,respondent:a}:w);N={id:S.id,token:S.token},Lt(_,N),S.existing&&(L=!0)}catch(S){q(S)&&S.status!==void 0&&S.status>=400&&S.status<500&&S.status!==429?X=!0:L=!0}})}function no(){!Ve()||d!=="idle"||(L=!0,x&&clearTimeout(x),x=setTimeout(()=>{x=null,ft()},xi))}function pr(){!Ve()||!J&&!N||(L=!0,ft())}function fr(){x&&(clearTimeout(x),x=null),L=!1,i&&Tt(i),N=null}function oo(g,_){!J&&s&&i&&(J=!0,s.startSession(i,n.pages.length).then(y=>B=y)),l={...l,[g]:_},t?.(l),m=void 0,g in c&&(c=Object.fromEntries(Object.entries(c).filter(([y])=>y!==g))),z(),no()}function io(g,_){_?v.add(g):v.delete(g),z()}function hr(g){if(g.length===0)return-1;let _=n.pages.length,y=Math.min(u,Math.max(_-1,0)),w=n.pages[y]?.id,A=w===void 0?-1:g.indexOf(w);if(A>=0)return A;let S=0;for(let C=0;C<g.length;C++){let re=n.pages.findIndex(ht=>ht.id===g[C]);re>=0&&re<=y&&(S=C)}return S}function so(){let g=n.pages.length,_=Math.min(u,Math.max(g-1,0));if(!e.skipValidation){let re=to(_);if(c=re,Object.keys(re).length>0){z();return}}let y=n.pages[_],w=nt(n,l),A=hr(w);if((y?jt(n,y.id,l):!0)||A<0||A+1>=w.length){mr();return}let C=n.pages.findIndex(re=>re.id===w[A+1]);u=C>=0?C:Math.min(_+1,g-1),B&&s&&s.reportProgress(B,{furthestPage:u}),z(),pr()}function ao(){c={};let g=nt(n,l),_=hr(g);if(_>0){let y=n.pages.findIndex(w=>w.id===g[_-1]);u=y>=0?y:Math.max(Math.min(u,n.pages.length-1)-1,0)}else if(g.length>0){let y=n.pages.findIndex(w=>w.id===g[0]);u=y>=0?y:0}z(),pr()}async function mr(){if(d==="submitting"||d==="submitted")return;let g=Pn(n,l);if(!g.ok){c=g.errors;let _=n.pages.findIndex(y=>Xe(n,y,l).some(w=>w.id in g.errors));_>=0&&(u=_),z();return}if(s&&e.resolveFormId){d="submitting",m=void 0,z();try{i=await e.resolveFormId()}catch(_){throw d="idle",m=zi(_),z(),_}}if(s&&i){let _=n.settings.responseLimit?.by==="browser"?_i(qt(n,i,g.data)):void 0,y=_??Se,w=n.settings.saveProgress?N??rt(i):null,A=e.challengeRequired?e.getChallengeToken?.():void 0;if(e.challengeRequired&&!A){d="idle",m=ki,z();return}d="submitting",m=void 0,z();let S;try{S=await s.submit(i,g.data,{hp:e.getHoneypot?.()??"",elapsedMs:Date.now()-ae,surface:e.surface??"headless",submissionKey:y,draft:w?{id:w.id,token:w.token}:void 0,respondent:a,challengeToken:A})}catch(C){if(d="idle",q(C)&&C.code==="challenge_failed"){m=$i,e.onChallengeFailed?.(),z();return}throw m=Un(C),z(),C}if(!S.ok){c=S.errors??{};let C=n.pages.findIndex(re=>Xe(n,re,l).some(ht=>ht.id in c));C>=0?u=C:m="We couldn't submit \u2014 please review your answers.",d="idle",z();return}xe=S.duplicate?"duplicate":S.updated?"updated":"created",B&&s.reportProgress(B,{completed:!0}),_&&wi(qt(n,i,g.data),S.responseId),fr(),d="submitted",z(),ce(S.responseId,g.data);return}if(e.skipValidation){d="submitted",z(),ce(void 0,g.data);return}s&&!i?yi():vi(),d="error",z()}return{getState:()=>V,subscribe(g){return E.add(g),()=>{E.delete(g)}},setValue:oo,setUploading:io,next:so,back:ao,submit:mr,setContext(g){if("formId"in g&&(i=g.formId),"client"in g&&(s=g.client),"respondent"in g&&(a=g.respondent),g.form&&g.form!==n){let _=ve(g.form);if(!_.ok)throw new Error(`Invalid form schema: ${_.error}`);n=_.schema}d==="idle"&&vn(n,i,l)&&(d="submitted",f=!0),pt(),z()},flushDraft(){ft(!0)},resetDraft(){if(d==="submitting")return;let g=N??(i?rt(i):null);if(fr(),g&&s&&s.deleteDraft(g.id,g.token).catch(()=>{}),l={...e.initialData??{}},typeof location<"u"&&location.search){let _=Object.fromEntries(new URLSearchParams(location.search));for(let[y,w]of Object.entries(gn(n,_)))l[y]===void 0&&(l[y]=w)}c={},u=0,m=void 0,le=!1,te=!1,z()},destroy(){x&&(clearTimeout(x),x=null),E.clear()}}}function Si(e){return ee(e)&&(e.kind==="select"||e.kind==="dropdown"||e.kind==="checkbox"||e.kind==="rating"||e.kind==="linear_scale")}function Bn(e){let t=e.filter(r=>ee(r)&&r.kind!=="hidden");return t.length!==1?!0:!Si(t[0])}function Vn(e,t,r){if(r.form.settings.submitMode!=="auto"||r.status!=="idle"||r.uploading||!(()=>{switch(e.kind){case"select":case"dropdown":return typeof t=="string"&&e.options.some(a=>a.id===t);case"checkbox":return t===!0;case"rating":case"linear_scale":return typeof t=="number";default:return!1}})()||t===r.data[e.id])return!1;let n={...r.data,[e.id]:t},i=r.form.pages.find(a=>a.blocks.some(l=>l.id===e.id));if(!i||!jt(r.form,i.id,n))return!1;let s=Sn(r.form,n).filter(a=>a.kind!=="hidden");return s.length!==1||s[0]?.id!==e.id?!1:Pn(r.form,n).ok}function or(e){return{id:e.id,theme:e.theme,schema:{version:1,title:e.title??"",description:e.description,pages:e.pages,settings:e.settings??{}},__filloCodeForm:!0}}function ir(e){return typeof e=="object"&&e!==null&&"__filloCodeForm"in e}var me=new Map,Ei=e=>new Promise(t=>setTimeout(t,e));function Ai(e){if(!q(e))return!0;let t=e.status??0;return t===0||t===408||t===429||t>=500}async function Ci(e,t){let r=800;for(let o=0;;o++)try{return await e.syncForm(t.id,t.schema,t.theme??null)}catch(n){if(!Ai(n)||o>=2)throw n;let i=q(n)?n.retryAfterSec:void 0;await Ei(Math.min(i?i*1e3:r*(1+Math.random()*.5),15e3)),r*=2}}function Fi(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)|0;return(t>>>0).toString(36)}function Hn(e,t){let r=o=>{if(Array.isArray(o))return o.map(r);if(o&&typeof o=="object"){let n=o;return Object.fromEntries(Object.keys(n).sort().map(i=>[i,r(n[i])]))}return o};return JSON.stringify(r(e))===JSON.stringify(r(t))}var Kt=e=>e==="published"?36e5:6e4,Ii=e=>!!(e.staged||e.resolvedSchema||e.syncError);function qn(e,t){return`fillo:sync:v3:${e.baseUrl}|${e.key}|${t}`}function Pi(e,t,r){try{let o=globalThis.localStorage?.getItem(qn(e,t));if(!o)return null;let n=JSON.parse(o);if(typeof n.formId!="string"||typeof n.slug!="string"||n.hash!==r||typeof n.ts!="number"||n.status!==void 0&&n.status!=="draft"&&n.status!=="published")return null;let i=Kt(n.status);return Date.now()-n.ts>i?null:n}catch{return null}}function Zi(e,t,r,o){if(!(o.staged||o.resolvedSchema||o.syncError)&&!o.challenge)try{globalThis.localStorage?.setItem(qn(e,t),JSON.stringify({formId:o.formId,slug:o.slug,status:o.status,hash:r,ts:Date.now()}))}catch{}}function sr(e,t,r){let o=JSON.stringify(t.schema)+JSON.stringify(t.theme??null),n=Fi(o),i=`${e.baseUrl}:${e.key}:${t.id}:${n}`,s=me.get(i);if(s&&!r?.bypassCache){if(s.expiresAt===null||s.expiresAt>Date.now())return s.promise;me.delete(i)}if(!r?.bypassCache){let c=Pi(e,t.id,n);if(c){let u=Promise.resolve({formId:c.formId,slug:c.slug,status:c.status});return me.set(i,{promise:u,expiresAt:c.ts+Kt(c.status)}),u}}let a=Ci(e,t),l={promise:a,expiresAt:null};return me.set(i,l),a.then(c=>{if(me.get(i)===l){if(Ii(c)){me.delete(i);return}l.expiresAt=Date.now()+Kt(c.status),Zi(e,t.id,n,c)}},()=>{me.get(i)===l&&me.delete(i)}),a}var Ni=class extends Error{constructor(e,t){super(`[fillo] ${t} \u2014 https://fillo.so/docs/troubleshooting#jsx-${e.toLowerCase()}`),this.code=e,this.name="FilloJsxError"}code},Mi=Symbol.for("fillo.block");var Li=["label","description","required","placeholder"],Z=(e,t,r,o={})=>({name:e,kind:t,props:[...Li,...r],...o}),_n=(e,t,r)=>({name:e,kind:t,props:r?["text"]:[],textChildren:r,content:!0}),Ot=["options","allowOther","shuffleOptions"],Ti=[Z("Text","short_text",["maxLength"]),Z("LongText","long_text",["maxLength"]),Z("Email","email",["maxLength"]),Z("Url","url",["maxLength"]),Z("Phone","phone",["defaultCountry"]),Z("Number","number",["min","max"]),Z("Select","select",Ot,{optionChildren:!0}),Z("MultiSelect","multi_select",Ot,{optionChildren:!0}),Z("Dropdown","dropdown",Ot,{optionChildren:!0}),Z("Checkbox","checkbox",["appearance"]),Z("Rating","rating",["max","insightsMetric"]),Z("Scale","linear_scale",["min","max","minLabel","maxLabel","insightsMetric"]),Z("Ranking","ranking",["options"],{optionChildren:!0}),Z("Matrix","matrix",["rows","columns"]),Z("Signature","signature",[]),Z("Date","date",[]),Z("FileUpload","file_upload",["maxFiles","maxFileSizeMb","accept"]),Z("Hidden","hidden",["paramName","defaultValue"]),Z("Custom","custom",["component","config"]),_n("Heading","heading",!0),_n("Paragraph","paragraph",!0),{name:"Divider",kind:"divider",props:[],content:!0}],Ri={name:"Page",kind:"__page",props:["title"]},Oi={name:"Option",kind:"__option",props:["label","icon"]};function Dt(e){let t=()=>{throw new Ni("RENDERED_INERT",`<Fillo.${e.name}> was rendered by React. Fillo fields are schema declarations, valid only inside <Fillo.Form> or Fillo.defineForm(). If this form lives in a server component, move it to a client module ("use client")`)};return t[Mi]=e,t}var ou=Object.fromEntries([...Ti.map(e=>[e.name,Dt(e)]),["Page",Dt(Ri)],["Option",Dt(Oi)]]);var Di=/\{\{\s*([\w-]+)\s*\}\}/g;function Ut(e,t,r){if(!e.includes("{{"))return e;let o=_e(r);return e.replace(Di,(n,i)=>{let s=o.find(c=>c.id===i),a=t[i];if(a==null||a==="")return"";let l=c=>s&&"options"in s?s.options.find(u=>u.id===c)?.label??c:c;return Array.isArray(a)?a.map(c=>l(String(c))).join(", "):typeof a=="string"?l(a):String(a)})}function Kn(e,t,r){let o=n=>n===void 0?n:Ut(n,t,r);switch(e.kind){case"heading":case"paragraph":return{...e,text:Ut(e.text,t,r)};case"divider":return e;default:return{...e,label:Ut(e.label,t,r),description:o(e.description)}}}var Ui="fillo-",ji=0,ct='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Bi(e,t){let r=`${Ui}${e}-${t}`;return{inputId:r,labelId:`${r}-label`,descriptionId:`${r}-desc`,errorId:`${r}-error`,name:r}}function p(e,t={}){let r=document.createElement(e);t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text);for(let[o,n]of Object.entries(t.attrs??{}))r.setAttribute(o,n);return r}function ze(e,t){let r=Xt(t);r&&(r.colorScheme&&e.setAttribute("data-fillo-color-scheme",r.colorScheme),r.primary&&e.style.setProperty("--fillo-primary",r.primary),r.background&&e.style.setProperty("--fillo-bg",r.background),r.text&&e.style.setProperty("--fillo-text",r.text),r.radius&&e.style.setProperty("--fillo-radius",r.radius),r.fontFamily&&e.style.setProperty("--fillo-font",r.fontFamily),(r.primary||r.background||r.text)&&e.setAttribute("data-fillo-has-color-theme",""))}function Xn(e){try{if(!e)return null;let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.toString()}catch{return null}}function Vi(e){let t=new URL(Xn(e)??"https://fillo.so");return t.searchParams.set("utm_source","form_badge"),t.toString()}function ar(e){return typeof e=="string"||typeof e=="number"?String(e):""}function F(e,t){for(let r of t)r&&e.appendChild(r);return e}var Wn="http://www.w3.org/2000/svg",Hi={thumbs_up:"M7 10v10M7 10l4.8-6.1a2 2 0 0 1 3.5 1.7L14.6 10h4.8a2.1 2.1 0 0 1 2 2.5l-1.1 5.4A3 3 0 0 1 17.4 20H7M3 10h4v10H3z",thumbs_down:"M7 14V4M7 14l4.8 6.1a2 2 0 0 0 3.5-1.7L14.6 14h4.8a2.1 2.1 0 0 0 2-2.5l-1.1-5.4A3 3 0 0 0 17.4 4H7M3 4h4v10H3z"};function Yn(e){if(!e)return null;let t=document.createElementNS(Wn,"svg");t.setAttribute("class","fillo-option-icon"),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true");let r=document.createElementNS(Wn,"path");return r.setAttribute("d",Hi[e]),t.appendChild(r),t}function j(e,t,r,o){r&&e.setAttribute("aria-invalid","true"),t.required&&e.setAttribute("aria-required","true");let n=[t.description?o.descriptionId:null,r?o.errorId:null].filter(Boolean).join(" ");n&&e.setAttribute("aria-describedby",n)}function Qn(e,t,r,o){e.addEventListener("keydown",n=>{let i=n.key==="ArrowRight"||n.key==="ArrowDown",s=n.key==="ArrowLeft"||n.key==="ArrowUp";if(!i&&!s)return;n.preventDefault();let a=r===null?-1:t.indexOf(r),l=a===-1?i?0:t.length-1:(a+(i?1:-1)+t.length)%t.length,c=t[l];c!==void 0&&(o(c),e.querySelectorAll('[role="radio"]')[l]?.focus())})}function W(e,t,r,o){let n=p("div",{className:`fillo-field fillo-field--${e.kind}${t?" fillo-field--error":""}`,attrs:{"data-fillo":"field","data-field":e.id,"data-kind":e.kind}});n.toggleAttribute("data-invalid",!!t),n.toggleAttribute("data-required",!!e.required);let i=p("label",{className:"fillo-label",text:e.label,attrs:{id:o.labelId,for:o.inputId,"data-fillo":"label"}});return e.required||i.appendChild(p("span",{className:"fillo-optional",text:" (optional)"})),n.appendChild(i),e.description&&n.appendChild(p("p",{className:"fillo-description",text:e.description,attrs:{id:o.descriptionId,"data-fillo":"fieldDescription"}})),n.appendChild(r),t&&n.appendChild(p("p",{className:"fillo-error",text:t,attrs:{role:"alert",id:o.errorId,"data-fillo":"error"}})),n}function Ue(e,t){let r=p("input",{className:"fillo-input",attrs:{id:t.ids.inputId,type:e,"data-fillo":"control"}});return r.value=ar(t.value),t.field.placeholder&&(r.placeholder=t.field.placeholder),"maxLength"in t.field&&t.field.maxLength!==void 0&&(r.maxLength=t.field.maxLength),t.field.kind==="number"&&(t.field.min!==void 0&&(r.min=String(t.field.min)),t.field.max!==void 0&&(r.max=String(t.field.max))),r.addEventListener("input",()=>t.setValue(r.value,{render:!1})),r.addEventListener("change",()=>t.setValue(r.value)),j(r,t.field,t.error,t.ids),W(t.field,t.error,r,t.ids)}function qi(){if(typeof navigator>"u")return;let t=(navigator.languages?.[0]||navigator.language||"").split("-")[1];return t&&/^[A-Za-z]{2}$/.test(t)?t.toUpperCase():void 0}function Ki(){if(!(typeof Intl>"u"))try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof e=="string"&&e?e:void 0}catch{return}}function Wi(e,t){if(t<=0)return e.setSelectionRange(0,0);let r=e.value,o=0,n=r.length;for(let i=0;i<r.length;i++)if(/\d/.test(r[i])&&++o===t){n=i+1;break}e.setSelectionRange(n,n)}function Gi(e){let t=e.field,r=at(ar(e.value)).country??it(t.defaultCountry)??En(Ki())??it(qi())??ie[0],o=p("div",{className:"fillo-phone"}),n=p("div",{className:"fillo-phone-country"}),i=p("button",{className:"fillo-phone-flag",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false"}}),s=p("span",{className:"fillo-phone-flag-emoji",attrs:{"aria-hidden":"true"}}),a=p("span",{className:"fillo-phone-dial"});F(i,[s,a,p("span",{className:"fillo-phone-caret",text:"\u25BE",attrs:{"aria-hidden":"true"}})]),F(n,[i]);let l=p("input",{className:"fillo-input fillo-phone-input",attrs:{id:e.ids.inputId,type:"tel",inputmode:"tel",autocomplete:"tel-national","data-fillo":"control"}});j(l,e.field,e.error,e.ids);let c=()=>{let x=se(ar(e.value));return x.startsWith(r.dialCode)?x.slice(r.dialCode.length):x},u=()=>{s.textContent=Gt(r.iso2),a.textContent=`+${r.dialCode}`,i.setAttribute("aria-label",`Country: ${r.name} (+${r.dialCode})`)},d=()=>{l.value=st(r,c()),l.placeholder=st(r,r.example)},f=x=>e.setValue(x?An(r,x):"",{render:!1});u(),d(),l.addEventListener("input",()=>{let x=l.value,R=l.selectionStart??x.length,L=se(x.slice(0,R)).length;if(x.trimStart().startsWith("+")){let X=at(x);X.country&&(r=X.country,u()),f(X.country?X.national:se(x))}else f(se(x));l.value=st(r,c()),Wi(l,L)});let h=e.registerOverlay,m=null,v=0,E=ie,ae=null,Se=null,B=`${e.ids.inputId}-countries`,J=()=>{if(!m)return;let x=Cn(n,m);m.classList.toggle("fillo-phone-popover--above",x==="above"),m.classList.toggle("fillo-phone-popover--below",x==="below")},le=()=>{ae?.();let x=()=>J();J(),window.addEventListener("resize",x),window.addEventListener("scroll",x,!0),ae=()=>{window.removeEventListener("resize",x),window.removeEventListener("scroll",x,!0)}},te=()=>{ae?.(),ae=null,m?.remove(),m=null,i.setAttribute("aria-expanded","false"),document.removeEventListener("mousedown",xe),Se?.(),Se=null},xe=x=>{n.contains(x.target)||te()},Ee=x=>{x&&(r=x,u(),f(c()),d(),te(),l.focus())},N=()=>{let x=p("div",{className:"fillo-phone-popover fillo-phone-popover--below"}),R=p("input",{className:"fillo-phone-search",attrs:{type:"text",role:"combobox","aria-expanded":"true","aria-controls":B,"aria-autocomplete":"list",placeholder:"Search country or code"}}),L=p("ul",{className:"fillo-phone-list",attrs:{role:"listbox",id:B,"aria-label":"Country"}}),X=()=>{if(L.replaceChildren(),E.length===0){L.appendChild(p("li",{className:"fillo-phone-empty",text:"No matches"})),J();return}E.forEach((I,V)=>{let z=p("li",{className:`fillo-phone-option${V===v?" fillo-phone-option--active":""}`,attrs:{id:`${B}-opt-${V}`,role:"option","aria-selected":String(I.iso2===r.iso2)}});F(z,[p("span",{className:"fillo-phone-flag-emoji",text:Gt(I.iso2),attrs:{"aria-hidden":"true"}}),p("span",{className:"fillo-phone-option-name",text:I.name}),p("span",{className:"fillo-phone-option-dial",text:`+${I.dialCode}`})]),z.addEventListener("mouseenter",()=>{v=V,R.setAttribute("aria-activedescendant",z.id),ge()}),z.addEventListener("mousedown",ce=>{ce.preventDefault(),Ee(I)}),L.appendChild(z)}),R.setAttribute("aria-activedescendant",`${B}-opt-${v}`),J()},ge=()=>{[...L.children].forEach((I,V)=>I.classList.toggle("fillo-phone-option--active",V===v)),document.getElementById(`${B}-opt-${v}`)?.scrollIntoView({block:"nearest"})},Ae=I=>{let V=I.trim().toLowerCase(),z=V.replace(/[^\d]/g,"");E=V?ie.filter(ce=>ce.name.toLowerCase().includes(V)||ce.iso2.toLowerCase()===V||z.length>0&&ce.dialCode.startsWith(z)):ie,v=0,X()};R.addEventListener("input",()=>Ae(R.value)),R.addEventListener("keydown",I=>{I.key==="ArrowDown"?(I.preventDefault(),v=Math.min(v+1,E.length-1),ge(),R.setAttribute("aria-activedescendant",`${B}-opt-${v}`)):I.key==="ArrowUp"?(I.preventDefault(),v=Math.max(v-1,0),ge(),R.setAttribute("aria-activedescendant",`${B}-opt-${v}`)):I.key==="Enter"?(I.preventDefault(),Ee(E[v])):I.key==="Escape"&&(I.preventDefault(),te(),i.focus())}),F(x,[R,L]),m=x,n.appendChild(x),i.setAttribute("aria-expanded","true"),E=ie,v=Math.max(0,ie.indexOf(r)),X(),le(),ge(),document.addEventListener("mousedown",xe),Se=h?.(te)??null,requestAnimationFrame(()=>R.focus())};return i.addEventListener("click",()=>m?te():N()),F(o,[n,l]),W(e.field,e.error,o,e.ids)}function Ji(e){let t=p("textarea",{className:"fillo-input fillo-textarea",attrs:{id:e.ids.inputId,rows:"4","data-fillo":"control"}});return t.value=typeof e.value=="string"?e.value:"",e.field.placeholder&&(t.placeholder=e.field.placeholder),"maxLength"in e.field&&e.field.maxLength!==void 0&&(t.maxLength=e.field.maxLength),t.addEventListener("input",()=>e.setValue(t.value,{render:!1})),t.addEventListener("change",()=>e.setValue(t.value)),j(t,e.field,e.error,e.ids),W(e.field,e.error,t,e.ids)}function Xi(e){let t=e.field,r=cr(t),o=typeof e.value=="string"?e.value:"",n=e.activeOtherFields,i=o!==""&&!t.options.some(l=>l.id===o),s=i||o===""&&n?.has(t.id)===!0,a=p("div",{className:"fillo-options",attrs:{role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"options"}});j(a,t,e.error,e.ids);for(let l of r){let c=p("label",{className:`fillo-option${l.icon?" fillo-option--has-icon":""}${o===l.id?" fillo-option--selected":""}`,attrs:{"data-option":l.id,"data-fillo":"option"}});c.toggleAttribute("data-selected",o===l.id);let u=p("input",{className:"fillo-option-input",attrs:{type:"radio",name:e.ids.name}});u.checked=o===l.id,u.addEventListener("change",()=>{n?.delete(t.id),e.setValue(l.id)}),F(c,[u,Yn(l.icon),p("span",{className:"fillo-option-label",text:l.label,attrs:{"data-fillo":"optionLabel"}})]),a.appendChild(c)}if(t.allowOther){let l=p("label",{className:`fillo-option fillo-option--other${s?" fillo-option--selected fillo-option--with-other":""}`,attrs:{"data-fillo":"option"}});l.toggleAttribute("data-selected",s);let c=p("input",{className:"fillo-option-input",attrs:{type:"radio",name:e.ids.name}});if(c.checked=s,c.addEventListener("change",()=>{n?.add(t.id),e.setValue("",{render:!0})}),F(l,[F(p("span",{className:"fillo-option-main"}),[c,p("span",{className:"fillo-option-label",text:"Other",attrs:{"data-fillo":"optionLabel"}})])]),s){let u=p("input",{className:"fillo-input fillo-other-input",attrs:{type:"text"}});u.value=i?o:"",u.placeholder="Your answer",u.addEventListener("input",()=>{n?.add(t.id),e.setValue(u.value,{render:!1})}),u.addEventListener("change",()=>{n?.add(t.id),e.setValue(u.value)}),l.appendChild(u),i||queueMicrotask(()=>u.focus())}a.appendChild(l)}return W(t,e.error,a,e.ids)}function Yi(e){let t=e.field,r=cr(t),o=Array.isArray(e.value)?e.value:[],n=new Set(t.options.map(u=>u.id)),i=o.find(u=>!n.has(u)),s=e.activeOtherFields,a=()=>{let u=e.getValue?.()??e.value;return Array.isArray(u)?u:[]},l=p("div",{className:"fillo-options",attrs:{role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"options"}});j(l,t,e.error,e.ids);let c=u=>e.setValue(u);for(let u of r){let d=p("label",{className:`fillo-option${u.icon?" fillo-option--has-icon":""}${o.includes(u.id)?" fillo-option--selected":""}`,attrs:{"data-option":u.id,"data-fillo":"option"}});d.toggleAttribute("data-selected",o.includes(u.id));let f=p("input",{className:"fillo-option-input",attrs:{type:"checkbox"}});f.checked=o.includes(u.id),f.addEventListener("change",()=>{let h=a();c(f.checked?[...h,u.id]:h.filter(m=>m!==u.id))}),F(d,[f,Yn(u.icon),p("span",{className:"fillo-option-label",text:u.label,attrs:{"data-fillo":"optionLabel"}})]),l.appendChild(d)}if(t.allowOther){let u=i!==void 0||s?.has(t.id)===!0,d=p("label",{className:`fillo-option fillo-option--other${u?" fillo-option--selected fillo-option--with-other":""}`,attrs:{"data-fillo":"option"}});d.toggleAttribute("data-selected",u);let f=p("input",{className:"fillo-option-input",attrs:{type:"checkbox"}});if(f.checked=u,f.addEventListener("change",()=>{let h=a().filter(m=>n.has(m));f.checked?(s?.add(t.id),c(h)):(s?.delete(t.id),c(h))}),F(d,[F(p("span",{className:"fillo-option-main"}),[f,p("span",{className:"fillo-option-label",text:"Other",attrs:{"data-fillo":"optionLabel"}})])]),u){let h=p("input",{className:"fillo-input fillo-other-input",attrs:{type:"text"}});h.value=i??"",h.placeholder="Your answer",h.addEventListener("input",()=>{s?.add(t.id);let m=a().filter(v=>n.has(v));e.setValue(h.value?[...m,h.value]:m,{render:!1})}),h.addEventListener("change",()=>{s?.add(t.id);let m=a().filter(v=>n.has(v));e.setValue(h.value?[...m,h.value]:m)}),d.appendChild(h),i===void 0&&queueMicrotask(()=>h.focus())}l.appendChild(d)}return W(t,e.error,l,e.ids)}function Qi(e){let t="__fillo_other__",r=new Set(e.options.map(o=>o.id));for(;r.has(t);)t+="_";return t}function es(e){let t=e.field,r=typeof e.value=="string"?e.value:"",o=Qi(t),n=e.activeOtherFields,i=r!==""&&!t.options.some(u=>u.id===r),s=i||r===""&&n?.has(t.id)===!0,a=p("div"),l=p("div",{className:"fillo-select-wrap"}),c=p("select",{className:"fillo-input fillo-select",attrs:{id:e.ids.inputId,"data-fillo":"control"}});c.appendChild(p("option",{text:t.placeholder??"Choose...",attrs:{value:""}}));for(let u of cr(t))c.appendChild(p("option",{text:u.label,attrs:{value:u.id}}));if(t.allowOther&&c.appendChild(p("option",{text:"Other...",attrs:{value:o}})),c.value=s?o:r,c.addEventListener("change",()=>{c.value===o?(n?.add(t.id),e.setValue("",{render:!0})):(n?.delete(t.id),e.setValue(c.value||null))}),j(c,t,e.error,e.ids),F(l,[c,p("span",{className:"fillo-select-icon",attrs:{"aria-hidden":"true"}})]),a.appendChild(l),s){let u=p("input",{className:"fillo-input fillo-other-input fillo-other-input--block",attrs:{type:"text"}});u.value=i?r:"",u.placeholder="Your answer",u.addEventListener("input",()=>{n?.add(t.id),e.setValue(u.value,{render:!1})}),u.addEventListener("change",()=>{n?.add(t.id),e.setValue(u.value)}),a.appendChild(u),i||queueMicrotask(()=>u.focus())}return W(t,e.error,a,e.ids)}function ts(e){if(e.field.kind==="checkbox"&&e.field.appearance==="toggle"){let i=p("div",{className:`fillo-field fillo-field--checkbox fillo-field--toggle${e.error?" fillo-field--error":""}`,attrs:{"data-fillo":"field","data-field":e.field.id,"data-kind":e.field.kind}});i.toggleAttribute("data-invalid",!!e.error),i.toggleAttribute("data-required",!!e.field.required);let s=p("label",{className:"fillo-toggle",attrs:{"data-fillo":"option"}});s.toggleAttribute("data-checked",e.value===!0);let a=p("span",{className:"fillo-option-label",text:e.field.label,attrs:{"data-fillo":"optionLabel"}});e.field.required||a.appendChild(p("span",{className:"fillo-optional",text:" (optional)"}));let l=p("span",{className:"fillo-toggle-copy"});l.appendChild(a);let c=p("input",{className:"fillo-toggle-input",attrs:{id:e.ids.inputId,type:"checkbox",role:"switch","aria-checked":String(e.value===!0)}});return c.checked=e.value===!0,c.addEventListener("change",()=>{c.setAttribute("aria-checked",String(c.checked)),e.setValue(c.checked)}),j(c,e.field,e.error,e.ids),F(s,[l,c,F(p("span",{className:"fillo-toggle-track",attrs:{"aria-hidden":"true"}}),[p("span",{className:"fillo-toggle-thumb"})])]),i.appendChild(s),e.field.description&&i.appendChild(p("p",{className:"fillo-description",text:e.field.description,attrs:{id:e.ids.descriptionId,"data-fillo":"fieldDescription"}})),e.error&&i.appendChild(p("p",{className:"fillo-error",text:e.error,attrs:{role:"alert",id:e.ids.errorId,"data-fillo":"error"}})),i}let t=p("div",{className:`fillo-field fillo-field--checkbox${e.error?" fillo-field--error":""}`,attrs:{"data-fillo":"field","data-field":e.field.id,"data-kind":e.field.kind}});t.toggleAttribute("data-invalid",!!e.error),t.toggleAttribute("data-required",!!e.field.required);let r=p("label",{className:"fillo-option",attrs:{"data-fillo":"option"}});r.toggleAttribute("data-checked",e.value===!0);let o=p("input",{className:"fillo-option-input",attrs:{id:e.ids.inputId,type:"checkbox"}});o.checked=e.value===!0,o.addEventListener("change",()=>e.setValue(o.checked)),j(o,e.field,e.error,e.ids);let n=p("span",{className:"fillo-option-label",text:e.field.label,attrs:{"data-fillo":"optionLabel"}});return e.field.required||n.appendChild(p("span",{className:"fillo-optional",text:" (optional)"})),F(r,[o,n]),t.appendChild(r),e.field.description&&t.appendChild(p("p",{className:"fillo-description",text:e.field.description,attrs:{id:e.ids.descriptionId,"data-fillo":"fieldDescription"}})),e.error&&t.appendChild(p("p",{className:"fillo-error",text:e.error,attrs:{role:"alert",id:e.ids.errorId,"data-fillo":"error"}})),t}function rs(e){if(e.field.kind!=="rating")return p("div");let t=typeof e.field.max=="number"?e.field.max:5,r=typeof e.value=="number"?e.value:0,o=Array.from({length:t},(a,l)=>l+1),n=r>0?r:null,i=n===null?0:Math.max(0,o.indexOf(n)),s=p("div",{className:"fillo-rating",attrs:{id:e.ids.inputId,role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});j(s,e.field,e.error,e.ids);for(let[a,l]of o.entries()){let c=p("button",{className:`fillo-star${l<=r?" fillo-star--active":""}`,text:"\u2605",attrs:{type:"button",role:"radio","aria-label":`${l} of ${t}`,"aria-checked":String(l===r),tabindex:String(a===i?0:-1),"data-fillo":"option"}});c.toggleAttribute("data-selected",l<=r),c.addEventListener("click",()=>e.setValue(l===r?null:l)),s.appendChild(c)}return Qn(s,o,n,a=>e.setValue(a)),W(e.field,e.error,s,e.ids)}function ns(e){if(e.field.kind!=="linear_scale")return p("div");let t=typeof e.field.min=="number"?e.field.min:1,r=typeof e.field.max=="number"?e.field.max:10,o=typeof e.value=="number"?e.value:null,n=Array.from({length:r-t+1},(d,f)=>t+f),i=o===null?0:Math.max(0,n.indexOf(o)),s=`${e.ids.inputId}-min`,a=`${e.ids.inputId}-max`,l=p("div"),c=p("div",{className:"fillo-scale",attrs:{id:e.ids.inputId,role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});j(c,e.field,e.error,e.ids);let u=[e.field.minLabel?s:null,e.field.maxLabel?a:null,c.getAttribute("aria-describedby")].filter(Boolean).join(" ");u&&c.setAttribute("aria-describedby",u);for(let[d,f]of n.entries()){let h=p("button",{className:`fillo-scale-step${e.value===f?" fillo-scale-step--active":""}`,text:String(f),attrs:{type:"button",role:"radio","aria-label":String(f),"aria-checked":String(e.value===f),tabindex:String(d===i?0:-1),"data-fillo":"option"}});h.toggleAttribute("data-selected",e.value===f),h.addEventListener("click",()=>e.setValue(e.value===f?null:f)),c.appendChild(h)}return Qn(c,n,o,d=>e.setValue(d)),l.appendChild(c),("minLabel"in e.field||"maxLabel"in e.field)&&F(l,[F(p("div",{className:"fillo-scale-labels"}),[p("span",{text:String(e.field.minLabel??""),attrs:{id:s}}),p("span",{text:String(e.field.maxLabel??""),attrs:{id:a}})])]),W(e.field,e.error,l,e.ids)}function os(e){let t=e.field;if(t.kind!=="ranking")return null;let r=Array.isArray(e.value)?e.value:[],o=[...r.filter(s=>t.options.some(a=>a.id===s)),...t.options.map(s=>s.id).filter(s=>!r.includes(s))],n=p("div",{attrs:{id:e.ids.inputId,role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});j(n,e.field,e.error,e.ids);let i=p("ol",{className:"fillo-ranking"});for(let[s,a]of o.entries()){let l=t.options.find(m=>m.id===a);if(!l)continue;let c=p("li",{className:"fillo-ranking-item"}),u=p("span",{className:"fillo-ranking-controls"}),d=m=>{let v=s+m;if(v<0||v>=o.length)return;let E=[...o];[E[s],E[v]]=[E[v],E[s]],e.setValue(E)},f=p("button",{className:"fillo-ranking-move",text:"Up",attrs:{type:"button","data-fillo-rank-opt":a,"data-fillo-rank-dir":"up"}});f.toggleAttribute("disabled",s===0),f.addEventListener("click",()=>d(-1));let h=p("button",{className:"fillo-ranking-move",text:"Down",attrs:{type:"button","data-fillo-rank-opt":a,"data-fillo-rank-dir":"down"}});h.toggleAttribute("disabled",s===o.length-1),h.addEventListener("click",()=>d(1)),F(u,[f,h]),F(c,[p("span",{className:"fillo-ranking-index",text:String(s+1)}),p("span",{className:"fillo-ranking-label",text:l.label}),u]),i.appendChild(c)}return n.appendChild(i),W(e.field,e.error,n,e.ids)}function is(e){let t=e.field;if(t.kind!=="matrix")return null;let r=e.value&&typeof e.value=="object"&&!Array.isArray(e.value)?e.value:{},o=p("table",{className:"fillo-matrix"}),n=document.createElement("thead"),i=document.createElement("tr");i.appendChild(document.createElement("th"));for(let l of t.columns)i.appendChild(p("th",{text:l.label,attrs:{scope:"col"}}));n.appendChild(i),o.appendChild(n);let s=document.createElement("tbody");for(let l of t.rows){let c=document.createElement("tr");c.appendChild(p("th",{text:l.label,attrs:{scope:"row"}}));for(let u of t.columns){let d=document.createElement("td"),f=p("input",{className:"fillo-option-input",attrs:{type:"radio",name:`${e.ids.name}-${l.id}`,"aria-label":`${l.label}: ${u.label}`}});f.checked=r[l.id]===u.id,f.addEventListener("change",()=>e.setValue({...r,[l.id]:u.id})),d.appendChild(f),c.appendChild(d)}s.appendChild(c)}o.appendChild(s);let a=p("div",{className:"fillo-matrix-wrap",attrs:{id:e.ids.inputId,role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});return j(a,e.field,e.error,e.ids),a.appendChild(o),W(e.field,e.error,a,e.ids)}function ss(e){let t=p("div",{className:"fillo-signature-field"}),r=p("div",{className:"fillo-signature",attrs:{"data-fillo":"control"}}),o=p("canvas",{className:"fillo-signature-canvas",attrs:{"aria-hidden":"true"}}),n=p("button",{className:"fillo-signature-clear",text:"Clear",attrs:{type:"button"}}),i=p("div",{className:"fillo-signature-hint",text:"Sign here",attrs:{"aria-hidden":"true"}});o.width=720,o.height=220;let s=o.getContext("2d"),a=!1,l=typeof e.value=="string"&&e.value.startsWith("data:image/");if(l&&s){let m=new Image;m.onload=()=>s.drawImage(m,0,0,o.width,o.height),m.src=String(e.value),i.style.display="none"}let c=p("input",{className:"fillo-input fillo-signature-type-input",attrs:{id:e.ids.inputId,type:"text",autocomplete:"name",placeholder:"Type your full name to sign"}});j(c,e.field,e.error,e.ids);let u=m=>{s&&(s.clearRect(0,0,o.width,o.height),m.trim()?(s.fillStyle=getComputedStyle(o).color||"#18181b",s.font=`italic ${Math.min(96,o.height*.45)}px "Segoe Script", "Brush Script MT", cursive`,s.textBaseline="middle",s.fillText(m,24,o.height/2),l=!0,i.style.display="none",e.setValue(o.toDataURL("image/png"),{render:!1})):(l=!1,i.style.display="",e.setValue(null,{render:!1})))};c.addEventListener("input",()=>u(c.value));let d=m=>{let v=o.getBoundingClientRect();return{x:(m.clientX-v.left)/v.width*o.width,y:(m.clientY-v.top)/v.height*o.height}};o.addEventListener("pointerdown",m=>{if(!s)return;a=!0,l=!0,i.style.display="none",c.value&&(c.value=""),o.setPointerCapture(m.pointerId);let v=d(m);s.beginPath(),s.moveTo(v.x,v.y)}),o.addEventListener("pointermove",m=>{if(!a||!s)return;let v=d(m);s.lineWidth=2.4,s.lineCap="round",s.strokeStyle=getComputedStyle(o).color||"#18181b",s.lineTo(v.x,v.y),s.stroke()});let f=()=>{a&&(a=!1,l&&e.setValue(o.toDataURL("image/png"),{render:!1}))};o.addEventListener("pointerup",f),o.addEventListener("pointercancel",f),n.addEventListener("click",()=>{s?.clearRect(0,0,o.width,o.height),l=!1,i.style.display="",c.value="",e.setValue(null,{render:!1})}),F(r,[o,i,n]);let h=p("div",{className:"fillo-signature-type"});return h.appendChild(c),F(t,[r,h]),W(e.field,e.error,t,e.ids)}function as(e){let t=e.field;if(t.kind!=="file_upload")return null;let r=p("input",{className:"fillo-input",attrs:{id:e.ids.inputId,type:"file","data-fillo":"control"}});(t.maxFiles??1)>1&&(r.multiple=!0),t.accept?.length&&(r.accept=t.accept.join(","));let o=e.uploadProgress?.get(t.id);r.disabled=o!==void 0,j(r,t,e.error,e.ids),r.addEventListener("change",()=>{let a=Array.from(r.files??[]);e.uploadFiles?.(t,a)});let n=p("div");if(n.appendChild(r),o!==void 0){let a=p("div",{className:"fillo-upload-progress",attrs:{role:"progressbar","aria-label":`Uploading ${t.label}`,"aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":String(Math.round(o*100))}});a.appendChild(p("div",{className:"fillo-upload-progress-fill"})),a.firstElementChild?.style.setProperty("width",`${Math.round(o*100)}%`),n.appendChild(a)}let i=Array.isArray(e.value)?e.value:[];for(let a of i)n.appendChild(p("p",{className:"fillo-description",text:`${a.name} (${Math.round(a.size/1024)} KB)`}));let s=e.uploadNotice;return s&&n.appendChild(p("p",{className:"fillo-upload-notice",text:s,attrs:{role:"status"}})),W(t,e.error,n,e.ids)}var Gn=new Map;function cr(e){if(!e.shuffleOptions)return e.options;let t=`${e.id}|${e.options.map(i=>i.id).join(",")}`,r=Gn.get(t);if(!r){r=e.options.map(i=>i.id);for(let i=r.length-1;i>0;i--){let s=Math.floor(Math.random()*(i+1));[r[i],r[s]]=[r[s],r[i]]}Gn.set(t,r)}let o=new Map(e.options.map(i=>[i.id,i])),n=r.flatMap(i=>o.get(i)??[]);return n.length===e.options.length?n:e.options}var ls={short_text:e=>Ue("text",e),email:e=>Ue("email",e),url:e=>Ue("url",e),phone:Gi,number:e=>Ue("number",e),date:e=>Ue("date",e),long_text:Ji,select:Xi,multi_select:Yi,dropdown:es,checkbox:ts,rating:rs,linear_scale:ns,ranking:os,matrix:is,signature:ss,file_upload:as};function cs(e){if(e.field.kind==="hidden"||e.field.kind==="custom")return null;let t=ls[e.field.kind];return t?t(e):null}var Be=class{constructor(t,r){this.target=t;this.options=r;this.element.className="fillo-dom-root",t.replaceChildren(this.element),this.resolve()}target;options;element=p("div");instanceId=`d${++ji}`;schema=null;theme;formId;closed=!1;fetchedPoweredBy=null;fetchedBrandLabel;fetchedBrandHref;phase="loading";engine=null;destroyed=!1;renderQueued=!1;hpValue="";liveSubmissionHandled=!1;activeOtherFields=new Set;uploadProgress=new Map;uploadControllers=new Map;uploadNotices=new Map;focusIntent=null;overlays=new Set;get status(){return this.phase==="ready"?this.engine?.getState().status??"idle":this.phase}get data(){return this.engine?.getState().data??this.options.initialData??{}}get form(){return this.schema}get mutableData(){return this.engine?.getState().data??this.options.initialData??{}}api(){let t=this.schema??{version:1,title:"",pages:[],settings:{}},r=this.engine?.getState(),o=r?.pageCount??t.pages.length;return{form:t,formId:this.formId,client:this.options.client,data:r?.data??this.mutableData,errors:r?.errors??{},status:this.status,pageIndex:r?.pageIndex??0,pageCount:o,page:r?.page??t.pages[0]??{id:"empty",blocks:[]},blocks:r?.blocks??[],isFirstPage:r?.isFirstPage??!0,isLastPage:r?.isLastPage??o<=1,setValue:(n,i,s)=>this.setValueInternal(n,i,s),next:()=>this.next(),back:()=>this.back(),submit:()=>this.submit()}}resolveFormIdFn;notLive=!1;fatalError=null;genericUnavailable=!1;syncErrorNotice=null;stagedNotice=!1;async resolve(){try{let t=ir(this.options.form)?this.options.form:null;if(t){let n=this.options.client;if(n?.key&&(this.resolveFormIdFn=async()=>{try{let i=await sr(n,t,{bypassCache:!0});if(i.status==="draft")throw new k("This form is no longer published. Submission was stopped before sending answers.",403,void 0,"form_not_published");let s=ve(i.resolvedSchema??t.schema);if(!s.ok)throw new k(`The canonical form schema was invalid: ${s.error}`,502,void 0,"invalid_sync_schema");if(this.schema&&!Hn(this.schema,s.schema))throw new k("The live form changed after this page loaded. Submission stopped before incompatible answers were sent. Reload to use the published schema.",409,void 0,"form_schema_changed");return i.syncError&&this.reportSyncNotice(new k(i.syncError.message,403,void 0,i.syncError.code)),i.formId}catch(i){let s=je(i);throw this.reportSubmitSyncFailure(s),s}}),n?.key||this.setSchema(t.schema,this.options.theme??t.theme,this.options.formId),n&&!n.key&&!this.options.formId){this.reportSyncFailure(new k('Code forms need createClient({ key: "pk_\u2026" }) to resolve the live form. Pass a publishable key or a published formId.',401,void 0,"sync_key_required"));return}if(!n?.key)return;we()?this.setSchema(t.schema,this.options.theme??t.theme,this.options.formId):(this.theme=this.options.theme??t.theme,this.render());try{let i=await sr(n,t);if(this.destroyed)return;if((i.staged||i.syncError)&&!i.resolvedSchema)throw new k("Sync did not return the live schema needed to render safely. Publish changes before deploy, and update @usefillo/* or your API.",409,void 0,"sync_snapshot_required");let s=we();if(this.notLive=i.status==="draft"&&!s,this.stagedNotice=!!i.staged,i.branding&&(this.fetchedPoweredBy=i.branding.poweredBy,this.fetchedBrandLabel=i.branding.label,this.fetchedBrandHref=i.branding.href),s&&i.resolvedSchema)this.formId=i.formId,this.engine?.setContext({formId:i.formId}),this.render();else{let a=i.resolvedSchema??t.schema,l=this.options.theme??(i.resolvedSchema?i.resolvedTheme??void 0:t.theme);this.applyCanonicalSchema(a,l,i.formId)}i.warning&&console.warn(`[fillo] ${i.warning}`),i.syncError&&this.reportSyncNotice(new k(i.syncError.message,403,void 0,i.syncError.code)),i.staged?console.info(`[fillo] "${t.id}" changes staged as a draft \u2014 rendering the live version until you publish them in your Fillo dashboard`):i.status==="draft"&&console.info(`[fillo] "${t.id}" is a draft \u2014 it renders here but won't accept responses until published`)}catch(i){if(this.destroyed)return;this.reportSyncFailure(je(i))}return}let r=this.options.form&&!ir(this.options.form)?this.options.form:null;if(r){this.setSchema(r,this.options.theme,this.options.formId);return}if(!this.options.formId)throw new k("Provide either `form`, or a `formId`.",0);this.options.client??=De(),this.render();let o=await this.options.client.getForm(this.options.formId);if(this.destroyed)return;this.closed=!!o.closed,this.fetchedPoweredBy=o.branding?.poweredBy??null,this.fetchedBrandLabel=o.branding?.label,this.fetchedBrandHref=o.branding?.href,this.setSchema(o.schema,this.options.theme??o.theme??void 0,o.id)}catch(t){if(this.destroyed)return;this.handleError(je(t))}}setSchema(t,r,o){if(this.destroyed)return;let n=ve(t);if(!n.ok)throw new k(`This form could not be rendered: ${n.error}`,422);let i=n.schema;this.schema=i,this.theme=r,this.formId=o,this.engine=jn({form:i,formId:o,client:this.options.client,initialData:this.options.initialData,onChange:this.options.onChange,onSubmitted:this.options.onSubmitted,getHoneypot:()=>this.element.querySelector('input[name="fillo_hp_field"]')?.value??this.hpValue,surface:"default",resolveFormId:this.resolveFormIdFn,respondent:this.options.respondent});let s=this.engine.getState().status,a=this.engine.getState().resumedDraft,l=this.engine.getState().editingPrevious;this.engine.subscribe(()=>{let c=this.engine?.getState();c&&(c.status!==s||c.resumedDraft!==a||c.editingPrevious!==l)&&(s=c.status,a=c.resumedDraft,l=c.editingPrevious,this.queueRender())}),this.configureDraftFlush(i),this.phase=this.closed?"closed":"ready",this.render()}applyCanonicalSchema(t,r,o){if(!this.engine){this.setSchema(t,r,o);return}let n=ve(t);if(!n.ok)throw new k(`This form could not be rendered: ${n.error}`,422);let i=n.schema;this.schema=i,this.theme=r,this.formId=o,this.engine.setContext({form:i,formId:o}),this.configureDraftFlush(i),this.phase=this.closed?"closed":"ready",this.render()}draftFlushWired=!1;flushDraftBound=()=>this.engine?.flushDraft();visibilityFlushBound=()=>{document.visibilityState==="hidden"&&this.engine?.flushDraft()};configureDraftFlush(t){this.teardownDraftFlush(),t.settings.saveProgress&&typeof window<"u"&&(window.addEventListener("pagehide",this.flushDraftBound),document.addEventListener("visibilitychange",this.visibilityFlushBound),this.draftFlushWired=!0)}teardownDraftFlush(){!this.draftFlushWired||typeof window>"u"||(window.removeEventListener("pagehide",this.flushDraftBound),document.removeEventListener("visibilitychange",this.visibilityFlushBound),this.draftFlushWired=!1)}flushDraft(){this.engine?.flushDraft()}resetDraft(){this.engine?.resetDraft(),this.queueRender()}setValue(t,r){this.setValueInternal(t,r)}setValueInternal(t,r,o={}){this.engine?.setValue(t,r),o.render!==!1&&this.queueRender()}next(){if(!this.engine)return;let t=this.engine.getState().pageIndex;this.engine.next(),this.focusIntent=this.engine.getState().pageIndex!==t?"page":"error",this.render()}back(){this.engine&&(this.engine.back(),this.focusIntent="page",this.render())}async submit(){if(!this.engine||this.phase!=="ready")return;let t=this.engine.submit();this.hasErrors()&&(this.focusIntent="error"),this.render();try{await t}catch(r){this.options.onError?.(je(r)),this.focusIntent="error",this.render();return}this.hasErrors()&&(this.focusIntent="error"),this.render()}hasErrors(){return Object.keys(this.engine?.getState().errors??{}).length>0}setTheme(t){this.options.theme=t,this.theme=t,this.render()}setClient(t){this.options.client=t,this.engine?.setContext({client:t}),this.render()}setRespondent(t){this.options.respondent=t,this.engine?.setContext({respondent:t})}async uploadFiles(t,r){if(!this.schema)return;if(this.uploadProgress.has(t.id)){this.uploadNotices.set(t.id,"Wait for the current upload to finish before adding more files."),this.queueRender();return}let o=t.maxFiles??1,n=o>1&&Array.isArray(this.mutableData[t.id])?[...this.mutableData[t.id]]:[],i=Math.max(0,o-n.length),s=r.slice(0,i),a=(t.maxFileSizeMb??500)*1024*1024,l=s.filter(f=>f.size<=a),c=r.length-s.length,u=s.length-l.length;if(c>0||u>0){let f=[];c>0&&f.push(`You can attach up to ${o} file${o===1?"":"s"}. ${c} ${c===1?"file was":"files were"} not added.`),u>0&&f.push(`${u} ${u===1?"file exceeds":"files exceed"} the ${t.maxFileSizeMb??500} MB limit.`),this.uploadNotices.set(t.id,f.join(" "))}else this.uploadNotices.delete(t.id);if(l.length===0){this.queueRender();return}let d=new AbortController;this.uploadControllers.set(t.id,d),this.uploadProgress.set(t.id,0),this.engine?.setUploading(t.id,!0),this.queueRender();try{let f=[];for(let[h,m]of l.entries())this.options.client&&this.formId?f.push(await this.options.client.uploadFile(this.formId,m,{fieldId:t.id,signal:d.signal,onProgress:v=>{this.uploadProgress.set(t.id,(h+v.fraction)/l.length),this.queueRender()}})):f.push({fileId:`local:${m.name}:${m.size}`,name:m.name,size:m.size,mime:m.type||"application/octet-stream"});if(this.destroyed)return;this.setValueInternal(t.id,[...n,...f])}catch(f){if(!this.destroyed&&!d.signal.aborted){let h=je(f);this.uploadNotices.set(t.id,h.message||"Upload failed \u2014 try again"),this.options.onError?.(h)}}finally{this.uploadControllers.get(t.id)===d&&this.uploadControllers.delete(t.id),this.uploadProgress.delete(t.id),this.engine?.setUploading(t.id,!1),this.queueRender()}}destroy(){this.destroyed=!0,this.teardownDraftFlush(),this.closeOverlays(),this.uploadControllers.forEach(t=>t.abort()),this.uploadControllers.clear(),this.uploadProgress.clear(),this.engine?.destroy(),this.engine=null,this.target.replaceChildren()}registerOverlay=t=>(this.overlays.add(t),()=>this.overlays.delete(t));closeOverlays(){if(this.overlays.size!==0){for(let t of Array.from(this.overlays))try{t()}catch{}this.overlays.clear()}}captureFocus(){if(typeof document>"u")return null;let t=document.activeElement;if(!t||!this.element.contains(t))return null;let r={};t.id&&(r.id=t.id);let o=t.getAttribute("data-fillo-rank-opt");o&&(r.rankOpt=o,r.rankDir=t.getAttribute("data-fillo-rank-dir")??void 0);let n=t.closest("[data-field]");if(n&&(r.fieldId=n.getAttribute("data-field")??void 0,r.controlIndex=Array.from(n.querySelectorAll(ct)).indexOf(t)),t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)try{r.selStart=t.selectionStart,r.selEnd=t.selectionEnd}catch{}return r.id||r.rankOpt||r.fieldId?r:null}restoreFocus(t){if(typeof document>"u")return;let r=null;if(t.rankOpt){let o=Array.from(this.element.querySelectorAll("[data-fillo-rank-opt]")).filter(n=>n.getAttribute("data-fillo-rank-opt")===t.rankOpt);r=o.find(n=>n.getAttribute("data-fillo-rank-dir")===t.rankDir&&!n.disabled)??o.find(n=>!n.disabled)??null}if(!r&&t.id&&(r=document.getElementById(t.id)),!r&&t.fieldId!=null&&t.controlIndex!=null&&t.controlIndex>=0){let o=Array.from(this.element.querySelectorAll("[data-field]")).find(n=>n.getAttribute("data-field")===t.fieldId);o&&(r=Array.from(o.querySelectorAll(ct))[t.controlIndex]??null)}if(!(!r||typeof r.focus!="function")&&(r.focus(),(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement)&&t.selStart!=null))try{r.setSelectionRange(t.selStart,t.selEnd??t.selStart)}catch{}}applyFocus(t,r){if(!(typeof document>"u")){if(t==="error"){let o=this.element.querySelector('[aria-invalid="true"]');(o?.matches(ct)?o:o?.querySelector(ct))?.focus?.();return}if(t==="page"){let n=this.element.querySelector(".fillo-page-title, .fillo-title")??this.element.querySelector(".fillo-blocks");n&&(n.hasAttribute("tabindex")||n.setAttribute("tabindex","-1"),n.focus?.());return}r&&this.restoreFocus(r)}}handleError(t){this.destroyed||(this.fatalError=t,this.phase="error",this.options.onError?.(t),this.render(t))}reportSyncFailure(t){if(this.destroyed)return;console.warn(`[fillo] form sync failed${t.code?` (${t.code})`:""}: ${t.message}`),this.syncErrorNotice=t;let r=we();if(!r||this.options.renderError){this.genericUnavailable=!r,this.handleError(t);return}this.options.onError?.(t),r&&this.render()}reportSyncNotice(t){this.destroyed||(console.warn(`[fillo] form sync needs attention${t.code?` (${t.code})`:""}: ${t.message}`),this.syncErrorNotice=t,this.options.onError?.(t),we()&&this.render())}reportSubmitSyncFailure(t){this.destroyed||(console.warn(`[fillo] form sync failed${t.code?` (${t.code})`:""}: ${t.message}`),this.syncErrorNotice=t)}queueRender(){this.renderQueued||this.destroyed||(this.renderQueued=!0,queueMicrotask(()=>{this.renderQueued=!1,this.render()}))}render(t){if(this.destroyed)return;let r=this.focusIntent;this.focusIntent=null;let o=r?null:this.captureFocus();if(this.closeOverlays(),this.element.replaceChildren(),this.phase==="loading"){let i=p("div",{className:`fillo-form fillo-form--loading ${this.options.className??""}`,attrs:{"aria-busy":"true","data-fillo":"root","data-state":"loading"}});ze(i,this.theme),F(i,[p("div",{className:"fillo-skeleton"}),p("div",{className:"fillo-skeleton"}),p("div",{className:"fillo-skeleton fillo-skeleton--short"})]),this.element.appendChild(i);return}let n=t??this.fatalError;if(this.phase==="error"&&n){let i=this.options.renderError?.(n)??p("div",{className:"fillo-form fillo-form--error",text:this.genericUnavailable?"This form is unavailable.":n.message});i.hasAttribute("data-fillo")||i.setAttribute("data-fillo","root"),i.hasAttribute("data-state")||i.setAttribute("data-state","error"),i.hasAttribute("role")||i.setAttribute("role","alert"),ze(i,this.theme),this.element.appendChild(i);return}if(this.phase==="closed"){let i=p("div",{className:`fillo-form fillo-form--closed ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":"closed"}});ze(i,this.theme),i.appendChild(p("p",{className:"fillo-closed",text:"This form is no longer accepting responses."})),this.element.appendChild(i);return}if(this.notLive){let i=p("div",{className:`fillo-form fillo-form--closed ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":"closed"}});ze(i,this.theme),i.appendChild(p("p",{className:"fillo-closed",text:"This form isn't live yet."})),this.element.appendChild(i);return}if(this.schema){if(this.engine?.getState().status==="submitted"){let i=this.api(),s=this.engine.getState(),a=this.options.renderSuccess?.(i)??ds(this.schema);if(a.setAttribute("data-fillo",a.getAttribute("data-fillo")??"root"),a.setAttribute("data-state",a.getAttribute("data-state")??"submitted"),a.setAttribute("role",a.getAttribute("role")??"status"),a.setAttribute("aria-live",a.getAttribute("aria-live")??"polite"),a.hasAttribute("tabindex")||a.setAttribute("tabindex","-1"),ze(a,this.theme),this.element.appendChild(a),this.brandingVisible()&&this.element.appendChild(Jn(this.fetchedBrandLabel,this.fetchedBrandHref)),!s.restoredSubmission&&!this.liveSubmissionHandled){this.liveSubmissionHandled=!0;let l=Xn(this.schema.settings.redirectUrl);l&&typeof window<"u"?window.location.assign(l):a.focus()}return}!this.options.client&&we()&&this.element.appendChild(ps()),this.syncErrorNotice&&we()&&this.element.appendChild(fs(this.syncErrorNotice)),this.stagedNotice&&we()&&this.element.appendChild(hs()),this.element.appendChild(this.renderForm()),this.brandingVisible()&&this.element.appendChild(Jn(this.fetchedBrandLabel,this.fetchedBrandHref)),this.applyFocus(r,o)}}brandingVisible(){return this.fetchedPoweredBy??!0}renderForm(){let t=this.api(),r=p("form",{className:`fillo-form ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":t.status,"data-page":String(t.pageIndex+1)}});r.toggleAttribute("data-last-page",t.isLastPage),ze(r,this.theme),r.noValidate=!0;let o=()=>{t.isLastPage?this.submit():this.next()};r.addEventListener("submit",d=>{d.preventDefault(),o()});let n=this.engine?.getState();if(n?.resumedDraft||n?.editingPrevious){let d=p("div",{className:"fillo-resume",attrs:{role:"status","data-fillo":"resume"}});d.appendChild(p("span",{className:"fillo-resume-text",text:n.editingPrevious?"You're updating your earlier response.":"Picked up where you left off."}));let f=p("button",{className:"fillo-resume-clear",text:"Start over",attrs:{type:"button"}});f.addEventListener("click",()=>this.resetDraft()),d.appendChild(f),r.appendChild(d)}if(t.pageCount>1&&this.schema?.settings.showProgress!==!1){let d=p("div",{className:"fillo-progress-track",attrs:{role:"progressbar","data-fillo":"progress","aria-label":t.form.title||"Form progress","aria-valuemin":"1","aria-valuemax":String(t.pageCount),"aria-valuenow":String(t.pageIndex+1)}});d.appendChild(p("div",{className:"fillo-progress-fill",attrs:{"data-fillo":"progressFill"}})),d.firstElementChild?.style.setProperty("--fillo-progress-value",`${(t.pageIndex+1)/t.pageCount*100}%`),r.appendChild(d)}if(t.pageIndex===0){let d=p("header",{className:"fillo-header",attrs:{"data-fillo":"header"}});t.form.title&&d.appendChild(p("h1",{className:"fillo-title",text:t.form.title,attrs:{"data-fillo":"title"}})),t.form.description&&d.appendChild(p("p",{className:"fillo-form-description",text:t.form.description,attrs:{"data-fillo":"description"}})),r.appendChild(d)}else t.page.title&&r.appendChild(p("h2",{className:"fillo-page-title",text:t.page.title,attrs:{"data-fillo":"pageTitle"}}));let i=p("div",{className:"fillo-blocks",attrs:{"data-fillo":"blocks"}});for(let d of t.blocks){let f=this.renderBlock(Kn(d,this.mutableData,t.form),t);f&&i.appendChild(f)}r.appendChild(i);let s=p("input",{className:"fillo-hp",attrs:{type:"text",name:"fillo_hp_field",tabindex:"-1",autocomplete:"off","aria-hidden":"true"}});s.style.position="absolute",s.style.left="-9999px",s.style.top="auto",s.style.width="1px",s.style.height="1px",s.style.opacity="0",s.style.overflow="hidden",s.style.pointerEvents="none",s.addEventListener("input",()=>{this.hpValue=s.value}),r.appendChild(s);let a=t.status==="error"?"This form can't submit right now. Please try again in a moment.":this.engine?.getState().submitError;a&&r.appendChild(p("p",{className:"fillo-submit-error",attrs:{role:"alert"},text:a}));let c=!(t.form.settings.submitMode==="auto")||!t.isLastPage||Bn($n(t.form,t.data));if(c||t.pageCount>1&&!t.isFirstPage){let d=p("footer",{className:"fillo-footer",attrs:{"data-fillo":"footer"}});if(t.pageCount>1&&!t.isFirstPage){let f=p("button",{className:"fillo-button fillo-button--ghost",text:"Back",attrs:{type:"button","data-fillo":"button"}});f.addEventListener("click",()=>this.back()),d.appendChild(f)}if(c){let f=p("button",{className:"fillo-button fillo-button--primary",text:t.status==="submitting"?"Submitting...":t.isLastPage?t.form.settings.submitLabel??"Submit":"Next",attrs:{type:"submit","data-fillo":"button"}});f.toggleAttribute("disabled",t.status==="submitting"||this.uploadProgress.size>0),f.addEventListener("click",h=>{h.preventDefault(),o()}),d.appendChild(f)}r.appendChild(d)}return r}renderBlock(t,r){if(!ee(t))return us(t);let o=(s,a)=>{if(this.setValueInternal(t.id,s,a),a?.render===!1)return;let l={form:r.form,data:r.data,status:r.status,isLastPage:r.isLastPage,uploading:this.uploadProgress.size>0};Vn(t,s,l)&&this.submit()},n={field:t,value:r.data[t.id],error:r.errors[t.id],ids:Bi(this.instanceId,t.id),api:r,setValue:o,uploadFiles:(s,a)=>this.uploadFiles(s,a),uploadProgress:this.uploadProgress,activeOtherFields:this.activeOtherFields,getValue:()=>this.engine?.getState().data[t.id],registerOverlay:this.registerOverlay,uploadNotice:this.uploadNotices.get(t.id)};return(t.kind==="custom"?this.options.customComponents?.[t.component]??this.options.components?.custom:this.options.components?.[t.kind]??cs)?.(n)??null}};function us(e){switch(e.kind){case"heading":return p("h3",{className:"fillo-heading",text:e.text});case"paragraph":return p("p",{className:"fillo-paragraph",text:e.text});case"divider":return p("hr",{className:"fillo-divider"})}return p("div")}function ds(e){let t=p("div",{className:"fillo-form fillo-form--success"}),r=p("div",{className:"fillo-success"});return F(r,[p("div",{className:"fillo-success-mark",text:"\u2713",attrs:{"aria-hidden":"true"}}),p("h2",{className:"fillo-success-title",text:e.settings.successTitle??"Thanks!"}),p("p",{className:"fillo-success-message",text:e.settings.successMessage??"Your response has been recorded."})]),t.appendChild(r),t}function Jn(e,t){return p("a",{className:"fillo-powered",text:e??"Powered by Fillo",attrs:{href:Vi(t),target:"_blank",rel:"noopener noreferrer"}})}function we(){return typeof process<"u"&&process.env?.NODE_ENV!=="production"}function ps(){return p("div",{className:"fillo-devwarning",text:"No Fillo client connected \u2014 this form is render-only and won't save responses. Pass a client to collect them in Fillo, or forward with webhooks. (Shown only in development.)",attrs:{role:"alert"}})}function fs(e){return p("div",{className:"fillo-devwarning",text:`Form sync needs attention${e.code?` (${e.code})`:""}: ${e.message} The safe form remains available for development.`,attrs:{role:"alert"}})}function hs(){return p("div",{className:"fillo-devwarning",text:"Code changes are staged. Local preview only. Publish in Fillo before deploying for respondents.",attrs:{role:"alert"}})}function je(e){return q(e)?e:new k(e instanceof Error?e.message:String(e),0)}function ut(e,t){let r=typeof e=="string"?document.querySelector(e):e;if(!r)throw new k(`Fillo mount target not found: ${String(e)}`,0);return new Be(r,{...t,initialData:t.initialData??{}})}function eo(e){let t=p("div");return ut(t,e),t}var ms=typeof HTMLElement<"u"?HTMLElement:class{},lr=class extends ms{instance=null;assignedForm;assignedClient;assignedTheme;assignedInitialData;mounted=!1;mountScheduled=!1;static get observedAttributes(){return["publishable-key","form-id"]}connectedCallback(){this.scheduleMount()}disconnectedCallback(){this.instance?.destroy(),this.instance=null,this.mounted=!1}attributeChangedCallback(){this.mounted&&this.isConnected&&this.scheduleMount()}set form(t){this.assignedForm=t,this.mounted&&this.scheduleMount()}get form(){return this.assignedForm}set client(t){this.assignedClient=t,this.mounted&&this.instance instanceof Be&&this.instance.setClient(t)}set theme(t){this.assignedTheme=t,this.mounted&&this.instance instanceof Be&&this.instance.setTheme(t)}set initialData(t){this.assignedInitialData=t,this.mounted&&this.scheduleMount()}scheduleMount(){this.mountScheduled||(this.mountScheduled=!0,queueMicrotask(()=>{this.mountScheduled=!1,this.isConnected&&this.mount()}))}mount(){this.instance?.destroy();let t=this.getAttribute("publishable-key")??void 0,r=this.getAttribute("form-id")??void 0,o=this.assignedClient??(r||t?De({key:t}):void 0);this.instance=ut(this,{form:this.assignedForm,client:o,formId:r,theme:this.assignedTheme,initialData:this.assignedInitialData,onChange:n=>this.dispatchEvent(new CustomEvent("fillo-change",{detail:{data:n}})),onSubmitted:(n,i)=>this.dispatchEvent(new CustomEvent("fillo-submit",{detail:{responseId:n,data:i}})),onError:n=>this.dispatchEvent(new CustomEvent("fillo-error",{detail:{error:n}}))}),this.mounted=!0}};function ur(e="fillo-form"){typeof customElements>"u"||customElements.get(e)||customElements.define(e,lr)}typeof customElements<"u"&&ur();return ho(gs);})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usefillo/dom",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Framework-agnostic DOM renderer and web component for embedding Fillo forms.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"access": "public"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
|
-
"@usefillo/core": "^0.
|
|
39
|
+
"@usefillo/core": "^0.9.0"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
42
|
"jsdom": "^25.0.1",
|