@tinkerlandai/indiana-sdk 0.3.1 → 0.5.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/CHANGELOG.md +19 -0
- package/README.md +18 -13
- package/README.zh-CN.md +7 -4
- package/THIRD_PARTY_NOTICES.md +27 -0
- package/dist/ai-usage-BzydP8eN.d.ts +11085 -0
- package/dist/chunk-3OSMEG44.js +17 -0
- package/dist/chunk-GA6X57BO.js +1 -0
- package/dist/chunk-GTBD4BJ4.js +11 -0
- package/dist/chunk-QUW4UOKZ.js +4 -0
- package/dist/chunk-RMFH5TWV.js +1 -0
- package/dist/chunk-YNUVRZRQ.js +1 -0
- package/dist/chunk-ZT523F45.js +1 -0
- package/dist/funnel-runtime-host-RZRB2CY6.js +1 -0
- package/dist/{funnel-runtime-start-CQhy2kx1.d.ts → funnel-runtime-start-JHA9ES24.d.ts} +68 -29
- package/dist/index.d.ts +109 -53
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +3 -2
- package/dist/openrouter.js +1 -1
- package/dist/page.d.ts +13 -12
- package/dist/page.js +1 -4
- package/dist/{paywall-Y3FIG43H.js → paywall-MYBEOVTQ.js} +1 -1
- package/dist/popup.d.ts +254 -1
- package/dist/popup.js +8 -7
- package/dist/{screen-Keau_Qa2.d.ts → screen-16d-xADb.d.ts} +354 -463
- package/dist/server.d.ts +4 -3
- package/dist/server.js +1 -1
- package/dist/src-E2GXK6WA.js +1 -0
- package/dist/visual-editor-agent-FDCV3BXP.js +1 -0
- package/dist/visual.d.ts +38 -0
- package/dist/visual.js +1 -0
- package/package.json +8 -2
- package/dist/ai-usage-D_mBF5Gp.d.ts +0 -9942
- package/dist/chunk-CRJJ4EA2.js +0 -1
- package/dist/chunk-D37O6FAW.js +0 -11
- package/dist/chunk-G5ZGWOLJ.js +0 -1
- package/dist/chunk-MJG7X7LM.js +0 -17
- package/dist/funnel-runtime-host-X7AGEGHN.js +0 -1
- package/dist/src-RZJKF6LQ.js +0 -1
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{z as Q}from"zod";var st=Q.enum(["sandbox","live"]),we=Q.object({projectId:Q.string().min(1),environment:st}).strict();function X(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function L(e,t,n){return n===2?X(X(e+t)+"")%1e4/1e4:null}function ve(e){return e<=0?[]:new Array(e).fill(1/e)}function H(e,t){return e>=t[0]&&e<t[1]}function Y(e,t){for(let[n,r]of t.entries())if(H(e,r))return n;return-1}function Z(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=ve(e);n=n||r,n.length!==e&&(n=r);let o=n.reduce((u,l)=>l+u,0);(o<.99||o>1.01)&&(n=r);let s=0,i=t;return n.map(u=>{let l=s;return s+=u,[l,l+i*u]})}function ee(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let s=r.replace(/#.*/,"").split("&").map(i=>i.split("=",2)).filter(([i])=>i===e).map(([,i])=>i===void 0?NaN:parseInt(i))[0];return s!==void 0&&s>=0&&s<n?s:null}function te(e){try{return e()}catch{return!1}}function _(e){return typeof e=="string"?e:JSON.stringify(e)}function w(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function Ae(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function ne(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let o of t){let s=ct(e,o.type,o.pattern);if(o.include===!1){if(s)return!1}else n=!0,s&&(r=!0)}return r||!n}function at(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function ut(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((o,s)=>{r.push([e.searchParams.get(s)||"",o,!1])}),!r.some(o=>!at(o[0],o[1],o[2]))}catch{return!1}}function ct(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let o=Ae(n);return o?o.test(r.href)||o.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return ut(r,n);return!1}catch{return!1}}function re(e){for(let n of["namespace","status","url","groups"])if(Object.hasOwn(e,n))throw new TypeError(`Retired experiment field: ${n}`);let t=e;if(t.hashVersion!==void 0&&t.hashVersion!==2)throw new TypeError("Only hash version 2 is supported");if(t.filters?.some(n=>n.hashVersion!==2))throw new TypeError("Only hash version 2 is supported")}function P(e){for(let t of Object.values(e)){if(Array.isArray(t))throw new TypeError("Saved groups require typed list or condition entries");if(t&&Object.hasOwn(t,"useEmptyListGroup"))throw new TypeError("Retired saved group field: useEmptyListGroup")}}function Ee(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);P(e.savedGroups??{})}var lt=e=>e/2**32|0,ft=e=>e>>>0;function Fe(e,t,n,r){let o=lt(n),s=ft(n);e.setUint32(t,r?s:o,r),e.setUint32(t+4,r?o:s,r)}function Oe(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var oe=e=>e?`"${e}" `:"";function dt(e,t=""){if(typeof e!="number")throw new TypeError(oe(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(oe(t)+"expected integer >= 0, got "+e);return e}function K(e,t,n=""){if(Oe(e)&&(t===void 0||e.length===t))return e;t!==void 0&&dt(t,"length");let r=Oe(e),o=t!==void 0?` of length ${t}`:"",s=r?`length=${e.length}`:`type=${typeof e}`,i=oe(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}var pt=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},$e=(e,t)=>{pt(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function ie(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Ve(e,t){K(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function se(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function M(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function F(e,t){return e<<32-t|e>>>t}var ht=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",gt=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Re(e){if(K(e),ht)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=gt[e[n]];return t}function bt(e,t,n="opts"){return $e(e,"defaults"),t!==void 0&&$e(t,n),Object.assign(Object.create(null),e,t)}function Ce(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=bt({},t,"info");let n=(o,s)=>e(s).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}var Be=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function je(e,t,n){return e&t^~e&n}function Te(e,t,n){return e&t^e&n^t&n}var N=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=M(this.buffer)}update(t){ie(this),K(t);let{view:n,buffer:r,blockLen:o}=this,s=t.length,i=!1;for(let u=0;u<s;){let l=Math.min(o-this.pos,s-u);if(l===o){let d=M(t);for(;o<=s-u;u+=o)this.process(d,u);i=!0;continue}r.set(u===0&&l===s?t:t.subarray(u,u+l),this.pos),this.pos+=l,u+=l,this.pos===o&&(this.process(n,0),this.pos=0,i=!0)}return this.length+=t.length,i&&this.roundClean(),this}digestInto(t){ie(this),Ve(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;n[i++]=128,n.fill(0,i),this.padOffset>o-i&&(this.process(r,0),n.fill(0)),Fe(r,o-8,this.length*8,s),this.process(r,0),this.roundClean();let u=t===n?r:M(t),l=this.outputLen,d=l/4,p=this.get();if(l%4||d>p.length)throw new Error("invalid outputLen");for(let f=0;f<d;f++)u.setUint32(4*f,p[f],s)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:o,destroyed:s,pos:i}=this;return t.destroyed=s,t.finished=o,t.length=r,t.pos=i,i&&t.buffer.set(n),t}clone(){return this._cloneInto()}},De=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var mt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),B=new Uint32Array(64),ae=class extends N{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){let{A:t,B:n,C:r,D:o,E:s,F:i,G:u,H:l}=this;return[t,n,r,o,s,i,u,l]}set(t,n,r,o,s,i,u,l){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=u|0,this.H=l|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let f=0;f<16;f++,n+=4)B[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){let m=B[f-15],k=B[f-2],A=F(m,7)^F(m,18)^m>>>3,E=F(k,17)^F(k,19)^k>>>10;B[f]=E+B[f-7]+A+B[f-16]|0}let{A:r,B:o,C:s,D:i,E:u,F:l,G:d,H:p}=this;for(let f=0;f<64;f++){let m=F(u,6)^F(u,11)^F(u,25),k=p+m+je(u,l,d)+mt[f]+B[f]|0,E=(F(r,2)^F(r,13)^F(r,22))+Te(r,o,s)|0;p=d,d=l,l=u,u=i+k|0,i=s,s=o,o=r,r=k+E|0}r=r+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,u=u+this.E|0,l=l+this.F|0,d=d+this.G|0,p=p+this.H|0,this.set(r,o,s,i,u,l,d,p)}roundClean(){se(B)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),se(this.buffer)}},ue=class extends ae{constructor(){super(32,De)}};var _e=Ce(()=>new ue,Be(1));var Ue=new Map,ce=32,Le=new WeakMap,He=new WeakMap;function xt(e){return Re(_e(new TextEncoder().encode(String(e))))}var q=e=>Array.isArray(e)?e.map(q):typeof e=="string"||typeof e=="number"?xt(e):null,z=e=>typeof e=="string"?e.toLowerCase():e;function Me(e){let t=Le.get(e);return t||(t=new Set(e),Le.set(e,t)),t}function yt(e){let t=He.get(e);return t||(t=new Set(e.map(z)),He.set(e,t)),t}function Ne(e){P(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=ce&&Me(n)}return e}function O(e,t,n,r){n=n||{},r||P(n),r=r||new Set;for(let[o,s]of Object.entries(t))switch(o){case"$or":if(!Ke(e,s,n,r))return!1;break;case"$nor":if(Ke(e,s,n,r))return!1;break;case"$and":if(!At(e,s,n,r))return!1;break;case"$not":if(O(e,s,n,r))return!1;break;case"$savedGroup":if(!kt(e,s,n,r))return!1;break;default:if(!I(s,ze(e,o),n,!1,r))return!1}return!0}function kt(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:o,attributeKey:s}=t;if(typeof o!="string"||r.has(o)||s!==void 0&&typeof s!="string")return!1;let i=n[o];if(!i||Array.isArray(i)||typeof i!="object")return!1;let u=new Set(r).add(o);if(i.type==="list"||i.type==="hashed"){let l=s??i.attributeKey;if(typeof l!="string"||!Array.isArray(i.values))return!1;let d=ze(e,l);return U(i.type==="hashed"?q(d):d,i.values)}return i.type==="condition"?!i.condition||typeof i.condition!="object"?!1:O(e,i.condition,n,u):!1}function ze(e,t){let n=t.split("."),r=e;for(let o of n)if(r&&typeof r=="object"&&o in r)r=r[o];else return null;return r}function Ie(e,t=!1){let n=`${e}${t?"/i":""}`,r=Ue.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),Ue.set(n,r)),r}function I(e,t,n,r=!1,o=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!qe(e))return JSON.stringify(t)===JSON.stringify(e);let s=e;for(let i in s)if(!vt(i,t,s[i],n,o))return!1;return!0}function qe(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function St(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function wt(e,t,n,r){if(!Array.isArray(e))return!1;let o=qe(t)?s=>I(t,s,n,!1,r):s=>O(s,t,n,r);for(let s=0;s<e.length;s++)if((e[s]??null)!==null&&o(e[s]))return!0;return!1}function U(e,t,n=!1){if(n){let o;if(t.length>=ce){let s=yt(t);o=i=>{let u=z(i);return!(typeof u=="number"&&Number.isNaN(u))&&s.has(u)}}else o=s=>t.some(i=>z(s)===z(i));return Array.isArray(e)?e.some(s=>o(s)):o(e)}let r=t.length>=ce?(o=>s=>o.has(s))(Me(t)):o=>t.includes(o);return Array.isArray(e)?e.some(o=>r(o)):r(e)}function Ge(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function Pe(e,t,n,r=!1,o=new Set){if(!Array.isArray(e))return!1;for(let s=0;s<t.length;s++){let i=!1;for(let u=0;u<e.length;u++)if(I(t[s],e[u],n,r,o)){i=!0;break}if(!i)return!1}return!0}function vt(e,t,n,r,o=new Set){let s=t,i=n;switch(e){case"$veq":return w(t)===w(n);case"$vne":return w(t)!==w(n);case"$vgt":return w(t)>w(n);case"$vgte":return w(t)>=w(n);case"$vlt":return w(t)<w(n);case"$vlte":return w(t)<=w(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return s<i;case"$lte":return s<=i;case"$gt":return s>i;case"$gte":return s>=i;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?U(t,n):!1;case"$ini":return Array.isArray(n)?U(t,n,!0):!1;case"$inGroup":{let u=r[n],l=Ge(u);return l===null?!1:U(u?.type==="hashed"?q(t):t,l)}case"$notInGroup":{let u=r[n],l=Ge(u);return l===null?!1:!U(u?.type==="hashed"?q(t):t,l)}case"$nin":return Array.isArray(n)?!U(t,n):!1;case"$nini":return Array.isArray(n)?!U(t,n,!0):!1;case"$not":return!I(n,t,r,!1,o);case"$size":return Array.isArray(t)?I(n,t.length,r,!1,o):!1;case"$elemMatch":return wt(t,n,r,o);case"$all":return Array.isArray(n)?Pe(t,n,r,!1,o):!1;case"$alli":return Array.isArray(n)?Pe(t,n,r,!0,o):!1;case"$regex":try{return Ie(n).test(t)}catch{return!1}case"$regexi":try{return Ie(n,!0).test(t)}catch{return!1}case"$type":return St(t)===n;default:return!1}}function Ke(e,t,n,r){if(!t.length)return!0;for(let o of t)if(O(e,o,n,r))return!0;return!1}function At(e,t,n,r){for(let o of t)if(!O(e,o,n,r))return!1;return!0}function le(e){return Ee(e),{context:e,stack:{evaluatedFeatures:new Set}}}function fe(e){return{...e.attributes,...e.attributeOverrides}}function R(e,t,n){let r=t||"id",o="",s=fe(e);return s[r]&&(o=s[r]),!o&&n&&(s[n]&&(o=s[n]),o&&(r=n)),{hashAttribute:r,hashValue:o}}function h(e,t,n){e.context.log?.(t,n)}function G(e,t){return t=t||0,`${e}__${t}`}function J(e,t){return`${e}||${t}`}function Et(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:o,hashValue:s}=R(e,t),i=J(o,_(s)),{hashAttribute:u,hashValue:l}=R(e,n),d=l?J(u,_(l)):null,p={};return d&&r[d]&&Object.assign(p,r[d].assignments||{}),r[i]&&Object.assign(p,r[i].assignments||{}),p}function de({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:o,expMinBucketVersion:s,expMeta:i}){n=n||0,s=s||0,r=r||"id",i=i||[];let u=G(t,n),l=Et(e,r,o);if(s>0)for(let f=0;f<s;f++){let m=G(t,f);if(l[m]!==void 0)return{variation:-1,versionIsBlocked:!0}}let d=l[u];if(d===void 0)return{variation:-1};let p=i.findIndex(f=>f.key===d);return p<0?{variation:-1}:{variation:p}}function pe(e,t,n,r){let o=J(t,n),s=e.stickyBucketAssignmentDocs,i=s&&s[o]?s[o].assignments||{}:{},u={...i,...r},l=JSON.stringify(i)!==JSON.stringify(u);return{key:o,doc:{attributeName:t,attributeValue:n,assignments:u},changed:l}}function Ft(e){let t=new Set;return Object.values(e).forEach(n=>{if(n.rules)for(let r of n.rules)r.variations&&(t.add(r.hashAttribute||"id"),r.fallbackAttribute&&t.add(r.fallbackAttribute))}),Array.from(t)}function Ot(e,t=e.features||{}){let n={};return Ft(t).forEach(r=>{let{hashValue:o}=R(e,r);n[r]=_(o)}),n}function y(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function $t(e){return y({...e,parentConditions:e.parentConditions?.map(t=>y(t)),filters:e.filters?.map(t=>y(t)),meta:e.meta?.map(t=>y(t))})}function Je(e){return y({...e,parentConditions:e.parentConditions?.map(t=>y(t)),filters:e.filters?.map(t=>y(t)),meta:e.meta?.map(t=>y(t)),tracks:e.tracks?.map(t=>({experiment:$t(t.experiment),result:y(t.result)}))})}function We(e,t){let n=le(t),r=Ye(e,null,n);return t.onExperimentEval?.(e,r),r}function Qe(e,t){return ge(e,le(t))}function Vt(e){return e.forcedVariations||{}}function Xe(e,t,n){let{context:r}=e;if(r.trackedExperiments){let o=tt(t,n);if(r.trackedExperiments.has(o))return;r.trackedExperiments.add(o)}he(()=>r.onExperimentViewed?.(t,n))}function Rt(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let o=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===o)return;r.trackedFeatureUsage[t]=o}he(()=>r.onFeatureUsage?.(t,n))}function he(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function ge(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return h(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),j(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let s of r?.rules??[])re(s);let o=n.forcedFeatureValues;if(o&&o.has(e))return h(t,"Global override",{id:e,value:o.get(e)}),j(t,e,o.get(e),"override");if(!r)return h(t,"Unknown feature",{id:e}),j(t,e,null,"unknownFeature");if(r.rules){let s=new Set(t.stack.evaluatedFeatures);e:for(let i of r.rules){if(i.parentConditions)for(let d of i.parentConditions){t.stack.evaluatedFeatures=new Set(s);let p=ge(d.id,t);if(p.source==="cyclicPrerequisite")return j(t,e,null,"cyclicPrerequisite");let f={value:p.value};if(!O(f,d.condition||{},n.savedGroups||{})){if(d.gate)return h(t,"Feature blocked by prerequisite",{id:e,rule:i}),j(t,e,null,"prerequisite");h(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:i});continue e}}if(i.filters&&et(i.filters,t)){h(t,"Skip rule because of filters",{id:e,rule:i});continue}if("force"in i){if(i.condition&&!Ze(i.condition,t)){h(t,"Skip rule because of condition ff",{id:e,rule:i});continue}if(!Ct(t,i.seed||e,i.hashAttribute,n.saveStickyBucketAssignmentDoc&&!i.disableStickyBucketing?i.fallbackAttribute:void 0,i.range,i.coverage,i.hashVersion)){h(t,"Skip rule because user not included in rollout",{id:e,rule:i});continue}return h(t,"Force value from rule",{id:e,rule:i}),i.tracks&&i.tracks.forEach(d=>{Xe(t,d.experiment,d.result)}),j(t,e,i.force,"force",i.id)}if(!i.variations){h(t,"Skip invalid rule",{id:e,rule:i});continue}let u={variations:i.variations,key:i.key||e};"coverage"in i&&(u.coverage=i.coverage),i.weights&&(u.weights=i.weights),i.hashAttribute&&(u.hashAttribute=i.hashAttribute),i.fallbackAttribute&&(u.fallbackAttribute=i.fallbackAttribute),i.disableStickyBucketing&&(u.disableStickyBucketing=i.disableStickyBucketing),i.bucketVersion!==void 0&&(u.bucketVersion=i.bucketVersion),i.minBucketVersion!==void 0&&(u.minBucketVersion=i.minBucketVersion),i.meta&&(u.meta=i.meta),i.ranges&&(u.ranges=i.ranges),i.name&&(u.name=i.name),i.phase&&(u.phase=i.phase),i.seed&&(u.seed=i.seed),i.hashVersion&&(u.hashVersion=i.hashVersion),i.filters&&(u.filters=i.filters),i.condition&&(u.condition=i.condition);let l=Ye(u,e,t);if(n.onExperimentEval?.(u,l),l.inExperiment&&!l.passthrough)return j(t,e,l.value,"experiment",i.id,u,l)}}return h(t,"Use default value",{id:e,value:r.defaultValue}),j(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Ye(e,t,n){let{context:r}=n;re(e);let o=e.key,s=e.variations.length;if(s<2)return h(n,"Invalid experiment",{id:o}),x(n,e,-1,!1,t);if(r.enabled===!1)return h(n,"Context disabled",{id:o}),x(n,e,-1,!1,t);if(e.urlPatterns&&!ne(r.url||"",e.urlPatterns))return h(n,"Skip because of url targeting",{id:o}),x(n,e,-1,!1,t);let i=ee(o,r.url||"",s);if(i!==null)return h(n,"Force via querystring",{id:o,variation:i}),x(n,e,i,!1,t);let l=Vt(r)[o];if(l!==void 0)return h(n,"Force via dev tools",{id:o,variation:l}),x(n,e,l,!1,t);if(e.active===!1)return h(n,"Skip because inactive",{id:o}),x(n,e,-1,!1,t);let{hashAttribute:d,hashValue:p}=R(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!p)return h(n,"Skip because missing hashAttribute",{id:o}),x(n,e,-1,!1,t);let f=-1,m=!1,k=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:S,versionIsBlocked:$}=de(y({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));m=S>=0,f=S,k=!!$}if(!m){if(e.filters&&et(e.filters,n))return h(n,"Skip because of filters",{id:o}),x(n,e,-1,!1,t);if(e.include&&!te(e.include))return h(n,"Skip because of include function",{id:o}),x(n,e,-1,!1,t);if(e.condition&&!Ze(e.condition,n))return h(n,"Skip because of condition exp",{id:o}),x(n,e,-1,!1,t);if(e.parentConditions){let S=new Set(n.stack.evaluatedFeatures);for(let $ of e.parentConditions){n.stack.evaluatedFeatures=new Set(S);let V=ge($.id,n);if(V.source==="cyclicPrerequisite")return x(n,e,-1,!1,t);let D={value:V.value};if(!O(D,$.condition||{},r.savedGroups||{}))return h(n,"Skip because prerequisite evaluation fails",{id:o}),x(n,e,-1,!1,t)}}}let A=L(e.seed||o,p,e.hashVersion??2);if(A===null)return h(n,"Skip because of invalid hash version",{id:o}),x(n,e,-1,!1,t);if(!m){let S=e.ranges||Z(s,e.coverage===void 0?1:e.coverage,e.weights);f=Y(A,S)}if(k)return h(n,"Skip because sticky bucket version is blocked",{id:o}),x(n,e,-1,!1,t,void 0,!0);if(f<0)return h(n,"Skip because of coverage",{id:o}),x(n,e,-1,!1,t);if("force"in e)return h(n,"Force variation",{id:o,variation:e.force}),x(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return h(n,"Skip because QA mode",{id:o}),x(n,e,-1,!1,t);let E=x(n,e,f,!0,t,A,m);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:S,key:$,doc:V}=pe(r,d,_(p),{[G(e.key,e.bucketVersion)]:E.key});if(S){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[$]=V;let D=r.saveStickyBucketAssignmentDoc;he(()=>D(V))}}return Xe(n,e,E),h(n,"In experiment",{id:o,variation:E.variationId}),E}function j(e,t,n,r,o,s,i){let u={value:n,on:!!n,off:!n,source:r,ruleId:o||""};return s&&(u.experiment=s),i&&(u.experimentResult=i),r!=="override"&&Rt(e,t,u),u}function Ze(e,t){return O(fe(t.context),e,t.context.savedGroups||{})}function et(e,t){return e.some(n=>{let{hashValue:r}=R(t.context,n.attribute);if(!r)return!0;let o=L(n.seed,r,n.hashVersion||2);return o===null?!0:!n.ranges.some(s=>H(o,s))})}function Ct(e,t,n,r,o,s,i){if(!o&&s===void 0)return!0;if(!o&&s===0)return!1;let{hashValue:u}=R(e.context,n,r);if(!u)return!1;let l=L(t,u,i??2);return l===null?!1:o?H(l,o):s!==void 0?l<=s:!0}function x(e,t,n,r,o,s,i){let u=!0;(n<0||n>=t.variations.length)&&(n=0,u=!1);let{hashAttribute:l,hashValue:d}=R(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),p=t.meta?.[n]??{},f=t.variations[0];for(let[k,A]of t.variations.entries())if(k===n){f=A;break}let m={key:p.key||""+n,featureId:o,inExperiment:u,hashUsed:r,variationId:n,value:f,hashAttribute:l,hashValue:d,stickyBucketUsed:!!i};return p.name&&(m.name=p.name),s!==void 0&&(m.bucket=s),p.passthrough&&(m.passthrough=p.passthrough),m}function tt(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
|
|
2
|
+
Copyright (c) 2025 GrowthBook, Inc.
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
|
5
|
+
furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all
|
|
8
|
+
copies or substantial portions of the Software.
|
|
9
|
+
|
|
10
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
11
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
12
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
13
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
14
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
15
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
16
|
+
SOFTWARE.
|
|
17
|
+
*/import{z as a}from"zod";var v=a.json().superRefine((e,t)=>{let n=0;function r(o,s){if(++n>1e4||s>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof o=="string"&&(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(o))o.forEach(i=>r(i,s+1));else if(o&&typeof o=="object")for(let[i,u]of Object.entries(o))(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i)||["__proto__","prototype","constructor"].includes(i))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(u,s+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),me=a.record(a.string().min(1).max(128),v).superRefine((e,t)=>{(!v.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),Bt=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),T=me.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[o,s]of Object.entries(r)){if(o==="$savedGroup"&&!a.strictObject({id:a.uuid(),attributeKey:a.string().min(1).max(128).optional()}).safeParse(s).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!o.startsWith("$")&&o.split(".").some(i=>["__proto__","prototype","constructor"].includes(i))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),o.startsWith("$")&&!Bt.has(o)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${o}`}),["$regex","$regexi"].includes(o)&&typeof s=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(s)||[...s.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(i=>Number(i[1])>255||Number(i[2]||0)>255)||o==="$regexi"&&/[^\x00-\x7f]/.test(s.replace(/\\u([0-9a-f]{4})/gi,(i,u)=>String.fromCharCode(Number.parseInt(u,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(s)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(s)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),jt=a.discriminatedUnion("type",[a.strictObject({type:a.literal("condition"),condition:T}),a.strictObject({type:a.literal("list"),attributeKey:a.string().min(1).max(128),values:a.array(a.union([a.string(),a.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Tt(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[o,s]of Object.entries(r))o==="$savedGroup"&&s&&typeof s=="object"&&!Array.isArray(s)&&typeof s.id=="string"?t.add(s.id):["$inGroup","$notInGroup"].includes(o)&&typeof s=="string"?t.add(s):["$eq","$ne","$in","$nin","$ini","$nini"].includes(o)||n(s)}return n(e),[...t]}var Dt=a.record(a.uuid(),jt).superRefine((e,t)=>{let n=new Set,r=new Set;function o(s){if(n.has(s)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(s))return;let i=e[s];if(!i){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(s),i.type==="condition"&&Tt(i.condition).forEach(o),n.delete(s),r.add(s)}Object.keys(e).forEach(o)}),xe=a.tuple([a.number().min(0).max(1),a.number().min(0).max(1)]).refine(([e,t])=>e<=t),nt=a.strictObject({attribute:a.string().optional(),seed:a.string().min(1),hashVersion:a.literal(2),ranges:a.array(xe).min(1).max(100)}),_t=a.strictObject({id:a.string().min(1).max(128),condition:T,gate:a.boolean().optional()}),be={id:a.string().max(128).optional(),condition:T.optional(),parentConditions:a.array(_t).max(50).optional(),filters:a.array(nt).max(20).optional()},Ut=a.union([a.strictObject({...be}),a.strictObject({...be,force:v,coverage:a.number().min(0).max(1).optional(),range:xe.optional(),seed:a.string().min(1).optional(),hashAttribute:a.string().optional(),hashVersion:a.literal(2).optional()}),a.strictObject({...be,type:a.literal("experiment-ref"),experimentId:a.uuid(),values:a.record(a.string().min(1),v),meta:a.record(a.string().min(1),a.strictObject({passthrough:a.boolean()})).optional()})]),Lt=a.strictObject({defaultValue:v,rules:a.array(Ut).max(100)}),Nn=a.record(a.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Lt).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function o(s){if(n.has(s)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${s}`});return}if(r.has(s))return;let i=e[s];if(!i){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${s}`});return}n.add(s);for(let u of i.rules)for(let l of u.parentConditions??[])o(l.id);n.delete(s),r.add(s)}Object.keys(e).forEach(o)}),Ht=a.strictObject({name:a.string().max(80),reason:a.string().max(500),dateStarted:a.iso.datetime({offset:!0}),dateEnded:a.iso.datetime({offset:!0}).nullable(),coverage:a.number().min(0).max(1),variationWeights:a.array(a.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:T,savedGroups:a.array(a.strictObject({match:a.enum(["any","all","none"]),ids:a.array(a.uuid()).min(1)})).max(50),namespace:a.strictObject({id:a.uuid(),ranges:a.array(xe).min(1)}).nullable(),seed:a.string().min(1).max(128)}),It=a.strictObject({key:a.string().min(1).max(128),name:a.string().min(1).max(80),hypothesis:a.string().max(2e3),status:a.enum(["draft","running","stopped"]),hashAttribute:a.string().min(1).max(128),fallbackAttribute:a.string().max(128).nullable(),hashVersion:a.literal(2),disableStickyBucketing:a.boolean(),bucketVersion:a.number().int().min(0).max(1e3),minBucketVersion:a.number().int().min(0).max(1e3),variations:a.array(a.strictObject({id:a.string().min(1),key:a.string().min(1),name:a.string().max(80),description:a.string().max(500)})).min(2).max(20),phases:a.array(Ht).min(1).max(100),releasedVariationId:a.string().nullable(),excludeFromPayload:a.boolean(),statusSchedule:a.strictObject({startAt:a.iso.datetime({offset:!0}).nullable(),stopAt:a.iso.datetime({offset:!0}).nullable(),stopAfter:a.strictObject({value:a.number().int().positive().max(36500),unit:a.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let o=e.phases[r-1];return!o?.dateEnded||Date.parse(n.dateStarted)<Date.parse(o.dateStarted)||Date.parse(o.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,o],s,i)=>r>=o||i.some(([u,l],d)=>d!==s&&r<l&&u<o)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});function zn(e,t,n=Date.now()){return Object.fromEntries(Object.entries(e).map(([r,o])=>[r,{defaultValue:o.defaultValue,rules:o.rules.flatMap(s=>{if(!("experimentId"in s))return[Je({...s,hashVersion:2})];let i=t[s.experimentId];if(!i)throw new Error(`Missing experiment: ${s.experimentId}`);let u=i.phases.at(-1);if(!u)throw new Error("Experiment requires an active phase");let l=i.statusSchedule?.startAt?Date.parse(i.statusSchedule.startAt):null,d=rt(i),p=i.status!=="stopped"&&(i.status==="running"||l!==null&&n>=l)&&(l===null||n>=l)&&(d===null||n<d),{type:f,experimentId:m,values:k,meta:A,...E}=s,S=y({...E,parentConditions:E.parentConditions?.map(b=>y(b)),filters:E.filters?.map(b=>y(b))});if(i.variations.some(b=>!Object.hasOwn(k,b.key))||Object.keys(k).length!==i.variations.length||Object.keys(A??{}).some(b=>!i.variations.some(C=>C.key===b)))throw new Error("Every variation needs a Feature value");let $=b=>{let C=k[b];if(C===void 0)throw new Error("Every variation needs a Feature value");return C},V={$and:[u.condition,...S.condition?[S.condition]:[],...u.savedGroups.map(b=>{let C=b.ids.map(it=>({$savedGroup:{id:it}}));return b.match==="all"?{$and:C}:b.match==="none"?{$nor:C}:{$or:C}})]},D=i.variations.find(b=>b.id===i.releasedVariationId);return D&&!i.excludeFromPayload?A?.[D.key]?.passthrough?[{...S,condition:V}]:[{...S,condition:V,force:$(D.key)}]:[{...S,condition:V,key:i.key,variations:i.variations.map(b=>$(b.key)),meta:i.variations.map(b=>({key:b.key,name:b.name,...y(A?.[b.key]??{})})),weights:u.variationWeights,coverage:p?u.coverage:0,seed:u.seed,hashVersion:2,hashAttribute:i.hashAttribute,...i.fallbackAttribute===null?{}:{fallbackAttribute:i.fallbackAttribute},disableStickyBucketing:!p||i.disableStickyBucketing,bucketVersion:i.bucketVersion,minBucketVersion:i.minBucketVersion,filters:[...S.filters??[],...(i.filters??[]).map(b=>y(b))]}]})}]))}function rt(e){if(e.statusSchedule?.stopAt)return Date.parse(e.statusSchedule.stopAt);let t=e.statusSchedule?.stopAfter;if(!t||e.status==="draft"&&!e.statusSchedule?.startAt)return null;let n=e.statusSchedule?.startAt??e.phases.at(-1)?.dateStarted;if(!n)throw new Error("Experiment requires an active phase");return Date.parse(n)+t.value*(t.unit==="days"?864e5:36e5)}function qn(e,t=Date.now()){let n=Object.values(e).filter(r=>r.status!=="stopped"&&!(r.releasedVariationId&&!r.excludeFromPayload)).flatMap(r=>[r.statusSchedule?.startAt?Date.parse(r.statusSchedule.startAt):null,rt(r)]).filter(r=>r!==null&&r>t);return n.length?new Date(Math.min(...n)).toISOString():null}var Gt=It.safeExtend({filters:a.array(nt).optional()}),Pt=a.strictObject({experiments:a.record(a.uuid(),Gt),savedGroups:Dt}),Kt=a.strictObject({attributeName:a.string(),attributeValue:a.string(),assignments:a.record(a.string(),a.string())}),Jn=a.strictObject({snapshot:Pt,attributes:me,results:me,stickyBucketAssignmentDocs:a.record(a.string(),Kt)}),Wn=a.strictObject({variantKey:a.string().nullable(),bucketVersion:a.number().int().min(0),source:a.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:a.number().min(0).max(1).optional(),stickyBucketUsed:a.boolean().optional(),hashUsed:a.boolean().optional()});import{z as c}from"zod";var ye=c.tuple([c.number().min(0).max(1),c.number().min(0).max(1)]).refine(([e,t])=>e<=t),Mt=c.strictObject({attribute:c.string().optional(),seed:c.string(),hashVersion:c.literal(2),ranges:c.array(ye).max(100)}),Nt=c.strictObject({id:c.string().min(1).max(255),condition:T,gate:c.boolean().optional()}),zt=c.strictObject({key:c.string().optional(),name:c.string().optional(),passthrough:c.boolean().optional()}),ot={condition:T.optional(),parentConditions:c.array(Nt).max(100).optional(),weights:c.array(c.number().min(0).max(1)).max(20).optional(),coverage:c.number().min(0).max(1).optional(),hashAttribute:c.string().optional(),fallbackAttribute:c.string().optional(),hashVersion:c.literal(2).optional(),disableStickyBucketing:c.boolean().optional(),bucketVersion:c.number().int().nonnegative().optional(),minBucketVersion:c.number().int().nonnegative().optional(),filters:c.array(Mt).max(100).optional(),ranges:c.array(ye).max(20).optional(),meta:c.array(zt).max(20).optional(),seed:c.string().optional(),name:c.string().optional(),phase:c.string().optional()},W=c.strictObject({...ot,key:c.string().min(1).max(255),variations:c.tuple([v,v]).rest(v).refine(e=>e.length<=20),urlPatterns:c.array(c.strictObject({include:c.boolean(),type:c.enum(["regex","simple"]),pattern:c.string()})).max(100).optional(),force:c.number().int().nonnegative().optional(),active:c.boolean().optional(),persistQueryString:c.boolean().optional()}),qt=c.strictObject({value:v,variationId:c.number().int(),key:c.string(),name:c.string().optional(),bucket:c.number().optional(),passthrough:c.boolean().optional(),inExperiment:c.boolean(),hashUsed:c.boolean().optional(),hashAttribute:c.string(),hashValue:c.string(),featureId:c.string().nullable(),stickyBucketUsed:c.boolean().optional()}),Jt=c.strictObject({...ot,id:c.string().max(255).optional(),force:v.optional(),variations:c.array(v).min(2).max(20).optional(),key:c.string().optional(),range:ye.optional(),tracks:c.array(c.strictObject({experiment:W,result:qt})).max(100).optional()}),Wt=c.strictObject({defaultValue:v.optional(),rules:c.array(Jt).max(500).optional()}),ke=c.record(c.string(),c.union([c.strictObject({type:c.literal("hashed"),attributeKey:c.string(),values:c.array(c.string().regex(/^[a-f0-9]{64}$/))}),c.strictObject({type:c.literal("list"),attributeKey:c.string(),values:c.array(c.union([c.string(),c.number()]))}),c.strictObject({type:c.literal("condition"),condition:T})])),er=c.strictObject({scope:we,generation:c.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:c.iso.datetime({offset:!0}),expiresAt:c.iso.datetime({offset:!0}).nullable(),features:c.record(c.string(),Wt),savedGroups:ke,experiments:c.record(c.uuid(),W)});import{z as g}from"zod";var Qt=g.strictObject({selector:g.string().min(1).max(2048),action:g.enum(["set","append","remove"]),attribute:g.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:g.string().max(5e4).optional(),parentSelector:g.string().max(2048).optional(),insertBeforeSelector:g.string().max(2048).optional()}),Xt=g.strictObject({variation:g.string().min(1).max(128),description:g.string().max(2e3).default(""),css:g.string().max(1e5).default(""),js:g.string().max(1e5).default(""),domMutations:g.array(Qt).max(200).default([])}),Se=Xt.omit({variation:!0,description:!0}),Yt=W.omit({variations:!0,active:!0}).extend({changeId:g.string().regex(/^[a-f0-9]{64}$/),variations:g.tuple([Se,Se]).rest(Se).refine(e=>e.length<=20)}),or=g.strictObject({environmentId:g.uuid(),trackExposures:g.boolean(),generation:g.string().regex(/^[a-f0-9]{64}$/),experiments:g.array(Yt).max(100),savedGroups:ke}),ir="__indiana_visual_editor",sr=g.object({selector:g.string().max(2048),tag:g.string().max(64),text:g.string().max(1e3),href:g.string().max(2048),src:g.string().max(2048),matches:g.number().int().nonnegative()});export{st as a,we as b,ee as c,_ as d,ne as e,Ne as f,O as g,Ot as h,We as i,Qe as j,tt as k,v as l,me as m,T as n,jt as o,Tt as p,Dt as q,Ut as r,Lt as s,Nn as t,Ht as u,It as v,zn as w,rt as x,qn as y,Gt as z,Pt as A,Kt as B,Jn as C,Wn as D,W as E,qt as F,Jt as G,Wt as H,ke as I,er as J,Qt as K,Xt as L,Se as M,Yt as N,or as O,ir as P,sr as Q};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as c,b as x}from"./chunk-YNUVRZRQ.js";import{Bi as A,Bk as U,Mk as T,Sk as L,Te as k,ei as _,hi as q}from"./chunk-GTBD4BJ4.js";import{J as N,f as P,g as D,i as V,j as R,m as b}from"./chunk-3OSMEG44.js";function j(a){let e=null,u=null,l=0,r=0,s=new Set,n=null,i=null,y=new Set,v=()=>{for(let t of y)try{t()}catch{}},o={attributes:b.parse(a.attributes??{}),onFeatureUsage:a.onFeatureUsage?(t,f)=>{!s.has(t)&&(!e||!("analyticsConfig"in e)||e.analyticsConfig.featureUsageEnabled)&&a.onFeatureUsage(t,structuredClone(f))}:void 0,onExperimentViewed:a.onExperimentViewed?(t,f)=>(!e||!("analyticsConfig"in e)||e.analyticsConfig.experimentViewsEnabled)&&a.onExperimentViewed(structuredClone(t),structuredClone(f)):void 0,stickyBucketAssignmentDocs:structuredClone(a.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:a.saveStickyBucketAssignmentDoc?t=>a.saveStickyBucketAssignmentDoc(structuredClone(t)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function d(t,f=new Set){return s.has(t)?!n||!n.features[t]||["unknownFeature","cyclicPrerequisite"].includes(n.features[t].source):f.has(t)?!1:(f.add(t),(e?.features[t]?.rules??[]).some(p=>[...p.parentConditions??[],...(p.tracks??[]).flatMap(h=>h.experiment.parentConditions??[])].some(h=>d(h.id,f))))}let m=t=>{if(!e)throw new Error("Initialize the Feature client before evaluation");if(e.expiresAt&&Date.parse(e.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return n?.expiresAt&&Date.parse(n.expiresAt)<=Date.now()&&(n=null,o.features=e.features),s.has(t)?!n||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now()?w():structuredClone(n.features[t]??w()):d(t)?w():structuredClone(R(t,o))};async function g(){if(!e||!s.size)return;if(!a.evaluateRemote)throw new Error("Remote Feature evaluation requires a server loader");let t=r;if(i?.revision===t)return i.loading;let f=l,p=e,h=[...s],I=(async()=>{let E=q.parse(await a.evaluateRemote({attributes:structuredClone(o.attributes),features:h}));if(!(f!==l||t!==r||p!==e)){if(E.generation!==p.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(h.some(S=>!Object.hasOwn(E.features,S))||Object.keys(E.features).some(S=>!s.has(S)))throw new Error("Invalid remote Feature results");n=structuredClone(E),o.features={...p.features,...Object.fromEntries(Object.entries(n.features).map(([S,B])=>[S,{defaultValue:B.value}]))},v()}})();i={revision:t,loading:I};try{await I}finally{i?.loading===I&&(i=null)}}function C(){g().catch(t=>{try{a.onError?.(t)}catch{}})}async function F(){if(u)return u;let t=l,f=(async()=>{let p=await a.load(),h="remoteFeatures"in p?_.parse(p):null,I=h??N.parse(p);if(I.scope.projectId!==a.scope.projectId||I.scope.environment!==a.scope.environment)throw new Error("Feature payload scope changed");if(t!==l)throw new Error("Feature client was reset");let E=new Set(h?.remoteFeatures??[]);if([...E].some(S=>Object.hasOwn(I.features,S)))throw new Error("Remote Feature definitions must not be delivered locally");return e&&"analyticsConfig"in e&&"analyticsConfig"in I&&!e.analyticsConfig.experimentViewsEnabled&&h?.analyticsConfig.experimentViewsEnabled&&o.trackedExperiments?.clear(),e=structuredClone(I),s=E,n=null,i=null,r++,o.features=e.features,o.savedGroups=P(e.savedGroups),o.trackedFeatureUsage={},v(),C(),structuredClone(e)})();u=f;try{return await f}finally{u===f&&(u=null)}}return{init:F,refresh:F,refreshRemote:g,get generation(){return e?.generation??null},get expiresAt(){return e?.expiresAt??null},subscribe(t){return y.add(t),()=>{y.delete(t)}},setAttributes(t){o.attributes=b.parse(t),r++,n=null,i=null,o.features=e?.features??{},o.trackedFeatureUsage={},v(),C()},evalFeature:m,isOn(t){return m(t).on},isOff(t){return m(t).off},getFeatureValue(t,f){let p=m(t).value;return structuredClone(p===null?f:p)},reset(){l++,r++,u=null,i=null,e=null,n=null,s.clear(),o.features={},o.savedGroups={},o.stickyBucketAssignmentDocs={},o.attributes={},o.trackedFeatureUsage={},o.trackedExperiments?.clear(),v()}}}async function M(a,e){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(e.customerToken))throw new c("INVALID_TOKEN","A verified Customer credential is required");let u=x(a);u.identify(e.customerToken);let l=A.resolvePaywall.request.parse({selector:{type:"paywall",paywallId:e.paywallId},commerce:e.commerce,locale:e.locale,...e.requirement?{requirement:e.requirement}:{}}),r=null,s=null,n=null,i=null,y=null;async function v(){let d=A.resolvePaywall,m=d.response.parse(await u.request(d.path,d.request.parse({...l,selector:r?{type:"version",versionId:r.id}:l.selector})));if(m.paywall.paywallId!==e.paywallId)throw new c("INVALID_RESPONSE","The requested Paywall changed");if(r&&(m.paywall.id!==r.id||m.paywall.paywallId!==r.paywallId||m.paywall.offering.id!==r.offering.id))throw new c("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return r=m.paywall,structuredClone(r)}async function o(d){if(!s)throw new c("INVALID_REQUEST","A quoted purchase is required");let m=d==="read"?A.readSubscriptionOperation:A.attach,g=m.response.parse(await u.request(m.path,m.request.parse({operationId:s.operationId,...d==="read"?{}:{intent:d}})));if(g.operation.operationId!==s.operationId||g.operation.currency!==l.commerce.currency)throw new c("INVALID_RESPONSE","The purchase operation changed");return n?.status==="complete"&&g.operation.status!=="complete"||n&&n.status!=="pending"&&g.operation.status==="pending"||(n=g.operation),structuredClone(n)}let w={get view(){return r?structuredClone(r):null},get quote(){return s?structuredClone(s):null},get operation(){return n?structuredClone(n):null},get webViewUrl(){return u.webViewUrl()},refresh:v,async preview(d){if(!r)throw new c("INVALID_REQUEST","Load the Paywall first");let m=r.document.buttons[d.actionId];if(m?.type!=="checkout")throw new c("INVALID_REQUEST","Choose an authored purchase action");let g=k(m.product,d.selection,r.capabilities);if(!g)throw new c("PRODUCT_UNAVAILABLE","Choose an available Product");let C=A.previewAttach.request.parse({requestId:d.requestId,plans:[{productVersionId:g}],provider:l.commerce.provider,currency:l.commerce.currency,...d.offerId?{offerId:d.offerId}:{},...d.nativeOffer?{nativeOffer:d.nativeOffer}:{}}),F=JSON.stringify(C);if(i&&i!==F&&(!n||n.status==="pending"))throw new c("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(i===F){if(y)return y;if(s)return structuredClone(s)}i=F;let t=(async()=>{let f=A.previewAttach,p=f.response.parse(await u.request(f.path,C));if(p.quote.currency!==l.commerce.currency||p.quote.provider!==l.commerce.provider||p.quote.lines.length!==1||p.quote.lines[0].productVersionId!==g)throw new c("INVALID_RESPONSE","The purchase quote changed its selected Product or presentment");return s=p.quote,n=null,structuredClone(s)})();y=t;try{return await t}finally{y===t&&(y=null)}},confirm:()=>o("confirm"),cancel:()=>o("cancel"),read:()=>o("read"),destroy(){u.reset(),r=null,s=null,n=null,i=null}};return await v(),w}function X(a,e,u){let l=L.parse(a);if(l.evaluationMode!=="local")throw new c("EVALUATION_MODE","Remote nodes are evaluated by Grow");if(l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())throw new c("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition");let r=l.topology.nodes.find(o=>o.id===e);if(!r)throw new c("NOT_FOUND","Funnel node is unavailable");let s=b.parse(u.attributes??{}),n={attributes:s,saveStickyBucketAssignmentDoc:u.saveStickyBucketAssignmentDoc?o=>u.saveStickyBucketAssignmentDoc(structuredClone(o)):void 0,onFeatureUsage:u.onFeatureUsage?(o,w)=>u.onFeatureUsage(o,structuredClone(w)):void 0,onExperimentViewed:u.onExperimentViewed?(o,w)=>u.onExperimentViewed(structuredClone(o),structuredClone(w)):void 0,features:structuredClone(l.growth.features),savedGroups:P(l.growth.savedGroups),stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)},i,y;if(r.type==="condition"){let o=l.conditions[r.id];if(!o)throw new c("INVALID_RESPONSE","Local condition rules are unavailable");i=o.find(w=>D(s,w.condition,n.savedGroups))?.port??"default"}else if(r.type==="feature"){if(!r.resources.featureKey)throw new c("INVALID_RESPONSE","Feature reference is unavailable");y=R(r.resources.featureKey,n).value,i="next"}else if(r.type==="split"){let o=r.resources.experimentId,w=o?l.growth.experiments[o]:null;if(!w||!o)throw new c("INVALID_RESPONSE","Experiment reference is unavailable");let d=V(w,n);y=d.value,i=d.inExperiment&&!d.passthrough&&typeof d.value=="string"?d.value:"notParticipating"}else throw new c("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let v=r.outputs[i];if(!v)throw new c("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:e,port:i,target:v,...y===void 0?{}:{value:y}}}function H(a,e){return e.type==="id"?a.customerId===e.value:a.externalUserId===e.value}function O(a,e){if(a===e)return!0;if(Array.isArray(a)||Array.isArray(e))return Array.isArray(a)&&Array.isArray(e)&&a.length===e.length&&a.every((r,s)=>O(r,e[s]));if(!a||!e||typeof a!="object"||typeof e!="object")return!1;let u=Object.entries(a),l=Object.entries(e);return u.length===l.length&&u.every(([r,s])=>Object.hasOwn(e,r)&&O(s,Reflect.get(e,r)))}function ne(a){let e=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(a.apiKey);if(typeof window<"u"&&!e)throw new c("SERVER_ONLY","Funnel starts are issued by your backend");if(!e&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(a.apiKey))throw new c("INVALID_TOKEN","A customer credential or server API key is required");let u=x({...a,timeoutMs:a.timeoutMs??35e3});return u.identify(a.apiKey),{async start(l){let r=U.safeParse({...l,operation:"start"});if(!r.success||r.data.operation!=="start"||(e?r.data.customer!==void 0:r.data.customer===void 0))throw new c("INVALID_REQUEST","Invalid current Funnel start");let s=r.data,n=T.safeParse(await u.request("funnels",s));if(!n.success||!n.data.runToken)throw new c("INVALID_RESPONSE","Funnel start credentials are missing");let i=n.data;if(i.run.source.id!==s.funnelId||i.run.locale!==(s.locale??"en")||!O(i.run.parameters,s.parameters??{})||(s.customer?!i.customerId||s.customer.type==="id"&&i.customerId!==s.customer.value:i.customerId!==void 0))throw new c("INVALID_RESPONSE","Funnel start contract changed");return{...i,runToken:i.runToken}}}}export{j as a,H as b,O as c,M as d,X as e,ne as f};
|