@usefillo/dom 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +37 -6
- package/dist/index.js +1107 -261
- package/dist/standalone.global.js +1 -1
- package/dist/styles.css +276 -59
- package/dist/styles.unlayered.css +276 -59
- package/package.json +4 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Fillo=(()=>{var gt=Object.defineProperty;var mo=Object.getOwnPropertyDescriptor;var go=Object.getOwnPropertyNames;var bo=Object.prototype.hasOwnProperty;var vo=(e,t)=>{for(var r in t)gt(e,r,{get:t[r],enumerable:!0})},yo=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of go(t))!bo.call(e,n)&&n!==r&>(e,n,{get:()=>t[n],enumerable:!(o=mo(t,n))||o.enumerable});return e};var wo=e=>yo(gt({},"__esModule",{value:!0}),e);var As={};vo(As,{FilloClient:()=>ct,FilloError:()=>x,createClient:()=>De,createFormElement:()=>so,defineForm:()=>ir,registerFilloElement:()=>fr,renderForm:()=>dt});var yr;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 f=0;f<u.length;f++){let d=u[f];d in a||(a[d]=c[d].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.")}};(yr=globalThis).__zod_globalConfig??(yr.__zod_globalConfig={});var bt=globalThis.__zod_globalConfig;function de(e){return e&&Object.assign(bt,e),bt}function _r(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 xr(e,t){return typeof t=="bigint"?t.toString():t}function kr(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 $r(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}var wr=Symbol("evaluating");function pe(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==wr)return o===void 0&&(o=wr,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}var wt="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ke(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _t(e){if(Ke(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Ke(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function xt(e){return _t(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var zr=new Set(["string","number","symbol"]);function Ce(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kt(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function M(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 Sr(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var _o={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 Er(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 fe(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function qe(e){return typeof e=="string"?e:e?.message}function he(e,t,r){let o=e.message?e.message:qe(e.inst?._zod.def?.error?.(e))??qe(t?.error?.(e))??qe(r.customError?.(e))??qe(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 Ar=(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,xr,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Cr=$("$ZodError",Ar),Ie=$("$ZodError",Ar,{Parent:Error});var ko=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=>he(l,i,de())));throw wt(a,n?.callee),a}return s.value},We=ko(Ie),$o=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=>he(l,i,de())));throw wt(a,n?.callee),a}return s.value},Ge=$o(Ie),zo=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??Cr)(i.issues.map(s=>he(s,n,de())))}:{success:!0,data:i.value}},Pe=zo(Ie),So=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=>he(s,n,de())))}:{success:!0,data:i.value}},Ne=So(Ie);var Fr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Eo="(?:(?:\\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])))",Ao=new RegExp(`^${Eo}$`);var Ir=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var zt=/^-?\d+(?:\.\d+)?$/;var ve=$("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Co={number:"number",bigint:"bigint",object:"date"};var Nr=$("$ZodCheckGreaterThan",(e,t)=>{ve.init(e,t);let r=Co[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 Zr=$("$ZodCheckMaxLength",(e,t)=>{var r;ve.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=$t(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Tr=$("$ZodCheckMinLength",(e,t)=>{var r;ve.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=$t(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}});var Lr=$("$ZodCheckStringFormat",(e,t)=>{var r,o;ve.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 Or={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=Or;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 f of a){if(f._zod.def.when){if(Er(s)||!f._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,h=f._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!==d&&(c||(c=Fe(s,d)))});else{if(s.issues.length===d)continue;c||(c=Fe(s,d))}}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)}}pe(e,"~standard",()=>({validate:n=>{try{let i=Pe(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Ne(e,n).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),St=$("$ZodString",(e,t)=>{K.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ir(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}}),Et=$("$ZodStringFormat",(e,t)=>{Lr.init(e,t),St.init(e,t)});var jr=$("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Fr),Et.init(e,t)});var Br=$("$ZodNumber",(e,t)=>{K.init(e,t),e._zod.pattern=e._zod.bag.pattern??zt,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 Vr=$("$ZodUnknown",(e,t)=>{K.init(e,t),e._zod.parse=r=>r});function Rr(e,t,r){e.issues.length&&t.issues.push(...fe(r,e.issues)),t.value[r]=e.value}var Hr=$("$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=>Rr(c,r,s))):Rr(l,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function Je(e,t,r,o,n,i){let s=r in o;if(e.issues.length){if(n&&i&&!s)return;t.issues.push(...fe(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 Io(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=Sr(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Po(e,t,r,o,n,i){let s=[],a=n.keySet,l=n.catchall._zod,c=l.def.type,u=l.optin==="optional",f=l.optout==="optional";for(let d in t){if(d==="__proto__"||a.has(d))continue;if(c==="never"){s.push(d);continue}let h=l.run({value:t[d],issues:[]},o);h instanceof Promise?e.push(h.then(m=>Je(m,r,d,t,u,f))):Je(h,r,d,t,u,f)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}var qr=$("$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=kr(()=>Io(t));pe(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 f of u.values)l[c].add(f)}}return l});let n=Ke,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=[],f=s.shape;for(let d of s.keys){let h=f[d],m=h._zod.optin==="optional",y=h._zod.optout==="optional",E=h._zod.run({value:c[d],issues:[]},l);E instanceof Promise?u.push(E.then(le=>Je(le,a,d,c,m,y))):Je(E,a,d,c,m,y)}return i?Po(u,c,a,l,o.value,e):u.length?Promise.all(u).then(()=>a):a}});var Kr=$("$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=>he(h,o,de())),input:c,path:[c],inst:e});continue}let f=u.value,d=t.valueType._zod.run({value:n[c],issues:[]},o);d instanceof Promise?i.push(d.then(h=>{h.issues.length&&r.issues.push(...fe(c,h.issues)),r.value[f]=h.value})):(d.issues.length&&r.issues.push(...fe(c,d.issues)),r.value[f]=d.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"&&zt.test(a)&&l.issues.length){let f=t.keyType._zod.run({value:Number(a),issues:[]},o);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");f.issues.length===0&&(l=f)}if(l.issues.length){t.mode==="loose"?r.value[a]=n[a]:r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(f=>he(f,o,de())),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(f=>{f.issues.length&&r.issues.push(...fe(a,f.issues)),r.value[l.value]=f.value})):(u.issues.length&&r.issues.push(...fe(a,u.issues)),r.value[l.value]=u.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Wr=$("$ZodEnum",(e,t)=>{K.init(e,t);let r=_r(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter(n=>zr.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}}),Gr=$("$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 Dr(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Jr=$("$ZodOptional",(e,t)=>{K.init(e,t),e._zod.optin="optional",e._zod.optout="optional",pe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),pe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${$r(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=>Dr(s,n)):Dr(i,n)}return r.value===void 0?r:t.innerType._zod.run(r,o)}});var Xr=$("$ZodDefault",(e,t)=>{K.init(e,t),e._zod.optin="optional",pe(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=>Ur(i,t)):Ur(n,t)}});function Ur(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function Yr(e,t){return new e({type:"string",...M(t)})}function Qr(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...M(t)})}function en(e,t){return new e({type:"number",checks:[],...M(t)})}function tn(e){return new e({type:"unknown"})}function At(e,t){return new Nr({check:"greater_than",...M(t),value:e,inclusive:!0})}function Ct(e){return At(0,e)}function R(e,t){return new Zr({check:"max_length",...M(t),maximum:e})}function $e(e,t){return new Tr({check:"min_length",...M(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)=>We(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Pe(e,r,o),e.parseAsync=async(r,o)=>Ge(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>Ne(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)=>kt(e,r,o),e.brand=()=>e,e.register=((r,o)=>(r.add(e,o),e)),e.apply=r=>r(e)}),nn=$("ZodMiniString",(e,t)=>{St.init(e,t),Y.init(e,t)});function D(e){return Yr(nn,e)}var Zo=$("ZodMiniStringFormat",(e,t)=>{Et.init(e,t),nn.init(e,t)}),To=$("ZodMiniEmail",(e,t)=>{jr.init(e,t),Zo.init(e,t)});function Xe(e){return Qr(To,e)}var Lo=$("ZodMiniNumber",(e,t)=>{Br.init(e,t),Y.init(e,t)});function on(e){return en(Lo,e)}var Mo=$("ZodMiniUnknown",(e,t)=>{Vr.init(e,t),Y.init(e,t)});function Ze(){return tn(Mo)}var Oo=$("ZodMiniArray",(e,t)=>{Hr.init(e,t),Y.init(e,t)});function me(e,t){return new Oo({type:"array",element:e,...M(t)})}var sn=$("ZodMiniObject",(e,t)=>{qr.init(e,t),Y.init(e,t),pe(e,"shape",()=>t.shape)});function Te(e,t){let r={type:"object",shape:e??{},...M(t)};return new sn(r)}function Ft(e,t){return new sn({type:"object",shape:e,catchall:Ze(),...M(t)})}var rn=$("ZodMiniRecord",(e,t)=>{Kr.init(e,t),Y.init(e,t)});function an(e,t,r){return!t||!t._zod?new rn({type:"record",keyType:D(),valueType:e,...M(t)}):new rn({type:"record",keyType:e,valueType:t,...M(r)})}var Ro=$("ZodMiniEnum",(e,t)=>{Wr.init(e,t),Y.init(e,t),e.options=Object.values(t.entries)});function ln(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new Ro({type:"enum",entries:r,...M(t)})}var Do=$("ZodMiniLiteral",(e,t)=>{Gr.init(e,t),Y.init(e,t)});function cn(e,t){return new Do({type:"literal",values:Array.isArray(e)?e:[e],...M(t)})}var Uo=$("ZodMiniOptional",(e,t)=>{Jr.init(e,t),Y.init(e,t)});function H(e){return new Uo({type:"optional",innerType:e})}var jo=$("ZodMiniDefault",(e,t)=>{Xr.init(e,t),Y.init(e,t)});function It(e,t){return new jo({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():xt(t)}})}var Ho=["heading","paragraph","divider"];function ee(e){return!Ho.includes(e.kind)}function Pt(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 un(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 dn(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 qo(e,t){let r=t(e.fieldId);switch(e.op){case"answered":return Pt(r);case"not_answered":return!Pt(r);case"eq":return Array.isArray(r)?r.some(o=>o===e.value):un(r,e.value);case"neq":return Pt(r)?Array.isArray(r)?!r.some(o=>o===e.value):!un(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=dn(r),n=dn(e.value);return o!==null&&n!==null&&(e.op==="gt"?o>n:o<n)}}}function $n(e,t){return e.length===0?!0:e.every(r=>qo(r,t))}function zn(e,t){return!e.visibleIf||e.visibleIf.length===0?!0:$n(e.visibleIf,t)}function Gt(e,t,r){return o=>t.has(o)&&!r.has(o)?void 0:e[o]}function it(e,t){let r=new Set(e.map(n=>n.id)),o=r;for(let n=0;n<=e.length;n++){let i=Gt(t,r,o),s=new Set;for(let a of e)zn(a,i)&&s.add(a.id);if(s.size===o.size&&[...s].every(a=>o.has(a)))return s;o=s}return o}function Ye(e,t,r){let o=_e(e),n=new Set(o.map(a=>a.id)),i=it(o,r),s=Gt(r,n,i);return t.blocks.filter(a=>ee(a)?i.has(a.id):zn(a,s))}function _e(e){return e.pages.flatMap(t=>t.blocks.filter(ee))}function Sn(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 En(e,t){let r=_e(e),o=it(r,t);return r.filter(n=>o.has(n.id))}function Ko(e,t){let r=_e(e),o=new Set(r.map(n=>n.id));return Gt(t,o,it(r,t))}function An(e,t,r){let n=e.pages.find(s=>s.id===t)?.next;if(!n||n.length===0)return{linear:!0};let i=Ko(e,r);for(let s of n)if($n(s.when,i))return s.to==="end"?{end:!0}:{to:s.to};return{linear:!0}}function ot(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=An(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 Wo(e,t){return new Set(ot(e,t))}function Bt(e,t,r){if("end"in An(e,t,r))return!0;let o=ot(e,r);return o.length>0&&o[o.length-1]===t}function Go(e,t){let r=Wo(e,t),o=it(_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 Cn(e,t){let r=Go(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")],Jo=new Map(ie.map(e=>[e.iso2,e])),Xo={"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 Jt(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 st(e){return e?Jo.get(e.toUpperCase()):void 0}function Fn(e){return st(e?Xo[e]:void 0)}function Yo(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 at(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 In(e,t){let r=se(t);return r?`+${e.dialCode}${r}`:""}function lt(e,t){let r=(e??"").trim(),o=r.startsWith("+"),n=se(r);if(!n)return{country:t,national:"",e164:""};if(o){let i=Yo(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 Qo(e){let{country:t,national:r,e164:o}=lt(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 ei=8;function Pn(e,t){if(!e||!t||typeof window>"u")return"below";let r=ei,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)),f=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(f)}px`),t.style.setProperty("--fillo-phone-popover-offset-x","0px");let d=Math.min(t.offsetWidth,f),h=0,m=i.left+d-(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 Nn="This field is required",ae={back:"Back",next:"Next",submit:"Submit",submitting:"Submitting\u2026",uploading:"Uploading\u2026",optional:" (optional)",other:"Other",otherPrompt:"Other \u2014 please specify",otherPlaceholder:"Your answer",choosePlaceholder:"Choose\u2026",successTitle:"Thanks!",successMessage:"Your response has been recorded.",closed:"This form is no longer accepting responses.",notLive:"This form isn't live yet.",notOpenTitle:"Not open just yet",notOpenBody:"This form is still being set up. Check back soon.",closedTitle:"Responses are closed",submitFailed:"This form can't submit right now. Please try again in a moment.",loadFailedNotFound:"Form not found \u2014 check the form id and that it's published.",loadFailedNetwork:"Couldn't reach the server \u2014 check your connection or CORS.",loadFailed:"This form could not be loaded.",renderFailed:"This form could not be rendered.",resumeNotice:"Picked up where you left off.",editNotice:"You're updating your earlier response.",resumeStartOver:"Start over",challengeUnavailable:"The verification check couldn't load. Refresh the page, or check that challenges.cloudflare.com isn't blocked."},Zn={required:Nn,resumeLinkExpired:"That saved-progress link expired or was already used \u2014 start again below.",alreadyAnswered:"You've already answered this form.",uploadRetry:"Retry",uploadsDisabled:"Uploads are disabled in preview",uploadsUnavailable:"Uploads are temporarily unavailable",uploadFailed:"Upload failed \u2014 try again",dropzoneTitle:e=>`Drop ${e?"files":"a file"} here or click to browse`,dropzoneHint:e=>`Up to ${e} MB per file`,fileTooLarge:e=>`Larger than ${e} MB limit`,filesUploading:e=>`Uploading ${e} ${e===1?"file":"files"}, please wait\u2026`,uploadsFailed:e=>`${e} ${e===1?"upload":"uploads"} failed.`,filesUploaded:e=>`${e} ${e===1?"file":"files"} uploaded.`};var ti=Te({fileId:D().check($e(1)),name:D(),size:on().check(Ct()),mime:D(),url:H(D())});function Tn(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 Ln(e,t){if(Tn(t))return e.required?Nn: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`:Xe().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"||!Qo(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=me(ti).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 Mn(e,t){let r=Cn(e,t),o={},n={};for(let i of r){let s=ri(i,t[i.id]),a=Ln(i,s);a?o[i.id]=a:Tn(s)||(n[i.id]=s)}return{ok:Object.keys(o).length===0,errors:o,data:n}}function ri(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 ni=["short_text","long_text","email","url","phone","number","select","multi_select","dropdown","checkbox","rating","linear_scale","ranking","matrix","signature","date","file_upload","hidden","custom"],oi=["heading","paragraph","divider"],ii=[...ni,...oi],Xt=D().check($e(1),R(128)),Nt=Ft({id:Xt,label:D().check(R(1e3)),icon:H(Ze())}),si=Ft({id:Xt,kind:ln(ii),label:H(D().check(R(2e3))),options:H(me(Nt).check(R(200))),rows:H(me(Nt).check(R(200))),columns:H(me(Nt).check(R(200)))}),ai=Te({id:Xt,title:H(D().check(R(500))),blocks:me(si).check(R(500)),next:H(Ze())}),li=Te({version:cn(1),title:It(H(D().check(R(2e3))),""),description:H(D().check(R(5e3))),pages:me(ai).check($e(1),R(50)),settings:It(H(an(D(),Ze())),{})}),ci=1,Vt=1,Ht="0.10.0";function G(e,t,r=""){return typeof e=="string"?e.trim().slice(0,t):r}function T(e,t){let r=G(e,t);return r===""?void 0:r}function oe(e){return typeof e=="boolean"?e:void 0}function Re(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function ye(e,t,r,o){let n=Re(e);return n===void 0?o:Math.max(t,Math.min(r,Math.round(n)))}function Qe(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 On(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 ui(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=On(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 Rn(e){return{id:G(e.id,128),visibleIf:On(e.visibleIf)}}function U(e,t){return{...Rn(e),kind:t,label:G(e.label,2e3,"Untitled field"),description:T(e.description,5e3),required:oe(e.required),placeholder:T(e.placeholder,500)}}function pn(e){let t=T(e,2e3);if(t)try{let r=new URL(t);return r.protocol==="http:"||r.protocol==="https:"?t:void 0}catch{return}}function di(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"?T(t.field,128):void 0;if(r==="field"&&!o)return;let n=T(t.scopeField,128),i=t.onRepeat==="update"&&r==="identify"?"update":"keep";return{by:r,...o?{field:o}:{},...n?{scopeField:n}:{},onRepeat:i}}function pi(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 fi(e){let t=e&&typeof e=="object"?e:{};return{submitMode:t.submitMode==="button"||t.submitMode==="auto"?t.submitMode:void 0,submitLabel:T(t.submitLabel,100),successTitle:T(t.successTitle,200),successMessage:T(t.successMessage,5e3),redirectUrl:pn(t.redirectUrl),showProgress:oe(t.showProgress),responseLimit:di(t.responseLimit),trust:pi(t.trust),notifyEmail:Xe().check(R(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:pn(t.resumeUrl),draftDigest:oe(t.draftDigest)}}function P(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function hi(e){if(!e||typeof e!="object")return null;let t=e,r=t.kind,o=Rn(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:Re(t.maxLength)===void 0?void 0:ye(t.maxLength,1,2e3,2e3)});case"phone":{let n=T(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:Re(t.maxLength)===void 0?void 0:ye(t.maxLength,1,2e4,2e4)});case"number":return P({...U(t,r),min:Re(t.min),max:Re(t.max)});case"select":case"multi_select":case"dropdown":{let n=Qe(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:T(t.minLabel,100),maxLabel:T(t.maxLabel,100),insightsMetric:s})}case"ranking":{let n=Qe(t.options);return n.length<2?null:P({...U(t,r),options:n})}case"matrix":{let n=Qe(t.rows),i=Qe(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:T(t.paramName,128),defaultValue:T(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=T(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 we(e){let t=li.safeParse(e);if(!t.success){let u=t.error.issues[0],f=u?.path.join(".");return{ok:!1,error:u?`${f?`${f}: `:""}${u.message}`:"Invalid schema"}}if(t.data.version>ci)return{ok:!1,error:`Unsupported schema version: ${t.data.version}`};let r=t.data.pages.map(u=>{let f=u.blocks.flatMap(d=>{let h=hi(d);return h?[h]:[]});return{id:G(u.id,128),title:T(u.title,500),blocks:f,next:u.next}}),o=new Set(r.map(u=>u.id)),n=new Set,i=r.map(u=>{for(let f of u.blocks)ee(f)&&n.add(f.id);return P({id:u.id,title:u.title,blocks:u.blocks,next:ui(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 f of u.blocks){if(a.has(f.id))return{ok:!1,error:`Duplicate block id: ${f.id}`};if(a.add(f.id),f.kind==="number"&&f.min!==void 0&&f.max!==void 0&&f.min>f.max)return{ok:!1,error:`Field ${f.id} has min greater than max`};if(f.kind==="select"||f.kind==="multi_select"||f.kind==="dropdown"||f.kind==="ranking"){let d=Zt(f.options);if(d)return{ok:!1,error:`Duplicate option id in field ${f.id}: ${d}`}}else if(f.kind==="matrix"){let d=Zt(f.rows);if(d)return{ok:!1,error:`Duplicate matrix row id in field ${f.id}: ${d}`};let h=Zt(f.columns);if(h)return{ok:!1,error:`Duplicate matrix column id in field ${f.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:Vt,title:G(t.data.title,2e3),pages:i,settings:fi(t.data.settings)},c=T(t.data.description,5e3);return c&&(l.description=c),{ok:!0,schema:l}}function Le(e,t){let r=T(e,t);if(r&&!(/[;{}<>]/.test(r)||/url\s*\(/i.test(r)))return r}function Yt(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 qt="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",mi=256-256%qt.length;function fn(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<mi&&(r+=qt[i%qt.length])}}return r}var Dn=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}},et="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Qt(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+=et[o>>2],t+=et[(o&3)<<4|n>>4],t+=r+1<e.length?et[(n&15)<<2|i>>6]:"=",t+=r+2<e.length?et[i&63]:"="}return t}var gi=e=>Qt(new Dn().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 hn(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 mn(e){let t=Number(e.headers.get("retry-after"));return Number.isFinite(t)&&t>0?t:void 0}var Me=3,Oe=3e4,bi=5*6e4,Q=10*6e4;function gn(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 Tt(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 tt(e){return e>=500||e===429||e===408}function bn(e){return typeof DOMException<"u"&&e instanceof DOMException&&e.name==="TimeoutError"?new x("Request timed out",0):e}function vi(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 yi(e){if(e.schemaVersion!==void 0&&e.schemaVersion!==Vt)throw new x(`This form uses schema version ${e.schemaVersion}; this SDK supports version ${Vt}. Update @usefillo/* to render it.`,426);if(e.minSdkVersion&&vi(Ht,e.minSdkVersion)<0)throw new x(`This form requires @usefillo/* ${e.minSdkVersion} or newer. Current SDK is ${Ht}.`,426)}function rt(e,t){return r=>t.onProgress?.({uploadedBytes:r,totalBytes:e,fraction:e===0?1:r/e})}async function wi(e){let t=globalThis.crypto?.subtle;if(t){let r=await t.digest("SHA-1",e);return Qt(new Uint8Array(r))}return gi(e)}var _i="https://fillo.so",vn={"X-Fillo-Client":`@usefillo/core@${Ht}`},ct=class{baseUrl;fetch;key;constructor(e={}){this.baseUrl=e.baseUrl?e.baseUrl.replace(/\/$/,""):e.sameOrigin?"":_i,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",...vn,...t?.headers}:t?.headers,o;try{o=await this.fetch(this.url(e),{...t,headers:r,signal:t?.signal??AbortSignal.timeout(Oe)})}catch(n){throw bn(n)}if(!o.ok){let{message:n,code:i}=await hn(o,`Request failed: ${o.status}`);throw new x(n,o.status,mn(o),i)}return await o.json()}async getForm(e){let t=await this.json(`/forms/${encodeURIComponent(e)}`);return yi(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=we(t);return o.ok?this.json("/forms/sync",{method:"POST",body:JSON.stringify({key:this.key,id:e,schema:o.schema,theme:Yt(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",...vn},body:JSON.stringify({data:t,meta:r}),signal:AbortSignal.timeout(Oe)})}catch(i){throw bn(i)}if(o.status===422)return{ok:!1,errors:(await o.json()).errors};if(!o.ok){let{message:i,code:s}=await hn(o,`Submit failed: ${o.status}`);throw new x(i,o.status,mn(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(Oe)});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(Oe)}).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 x("File does not match this upload session",400);i=c,i.token||=r.uploadToken}else{let c=fn(24),u=fn(32),f=()=>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)}),d=Date.now()+Q,h=250;for(;;)try{i=await f();break}catch(m){if(r.signal?.aborted||!Tt(m,!0))throw m;let y=d-Date.now();if(y<=0)throw m;await gn(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(c){if(r.signal?.aborted||!Tt(c))throw c;let u=Date.now()+Q,f=250;for(;;){let d=await this.getUploadSession(i.id,i.token,this.uploadSignal(r,Math.max(1,u-Date.now())));if(d.status==="complete"&&d.file)return d.file;if(d.status==="aborted")throw c;try{l=await a();break}catch(m){if(r.signal?.aborted||!Tt(m,!0))throw m}let h=u-Date.now();if(h<=0)throw c;await gn(Math.min(f,h),r.signal),f=Math.min(f*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=rt(t.size,r);o(0);let n={Authorization:`Bearer ${e.token}`};if(e.mode==="simple"){let d=new FormData;d.append("attributes",JSON.stringify({name:e.fileName,parent:{id:e.folderId}})),d.append("file",t,e.fileName);let h=await this.retry(r,async()=>{let y=await this.fetch(e.uploadUrl,{method:"POST",headers:n,body:d,signal:this.uploadSignal(r)});if(!y.ok&&tt(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 d=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(!d.ok&&tt(d.status))throw new x(`Box session failed: ${d.status}`,d.status);return d});if(!i.ok)throw new x(`Box session failed: ${i.status}`,i.status);let s=await i.json(),a=new Dn,l=[],c=0;for(;c<t.size;){r.signal?.throwIfAborted();let d=Math.min(c+s.part_size,t.size),h=new Uint8Array(await t.slice(c,d).arrayBuffer());a.update(h);let m=await wi(h),y=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}-${d-1}/${t.size}`},body:h,signal:this.uploadSignal(r)});if(!E.ok&&tt(E.status))throw new x(`Box part failed: ${E.status}`,E.status);return E});if(!y.ok)throw new x(`Box part failed: ${y.status}`,y.status);l.push((await y.json()).part),c=d,o(c)}let u=await this.retry(r,async()=>{let d=await this.fetch(s.session_endpoints.commit,{method:"POST",headers:{...n,"Content-Type":"application/json",Digest:`sha=${Qt(a.digest())}`},body:JSON.stringify({parts:l}),signal:this.uploadSignal(r)});if(!d.ok&&tt(d.status))throw new x(`Box commit failed: ${d.status}`,d.status);return d});if(!u.ok)throw new x(`Box commit failed: ${u.status}`,u.status);return{providerFileId:(await u.json()).entries?.[0]?.id}}uploadSignal(e,t=Oe){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>=Me))throw o;await new Promise(n=>setTimeout(n,500*2**r))}}async driveUploadLoop(e,t,r,o){let n=e.uploadedBytes,i=rt(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 f=await this.fetch(t,{method:"PUT",headers:{"Content-Range":`bytes ${n}-${l-1}/${r.size}`},body:c,signal:this.uploadSignal(o)});if(f.status===308){let d=f.headers.get("Range")??f.headers.get("range"),h=d?.match(/bytes=0-(\d+)/);h?n=Number(h[1])+1:d==null?n=0:n=(await this.getUploadSession(e.id,e.token,this.uploadSignal(o,Q))).uploadedBytes;break}if(f.ok){n=r.size;break}throw new x(`Drive chunk failed: ${f.status}`,f.status)}catch(f){if(o.signal?.aborted||(u+=1,u>=Me))throw f;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>=Me)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=rt(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 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 x("S3 part URL was unavailable",502);c=u.uploadUrl;let f=await this.fetch(c,{method:"PUT",body:a,signal:this.uploadSignal(r,bi)});if(!f.ok)throw new x(`S3 part upload failed: ${f.status}`,f.status);n=s,o(n);break}catch(u){if(r.signal?.aborted)throw u;let f=await this.getUploadSession(e.id,e.token,this.uploadSignal(r,Q));if(f.status==="aborted")throw new x("This upload session was cancelled",409);if(!Number.isSafeInteger(f.uploadedBytes)||f.uploadedBytes<n||f.uploadedBytes>t.size||f.uploadedBytes<t.size&&f.uploadedBytes%e.chunkSize!==0)throw new x("S3 upload session returned invalid progress",502);if(f.uploadedBytes>n){n=f.uploadedBytes,o(n);break}if(l+=1,l>=Me)throw u;await new Promise(d=>setTimeout(d,500*2**l))}}}}async s3PutUpload(e,t,r){let o=rt(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>=Me))throw i;await new Promise(s=>setTimeout(s,500*2**n))}}};function De(e={}){return new ct(e)}function Lt(e){let t=e.trim();if(!/^-?\d*\.?\d+$/.test(t))return null;let r=Number(t);return Number.isFinite(r)?r:null}function yn(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=Lt(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=Lt(n);i!==null&&Number.isInteger(i)&&i>=1&&i<=(o.max??5)&&(r[o.id]=i);break}case"linear_scale":{let i=Lt(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 xi={id:"empty",blocks:[]},wn=!1,_n=!1;function ki(){_n||(_n=!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 $i(){wn||(wn=!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 Un=new Map;function er(){try{return globalThis.localStorage??null}catch{return null}}function jn(e){return`fillo:submission:${e}`}function tr(){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 Bn(e,t,r,o){let n=er();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 Vn(e,t,r,o){e.set(r,o);let n=er();if(n)try{n.setItem(t,JSON.stringify(o))}catch{}}function rr(e){return Bn(Un,jn(e),e,t=>typeof t.key=="string")}function Hn(e,t){Vn(Un,jn(e),e,t)}function zi(e){let t=rr(e);if(t?.key)return t.key;let r={key:tr()};return Hn(e,r),r.key}function Si(e,t){let r=rr(e);Hn(e,{key:r?.key??tr(),submittedAt:new Date().toISOString(),responseId:t})}function Kt(e,t,r){let o=Sn(e.settings,r);return o===null?t:`${t}::${o}`}function xn(e,t,r){return e.settings.responseLimit?.by!=="browser"||!t?!1:!!rr(Kt(e,t,r))?.submittedAt}var nr=new Map;function or(e){return`fillo:draft:${e}`}function nt(e){return Bn(nr,or(e),e,t=>{let r=t;return typeof r.id=="string"&&typeof r.token=="string"})}function Mt(e,t){Vn(nr,or(e),e,t)}function Ot(e){nr.delete(e);let t=er();if(t)try{t.removeItem(or(e))}catch{}}function Rt(e){return q(e)&&(e.status===401||e.status===403||e.status===404)}var Ei=1500,Ai="Please complete the verification check, then submit.",Ci="That verification didn't go through. Please complete the check again and resubmit.";function qn(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 Fi(e,t){if(q(e)){let r=e.status??0;if(t&&r>0&&e.message)return e.code?`${e.message} (${e.code})`:e.message;if(r>0&&r<500&&r!==408&&r!==429)return"This form is unavailable."}return qn(e)}function Kn(e){let{onChange:t,onSubmitted:r}=e,o=we(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,f="idle",d=!1,h=!1;queueMicrotask(()=>{if(typeof location<"u"&&location.search){let w=Object.fromEntries(new URLSearchParams(location.search)),v=null;for(let[_,A]of Object.entries(yn(n,w)))l[_]===void 0&&(v=v??{...l},v[_]=A);v&&f==="idle"&&(l=v,z())}f==="idle"&&xn(n,i,l)&&(f="submitted",d=!0,z());let g=!1;if(n.settings.saveProgress&&i&&s&&typeof location<"u"&&location.hash.includes("fillo-draft=")){let w=/fillo-draft=([^&]+)/.exec(location.hash),v=w?.[1]?decodeURIComponent(w[1]):"",_=v.indexOf(".");if(_>0){g=!0;let A=v.slice(0,_),S=v.slice(_+1);s.getDraft(A,S,!0).then(F=>{Mt(i,{id:A,token:F.token??S});try{history.replaceState(null,"",location.pathname+location.search)}catch{}}).catch(F=>{Rt(F)&&(h=!0,z())}).finally(()=>ft())}}g||ft()});let m,y=new Set,E=new Set,le=Date.now(),Se=tr(),B=null,J=!1,ce=!1,te=!1,xe="created",Ee=!1,Z=null,k=null,O=Promise.resolve(),L=!1,X=!1,be=!1,Ae=!1;function I(){let g=n.pages.length,w=Math.min(u,Math.max(g-1,0)),v=n.pages[w]??xi;return{data:l,errors:c,status:f,pageIndex:w,pageCount:g,page:v,blocks:Ye(n,v,l),isFirstPage:w===0,isLastPage:Bt(n,v.id,l),uploading:y.size>0,submitError:m,restoredSubmission:d,resumedDraft:ce,editingPrevious:te,duplicateSubmission:xe==="duplicate",updatedSubmission:xe==="updated",resumeLinkFailed:h}}let V=I();function z(){V=I();for(let g of E)g()}function ue(g,w){try{r?.(g,w)}catch(v){console.error("[fillo] onSubmitted handler threw:",v)}}function ao(g){let w=n.pages[g];if(!w)return{};let v={};for(let _ of Ye(n,w,l)){if(!ee(_))continue;let A=Ln(_,l[_.id]);A&&(v[_.id]=A)}return v}function He(){return!!(n.settings.saveProgress&&s&&i&&!X)}function lo(){let g=new Set;for(let w of n.pages)for(let v of w.blocks)ee(v)&&g.add(v.id);return g}function pt(g){if(f!=="idle"||J)return;let w=lo(),v=null;for(let[S,F]of Object.entries(g.data??{}))l[S]===void 0&&w.has(S)&&(v=v??{...l},v[S]=F);let _=typeof g.page=="number"&&Number.isFinite(g.page)?Math.max(0,Math.min(Math.floor(g.page),n.pages.length-1)):0,A=_>0&&u===0;!v&&!A||(v&&(l=v),A&&(u=_),ce=!0,z())}function ft(){if(f!=="idle")return;if(!He()){hr();return}let g=i,w=s,v=Z??nt(g);if(v&&!be){be=!0,Z=v,w.getDraft(v.id,v.token).then(pt).catch(_=>{Rt(_)&&(Ot(g),Z=null)});return}!v&&!Ae&&a?.hash&&(Ae=!0,w.createDraft(g,{data:{},page:0,respondent:a}).then(_=>{if(!Z){if(Z={id:_.id,token:_.token},Mt(g,Z),_.existing)return w.getDraft(_.id,_.token).then(pt);hr()}}).catch(_=>{q(_)&&_.status!==void 0&&_.status>=400&&_.status<500||(Ae=!1)}))}function hr(){if(Ee||n.settings.responseLimit?.onRepeat!=="update"||!s||!i||!a?.hash||f!=="idle")return;Ee=!0;let g=s,w=Sn(n.settings,l)??void 0;g.fetchOwnResponse(i,a,w).then(v=>{!v||f!=="idle"||J||ce||(pt({data:v.data,page:0}),ce&&(ce=!1,te=!0,z()))}).catch(()=>{})}function ht(g=!1){if(k&&(clearTimeout(k),k=null),!He()||f!=="idle"||!L)return;let w=i,v=s;L=!1,O=O.then(async()=>{let _={data:l,page:Math.max(0,Math.min(u,n.pages.length-1))},A=Z??nt(w);try{if(A)try{await v.saveDraft(A.id,A.token,_,g?{keepalive:!0}:void 0),Z=A;return}catch(F){if(!Rt(F))throw F;Ot(w),Z=null}let S=await v.createDraft(w,a?.hash?{..._,respondent:a}:_);Z={id:S.id,token:S.token},Mt(w,Z),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 co(){!He()||f!=="idle"||(L=!0,k&&clearTimeout(k),k=setTimeout(()=>{k=null,ht()},Ei))}function mr(){!He()||!J&&!Z||(L=!0,ht())}function gr(){k&&(clearTimeout(k),k=null),L=!1,i&&Ot(i),Z=null}function uo(g,w){!J&&s&&i&&(J=!0,s.startSession(i,n.pages.length).then(v=>B=v)),l={...l,[g]:w},t?.(l),m=void 0,g in c&&(c=Object.fromEntries(Object.entries(c).filter(([v])=>v!==g))),z(),co()}function po(g,w){w?y.add(g):y.delete(g),z()}function br(g){if(g.length===0)return-1;let w=n.pages.length,v=Math.min(u,Math.max(w-1,0)),_=n.pages[v]?.id,A=_===void 0?-1:g.indexOf(_);if(A>=0)return A;let S=0;for(let F=0;F<g.length;F++){let re=n.pages.findIndex(mt=>mt.id===g[F]);re>=0&&re<=v&&(S=F)}return S}function fo(){let g=n.pages.length,w=Math.min(u,Math.max(g-1,0));if(!e.skipValidation){let re=ao(w);if(c=re,Object.keys(re).length>0){z();return}}let v=n.pages[w],_=ot(n,l),A=br(_);if((v?Bt(n,v.id,l):!0)||A<0||A+1>=_.length){vr();return}let F=n.pages.findIndex(re=>re.id===_[A+1]);u=F>=0?F:Math.min(w+1,g-1),B&&s&&s.reportProgress(B,{furthestPage:u}),z(),mr()}function ho(){c={};let g=ot(n,l),w=br(g);if(w>0){let v=n.pages.findIndex(_=>_.id===g[w-1]);u=v>=0?v:Math.max(Math.min(u,n.pages.length-1)-1,0)}else if(g.length>0){let v=n.pages.findIndex(_=>_.id===g[0]);u=v>=0?v:0}z(),mr()}async function vr(){if(f==="submitting"||f==="submitted")return;let g=Mn(n,l);if(!g.ok){c=g.errors;let w=n.pages.findIndex(v=>Ye(n,v,l).some(_=>_.id in g.errors));w>=0&&(u=w),z();return}if(s&&e.resolveFormId){f="submitting",m=void 0,z();try{i=await e.resolveFormId()}catch(w){throw f="idle",m=Fi(w,e.verboseResolutionErrors===!0),z(),w}}if(s&&i){let w=n.settings.responseLimit?.by==="browser"?zi(Kt(n,i,g.data)):void 0,v=w??Se,_=n.settings.saveProgress?Z??nt(i):null,A=e.challengeRequired?e.getChallengeToken?.():void 0;if(e.challengeRequired&&!A){f="idle",m=Ai,z();return}f="submitting",m=void 0,z();let S;try{S=await s.submit(i,g.data,{hp:e.getHoneypot?.()??"",elapsedMs:Date.now()-le,surface:e.surface??"headless",submissionKey:v,draft:_?{id:_.id,token:_.token}:void 0,respondent:a,challengeToken:A})}catch(F){if(f="idle",q(F)&&F.code==="challenge_failed"){m=Ci,e.onChallengeFailed?.(),z();return}throw m=qn(F),z(),F}if(!S.ok){c=S.errors??{};let F=n.pages.findIndex(re=>Ye(n,re,l).some(mt=>mt.id in c));F>=0?u=F:m="We couldn't submit \u2014 please review your answers.",f="idle",z();return}xe=S.duplicate?"duplicate":S.updated?"updated":"created",B&&s.reportProgress(B,{completed:!0}),w&&Si(Kt(n,i,g.data),S.responseId),gr(),f="submitted",z(),ue(S.responseId,g.data);return}if(e.skipValidation){f="submitted",z(),ue(void 0,g.data);return}s&&!i?ki():$i(),f="error",z()}return{getState:()=>V,subscribe(g){return E.add(g),()=>{E.delete(g)}},setValue:uo,setUploading:po,next:fo,back:ho,submit:vr,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 w=we(g.form);if(!w.ok)throw new Error(`Invalid form schema: ${w.error}`);n=w.schema}f==="idle"&&xn(n,i,l)&&(f="submitted",d=!0),ft(),z()},flushDraft(){ht(!0)},resetDraft(){if(f==="submitting")return;let g=Z??(i?nt(i):null);if(gr(),g&&s&&s.deleteDraft(g.id,g.token).catch(()=>{}),l={...e.initialData??{}},typeof location<"u"&&location.search){let w=Object.fromEntries(new URLSearchParams(location.search));for(let[v,_]of Object.entries(yn(n,w)))l[v]===void 0&&(l[v]=_)}c={},u=0,m=void 0,ce=!1,te=!1,z()},destroy(){k&&(clearTimeout(k),k=null),E.clear()}}}function Ii(e){return ee(e)&&(e.kind==="select"||e.kind==="dropdown"||e.kind==="checkbox"||e.kind==="rating"||e.kind==="linear_scale")}function Wn(e){let t=e.filter(r=>ee(r)&&r.kind!=="hidden");return t.length!==1?!0:!Ii(t[0])}function Gn(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||!Bt(r.form,i.id,n))return!1;let s=Cn(r.form,n).filter(a=>a.kind!=="hidden");return s.length!==1||s[0]?.id!==e.id?!1:Mn(r.form,n).ok}function ir(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 sr(e){return typeof e=="object"&&e!==null&&"__filloCodeForm"in e}var ge=new Map,Pi=e=>new Promise(t=>setTimeout(t,e));function Ni(e){if(!q(e))return!0;let t=e.status??0;return t===0||t===408||t===429||t>=500}async function Zi(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(!Ni(n)||o>=2)throw n;let i=q(n)?n.retryAfterSec:void 0;await Pi(Math.min(i?i*1e3:r*(1+Math.random()*.5),15e3)),r*=2}}function Ti(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 Jn(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 Wt=e=>e==="published"?36e5:6e4,Li=e=>!!(e.staged||e.resolvedSchema||e.syncError||e.accepting===!1);function Xn(e,t){return`fillo:sync:v3:${e.baseUrl}|${e.key}|${t}`}function Mi(e,t,r){try{let o=globalThis.localStorage?.getItem(Xn(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=Wt(n.status);return Date.now()-n.ts>i?null:n}catch{return null}}function Oi(e,t,r,o){if(!(o.staged||o.resolvedSchema||o.syncError||o.accepting===!1)&&!o.challenge)try{globalThis.localStorage?.setItem(Xn(e,t),JSON.stringify({formId:o.formId,slug:o.slug,status:o.status,hash:r,ts:Date.now()}))}catch{}}function ar(e,t,r){let o=JSON.stringify(t.schema)+JSON.stringify(t.theme??null),n=Ti(o),i=`${e.baseUrl}:${e.key}:${t.id}:${n}`,s=ge.get(i);if(s&&!r?.bypassCache){if(s.expiresAt===null||s.expiresAt>Date.now())return s.promise;ge.delete(i)}if(!r?.bypassCache){let c=Mi(e,t.id,n);if(c){let u=Promise.resolve({formId:c.formId,slug:c.slug,status:c.status});return ge.set(i,{promise:u,expiresAt:c.ts+Wt(c.status)}),u}}let a=Zi(e,t),l={promise:a,expiresAt:null};return ge.set(i,l),a.then(c=>{if(ge.get(i)===l){if(Li(c)){ge.delete(i);return}l.expiresAt=Date.now()+Wt(c.status),Oi(e,t.id,n,c)}},()=>{ge.get(i)===l&&ge.delete(i)}),a}var Ri=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},Di=Symbol.for("fillo.block");var Ui=["label","description","required","placeholder"],N=(e,t,r,o={})=>({name:e,kind:t,props:[...Ui,...r],...o}),kn=(e,t,r)=>({name:e,kind:t,props:r?["text"]:[],textChildren:r,content:!0}),Dt=["options","allowOther","shuffleOptions"],ji=[N("Text","short_text",["maxLength"]),N("LongText","long_text",["maxLength"]),N("Email","email",["maxLength"]),N("Url","url",["maxLength"]),N("Phone","phone",["defaultCountry"]),N("Number","number",["min","max"]),N("Select","select",Dt,{optionChildren:!0}),N("MultiSelect","multi_select",Dt,{optionChildren:!0}),N("Dropdown","dropdown",Dt,{optionChildren:!0}),N("Checkbox","checkbox",["appearance"]),N("Rating","rating",["max","insightsMetric"]),N("Scale","linear_scale",["min","max","minLabel","maxLabel","insightsMetric"]),N("Ranking","ranking",["options"],{optionChildren:!0}),N("Matrix","matrix",["rows","columns"]),N("Signature","signature",[]),N("Date","date",[]),N("FileUpload","file_upload",["maxFiles","maxFileSizeMb","accept"]),N("Hidden","hidden",["paramName","defaultValue"]),N("Custom","custom",["component","config"]),kn("Heading","heading",!0),kn("Paragraph","paragraph",!0),{name:"Divider",kind:"divider",props:[],content:!0}],Bi={name:"Page",kind:"__page",props:["title"]},Vi={name:"Option",kind:"__option",props:["label","icon"]};function Ut(e){let t=()=>{throw new Ri("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[Di]=e,t}var gu=Object.fromEntries([...ji.map(e=>[e.name,Ut(e)]),["Page",Ut(Bi)],["Option",Ut(Vi)]]);function Hi(e){let t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)||t==="::1"||t==="[::1]"||t==="0.0.0.0"}function lr(){return typeof process<"u"&&process.env?.NODE_ENV!=="production"}function Yn(){if(lr())return!0;if(typeof window>"u")return!1;let e=window.location?.hostname;return typeof e=="string"&&Hi(e)}var qi=/\{\{\s*([\w-]+)\s*\}\}/g;function jt(e,t,r){if(!e.includes("{{"))return e;let o=_e(r);return e.replace(qi,(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 Qn(e,t,r){let o=n=>n===void 0?n:jt(n,t,r);switch(e.kind){case"heading":case"paragraph":return{...e,text:jt(e.text,t,r)};case"divider":return e;default:return{...e,label:jt(e.label,t,r),description:o(e.description)}}}var Ki="fillo-",Wi=0,ut='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Gi(e,t){let r=`${Ki}${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=Yt(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 Be(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 Ji(e){let t=new URL(Be(e)??"https://fillo.so");return t.searchParams.set("utm_source","form_badge"),t.toString()}function ur(e){return typeof e=="string"||typeof e=="number"?String(e):""}function C(e,t){for(let r of t)r&&e.appendChild(r);return e}var eo="http://www.w3.org/2000/svg",Xi={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 oo(e){if(!e)return null;let t=document.createElementNS(eo,"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(eo,"path");return r.setAttribute("d",Xi[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 io(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=ur(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 Yi(){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 Qi(){if(!(typeof Intl>"u"))try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof e=="string"&&e?e:void 0}catch{return}}function es(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 ts(e){let t=e.field,r=lt(ur(e.value)).country??st(t.defaultCountry)??Fn(Qi())??st(Yi())??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"});C(i,[s,a,p("span",{className:"fillo-phone-caret",text:"\u25BE",attrs:{"aria-hidden":"true"}})]),C(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 k=se(ur(e.value));return k.startsWith(r.dialCode)?k.slice(r.dialCode.length):k},u=()=>{s.textContent=Jt(r.iso2),a.textContent=`+${r.dialCode}`,i.setAttribute("aria-label",`Country: ${r.name} (+${r.dialCode})`)},f=()=>{l.value=at(r,c()),l.placeholder=at(r,r.example)},d=k=>e.setValue(k?In(r,k):"",{render:!1});u(),f(),l.addEventListener("input",()=>{let k=l.value,O=l.selectionStart??k.length,L=se(k.slice(0,O)).length;if(k.trimStart().startsWith("+")){let X=lt(k);X.country&&(r=X.country,u()),d(X.country?X.national:se(k))}else d(se(k));l.value=at(r,c()),es(l,L)});let h=e.registerOverlay,m=null,y=0,E=ie,le=null,Se=null,B=`${e.ids.inputId}-countries`,J=()=>{if(!m)return;let k=Pn(n,m);m.classList.toggle("fillo-phone-popover--above",k==="above"),m.classList.toggle("fillo-phone-popover--below",k==="below")},ce=()=>{le?.();let k=()=>J();J(),window.addEventListener("resize",k),window.addEventListener("scroll",k,!0),le=()=>{window.removeEventListener("resize",k),window.removeEventListener("scroll",k,!0)}},te=()=>{le?.(),le=null,m?.remove(),m=null,i.setAttribute("aria-expanded","false"),document.removeEventListener("mousedown",xe),Se?.(),Se=null},xe=k=>{n.contains(k.target)||te()},Ee=k=>{k&&(r=k,u(),d(c()),f(),te(),l.focus())},Z=()=>{let k=p("div",{className:"fillo-phone-popover fillo-phone-popover--below"}),O=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===y?" fillo-phone-option--active":""}`,attrs:{id:`${B}-opt-${V}`,role:"option","aria-selected":String(I.iso2===r.iso2)}});C(z,[p("span",{className:"fillo-phone-flag-emoji",text:Jt(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",()=>{y=V,O.setAttribute("aria-activedescendant",z.id),be()}),z.addEventListener("mousedown",ue=>{ue.preventDefault(),Ee(I)}),L.appendChild(z)}),O.setAttribute("aria-activedescendant",`${B}-opt-${y}`),J()},be=()=>{[...L.children].forEach((I,V)=>I.classList.toggle("fillo-phone-option--active",V===y)),document.getElementById(`${B}-opt-${y}`)?.scrollIntoView({block:"nearest"})},Ae=I=>{let V=I.trim().toLowerCase(),z=V.replace(/[^\d]/g,"");E=V?ie.filter(ue=>ue.name.toLowerCase().includes(V)||ue.iso2.toLowerCase()===V||z.length>0&&ue.dialCode.startsWith(z)):ie,y=0,X()};O.addEventListener("input",()=>Ae(O.value)),O.addEventListener("keydown",I=>{I.key==="ArrowDown"?(I.preventDefault(),y=Math.min(y+1,E.length-1),be(),O.setAttribute("aria-activedescendant",`${B}-opt-${y}`)):I.key==="ArrowUp"?(I.preventDefault(),y=Math.max(y-1,0),be(),O.setAttribute("aria-activedescendant",`${B}-opt-${y}`)):I.key==="Enter"?(I.preventDefault(),Ee(E[y])):I.key==="Escape"&&(I.preventDefault(),te(),i.focus())}),C(k,[O,L]),m=k,n.appendChild(k),i.setAttribute("aria-expanded","true"),E=ie,y=Math.max(0,ie.indexOf(r)),X(),ce(),be(),document.addEventListener("mousedown",xe),Se=h?.(te)??null,requestAnimationFrame(()=>O.focus())};return i.addEventListener("click",()=>m?te():Z()),C(o,[n,l]),W(e.field,e.error,o,e.ids)}function rs(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 ns(e){let t=e.field,r=pr(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)}),C(c,[u,oo(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})}),C(l,[C(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 os(e){let t=e.field,r=pr(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 f=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"}});f.toggleAttribute("data-selected",o.includes(u.id));let d=p("input",{className:"fillo-option-input",attrs:{type:"checkbox"}});d.checked=o.includes(u.id),d.addEventListener("change",()=>{let h=a();c(d.checked?[...h,u.id]:h.filter(m=>m!==u.id))}),C(f,[d,oo(u.icon),p("span",{className:"fillo-option-label",text:u.label,attrs:{"data-fillo":"optionLabel"}})]),l.appendChild(f)}if(t.allowOther){let u=i!==void 0||s?.has(t.id)===!0,f=p("label",{className:`fillo-option fillo-option--other${u?" fillo-option--selected fillo-option--with-other":""}`,attrs:{"data-fillo":"option"}});f.toggleAttribute("data-selected",u);let d=p("input",{className:"fillo-option-input",attrs:{type:"checkbox"}});if(d.checked=u,d.addEventListener("change",()=>{let h=a().filter(m=>n.has(m));d.checked?(s?.add(t.id),c(h)):(s?.delete(t.id),c(h))}),C(f,[C(p("span",{className:"fillo-option-main"}),[d,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(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)}),f.appendChild(h),i===void 0&&queueMicrotask(()=>h.focus())}l.appendChild(f)}return W(t,e.error,l,e.ids)}function is(e){let t="__fillo_other__",r=new Set(e.options.map(o=>o.id));for(;r.has(t);)t+="_";return t}function ss(e){let t=e.field,r=typeof e.value=="string"?e.value:"",o=is(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 pr(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),C(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 as(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),C(s,[l,c,C(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)"})),C(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 ls(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 io(s,o,n,a=>e.setValue(a)),W(e.field,e.error,s,e.ids)}function cs(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},(f,d)=>t+d),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[f,d]of n.entries()){let h=p("button",{className:`fillo-scale-step${e.value===d?" fillo-scale-step--active":""}`,text:String(d),attrs:{type:"button",role:"radio","aria-label":String(d),"aria-checked":String(e.value===d),tabindex:String(f===i?0:-1),"data-fillo":"option"}});h.toggleAttribute("data-selected",e.value===d),h.addEventListener("click",()=>e.setValue(e.value===d?null:d)),c.appendChild(h)}return io(c,n,o,f=>e.setValue(f)),l.appendChild(c),("minLabel"in e.field||"maxLabel"in e.field)&&C(l,[C(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 us(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"}),f=m=>{let y=s+m;if(y<0||y>=o.length)return;let E=[...o];[E[s],E[y]]=[E[y],E[s]],e.setValue(E)},d=p("button",{className:"fillo-ranking-move",text:"Up",attrs:{type:"button","data-fillo-rank-opt":a,"data-fillo-rank-dir":"up"}});d.toggleAttribute("disabled",s===0),d.addEventListener("click",()=>f(-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",()=>f(1)),C(u,[d,h]),C(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 ds(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 f=document.createElement("td"),d=p("input",{className:"fillo-option-input",attrs:{type:"radio",name:`${e.ids.name}-${l.id}`,"aria-label":`${l.label}: ${u.label}`}});d.checked=r[l.id]===u.id,d.addEventListener("change",()=>e.setValue({...r,[l.id]:u.id})),f.appendChild(d),c.appendChild(f)}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 ps(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 f=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",c.value&&(c.value=""),o.setPointerCapture(m.pointerId);let y=f(m);s.beginPath(),s.moveTo(y.x,y.y)}),o.addEventListener("pointermove",m=>{if(!a||!s)return;let y=f(m);s.lineWidth=2.4,s.lineCap="round",s.strokeStyle=getComputedStyle(o).color||"#18181b",s.lineTo(y.x,y.y),s.stroke()});let d=()=>{a&&(a=!1,l&&e.setValue(o.toDataURL("image/png"),{render:!1}))};o.addEventListener("pointerup",d),o.addEventListener("pointercancel",d),n.addEventListener("click",()=>{s?.clearRect(0,0,o.width,o.height),l=!1,i.style.display="",c.value="",e.setValue(null,{render:!1})}),C(r,[o,i,n]);let h=p("div",{className:"fillo-signature-type"});return h.appendChild(c),C(t,[r,h]),W(e.field,e.error,t,e.ids)}function fs(e){let t=e.field;if(t.kind!=="file_upload")return null;let r=e,o=r.storageBlocked===!0,n=p("input",{className:"fillo-input",attrs:{id:e.ids.inputId,type:"file","data-fillo":"control"}});(t.maxFiles??1)>1&&(n.multiple=!0),t.accept?.length&&(n.accept=t.accept.join(","));let i=e.uploadProgress?.get(t.id);n.disabled=i!==void 0||o,j(n,t,e.error,e.ids),n.addEventListener("change",()=>{if(o)return;let c=Array.from(n.files??[]);e.uploadFiles?.(t,c)});let s=p("div");if(s.appendChild(n),o){let c=p("p",{className:"fillo-upload-notice",text:r.storageFixUrl?"Connect file storage to enable uploads":Zn.uploadsUnavailable,attrs:{role:"status"}});r.storageFixUrl&&(c.append(" \u2014 "),c.appendChild(p("a",{text:r.storageFixUrl,attrs:{href:r.storageFixUrl,target:"_blank",rel:"noopener noreferrer"}}))),s.appendChild(c)}if(i!==void 0){let c=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(i*100))}});c.appendChild(p("div",{className:"fillo-upload-progress-fill"})),c.firstElementChild?.style.setProperty("width",`${Math.round(i*100)}%`),s.appendChild(c)}let a=Array.isArray(e.value)?e.value:[];for(let c of a)s.appendChild(p("p",{className:"fillo-description",text:`${c.name} (${Math.round(c.size/1024)} KB)`}));let l=e.uploadNotice;return l&&s.appendChild(p("p",{className:"fillo-upload-notice",text:l,attrs:{role:"status"}})),W(t,e.error,s,e.ids)}var to=new Map;function pr(e){if(!e.shuffleOptions)return e.options;let t=`${e.id}|${e.options.map(i=>i.id).join(",")}`,r=to.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]]}to.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 hs={short_text:e=>Ue("text",e),email:e=>Ue("email",e),url:e=>Ue("url",e),phone:ts,number:e=>Ue("number",e),date:e=>Ue("date",e),long_text:rs,select:ns,multi_select:os,dropdown:ss,checkbox:as,rating:ls,linear_scale:cs,ranking:us,matrix:ds,signature:ps,file_upload:fs};function ms(e){if(e.field.kind==="hidden"||e.field.kind==="custom")return null;let t=hs[e.field.kind];return t?t(e):null}var Ve=class{constructor(t,r){this.target=t;this.options=r;this.element.className="fillo-dom-root",r.preview===!0&&$s(),t.replaceChildren(this.element),this.resolve()}target;options;element=p("div");instanceId=`d${++Wi}`;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;devChrome(){return this.options.preview===!0||vs()}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;notOpenVariant=null;fatalError=null;genericUnavailable=!1;syncErrorNotice=null;stagedNotice=!1;draftNotice=!1;syncWarningCode;syncWarningUrl;uploadsAvailable;resolutionFailureCode=null;async resolve(){try{let t=sr(this.options.form)?this.options.form:null;if(t){let n=this.options.client;if(n?.key&&(this.resolveFormIdFn=async()=>{try{let i=await ar(n,t,{bypassCache:!0});if(this.syncWarningCode=i.warningCode,this.syncWarningUrl=i.warningUrl,this.uploadsAvailable=i.uploadsAvailable,i.status==="draft")throw new x("This form is no longer published. Submission was stopped before sending answers.",403,void 0,"form_not_published");if(i.accepting===!1)throw new x("This form is no longer accepting responses. Submission was stopped before sending answers.",403,void 0,i.acceptingReason??"form_not_accepting");let s=we(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&&!Jn(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)),this.resolutionFailureCode=null,i.formId}catch(i){let s=je(i);throw this.resolutionFailureCode=s.code??"sync_failed",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;this.devChrome()?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 ar(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=this.devChrome();if(this.notOpenVariant=s?null:i.status==="draft"?"notOpen":i.accepting===!1?ro(i.acceptingReason):null,this.stagedNotice=!!i.staged,this.draftNotice=i.status==="draft",this.syncWarningCode=i.warningCode,this.syncWarningUrl=i.warningUrl,this.uploadsAvailable=i.uploadsAvailable,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 l=i.resolvedSchema??t.schema,c=this.options.theme??(i.resolvedSchema?i.resolvedTheme??void 0:t.theme);this.applyCanonicalSchema(l,c,i.formId)}i.warning&&console.warn(`[fillo] ${i.warning}`),i.syncError&&this.reportSyncNotice(new x(i.syncError.message,403,void 0,i.syncError.code));let a=i.warningUrl?` \u2014 connect storage to publish: ${i.warningUrl}`:"";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${a}`):i.status==="draft"&&console.info(`[fillo] "${t.id}" is a draft \u2014 it renders here but won't accept responses until published${a}`)}catch(i){if(this.destroyed)return;this.reportSyncFailure(je(i))}return}let r=this.options.form&&!sr(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??=De(),this.render();let o=await this.options.client.getForm(this.options.formId);if(this.destroyed)return;if(o.accepting===!1?this.notOpenVariant=ro(o.acceptingReason):this.closed=!!o.closed,this.uploadsAvailable=o.uploadsAvailable,this.fetchedPoweredBy=o.branding?.poweredBy??null,this.fetchedBrandLabel=o.branding?.label,this.fetchedBrandHref=o.branding?.href,o.accepting===!1&&this.options.renderError){let n=this.notOpenVariant==="closed"?"This form is no longer accepting responses.":"This form isn't accepting responses yet.";this.fatalError=new x(n,403,void 0,o.acceptingReason),this.phase="error",this.render(this.fatalError);return}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=we(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;let s=this.notOpenVariant!==null;this.engine=Kn({form:i,formId:s?void 0:o,client:s?void 0:this.options.client,initialData:this.options.initialData,onChange:s?void 0:this.options.onChange,onSubmitted:s?void 0:this.options.onSubmitted,getHoneypot:()=>this.element.querySelector('input[name="fillo_hp_field"]')?.value??this.hpValue,surface:"default",resolveFormId:s?void 0:this.resolveFormIdFn,verboseResolutionErrors:this.devChrome(),respondent:s?void 0:this.options.respondent});let a=this.engine.getState().status,l=this.engine.getState().resumedDraft,c=this.engine.getState().editingPrevious;this.engine.subscribe(()=>{let u=this.engine?.getState();u&&(u.status!==a||u.resumedDraft!==l||u.editingPrevious!==c)&&(a=u.status,l=u.resumedDraft,c=u.editingPrevious,this.queueRender())}),s||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=we(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.notOpenVariant===null&&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.notOpenVariant||(this.engine?.setValue(t,r),o.render!==!1&&this.queueRender())}next(){if(!this.engine||this.notOpenVariant)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.notOpenVariant||(this.engine.back(),this.focusIntent="page",this.render())}async submit(){if(!this.engine||this.phase!=="ready"||this.notOpenVariant)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||this.notOpenVariant)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(d=>d.size<=a),c=r.length-s.length,u=s.length-l.length;if(c>0||u>0){let d=[];c>0&&d.push(`You can attach up to ${o} file${o===1?"":"s"}. ${c} ${c===1?"file was":"files were"} not added.`),u>0&&d.push(`${u} ${u===1?"file exceeds":"files exceed"} the ${t.maxFileSizeMb??500} MB limit.`),this.uploadNotices.set(t.id,d.join(" "))}else this.uploadNotices.delete(t.id);if(l.length===0){this.queueRender();return}let f=new AbortController;this.uploadControllers.set(t.id,f),this.uploadProgress.set(t.id,0),this.engine?.setUploading(t.id,!0),this.queueRender();try{let d=[];for(let[h,m]of l.entries())this.options.client&&this.formId?d.push(await this.options.client.uploadFile(this.formId,m,{fieldId:t.id,signal:f.signal,onProgress:y=>{this.uploadProgress.set(t.id,(h+y.fraction)/l.length),this.queueRender()}})):d.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,...d])}catch(d){if(!this.destroyed&&!f.signal.aborted){let h=je(d);this.uploadNotices.set(t.id,h.message||"Upload failed \u2014 try again"),this.options.onError?.(h)}}finally{this.uploadControllers.get(t.id)===f&&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()}storageBlocked(){return this.uploadsAvailable===!1}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(ut)).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(ut))[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(ut)?o:o?.querySelector(ut))?.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=this.devChrome();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),this.devChrome()&&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),C(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.":Ss(n)});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.notOpenVariant&&this.schema){this.element.appendChild(this.renderNotOpen(this.notOpenVariant)),this.brandingVisible()&&this.element.appendChild(cr(this.fetchedBrandLabel,this.fetchedBrandHref));return}if(this.schema){if(this.engine?.getState().status==="submitted"){let i=this.api(),s=this.engine.getState(),a=this.options.renderSuccess?.(i)??bs(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(cr(this.fetchedBrandLabel,this.fetchedBrandHref)),!s.restoredSubmission&&!this.liveSubmissionHandled){this.liveSubmissionHandled=!0;let l=Be(this.schema.settings.redirectUrl);l&&typeof window<"u"?window.location.assign(l):a.focus()}return}this.devChrome()&&C(this.element,zs({preview:this.options.preview===!0,devNotices:this.options.devNotices,syncError:this.syncErrorNotice,staged:this.stagedNotice,draft:this.draftNotice,warningUrl:this.syncWarningUrl,noClient:!this.options.client})),this.element.appendChild(this.renderForm()),this.brandingVisible()&&this.element.appendChild(cr(this.fetchedBrandLabel,this.fetchedBrandHref)),this.applyFocus(r,o)}}brandingVisible(){return this.fetchedPoweredBy??!0}renderNotOpen(t){let r=p("div",{className:`fillo-form fillo-form--not-open ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":"closed"}});ze(r,this.theme);let o=p("div",{className:"fillo-not-open-preview",attrs:{"aria-hidden":"true",inert:""}});o.appendChild(this.renderForm());let n=p("div",{className:"fillo-not-open-card",attrs:{role:"status","data-fillo":"not-open-card"}});return n.appendChild(p("h2",{className:"fillo-not-open-title",text:t==="closed"?ae.closedTitle:ae.notOpenTitle})),n.appendChild(p("p",{className:"fillo-not-open-body",text:t==="closed"?ae.closed:ae.notOpenBody})),C(r,[o,n]),r}renderForm(){let t=this.api(),r=this.notOpenVariant!==null,o=p(r?"div":"form",{className:`fillo-form ${this.options.className??""}`,attrs:{"data-fillo":r?"preview-form":"root","data-state":r?"preview":t.status,"data-page":String(t.pageIndex+1)}});o.toggleAttribute("data-last-page",t.isLastPage),ze(o,this.theme);let n=()=>{t.isLastPage?this.submit():this.next()};if(!r){let d=o;d.noValidate=!0,d.addEventListener("submit",h=>{h.preventDefault(),n()})}let i=r?o.appendChild(p("fieldset",{className:"fillo-not-open-fields",attrs:{disabled:""}})):o,s=this.engine?.getState();if(s?.resumedDraft||s?.editingPrevious){let d=p("div",{className:"fillo-resume",attrs:{role:"status","data-fillo":"resume"}});d.appendChild(p("span",{className:"fillo-resume-text",text:s.editingPrevious?"You're updating your earlier response.":"Picked up where you left off."}));let h=p("button",{className:"fillo-resume-clear",text:"Start over",attrs:{type:"button"}});h.addEventListener("click",()=>this.resetDraft()),d.appendChild(h),i.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}%`),i.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"}})),i.appendChild(d)}else t.page.title&&i.appendChild(p("h2",{className:"fillo-page-title",text:t.page.title,attrs:{"data-fillo":"pageTitle"}}));let a=p("div",{className:"fillo-blocks",attrs:{"data-fillo":"blocks"}});for(let d of t.blocks){let h=this.renderBlock(Qn(d,this.mutableData,t.form),t);h&&a.appendChild(h)}if(i.appendChild(a),!r){let d=p("input",{className:"fillo-hp",attrs:{type:"text",name:"fillo_hp_field",tabindex:"-1",autocomplete:"off","aria-hidden":"true"}});d.style.position="absolute",d.style.left="-9999px",d.style.top="auto",d.style.width="1px",d.style.height="1px",d.style.opacity="0",d.style.overflow="hidden",d.style.pointerEvents="none",d.addEventListener("input",()=>{this.hpValue=d.value}),i.appendChild(d)}let l=t.status==="error"?"This form can't submit right now. Please try again in a moment.":this.engine?.getState().submitError;if(l){let d=p("p",{className:"fillo-submit-error",attrs:{role:"alert"},text:l}),h=this.devChrome()&&this.resolutionFailureCode==="form_not_published"&&this.syncWarningCode==="storage_required"?Be(this.syncWarningUrl):null;h&&(d.append(" Connect storage: "),d.appendChild(p("a",{text:h,attrs:{href:h,target:"_blank",rel:"noopener noreferrer"}}))),i.appendChild(d)}let u=!(t.form.settings.submitMode==="auto")||!t.isLastPage||Wn(En(t.form,t.data));if(u||t.pageCount>1&&!t.isFirstPage){let d=p("footer",{className:"fillo-footer",attrs:{"data-fillo":"footer"}});if(t.pageCount>1&&!t.isFirstPage){let h=p("button",{className:"fillo-button fillo-button--ghost",text:"Back",attrs:{type:"button","data-fillo":"button"}});h.addEventListener("click",()=>this.back()),d.appendChild(h)}if(u){let h=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"}});h.toggleAttribute("disabled",t.status==="submitting"||this.uploadProgress.size>0),h.addEventListener("click",m=>{m.preventDefault(),n()}),d.appendChild(h)}i.appendChild(d)}return o}renderBlock(t,r){if(!ee(t))return gs(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};Gn(t,s,l)&&this.submit()},n={field:t,value:r.data[t.id],error:r.errors[t.id],ids:Gi(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),storageBlocked:this.storageBlocked(),storageFixUrl:this.storageBlocked()&&this.devChrome()?Be(this.syncWarningUrl):null};return(t.kind==="custom"?this.options.customComponents?.[t.component]??this.options.components?.custom:this.options.components?.[t.kind]??ms)?.(n)??null}};function gs(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 bs(e){let t=p("div",{className:"fillo-form fillo-form--success"}),r=p("div",{className:"fillo-success"});return C(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 cr(e,t){return p("a",{className:"fillo-powered",text:e??"Powered by Fillo",attrs:{href:Ji(t),target:"_blank",rel:"noopener noreferrer"}})}function ro(e){return e==="expired"||e==="capped"||e==="storage_full"?"closed":"notOpen"}function vs(){return Yn()}function ys(){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 and preview.)",attrs:{role:"alert"}})}function ws(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 _s(){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 xs(e){let t=p("div",{className:"fillo-devwarning",attrs:{role:"alert"}});t.append("Draft form \u2014 it renders here, but it won't accept responses until you publish it in your Fillo dashboard. ");let r=Be(e);return r&&(t.append("Connect storage to publish: "),t.appendChild(p("a",{text:r,attrs:{href:r,target:"_blank",rel:"noopener noreferrer"}})),t.append(". ")),t.append("(Shown only in development and preview.)"),t}function ks(){return p("span",{className:"fillo-preview-badge",text:"Preview",attrs:{"data-fillo":"preview-badge"}})}var no=!1;function $s(){no||lr()||(no=!0,console.warn("[fillo] `preview` is enabled in a production build. Preview is cosmetic only \u2014 it shows developer chrome and never changes where submissions go or whether they are accepted \u2014 but remove it before respondents see this page."))}function zs(e){let t=[];return e.preview&&t.push(ks()),e.devNotices===!1||(e.syncError?t.push(ws(e.syncError)):e.staged?t.push(_s()):e.draft?t.push(xs(e.warningUrl)):e.noClient&&t.push(ys())),t}function Ss(e){return e.status===404?ae.loadFailedNotFound:e.status===0?ae.loadFailedNetwork:e.status===422?ae.renderFailed:ae.loadFailed}function je(e){return q(e)?e:new x(e instanceof Error?e.message:String(e),0)}function dt(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 Ve(r,{...t,initialData:t.initialData??{}})}function so(e){let t=p("div");return dt(t,e),t}var Es=typeof HTMLElement<"u"?HTMLElement:class{},dr=class extends Es{instance=null;assignedForm;assignedClient;assignedTheme;assignedInitialData;mounted=!1;mountScheduled=!1;static get observedAttributes(){return["publishable-key","form-id","data-preview"]}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 Ve&&this.instance.setClient(t)}set theme(t){this.assignedTheme=t,this.mounted&&this.instance instanceof Ve&&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()}))}previewAttrEnabled(){let t=this.getAttribute("data-preview");return t!==null&&t!=="false"&&t!=="0"}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=dt(this,{form:this.assignedForm,client:o,formId:r,theme:this.assignedTheme,initialData:this.assignedInitialData,preview:this.previewAttrEnabled()?!0:void 0,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 fr(e="fillo-form"){typeof customElements>"u"||customElements.get(e)||customElements.define(e,dr)}typeof customElements<"u"&&fr();return wo(As);})();
|
|
1
|
+
"use strict";var Fillo=(()=>{var Pt=Object.defineProperty;var Yi=Object.getOwnPropertyDescriptor;var Qi=Object.getOwnPropertyNames;var eo=Object.prototype.hasOwnProperty;var to=(e,t)=>{for(var n in t)Pt(e,n,{get:t[n],enumerable:!0})},no=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Qi(t))!eo.call(e,i)&&i!==n&&Pt(e,i,{get:()=>t[i],enumerable:!(r=Yi(t,i))||r.enumerable});return e};var ro=e=>no(Pt({},"__esModule",{value:!0}),e);var Fa={};to(Fa,{FilloClient:()=>Et,FilloError:()=>$,createClient:()=>Te,createFormElement:()=>qi,defineForm:()=>In,registerFilloElement:()=>On,renderForm:()=>It});var jn;function E(e,t,n){function r(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 f=0;f<c.length;f++){let h=c[f];h in a||(a[h]=u[h].bind(a))}}let i=n?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(a){var l;let u=n?.Parent?new o:this;r(u,a),(l=u._zod).deferred??(l.deferred=[]);for(let c of u._zod.deferred)c();return u}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var fe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(jn=globalThis).__zod_globalConfig??(jn.__zod_globalConfig={});var Lt=globalThis.__zod_globalConfig;function be(e){return e&&Object.assign(Lt,e),Lt}function Hn(e){let t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function qn(e,t){return typeof t=="bigint"?t.toString():t}function Wn(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Zt(e){return e==null}function Kn(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var Vn=Symbol("evaluating");function ve(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Vn)return r===void 0&&(r=Vn,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}var Ot="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rt(e){if(ft(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(ft(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Dt(e){return Rt(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var Gn=new Set(["string","number","symbol"]);function We(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ut(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function j(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 Jn(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var io={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 Ke(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Xn(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function ye(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function pt(e){return typeof e=="string"?e:e?.message}function we(e,t,n){let r=e.message?e.message:pt(e.inst?._zod.def?.error?.(e))??pt(t?.error?.(e))??pt(n.customError?.(e))??pt(n.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:s,...a}=e;return a.path??(a.path=[]),a.message=r,t?.reportInput&&(a.input=s),a}function Bt(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}var Yn=(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,qn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Qn=E("$ZodError",Yn),Ge=E("$ZodError",Yn,{Parent:Error});var so=e=>(t,n,r,i)=>{let o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new fe;if(s.issues.length){let a=new(i?.Err??e)(s.issues.map(l=>we(l,o,be())));throw Ot(a,i?.callee),a}return s.value},ht=so(Ge),ao=e=>async(t,n,r,i)=>{let o=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??e)(s.issues.map(l=>we(l,o,be())));throw Ot(a,i?.callee),a}return s.value},mt=ao(Ge),lo=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new fe;return o.issues.length?{success:!1,error:new(e??Qn)(o.issues.map(s=>we(s,i,be())))}:{success:!0,data:o.value}},Je=lo(Ge),uo=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(s=>we(s,i,be())))}:{success:!0,data:o.value}},Xe=uo(Ge);var er=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var co="(?:(?:\\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])))",po=new RegExp(`^${co}$`);var tr=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var jt=/^-?\d+(?:\.\d+)?$/;var Ce=E("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),fo={number:"number",bigint:"bigint",object:"date"};var rr=E("$ZodCheckGreaterThan",(e,t)=>{Ce.init(e,t);let n=fo[typeof t.value];e._zod.onattach.push(r=>{let i=r._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}});var ir=E("$ZodCheckMaxLength",(e,t)=>{var n;Ce.init(e,t),(n=e._zod.def).when??(n.when=r=>{let i=r.value;return!Zt(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{let i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let i=r.value;if(i.length<=t.maximum)return;let s=Bt(i);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),or=E("$ZodCheckMinLength",(e,t)=>{var n;Ce.init(e,t),(n=e._zod.def).when??(n.when=r=>{let i=r.value;return!Zt(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{let i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let i=r.value;if(i.length>=t.minimum)return;let s=Bt(i);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}});var sr=E("$ZodCheckStringFormat",(e,t)=>{var n,r;Ce.init(e,t),e._zod.onattach.push(i=>{let o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})});var lr={major:4,minor:4,patch:3};var ee=E("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=lr;let r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(let i of r)for(let o of i._zod.onattach)o(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(s,a,l)=>{let u=Ke(s),c;for(let f of a){if(f._zod.def.when){if(Xn(s)||!f._zod.def.when(s))continue}else if(u)continue;let h=s.issues.length,p=f._zod.check(s);if(p instanceof Promise&&l?.async===!1)throw new fe;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==h&&(u||(u=Ke(s,h)))});else{if(s.issues.length===h)continue;u||(u=Ke(s,h))}}return c?c.then(()=>s):s},o=(s,a,l)=>{if(Ke(s))return s.aborted=!0,s;let u=i(a,r,l);if(u instanceof Promise){if(l.async===!1)throw new fe;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=>o(c,s,a)):o(u,s,a)}let l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new fe;return l.then(u=>i(u,r,a))}return i(l,r,a)}}ve(e,"~standard",()=>({validate:i=>{try{let o=Je(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Xe(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Vt=E("$ZodString",(e,t)=>{ee.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??tr(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ht=E("$ZodStringFormat",(e,t)=>{sr.init(e,t),Vt.init(e,t)});var pr=E("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=er),Ht.init(e,t)});var fr=E("$ZodNumber",(e,t)=>{ee.init(e,t),e._zod.pattern=e._zod.bag.pattern??jt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;let o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}});var hr=E("$ZodUnknown",(e,t)=>{ee.init(e,t),e._zod.parse=n=>n});function ur(e,t,n){e.issues.length&&t.issues.push(...ye(n,e.issues)),t.value[n]=e.value}var mr=E("$ZodArray",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let a=i[s],l=t.element._zod.run({value:a,issues:[]},r);l instanceof Promise?o.push(l.then(u=>ur(u,n,s))):ur(l,n,s)}return o.length?Promise.all(o).then(()=>n):n}});function gt(e,t,n,r,i,o){let s=n in r;if(e.issues.length){if(i&&o&&!s)return;t.issues.push(...ye(n,e.issues))}if(!s&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?s&&(t.value[n]=void 0):t.value[n]=e.value}function mo(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=Jn(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function go(e,t,n,r,i,o){let s=[],a=i.keySet,l=i.catchall._zod,u=l.def.type,c=l.optin==="optional",f=l.optout==="optional";for(let h in t){if(h==="__proto__"||a.has(h))continue;if(u==="never"){s.push(h);continue}let p=l.run({value:t[h],issues:[]},r);p instanceof Promise?e.push(p.then(m=>gt(m,n,h,t,c,f))):gt(p,n,h,t,c,f)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}var gr=E("$ZodObject",(e,t)=>{if(ee.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 r=Wn(()=>mo(t));ve(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 f of c.values)l[u].add(f)}}return l});let i=ft,o=t.catchall,s;e._zod.parse=(a,l)=>{s??(s=r.value);let u=a.value;if(!i(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let c=[],f=s.shape;for(let h of s.keys){let p=f[h],m=p._zod.optin==="optional",g=p._zod.optout==="optional",b=p._zod.run({value:u[h],issues:[]},l);b instanceof Promise?c.push(b.then(z=>gt(z,a,h,u,m,g))):gt(b,a,h,u,m,g)}return o?go(c,u,a,l,r.value,e):c.length?Promise.all(c).then(()=>a):a}});var br=E("$ZodRecord",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Rt(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;let o=[],s=t.keyType._zod.values;if(s){n.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:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(p=>we(p,r,be())),input:u,path:[u],inst:e});continue}let f=c.value,h=t.valueType._zod.run({value:i[u],issues:[]},r);h instanceof Promise?o.push(h.then(p=>{p.issues.length&&n.issues.push(...ye(u,p.issues)),n.value[f]=p.value})):(h.issues.length&&n.issues.push(...ye(u,h.issues)),n.value[f]=h.value)}let l;for(let u in i)a.has(u)||(l=l??[],l.push(u));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:l})}else{n.value={};for(let a of Reflect.ownKeys(i)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&jt.test(a)&&l.issues.length){let f=t.keyType._zod.run({value:Number(a),issues:[]},r);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");f.issues.length===0&&(l=f)}if(l.issues.length){t.mode==="loose"?n.value[a]=i[a]:n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(f=>we(f,r,be())),input:a,path:[a],inst:e});continue}let c=t.valueType._zod.run({value:i[a],issues:[]},r);c instanceof Promise?o.push(c.then(f=>{f.issues.length&&n.issues.push(...ye(a,f.issues)),n.value[l.value]=f.value})):(c.issues.length&&n.issues.push(...ye(a,c.issues)),n.value[l.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}});var vr=E("$ZodEnum",(e,t)=>{ee.init(e,t);let n=Hn(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>Gn.has(typeof i)).map(i=>typeof i=="string"?We(i):i.toString()).join("|")})$`),e._zod.parse=(i,o)=>{let s=i.value;return r.has(s)||i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),yr=E("$ZodLiteral",(e,t)=>{if(ee.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?We(r):r?We(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,i)=>{let o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});function cr(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var wr=E("$ZodOptional",(e,t)=>{ee.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ve(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Kn(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let i=n.value,o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>cr(s,i)):cr(o,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}});var _r=E("$ZodDefault",(e,t)=>{ee.init(e,t),e._zod.optin="optional",ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>dr(o,t)):dr(i,t)}});function dr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function xr(e,t){return new e({type:"string",...j(t)})}function kr(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...j(t)})}function $r(e,t){return new e({type:"number",checks:[],...j(t)})}function zr(e){return new e({type:"unknown"})}function qt(e,t){return new rr({check:"greater_than",...j(t),value:e,inclusive:!0})}function Wt(e){return qt(0,e)}function q(e,t){return new ir({check:"max_length",...j(t),maximum:e})}function Oe(e,t){return new or({check:"min_length",...j(t),minimum:e})}var le=E("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");ee.init(e,t),e.def=t,e.type=t.type,e.parse=(n,r)=>ht(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Je(e,n,r),e.parseAsync=async(n,r)=>mt(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Xe(e,n,r),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]},{parent:!0}),e.with=e.check,e.clone=(n,r)=>Ut(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.apply=n=>n(e)}),Er=E("ZodMiniString",(e,t)=>{Vt.init(e,t),le.init(e,t)});function W(e){return xr(Er,e)}var vo=E("ZodMiniStringFormat",(e,t)=>{Ht.init(e,t),Er.init(e,t)}),yo=E("ZodMiniEmail",(e,t)=>{pr.init(e,t),vo.init(e,t)});function bt(e){return kr(yo,e)}var wo=E("ZodMiniNumber",(e,t)=>{fr.init(e,t),le.init(e,t)});function Ar(e){return $r(wo,e)}var _o=E("ZodMiniUnknown",(e,t)=>{hr.init(e,t),le.init(e,t)});function Ye(){return zr(_o)}var xo=E("ZodMiniArray",(e,t)=>{mr.init(e,t),le.init(e,t)});function _e(e,t){return new xo({type:"array",element:e,...j(t)})}var Cr=E("ZodMiniObject",(e,t)=>{gr.init(e,t),le.init(e,t),ve(e,"shape",()=>t.shape)});function Qe(e,t){let n={type:"object",shape:e??{},...j(t)};return new Cr(n)}function Kt(e,t){return new Cr({type:"object",shape:e,catchall:Ye(),...j(t)})}var Sr=E("ZodMiniRecord",(e,t)=>{br.init(e,t),le.init(e,t)});function Fr(e,t,n){return!t||!t._zod?new Sr({type:"record",keyType:W(),valueType:e,...j(t)}):new Sr({type:"record",keyType:e,valueType:t,...j(n)})}var ko=E("ZodMiniEnum",(e,t)=>{vr.init(e,t),le.init(e,t),e.options=Object.values(t.entries)});function Ir(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new ko({type:"enum",entries:n,...j(t)})}var $o=E("ZodMiniLiteral",(e,t)=>{yr.init(e,t),le.init(e,t)});function Nr(e,t){return new $o({type:"literal",values:Array.isArray(e)?e:[e],...j(t)})}var zo=E("ZodMiniOptional",(e,t)=>{wr.init(e,t),le.init(e,t)});function G(e){return new zo({type:"optional",innerType:e})}var So=E("ZodMiniDefault",(e,t)=>{_r.init(e,t),le.init(e,t)});function Gt(e,t){return new So({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Dt(t)}})}var Co=["heading","paragraph","divider"];function J(e){return!Co.includes(e.kind)}function vn(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 Gr(e,t){if(t==null||e.kind==="custom")return t;if(e.kind==="number"&&typeof t=="string"&&t.trim()!==""){let n=Number(t);return Number.isNaN(n)?t:n}if((e.kind==="rating"||e.kind==="linear_scale")&&typeof t=="string"){let n=Number(t);return Number.isNaN(n)?t:n}return typeof t=="string"?t.trim():t}function Fo(e,t){let n=Gr(e,t);return vn(n)?void 0:n}function Jr(e){return e===void 0||!Number.isFinite(e)?0:Math.max(0,Math.min(6,Math.round(e)))}function Xr(e,t){let n=10**t,r=Math.round(Math.abs(e)*n)/n;return e<0?-r:r}function Fe(e){return Number.isFinite(e)?e:null}function Ue(e,t){switch(e.op){case"value":return cn(t(e.fieldId));case"const":return Fe(e.value);case"add":case"mul":case"min":case"max":{if(e.args.length===0)return null;let n=[];for(let r of e.args){let i=Ue(r,t);if(i===null)return null;n.push(i)}return e.op==="add"?Fe(n.reduce((r,i)=>r+i,0)):e.op==="mul"?Fe(n.reduce((r,i)=>r*i,1)):e.op==="min"?Math.min(...n):Math.max(...n)}case"sub":case"div":{let n=Ue(e.left,t);if(n===null)return null;let r=Ue(e.right,t);return r===null?null:e.op==="sub"?Fe(n-r):r===0?null:Fe(n/r)}case"round":{let n=Ue(e.arg,t);return n===null?null:Fe(Xr(n,Jr(e.decimals)))}case"if":return Ue(yn(e.when,t)?e.then:e.else,t)}}function Io(e,t){let n=Ue(e.calc,t);return n===null||e.decimals===void 0?n:Fe(Xr(n,Jr(e.decimals)))}function Re(e,t){let n=ze(e);if(!n.some(a=>a.kind==="calculated"))return t;let r=t,i=pn(e,r);for(let a=0;a<=n.length;a++){let l={},u=!1;for(let[c,f]of Object.entries(r))i.has(c)?l[c]=f:u=!0;if(!u)break;r=l,i=pn(e,r)}let o=zt(n,r),s={};for(let[a,l]of Object.entries(t))o.calcIds.has(a)||(s[a]=l);for(let[a,l]of Object.entries(o.calc))i.has(a)&&(s[a]=l);return s}function Jt(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 Tr(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 cn(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 No(e,t){let n=t(e.fieldId);switch(e.op){case"answered":return Jt(n);case"not_answered":return!Jt(n);case"eq":return Array.isArray(n)?n.some(r=>r===e.value):Tr(n,e.value);case"neq":return Jt(n)?Array.isArray(n)?!n.some(r=>r===e.value):!Tr(n,e.value):!1;case"contains":return typeof n=="string"?n.toLowerCase().includes(String(e.value??"").toLowerCase()):Array.isArray(n)?n.some(r=>r===e.value):!1;case"gt":case"lt":{let r=cn(n),i=cn(e.value);return r!==null&&i!==null&&(e.op==="gt"?r>i:r<i)}}}function yn(e,t){return e.length===0?!0:e.every(n=>No(n,t))}function Yr(e,t){return!e.visibleIf||e.visibleIf.length===0?!0:yn(e.visibleIf,t)}function Xt(e,t,n,r,i,o){return s=>n.has(s)?r.has(s)?i.has(s)?o[s]:e[s]:void 0:t[s]}function zt(e,t){let n=new Set(e.map(l=>l.id)),r=e.filter(l=>l.kind==="calculated"),i=new Set(r.map(l=>l.id)),o={};for(let l of e){if(l.kind==="calculated")continue;let u=Fo(l,t[l.id]);u!==void 0&&(o[l.id]=u)}let s=n,a={};for(let l=0;l<=e.length;l++){let u=a;if(r.length>0){u={...a};let p=Xt(o,t,n,s,i,u);for(let m of r){let g=s.has(m.id)?Io(m,p):null;g===null?delete u[m.id]:u[m.id]=g}}let c=Xt(o,t,n,s,i,u),f=new Set;for(let p of e)Yr(p,c)&&f.add(p.id);let h=f.size===s.size&&[...f].every(p=>s.has(p))&&To(a,u);if(s=f,a=u,h)break}return{visible:s,calc:a,calcIds:i,resolve:Xt(o,t,n,s,i,a)}}function To(e,t){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>e[r]===t[r])}function Qr(e,t){return zt(e,t).visible}function vt(e,t,n){let r=zt(ze(e),n);return t.blocks.filter(i=>J(i)?r.visible.has(i.id):Yr(i,r.resolve))}function ze(e){return e.pages.flatMap(t=>t.blocks.filter(J))}function ei(e,t){let n=e.responseLimit?.scopeField;if(!n)return null;let r=t[n];return typeof r=="number"?Number.isFinite(r)?String(r):null:typeof r!="string"?null:r.trim()||null}function ti(e,t){let n=ze(e),r=Qr(n,t);return n.filter(i=>r.has(i.id))}function Po(e,t){return zt(ze(e),t).resolve}function ni(e,t,n){let i=e.pages.find(s=>s.id===t)?.next;if(!i||i.length===0)return{linear:!0};let o=Po(e,n);for(let s of i)if(yn(s.when,o))return s.to==="end"?{end:!0}:{to:s.to};return{linear:!0}}function Be(e,t){let n=[];if(e.pages.length===0)return n;let r=new Set,i=0;for(let o=0;o<=e.pages.length;o++){let s=e.pages[i];if(!s||r.has(s.id))break;r.add(s.id),n.push(s.id);let a=ni(e,s.id,t);if("end"in a)break;if("to"in a){let l=e.pages.findIndex(u=>u.id===a.to);if(l<0)break;i=l}else if(i+=1,i>=e.pages.length)break}return n}function Lo(e,t){return new Set(Be(e,t))}function dn(e,t,n){if("end"in ni(e,t,n))return!0;let r=Be(e,n);return r.length>0&&r[r.length-1]===t}function pn(e,t){let n=Lo(e,t),r=Qr(ze(e),t),i=new Set;for(let o of e.pages)if(n.has(o.id))for(let s of o.blocks)J(s)&&r.has(s.id)&&i.add(s.id);return i}function ri(e,t){let n=pn(e,t);return ze(e).filter(r=>n.has(r.id))}var De;function Mo(){if(De!==void 0)return De??void 0;if(typeof Intl>"u"||typeof Intl.DisplayNames>"u"){De=null;return}try{De=new Intl.DisplayNames(void 0,{type:"region"})}catch{De=null}return De??void 0}function ii(e){try{return Mo()?.of(e)??e}catch{return e}}var y=(e,t,n=[],r=[],i="")=>({iso2:e,name:ii(e),dialCode:t,lengths:n,groups:r,example:i}),Zo=[y("US","1",[10],[3,3,4],"2015550123"),y("CA","1",[10],[3,3,4],"5145550123"),y("GB","44",[10],[4,6],"7400123456"),y("AU","61",[9],[3,3,3],"412345678"),y("DE","49",[10,11],[4,7],"15123456789"),y("FR","33",[9],[1,2,2,2,2],"612345678"),y("IN","91",[10],[5,5],"8123456789"),y("DK","45",[8],[2,2,2,2],"32123456"),y("SE","46",[9],[2,3,4],"701234567"),y("NO","47",[8],[3,2,3],"40612345"),y("FI","358",[9,10],[2,3,4],"412345678"),y("NL","31",[9],[1,4,4],"612345678"),y("BE","32",[9],[3,2,2,2],"470123456"),y("ES","34",[9],[3,3,3],"612345678"),y("IT","39",[9,10],[3,3,4],"3123456789"),y("PT","351",[9],[3,3,3],"912345678"),y("IE","353",[9],[2,3,4],"851234567"),y("CH","41",[9],[2,3,2,2],"781234567"),y("AT","43",[10,11],[3,7],"6641234567"),y("PL","48",[9],[3,3,3],"512345678"),y("CZ","420",[9],[3,3,3],"601123456"),y("GR","30",[10],[3,3,4],"6912345678"),y("RO","40",[9],[3,3,3],"712345678"),y("HU","36",[9],[2,3,4],"201234567"),y("UA","380",[9],[2,3,2,2],"501234567"),y("RU","7",[10],[3,3,2,2],"9123456789"),y("TR","90",[10],[3,3,2,2],"5012345678"),y("IL","972",[9],[2,3,4],"501234567"),y("AE","971",[9],[2,3,4],"501234567"),y("SA","966",[9],[2,3,4],"512345678"),y("ZA","27",[9],[2,3,4],"711234567"),y("NG","234",[10],[3,3,4],"8021234567"),y("KE","254",[9],[3,3,3],"712123456"),y("EG","20",[10],[3,3,4],"1001234567"),y("BR","55",[10,11],[2,5,4],"11961234567"),y("MX","52",[10],[3,3,4],"2221234567"),y("AR","54",[10],[4,6],"1123456789"),y("CL","56",[9],[1,4,4],"221234567"),y("CO","57",[10],[3,3,4],"3211234567"),y("PE","51",[9],[3,3,3],"912345678"),y("CN","86",[11],[3,4,4],"13123456789"),y("JP","81",[10],[2,4,4],"9012345678"),y("KR","82",[9,10],[2,4,4],"1023456789"),y("SG","65",[8],[4,4],"81234567"),y("HK","852",[8],[4,4],"51234567"),y("TW","886",[9],[3,3,3],"912345678"),y("MY","60",[9,10],[2,3,4],"123456789"),y("ID","62",[10,11],[3,4,4],"81234567890"),y("TH","66",[9],[2,3,4],"812345678"),y("PH","63",[10],[3,3,4],"9171234567"),y("VN","84",[9],[3,3,3],"912345678"),y("PK","92",[10],[3,3,4],"3012345678"),y("BD","880",[10],[2,4,4],"1812345678"),y("NZ","64",[9,10],[2,3,4],"211234567"),y("SK","421",[9],[3,3,3],"912123456"),y("BG","359",[9],[2,3,4],"481234567"),y("HR","385",[8,9],[2,3,4],"921234567"),y("RS","381",[8,9],[2,3,4],"601234567"),y("SI","386",[8],[2,3,3],"31234567"),y("LT","370",[8],[3,2,3],"61234567"),y("LV","371",[8],[2,3,3],"21234567"),y("EE","372",[7,8],[3,4],"51234567"),y("IS","354",[7],[3,4],"6111234"),y("LU","352",[9],[3,3,3],"628123456"),y("MA","212",[9],[3,3,3],"650123456"),y("CR","506",[8],[4,4],"83123456"),y("EC","593",[9],[2,3,4],"991234567"),y("UY","598",[8],[1,3,4],"94231234"),y("QA","974",[8],[4,4],"33123456"),y("KW","965",[8],[4,4],"50012345")],Oo="AD376 AF93 AG1 AI1 AL355 AM374 AO244 AS1 AW297 AX358 AZ994 BA387 BB1 BF226 BH973 BI257 BJ229 BL590 BM1 BN673 BO591 BQ599 BS1 BT975 BV47 BW267 BY375 BZ501 CC61 CD243 CF236 CG242 CI225 CK682 CM237 CU53 CV238 CW599 CX61 CY357 DJ253 DM1 DO1 DZ213 EH212 ER291 ET251 FJ679 FK500 FM691 FO298 GA241 GD1 GE995 GF594 GG44 GH233 GI350 GL299 GM220 GN224 GP590 GQ240 GS500 GT502 GU1 GW245 GY592 HN504 HT509 IM44 IO246 IQ964 IR98 JE44 JM1 JO962 KG996 KH855 KI686 KM269 KN1 KP850 KY1 KZ7 LA856 LB961 LC1 LI423 LK94 LR231 LS266 LY218 MC377 MD373 ME382 MF590 MG261 MH692 MK389 ML223 MM95 MN976 MO853 MP1 MQ596 MR222 MS1 MT356 MU230 MV960 MW265 MZ258 NA264 NC687 NE227 NF672 NI505 NP977 NR674 NU683 OM968 PA507 PF689 PG675 PM508 PN64 PR1 PS970 PW680 PY595 RE262 RW250 SB677 SC248 SD249 SH290 SJ47 SL232 SM378 SN221 SO252 SR597 SS211 ST239 SV503 SX1 SY963 SZ268 TC1 TD235 TF262 TG228 TJ992 TK690 TL670 TM993 TN216 TO676 TT1 TV688 TZ255 UG256 UZ998 VA379 VC1 VE58 VG1 VI1 VU678 WF681 WS685 XK383 YE967 YT262 ZM260 ZW263";function Ro(e){let t=[];for(let n of e.trim().split(/\s+/)){let r=n.slice(0,2),i=n.slice(2);t.push({iso2:r,name:ii(r),dialCode:i,lengths:[],groups:[],example:""})}return t}var rt=[...Zo,...Ro(Oo)],je=Do(rt);function Do(e){if(typeof Intl>"u"||typeof Intl.Collator>"u")return[...e].sort((n,r)=>n.iso2<r.iso2?-1:n.iso2>r.iso2?1:0);let t=new Intl.Collator(void 0,{sensitivity:"base"});return[...e].sort((n,r)=>t.compare(n.name,r.name))}var Uo=new Map(rt.map(e=>[e.iso2,e])),Bo={"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 wn(e){let t=e.toUpperCase();return/^[A-Z]{2}$/.test(t)?String.fromCodePoint(...[...t].map(n=>127462+n.charCodeAt(0)-65)):"\u{1F3F3}\uFE0F"}function St(e){return e?Uo.get(e.toUpperCase()):void 0}function oi(e){return St(e?Bo[e]:void 0)}function jo(e){let t;for(let n of rt)e.startsWith(n.dialCode)&&(!t||n.dialCode.length>t.dialCode.length)&&(t=n);return t}function de(e){return e.replace(/[^\d]/g,"")}function it(e,t){let n=de(t);if(!n)return"";let r=e?.groups?.length?e.groups:[],i=[],o=0;for(let s of r){if(o>=n.length)break;i.push(n.slice(o,o+s)),o+=s}for(;o<n.length;)i.push(n.slice(o,o+3)),o+=3;return i.join(" ")}function si(e,t){let n=de(t);return n?`+${e.dialCode}${n}`:""}function ot(e,t,n){let r=(e??"").trim(),i=r.startsWith("+"),o=de(r);if(i){if(!o)return{national:"",e164:"",pending:!0,raw:r};let s=n?.previousDigits?de(n.previousDigits):"";if(s&&o===s)return{national:o,e164:`+${o}`,pending:!0,raw:r};let a=jo(o);if(a){let l=o.slice(a.dialCode.length);return{country:a,national:l,e164:`+${o}`}}return{national:o,e164:`+${o}`,pending:!0,raw:r}}if(!o)return{country:t,national:"",e164:""};if(t){let s=o.startsWith(t.dialCode)?o.slice(t.dialCode.length):o;return{country:t,national:s,e164:`+${t.dialCode}${s}`}}return{national:o,e164:`+${o}`}}function Vo(e){let{country:t,national:n,e164:r}=ot(e);if(!r)return!1;let i=de(r).length;return i<8||i>15?!1:t?.lengths.length?t.lengths.includes(n.length):n.length>=4}var Ho=8;function ai(e,t){if(!e||!t||typeof window>"u")return"below";let n=Ho,r=document.documentElement.clientWidth||window.innerWidth,i=document.documentElement.clientHeight||window.innerHeight,o=e.getBoundingClientRect(),s=Math.max(0,i-o.bottom-n),a=Math.max(0,o.top-n),l=s<t.scrollHeight&&a>s?"above":"below",c=Math.max(0,Math.min(l==="above"?a:s,i-n*2)),f=Math.max(0,r-n*2);t.style.setProperty("--fillo-phone-popover-max-height",`${Math.floor(c)}px`),t.style.setProperty("--fillo-phone-popover-max-width",`${Math.floor(f)}px`),t.style.setProperty("--fillo-phone-popover-offset-x","0px");let h=Math.min(t.offsetWidth,f),m=getComputedStyle(e).direction==="rtl"?o.right-h:o.left,g=0,b=m+h-(r-n);b>0&&(g-=b);let z=n-(m+g);return z>0&&(g+=z),t.style.setProperty("--fillo-phone-popover-offset-x",`${Math.round(g)}px`),l}var li="This field is required",P={back:"Back",next:"Next",submit:"Submit",submitting:"Submitting\u2026",uploading:"Uploading\u2026",optional:" (optional)",other:"Other",otherPrompt:"Other \u2014 please specify",otherPlaceholder:"Your answer",choosePlaceholder:"Choose\u2026",successTitle:"Thanks!",successMessage:"Your response has been recorded.",closed:"This form is no longer accepting responses.",notLive:"This form isn't live yet.",notOpenTitle:"This form isn't open yet",notOpenBody:"The form owner is still setting things up. Please check back soon.",closedTitle:"Responses are closed",submitFailed:"This form can't submit right now. Please try again in a moment.",loadFailedNotFound:"Form not found \u2014 check the form id and that it's published.",loadFailedNetwork:"Couldn't reach the server \u2014 check your connection or CORS.",loadFailed:"This form could not be loaded.",renderFailed:"This form could not be rendered.",resumeNotice:"Picked up where you left off.",editNotice:"You're updating your earlier response.",resumeStartOver:"Start over",challengeUnavailable:"The verification check couldn't load. Refresh the page, or check that challenges.cloudflare.com isn't blocked."},B={required:li,resumeLinkExpired:"That saved-progress link expired or was already used \u2014 start again below.",alreadyAnswered:"You've already answered this form.",uploadRetry:"Retry",uploadsDisabled:"Connect this form to Fillo to enable uploads",uploadsRenderOnly:"Uploads are unavailable in this render-only preview",uploadsUnavailable:"Uploads are temporarily unavailable",uploadUnavailable:"We couldn't upload this file right now. Try again in a moment.",uploadFailed:"Upload failed \u2014 try again",dropzoneTitle:e=>`Drop ${e?"files":"a file"} here or click to browse`,dropzoneHint:e=>`Up to ${e} MB per file`,fileTooLarge:e=>`Larger than ${e} MB limit`,filesUploading:e=>`Uploading ${e} ${e===1?"file":"files"}, please wait\u2026`,uploadsFailed:e=>`${e} ${e===1?"upload":"uploads"} failed.`,filesUploaded:e=>`${e} ${e===1?"file":"files"} uploaded.`,submittingAnnouncement:"Submitting your response\u2026",errorSummaryTitle:"Please fix the following:",rankingPosition:(e,t,n)=>`${e}, position ${t} of ${n}`,phoneCountrySelected:e=>`${e} selected`,phoneResultsCount:e=>`${e} ${e===1?"result":"results"}`,signatureEmpty:"No signature yet",signatureSigned:"Signature saved"};var qo=Qe({fileId:W().check(Oe(1)),name:W(),size:Ar().check(Wt()),mime:W(),url:G(W())});function ui(e,t){if(vn(t))return e.kind==="calculated"?null:e.required?li: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 n=e.kind==="long_text"?2e4:2e3;return!e.maxLength&&t.length>n?"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`:bt().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 n=new URL(t);if(n.protocol!=="http:"&&n.protocol!=="https:")return"Enter an http(s) URL"}catch{return"Enter a valid URL (including https://)"}return null}case"phone":return typeof t!="string"||!Vo(t)?"Enter a valid phone number":null;case"number":{let n=typeof t=="string"?Number(t):t;return typeof n!="number"||!Number.isFinite(n)?"Enter a number":e.min!==void 0&&n<e.min?`Must be at least ${e.min}`:e.max!==void 0&&n>e.max?`Must be at most ${e.max}`:null}case"select":case"dropdown":return typeof t!="string"||t===""?"Pick an option":e.options.some(n=>n.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 n=new Set(e.options.map(s=>s.id)),r=t,i=0,o=new Set;for(let s of r){if(typeof s!="string")return"Pick valid options";if(o.has(s))return"Pick each option only once";if(o.add(s),!n.has(s)){if(e.allowOther!==!0||s.length===0||s.length>500)return"Pick valid options";if(++i>1)return"Only one 'Other' answer is allowed"}}return null}case"checkbox":return typeof t=="boolean"?null:"Invalid value";case"rating":{let n=e.max??5,r=typeof t=="string"?Number(t):t;return typeof r!="number"||!Number.isInteger(r)||r<1||r>n?`Pick a rating between 1 and ${n}`:null}case"linear_scale":{let n=e.min??1,r=e.max??10,i=typeof t=="string"?Number(t):t;return typeof i!="number"||!Number.isInteger(i)||i<n||i>r?`Pick a value between ${n} and ${r}`:null}case"ranking":{if(!Array.isArray(t))return"Drag the options into order";let n=e.options.map(i=>i.id).sort(),r=[...t].sort();return n.length!==r.length||n.some((i,o)=>i!==r[o])?"Rank every option":null}case"matrix":{if(typeof t!="object"||t===null||Array.isArray(t))return"Answer the grid";let n=t,r=new Set(e.columns.map(o=>o.id)),i=new Set(e.rows.map(o=>o.id));for(let[o,s]of Object.entries(n))if(!i.has(o)||!r.has(s))return"Invalid grid answer";return e.required&&Object.keys(n).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"calculated":return null;case"custom":return null;case"date":{if(typeof t!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(t))return"Enter a valid date";let[n,r,i]=t.split("-").map(Number),o=new Date(Date.UTC(n,r-1,i));return o.getUTCFullYear()!==n||o.getUTCMonth()!==r-1||o.getUTCDate()!==i?"Enter a valid date":null}case"file_upload":{let n=_e(qo).safeParse(t);if(!n.success)return"Upload did not complete";let r=e.maxFiles??1;return n.data.length>r?`At most ${r} file${r===1?"":"s"}`:null}}}function ci(e,t){let n=ri(e,t),r={},i={};for(let o of n){if(o.kind==="calculated")continue;let s=Gr(o,t[o.id]),a=ui(o,s);a?r[o.id]=a:vn(s)||(i[o.id]=s)}return{ok:Object.keys(r).length===0,errors:r,data:i}}var Wo=["short_text","long_text","email","url","phone","number","select","multi_select","dropdown","checkbox","rating","linear_scale","ranking","matrix","signature","date","file_upload","hidden","calculated","custom"],Ko=["heading","paragraph","divider"],Go=[...Wo,...Ko],_n=W().check(Oe(1),q(128)),Yt=Kt({id:_n,label:W().check(q(1e3)),icon:G(Ye())}),Jo=Kt({id:_n,kind:Ir(Go),label:G(W().check(q(2e3))),options:G(_e(Yt).check(q(200))),rows:G(_e(Yt).check(q(200))),columns:G(_e(Yt).check(q(200)))}),Xo=Qe({id:_n,title:G(W().check(q(500))),blocks:_e(Jo).check(q(500)),next:G(Ye())}),Yo=Qe({version:Nr(1),title:Gt(G(W().check(q(2e3))),""),description:G(W().check(q(5e3))),pages:_e(Xo).check(Oe(1),q(50)),settings:Gt(G(Fr(W(),Ye())),{})}),Qo=1,fn=1,hn="0.12.0";function te(e,t,n=""){return typeof e=="string"?e.trim().slice(0,t):n}function D(e,t){let n=te(e,t);return n===""?void 0:n}function yt(e,t){if(typeof e!="string")return;let n=e.slice(0,t);return n.trim()===""?void 0:n}function he(e){return typeof e=="boolean"?e:void 0}function me(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function ce(e,t,n,r){let i=me(e);return i===void 0?r:Math.max(t,Math.min(n,Math.round(i)))}function wt(e,t=200){return Array.isArray(e)?e.slice(0,t).flatMap(n=>{if(!n||typeof n!="object")return[];let r=n,i=te(r.id,128),o=te(r.label,1e3),s=r.icon==="thumbs_up"||r.icon==="thumbs_down"?r.icon:void 0;return i&&o?[M({id:i,label:o,icon:s})]:[]}):[]}function Qt(e){let t=new Set;for(let{id:n}of e){if(t.has(n))return n;t.add(n)}}function xn(e){if(!Array.isArray(e))return;let t=e.slice(0,20).flatMap(n=>{if(!n||typeof n!="object")return[];let r=n,i=r.op;if(i!=="eq"&&i!=="neq"&&i!=="contains"&&i!=="gt"&&i!=="lt"&&i!=="answered"&&i!=="not_answered")return[];let o=te(r.fieldId,128);if(!o)return[];let s=r.value,a=typeof s=="string"||typeof s=="number"||typeof s=="boolean"?s:void 0;return[{fieldId:o,op:i,...a!==void 0?{value:a}:{}}]});return t.length?t:void 0}function di(e,t,n,r){let i=t.get(e);if(i===void 0)return n.has(e);if(r.has(e))return!0;r.add(e);for(let o of i)if(!di(o,t,n,r))return!1;return!0}function es(e,t,n,r,i){if(!Array.isArray(e))return;let o=e.slice(0,50).flatMap(s=>{if(!s||typeof s!="object")return[];let a=s,l=typeof a.to=="string"?a.to:void 0;if(!l||l!=="end"&&!t.has(l))return[];if(l===n)return[];let u=a.when;if(u!==void 0&&!Array.isArray(u))return[];let c=xn(u);return Array.isArray(u)&&u.length>0&&c===void 0?[]:c&&c.some(f=>!di(f.fieldId,i,r,new Set))?[]:[{when:c??[],to:l}]});return o.length?o:void 0}var ts=["number","rating","linear_scale","calculated"];function ke(e,t=0){if(t>32||!e||typeof e!="object"||Array.isArray(e))return null;let n=e;switch(n.op){case"value":{let r=te(n.fieldId,128);return r?{op:"value",fieldId:r}:null}case"const":{let r=me(n.value);return r===void 0?null:{op:"const",value:r}}case"add":case"mul":case"min":case"max":{if(!Array.isArray(n.args)||n.args.length<1||n.args.length>50)return null;let r=[];for(let i of n.args){let o=ke(i,t+1);if(!o)return null;r.push(o)}return{op:n.op,args:r}}case"sub":case"div":{let r=ke(n.left,t+1),i=ke(n.right,t+1);return r&&i?{op:n.op,left:r,right:i}:null}case"round":{let r=ke(n.arg,t+1);return r?M({op:"round",arg:r,decimals:me(n.decimals)===void 0?void 0:ce(n.decimals,0,6,0)}):null}case"if":{if(!Array.isArray(n.when))return null;let r=xn(n.when)??[];if(r.length!==n.when.length)return null;let i=ke(n.then,t+1),o=ke(n.else,t+1);return i&&o?{op:"if",when:r,then:i,else:o}:null}default:return null}}function $e(e,t,n){switch(e.op){case"value":t.add(e.fieldId);return;case"const":return;case"add":case"mul":case"min":case"max":for(let r of e.args)$e(r,t,n);return;case"sub":case"div":$e(e.left,t,n),$e(e.right,t,n);return;case"round":$e(e.arg,t,n);return;case"if":for(let r of e.when)n.add(r.fieldId);$e(e.then,t,n),$e(e.else,t,n);return}}function ns(e){let t=new Map;for(let o of e)for(let s of o.blocks)J(s)&&t.set(s.id,s.kind);let n=new Map;for(let o of e)for(let s of o.blocks){if(s.kind!=="calculated")continue;let a=ke(s.calc);if(!a)return`Field ${s.id} has a malformed calc expression \u2014 build it from value/const/add/sub/mul/div/min/max/round/if nodes`;s.calc=a;let l=new Set,u=new Set;$e(a,l,u);for(let c of l){let f=t.get(c);if(f===void 0)return`Calculated field ${s.id} references a missing field: ${c} \u2014 remove the reference or restore that field`;if(!ts.includes(f))return`Calculated field ${s.id} references non-numeric field ${c} (${f}) \u2014 calculations can read number, rating, linear_scale, and calculated fields only`}n.set(s.id,[...l,...u].filter(c=>t.get(c)==="calculated"))}let r=new Map,i=(o,s)=>{let a=r.get(o);if(a==="done")return null;if(a==="visiting"){let l=[...s.slice(s.indexOf(o)),o].join(" \u2192 ");return`Calculated field ${o} depends on its own result (${l}) \u2014 break the cycle so the value can be computed`}r.set(o,"visiting");for(let l of n.get(o)??[]){let u=i(l,[...s,o]);if(u)return u}return r.set(o,"done"),null};for(let o of n.keys()){let s=i(o,[]);if(s)return s}return null}var Pr=100,Lr=5e3;function Ie(e){switch(e.op){case"value":case"const":return 1;case"add":case"mul":case"min":case"max":return 1+e.args.reduce((t,n)=>t+Ie(n),0);case"sub":case"div":return 1+Ie(e.left)+Ie(e.right);case"round":return 1+Ie(e.arg);case"if":return 1+Ie(e.then)+Ie(e.else)}}function rs(e){let t=0,n=0;for(let r of e)for(let i of r.blocks)i.kind==="calculated"&&(t+=1,n+=Ie(i.calc));return t>Pr?`Form has ${t} calculated fields \u2014 the maximum is ${Pr}; remove some or consolidate them into fewer expressions`:n>Lr?`Calculated expressions total ${n} operations \u2014 the maximum is ${Lr} across the form; simplify or split up the calculations`:null}function pi(e){return{id:te(e.id,128),visibleIf:xn(e.visibleIf)}}function V(e,t){return{...pi(e),kind:t,label:te(e.label,2e3,"Untitled field"),description:D(e.description,5e3),required:he(e.required),placeholder:D(e.placeholder,500)}}function Mr(e){let t=D(e,2e3);if(t)try{let n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"?t:void 0}catch{return}}function is(e){if(!e||typeof e!="object")return;let t=e,n=t.by==="browser"||t.by==="field"||t.by==="identify"?t.by:void 0;if(!n)return;let r=n==="field"?D(t.field,128):void 0;if(n==="field"&&!r)return;let i=D(t.scopeField,128),o=t.onRepeat==="update"&&n==="identify"?"update":"keep";return{by:n,...r?{field:r}:{},...i?{scopeField:i}:{},onRepeat:o}}function os(e){if(!e||typeof e!="object")return;let t=e,n=t.unverified==="allow"||t.unverified==="quarantine"?t.unverified:void 0,r=t.challenge==="turnstile"?"turnstile":void 0;if(!(!n&&!r))return{...n?{unverified:n}:{},...r?{challenge:r}:{}}}function ss(e){let t=e&&typeof e=="object"?e:{};return{submitMode:t.submitMode==="button"||t.submitMode==="auto"?t.submitMode:void 0,submitLabel:D(t.submitLabel,100),successTitle:D(t.successTitle,200),successMessage:D(t.successMessage,5e3),redirectUrl:Mr(t.redirectUrl),showProgress:he(t.showProgress),responseLimit:is(t.responseLimit),trust:os(t.trust),notifyEmail:bt().check(q(254)).safeParse(t.notifyEmail).success?t.notifyEmail:void 0,sendReceipt:he(t.sendReceipt),saveProgress:he(t.saveProgress),draftAnswersVisible:he(t.draftAnswersVisible),resumeEmails:he(t.resumeEmails),resumeUrl:Mr(t.resumeUrl),draftDigest:he(t.draftDigest)}}function M(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function as(e){if(!e||typeof e!="object")return null;let t=e,n=t.kind,r=pi(t);if(!r.id||typeof n!="string")return null;switch(n){case"heading":return M({...r,kind:n,text:te(t.text,2e3,"Section")});case"paragraph":return M({...r,kind:n,text:te(t.text,5e3)});case"divider":return M({...r,kind:n});case"short_text":case"email":case"url":return M({...V(t,n),maxLength:me(t.maxLength)===void 0?void 0:ce(t.maxLength,1,2e3,2e3)});case"phone":{let i=D(t.defaultCountry,2)?.toUpperCase();return M({...V(t,n),defaultCountry:i&&/^[A-Z]{2}$/.test(i)?i:void 0})}case"long_text":return M({...V(t,n),maxLength:me(t.maxLength)===void 0?void 0:ce(t.maxLength,1,2e4,2e4)});case"number":return M({...V(t,n),min:me(t.min),max:me(t.max),decimals:me(t.decimals)===void 0?void 0:ce(t.decimals,0,6,0),prefix:yt(t.prefix,100),suffix:yt(t.suffix,100),notation:t.notation==="grouped"?"grouped":t.notation==="grouped-comma"?"grouped-comma":t.notation==="grouped-dot"?"grouped-dot":void 0});case"select":case"multi_select":case"dropdown":{let i=wt(t.options);return i.length===0?null:M({...V(t,n),options:i,allowOther:he(t.allowOther),shuffleOptions:he(t.shuffleOptions)})}case"checkbox":{let i=t.appearance==="toggle"?"toggle":void 0;return M({...V(t,n),appearance:i})}case"signature":case"date":return M(V(t,n));case"rating":{let i=ce(t.max,1,10,5);return M({...V(t,n),max:i,insightsMetric:t.insightsMetric==="csat"&&i===5?"csat":void 0})}case"linear_scale":{let i=ce(t.min,0,9,1),o=ce(t.max,i+1,10,10),s=t.insightsMetric==="nps"&&i===0&&o===10?"nps":t.insightsMetric==="csat"&&i===1&&o===5?"csat":void 0;return M({...V(t,n),min:i,max:o,minLabel:D(t.minLabel,100),maxLabel:D(t.maxLabel,100),insightsMetric:s})}case"ranking":{let i=wt(t.options);return i.length<2?null:M({...V(t,n),options:i})}case"matrix":{let i=wt(t.rows),o=wt(t.columns);return i.length===0||o.length===0?null:M({...V(t,n),rows:i,columns:o})}case"hidden":return M({...V(t,n),required:!1,paramName:D(t.paramName,128),defaultValue:D(t.defaultValue,1e3)});case"calculated":return M({...V(t,n),required:!1,calc:t.calc,decimals:me(t.decimals)===void 0?void 0:ce(t.decimals,0,6,0),prefix:yt(t.prefix,100),suffix:yt(t.suffix,100)});case"file_upload":return M({...V(t,n),maxFiles:ce(t.maxFiles,1,20,1),maxFileSizeMb:ce(t.maxFileSizeMb,1,5e3,500),accept:Array.isArray(t.accept)?t.accept.flatMap(i=>{let o=D(i,100);return o?[o]:[]}).slice(0,50):void 0});case"custom":return M({...V(t,n),component:te(t.component,128),config:t.config&&typeof t.config=="object"&&!Array.isArray(t.config)?t.config:void 0});default:return null}}function Ne(e){let t=Yo.safeParse(e);if(!t.success){let p=t.error.issues[0],m=p?.path.join(".");return{ok:!1,error:p?`${m?`${m}: `:""}${p.message}`:"Invalid schema"}}if(t.data.version>Qo)return{ok:!1,error:`Unsupported schema version: ${t.data.version}`};let n=t.data.pages.map(p=>{let m=p.blocks.flatMap(g=>{let b=as(g);return b?[b]:[]});return{id:te(p.id,128),title:D(p.title,500),blocks:m,next:p.next}}),r=new Set(n.map(p=>p.id)),i=new Map;for(let p of n)for(let m of p.blocks){if(m.kind!=="calculated")continue;let g=new Set,b=ke(m.calc);if(b){let z=new Set,T=new Set;$e(b,z,T);for(let F of z)g.add(F);for(let F of T)g.add(F)}i.set(m.id,g)}let o=new Set,s=n.map(p=>{for(let m of p.blocks)J(m)&&o.add(m.id);return M({id:p.id,title:p.title,blocks:p.blocks,next:es(p.next,r,p.id,new Set(o),i)})}),a=new Set,l=new Set;for(let p of s){if(!p.id)return{ok:!1,error:"Page ids cannot be blank"};if(a.has(p.id))return{ok:!1,error:`Duplicate page id: ${p.id}`};a.add(p.id);for(let m of p.blocks){if(l.has(m.id))return{ok:!1,error:`Duplicate block id: ${m.id}`};if(l.add(m.id),m.kind==="number"&&m.min!==void 0&&m.max!==void 0&&m.min>m.max)return{ok:!1,error:`Field ${m.id} has min greater than max`};if(m.kind==="select"||m.kind==="multi_select"||m.kind==="dropdown"||m.kind==="ranking"){let g=Qt(m.options);if(g)return{ok:!1,error:`Duplicate option id in field ${m.id}: ${g}`}}else if(m.kind==="matrix"){let g=Qt(m.rows);if(g)return{ok:!1,error:`Duplicate matrix row id in field ${m.id}: ${g}`};let b=Qt(m.columns);if(b)return{ok:!1,error:`Duplicate matrix column id in field ${m.id}: ${b}`}}}}let u=ns(s);if(u)return{ok:!1,error:u};let c=rs(s);if(c)return{ok:!1,error:c};if(s.every(p=>p.blocks.length===0))return{ok:!1,error:"Schema must contain at least one valid block"};let f={version:fn,title:te(t.data.title,2e3),pages:s,settings:ss(t.data.settings)},h=D(t.data.description,5e3);return h&&(f.description=h),{ok:!0,schema:f}}function et(e,t){let n=D(e,t);if(n&&!(/[;{}<>]/.test(n)||/url\s*\(/i.test(n)))return n}function kn(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n=t.colorScheme==="light"||t.colorScheme==="dark"||t.colorScheme==="auto"?t.colorScheme:void 0,r=M({colorScheme:n,primary:et(t.primary,200),background:et(t.background,200),text:et(t.text,200),radius:et(t.radius,64),fontFamily:et(t.fontFamily,200)});return Object.keys(r).length>0?r:null}function ls(e){throw new Error(`Unhandled field kind: ${JSON.stringify(e)}`)}function fi(e,t){if(t==null||t==="")return"";switch(e.kind){case"file_upload":return Array.isArray(t)?t.map(n=>n.name).join(", "):String(t);case"select":case"dropdown":return e.options.find(n=>n.id===t)?.label??String(t);case"multi_select":return Array.isArray(t)?t.map(n=>e.options.find(r=>r.id===n)?.label??n).join(", "):String(t);case"ranking":return Array.isArray(t)?t.map((n,r)=>`${r+1}. ${e.options.find(i=>i.id===n)?.label??n}`).join(", "):String(t);case"matrix":{if(typeof t!="object"||t===null||Array.isArray(t))return String(t);let n=t;return e.rows.filter(r=>n[r.id]).map(r=>`${r.label}: ${e.columns.find(i=>i.id===n[r.id])?.label??""}`).join(", ")}case"signature":return typeof t=="string"&&t.startsWith("data:image/")?"\u270D signed":"";case"checkbox":return t===!0?"Yes":"No";case"rating":case"linear_scale":return String(t);case"number":{let n=typeof t=="number"?t:Number(t);if(!Number.isFinite(n))return String(t);let r=e.decimals===void 0?String(n):n.toFixed(Math.max(0,Math.min(6,e.decimals)));return`${e.prefix??""}${r}${e.suffix??""}`}case"calculated":{let n=typeof t=="number"?t:Number(t);if(!Number.isFinite(n))return String(t);let r=e.decimals===void 0?String(n):n.toFixed(Math.max(0,Math.min(6,e.decimals)));return`${e.prefix??""}${r}${e.suffix??""}`}case"phone":{let{country:n,national:r,e164:i}=ot(String(t));if(!i)return String(t);let o=it(n,r),s=n?`+${n.dialCode}`:i.replace(r,"");return o?`${s} ${o}`:i}case"short_text":case"long_text":case"email":case"url":case"date":case"hidden":return String(t);case"custom":return typeof t=="object"?JSON.stringify(t):String(t);default:return ls(e)}}function us(e){return Math.max(0,Math.min(6,Math.round(e)))}function hi(e){switch(e){case"grouped-comma":return"en-US";case"grouped-dot":return"de-DE";case"grouped":case void 0:return}}function mi(e,t){if(!Number.isFinite(e))return String(e);let n=t?.decimals===void 0?void 0:us(t.decimals);if(typeof Intl>"u")return n===void 0?String(e):e.toFixed(n);let r={useGrouping:!0};return n===void 0?r.maximumFractionDigits=20:(r.minimumFractionDigits=n,r.maximumFractionDigits=n),new Intl.NumberFormat(t?.locale,r).format(e)}function gi(e,t){return t?e.split(t).join(""):e}function Zr(e,t){return t==="."?e:e.split(t).join(".")}function cs(e,t,n){if(n!==t&&e.includes(n)){let o=e.lastIndexOf(n),s=gi(e.slice(0,o),t),a=e.slice(o+n.length);return`${s}.${a}`}let r=e.split(t);return r.length===1?e:r.every((o,s)=>s===0?/^[1-9]\d{0,2}$/.test(o):/^\d{3}$/.test(o))?r.join(""):`${r.slice(0,-1).join("")}.${r.at(-1)??""}`}function $n(e,t){if(typeof Intl>"u"||e.trim()==="")return e;let n=new Intl.NumberFormat(t).formatToParts(12345678e-1),r=n.find(a=>a.type==="group")?.value??",",i=n.find(a=>a.type==="decimal")?.value??".",o=e.trim(),s=o.startsWith("-");return s&&(o=o.slice(1)),/^\s$/.test(r)?o=Zr(o.replace(/\s/g,""),i):r==="."||r===","?o=cs(o,r,i):o=Zr(gi(o,r),i),o===""||o==="."||!/^\d*\.?\d*$/.test(o)?e:s?`-${o}`:o}function st(e,t){let r=e.startsWith("-")?e.slice(1):e;if(r.includes("-"))return!1;if(r==="")return!0;if(typeof Intl>"u")return/^[\d.,]*$/.test(r);let i=new Intl.NumberFormat(t).formatToParts(12345678e-1),o=i.find(f=>f.type==="group")?.value??",",s=i.find(f=>f.type==="decimal")?.value??".",a=o===".",l=/^\s$/.test(o),u=a?[s]:Array.from(new Set([".",s])),c=0;for(let f of r)if(!/\d/.test(f)){if(u.includes(f)){if(++c>1)return!1;continue}if(!(l?/\s/.test(f):f===o))return!1}return!0}var mn="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",ds=256-256%mn.length;function Or(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 n="";for(;n.length<e;){let r=new Uint8Array(e);t.getRandomValues(r);for(let i=0;i<e&&n.length<e;i++){let o=r[i];o<ds&&(n+=mn[o%mn.length])}}return n}var bi=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,n=[128],r=this.blockLen+1;for(;r%64!==56;)n.push(0),r++;n.push(e>>>24&255,e>>>16&255,e>>>8&255,e&255),n.push(t>>>24&255,t>>>16&255,t>>>8&255,t&255),this.update(new Uint8Array(n));let i=new Uint8Array(20),o=[this.h0,this.h1,this.h2,this.h3,this.h4];for(let s=0;s<5;s++)i[s*4]=o[s]>>>24&255,i[s*4+1]=o[s]>>>16&255,i[s*4+2]=o[s]>>>8&255,i[s*4+3]=o[s]&255;return i}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 n=this.h0,r=this.h1,i=this.h2,o=this.h3,s=this.h4;for(let a=0;a<80;a++){let l,u;a<20?(l=r&i|~r&o,u=1518500249):a<40?(l=r^i^o,u=1859775393):a<60?(l=r&i|r&o|i&o,u=2400959708):(l=r^i^o,u=3395469782);let c=(n<<5|n>>>27)+l+s+u+t[a]|0;s=o,o=i,i=r<<30|r>>>2,r=n,n=c}this.h0=this.h0+n|0,this.h1=this.h1+r|0,this.h2=this.h2+i|0,this.h3=this.h3+o|0,this.h4=this.h4+s|0}},_t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function zn(e){let t="";for(let n=0;n<e.length;n+=3){let r=e[n],i=n+1<e.length?e[n+1]:0,o=n+2<e.length?e[n+2]:0;t+=_t[r>>2],t+=_t[(r&3)<<4|i>>4],t+=n+1<e.length?_t[(i&15)<<2|o>>6]:"=",t+=n+2<e.length?_t[o&63]:"="}return t}var ps=e=>zn(new bi().update(e).digest()),$=class extends Error{constructor(e,t,n,r){super(e),this.status=t,this.retryAfterSec=n,this.code=r,this.name="FilloError"}status;retryAfterSec;code};function X(e){return e instanceof Error&&e.name==="FilloError"}async function Rr(e,t){try{let n=await e.json();return{message:typeof n.error=="string"&&n.error?n.error:t,code:typeof n.code=="string"&&n.code?n.code:void 0}}catch{}return{message:t}}function Dr(e){let t=Number(e.headers.get("retry-after"));return Number.isFinite(t)&&t>0?t:void 0}var tt=3,nt=3e4,fs=5*6e4,ue=10*6e4;function Ur(e,t){return t?.throwIfAborted(),new Promise((n,r)=>{let i=()=>{clearTimeout(o),r(t?.reason)},o=setTimeout(()=>{t?.removeEventListener("abort",i),n()},e);t?.addEventListener("abort",i,{once:!0})})}function en(e,t=!1){let n=X(e)?e.status??0:0;return n===0||n===503||n===504||t&&n===409&&X(e)&&e.retryAfterSec!==void 0}function xt(e){return e>=500||e===429||e===408}function Br(e){return typeof DOMException<"u"&&e instanceof DOMException&&e.name==="TimeoutError"?new $("Request timed out",0):e}function hs(e,t){let n=e.split(".").map(i=>Number(i)||0),r=t.split(".").map(i=>Number(i)||0);for(let i=0;i<Math.max(n.length,r.length);i++){let o=(n[i]??0)-(r[i]??0);if(o!==0)return o}return 0}function ms(e){if(e.schemaVersion!==void 0&&e.schemaVersion!==fn)throw new $(`This form uses schema version ${e.schemaVersion}; this SDK supports version ${fn}. Update @usefillo/* to render it.`,426);if(e.minSdkVersion&&hs(hn,e.minSdkVersion)<0)throw new $(`This form requires @usefillo/* ${e.minSdkVersion} or newer. Current SDK is ${hn}.`,426)}function kt(e,t){return n=>t.onProgress?.({uploadedBytes:n,totalBytes:e,fraction:e===0?1:n/e})}async function gs(e){let t=globalThis.crypto?.subtle;if(t){let n=await t.digest("SHA-1",e);return zn(new Uint8Array(n))}return ps(e)}var bs="https://fillo.so",jr={"X-Fillo-Client":`@usefillo/core@${hn}`},Et=class{baseUrl;fetch;key;constructor(e={}){this.baseUrl=e.baseUrl?e.baseUrl.replace(/\/$/,""):e.sameOrigin?"":bs,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 n=t?.body!=null?{"Content-Type":"application/json",...jr,...t?.headers}:t?.headers,r;try{r=await this.fetch(this.url(e),{...t,headers:n,signal:t?.signal??AbortSignal.timeout(nt)})}catch(i){throw Br(i)}if(!r.ok){let{message:i,code:o}=await Rr(r,`Request failed: ${r.status}`);throw new $(i,r.status,Dr(r),o)}return await r.json()}async getForm(e){let t=await this.json(`/forms/${encodeURIComponent(e)}`);return ms(t),t}syncForm(e,t,n){if(!this.key)return Promise.reject(new $("createClient needs a `key` (pk_\u2026) to sync code-defined forms",401));let r=Ne(t);return r.ok?this.json("/forms/sync",{method:"POST",body:JSON.stringify({key:this.key,id:e,schema:r.schema,theme:kn(n)})}):Promise.reject(new $(`Invalid form schema: ${r.error}`,400))}async submit(e,t,n){let r;try{r=await this.fetch(this.url(`/forms/${encodeURIComponent(e)}/responses`),{method:"POST",headers:{"Content-Type":"application/json",...jr},body:JSON.stringify({data:t,meta:n}),signal:AbortSignal.timeout(nt)})}catch(o){throw Br(o)}if(r.status===422)return{ok:!1,errors:(await r.json()).errors};if(!r.ok){let{message:o,code:s}=await Rr(r,`Submit failed: ${r.status}`);throw new $(o,r.status,Dr(r),s)}let i=await r.json();return{ok:!0,responseId:i.id,duplicate:i.duplicate,updated:i.updated}}async fetchOwnResponse(e,t,n){try{return await this.json(`/forms/${encodeURIComponent(e)}/respondent-response`,{method:"POST",body:JSON.stringify({respondent:t,scopeValue:n})})}catch(r){if(X(r)&&(r.status===404||r.status===403))return null;throw r}}async startSession(e,t){try{let n=await this.fetch(this.url(`/forms/${encodeURIComponent(e)}/sessions`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pageCount:t}),signal:AbortSignal.timeout(nt)});return n.ok?(await n.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(nt)}).catch(()=>{})}catch{}}createDraft(e,t){return this.json(`/forms/${encodeURIComponent(e)}/drafts`,{method:"POST",body:JSON.stringify(t)})}getDraft(e,t,n){return this.json(`/drafts/${encodeURIComponent(e)}`,{headers:n?{"X-Fillo-Draft-Token":t,"X-Fillo-Draft-Adopt":"1"}:{"X-Fillo-Draft-Token":t}})}async saveDraft(e,t,n,r){await this.json(`/drafts/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"X-Fillo-Draft-Token":t},body:JSON.stringify(n),...r?.keepalive?{keepalive:!0}:{}})}async deleteDraft(e,t){await this.json(`/drafts/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-Fillo-Draft-Token":t}})}getUploadSession(e,t,n=AbortSignal.timeout(ue)){return this.json(`/uploads/${encodeURIComponent(e)}`,{...t?{headers:{"X-Fillo-Upload-Token":t}}:{},signal:n})}async uploadFile(e,t,n){let r=typeof File<"u"&&t instanceof File?t.name:"upload.bin",i=(t.type||"application/octet-stream").trim().toLowerCase(),o;if(n.sessionId){let u=await this.getUploadSession(n.sessionId,n.uploadToken,this.uploadSignal(n,ue));if(u.formId!==e||u.fieldId!==n.fieldId||u.fileName!==r||u.size!==t.size||u.mime.trim().toLowerCase()!==i)throw new $("File does not match this upload session",400);o=u,o.token||=n.uploadToken}else{let u=Or(24),c=Or(32),f=()=>this.json(`/forms/${encodeURIComponent(e)}/uploads`,{method:"POST",body:JSON.stringify({requestId:u,uploadToken:c,fieldId:n.fieldId,fileName:r,size:t.size,mime:i}),signal:this.uploadSignal(n,ue)}),h=Date.now()+ue,p=250;for(;;)try{o=await f();break}catch(m){if(n.signal?.aborted||!en(m,!0))throw m;let g=h-Date.now();if(g<=0)throw m;await Ur(Math.min(p,g),n.signal),p=Math.min(p*2,5e3)}}if(n.onSession?.({sessionId:o.id,uploadToken:o.token}),o.status==="complete"&&o.file)return o.file;if(o.status==="aborted")throw new $("This upload session was cancelled",409);let s;if(o.transport?.type==="gdrive")await this.driveUploadLoop(o,o.transport.uploadUrl,t,n);else if(o.transport?.type==="s3-multipart")await this.s3MultipartUploadLoop(o,t,n);else if(o.transport?.type==="s3-put")await this.s3PutUpload(o.transport.uploadUrl,t,n);else if(o.transport?.type==="box")s=await this.boxUpload(o.transport,t,n);else throw new $("This form's storage doesn't support uploads \u2014 connect Drive, S3, or Box.");let a=()=>this.json(`/uploads/${encodeURIComponent(o.id)}/complete`,{method:"POST",headers:o.token?{"X-Fillo-Upload-Token":o.token}:void 0,...s?{body:JSON.stringify(s)}:{},signal:this.uploadSignal(n,ue)}),l;try{l=await a()}catch(u){if(n.signal?.aborted||!en(u))throw u;let c=Date.now()+ue,f=250;for(;;){let h=await this.getUploadSession(o.id,o.token,this.uploadSignal(n,Math.max(1,c-Date.now())));if(h.status==="complete"&&h.file)return h.file;if(h.status==="aborted")throw u;try{l=await a();break}catch(m){if(n.signal?.aborted||!en(m,!0))throw m}let p=c-Date.now();if(p<=0)throw u;await Ur(Math.min(f,p),n.signal),f=Math.min(f*2,5e3)}}if(!l.file)throw new $("Upload completed but no file was returned");return l.file}async boxUpload(e,t,n){let r=kt(t.size,n);r(0);let i={Authorization:`Bearer ${e.token}`};if(e.mode==="simple"){let h=new FormData;h.append("attributes",JSON.stringify({name:e.fileName,parent:{id:e.folderId}})),h.append("file",t,e.fileName);let p=await this.retry(n,async()=>{let g=await this.fetch(e.uploadUrl,{method:"POST",headers:i,body:h,signal:this.uploadSignal(n)});if(!g.ok&&xt(g.status))throw new $(`Box upload failed: ${g.status}`,g.status);return g});if(!p.ok)throw new $(`Box upload failed: ${p.status}`,p.status);let m=await p.json();return r(t.size),{providerFileId:m.entries?.[0]?.id}}if(e.size!==t.size)throw new $(`File size changed since the upload was requested (${t.size} vs ${e.size}).`,400);let o=await this.retry(n,async()=>{let h=await this.fetch(e.sessionUrl,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify({folder_id:e.folderId,file_size:e.size,file_name:e.fileName}),signal:this.uploadSignal(n)});if(!h.ok&&xt(h.status))throw new $(`Box session failed: ${h.status}`,h.status);return h});if(!o.ok)throw new $(`Box session failed: ${o.status}`,o.status);let s=await o.json(),a=new bi,l=[],u=0;for(;u<t.size;){n.signal?.throwIfAborted();let h=Math.min(u+s.part_size,t.size),p=new Uint8Array(await t.slice(u,h).arrayBuffer());a.update(p);let m=await gs(p),g=await this.retry(n,async()=>{let b=await this.fetch(s.session_endpoints.upload_part,{method:"PUT",headers:{...i,"Content-Type":"application/octet-stream",Digest:`sha=${m}`,"Content-Range":`bytes ${u}-${h-1}/${t.size}`},body:p,signal:this.uploadSignal(n)});if(!b.ok&&xt(b.status))throw new $(`Box part failed: ${b.status}`,b.status);return b});if(!g.ok)throw new $(`Box part failed: ${g.status}`,g.status);l.push((await g.json()).part),u=h,r(u)}let c=await this.retry(n,async()=>{let h=await this.fetch(s.session_endpoints.commit,{method:"POST",headers:{...i,"Content-Type":"application/json",Digest:`sha=${zn(a.digest())}`},body:JSON.stringify({parts:l}),signal:this.uploadSignal(n)});if(!h.ok&&xt(h.status))throw new $(`Box commit failed: ${h.status}`,h.status);return h});if(!c.ok)throw new $(`Box commit failed: ${c.status}`,c.status);return{providerFileId:(await c.json()).entries?.[0]?.id}}uploadSignal(e,t=nt){let n=AbortSignal.timeout(t);return e.signal?AbortSignal.any([e.signal,n]):n}async retry(e,t){let n=0;for(;;)try{return await t()}catch(r){if(e.signal?.aborted||(n+=1,n>=tt))throw r;await new Promise(i=>setTimeout(i,500*2**n))}}async driveUploadLoop(e,t,n,r){let i=e.uploadedBytes,o=kt(n.size,r);o(i);let s=0;for(;i<n.size;){r.signal?.throwIfAborted();let a=i,l=Math.min(i+e.chunkSize,n.size),u=n.slice(i,l),c=0;for(;;)try{let f=await this.fetch(t,{method:"PUT",headers:{"Content-Range":`bytes ${i}-${l-1}/${n.size}`},body:u,signal:this.uploadSignal(r)});if(f.status===308){let h=f.headers.get("Range")??f.headers.get("range"),p=h?.match(/bytes=0-(\d+)/);p?i=Number(p[1])+1:h==null?i=0:i=(await this.getUploadSession(e.id,e.token,this.uploadSignal(r,ue))).uploadedBytes;break}if(f.ok){i=n.size;break}throw new $(`Drive chunk failed: ${f.status}`,f.status)}catch(f){if(r.signal?.aborted||(c+=1,c>=tt))throw f;if(await new Promise(p=>setTimeout(p,500*2**c)),i=(await this.getUploadSession(e.id,e.token,this.uploadSignal(r,ue))).uploadedBytes,i>=n.size)break;l=Math.min(i+e.chunkSize,n.size),u=n.slice(i,l)}if(o(i),i<=a){if(++s>=tt)throw new $("Drive upload stalled \u2014 the storage endpoint stopped accepting progress",0)}else s=0}}async s3MultipartUploadLoop(e,t,n){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 $("S3 upload session returned invalid progress",502);let r=kt(t.size,n),i=e.uploadedBytes;for(r(i);i<t.size;){n.signal?.throwIfAborted();let o=Math.floor(i/e.chunkSize)+1;if(o>1e4)throw new $("S3 upload needs too many parts",413);let s=Math.min(i+e.chunkSize,t.size),a=t.slice(i,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:o}),signal:this.uploadSignal(n,ue)});if(typeof c.uploadUrl!="string"||!c.uploadUrl)throw new $("S3 part URL was unavailable",502);u=c.uploadUrl;let f=await this.fetch(u,{method:"PUT",body:a,signal:this.uploadSignal(n,fs)});if(!f.ok)throw new $(`S3 part upload failed: ${f.status}`,f.status);i=s,r(i);break}catch(c){if(n.signal?.aborted)throw c;let f=await this.getUploadSession(e.id,e.token,this.uploadSignal(n,ue));if(f.status==="aborted")throw new $("This upload session was cancelled",409);if(!Number.isSafeInteger(f.uploadedBytes)||f.uploadedBytes<i||f.uploadedBytes>t.size||f.uploadedBytes<t.size&&f.uploadedBytes%e.chunkSize!==0)throw new $("S3 upload session returned invalid progress",502);if(f.uploadedBytes>i){i=f.uploadedBytes,r(i);break}if(l+=1,l>=tt)throw c;await new Promise(h=>setTimeout(h,500*2**l))}}}}async s3PutUpload(e,t,n){let r=kt(t.size,n);r(0);let i=0;for(;;)try{let o=await this.fetch(e,{method:"PUT",headers:{"Content-Type":t.type||"application/octet-stream"},body:t,signal:this.uploadSignal(n)});if(!o.ok)throw new $(`S3 upload failed: ${o.status}`,o.status);r(t.size);return}catch(o){if(n.signal?.aborted||(i+=1,i>=tt))throw o;await new Promise(s=>setTimeout(s,500*2**i))}}};function Te(e={}){return new Et(e)}function tn(e){let t=e.trim();if(!/^-?\d*\.?\d+$/.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}function Vr(e,t){let n={};for(let r of ze(e)){let i=r.kind==="hidden"?t[r.paramName??r.id]??r.defaultValue:t[r.id];if(!(i===void 0||i===""))switch(r.kind){case"number":{let o=tn(i);if(o===null||r.min!==void 0&&o<r.min||r.max!==void 0&&o>r.max)break;n[r.id]=o;break}case"rating":{let o=tn(i);o!==null&&Number.isInteger(o)&&o>=1&&o<=(r.max??5)&&(n[r.id]=o);break}case"linear_scale":{let o=tn(i),s=r.min??1,a=r.max??10;o!==null&&Number.isInteger(o)&&o>=s&&o<=a&&(n[r.id]=o);break}case"checkbox":n[r.id]=i==="true"||i==="1"||i==="yes";break;case"select":case"dropdown":{r.options.some(o=>o.id===i)&&(n[r.id]=i);break}case"multi_select":{let o=new Set(r.options.map(a=>a.id)),s=[...new Set(i.split(",").filter(a=>o.has(a)))];s.length>0&&(n[r.id]=s);break}case"file_upload":case"ranking":case"matrix":case"signature":case"custom":break;case"calculated":break;default:n[r.id]=i}}return n}var vs={id:"empty",blocks:[]},Hr=!1,qr=!1;function ys(){qr||(qr=!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 ws(){Hr||(Hr=!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 vi=new Map;function Sn(){try{return globalThis.localStorage??null}catch{return null}}function yi(e){return`fillo:submission:${e}`}function En(){let e=globalThis.crypto;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);return e?.getRandomValues?(e.getRandomValues(t),Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")):`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function wi(e,t,n,r){let i=Sn();if(!i)return e.get(n)??null;try{let o=JSON.parse(i.getItem(t)??"null");if(o&&r(o))return o}catch{}return null}function _i(e,t,n,r){e.set(n,r);let i=Sn();if(i)try{i.setItem(t,JSON.stringify(r))}catch{}}function An(e){return wi(vi,yi(e),e,t=>typeof t.key=="string")}function xi(e,t){_i(vi,yi(e),e,t)}function _s(e){let t=An(e);if(t?.key)return t.key;let n={key:En()};return xi(e,n),n.key}function xs(e,t){let n=An(e);xi(e,{key:n?.key??En(),submittedAt:new Date().toISOString(),responseId:t})}function gn(e,t,n){let r=ei(e.settings,n);return r===null?t:`${t}::${r}`}function Wr(e,t,n){return e.settings.responseLimit?.by!=="browser"||!t?!1:!!An(gn(e,t,n))?.submittedAt}var Cn=new Map;function Fn(e){return`fillo:draft:${e}`}function $t(e){return wi(Cn,Fn(e),e,t=>{let n=t;return typeof n.id=="string"&&typeof n.token=="string"})}function nn(e,t){_i(Cn,Fn(e),e,t)}function rn(e){Cn.delete(e);let t=Sn();if(t)try{t.removeItem(Fn(e))}catch{}}function on(e){return X(e)&&(e.status===401||e.status===403||e.status===404)}var ks=1500,$s="Please complete the verification check, then submit.",zs="That verification didn't go through. Please complete the check again and resubmit.";function ki(e){return X(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 Ss(e,t){if(X(e)){let n=e.status??0;if(t&&n>0&&e.message)return e.code?`${e.message} (${e.code})`:e.message;if(n>0&&n<500&&n!==408&&n!==429)return"This form is unavailable."}return ki(e)}function $i(e){let{onChange:t,onSubmitted:n}=e,r=Ne(e.form);if(!r.ok)throw new Error(`Invalid form schema: ${r.error}`);let i=r.schema,o=e.formId,s=e.client,a=e.respondent,l=Re(i,{...e.initialData??{}}),u={},c=0,f="idle",h=!1,p=!1;queueMicrotask(()=>{if(typeof location<"u"&&location.search){let _=Object.fromEntries(new URLSearchParams(location.search)),w=null;for(let[k,I]of Object.entries(Vr(i,_)))l[k]===void 0&&(w=w??{...l},w[k]=I);w&&f==="idle"&&(l=Re(i,w),S())}f==="idle"&&Wr(i,o,l)&&(f="submitted",h=!0,S());let v=!1;if(i.settings.saveProgress&&o&&s&&typeof location<"u"&&location.hash.includes("fillo-draft=")){let _=/fillo-draft=([^&]+)/.exec(location.hash),w=_?.[1]?decodeURIComponent(_[1]):"",k=w.indexOf(".");if(k>0){v=!0;let I=w.slice(0,k),A=w.slice(k+1);s.getDraft(I,A,!0).then(N=>{nn(o,{id:I,token:N.token??A});try{history.replaceState(null,"",location.pathname+location.search)}catch{}}).catch(N=>{on(N)&&(p=!0,S())}).finally(()=>Q())}}v||Q()});let m,g=new Set,b=new Set,z=Date.now(),T=En(),F=null,ie=!1,oe=!1,Se=!1,Y="created",Ee=!1,R=null,U=null,se=Promise.resolve(),ae=!1,qe=!1,Pe=!1,x=!1;function re(){let v=i.pages.length,_=Math.min(c,Math.max(v-1,0)),w=i.pages[_]??vs;return{data:l,errors:u,status:f,pageIndex:_,pageCount:v,page:w,blocks:vt(i,w,l),isFirstPage:_===0,isLastPage:dn(i,w.id,l),uploading:g.size>0,submitError:m,restoredSubmission:h,resumedDraft:oe,editingPrevious:Se,duplicateSubmission:Y==="duplicate",updatedSubmission:Y==="updated",resumeLinkFailed:p}}let O=re();function S(){O=re();for(let v of b)v()}function Le(v,_){try{n?.(v,_)}catch(w){console.error("[fillo] onSubmitted handler threw:",w)}}function Me(v){let _=i.pages[v];if(!_)return{};let w={};for(let k of vt(i,_,l)){if(!J(k))continue;let I=ui(k,l[k.id]);I&&(w[k.id]=I)}return w}function Ae(){return!!(i.settings.saveProgress&&s&&o&&!qe)}function L(){let v=new Set;for(let _ of i.pages)for(let w of _.blocks)J(w)&&v.add(w.id);return v}function H(v){if(f!=="idle"||ie)return;let _=L(),w=null;for(let[A,N]of Object.entries(v.data??{}))l[A]===void 0&&_.has(A)&&(w=w??{...l},w[A]=N);let k=typeof v.page=="number"&&Number.isFinite(v.page)?Math.max(0,Math.min(Math.floor(v.page),i.pages.length-1)):0,I=k>0&&c===0;!w&&!I||(w&&(l=Re(i,w)),I&&(c=k),oe=!0,S())}function Q(){if(f!=="idle")return;if(!Ae()){ge();return}let v=o,_=s,w=R??$t(v);if(w&&!Pe){Pe=!0,R=w,_.getDraft(w.id,w.token).then(H).catch(k=>{on(k)&&(rn(v),R=null)});return}!w&&!x&&a?.hash&&(x=!0,_.createDraft(v,{data:{},page:0,respondent:a}).then(k=>{if(!R){if(R={id:k.id,token:k.token},nn(v,R),k.existing)return _.getDraft(k.id,k.token).then(H);ge()}}).catch(k=>{X(k)&&k.status!==void 0&&k.status>=400&&k.status<500||(x=!1)}))}function ge(){if(Ee||i.settings.responseLimit?.onRepeat!=="update"||!s||!o||!a?.hash||f!=="idle")return;Ee=!0;let v=s,_=ei(i.settings,l)??void 0;v.fetchOwnResponse(o,a,_).then(w=>{!w||f!=="idle"||ie||oe||(H({data:w.data,page:0}),oe&&(oe=!1,Se=!0,S()))}).catch(()=>{})}function Nt(v=!1){if(U&&(clearTimeout(U),U=null),!Ae()||f!=="idle"||!ae)return;let _=o,w=s;ae=!1,se=se.then(async()=>{let k={data:l,page:Math.max(0,Math.min(c,i.pages.length-1))},I=R??$t(_);try{if(I)try{await w.saveDraft(I.id,I.token,k,v?{keepalive:!0}:void 0),R=I;return}catch(N){if(!on(N))throw N;rn(_),R=null}let A=await w.createDraft(_,a?.hash?{...k,respondent:a}:k);R={id:A.id,token:A.token},nn(_,R),A.existing&&(ae=!0)}catch(A){X(A)&&A.status!==void 0&&A.status>=400&&A.status<500&&A.status!==429?qe=!0:ae=!0}})}function Wi(){!Ae()||f!=="idle"||(ae=!0,U&&clearTimeout(U),U=setTimeout(()=>{U=null,Nt()},ks))}function Rn(){!Ae()||!ie&&!R||(ae=!0,Nt())}function Dn(){U&&(clearTimeout(U),U=null),ae=!1,o&&rn(o),R=null}function Ki(v,_){!ie&&s&&o&&(ie=!0,s.startSession(o,i.pages.length).then(w=>F=w)),l=Re(i,{...l,[v]:_}),t?.(l),m=void 0,v in u&&(u=Object.fromEntries(Object.entries(u).filter(([w])=>w!==v))),S(),Wi()}function Gi(v,_){_?g.add(v):g.delete(v),S()}function Un(v){if(v.length===0)return-1;let _=i.pages.length,w=Math.min(c,Math.max(_-1,0)),k=i.pages[w]?.id,I=k===void 0?-1:v.indexOf(k);if(I>=0)return I;let A=0;for(let N=0;N<v.length;N++){let pe=i.pages.findIndex(Tt=>Tt.id===v[N]);pe>=0&&pe<=w&&(A=N)}return A}function Ji(){let v=i.pages.length,_=Math.min(c,Math.max(v-1,0));if(!e.skipValidation){let pe=Me(_);if(u=pe,Object.keys(pe).length>0){S();return}}let w=i.pages[_],k=Be(i,l),I=Un(k);if((w?dn(i,w.id,l):!0)||I<0||I+1>=k.length){Bn();return}let N=i.pages.findIndex(pe=>pe.id===k[I+1]);c=N>=0?N:Math.min(_+1,v-1),F&&s&&s.reportProgress(F,{furthestPage:c}),S(),Rn()}function Xi(){u={};let v=Be(i,l),_=Un(v);if(_>0){let w=i.pages.findIndex(k=>k.id===v[_-1]);c=w>=0?w:Math.max(Math.min(c,i.pages.length-1)-1,0)}else if(v.length>0){let w=i.pages.findIndex(k=>k.id===v[0]);c=w>=0?w:0}S(),Rn()}async function Bn(){if(f==="submitting"||f==="submitted")return;let v=ci(i,l);if(!v.ok){let _=e.skipValidation&&!(s&&o),w=_?Object.fromEntries(Object.entries(v.errors).filter(([I])=>i.pages.every(A=>A.blocks.every(N=>!(J(N)&&N.id===I&&N.kind==="file_upload"))))):v.errors;if(_&&Object.keys(w).length===0){u={},f="submitted",S(),Le(void 0,l);return}u=w;let k=i.pages.findIndex(I=>vt(i,I,l).some(A=>A.id in w));k>=0&&(c=k),S();return}if(s&&e.resolveFormId){f="submitting",m=void 0,S();try{o=await e.resolveFormId()}catch(_){throw f="idle",m=Ss(_,e.verboseResolutionErrors===!0),S(),_}}if(s&&o){let _=i.settings.responseLimit?.by==="browser"?_s(gn(i,o,v.data)):void 0,w=_??T,k=i.settings.saveProgress?R??$t(o):null,I=e.challengeRequired?e.getChallengeToken?.():void 0;if(e.challengeRequired&&!I){f="idle",m=$s,S();return}f="submitting",m=void 0,S();let A;try{A=await s.submit(o,v.data,{hp:e.getHoneypot?.()??"",elapsedMs:Date.now()-z,surface:e.surface??"headless",submissionKey:w,draft:k?{id:k.id,token:k.token}:void 0,respondent:a,challengeToken:I})}catch(N){if(f="idle",X(N)&&N.code==="challenge_failed"){m=zs,e.onChallengeFailed?.(),S();return}throw m=ki(N),S(),N}if(!A.ok){u=A.errors??{};let N=i.pages.findIndex(pe=>vt(i,pe,l).some(Tt=>Tt.id in u));N>=0?c=N:m="We couldn't submit \u2014 please review your answers.",f="idle",S();return}Y=A.duplicate?"duplicate":A.updated?"updated":"created",F&&s.reportProgress(F,{completed:!0}),_&&xs(gn(i,o,v.data),A.responseId),Dn(),f="submitted",S(),Le(A.responseId,v.data);return}if(e.skipValidation){f="submitted",S(),Le(void 0,v.data);return}s&&!o?ys():ws(),f="error",S()}return{getState:()=>O,subscribe(v){return b.add(v),()=>{b.delete(v)}},setValue:Ki,setUploading:Gi,next:Ji,back:Xi,submit:Bn,setContext(v){if("formId"in v&&(o=v.formId),"client"in v&&(s=v.client),"respondent"in v&&(a=v.respondent),v.form&&v.form!==i){let _=Ne(v.form);if(!_.ok)throw new Error(`Invalid form schema: ${_.error}`);i=_.schema,l=Re(i,l)}f==="idle"&&Wr(i,o,l)&&(f="submitted",h=!0),Q(),S()},flushDraft(){Nt(!0)},resetDraft(){if(f==="submitting")return;let v=R??(o?$t(o):null);if(Dn(),v&&s&&s.deleteDraft(v.id,v.token).catch(()=>{}),l={...e.initialData??{}},typeof location<"u"&&location.search){let _=Object.fromEntries(new URLSearchParams(location.search));for(let[w,k]of Object.entries(Vr(i,_)))l[w]===void 0&&(l[w]=k)}l=Re(i,l),u={},c=0,m=void 0,oe=!1,Se=!1,S()},destroy(){U&&(clearTimeout(U),U=null),b.clear()}}}function Es(e){return J(e)&&(e.kind==="select"||e.kind==="dropdown"||e.kind==="checkbox"||e.kind==="rating"||e.kind==="linear_scale")}function zi(e){let t=e.filter(n=>J(n)&&n.kind!=="hidden"&&n.kind!=="calculated");return t.length!==1?!0:!Es(t[0])}function Si(e,t,n){if(n.form.settings.submitMode!=="auto"||n.status!=="idle"||n.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===n.data[e.id])return!1;let i={...n.data,[e.id]:t},o=n.form.pages.find(a=>a.blocks.some(l=>l.id===e.id));if(!o||!dn(n.form,o.id,i))return!1;let s=ri(n.form,i).filter(a=>a.kind!=="hidden"&&a.kind!=="calculated");return s.length!==1||s[0]?.id!==e.id?!1:ci(n.form,i).ok}function Ei(e,t,n,r){if(n<=0)return null;let i=r?.rtl??!1;if(e==="Home")return 0;if(e==="End")return n-1;let o;switch(e){case"ArrowRight":o=i?-1:1;break;case"ArrowLeft":o=i?1:-1;break;case"ArrowDown":o=1;break;case"ArrowUp":o=-1;break;default:return null}let s=t+o;return Math.min(n-1,Math.max(0,s))}var As=Math.sqrt(1.05*.05)-.05,Cs=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i,Fs=/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i;function sn(e){let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function Is(e){let t=e.trim(),n=null,r=Cs.exec(t);if(r)n=`${r[1]}${r[2]}${r[3]}`;else{let a=Fs.exec(t);a&&(n=`${a[1]}${a[1]}${a[2]}${a[2]}${a[3]}${a[3]}`)}if(!n)return null;let i=parseInt(n.slice(0,2),16),o=parseInt(n.slice(2,4),16),s=parseInt(n.slice(4,6),16);return .2126*sn(i)+.7152*sn(o)+.0722*sn(s)}function Ai(e){if(!e||e.colorScheme||!e.background||!e.text)return e;let t=Is(e.background);return t==null?e:{...e,colorScheme:t>As?"light":"dark"}}function In(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 Nn(e){return typeof e=="object"&&e!==null&&"__filloCodeForm"in e}var xe=new Map,Ns=e=>new Promise(t=>setTimeout(t,e));function Ts(e){if(!X(e))return!0;let t=e.status??0;return t===0||t===408||t===429||t>=500}async function Ps(e,t){let n=800;for(let r=0;;r++)try{return await e.syncForm(t.id,t.schema,t.theme??null)}catch(i){if(!Ts(i)||r>=2)throw i;let o=X(i)?i.retryAfterSec:void 0;await Ns(Math.min(o?o*1e3:n*(1+Math.random()*.5),15e3)),n*=2}}function Ls(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function Ci(e,t){let n=r=>{if(Array.isArray(r))return r.map(n);if(r&&typeof r=="object"){let i=r;return Object.fromEntries(Object.keys(i).sort().map(o=>[o,n(i[o])]))}return r};return JSON.stringify(n(e))===JSON.stringify(n(t))}var bn=e=>e==="published"?36e5:6e4,Ms=e=>!!(e.staged||e.resolvedSchema||e.syncError||e.accepting===!1||e.uploadsAvailable===!1);function Fi(e,t){return`fillo:sync:v4:${e.baseUrl}|${e.key}|${t}`}function Zs(e,t,n){try{let r=globalThis.localStorage?.getItem(Fi(e,t));if(!r)return null;let i=JSON.parse(r);if(typeof i.formId!="string"||typeof i.slug!="string"||i.hash!==n||typeof i.ts!="number"||i.uploadFileSizeLimitMb!==void 0&&(typeof i.uploadFileSizeLimitMb!="number"||!Number.isFinite(i.uploadFileSizeLimitMb)||i.uploadFileSizeLimitMb<=0)||i.status!==void 0&&i.status!=="draft"&&i.status!=="published")return null;let o=bn(i.status);return Date.now()-i.ts>o?null:i}catch{return null}}function Os(e,t,n,r){if(!(r.staged||r.resolvedSchema||r.syncError||r.accepting===!1)&&!r.challenge)try{globalThis.localStorage?.setItem(Fi(e,t),JSON.stringify({formId:r.formId,slug:r.slug,status:r.status,uploadFileSizeLimitMb:r.uploadFileSizeLimitMb,hash:n,ts:Date.now()}))}catch{}}function Tn(e,t,n){let r=JSON.stringify(t.schema)+JSON.stringify(t.theme??null),i=Ls(r),o=`${e.baseUrl}:${e.key}:${t.id}:${i}`,s=xe.get(o);if(s&&!n?.bypassCache){if(s.expiresAt===null||s.expiresAt>Date.now())return s.promise;xe.delete(o)}if(!n?.bypassCache){let u=Zs(e,t.id,i);if(u){let c=Promise.resolve({formId:u.formId,slug:u.slug,status:u.status,uploadFileSizeLimitMb:u.uploadFileSizeLimitMb});return xe.set(o,{promise:c,expiresAt:u.ts+bn(u.status)}),c}}let a=Ps(e,t),l={promise:a,expiresAt:null};return xe.set(o,l),a.then(u=>{if(xe.get(o)===l){if(Ms(u)){xe.delete(o);return}l.expiresAt=Date.now()+bn(u.status),Os(e,t.id,i,u)}},()=>{xe.get(o)===l&&xe.delete(o)}),a}var Rs=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},Ds=Symbol.for("fillo.block");var Us=["label","description","required","placeholder"],Z=(e,t,n,r={})=>({name:e,kind:t,props:[...Us,...n],...r}),Kr=(e,t,n)=>({name:e,kind:t,props:n?["text"]:[],textChildren:n,content:!0}),an=["options","allowOther","shuffleOptions"],Bs=[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","decimals","prefix","suffix","notation"]),Z("Select","select",an,{optionChildren:!0}),Z("MultiSelect","multi_select",an,{optionChildren:!0}),Z("Dropdown","dropdown",an,{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("Calculated","calculated",["calc","decimals","prefix","suffix"]),Z("Custom","custom",["component","config"]),Kr("Heading","heading",!0),Kr("Paragraph","paragraph",!0),{name:"Divider",kind:"divider",props:[],content:!0}],js={name:"Page",kind:"__page",props:["title"]},Vs={name:"Option",kind:"__option",props:["label","icon"]};function ln(e){let t=()=>{throw new Rs("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[Ds]=e,t}var vd=Object.fromEntries([...Bs.map(e=>[e.name,ln(e)]),["Page",ln(js)],["Option",ln(Vs)]]);function Hs(e){let t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)||t==="::1"||t==="[::1]"||t==="0.0.0.0"}function Pn(){return typeof process<"u"&&process.env?.NODE_ENV!=="production"}function Ii(){if(Pn())return!0;if(typeof window>"u")return!1;let e=window.location?.hostname;return typeof e=="string"&&Hs(e)}var qs=/\{\{\s*([\w-]+)\s*\}\}/g;function un(e,t,n){if(!e.includes("{{"))return e;let r=ze(n);return e.replace(qs,(i,o)=>{let s=r.find(u=>u.id===o),a=t[o];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 Ni(e,t,n){let r=i=>i===void 0?i:un(i,t,n);switch(e.kind){case"heading":case"paragraph":return{...e,text:un(e.text,t,n)};case"divider":return e;default:return{...e,label:un(e.label,t,n),description:r(e.description)}}}var Ws="fillo-",Ks=0,Ct='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Ti(e){return e.matches(Ct)?e:e.querySelector(Ct)}function Pi(e,t){let n=`${Ws}${e}-${t}`;return{inputId:n,labelId:`${n}-label`,descriptionId:`${n}-desc`,errorId:`${n}-error`,name:n}}function d(e,t={}){let n=document.createElement(e);t.className&&(n.className=t.className),t.text!==void 0&&(n.textContent=t.text);for(let[r,i]of Object.entries(t.attrs??{}))n.setAttribute(r,i);return n}function Ve(e,t){let n=Ai(kn(t));n&&(n.colorScheme&&e.setAttribute("data-fillo-color-scheme",n.colorScheme),n.primary&&e.style.setProperty("--fillo-primary",n.primary),n.background&&e.style.setProperty("--fillo-bg",n.background),n.text&&e.style.setProperty("--fillo-text",n.text),n.radius&&e.style.setProperty("--fillo-radius",n.radius),n.fontFamily&&e.style.setProperty("--fillo-font",n.fontFamily),(n.primary||n.background||n.text)&&e.setAttribute("data-fillo-has-color-theme",""))}function ct(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 Gs(e){let t=new URL(ct(e)??"https://fillo.so");return t.searchParams.set("utm_source","form_badge"),t.toString()}function Ft(e){return typeof e=="string"||typeof e=="number"?String(e):""}function Li(e,t,n){let r=Ft(e);if(r==="")return r;let i=Number(r);return Number.isFinite(i)?mi(i,{locale:n,decimals:t}):r}function C(e,t){for(let n of t)n&&e.appendChild(n);return e}var Mi="http://www.w3.org/2000/svg",Js={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 Vi(e){if(!e)return null;let t=document.createElementNS(Mi,"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 n=document.createElementNS(Mi,"path");return n.setAttribute("d",Js[e]),t.appendChild(n),t}function K(e,t,n,r,i={}){n&&e.setAttribute("aria-invalid","true"),(i.requiredSupported??!0)&&t.required&&e.setAttribute("aria-required","true");let o=[t.description?r.descriptionId:null,n?r.errorId:null].filter(Boolean).join(" ");o&&e.setAttribute("aria-describedby",o)}function Hi(e,t,n,r){e.addEventListener("keydown",i=>{let o=getComputedStyle(e).direction==="rtl",s=n===null?-1:t.indexOf(n),a=Ei(i.key,s,t.length,{rtl:o});if(a===null)return;i.preventDefault();let l=t[a];l!==void 0&&(r(l),e.querySelectorAll('[role="radio"]')[a]?.focus())})}function ne(e,t,n,r){let i=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}});i.toggleAttribute("data-invalid",!!t),i.toggleAttribute("data-required",!!e.required);let o=d("label",{className:"fillo-label",text:e.label,attrs:{id:r.labelId,for:r.inputId,"data-fillo":"label"}});return e.required||o.appendChild(d("span",{className:"fillo-optional",text:" (optional)"})),i.appendChild(o),e.description&&i.appendChild(d("p",{className:"fillo-description",text:e.description,attrs:{id:r.descriptionId,"data-fillo":"fieldDescription"}})),i.appendChild(n),t&&i.appendChild(d("p",{className:"fillo-error",text:t,attrs:{id:r.errorId,"data-fillo":"error"}})),i}function at(e,t){let n=t.field,r=n.kind==="number"?n:void 0,i=r?.notation!==void 0,o=hi(r?.notation),s=i||!!r?.prefix||!!r?.suffix,a=d("input",{className:"fillo-input",attrs:{id:t.ids.inputId,type:s?"text":e,"data-fillo":"control"}});if(s&&a.setAttribute("inputmode","decimal"),e==="email"?a.setAttribute("autocomplete","email"):e==="url"&&a.setAttribute("autocomplete","url"),a.value=i?Li(t.value,r?.decimals,o):Ft(t.value),n.placeholder&&(a.placeholder=n.placeholder),"maxLength"in n&&n.maxLength!==void 0&&(a.maxLength=n.maxLength),r&&!s&&(r.min!==void 0&&(a.min=String(r.min)),r.max!==void 0&&(a.max=String(r.max))),s){let u=a.value,c=a.value.length,f=()=>{a.value=u,a.setSelectionRange(c,c)};i?(a.addEventListener("input",()=>{if(!st(a.value,o))return f();u=a.value,c=a.selectionStart??a.value.length,t.setValue($n(a.value,o),{render:!1})}),a.addEventListener("change",()=>{if(!st(a.value,o))return f();u=a.value,t.setValue($n(a.value,o))}),a.addEventListener("blur",()=>{let h=t.getValue?.()??t.value;a.value=Li(h,r?.decimals,o),u=a.value,c=a.value.length})):(a.addEventListener("input",()=>{if(!st(a.value,o))return f();u=a.value,c=a.selectionStart??a.value.length,t.setValue(a.value,{render:!1})}),a.addEventListener("change",()=>{if(!st(a.value,o))return f();u=a.value,t.setValue(a.value)}))}else a.addEventListener("input",()=>t.setValue(a.value,{render:!1})),a.addEventListener("change",()=>t.setValue(a.value));K(a,n,t.error,t.ids);let l=a;return r&&(r.prefix||r.suffix)&&(l=C(d("div",{className:"fillo-number"}),[r.prefix?d("span",{className:"fillo-number-prefix",text:r.prefix}):null,a,r.suffix?d("span",{className:"fillo-number-suffix",text:r.suffix}):null])),ne(n,t.error,l,t.ids)}function Xs(){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 Ys(){if(!(typeof Intl>"u"))try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof e=="string"&&e?e:void 0}catch{return}}function Qs(e,t){if(t<=0)return e.setSelectionRange(0,0);let n=e.value,r=0,i=n.length;for(let o=0;o<n.length;o++)if(/\d/.test(n[o])&&++r===t){i=o+1;break}e.setSelectionRange(i,i)}function ea(e){let t=e.field,n=ot(Ft(e.value)).country??St(t.defaultCountry)??oi(Ys())??St(Xs())??rt[0],r=d("div",{className:"fillo-phone"}),i=d("div",{className:"fillo-phone-country"}),o=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"});C(o,[s,a,d("span",{className:"fillo-phone-caret",text:"\u25BE",attrs:{"aria-hidden":"true"}})]),C(i,[o]);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"}});K(l,e.field,e.error,e.ids);let u=()=>e.getValue?.()??e.value,c=()=>{let x=de(Ft(u()));return x.startsWith(n.dialCode)?x.slice(n.dialCode.length):x},f=()=>{s.textContent=wn(n.iso2),a.textContent=`+${n.dialCode}`,o.setAttribute("aria-label",`Country: ${n.name} (+${n.dialCode})`)},h=()=>{l.value=it(n,c()),l.placeholder=it(n,n.example)},p=x=>e.setValue(x?si(n,x):"",{render:!1}),m=x=>e.setValue(x,{render:!1});f(),h(),l.addEventListener("input",()=>{let x=l.value,re=l.selectionStart??x.length,O=de(x.slice(0,re)).length;if(x.trimStart().startsWith("+")){let S=ot(x,n,{previousDigits:c()});if(S.pending){m(S.raw??x);return}S.country&&(n=S.country,f()),p(S.country?S.national:de(x))}else p(de(x));l.value=it(n,c()),Qs(l,O)});let g=e.registerOverlay,b=e.announce,z=null,T=0,F=je,ie=null,oe=null,Se,Y=`${e.ids.inputId}-countries`,Ee=()=>{if(!z)return;let x=ai(i,z);z.classList.toggle("fillo-phone-popover--above",x==="above"),z.classList.toggle("fillo-phone-popover--below",x==="below")},R=()=>{ie?.();let x=()=>Ee();Ee(),window.addEventListener("resize",x),window.addEventListener("scroll",x,!0),ie=()=>{window.removeEventListener("resize",x),window.removeEventListener("scroll",x,!0)}},U=x=>{let re=x.relatedTarget;if(re){i.contains(re)||se();return}queueMicrotask(()=>{z&&!i.contains(document.activeElement)&&se()})},se=()=>{clearTimeout(Se),ie?.(),ie=null,z?.remove(),z=null,o.setAttribute("aria-expanded","false"),o.removeAttribute("aria-controls"),document.removeEventListener("mousedown",ae),i.removeEventListener("focusout",U),oe?.(),oe=null},ae=x=>{i.contains(x.target)||se()},qe=x=>{x&&(n=x,f(),p(c()),h(),se(),b?.(B.phoneCountrySelected(x.name)),l.focus())},Pe=x=>{let re=d("div",{className:"fillo-phone-popover fillo-phone-popover--below"}),O=d("input",{className:"fillo-phone-search",attrs:{type:"text",role:"combobox","aria-expanded":"true","aria-controls":Y,"aria-autocomplete":"list","aria-label":"Search country or code",placeholder:"Search country or code"}});x&&(O.value=x);let S=d("ul",{className:"fillo-phone-list",attrs:{role:"listbox",id:Y,"aria-label":"Country"}}),Le=()=>{if(S.replaceChildren(),F.length===0){S.appendChild(d("li",{className:"fillo-phone-empty",text:"No matches",attrs:{role:"option","aria-disabled":"true"}})),O.removeAttribute("aria-activedescendant"),Ee();return}F.forEach((L,H)=>{let Q=d("li",{className:`fillo-phone-option${H===T?" fillo-phone-option--active":""}`,attrs:{id:`${Y}-opt-${H}`,role:"option","aria-selected":String(L.iso2===n.iso2)}});C(Q,[d("span",{className:"fillo-phone-flag-emoji",text:wn(L.iso2),attrs:{"aria-hidden":"true"}}),d("span",{className:"fillo-phone-option-name",text:L.name}),d("span",{className:"fillo-phone-option-dial",text:`+${L.dialCode}`})]),Q.addEventListener("mouseenter",()=>{T=H,O.setAttribute("aria-activedescendant",Q.id),Me()}),Q.addEventListener("mousedown",ge=>{ge.preventDefault(),qe(L)}),S.appendChild(Q)}),O.setAttribute("aria-activedescendant",`${Y}-opt-${T}`),Ee()},Me=()=>{[...S.children].forEach((L,H)=>L.classList.toggle("fillo-phone-option--active",H===T)),document.getElementById(`${Y}-opt-${T}`)?.scrollIntoView({block:"nearest"})},Ae=L=>{let H=L.trim().toLowerCase(),Q=H.replace(/[^\d]/g,"");F=H?je.filter(ge=>ge.name.toLowerCase().includes(H)||ge.iso2.toLowerCase()===H||Q.length>0&&ge.dialCode.startsWith(Q)):je,T=0,Le(),clearTimeout(Se),Se=setTimeout(()=>b?.(B.phoneResultsCount(F.length)),300)};O.addEventListener("input",()=>Ae(O.value)),O.addEventListener("keydown",L=>{if(L.key==="ArrowDown"){if(L.preventDefault(),F.length===0)return;T=Math.min(T+1,F.length-1),Me(),O.setAttribute("aria-activedescendant",`${Y}-opt-${T}`)}else if(L.key==="ArrowUp"){if(L.preventDefault(),F.length===0)return;T=Math.max(T-1,0),Me(),O.setAttribute("aria-activedescendant",`${Y}-opt-${T}`)}else L.key==="Enter"?(L.preventDefault(),qe(F[T])):L.key==="Escape"&&(L.preventDefault(),se(),o.focus())}),C(re,[O,S]),z=re,i.appendChild(re),o.setAttribute("aria-expanded","true"),o.setAttribute("aria-controls",Y),x?Ae(x):(F=je,T=Math.max(0,je.indexOf(n)),Le()),R(),Me(),document.addEventListener("mousedown",ae),i.addEventListener("focusout",U),oe=g?.(se)??null,requestAnimationFrame(()=>{if(O.focus(),x){let L=O.value.length;O.setSelectionRange(L,L)}})};return o.addEventListener("click",()=>z?se():Pe()),o.addEventListener("keydown",x=>{if(!z){if(x.key==="ArrowDown"||x.key==="ArrowUp"){x.preventDefault(),Pe();return}x.key.length===1&&x.key!==" "&&!x.ctrlKey&&!x.metaKey&&!x.altKey&&(x.preventDefault(),Pe(x.key))}}),C(r,[i,l]),ne(e.field,e.error,r,e.ids)}function ta(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)),K(t,e.field,e.error,e.ids),ne(e.field,e.error,t,e.ids)}function na(e){let t=e.field,n=Zn(t),r=typeof e.value=="string"?e.value:"",i=e.activeOtherFields,o=r!==""&&!t.options.some(l=>l.id===r),s=o||r===""&&i?.has(t.id)===!0,a=d("div",{className:"fillo-options",attrs:{role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"options"}});K(a,t,e.error,e.ids);for(let l of n){let u=d("label",{className:`fillo-option${l.icon?" fillo-option--has-icon":""}${r===l.id?" fillo-option--selected":""}`,attrs:{"data-option":l.id,"data-fillo":"option"}});u.toggleAttribute("data-selected",r===l.id);let c=d("input",{className:"fillo-option-input",attrs:{type:"radio",name:e.ids.name}});c.checked=r===l.id,c.addEventListener("change",()=>{i?.delete(t.id),e.setValue(l.id)}),C(u,[c,Vi(l.icon),d("span",{className:"fillo-option-label",text:l.label,attrs:{"data-fillo":"optionLabel"}}),l.icon&&r===l.id?d("span",{className:"fillo-option-check",text:"\u2713",attrs:{"aria-hidden":"true"}}):null]),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",()=>{i?.add(t.id),e.setValue("",{render:!0})}),C(l,[C(d("span",{className:"fillo-option-main"}),[u,d("span",{className:"fillo-option-label",text:P.other,attrs:{"data-fillo":"optionLabel"}})])]),s){let c=d("input",{className:"fillo-input fillo-other-input",attrs:{type:"text","aria-label":P.otherPrompt}});c.value=o?r:"",c.placeholder=P.otherPlaceholder,c.addEventListener("input",()=>{i?.add(t.id),e.setValue(c.value,{render:!1})}),c.addEventListener("change",()=>{i?.add(t.id),e.setValue(c.value)}),l.appendChild(c),o||queueMicrotask(()=>c.focus())}a.appendChild(l)}return ne(t,e.error,a,e.ids)}function ra(e){let t=e.field,n=Zn(t),r=Array.isArray(e.value)?e.value:[],i=new Set(t.options.map(c=>c.id)),o=r.find(c=>!i.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"}});K(l,t,e.error,e.ids,{requiredSupported:!1});let u=c=>e.setValue(c);for(let c of n){let f=d("label",{className:`fillo-option${c.icon?" fillo-option--has-icon":""}${r.includes(c.id)?" fillo-option--selected":""}`,attrs:{"data-option":c.id,"data-fillo":"option"}});f.toggleAttribute("data-selected",r.includes(c.id));let h=d("input",{className:"fillo-option-input",attrs:{type:"checkbox"}});h.checked=r.includes(c.id),h.addEventListener("change",()=>{let p=a();u(h.checked?[...p,c.id]:p.filter(m=>m!==c.id))}),C(f,[h,Vi(c.icon),d("span",{className:"fillo-option-label",text:c.label,attrs:{"data-fillo":"optionLabel"}}),c.icon&&r.includes(c.id)?d("span",{className:"fillo-option-check",text:"\u2713",attrs:{"aria-hidden":"true"}}):null]),l.appendChild(f)}if(t.allowOther){let c=o!==void 0||s?.has(t.id)===!0,f=d("label",{className:`fillo-option fillo-option--other${c?" fillo-option--selected fillo-option--with-other":""}`,attrs:{"data-fillo":"option"}});f.toggleAttribute("data-selected",c);let h=d("input",{className:"fillo-option-input",attrs:{type:"checkbox"}});if(h.checked=c,h.addEventListener("change",()=>{let p=a().filter(m=>i.has(m));h.checked?(s?.add(t.id),u(p)):(s?.delete(t.id),u(p))}),C(f,[C(d("span",{className:"fillo-option-main"}),[h,d("span",{className:"fillo-option-label",text:P.other,attrs:{"data-fillo":"optionLabel"}})])]),c){let p=d("input",{className:"fillo-input fillo-other-input",attrs:{type:"text","aria-label":P.otherPrompt}});p.value=o??"",p.placeholder=P.otherPlaceholder,p.addEventListener("input",()=>{s?.add(t.id);let m=a().filter(g=>i.has(g));e.setValue(p.value?[...m,p.value]:m,{render:!1})}),p.addEventListener("change",()=>{s?.add(t.id);let m=a().filter(g=>i.has(g));e.setValue(p.value?[...m,p.value]:m)}),f.appendChild(p),o===void 0&&queueMicrotask(()=>p.focus())}l.appendChild(f)}return ne(t,e.error,l,e.ids)}function ia(e){let t="__fillo_other__",n=new Set(e.options.map(r=>r.id));for(;n.has(t);)t+="_";return t}function oa(e){let t=e.field,n=typeof e.value=="string"?e.value:"",r=ia(t),i=e.activeOtherFields,o=n!==""&&!t.options.some(c=>c.id===n),s=o||n===""&&i?.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 Zn(t))u.appendChild(d("option",{text:c.label,attrs:{value:c.id}}));if(t.allowOther&&u.appendChild(d("option",{text:`${P.other}\u2026`,attrs:{value:r}})),u.value=s?r:n,u.addEventListener("change",()=>{u.value===r?(i?.add(t.id),e.setValue("",{render:!0})):(i?.delete(t.id),e.setValue(u.value||null))}),K(u,t,e.error,e.ids),C(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","aria-label":P.otherPrompt}});c.value=o?n:"",c.placeholder=P.otherPlaceholder,c.addEventListener("input",()=>{i?.add(t.id),e.setValue(c.value,{render:!1})}),c.addEventListener("change",()=>{i?.add(t.id),e.setValue(c.value)}),a.appendChild(c),o||queueMicrotask(()=>c.focus())}return ne(t,e.error,a,e.ids)}function sa(e){if(e.field.kind==="checkbox"&&e.field.appearance==="toggle"){let o=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}});o.toggleAttribute("data-invalid",!!e.error),o.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"}});return u.checked=e.value===!0,u.addEventListener("change",()=>{e.setValue(u.checked)}),K(u,e.field,e.error,e.ids),C(s,[l,u,C(d("span",{className:"fillo-toggle-track",attrs:{"aria-hidden":"true"}}),[d("span",{className:"fillo-toggle-thumb"})])]),o.appendChild(s),e.field.description&&o.appendChild(d("p",{className:"fillo-description",text:e.field.description,attrs:{id:e.ids.descriptionId,"data-fillo":"fieldDescription"}})),e.error&&o.appendChild(d("p",{className:"fillo-error",text:e.error,attrs:{id:e.ids.errorId,"data-fillo":"error"}})),o}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 n=d("label",{className:"fillo-option",attrs:{"data-fillo":"option"}});n.toggleAttribute("data-checked",e.value===!0);let r=d("input",{className:"fillo-option-input",attrs:{id:e.ids.inputId,type:"checkbox"}});r.checked=e.value===!0,r.addEventListener("change",()=>e.setValue(r.checked)),K(r,e.field,e.error,e.ids);let i=d("span",{className:"fillo-option-label",text:e.field.label,attrs:{"data-fillo":"optionLabel"}});return e.field.required||i.appendChild(d("span",{className:"fillo-optional",text:" (optional)"})),C(n,[r,i]),t.appendChild(n),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 aa(e){if(e.field.kind!=="rating")return d("div");let t=typeof e.field.max=="number"?e.field.max:5,n=typeof e.value=="number"?e.value:0,r=Array.from({length:t},(a,l)=>l+1),i=n>0?n:null,o=i===null?0:Math.max(0,r.indexOf(i)),s=d("div",{className:"fillo-rating",attrs:{id:e.ids.inputId,role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});K(s,e.field,e.error,e.ids);for(let[a,l]of r.entries()){let u=d("button",{className:`fillo-star${l<=n?" fillo-star--active":""}`,text:l<=n?"\u2605":"\u2606",attrs:{type:"button",role:"radio","aria-label":`${l} of ${t}`,"aria-checked":String(l===n),tabindex:String(a===o?0:-1),"data-fillo":"option"}});u.toggleAttribute("data-selected",l<=n),u.addEventListener("click",c=>{c.detail===0&&l===n||e.setValue(l===n?null:l)}),s.appendChild(u)}return Hi(s,r,i,a=>e.setValue(a)),ne(e.field,e.error,s,e.ids)}function la(e){if(e.field.kind!=="linear_scale")return d("div");let t=typeof e.field.min=="number"?e.field.min:1,n=typeof e.field.max=="number"?e.field.max:10,r=typeof e.value=="number"?e.value:null,i=Array.from({length:n-t+1},(f,h)=>t+h),o=r===null?0:Math.max(0,i.indexOf(r)),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"}});K(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[f,h]of i.entries()){let p=d("button",{className:`fillo-scale-step${e.value===h?" fillo-scale-step--active":""}`,text:String(h),attrs:{type:"button",role:"radio","aria-label":String(h),"aria-checked":String(e.value===h),tabindex:String(f===o?0:-1),"data-fillo":"option"}});p.toggleAttribute("data-selected",e.value===h),p.addEventListener("click",m=>{m.detail===0&&e.value===h||e.setValue(e.value===h?null:h)}),u.appendChild(p)}return Hi(u,i,r,f=>e.setValue(f)),l.appendChild(u),("minLabel"in e.field||"maxLabel"in e.field)&&C(l,[C(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}})])]),ne(e.field,e.error,l,e.ids)}function ua(e){let t=e.field;if(t.kind!=="ranking")return null;let n=e.announce,r=Array.isArray(e.value)?e.value:[],i=[...r.filter(a=>t.options.some(l=>l.id===a)),...t.options.map(a=>a.id).filter(a=>!r.includes(a))],o=d("div",{attrs:{id:e.ids.inputId,role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});K(o,e.field,e.error,e.ids,{requiredSupported:!1});let s=d("ol",{className:"fillo-ranking"});for(let[a,l]of i.entries()){let u=t.options.find(g=>g.id===l);if(!u)continue;let c=d("li",{className:"fillo-ranking-item"}),f=d("span",{className:"fillo-ranking-controls"}),h=g=>{let b=a+g;if(b<0||b>=i.length)return;let z=[...i];[z[a],z[b]]=[z[b],z[a]],e.setValue(z),n?.(B.rankingPosition(u.label,b+1,i.length))},p=d("button",{className:"fillo-ranking-move",text:"\u2191",attrs:{type:"button","data-fillo-rank-opt":l,"data-fillo-rank-dir":"up","aria-label":`Move ${u.label} up`}});p.toggleAttribute("disabled",a===0),p.addEventListener("click",()=>h(-1));let m=d("button",{className:"fillo-ranking-move",text:"\u2193",attrs:{type:"button","data-fillo-rank-opt":l,"data-fillo-rank-dir":"down","aria-label":`Move ${u.label} down`}});m.toggleAttribute("disabled",a===i.length-1),m.addEventListener("click",()=>h(1)),C(f,[p,m]),C(c,[d("span",{className:"fillo-ranking-index",text:String(a+1)}),d("span",{className:"fillo-ranking-label",text:u.label}),f]),s.appendChild(c)}return o.appendChild(s),ne(e.field,e.error,o,e.ids)}function ca(e){let t=e.field;if(t.kind!=="matrix")return null;let n=e.value&&typeof e.value=="object"&&!Array.isArray(e.value)?e.value:{},r=d("table",{className:"fillo-matrix"}),i=document.createElement("thead"),o=document.createElement("tr");o.appendChild(document.createElement("td"));for(let l of t.columns)o.appendChild(d("th",{text:l.label,attrs:{scope:"col"}}));i.appendChild(o),r.appendChild(i);let s=document.createElement("tbody");for(let l of t.rows){let u=`${e.ids.inputId}-${l.id}`,c=n[l.id]!==void 0,f=!!e.error&&!!t.required&&!c,h=b=>`${e.ids.inputId}-${l.id}-${b.id}`,p=document.createElement("tr"),m=d("th",{attrs:{scope:"row"}}),g=d("div",{attrs:{role:"radiogroup","aria-labelledby":`${e.ids.labelId} ${u}`,"aria-owns":t.columns.map(h).join(" ")}});g.appendChild(d("span",{text:l.label,attrs:{id:u}})),m.appendChild(g),p.appendChild(m);for(let b of t.columns){let z=d("td",{attrs:{"data-label":b.label}}),T=d("label",{className:"fillo-matrix-cell"}),F=d("input",{className:"fillo-option-input",attrs:{id:h(b),type:"radio",name:`${e.ids.name}-${l.id}`,"aria-label":`${l.label}: ${b.label}`}});t.required&&F.setAttribute("aria-required","true"),f&&F.setAttribute("aria-invalid","true"),F.checked=n[l.id]===b.id,F.addEventListener("change",()=>e.setValue({...n,[l.id]:b.id})),T.appendChild(F),z.appendChild(T),p.appendChild(z)}s.appendChild(p)}r.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 K(a,e.field,e.error,e.ids,{requiredSupported:!1}),a.appendChild(r),ne(e.field,e.error,a,e.ids)}function da(e){let t=d("div",{className:"fillo-signature-field"}),n=d("div",{className:"fillo-signature",attrs:{"data-fillo":"control"}}),r=d("canvas",{className:"fillo-signature-canvas",attrs:{role:"img"}}),i=d("button",{className:"fillo-signature-clear",text:"Clear",attrs:{type:"button"}}),o=d("div",{className:"fillo-signature-hint",text:"Sign here",attrs:{"aria-hidden":"true"}});r.width=720,r.height=220;let s=r.getContext("2d"),a=!1,l=typeof e.value=="string"&&e.value.startsWith("data:image/"),u=()=>{r.setAttribute("aria-label",l?B.signatureSigned:B.signatureEmpty)};if(u(),l&&s){let b=new Image;b.onload=()=>s.drawImage(b,0,0,r.width,r.height),b.src=String(e.value),o.style.display="none"}let c=d("input",{className:"fillo-input fillo-signature-type-input",attrs:{id:e.ids.inputId,type:"text",autocomplete:"name"}});K(c,e.field,e.error,e.ids);let f=b=>{s&&(s.clearRect(0,0,r.width,r.height),b.trim()?(s.fillStyle=getComputedStyle(r).color||"#18181b",s.font=`italic ${Math.min(96,r.height*.45)}px "Segoe Script", "Brush Script MT", cursive`,s.textBaseline="middle",s.fillText(b,24,r.height/2),l=!0,o.style.display="none",e.setValue(r.toDataURL("image/png"),{render:!1})):(l=!1,o.style.display="",e.setValue(null,{render:!1})),u())};c.addEventListener("input",()=>f(c.value));let h=b=>{let z=r.getBoundingClientRect();return{x:(b.clientX-z.left)/z.width*r.width,y:(b.clientY-z.top)/z.height*r.height}};r.addEventListener("pointerdown",b=>{if(!s)return;a=!0,l=!0,o.style.display="none",u(),c.value&&(c.value=""),r.setPointerCapture(b.pointerId);let z=h(b);s.beginPath(),s.moveTo(z.x,z.y)}),r.addEventListener("pointermove",b=>{if(!a||!s)return;let z=h(b);s.lineWidth=2.4,s.lineCap="round",s.strokeStyle=getComputedStyle(r).color||"#18181b",s.lineTo(z.x,z.y),s.stroke()});let p=()=>{a&&(a=!1,l&&e.setValue(r.toDataURL("image/png"),{render:!1}))};r.addEventListener("pointerup",p),r.addEventListener("pointercancel",p),i.addEventListener("click",()=>{s?.clearRect(0,0,r.width,r.height),l=!1,o.style.display="",c.value="",u(),e.setValue(null,{render:!1})}),C(n,[r,o,i]);let m=d("div",{className:"fillo-signature-type"}),g=d("label",{className:"fillo-signature-type-label",text:"Or type your full name to sign",attrs:{for:e.ids.inputId}});return C(m,[g,c]),C(t,[n,m]),ne(e.field,e.error,t,e.ids)}function Zi(e){return e<1024?`${e} B`:e<1024**2?`${(e/1024).toFixed(0)} KB`:e<1024**3?`${(e/1024**2).toFixed(1)} MB`:`${(e/1024**3).toFixed(2)} GB`}function At(e,t,n,r){let i=d("button",{className:e,text:n,attrs:{type:"button","aria-label":t}});return i.addEventListener("click",r),i}function pa(e){let t=e.field;if(t.kind!=="file_upload")return null;let n=e,r=n.uploadDisabledReason,i=r===void 0,o=t.maxFiles??1,s=t.maxFileSizeMb??500,a=Array.isArray(e.value)?e.value:[],l=n.uploadRows??[],u=o-a.length-l.filter(h=>h.error===void 0).length,c=d("div");if(u>0){let h=d("input",{className:"fillo-input",attrs:{id:e.ids.inputId,type:"file",hidden:""}});o>1&&(h.multiple=!0),t.accept?.length&&(h.accept=t.accept.join(",")),h.disabled=!i,h.addEventListener("change",()=>{if(!i)return;let m=Array.from(h.files??[]);h.value="",e.uploadFiles?.(t,m)});let p=d("div",{className:`fillo-dropzone${i?"":" fillo-dropzone--disabled"}`,attrs:{role:"button",tabindex:"0","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});if(K(p,t,e.error,e.ids,{requiredSupported:!1}),i||p.setAttribute("aria-disabled","true"),p.addEventListener("dragover",m=>{m.preventDefault(),p.classList.add("fillo-dropzone--over"),p.setAttribute("data-drag-over","")}),p.addEventListener("dragleave",()=>{p.classList.remove("fillo-dropzone--over"),p.removeAttribute("data-drag-over")}),p.addEventListener("drop",m=>{m.preventDefault(),p.classList.remove("fillo-dropzone--over"),p.removeAttribute("data-drag-over"),i&&e.uploadFiles?.(t,Array.from(m.dataTransfer?.files??[]))}),p.addEventListener("click",()=>{i&&h.click()}),p.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),i&&h.click())}),p.appendChild(h),i)C(p,[d("span",{className:"fillo-dropzone-title",text:B.dropzoneTitle(o>1)}),d("span",{className:"fillo-dropzone-hint",text:B.dropzoneHint(s)})]);else if(r==="render_only")p.appendChild(d("span",{className:"fillo-dropzone-hint",text:B.uploadsRenderOnly}));else if(n.storageFixUrl){let m=d("span",{className:"fillo-dropzone-hint",text:"Connect file storage to enable uploads"});m.append(" \u2014 "),m.appendChild(d("a",{text:n.storageFixUrl,attrs:{href:n.storageFixUrl,target:"_blank",rel:"noopener noreferrer"}})),p.appendChild(m)}else p.appendChild(d("span",{className:"fillo-dropzone-hint",text:B.uploadsUnavailable}));c.appendChild(p)}if(a.length>0||l.length>0){let h=d("ul",{className:"fillo-files"});for(let p of a){let m=d("li",{className:"fillo-file fillo-file--done"});C(m,[d("span",{className:"fillo-file-name",text:p.name}),d("span",{className:"fillo-file-meta",text:Zi(p.size)}),d("span",{className:"fillo-sr-only",text:"Uploaded"}),At("fillo-file-remove",`Remove ${p.name}`,"\xD7",()=>e.setValue(a.filter(g=>g.fileId!==p.fileId)))]),h.appendChild(m)}for(let p of l){let m=p.error!==void 0,g=d("li",{className:`fillo-file${m?" fillo-file--failed":""}`,attrs:m?{}:{role:"progressbar","aria-label":`Uploading ${p.name}`,"aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":String(Math.round(p.fraction*100))}});if(g.appendChild(d("span",{className:"fillo-file-name",text:p.name})),m){let b=d("span",{className:"fillo-file-actions"});u>0&&b.appendChild(At("fillo-file-retry",`${B.uploadRetry} ${p.name}`,B.uploadRetry,()=>n.uploadAction?.(p.key,"retry"))),b.appendChild(At("fillo-file-remove","Dismiss","\xD7",()=>n.uploadAction?.(p.key,"dismiss"))),g.appendChild(b),g.appendChild(d("span",{className:"fillo-file-error",text:p.error??""}))}else{let b=d("span",{className:"fillo-progress-bar"});b.style.width=`${p.fraction*100}%`,C(g,[d("span",{className:"fillo-file-meta",text:`${Math.round(p.fraction*100)}% of ${Zi(p.size)}`}),At("fillo-file-remove",`Cancel ${p.name}`,"\xD7",()=>n.uploadAction?.(p.key,"cancel")),C(d("span",{className:"fillo-progress",attrs:{"aria-hidden":"true"}}),[b])])}h.appendChild(g)}c.appendChild(h)}let f=n.uploadNotice;return f&&c.appendChild(d("p",{className:"fillo-upload-notice",text:f})),ne(t,e.error,c,e.ids)}function fa(e){let t=e.field,n=d("div",{className:"fillo-field fillo-field--calculated fillo-calculated",attrs:{"data-fillo":"calculated","data-field":t.id,"data-kind":t.kind}});n.appendChild(d("label",{className:"fillo-label",text:t.label,attrs:{id:e.ids.labelId,for:e.ids.inputId,"data-fillo":"label"}})),t.description&&n.appendChild(d("p",{className:"fillo-description",text:t.description,attrs:{id:e.ids.descriptionId,"data-fillo":"fieldDescription"}}));let r=e.value,i=r!=null&&r!=="",o=d("output",{className:`fillo-calculated-value${i?"":" fillo-calculated-value--empty"}`,text:i?fi(t,r):"\u2014",attrs:{id:e.ids.inputId}});return t.description&&o.setAttribute("aria-describedby",e.ids.descriptionId),n.appendChild(o),n}var Oi=new Map;function Zn(e){if(!e.shuffleOptions)return e.options;let t=`${e.id}|${e.options.map(o=>o.id).join(",")}`,n=Oi.get(t);if(!n){n=e.options.map(o=>o.id);for(let o=n.length-1;o>0;o--){let s=Math.floor(Math.random()*(o+1));[n[o],n[s]]=[n[s],n[o]]}Oi.set(t,n)}let r=new Map(e.options.map(o=>[o.id,o])),i=n.flatMap(o=>r.get(o)??[]);return i.length===e.options.length?i:e.options}var ha={short_text:e=>at("text",e),email:e=>at("email",e),url:e=>at("url",e),phone:ea,number:e=>at("number",e),date:e=>at("date",e),long_text:ta,select:na,multi_select:ra,dropdown:oa,checkbox:sa,rating:aa,linear_scale:la,ranking:ua,matrix:ca,signature:da,file_upload:pa,calculated:fa};function ma(e){if(e.field.kind==="hidden"||e.field.kind==="custom")return null;let t=ha[e.field.kind];return t?t(e):null}var ga="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",Ri="fillo-turnstile-script",lt=null;function He(){return globalThis.turnstile}function ba(){return typeof window>"u"||typeof document>"u"?Promise.reject(new Error("Turnstile needs a browser")):He()?Promise.resolve():lt||(lt=new Promise((e,t)=>{let n=()=>{He()?e():t(new Error("Turnstile loaded without its global"))},r=document.getElementById(Ri);if(r){if(He()){e();return}r.addEventListener("load",n,{once:!0}),r.addEventListener("error",()=>t(new Error("Turnstile script failed to load")),{once:!0});return}let i=document.createElement("script");i.id=Ri,i.src=ga,i.async=!0,i.defer=!0,i.addEventListener("load",n,{once:!0}),i.addEventListener("error",()=>{i.remove(),lt=null,t(new Error("Turnstile script failed to load"))},{once:!0}),document.head.appendChild(i)}),lt)}function Di(){return d("div",{className:"fillo-turnstile",attrs:{"data-fillo":"turnstile"}})}var dt=class{constructor(t,n){this.target=t;this.options=n;this.element.className="fillo-dom-root",n.preview===!0&&Sa(),t.replaceChildren(this.element,this.statusEl,this.alertEl),this.resolve()}target;options;element=d("div");statusEl=d("span",{className:"fillo-sr-only",attrs:{role:"status","aria-live":"polite","data-fillo":"announce"}});alertEl=d("span",{className:"fillo-sr-only",attrs:{role:"alert","data-fillo":"announce-alert"}});instanceId=`d${++Ks}`;schema=null;theme;formId;closed=!1;fetchedPoweredBy=null;fetchedBrandLabel;fetchedBrandHref;phase="loading";engine=null;destroyed=!1;renderQueued=!1;hpValue="";liveSubmissionHandled=!1;activeOtherFields=new Set;inFlight=new Map;uploadNotices=new Map;focusIntent=null;overlays=new Set;challenge;challengeToken;challengeError=!1;turnstileContainer=Di();turnstileWidgetId=null;turnstileSiteKey;turnstileLoadInFlight=!1;turnstileAttempt=0;announce=t=>{this.statusEl.textContent="",requestAnimationFrame(()=>{this.statusEl.textContent=t})};announceAlert=t=>{this.alertEl.textContent="",requestAnimationFrame(()=>{this.alertEl.textContent=t})};devChrome(){return this.options.preview===!0||wa()}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:{}},n=this.engine?.getState(),r=n?.pageCount??t.pages.length;return{form:t,formId:this.formId,client:this.options.renderOnly?void 0:this.options.client,data:n?.data??this.mutableData,errors:n?.errors??{},status:this.status,pageIndex:n?.pageIndex??0,pageCount:r,page:n?.page??t.pages[0]??{id:"empty",blocks:[]},blocks:n?.blocks??[],isFirstPage:n?.isFirstPage??!0,isLastPage:n?.isLastPage??r<=1,setValue:(i,o,s)=>this.setValueInternal(i,o,s),next:()=>this.next(),back:()=>this.back(),submit:()=>this.submit()}}resolveFormIdFn;notOpenVariant=null;fatalError=null;genericUnavailable=!1;syncErrorNotice=null;stagedNotice=!1;draftNotice=!1;syncWarningCode;syncWarningUrl;uploadsAvailable;uploadFileSizeLimitMb;resolutionFailureCode=null;async resolve(){try{this.challenge=this.options.renderOnly?void 0:this.options.challenge;let t=Nn(this.options.form)?this.options.form:null;if(t){if(this.options.renderOnly){this.setSchema(t.schema,this.options.theme??t.theme,void 0);return}!this.options.client&&this.options.formId&&(this.options.client=Te());let i=this.options.client;if(i?.key&&(this.resolveFormIdFn=async()=>{try{let o=await Tn(i,t,{bypassCache:!0});if(this.syncWarningCode=o.warningCode,this.syncWarningUrl=o.warningUrl,this.uploadsAvailable=o.uploadsAvailable,this.uploadFileSizeLimitMb=o.uploadFileSizeLimitMb,o.status==="draft")throw new $("This form is no longer published. Submission was stopped before sending answers.",403,void 0,"form_not_published");if(o.accepting===!1)throw new $("This form is no longer accepting responses. Submission was stopped before sending answers.",403,void 0,o.acceptingReason??"form_not_accepting");let s=Ne(o.resolvedSchema??t.schema);if(!s.ok)throw new $(`The canonical form schema was invalid: ${s.error}`,502,void 0,"invalid_sync_schema");if(this.schema&&!Ci(this.schema,s.schema))throw new $("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 o.syncError&&this.reportSyncNotice(new $(o.syncError.message,403,void 0,o.syncError.code)),this.resolutionFailureCode=null,o.formId}catch(o){let s=ut(o);throw this.resolutionFailureCode=s.code??"sync_failed",this.reportSubmitSyncFailure(s),s}}),!i?.key&&this.options.formId&&this.setSchema(t.schema,this.options.theme??t.theme,this.options.formId),!i&&!this.options.formId)throw this.genericUnavailable=!this.devChrome(),ji();if(i&&!i.key&&!this.options.formId){this.reportSyncFailure(new $('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(!i?.key)return;this.devChrome()?this.setSchema(t.schema,this.options.theme??t.theme,this.options.formId):(this.theme=this.options.theme??t.theme,this.render());try{let o=await Tn(i,t);if(this.destroyed)return;if((o.staged||o.syncError)&&!o.resolvedSchema)throw new $("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=this.devChrome();if(this.notOpenVariant=s?null:o.status==="draft"?"notOpen":o.accepting===!1?Ui(o.acceptingReason):null,this.stagedNotice=!!o.staged,this.draftNotice=o.status==="draft",this.syncWarningCode=o.warningCode,this.syncWarningUrl=o.warningUrl,this.uploadsAvailable=o.uploadsAvailable,this.uploadFileSizeLimitMb=o.uploadFileSizeLimitMb,this.challenge=this.options.challenge??o.challenge,o.branding&&(this.fetchedPoweredBy=o.branding.poweredBy,this.fetchedBrandLabel=o.branding.label,this.fetchedBrandHref=o.branding.href),s&&o.resolvedSchema)this.formId=o.formId,this.engine?.setContext({formId:o.formId}),this.render();else{let l=o.resolvedSchema??t.schema,u=this.options.theme??(o.resolvedSchema?o.resolvedTheme??void 0:t.theme);this.applyCanonicalSchema(l,u,o.formId)}o.warning&&console.warn(`[fillo] ${o.warning}`),o.syncError&&this.reportSyncNotice(new $(o.syncError.message,403,void 0,o.syncError.code));let a=o.warningUrl?` \u2014 connect storage to publish: ${o.warningUrl}`:"";o.staged?console.info(`[fillo] "${t.id}" changes staged as a draft \u2014 rendering the live version until you publish them in your Fillo dashboard${a}`):o.status==="draft"&&console.info(`[fillo] "${t.id}" is a draft \u2014 it renders here but won't accept responses until published${a}`)}catch(o){if(this.destroyed)return;this.reportSyncFailure(ut(o))}return}let n=this.options.form&&!Nn(this.options.form)?this.options.form:null;if(n){if(this.options.renderOnly){this.setSchema(n,this.options.theme,void 0);return}if(!this.options.formId)throw this.genericUnavailable=!this.devChrome(),ji();this.options.client??=Te(),this.setSchema(n,this.options.theme,this.options.formId);return}if(!this.options.formId)throw new $("Provide either `form`, or a `formId`.",0);this.options.client??=Te(),this.render();let r=await this.options.client.getForm(this.options.formId);if(this.destroyed)return;if(r.accepting===!1?this.notOpenVariant=Ui(r.acceptingReason):this.closed=!!r.closed,this.uploadsAvailable=r.uploadsAvailable,this.uploadFileSizeLimitMb=r.uploadFileSizeLimitMb,this.fetchedPoweredBy=r.branding?.poweredBy??null,this.fetchedBrandLabel=r.branding?.label,this.fetchedBrandHref=r.branding?.href,this.challenge=this.options.challenge??r.challenge,r.accepting===!1&&this.options.renderError){let i=this.notOpenVariant==="closed"?"This form is no longer accepting responses.":"This form isn't accepting responses yet.";this.fatalError=new $(i,403,void 0,r.acceptingReason),this.phase="error",this.render(this.fatalError);return}this.setSchema(r.schema,this.options.theme??r.theme??void 0,r.id)}catch(t){if(this.destroyed)return;this.handleError(ut(t))}}setSchema(t,n,r){if(this.destroyed)return;let i=Ne(t);if(!i.ok)throw new $(`This form could not be rendered: ${i.error}`,422);let o=i.schema;this.schema=o,this.theme=n;let s=this.options.renderOnly===!0;this.formId=s?void 0:r;let a=this.notOpenVariant!==null,l=a||s;this.engine=$i({form:o,formId:l?void 0:r,client:l?void 0:this.options.client,initialData:this.options.initialData,onChange:a?void 0:this.options.onChange,onSubmitted:l?void 0:this.options.onSubmitted,getHoneypot:()=>this.element.querySelector('input[name="fillo_hp_field"]')?.value??this.hpValue,surface:"default",resolveFormId:l?void 0:this.resolveFormIdFn,skipValidation:s,verboseResolutionErrors:this.devChrome(),respondent:l?void 0:this.options.respondent,challengeRequired:l?!1:!!this.challenge,getChallengeToken:()=>this.challengeToken,onChallengeFailed:()=>this.resetChallengeWidget()});let u=this.engine.getState().status,c=this.engine.getState().resumedDraft,f=this.engine.getState().editingPrevious;this.engine.subscribe(()=>{let h=this.engine?.getState();h&&(h.status!==u||h.resumedDraft!==c||h.editingPrevious!==f)&&(h.editingPrevious&&!f?this.announce(P.editNotice):h.resumedDraft&&!c&&this.announce(P.resumeNotice),u=h.status,c=h.resumedDraft,f=h.editingPrevious,this.queueRender())}),l||this.configureDraftFlush(o),this.phase=this.closed?"closed":"ready",this.render()}applyCanonicalSchema(t,n,r){if(!this.engine){this.setSchema(t,n,r);return}let i=Ne(t);if(!i.ok)throw new $(`This form could not be rendered: ${i.error}`,422);let o=i.schema;this.schema=o,this.theme=n,this.formId=r,this.engine.setContext({form:o,formId:r}),this.notOpenVariant===null&&this.configureDraftFlush(o),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,n){this.setValueInternal(t,n)}setValueInternal(t,n,r={}){this.notOpenVariant||(this.engine?.setValue(t,n),r.render!==!1&&this.queueRender())}next(){if(!this.engine||this.notOpenVariant)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.notOpenVariant||(this.engine.back(),this.focusIntent="page",this.render())}async submit(){if(!this.engine||this.phase!=="ready"||this.notOpenVariant)return;let t=this.engine.submit();this.hasErrors()?this.focusIntent="error":this.engine.getState().status==="submitting"&&this.announce(B.submittingAnnouncement),this.render();try{await t}catch(n){this.options.onError?.(ut(n)),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})}fieldActive(t){let n=0;for(let r of this.inFlight.values())r.fieldId===t&&r.error===void 0&&n++;return n}uploadRowsFor(t){let n=[];for(let[r,i]of this.inFlight)i.fieldId===t&&n.push({key:r,name:i.name,size:i.size,fraction:i.fraction,error:i.error});return n}uploadAction=(t,n)=>{let r=this.inFlight.get(t);r&&(n==="cancel"?(r.controller.abort(),this.inFlight.delete(t)):n==="dismiss"?this.inFlight.delete(t):(this.inFlight.delete(t),this.startUpload(r.fieldId,r.file,r.maxFiles)),this.fieldActive(r.fieldId)===0&&this.engine?.setUploading(r.fieldId,!1),this.queueRender())};async startUpload(t,n,r){let i=`${n.name}-${n.size}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,o=new AbortController;this.inFlight.set(i,{fieldId:t,name:n.name,size:n.size,fraction:0,file:n,controller:o,maxFiles:r}),this.engine?.setUploading(t,!0),this.queueRender();try{let s=this.options.client&&this.formId?await this.options.client.uploadFile(this.formId,n,{fieldId:t,signal:o.signal,onProgress:l=>{let u=this.inFlight.get(i);u&&(u.fraction=l.fraction,this.queueRender())}}):{fileId:`local:${n.name}:${n.size}`,name:n.name,size:n.size,mime:n.type||"application/octet-stream"};if(this.destroyed)return;this.inFlight.delete(i);let a=r>1&&Array.isArray(this.mutableData[t])?this.mutableData[t]:[];this.setValueInternal(t,[...a,s])}catch(s){if(this.destroyed||o.signal.aborted)return;let a=ut(s),l=a.status!==void 0&&a.status>=500?B.uploadUnavailable:a.message||B.uploadFailed,u=this.inFlight.get(i);u&&(u.error=l),this.announceAlert(l),this.options.onError?.(a)}finally{this.fieldActive(t)===0&&this.engine?.setUploading(t,!1),this.queueRender()}}async uploadFiles(t,n){if(!this.schema||this.notOpenVariant)return;let r=t.maxFiles??1,i=r>1&&Array.isArray(this.mutableData[t.id])?this.mutableData[t.id].length:0,o=Math.max(0,r-i-this.fieldActive(t.id)),s=n.slice(0,o),a=t.maxFileSizeMb??500,l=this.uploadFileSizeLimitMb?Math.min(a,this.uploadFileSizeLimitMb):a,u=l*1024*1024,c=s.filter(p=>p.size<=u),f=n.length-s.length,h=s.length-c.length;if(f>0||h>0){let p=[];f>0&&p.push(`You can attach up to ${r} file${r===1?"":"s"}. ${f} ${f===1?"file was":"files were"} not added.`),h>0&&p.push(`${h} ${h===1?"file exceeds":"files exceed"} the ${l} MB limit.`);let m=p.join(" ");this.uploadNotices.set(t.id,m),this.announce(m)}else this.uploadNotices.delete(t.id);if(c.length===0){this.queueRender();return}await Promise.all(c.map(p=>this.startUpload(t.id,p,r)))}destroy(){this.destroyed=!0,this.teardownDraftFlush(),this.closeOverlays(),this.teardownTurnstileWidget();for(let t of this.inFlight.values())t.controller.abort();this.inFlight.clear(),this.engine?.destroy(),this.engine=null,this.target.replaceChildren()}storageBlocked(){return this.uploadsAvailable===!1}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()}}ensureTurnstileWidget(t){if(this.turnstileSiteKey!==t&&(this.teardownTurnstileWidget(),this.turnstileSiteKey=t),this.turnstileWidgetId!==null||this.turnstileLoadInFlight||this.challengeError)return;this.turnstileLoadInFlight=!0;let n=++this.turnstileAttempt;ba().then(()=>{if(this.destroyed||n!==this.turnstileAttempt)return;let r=He();if(!r){this.turnstileLoadInFlight=!1,this.handleChallengeError();return}this.turnstileWidgetId=r.render(this.turnstileContainer,{sitekey:t,theme:"auto",callback:i=>this.handleChallengeToken(i),"error-callback":()=>{this.handleChallengeToken(void 0),this.handleChallengeError()},"expired-callback":()=>this.resetChallengeWidget(),"timeout-callback":()=>this.resetChallengeWidget()}),this.turnstileLoadInFlight=!1}).catch(()=>{this.destroyed||n!==this.turnstileAttempt||(this.turnstileLoadInFlight=!1,this.handleChallengeError())})}handleChallengeToken(t){this.challengeToken=t,t&&(this.challengeError=!1),this.queueRender()}handleChallengeError(){this.challengeError=!0,this.announceAlert(P.challengeUnavailable),this.queueRender()}resetChallengeWidget(){this.challengeToken=void 0,this.turnstileWidgetId&&He()?.reset(this.turnstileWidgetId),this.queueRender()}teardownTurnstileWidget(){if(this.turnstileWidgetId===null&&!this.turnstileLoadInFlight)return;this.turnstileAttempt++;let t=He();if(this.turnstileWidgetId&&t)try{t.remove(this.turnstileWidgetId)}catch{}this.turnstileWidgetId=null,this.turnstileLoadInFlight=!1,this.challengeError=!1,this.turnstileContainer=Di(),this.challengeToken=void 0}captureFocus(){if(typeof document>"u")return null;let t=document.activeElement;if(!t||!this.element.contains(t))return null;let n={};t.id&&(n.id=t.id);let r=t.getAttribute("data-fillo-rank-opt");r&&(n.rankOpt=r,n.rankDir=t.getAttribute("data-fillo-rank-dir")??void 0);let i=t.closest("[data-field]");if(i&&(n.fieldId=i.getAttribute("data-field")??void 0,n.controlIndex=Array.from(i.querySelectorAll(Ct)).indexOf(t)),t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)try{n.selStart=t.selectionStart,n.selEnd=t.selectionEnd}catch{}return n.id||n.rankOpt||n.fieldId?n:null}restoreFocus(t){if(typeof document>"u")return;let n=null;if(t.rankOpt){let r=Array.from(this.element.querySelectorAll("[data-fillo-rank-opt]")).filter(i=>i.getAttribute("data-fillo-rank-opt")===t.rankOpt);n=r.find(i=>i.getAttribute("data-fillo-rank-dir")===t.rankDir&&!i.disabled)??r.find(i=>!i.disabled)??null}if(!n&&t.id&&(n=document.getElementById(t.id)),!n&&t.fieldId!=null&&t.controlIndex!=null&&t.controlIndex>=0){let r=Array.from(this.element.querySelectorAll("[data-field]")).find(i=>i.getAttribute("data-field")===t.fieldId);r&&(n=Array.from(r.querySelectorAll(Ct))[t.controlIndex]??null)}if(!(!n||typeof n.focus!="function")&&(n.focus(),(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&t.selStart!=null))try{n.setSelectionRange(t.selStart,t.selEnd??t.selStart)}catch{}}applyFocus(t,n){if(!(typeof document>"u")){if(t==="error"){let r=this.element.querySelector(".fillo-error-summary");if(r){r.focus();return}let i=this.element.querySelector('[aria-invalid="true"]');i&&Ti(i)?.focus();return}if(t==="page"){let i=this.element.querySelector(".fillo-page-title, .fillo-title")??this.element.querySelector(".fillo-blocks");i&&(i.hasAttribute("tabindex")||i.setAttribute("tabindex","-1"),i.focus?.());return}n&&this.restoreFocus(n)}}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 n=this.devChrome();if(!n||this.options.renderError){this.genericUnavailable=!n,this.handleError(t);return}this.options.onError?.(t),n&&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),this.devChrome()&&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,setTimeout(()=>{this.renderQueued=!1,this.render()},0))}render(t){if(this.destroyed)return;let n=this.focusIntent;this.focusIntent=null;let r=n?null:this.captureFocus();if(this.closeOverlays(),this.phase==="ready"&&this.engine?.getState().status!=="submitted"||this.teardownTurnstileWidget(),this.element.replaceChildren(),this.phase==="loading"){let s=d("div",{className:`fillo-form fillo-form--loading ${this.options.className??""}`,attrs:{"aria-busy":"true","data-fillo":"root","data-state":"loading"}});Ve(s,this.theme),C(s,[d("div",{className:"fillo-skeleton"}),d("div",{className:"fillo-skeleton"}),d("div",{className:"fillo-skeleton fillo-skeleton--short"})]),this.element.appendChild(s);return}let o=t??this.fatalError;if(this.phase==="error"&&o){let s=o.code==="form_target_required"&&this.devChrome()?`${o.message} (${o.code})`:null,a=this.options.renderError?.(o)??d("div",{className:"fillo-form fillo-form--error",text:s??(this.genericUnavailable?"This form is unavailable.":Aa(o))});a.hasAttribute("data-fillo")||a.setAttribute("data-fillo","root"),a.hasAttribute("data-state")||a.setAttribute("data-state","error"),o.code&&!a.hasAttribute("data-error-code")&&a.setAttribute("data-error-code",o.code),a.hasAttribute("role")||a.setAttribute("role","alert"),Ve(a,this.theme),this.element.appendChild(a);return}if(this.phase==="closed"){let s=d("div",{className:`fillo-form fillo-form--closed ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":"closed"}});Ve(s,this.theme),s.appendChild(d("p",{className:"fillo-closed",text:"This form is no longer accepting responses."})),this.element.appendChild(s);return}if(this.notOpenVariant&&this.schema){this.element.appendChild(this.renderNotOpen(this.notOpenVariant)),this.brandingVisible()&&this.element.appendChild(Ln(this.fetchedBrandLabel,this.fetchedBrandHref));return}if(this.schema){if(this.engine?.getState().status==="submitted"){let s=this.api(),a=this.engine.getState(),l=this.options.renderSuccess?.(s)??ya(this.schema);if(l.setAttribute("data-fillo",l.getAttribute("data-fillo")??"root"),this.formId&&!l.hasAttribute("data-fillo-form-id")&&l.setAttribute("data-fillo-form-id",this.formId),l.setAttribute("data-state",l.getAttribute("data-state")??"submitted"),l.hasAttribute("tabindex")||l.setAttribute("tabindex","-1"),Ve(l,this.theme),this.element.appendChild(l),this.brandingVisible()&&this.element.appendChild(Ln(this.fetchedBrandLabel,this.fetchedBrandHref)),!a.restoredSubmission&&!this.liveSubmissionHandled){this.liveSubmissionHandled=!0;let u=ct(this.schema.settings.redirectUrl);u&&typeof window<"u"?window.location.assign(u):(l.focus(),this.announce(l.textContent??""))}return}this.devChrome()&&C(this.element,Ea({preview:this.options.preview===!0,devNotices:this.options.devNotices,syncError:this.syncErrorNotice,staged:this.stagedNotice,draft:this.draftNotice,warningUrl:this.syncWarningUrl,noClient:!this.options.client&&!this.options.renderOnly})),this.element.appendChild(this.renderForm()),this.brandingVisible()&&this.element.appendChild(Ln(this.fetchedBrandLabel,this.fetchedBrandHref)),this.applyFocus(n,r)}}brandingVisible(){return this.fetchedPoweredBy??!0}renderNotOpen(t){let n=d("div",{className:`fillo-form fillo-form--not-open ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":"closed"}});Ve(n,this.theme);let r=d("div",{className:"fillo-not-open-preview",attrs:{"aria-hidden":"true",inert:""}});r.appendChild(this.renderForm());let i=d("div",{className:"fillo-not-open-card",attrs:{role:"status","data-fillo":"not-open-card"}});return i.appendChild(d("h2",{className:"fillo-not-open-title",text:t==="closed"?P.closedTitle:P.notOpenTitle})),i.appendChild(d("p",{className:"fillo-not-open-body",text:t==="closed"?P.closed:P.notOpenBody})),C(n,[r,i]),n}renderForm(){let t=this.api(),n=this.notOpenVariant!==null,r=!!this.challenge,i=!n&&r&&t.isLastPage,o=d(n?"div":"form",{className:`fillo-form ${this.options.className??""}`,attrs:{"data-fillo":n?"preview-form":"root","data-state":n?"preview":t.status,"data-page":String(t.pageIndex+1)}});!n&&this.formId&&o.setAttribute("data-fillo-form-id",this.formId),o.toggleAttribute("data-last-page",t.isLastPage),Ve(o,this.theme);let s=()=>{t.isLastPage?this.submit():this.next()};if(!n){let g=o;g.noValidate=!0,g.addEventListener("submit",b=>{b.preventDefault(),s()})}let a=n?o.appendChild(d("fieldset",{className:"fillo-not-open-fields",attrs:{disabled:""}})):o,l=this.engine?.getState();if(l?.resumedDraft||l?.editingPrevious){let g=d("div",{className:"fillo-resume",attrs:{"data-fillo":"resume"}});g.appendChild(d("span",{className:"fillo-resume-text",text:l.editingPrevious?P.editNotice:P.resumeNotice}));let b=d("button",{className:"fillo-resume-clear",text:P.resumeStartOver,attrs:{type:"button"}});b.addEventListener("click",()=>this.resetDraft()),g.appendChild(b),a.appendChild(g)}if(t.pageCount>1&&this.schema?.settings.showProgress!==!1){let g=Be(t.form,t.data),b=Math.max(g.length,1),z=g.indexOf(t.page.id),T=z>=0?z+1:Math.min(t.pageIndex+1,b),F=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(b),"aria-valuenow":String(T)}});F.appendChild(d("div",{className:"fillo-progress-fill",attrs:{"data-fillo":"progressFill"}})),F.firstElementChild?.style.setProperty("--fillo-progress-value",`${T/b*100}%`),a.appendChild(F)}if(t.pageIndex===0){let g=d("header",{className:"fillo-header",attrs:{"data-fillo":"header"}});t.form.title&&g.appendChild(d("h1",{className:"fillo-title",text:t.form.title,attrs:{"data-fillo":"title"}})),t.form.description&&g.appendChild(d("p",{className:"fillo-form-description",text:t.form.description,attrs:{"data-fillo":"description"}})),a.appendChild(g)}else t.page.title&&a.appendChild(d("h2",{className:"fillo-page-title",text:t.page.title,attrs:{"data-fillo":"pageTitle"}}));let u=this.renderErrorSummary(t);u&&a.appendChild(u);let c=d("div",{className:"fillo-blocks",attrs:{"data-fillo":"blocks"}});for(let g of t.blocks){let b=this.renderBlock(Ni(g,this.mutableData,t.form),t);b&&c.appendChild(b)}if(a.appendChild(c),!n){let g=d("input",{className:"fillo-hp",attrs:{type:"text",name:"fillo_hp_field",tabindex:"-1",autocomplete:"off","aria-hidden":"true"}});g.style.position="absolute",g.style.left="-9999px",g.style.top="auto",g.style.width="1px",g.style.height="1px",g.style.opacity="0",g.style.overflow="hidden",g.style.pointerEvents="none",g.addEventListener("input",()=>{this.hpValue=g.value}),a.appendChild(g)}if(i){let g=d("div",{className:"fillo-turnstile-slot",attrs:{"data-fillo":"turnstile-slot"}});g.appendChild(this.turnstileContainer),this.challengeError&&g.appendChild(d("p",{className:"fillo-turnstile-error",attrs:{role:"alert"},text:P.challengeUnavailable})),a.appendChild(g),this.ensureTurnstileWidget(this.challenge.siteKey)}else(this.turnstileWidgetId!==null||this.turnstileLoadInFlight)&&this.teardownTurnstileWidget();let f=t.status==="error"?"This form can't submit right now. Please try again in a moment.":this.engine?.getState().submitError;if(f){let g=d("p",{className:"fillo-submit-error",attrs:{role:"alert"},text:f}),b=this.devChrome()&&this.resolutionFailureCode==="form_not_published"&&this.syncWarningCode==="storage_required"?ct(this.syncWarningUrl):null;b&&(g.append(" Connect storage: "),g.appendChild(d("a",{text:b,attrs:{href:b,target:"_blank",rel:"noopener noreferrer"}}))),a.appendChild(g)}let p=!(t.form.settings.submitMode==="auto")||!t.isLastPage||zi(ti(t.form,t.data))||i;if(p||t.pageCount>1&&!t.isFirstPage){let g=d("footer",{className:"fillo-footer",attrs:{"data-fillo":"footer"}});if(t.pageCount>1&&!t.isFirstPage){let b=d("button",{className:"fillo-button fillo-button--ghost",text:"Back",attrs:{type:"button","data-fillo":"button"}});b.addEventListener("click",()=>this.back()),g.appendChild(b)}if(p){let b=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"}});b.toggleAttribute("disabled",t.status==="submitting"||this.engine?.getState().uploading===!0||i&&!this.challengeToken),b.addEventListener("click",z=>{z.preventDefault(),s()}),g.appendChild(b)}a.appendChild(g)}return o}renderErrorSummary(t){let n=t.blocks.filter(J).filter(o=>t.errors[o.id]);if(n.length===0)return null;let r=d("div",{className:"fillo-error-summary",attrs:{role:"alert",tabindex:"-1","data-fillo":"error-summary"}});r.appendChild(d("p",{className:"fillo-error-summary-title",text:B.errorSummaryTitle}));let i=d("ul");for(let o of n){let s=d("a",{text:`${o.label}: ${t.errors[o.id]}`,attrs:{href:`#${Pi(this.instanceId,o.id).inputId}`}});s.addEventListener("click",l=>{l.preventDefault();let u=Array.from(this.element.querySelectorAll("[data-field]")).find(f=>f.getAttribute("data-field")===o.id);if(!u)return;let c=u.querySelector('[aria-invalid="true"]')??u;Ti(c)?.focus()});let a=d("li");a.appendChild(s),i.appendChild(a)}return r.appendChild(i),r}renderBlock(t,n){if(!J(t))return va(t);let r=(s,a)=>{if(this.setValueInternal(t.id,s,a),a?.render===!1)return;let l={form:n.form,data:n.data,status:n.status,isLastPage:n.isLastPage,uploading:this.engine?.getState().uploading===!0};Si(t,s,l)&&this.submit()},i={field:t,value:n.data[t.id],error:n.errors[t.id],ids:Pi(this.instanceId,t.id),api:n,setValue:r,uploadFiles:(s,a)=>this.uploadFiles(s,a),uploadRows:this.uploadRowsFor(t.id),uploadAction:this.uploadAction,activeOtherFields:this.activeOtherFields,getValue:()=>this.engine?.getState().data[t.id],registerOverlay:this.registerOverlay,uploadNotice:this.uploadNotices.get(t.id),uploadDisabledReason:this.options.renderOnly?"render_only":this.storageBlocked()?"storage_unavailable":void 0,storageFixUrl:this.storageBlocked()&&this.devChrome()?ct(this.syncWarningUrl):null,announce:this.announce,announceAlert:this.announceAlert};return(t.kind==="custom"?this.options.customComponents?.[t.component]??this.options.components?.custom:this.options.components?.[t.kind]??ma)?.(i)??null}};function va(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 ya(e){let t=d("div",{className:"fillo-form fillo-form--success"}),n=d("div",{className:"fillo-success"});return C(n,[d("div",{className:"fillo-success-mark",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(n),t}function Ln(e,t){return d("a",{className:"fillo-powered",text:e??"Powered by Fillo",attrs:{href:Gs(t),target:"_blank",rel:"noopener noreferrer"}})}function Ui(e){return e==="expired"||e==="capped"||e==="storage_full"?"closed":"notOpen"}function wa(){return Ii()}function _a(){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 and preview.)",attrs:{role:"alert"}})}function xa(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 ka(){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 $a(e){let t=d("div",{className:"fillo-devwarning",attrs:{role:"alert"}});t.append("Draft form \u2014 it renders here, but it won't accept responses until you publish it in your Fillo dashboard. ");let n=ct(e);return n&&(t.append("Connect storage to publish: "),t.appendChild(d("a",{text:n,attrs:{href:n,target:"_blank",rel:"noopener noreferrer"}})),t.append(". ")),t.append("(Shown only in development and preview.)"),t}function za(){return d("span",{className:"fillo-preview-badge",text:"Preview",attrs:{"data-fillo":"preview-badge"}})}var Bi=!1;function Sa(){Bi||Pn()||(Bi=!0,console.warn("[fillo] `preview` is enabled in a production build. Preview is cosmetic only \u2014 it shows developer chrome and never changes where submissions go or whether they are accepted \u2014 but remove it before respondents see this page."))}function Ea(e){let t=[];return e.preview&&t.push(za()),e.devNotices===!1||(e.syncError?t.push(xa(e.syncError)):e.staged?t.push(ka()):e.draft?t.push($a(e.warningUrl)):e.noClient&&t.push(_a())),t}function Aa(e){return e.status===404?P.loadFailedNotFound:e.status===0?P.loadFailedNetwork:e.status===422?P.renderFailed:P.loadFailed}function ji(){return new $("This form has no Fillo target. Pass formId with the schema, use a defineForm() value with client, or set renderOnly for a non-submitting preview.",422,void 0,"form_target_required")}function ut(e){return X(e)?e:new $(e instanceof Error?e.message:String(e),0)}function It(e,t){let n=typeof e=="string"?document.querySelector(e):e;if(!n)throw new $(`Fillo mount target not found: ${String(e)}`,0);let r={...t,initialData:t.initialData??{}};return new dt(n,r)}function qi(e){let t=d("div");return It(t,e),t}var Ca=typeof HTMLElement<"u"?HTMLElement:class{},Mn=class extends Ca{instance=null;assignedForm;assignedClient;assignedTheme;assignedInitialData;mounted=!1;mountScheduled=!1;static get observedAttributes(){return["publishable-key","form-id","data-preview","data-render-only"]}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 dt&&this.instance.setClient(t)}set theme(t){this.assignedTheme=t,this.mounted&&this.instance instanceof dt&&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()}))}previewAttrEnabled(){let t=this.getAttribute("data-preview");return t!==null&&t!=="false"&&t!=="0"}renderOnlyAttrEnabled(){let t=this.getAttribute("data-render-only");return t!==null&&t!=="false"&&t!=="0"}mount(){this.instance?.destroy();let t=this.getAttribute("publishable-key")??void 0,n=this.getAttribute("form-id")??void 0,r=this.assignedClient??(n||t?Te({key:t}):void 0);this.instance=It(this,{form:this.assignedForm,client:r,formId:n,theme:this.assignedTheme,initialData:this.assignedInitialData,preview:this.previewAttrEnabled()?!0:void 0,renderOnly:this.renderOnlyAttrEnabled()?!0:void 0,onChange:i=>this.dispatchEvent(new CustomEvent("fillo-change",{detail:{data:i}})),onSubmitted:(i,o)=>this.dispatchEvent(new CustomEvent("fillo-submit",{detail:{responseId:i,data:o}})),onError:i=>this.dispatchEvent(new CustomEvent("fillo-error",{detail:{error:i}}))}),this.mounted=!0}};function On(e="fillo-form"){typeof customElements>"u"||customElements.get(e)||customElements.define(e,Mn)}typeof customElements<"u"&&On();return ro(Fa);})();
|