@stndrds/schema 1.0.0-alpha.317 → 1.0.0-alpha.318
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/all-BUvW7Ce2.d.ts +1375 -0
- package/dist/all-CNndYMgi.d.mts +1375 -0
- package/dist/{attributes-2ELU4S-n.d.mts → attributes-B9zZJdoT.d.mts} +3 -1
- package/dist/{attributes-2ELU4S-n.d.ts → attributes-B9zZJdoT.d.ts} +3 -1
- package/dist/{chunk-3VONXKAN.js → chunk-4XVOAVGO.js} +2 -2
- package/dist/{chunk-MMOW6WTJ.mjs → chunk-AQPK2UI7.mjs} +2 -2
- package/dist/{chunk-HS7IRPL2.js → chunk-HRX4YCKZ.js} +1 -1
- package/dist/{chunk-B2W4ZEO2.mjs → chunk-QIDZFNGR.mjs} +1 -1
- package/dist/exceptions.d.mts +1 -1
- package/dist/exceptions.d.ts +1 -1
- package/dist/{helpers-CJpLZ8jG.d.mts → helpers-Cic6nWBr.d.mts} +2 -2
- package/dist/{helpers-CAOdIXNe.d.ts → helpers-JGJLPkwG.d.ts} +2 -2
- package/dist/{index-C6-AlR2_.d.mts → index-Cap0zZBP.d.mts} +1 -1
- package/dist/{index-iKNo_z7O.d.ts → index-iz5DJ6dg.d.ts} +1 -1
- package/dist/index.d.mts +131 -303
- package/dist/index.d.ts +131 -303
- package/dist/index.js +19 -19
- package/dist/index.mjs +18 -18
- package/dist/{types-DFs7mc3G.d.mts → types-BpuX5PuM.d.mts} +1 -1
- package/dist/{types-DjTB_kVH.d.ts → types-DLwv9Jgf.d.ts} +1 -1
- package/dist/utils.d.mts +1 -1
- package/dist/utils.d.ts +1 -1
- package/dist/validation/all.d.mts +5 -5
- package/dist/validation/all.d.ts +5 -5
- package/dist/validation/all.js +1 -1
- package/dist/validation/all.mjs +1 -1
- package/dist/validation/complex/currency.d.mts +2 -2
- package/dist/validation/complex/currency.d.ts +2 -2
- package/dist/validation/complex/location.d.mts +2 -2
- package/dist/validation/complex/location.d.ts +2 -2
- package/dist/validation/complex/phone.d.mts +2 -2
- package/dist/validation/complex/phone.d.ts +2 -2
- package/dist/validation/complex/relation.d.mts +2 -2
- package/dist/validation/complex/relation.d.ts +2 -2
- package/dist/validation/complex/richtext.d.mts +2 -2
- package/dist/validation/complex/richtext.d.ts +2 -2
- package/dist/validation/complex/select.d.mts +2 -2
- package/dist/validation/complex/select.d.ts +2 -2
- package/dist/validation/complex/user.d.mts +2 -2
- package/dist/validation/complex/user.d.ts +2 -2
- package/dist/validation/computed/formula.d.mts +2 -2
- package/dist/validation/computed/formula.d.ts +2 -2
- package/dist/validation/computed/rollup.d.mts +2 -2
- package/dist/validation/computed/rollup.d.ts +2 -2
- package/dist/validation/config/index.d.mts +2 -2
- package/dist/validation/config/index.d.ts +2 -2
- package/dist/validation/config/index.js +1 -1
- package/dist/validation/config/index.mjs +1 -1
- package/dist/validation/core/index.d.mts +3 -3
- package/dist/validation/core/index.d.ts +3 -3
- package/dist/validation/object/index.d.mts +4 -4
- package/dist/validation/object/index.d.ts +4 -4
- package/dist/validation/primitives/checkbox.d.mts +2 -2
- package/dist/validation/primitives/checkbox.d.ts +2 -2
- package/dist/validation/primitives/date.d.mts +2 -2
- package/dist/validation/primitives/date.d.ts +2 -2
- package/dist/validation/primitives/number.d.mts +2 -2
- package/dist/validation/primitives/number.d.ts +2 -2
- package/dist/validation/primitives/text.d.mts +2 -2
- package/dist/validation/primitives/text.d.ts +2 -2
- package/package.json +2 -2
- package/dist/all-BsINIhT4.d.ts +0 -1375
- package/dist/all-Js3OaRJY.d.mts +0 -1375
package/dist/index.mjs
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import {b as b$
|
|
2
|
-
var Co=["fyi","task","question","handoff","system"],Eo=["low","normal","high","urgent"],No=["public","internal","sensitive"],Do=["unread","read","archived","snoozed"],Oo=["none","pending","processing","completed","dismissed","expired","failed"],Lc="agent.session.waiting_human",Uc="agent.task.assigned",$c="agent.question.requested",tg=[Lc,Uc,$c];var rg=["name","type"],ig=["required","hidden","archived","deprecated","defaultValue","config","order","unique"],og=["label","description","placeholder","icon"];var Kt=["text","richtext","number","checkbox","date","phone","currency","status","location","select","multiselect","user","relation","formula","rollup","document"],ye="*";function cg(e){return e.type!=="relation"||!Array.isArray(e.targets)?[]:e.targets.map(t=>t.object).filter(t=>t!==ye)}a(cg,"relationTargetsOf");function ko(e){return e.targets.length===1&&e.targets[0].object===ye}a(ko,"isUniversalRelation");function ug(e){return e.bilateral!==void 0}a(ug,"isBilateralRelation");function lg(e){return "many"}a(lg,"inferInverseCardinality");function dg(e){return n$1(e)}a(dg,"isAttributeSortable");var fg=["record","object","attribute","view","user","role","settings","file","agent","schema_source"],bg=["record.created","record.updated","record.deleted","record.restored","record.purged","object.created","object.updated","object.deleted","attribute.created","attribute.updated","attribute.deleted","view.created","view.updated","view.deleted","schema_source.applied","schema_source.removed","user.created","user.invited","user.updated","user.deleted","user.login","user.logout","role.created","role.updated","role.deleted","role.assigned","role.revoked","settings.updated","file.uploaded","file.updated","file.deleted"];function hg(e){return e.phase==="terminal"}a(hg,"isTerminalState");function Ag(e){switch(e.phase){case "running":return "active";case "queued":return "idle";case "parked":if(e.parkedOn===void 0)throw new b("parked state without parkedOn",a$2.INVARIANT_VIOLATION);return e.parkedOn==="agents"?"waiting_agents":"waiting_human";case "terminal":if(e.outcome===void 0)throw new b("terminal state without outcome",a$2.INVARIANT_VIOLATION);return e.outcome}}a(Ag,"sessionStateToLegacyStatus");function xg(e){switch(e){case "active":return {phase:"running"};case "idle":return {phase:"queued"};case "waiting_human":return {phase:"parked",parkedOn:"human",humanRequestIds:[]};case "waiting_agents":return {phase:"parked",parkedOn:"agents"};default:return {phase:"terminal",outcome:e}}}a(xg,"legacyStatusToSessionState");var qc=["completed","failed","cancelled","timeout","expired"];function Tg(e){return qc.includes(e)}a(Tg,"isTerminalSessionStatus");var zc=["idle","completed","waiting_human","waiting_agents","cancelled","failed","timeout"];function wg(e){return zc.includes(e)}a(wg,"isClaimableSessionStatus");var jo=Object.freeze({mutation:"ask",destructive:"ask",outward:"ask"}),Sg=["active","completed","abandoned"],_o=["openai","anthropic","google","spacexai","deepseek","moonshotai","alibaba","mistral","minimax","meta","zai"],Po=["standard","fast"],Mo=["none","minimal","low","medium","high","xhigh"];function Ig(e){return e.label?.trim()||e.name}a(Ig,"agentDisplayName");var Fo=["approval-requested","approval-responded","approval-dispatched"],Wc=["streaming","running","pending",...Fo];function Rg(e){return Wc.includes(e)}a(Rg,"isOpenToolPartState");function vg(e){return Fo.includes(e)}a(vg,"isToolApprovalState");var Fn=["CREDITS_EXHAUSTED"];function Cg(e){return typeof e=="string"&&Fn.includes(e)}a(Cg,"isSystemPartCode");function Gc(e,t){let n=e.createdAt.getTime()-t.createdAt.getTime();return n===0?e.id.localeCompare(t.id):n}a(Gc,"compareAgentSessionMessages");function Eg(e){return [...e].sort(Gc)}a(Eg,"orderAgentSessionMessages");var Ng=["pending","in_progress","completed","blocked"],Dg=50,Og=80,kg=500;var Mg="session-state",Kc="__stndrdsNativeUiPartIds",Yc=1,Hc="Native agent UI part IDs metadata is invalid";function _e(){throw new h(Hc,[])}a(_e,"invalidNativePartIds");function Vo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}a(Vo,"isPlainRecord");function Jc(e,t){if(e.type==="text"||e.type==="reasoning")return `${e.type}:${t}`;if(e.type==="tool")return `tool:${e.toolCallId}`}a(Jc,"nativeAgentUIPartIdMetadataKey");function Fg(e){let t=e.metadata?.[Kc];Vo(t)||_e(),(Object.keys(t).length!==2||t.schemaVersion!==Yc||!Vo(t.partIds))&&_e();let n=new Map;for(let[s,c]of e.parts.entries()){let u=Jc(c,s);if(!u||n.has(u)){u&&_e();continue}n.set(u,c);}let r=Object.entries(t.partIds);r.length!==n.size&&_e();let o=new Map,a={};for(let[s,c]of r){let u=n.get(s);u&&typeof c=="string"&&c.length>0||_e();let m=o.get(c);m&&(u.type==="tool"||m!==u.type)&&_e(),u.type==="tool"&&c!==u.toolCallId&&_e(),o.set(c,u.type),a[s]=c;}return a}a(Fg,"parseNativeAgentUIPartIdsMetadata");var Lg=16e3,Ug=3200,$g=6400,qg=16e3,zg=65536,Wg=15e3,Gg=1e4,Kg=5e3,Yg="google/gemini-3.5-transcribe-live",Hg={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2};var Qg=["web","presentation","document","spreadsheet","image","code","other"],Xg=["ephemeral","conversation","persistent"],Zg=["source","preview","entrypoint","asset"];var Bo=5;function ny(e){return e instanceof Error?e.message:typeof e=="string"?e:e&&typeof e=="object"?"message"in e&&typeof e.message=="string"?e.message:JSON.stringify(e):String(e)}a(ny,"getErrorMessage");function ay(e){return typeof e=="object"&&e!==null&&"slots"in e&&"steps"in e&&"name"in e&&typeof e.name=="string"&&Array.isArray(e.slots)&&Array.isArray(e.steps)}a(ay,"isFormDefinition");var Vn=["relation","multiRelation","formula","rollup","document","richtext","user"];function Lo(e){return e.type==="slot"}a(Lo,"isFormSlotFieldRef");function Bn(e){return e.type==="free"}a(Bn,"isFormFreeFieldRef");function uy(e){return e.fieldRequired!==void 0?e.fieldRequired:e.slotMode==="create"&&e.attributeRequired===true}a(uy,"resolveFieldRequired");function Uo(e){return e.additionalSlotIds?.length?[e.slotId,...e.additionalSlotIds]:[e.slotId]}a(Uo,"getSlotFieldTargets");function Qc(e){return Lo(e)?`${e.slotId}.${e.attribute}`:`free.${e.attribute.name}`}a(Qc,"formFieldKey");function Xc(e){return Lo(e)?e.attribute:e.attribute.name}a(Xc,"formFieldFlatKey");function ly(e,t){return e[Qc(t)]??e[Xc(t)]}a(ly,"readFormFieldValue");function Yt(e){return e.type==="fields"}a(Yt,"isFormFieldsRow");function my(e){return e.type==="heading"}a(my,"isFormHeadingRow");function fy(e){return e.type==="separator"}a(fy,"isFormSeparatorRow");function by(e){return e.type==="text"}a(by,"isFormTextRow");var Ln=class Ln{async autocomplete(){return await Promise.resolve([])}async reverse(){return await Promise.resolve(null)}async geocode(){return await Promise.resolve(null)}};a(Ln,"NoopGeocodingAdapter");var $o=Ln;var Un=["read","create","update","delete","manage"];function wy(e){return e.length===0?"none":e.length===1&&e[0]==="read"?"read-only":e.length===Un.length&&Un.every(t=>e.includes(t))?"full":"custom"}a(wy,"actionsToAccessLevel");function Sy(e){switch(e){case "full":return [...Un];case "read-only":return ["read"];case "none":return []}}a(Sy,"accessLevelToActions");function qo(e){let t=e.properties;if(!t)return [];if(Array.isArray(t))return t;let n=t;return Array.isArray(n.definitions)?n.definitions:[]}a(qo,"resolvePropertyDefinitions");function vy(e){return e.type==="select"||e.type==="status"||e.type==="multiselect"}a(vy,"hasOptions");var Zc="Notetaker",Ny={systemPrompt:null,meetingRecordingPolicy:"none",meetingBotDisplayName:Zc};var Oy=["active","suspended"],ky=["architect","manual","auto"];var _y=["square","landscape","portrait"];var zo=["none","estimated","exact"];function eu(e){if(typeof e=="string"&&zo.includes(e))return e;throw new h(`countMode must be one of: ${zo.join(", ")} (received: ${String(e)})`,[])}a(eu,"parseCountMode");function Fy(e){return e===void 0?void 0:eu(e)}a(Fy,"parseOptionalCountMode");var Vy=1e4;var Uy=["storage.bytes","members.seats","data.live_records"];function tu(e){return e==null?true:typeof e!="object"?false:Object.keys(e).length===0}a(tu,"isEmptyObject");function Wo(e){return e!=null&&typeof e=="object"&&Object.keys(e).length>0}a(Wo,"isNotEmpty");function nu(e){return Wo(e)?e:void 0}a(nu,"toUndefinedIfEmpty");function ru(e){if(e<=0)return {value:0,unitIndex:0};let t=1e3,n=Math.min(4,Math.floor(Math.log(e)/Math.log(t)));return {value:Number.parseFloat((e/t**n).toFixed(1)),unitIndex:n}}a(ru,"computeByteMagnitude");var iu=["B","KB","MB","GB","TB"];function Ph(e){let{value:t,unitIndex:n}=ru(e);return `${t} ${iu[n]}`}a(Ph,"formatByteSize");var Vh={ATTACHMENTS:"attachments"};function Bh(e){return e.type==="document"}a(Bh,"isDocumentAttribute");function Lh(e,t){if(!t||t.length===0)return true;let n=e.name.toLowerCase();return t.some(r=>r.endsWith("/*")?e.mimeType.startsWith(r.slice(0,-1)):r.startsWith(".")?n.endsWith(r.toLowerCase()):e.mimeType===r)}a(Lh,"matchesAccepts");var Go=Object.freeze(["text","number","checkbox","date","phone","currency","status","select","multiselect","location"]);function Ht(e){let t=[];for(let n of e){let r=n.build();if(!Go.includes(r.type))throw new Error(`Property type "${r.type}" is not supported in .qualifyWith()`);t.push(r);}return {definitions:t}}a(Ht,"buildPropertySchema");var Wh="__";function Gh(e){let t=e.indexOf("__");return t<=0||t+2>=e.length?{kind:"scalar",attribute:e}:{kind:"qualified",root:e.slice(0,t),property:e.slice(t+2)}}a(Gh,"parseQualifiedAttribute");function Kh(e,t){return `${e}__${t}`}a(Kh,"buildQualifiedAttribute");function Ie(e){return typeof e=="object"&&e!==null&&typeof e.start=="string"}a(Ie,"isDateRangeValue");function ou(e,t){return a$1(e)?null:Ie(e)?t.endDate?{start:e.start,end:e.end??null}:e.start:typeof e=="string"?t.endDate?{start:e,end:null}:e:null}a(ou,"normalizeDateValue");function Ke(e){return typeof e=="string"&&e!==""?e:Ie(e)&&e.start!==""?e.start:null}a(Ke,"dateValueStart");var Jt="\u2014";function au(e){return String(e)}a(au,"formatText");function su(e){return e?"Yes":"No"}a(su,"formatCheckbox");function cu(e,t){if(typeof e!="number")return String(e);if(t.renderAs==="rating")return `${e}/${t.max??5}`;let n=t.decimals;return t.unit==="integer"?e.toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:0}):t.unit==="percentage"?(e/100).toLocaleString(void 0,{style:"percent",minimumFractionDigits:n,maximumFractionDigits:n}):e.toLocaleString(void 0,{minimumFractionDigits:n,maximumFractionDigits:n})}a(cu,"formatNumber");function uu(e,t){if(typeof e!="object"||e===null)return String(e);let n=e;return "value"in n&&"code"in n?`${n.value.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})} ${n.code}`:String(e)}a(uu,"formatCurrency");function $n(e){if(Ie(e)){let t=$n(e.start);return e.end?`${t} \u2192 ${$n(e.end)}`:t}if(e instanceof Date)return e.toISOString().split("T")[0];if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString().split("T")[0]}return String(e)}a($n,"formatDate");function lu(e){if(typeof e!="object"||e===null)return String(e);let t=e;return "phoneNumber"in t?t.phoneNumber?t.countryCode?c(t):t.phoneNumber:"":String(e)}a(lu,"formatPhone");function du(e,t="full"){if(typeof e!="object"||e===null)return "";let n=e,r=[];switch(t){case "country":n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;case "state":n.state&&r.push(n.state),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;case "city":n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;case "coordinates":n.latitude!==void 0&&n.longitude!==void 0&&r.push(`${n.latitude}, ${n.longitude}`);break;case "address":n.address&&r.push(n.address),n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;default:n.address&&r.push(n.address),n.address2&&r.push(n.address2),n.city&&r.push(n.city),n.state&&r.push(n.state),n.postalCode&&r.push(n.postalCode),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break}return r.join(", ")}a(du,"formatLocationValue");function pu(e,t){return typeof e!="object"||e===null?String(e):du(e,t.granularity??"full")||Jt}a(pu,"formatLocation");function mu(e,t){return typeof e!="string"?String(e):t.options?.find(r=>r.value===e)?.label??String(e)}a(mu,"formatSelect");function fu(e,t){return Array.isArray(e)?t.options?e.map(r=>t.options.find(o=>o.value===r)?.label).filter(Boolean).join(", "):e.join(", "):String(e)}a(fu,"formatMultiselect");function Ko(e,t){if(a$1(e))return Jt;switch(t.type){case "text":return au(e);case "checkbox":return su(e);case "number":return cu(e,t);case "currency":return uu(e);case "date":return $n(e);case "phone":return lu(e);case "location":return pu(e,t);case "select":case "status":return mu(e,t);case "multiselect":return fu(e,t);case "user":case "relation":return Array.isArray(e)?e.join(", "):String(e);default:return Array.isArray(e)?e.join(", "):String(e)}}a(Ko,"formatAttributeValue");var gu=["UPPER","LOWER","capitalize","trim"],yu=["prefix","suffix","wrap","default"],Qt=[...gu,...yu],Ye=z.string().min(1,"labelExpression cannot be empty").refine(e=>Xt(e),{message:"labelExpression must contain at least one {{ attribute }} interpolation"}).refine(e=>!/\{\{\s*\}\}/.test(e),{message:"labelExpression contains empty {{ }} interpolation"}).refine(e=>{let t=/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g,n;for(;(n=t.exec(e))!==null;){let r=n[1];if(!Qt.includes(r))return false}return true},{message:`Invalid pipe name. Valid pipes: ${Qt.join(", ")}`});function hu(e){let t=Ye.safeParse(e);return t.success?{success:true,attributes:ht(e)}:{success:false,error:t.error.issues[0]?.message??"Invalid labelExpression"}}a(hu,"validateLabelExpression");function Au(e,t){let{name:n,args:r}=Tu(t);switch(n){case "UPPER":return e.toUpperCase();case "LOWER":return e.toLowerCase();case "capitalize":return e.replace(/(^|\s)\S/g,o=>o.toUpperCase());case "trim":return e.trim();case "prefix":return e?`${r[0]??""}${e}`:"";case "suffix":return e?`${e}${r[0]??""}`:"";case "wrap":return e?`${r[0]??""}${e}${r[1]??""}`:"";case "default":return e||r[0]||"";default:return e}}a(Au,"applyPipe");function Yo(e,t){let n=e;for(let r of t)n=Au(n,r);return n}a(Yo,"applyPipes");function xu(e,t){return t.split(".").reduce((n,r)=>{if(!(n==null||typeof n!="object"))return n[r]},e)}a(xu,"getValue");var Ho="(Untitled)";function Tu(e){let t=e.match(/^(\w+)(?::(.*))?$/);if(!t)return {name:e,args:[]};let n=t[1],r=t[2];if(!r)return {name:n,args:[]};let o=[],a=/["']([^"']*?)["']/g,s;for(;(s=a.exec(r))!==null;)o.push(s[1]);return {name:n,args:o}}a(Tu,"parsePipeExpression");function*Jo(e){let t=0;for(;t<e.length;){let n=e.indexOf("{{",t);if(n<0)return;let r=e.indexOf("}",n+2);if(r<0)return;if(e[r+1]!=="}"){t=r+1;continue}t=r+2;let o=e.slice(n+2,r);o.length>0&&(yield {start:n,end:t,expr:o});}}a(Jo,"templateBlocks");function wu(e,t){let n=e.split("||").map(u=>u.trim()),o=n[n.length-1].split("|").map(u=>u.trim());n[n.length-1]=o[0];let a=o.slice(1).filter(Boolean),s=n.filter(Boolean),c="";for(let u of s){let m=Qo(xu(t,u));if(m!==""){c=m;break}}return Yo(c,a)}a(wu,"resolveLabelBlock");function qn(e,t,n=Ho){let r=[],o=0;for(let s of Jo(e))r.push(e.slice(o,s.start),wu(s.expr,t)),o=s.end;return r.push(e.slice(o)),r.join("").trim()||n}a(qn,"renderLabelExpression");function Qo(e){if(e==null||typeof e=="function")return "";if(typeof e!="object")return String(e);if(Array.isArray(e))return e.map(Qo).filter(Boolean).join(",");let t=e.toString;return typeof t=="function"&&t!==Object.prototype.toString?String(e):""}a(Qo,"toText");function Xt(e){let t=0;for(;t<e.length;){let n=e.indexOf("{{",t);if(n<0)return false;let r=e.indexOf("}}",n+2);if(r<0)return false;if(e.slice(n+2,r).trim().length>0)return true;t=r+2;}return false}a(Xt,"isLabelExpression");function ht(e){let t=[];for(let n of Jo(e)){let r=n.expr.trim();if(!r)continue;let o=r.split("||").map(s=>s.trim()),a=o[o.length-1];o[o.length-1]=a.split("|")[0].trim();for(let s of o){if(!s)continue;let c=s.split(".")[0];c&&!t.includes(c)&&t.push(c);}}return t}a(ht,"extractAttributeNames");var Su=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function Xo(e){let t=e.trim().match(Su);return t?t[1]:null}a(Xo,"getSingleAttributeFromExpression");function Iu(e,t){let n=Xo(e);if(n===null)return null;let r=t.find(o=>o.name===n);return !r||r.type!=="text"||j$2(r).authoring.readOnly?null:r}a(Iu,"getEditableLabelAttribute");var Ru=/\{\{\s*props\./;function vu(e,t,n){if(!Ru.test(e))return e;let r={},o=new Map(n?.map(s=>[s.name,s]));if(t)for(let[s,c]of Object.entries(t)){if(c==null)continue;let u=o.get(s);if(u){let m=Ko(c,u);r[s]=m===Jt?"":m;}else r[s]=c;}return qn(e,{props:r},"").replace(/\(\s*\)/g,"").replace(/\[\s*\]/g,"").replace(/\s*[-—|:]\s*$/g,"").replace(/\s{2,}/g," ").trim()}a(vu,"applyRelationProps");function Cu(e){if(e?.type==="relation")return e.properties?.definitions}a(Cu,"relationPropertyDefs");function Eu(e){if(e?.type==="relation"||e?.type==="document")return e.properties?.definitions}a(Eu,"qualifiedPropertyDefs");function Zo(e){if(a$1(e))return [];if(typeof e=="string")return [{id:e}];if(Array.isArray(e))return e.flatMap(t=>Zo(t));if(typeof e=="object"&&"id"in e){let t=e;if(typeof t.id=="string")return [{id:t.id,props:t.props}]}return []}a(Zo,"extractValueRefs");function Nu(e){let t=[e.firstName,e.lastName].map(n=>n?.trim()).filter(Boolean).join(" ");return t!==""?t:e.email?.split("@")[0]??""}a(Nu,"getUserDisplayName");var Du=/\p{L}|\p{N}/u;function Ou(e,t){let n=e?.trim()??"";if(n==="")return t;let r=n.split(/\s+/),a=(r.length===1?n.split("@")[0].split(/[._-]/):r).map(s=>{let c=s.match(Du)?.[0];return c===void 0?"":[...c.toUpperCase()][0]??""}).filter(Boolean).slice(0,2).join("");return a===""?t:a}a(Ou,"deriveInitials");var ea="__creatorRootActorId";function ku(e){let t=e.metadata?.[ea];return typeof t=="string"&&t.length>0?t:e.createdBy}a(ku,"getRecordCreatorPrincipalId");function He(e,t){return e?.includes("*")===true||e?.includes(t)===true}a(He,"includesAction");function ju(e){return {canRead:He(e,"read"),canCreate:He(e,"create"),canUpdate:He(e,"update"),canDelete:He(e,"delete"),canManage:He(e,"manage")}}a(ju,"buildPermissionFlags");var xA=new Set(["id","name","label","type","required","system","unique","order"]);var X={PEOPLE:"people",WORKSPACE:"workspace",ARCHITECT:"architect",FEATURE_FLAGS:"feature-flags",FILES:"files",VIEWS:"views",FORMS:"forms",DOCUMENTS:"documents",AUDIT:"audit",API_KEYS:"api-keys",CONNECTORS:"connectors",ENV_VARS:"env-vars",SESSION:"session"},wA=[X.PEOPLE,X.WORKSPACE,X.ARCHITECT,X.FEATURE_FLAGS,X.FILES,X.VIEWS,X.FORMS,X.DOCUMENTS,X.AUDIT,X.API_KEYS,X.CONNECTORS,X.ENV_VARS,X.SESSION],SA={people:"People",workspace:"Workspace",architect:"Architect","feature-flags":"Feature flags",files:"Files",views:"Views",forms:"Forms",documents:"Documents",audit:"Audit","api-keys":"API keys",connectors:"Connected accounts","env-vars":"Environment variables",session:"Agent sessions"},_u={OWNER:"owner",MEMBER:"member",AGENT_DEFAULT:"agent_default",REFLEX_DEFAULT:"reflex_default"},IA={owner:"Owner",member:"Member",agent_default:"Agent Default",reflex_default:"Reflex Default"},RA={owner:"Full access to all platform features and data",member:"Can view, create, edit and delete business data",agent_default:"Default role for AI agents \u2014 CRUD on records plus documents and files",reflex_default:"Default role for reflexes \u2014 no data access; each reflex is granted exactly what its rehearsal showed it uses"},zn=["read","create","update","delete","manage"],Pu=["read","create","update","delete"],ta=["read","create","update","delete"],vA={owner:{system:[{target:"*",actions:zn}],object:[{target:"*",actions:zn}]},member:{system:[{target:"people",actions:["read"]},{target:"workspace",actions:["read"]},{target:"connectors",actions:Pu},{target:"files",actions:ta},{target:"documents",actions:ta}],object:[{target:"*",actions:zn}]},agent_default:{system:[{target:"documents",actions:["read","create","update"]},{target:"files",actions:["read","create","update"]},{target:"env-vars",actions:["read"]},{target:"session",actions:["observe"]}],object:[{target:"*",actions:["read","create","update","delete"]}]},reflex_default:{system:[],object:[]}};function CA(e){return Object.values(_u).includes(e)}a(CA,"isDefaultRole");var Fu=new Set(ICONS),ra=/^[a-zA-Z_][a-zA-Z0-9_]*$/,Vu=/^[a-z][a-z0-9-]*$/,Je=63,na=128,Zt=Wn.string().min(1,"Object name cannot be empty").max(63,"Object name is too long (max 63 characters)").regex(/^[a-z][a-z0-9-]*$/,{message:`Invalid object name format.
|
|
1
|
+
import {b as b$2,j as j$1}from'./chunk-YJSVWV3Z.mjs';export{a as NonJsonValueError,f as asTenantId,g as asUserId,b as canonicalStringify,j as deepEqual,h as generateId,i as indexBy,e as sameStableValue,d as serializeCanonicalJson,c as serializeStableJson}from'./chunk-YJSVWV3Z.mjs';import {B as B$1,d,S as S$1,V as V$1,w as w$1,C as C$1,ca as ca$1,n,j,ea as ea$1,da as da$1,g,h as h$1,K,J as J$1,H,D as D$1}from'./chunk-AQPK2UI7.mjs';export{i as ATTRIBUTE_FILTER_OPERATORS,y as LIST_VIEW_TAB_VISIBILITIES,f as LOCATION_FILTER_PROPERTIES,v as NATIVE_OBJECT_NAMES,s as NO_VALUE_OPERATORS,r as OPERATORS_BY_TYPE,W as REMOVED_OPERATOR_REPLACEMENTS,B as RESERVED_ATTRIBUTE_NAMES,C as RESERVED_OBJECT_NAMES,x as RESOURCE_VISIBILITIES,O as SYNONYM_ALIASES,c as SYSTEM_ATTRIBUTES,a as SYSTEM_ATTRIBUTE_I18N_KEYS,A as SYSTEM_FIELD_NAMES,V as SYSTEM_FILTER_ATTRIBUTE_TYPES,N as canonicalizeFilterValue,X as collectQualifiedRuleIssues,ba as collectionContentSourceSchema,Z as columnsSchema,ea as contentViewDefinitionSchema,E as currentActor,_ as displayAttributesSchema,da as draftContentViewDefinitionSchema,H as extractCurrencyFilterValue,I as extractFilterValue,aa as filterStateSchema,j as getAttributeCapabilities,k as getAttributeFilterOperators,J as getOperatorPolarity,u as getRollupFilterOperators,b as getSystemAttributeI18nKey,d as getSystemAttributeList,l as isAttributeFilterable,o as isAttributeGroupable,p as isAttributeKanbanGroupable,m as isAttributeSearchable,D as isDynamicValue,g as isLocationFilterProperty,h as isLocationPartOperator,e as isManagedSystemAttribute,w as isNativeObjectName,t as isNoValueOperator,R as isRelativeDateValue,M as isSetMembershipOperator,Q as normalizeFilterRule,K as normalizeForEdgeRpc,P as normalizeOperator,G as now,z as parseResourceVisibility,ca as publishedViewContentDefinitionSchema,q as resolveEffectiveFilterType,S as resolveIsWithinBounds,T as resolveUtcDayBounds,$ as sortsSchema,L as toMultiValueOperator,U as toUtcDayString,F as today,Y as validateQualifiedRule}from'./chunk-AQPK2UI7.mjs';import {c,e as e$1,n as n$1,k}from'./chunk-QIDZFNGR.mjs';export{d as ComputedFormulaParseError,a as SCHEMA_LIMITS,j as attributeConfigSchemas,b as colorIdSchema,c as iconNameSchema,h as multiselectOptionWriteSchema,l as parseAttributeConfig,n as parseAttributeConfigForCreate,o as parseAttributeConfigForUpdate,e as parseComputedFormula,g as selectOptionWriteSchema,f as statusGroupSchema,i as statusOptionWriteSchema}from'./chunk-QIDZFNGR.mjs';import {a as a$1,c as c$2,e,g as g$1}from'./chunk-XAVRKIBE.mjs';export{d as createFormAttributeValidator,a as isNullishOrEmptyString,b as isValuePresent,l as rejectUnknownAttributesOrThrow,j as validateDraft,k as validateDraftOrThrow,h as validateObject,i as validateObjectOrThrow}from'./chunk-XAVRKIBE.mjs';import'./chunk-GKXTXH4Y.mjs';import'./chunk-Q7TQCRSD.mjs';import'./chunk-WMQRTFOP.mjs';export{a as createCheckboxValidator}from'./chunk-4VCADZK4.mjs';export{a as createDateValidator}from'./chunk-KYPEBOPW.mjs';import {c as c$1,a as a$3,b as b$1}from'./chunk-LB4TNMZU.mjs';import'./chunk-PFO7NWQW.mjs';import'./chunk-XMQV2WFY.mjs';import'./chunk-VKFLXFPP.mjs';import'./chunk-YIXNAWH6.mjs';import'./chunk-XRDP2Y4J.mjs';import {h,b,a as a$2,r,s,c as c$3}from'./chunk-XRWRECDA.mjs';export{C as AccessDeniedError,I as AttributeInUseError,e as AttributeNotFoundError,q as ChangeTypeNotSupportedError,A as ConcurrentModificationError,o as DestructiveSyncNotAllowedError,r as DuplicateError,x as ForbiddenError,G as MemoryNotFoundError,p as MigrationTimeoutError,c as NotFoundError,F as NotImplementedError,d as ObjectNotFoundError,J as ObjectReferencedError,n as OrphanSystemAttributeError,i as ProtectedResourceError,y as ProtectedRoleError,f as RecordNotFoundError,H as RecordReferencedError,D as RepositoryError,s as ReservedObjectNameError,z as RoleNotFoundError,b as SchemaError,a as SchemaErrorCode,g as SchemaPlanNotFoundError,E as SearchBackendError,B as StorageError,m as SyncCascadeError,l as SyncConflictError,j as SyncError,k as SystemEntityImmutableError,h as ValidationError,L as isAttributeInUseError,u as isNotFoundError,M as isObjectReferencedError,w as isProtectedResourceError,K as isRecordReferencedError,t as isSchemaError,v as isValidationError}from'./chunk-XRWRECDA.mjs';export{a as TEXT_FORMAT_PATTERNS,c as createTextValidator,b as resolveTextPattern}from'./chunk-O34B5KOW.mjs';export{a as createNumberValidator}from'./chunk-KG2ADZG6.mjs';export{a as DEFAULT_VALIDATION_MESSAGES,b as formatZodErrors}from'./chunk-4OTKOCGB.mjs';import {a}from'./chunk-KSPJP74K.mjs';import {ICONS,SKILL_NAME_MAX_LENGTH,SKILL_DESCRIPTION_MAX_LENGTH,MEMORY_NAME_MAX_LENGTH,MEMORY_DESCRIPTION_MAX_LENGTH,getCountryDisplayNameByIso3}from'@stndrds/constants';import zn,{z}from'zod';/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
+
var go=["fyi","task","question","handoff","system"],yo=["low","normal","high","urgent"],ho=["public","internal","sensitive"],Ao=["unread","read","archived","snoozed"],xo=["none","pending","processing","completed","dismissed","expired","failed"],Nc="agent.session.waiting_human",Dc="agent.task.assigned",Oc="agent.question.requested",Jb=[Nc,Dc,Oc];var Xb=["name","type"],Zb=["required","hidden","archived","deprecated","defaultValue","config","order","unique"],eg=["label","description","placeholder","icon"];var Kt=["text","richtext","number","checkbox","date","phone","currency","status","location","select","multiselect","user","relation","formula","rollup","document"],we="*";function rg(e){return e.type!=="relation"||!Array.isArray(e.targets)?[]:e.targets.map(t=>t.object).filter(t=>t!==we)}a(rg,"relationTargetsOf");function To(e){return e.targets.length===1&&e.targets[0].object===we}a(To,"isUniversalRelation");function ig(e){return e.bilateral!==void 0}a(ig,"isBilateralRelation");function wo(e){return "many"}a(wo,"inferInverseCardinality");function og(e){return n(e)}a(og,"isAttributeSortable");var cg=["record","object","attribute","view","user","role","settings","file","agent","schema_source"],ug=["record.created","record.updated","record.deleted","record.restored","record.purged","object.created","object.updated","object.deleted","attribute.created","attribute.updated","attribute.deleted","view.created","view.updated","view.deleted","schema_source.applied","schema_source.removed","user.created","user.invited","user.updated","user.deleted","user.login","user.logout","role.created","role.updated","role.deleted","role.assigned","role.revoked","settings.updated","file.uploaded","file.updated","file.deleted"];function pg(e){return e.phase==="terminal"}a(pg,"isTerminalState");function mg(e){switch(e.phase){case "running":return "active";case "queued":return "idle";case "parked":if(e.parkedOn===void 0)throw new b("parked state without parkedOn",a$2.INVARIANT_VIOLATION);return e.parkedOn==="agents"?"waiting_agents":"waiting_human";case "terminal":if(e.outcome===void 0)throw new b("terminal state without outcome",a$2.INVARIANT_VIOLATION);return e.outcome}}a(mg,"sessionStateToLegacyStatus");function fg(e){switch(e){case "active":return {phase:"running"};case "idle":return {phase:"queued"};case "waiting_human":return {phase:"parked",parkedOn:"human",humanRequestIds:[]};case "waiting_agents":return {phase:"parked",parkedOn:"agents"};default:return {phase:"terminal",outcome:e}}}a(fg,"legacyStatusToSessionState");var kc=["completed","failed","cancelled","timeout","expired"];function bg(e){return kc.includes(e)}a(bg,"isTerminalSessionStatus");var jc=["idle","completed","waiting_human","waiting_agents","cancelled","failed","timeout"];function gg(e){return jc.includes(e)}a(gg,"isClaimableSessionStatus");var So=Object.freeze({mutation:"ask",destructive:"ask",outward:"ask"}),yg=["active","completed","abandoned"],Io=["openai","anthropic","google","spacexai","deepseek","moonshotai","alibaba","mistral","minimax","meta","zai"],Ro=["standard","fast"],Co=["none","minimal","low","medium","high","xhigh"];function hg(e){return e.label?.trim()||e.name}a(hg,"agentDisplayName");var vo=["approval-requested","approval-responded","approval-dispatched"],_c=["streaming","running","pending",...vo];function Ag(e){return _c.includes(e)}a(Ag,"isOpenToolPartState");function xg(e){return vo.includes(e)}a(xg,"isToolApprovalState");var Mn=["CREDITS_EXHAUSTED"];function Tg(e){return typeof e=="string"&&Mn.includes(e)}a(Tg,"isSystemPartCode");function Pc(e,t){let n=e.createdAt.getTime()-t.createdAt.getTime();return n===0?e.id.localeCompare(t.id):n}a(Pc,"compareAgentSessionMessages");function wg(e){return [...e].sort(Pc)}a(wg,"orderAgentSessionMessages");var Sg=["pending","in_progress","completed","blocked"],Ig=50,Rg=80,Cg=500;var Dg="session-state",Mc="__stndrdsNativeUiPartIds",Fc=1,Vc="Native agent UI part IDs metadata is invalid";function Le(){throw new h(Vc,[])}a(Le,"invalidNativePartIds");function Eo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}a(Eo,"isPlainRecord");function Bc(e,t){if(e.type==="text"||e.type==="reasoning")return `${e.type}:${t}`;if(e.type==="tool")return `tool:${e.toolCallId}`}a(Bc,"nativeAgentUIPartIdMetadataKey");function Og(e){let t=e.metadata?.[Mc];Eo(t)||Le(),(Object.keys(t).length!==2||t.schemaVersion!==Fc||!Eo(t.partIds))&&Le();let n=new Map;for(let[s,c]of e.parts.entries()){let u=Bc(c,s);if(!u||n.has(u)){u&&Le();continue}n.set(u,c);}let r=Object.entries(t.partIds);r.length!==n.size&&Le();let o=new Map,a={};for(let[s,c]of r){let u=n.get(s);u&&typeof c=="string"&&c.length>0||Le();let d=o.get(c);d&&(u.type==="tool"||d!==u.type)&&Le(),u.type==="tool"&&c!==u.toolCallId&&Le(),o.set(c,u.type),a[s]=c;}return a}a(Og,"parseNativeAgentUIPartIdsMetadata");var _g=16e3,Pg=3200,Mg=6400,Fg=16e3,Vg=65536,Bg=15e3,Lg=1e4,$g=5e3,Ug="google/gemini-3.5-transcribe-live",qg={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2};var Wg=["web","presentation","document","spreadsheet","image","code","other"],Gg=["ephemeral","conversation","persistent"],Kg=["source","preview","entrypoint","asset"];var No=5;function Jg(e){return e instanceof Error?e.message:typeof e=="string"?e:e&&typeof e=="object"?"message"in e&&typeof e.message=="string"?e.message:JSON.stringify(e):String(e)}a(Jg,"getErrorMessage");function ey(e){return typeof e=="object"&&e!==null&&"slots"in e&&"steps"in e&&"name"in e&&typeof e.name=="string"&&Array.isArray(e.slots)&&Array.isArray(e.steps)}a(ey,"isFormDefinition");var Fn=["relation","multiRelation","formula","rollup","document","richtext","user"];function Do(e){return e.type==="slot"}a(Do,"isFormSlotFieldRef");function Vn(e){return e.type==="free"}a(Vn,"isFormFreeFieldRef");function ry(e){return e.fieldRequired!==void 0?e.fieldRequired:e.slotMode==="create"&&e.attributeRequired===true}a(ry,"resolveFieldRequired");function Oo(e){return e.additionalSlotIds?.length?[e.slotId,...e.additionalSlotIds]:[e.slotId]}a(Oo,"getSlotFieldTargets");function Lc(e){return Do(e)?`${e.slotId}.${e.attribute}`:`free.${e.attribute.name}`}a(Lc,"formFieldKey");function $c(e){return Do(e)?e.attribute:e.attribute.name}a($c,"formFieldFlatKey");function iy(e,t){return e[Lc(t)]??e[$c(t)]}a(iy,"readFormFieldValue");function Yt(e){return e.type==="fields"}a(Yt,"isFormFieldsRow");function sy(e){return e.type==="heading"}a(sy,"isFormHeadingRow");function cy(e){return e.type==="separator"}a(cy,"isFormSeparatorRow");function uy(e){return e.type==="text"}a(uy,"isFormTextRow");var Bn=class Bn{async autocomplete(){return await Promise.resolve([])}async reverse(){return await Promise.resolve(null)}async geocode(){return await Promise.resolve(null)}};a(Bn,"NoopGeocodingAdapter");var ko=Bn;var Ln=["read","create","update","delete","manage"];function gy(e){return e.length===0?"none":e.length===1&&e[0]==="read"?"read-only":e.length===Ln.length&&Ln.every(t=>e.includes(t))?"full":"custom"}a(gy,"actionsToAccessLevel");function yy(e){switch(e){case "full":return [...Ln];case "read-only":return ["read"];case "none":return []}}a(yy,"accessLevelToActions");function jo(e){let t=e.properties;if(!t)return [];if(Array.isArray(t))return t;let n=t;return Array.isArray(n.definitions)?n.definitions:[]}a(jo,"resolvePropertyDefinitions");function xy(e){return e.type==="select"||e.type==="status"||e.type==="multiselect"}a(xy,"hasOptions");var Uc="Notetaker",Sy={systemPrompt:null,meetingRecordingPolicy:"none",meetingBotDisplayName:Uc};var Ry=["active","suspended"],Cy=["architect","manual","auto"];var Ey=["square","landscape","portrait"];var _o=["none","estimated","exact"];function qc(e){if(typeof e=="string"&&_o.includes(e))return e;throw new h(`countMode must be one of: ${_o.join(", ")} (received: ${String(e)})`,[])}a(qc,"parseCountMode");function Oy(e){return e===void 0?void 0:qc(e)}a(Oy,"parseOptionalCountMode");var ky=1e4;var Py=["storage.bytes","members.seats","data.live_records"];function zc(e){return e==null?true:typeof e!="object"?false:Object.keys(e).length===0}a(zc,"isEmptyObject");function Po(e){return e!=null&&typeof e=="object"&&Object.keys(e).length>0}a(Po,"isNotEmpty");function Wc(e){return Po(e)?e:void 0}a(Wc,"toUndefinedIfEmpty");function Gc(e){if(e<=0)return {value:0,unitIndex:0};let t=1e3,n=Math.min(4,Math.floor(Math.log(e)/Math.log(t)));return {value:Number.parseFloat((e/t**n).toFixed(1)),unitIndex:n}}a(Gc,"computeByteMagnitude");var Kc=["B","KB","MB","GB","TB"];function vh(e){let{value:t,unitIndex:n}=Gc(e);return `${t} ${Kc[n]}`}a(vh,"formatByteSize");var Dh={ATTACHMENTS:"attachments"};function Oh(e){return e.type==="document"}a(Oh,"isDocumentAttribute");function kh(e,t){if(!t||t.length===0)return true;let n=e.name.toLowerCase();return t.some(r=>r.endsWith("/*")?e.mimeType.startsWith(r.slice(0,-1)):r.startsWith(".")?n.endsWith(r.toLowerCase()):e.mimeType===r)}a(kh,"matchesAccepts");var Mo=Object.freeze(["text","number","checkbox","date","phone","currency","status","select","multiselect","location"]);function Ht(e){let t=[];for(let n of e){let r=n.build();if(!Mo.includes(r.type))throw new Error(`Property type "${r.type}" is not supported in .qualifyWith()`);t.push(r);}return {definitions:t}}a(Ht,"buildPropertySchema");var Fh="__";function Vh(e){let t=e.indexOf("__");return t<=0||t+2>=e.length?{kind:"scalar",attribute:e}:{kind:"qualified",root:e.slice(0,t),property:e.slice(t+2)}}a(Vh,"parseQualifiedAttribute");function Bh(e,t){return `${e}__${t}`}a(Bh,"buildQualifiedAttribute");function Ne(e){return typeof e=="object"&&e!==null&&typeof e.start=="string"}a(Ne,"isDateRangeValue");function Yc(e,t){return a$1(e)?null:Ne(e)?t.endDate?{start:e.start,end:e.end??null}:e.start:typeof e=="string"?t.endDate?{start:e,end:null}:e:null}a(Yc,"normalizeDateValue");function Ze(e){return typeof e=="string"&&e!==""?e:Ne(e)&&e.start!==""?e.start:null}a(Ze,"dateValueStart");var Jt="\u2014";function Hc(e){return String(e)}a(Hc,"formatText");function Jc(e){return e?"Yes":"No"}a(Jc,"formatCheckbox");function Qc(e,t){if(typeof e!="number")return String(e);if(t.renderAs==="rating")return `${e}/${t.max??5}`;let n=t.decimals;return t.unit==="integer"?e.toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:0}):t.unit==="percentage"?(e/100).toLocaleString(void 0,{style:"percent",minimumFractionDigits:n,maximumFractionDigits:n}):e.toLocaleString(void 0,{minimumFractionDigits:n,maximumFractionDigits:n})}a(Qc,"formatNumber");function Xc(e,t){if(typeof e!="object"||e===null)return String(e);let n=e;return "value"in n&&"code"in n?`${n.value.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})} ${n.code}`:String(e)}a(Xc,"formatCurrency");function $n(e){if(Ne(e)){let t=$n(e.start);return e.end?`${t} \u2192 ${$n(e.end)}`:t}if(e instanceof Date)return e.toISOString().split("T")[0];if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString().split("T")[0]}return String(e)}a($n,"formatDate");function Zc(e){if(typeof e!="object"||e===null)return String(e);let t=e;return "phoneNumber"in t?t.phoneNumber?t.countryCode?c$1(t):t.phoneNumber:"":String(e)}a(Zc,"formatPhone");function eu(e,t="full"){if(typeof e!="object"||e===null)return "";let n=e,r=[];switch(t){case "country":n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;case "state":n.state&&r.push(n.state),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;case "city":n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;case "coordinates":n.latitude!==void 0&&n.longitude!==void 0&&r.push(`${n.latitude}, ${n.longitude}`);break;case "address":n.address&&r.push(n.address),n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;default:n.address&&r.push(n.address),n.address2&&r.push(n.address2),n.city&&r.push(n.city),n.state&&r.push(n.state),n.postalCode&&r.push(n.postalCode),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break}return r.join(", ")}a(eu,"formatLocationValue");function tu(e,t){return typeof e!="object"||e===null?String(e):eu(e,t.granularity??"full")||Jt}a(tu,"formatLocation");function nu(e,t){return typeof e!="string"?String(e):t.options?.find(r=>r.value===e)?.label??String(e)}a(nu,"formatSelect");function ru(e,t){return Array.isArray(e)?t.options?e.map(r=>t.options.find(o=>o.value===r)?.label).filter(Boolean).join(", "):e.join(", "):String(e)}a(ru,"formatMultiselect");function Fo(e,t){if(a$1(e))return Jt;switch(t.type){case "text":return Hc(e);case "checkbox":return Jc(e);case "number":return Qc(e,t);case "currency":return Xc(e);case "date":return $n(e);case "phone":return Zc(e);case "location":return tu(e,t);case "select":case "status":return nu(e,t);case "multiselect":return ru(e,t);case "user":case "relation":return Array.isArray(e)?e.join(", "):String(e);default:return Array.isArray(e)?e.join(", "):String(e)}}a(Fo,"formatAttributeValue");var ou=["UPPER","LOWER","capitalize","trim"],au=["prefix","suffix","wrap","default"],Qt=[...ou,...au],et=z.string().min(1,"labelExpression cannot be empty").refine(e=>Xt(e),{message:"labelExpression must contain at least one {{ attribute }} interpolation"}).refine(e=>!/\{\{\s*\}\}/.test(e),{message:"labelExpression contains empty {{ }} interpolation"}).refine(e=>{let t=/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g,n;for(;(n=t.exec(e))!==null;){let r=n[1];if(!Qt.includes(r))return false}return true},{message:`Invalid pipe name. Valid pipes: ${Qt.join(", ")}`});function su(e){let t=et.safeParse(e);return t.success?{success:true,attributes:Tt(e)}:{success:false,error:t.error.issues[0]?.message??"Invalid labelExpression"}}a(su,"validateLabelExpression");function cu(e,t){let{name:n,args:r}=lu(t);switch(n){case "UPPER":return e.toUpperCase();case "LOWER":return e.toLowerCase();case "capitalize":return e.replace(/(^|\s)\S/g,o=>o.toUpperCase());case "trim":return e.trim();case "prefix":return e?`${r[0]??""}${e}`:"";case "suffix":return e?`${e}${r[0]??""}`:"";case "wrap":return e?`${r[0]??""}${e}${r[1]??""}`:"";case "default":return e||r[0]||"";default:return e}}a(cu,"applyPipe");function Vo(e,t){let n=e;for(let r of t)n=cu(n,r);return n}a(Vo,"applyPipes");function uu(e,t){return t.split(".").reduce((n,r)=>{if(!(n==null||typeof n!="object"))return n[r]},e)}a(uu,"getValue");var Bo="(Untitled)";function lu(e){let t=e.match(/^(\w+)(?::(.*))?$/);if(!t)return {name:e,args:[]};let n=t[1],r=t[2];if(!r)return {name:n,args:[]};let o=[],a=/["']([^"']*?)["']/g,s;for(;(s=a.exec(r))!==null;)o.push(s[1]);return {name:n,args:o}}a(lu,"parsePipeExpression");function*Lo(e){let t=0;for(;t<e.length;){let n=e.indexOf("{{",t);if(n<0)return;let r=e.indexOf("}",n+2);if(r<0)return;if(e[r+1]!=="}"){t=r+1;continue}t=r+2;let o=e.slice(n+2,r);o.length>0&&(yield {start:n,end:t,expr:o});}}a(Lo,"templateBlocks");function du(e,t){let n=e.split("||").map(u=>u.trim()),o=n[n.length-1].split("|").map(u=>u.trim());n[n.length-1]=o[0];let a=o.slice(1).filter(Boolean),s=n.filter(Boolean),c="";for(let u of s){let d=$o(uu(t,u));if(d!==""){c=d;break}}return Vo(c,a)}a(du,"resolveLabelBlock");function Un(e,t,n=Bo){let r=[],o=0;for(let s of Lo(e))r.push(e.slice(o,s.start),du(s.expr,t)),o=s.end;return r.push(e.slice(o)),r.join("").trim()||n}a(Un,"renderLabelExpression");function $o(e){if(e==null||typeof e=="function")return "";if(typeof e!="object")return String(e);if(Array.isArray(e))return e.map($o).filter(Boolean).join(",");let t=e.toString;return typeof t=="function"&&t!==Object.prototype.toString?String(e):""}a($o,"toText");function Xt(e){let t=0;for(;t<e.length;){let n=e.indexOf("{{",t);if(n<0)return false;let r=e.indexOf("}}",n+2);if(r<0)return false;if(e.slice(n+2,r).trim().length>0)return true;t=r+2;}return false}a(Xt,"isLabelExpression");function Tt(e){let t=[];for(let n of Lo(e)){let r=n.expr.trim();if(!r)continue;let o=r.split("||").map(s=>s.trim()),a=o[o.length-1];o[o.length-1]=a.split("|")[0].trim();for(let s of o){if(!s)continue;let c=s.split(".")[0];c&&!t.includes(c)&&t.push(c);}}return t}a(Tt,"extractAttributeNames");var pu=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function Uo(e){let t=e.trim().match(pu);return t?t[1]:null}a(Uo,"getSingleAttributeFromExpression");function mu(e,t){let n=Uo(e);if(n===null)return null;let r=t.find(o=>o.name===n);return !r||r.type!=="text"||j(r).authoring.readOnly?null:r}a(mu,"getEditableLabelAttribute");var fu=/\{\{\s*props\./;function bu(e,t,n){if(!fu.test(e))return e;let r={},o=new Map(n?.map(s=>[s.name,s]));if(t)for(let[s,c]of Object.entries(t)){if(c==null)continue;let u=o.get(s);if(u){let d=Fo(c,u);r[s]=d===Jt?"":d;}else r[s]=c;}return Un(e,{props:r},"").replace(/\(\s*\)/g,"").replace(/\[\s*\]/g,"").replace(/\s*[-—|:]\s*$/g,"").replace(/\s{2,}/g," ").trim()}a(bu,"applyRelationProps");function gu(e){if(e?.type==="relation")return e.properties?.definitions}a(gu,"relationPropertyDefs");function yu(e){if(e?.type==="relation"||e?.type==="document")return e.properties?.definitions}a(yu,"qualifiedPropertyDefs");function qo(e){if(a$1(e))return [];if(typeof e=="string")return [{id:e}];if(Array.isArray(e))return e.flatMap(t=>qo(t));if(typeof e=="object"&&"id"in e){let t=e;if(typeof t.id=="string")return [{id:t.id,props:t.props}]}return []}a(qo,"extractValueRefs");function hu(e){let t=[e.firstName,e.lastName].map(n=>n?.trim()).filter(Boolean).join(" ");return t!==""?t:e.email?.split("@")[0]??""}a(hu,"getUserDisplayName");var Au=/\p{L}|\p{N}/u;function xu(e,t){let n=e?.trim()??"";if(n==="")return t;let r=n.split(/\s+/),a=(r.length===1?n.split("@")[0].split(/[._-]/):r).map(s=>{let c=s.match(Au)?.[0];return c===void 0?"":[...c.toUpperCase()][0]??""}).filter(Boolean).slice(0,2).join("");return a===""?t:a}a(xu,"deriveInitials");var zo="__creatorRootActorId";function Tu(e){let t=e.metadata?.[zo];return typeof t=="string"&&t.length>0?t:e.createdBy}a(Tu,"getRecordCreatorPrincipalId");function tt(e,t){return e?.includes("*")===true||e?.includes(t)===true}a(tt,"includesAction");function wu(e){return {canRead:tt(e,"read"),canCreate:tt(e,"create"),canUpdate:tt(e,"update"),canDelete:tt(e,"delete"),canManage:tt(e,"manage")}}a(wu,"buildPermissionFlags");var pA=new Set(["id","name","label","type","required","system","unique","order"]);var te={PEOPLE:"people",WORKSPACE:"workspace",ARCHITECT:"architect",FEATURE_FLAGS:"feature-flags",FILES:"files",VIEWS:"views",FORMS:"forms",DOCUMENTS:"documents",AUDIT:"audit",API_KEYS:"api-keys",CONNECTORS:"connectors",ENV_VARS:"env-vars",SESSION:"session"},fA=[te.PEOPLE,te.WORKSPACE,te.ARCHITECT,te.FEATURE_FLAGS,te.FILES,te.VIEWS,te.FORMS,te.DOCUMENTS,te.AUDIT,te.API_KEYS,te.CONNECTORS,te.ENV_VARS,te.SESSION],bA={people:"People",workspace:"Workspace",architect:"Architect","feature-flags":"Feature flags",files:"Files",views:"Views",forms:"Forms",documents:"Documents",audit:"Audit","api-keys":"API keys",connectors:"Connected accounts","env-vars":"Environment variables",session:"Agent sessions"},Su={OWNER:"owner",MEMBER:"member",AGENT_DEFAULT:"agent_default",REFLEX_DEFAULT:"reflex_default"},gA={owner:"Owner",member:"Member",agent_default:"Agent Default",reflex_default:"Reflex Default"},yA={owner:"Full access to all platform features and data",member:"Can view, create, edit and delete business data",agent_default:"Default role for AI agents \u2014 CRUD on records plus documents and files",reflex_default:"Default role for reflexes \u2014 no data access; each reflex is granted exactly what its rehearsal showed it uses"},qn=["read","create","update","delete","manage"],Iu=["read","create","update","delete"],Wo=["read","create","update","delete"],hA={owner:{system:[{target:"*",actions:qn}],object:[{target:"*",actions:qn}]},member:{system:[{target:"people",actions:["read"]},{target:"workspace",actions:["read"]},{target:"connectors",actions:Iu},{target:"files",actions:Wo},{target:"documents",actions:Wo}],object:[{target:"*",actions:qn}]},agent_default:{system:[{target:"documents",actions:["read","create","update"]},{target:"files",actions:["read","create","update"]},{target:"env-vars",actions:["read"]},{target:"session",actions:["observe"]}],object:[{target:"*",actions:["read","create","update","delete"]}]},reflex_default:{system:[],object:[]}};function AA(e){return Object.values(Su).includes(e)}a(AA,"isDefaultRole");var Cu=new Set(ICONS),Ko=/^[a-zA-Z_][a-zA-Z0-9_]*$/,vu=/^[a-z][a-z0-9-]*$/,nt=63,Go=128,Zt=zn.string().min(1,"Object name cannot be empty").max(63,"Object name is too long (max 63 characters)").regex(/^[a-z][a-z0-9-]*$/,{message:`Invalid object name format.
|
|
3
3
|
Name must be in kebab-case (slug format):
|
|
4
4
|
\u2705 Valid: 'products', 'user-profiles', 'order-items'
|
|
5
|
-
\u274C Invalid: 'Products', 'userProfiles', 'user_profiles'`});function
|
|
5
|
+
\u274C Invalid: 'Products', 'userProfiles', 'user_profiles'`});function wt(e){try{Zt.parse(e);}catch(t){throw t instanceof zn.ZodError?new b(t.issues[0].message,a$2.INVALID_OBJECT_NAME):t}}a(wt,"validateObjectName");function Eu(e){if(!e||e.length===0)throw new h("View name cannot be empty",[{path:["name"],message:"View name cannot be empty"}]);if(e.length>nt)throw new h("View name is too long",[{path:["name"],message:`View name is too long (max ${nt} characters)`}]);if(!vu.test(e))throw new h("Invalid view name format",[{path:["name"],message:"View name must be in kebab-case (e.g., 'detail', 'list-view')"}])}a(Eu,"validateViewName");function en(e,t,n){let r=new Set;for(let o of e){let a=t(o);if(r.has(a))throw n(a);r.add(a);}}a(en,"assertUniqueBy");var Wn=zn.string().min(1,"Attribute name cannot be empty").max(nt,`Attribute name is too long (max ${nt} characters)`).regex(Ko,{message:`Invalid attribute name format.
|
|
6
6
|
Name must be a valid variable identifier:
|
|
7
7
|
\u2705 Valid: 'firstName', 'first_name', 'FirstName', 'FIRST_NAME'
|
|
8
|
-
\u274C Invalid: 'first-name', 'first name', '123name', 'first.name'`}).refine(e=>!B$1.includes(e),{message:"This is a reserved attribute name"});function
|
|
8
|
+
\u274C Invalid: 'first-name', 'first name', '123name', 'first.name'`}).refine(e=>!B$1.includes(e),{message:"This is a reserved attribute name"});function St(e){if(!e||e.length===0)throw new Error("[AttributeBuilder] Attribute name cannot be empty");if(e.length>nt)throw new Error(`[AttributeBuilder] Attribute name is too long (max ${nt} characters)`);if(!Ko.test(e))throw new Error(`[AttributeBuilder] Invalid attribute name format.
|
|
9
9
|
Name must be a valid variable identifier:
|
|
10
10
|
\u2705 Valid: 'firstName', 'first_name', 'FirstName', 'FIRST_NAME'
|
|
11
11
|
\u274C Invalid: 'first-name', 'first name', '123name', 'first.name'`);if(B$1.includes(e))throw new Error(`[AttributeBuilder] "${e}" is a reserved name and cannot be used as an attribute name.
|
|
12
|
-
Reserved names: ${B$1.join(", ")}`)}a(
|
|
13
|
-
Icon must be one of the predefined icons from @stndrds/constants.`)}a(oa,"validateIconName");function Pe(e,t){let n=new Set;for(let r of t){if(!r.value?.trim())throw new Error(`[AttributeBuilder] Option in "${e}" has an empty or missing value.`);if(!r.label?.trim())throw new Error(`[AttributeBuilder] Option "${r.value}" in "${e}" has an empty or missing label.`);if(n.has(r.value))throw new Error(`[AttributeBuilder] Duplicate option value "${r.value}" in "${e}".`);n.add(r.value);}for(let r of t){if(r.inverse===void 0)continue;let o=t.find(a=>a.value===r.inverse);if(!o)throw new Error(`[AttributeBuilder] Option "${r.value}" in "${e}" has inverse "${r.inverse}" which does not match any option value.`);if(o.inverse!==r.value)throw new Error(`[AttributeBuilder] Inverse mismatch in "${e}": "${r.value}" points to "${r.inverse}", but "${r.inverse}" points to "${o.inverse??"(none)"}". Inverse pairs must be symmetric.`)}}a(Pe,"validateOptions");var aa={maxConcurrentRuns:3,retryPolicy:{maxRetries:3,backoffMs:1e3,backoffMultiplier:2},timeoutMs:3e5},Yn=class Yn{constructor(t){if(!t.name||t.name.trim().length===0)throw new h("Agent name is required",[]);this.bp={name:t.name,system:true,visibility:"workspace",triggers:[]};}description(t){return this.bp.description=t,this}label(t){return this.bp.label=t,this}icon(t){return this.bp.icon=t,this}systemPrompt(t){return this.bp.systemPrompt=t,this}model(t,n,r){return this.bp.model={provider:t,model:n,...r},this}tools(t){return this.bp.tools=[...t],this}schedule(t){return this.bp.schedule={...t,enabled:t.enabled??true},this}config(t){let n=this.bp.config??aa,r=t.inference===void 0?n.inference:{...n.inference,...t.inference};return this.bp.config={...n,...t,...r===void 0?{}:{inference:r}},this}delegation(t){return Object.assign(this.bp,t),this}mcpServers(t){return this.bp.mcpServers=Array.isArray(t)?[...t]:t,this}approval(t){return this.bp.approval={...jo,...this.bp.approval,...t},this}visibility(t){return this.bp.visibility=t,this}requiresPermission(t,n){return this.bp.requiredPermission={resource:t,action:n},this}trigger(t,n,r){return this.bp.triggers.push({name:t,eventType:n,...r,enabled:r?.enabled??true}),this}runtime(){return this.bp.system=false,this}build(){if(!this.bp.systemPrompt)throw new h(`Agent "${this.bp.name}": systemPrompt is required`,[]);if(!this.bp.model)throw new h(`Agent "${this.bp.name}": model is required`,[]);if(this.bp.system&&this.bp.visibility==="private")throw new h(`Agent "${this.bp.name}": system agents must use workspace visibility`,[]);return en(this.bp.triggers,t=>t.name,t=>new h(`Agent "${this.bp.name}": duplicate trigger name "${t}"`,[])),{...this.bp,visibility:this.bp.visibility??"workspace",config:this.bp.config??aa,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};a(Yn,"AgentBuilder");var Kn=Yn;function BA(e){return new Kn(e)}a(BA,"agent");var Lu="@stndrds/schema";function tn(e){return {version:1,vendor:Lu,validate:a(t=>{let n=e.safeParse(t);return n.success?{value:n.data}:{issues:n.error.issues.map(r=>({message:r.message,path:r.path}))}},"validate")}}a(tn,"createStandardSchemaProps");function $A(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"].version===1}a($A,"isStandardSchema");var sa=z.string().refine(e=>e.trim().length>0,"Must not be blank"),Tt=z.enum(Object.values(COUNTRIES).map(e=>e.iso3)),Hn=z.custom(e=>typeof e=="string"&&Object.hasOwn(CURRENCIES,e),"Invalid currency code"),se={name:sa,label:sa,id:z.string().optional(),objectId:z.string().optional(),required:z.boolean().optional(),system:z.boolean().optional(),unique:z.boolean().optional(),icon:e.optional()},Jn=r.shape.options.pipe(z.array(r.shape.options.element.extend({color:d.optional()}).strict())),ca=[j$1.extend({...se,type:z.literal("text"),defaultValue:z.string().optional()}).strict(),k$1.extend({...se,type:z.literal("number"),defaultValue:z.number().optional()}).strict(),l.extend({...se,type:z.literal("checkbox"),defaultValue:z.boolean().optional()}).strict(),m.extend({...se,type:z.literal("date"),defaultValue:z.union([z.string(),z.object({start:z.string(),end:z.string().nullable()}).strict()]).optional()}).strict(),n.extend({...se,type:z.literal("phone"),defaultCountryCode:Tt.optional(),defaultValue:z.object({countryCode:Tt,phoneNumber:z.string()}).strict().optional()}).strict(),o.extend({...se,type:z.literal("currency"),defaultCurrency:Hn.optional(),allowedCurrencies:z.array(Hn).optional(),defaultValue:z.object({code:Hn,value:z.number()}).strict().optional()}).strict(),q.extend({...se,type:z.literal("location"),defaultCountry:Tt.optional(),allowedCountries:z.array(Tt).optional(),defaultValue:z.object({address:z.string().optional(),address2:z.string().optional(),city:z.string().optional(),state:z.string().optional(),postalCode:z.string().optional(),country:Tt.optional(),latitude:z.number().optional(),longitude:z.number().optional()}).strict().optional()}).strict(),r.extend({...se,type:z.literal("select"),options:Jn,defaultValue:z.string().optional()}).strict(),p.extend({...se,type:z.literal("status"),options:Jn,defaultValue:z.string().optional()}).strict(),s.extend({...se,type:z.literal("multiselect"),options:Jn,defaultValue:z.array(z.string()).optional()}).strict()];var nn=z.string().refine(e=>e.trim().length>0,"Must not be blank"),ua={object:nn,name:nn,label:nn,required:z.boolean().optional(),description:z.string().optional()},la=z.discriminatedUnion("cardinality",[z.object({...ua,cardinality:z.literal("one"),maxItems:z.never().optional()}).strict(),z.object({...ua,cardinality:z.literal("many"),maxItems:z.number().int().positive().optional()}).strict()]),qu=z.discriminatedUnion("type",ca),zu=z.object({name:nn,endpoints:z.tuple([la,la]),properties:z.object({definitions:z.array(qu)}).strict().optional()}).strict();function Qe(e,t=["relations","0"]){let n=zu.safeParse(e);if(!n.success)throw h.fromZodErrors(n.error.issues.map(o=>({path:[...t,...o.path.map(String)],message:o.message})));let r=new Set;for(let o of n.data.properties?.definitions??[]){if(r.has(o.name))throw new r$1("attribute",o.name);r.add(o.name);}try{return structuredClone(n.data)}catch{let o="Relation definition must contain cloneable data";throw new h(o,[{path:t,message:o}])}}a(Qe,"validateStructuredRelationDefinition");function da(e){try{return structuredClone(e)}catch{let t="Relation definition must contain cloneable data";throw new h(t,[{path:["relations","0"],message:t}])}}a(da,"capture");var wt=class wt{constructor(t,n,r=[]){this.name=t;this.kind="relation";this.endpoints=da(n),this.properties=da(r);}between(t,n){return new wt(this.name,[t,n],this.properties)}qualifyWith(...t){let n=t.map(r=>r.build());return new wt(this.name,this.endpoints,[...this.properties,...n])}build(){return {kind:"relation",definition:Qe({name:this.name,endpoints:this.endpoints,...this.properties.length>0?{properties:{definitions:this.properties}}:{}})}}};a(wt,"RelationBuilder");var rn=wt;var fr=class fr{get"~standard"(){let t=c$1(this.build());return tn(t)}constructor(t,n,r){xt(n),ia(r),this.attr={name:n,label:r,type:t,required:false,system:true};}setRequired(t){this.attr.required=t;}asRequiredState(){return this}asPhantomState(){return this}runtime(){return this.attr.system=false,this}hidden(){return this.attr.hidden=true,this}placeholder(t){return this.attr.placeholder=t,this}description(t){return this.attr.description=t,this}icon(t){return oa(t,`attribute "${this.attr.name}"`),this.attr.icon=t,this}order(t){return this.attr.order=t,this}defaultValue(t){return ("defaultValue"in this.attr||!["formula","rollup"].includes(this.attr.type))&&(this.attr.defaultValue=t),this}metadata(t){return this.attr.metadata=t,this}build(){return this.attr}};a(fr,"BaseAttributeBuilder");var B=fr,br=class br extends B{constructor(t,n){super("text",t,n);}minLength(t){return this.attr.minLength=t,this}maxLength(t){return this.attr.maxLength=t,this}pattern(t){return this.attr.pattern=t,this.attr.format=void 0,this}multiline(t=true){return this.attr.multiline=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}email(){return this.attr.format="email",this.attr.pattern=void 0,this}url(){return this.attr.format="url",this.attr.pattern=void 0,this}slug(){return this.attr.format="slug",this.attr.pattern=void 0,this}};a(br,"TextAttributeBuilder");var Qn=br;function w(e){return new Qn(e.name,e.label)}a(w,"text");var gr=class gr extends B{constructor(t,n){super("richtext",t,n);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(gr,"RichtextAttributeBuilder");var Xn=gr;function Re(e){return new Xn(e.name,e.label)}a(Re,"richtext");var yr=class yr extends B{constructor(t,n){super("number",t,n);}min(t){return this.attr.min=t,this}max(t){return this.attr.max=t,this}integer(){return this.attr.unit="integer",this.attr.decimals=0,this}decimal(t=2){return this.attr.unit="decimal",this.attr.decimals=t,this}percentage(){return this.attr.unit="percentage",this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(yr,"NumberAttributeBuilder");var Zn=yr;function an(e){return new Zn(e.name,e.label)}a(an,"number");var hr=class hr extends B{constructor(t,n){super("checkbox",t,n);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(hr,"CheckboxAttributeBuilder");var er=hr;function pa(e){return new er(e.name,e.label)}a(pa,"checkbox");var Ar=class Ar extends B{constructor(t,n){super("date",t,n);}format(t){return this.attr.dateFormat=t,this}minDate(t){return this.attr.minDate=t,this}maxDate(t){return this.attr.maxDate=t,this}endDate(){return this.attr.endDate=true,this.asPhantomState()}includeTime(){return this.attr.includeTime=true,this}timeFormat(t){return this.attr.timeFormat=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Ar,"DateAttributeBuilder");var tr=Ar;function ee(e){return new tr(e.name,e.label)}a(ee,"date");var xr=class xr extends B{constructor(t,n){super("phone",t,n);}defaultCountry(t){return this.attr.defaultCountryCode=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(xr,"PhoneAttributeBuilder");var nr=xr;function px(e){return new nr(e.name,e.label)}a(px,"phone");var Tr=class Tr extends B{constructor(t,n){super("currency",t,n);}defaultCurrency(t){return this.attr.defaultCurrency=t,this}allowedCurrencies(t){return this.attr.allowedCurrencies=t,this}allowNegative(t=true){return this.attr.allowNegative=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Tr,"CurrencyAttributeBuilder");var rr=Tr;function mx(e){return new rr(e.name,e.label)}a(mx,"currency");var wr=class wr extends B{constructor(t,n){super("status",t,n);}options(t){let n=t;return Pe(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return Pe(this.attr.name??"unknown",n),this.attr.options.push(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(wr,"StatusAttributeBuilder");var ir=wr;function fx(e){return new ir(e.name,e.label)}a(fx,"status");var Sr=class Sr extends B{constructor(t,n){super("select",t,n);}options(t){let n=t;return Pe(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return Pe(this.attr.name??"unknown",n),this.attr.options.push(t),this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Sr,"SelectAttributeBuilder");var or=Sr;function ce(e){return new or(e.name,e.label)}a(ce,"select");var Ir=class Ir extends B{constructor(t,n){super("multiselect",t,n);}options(t){let n=t;return Pe(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return Pe(this.attr.name??"unknown",n),this.attr.options.push(t),this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Ir,"MultiselectAttributeBuilder");var ar=Ir;function bx(e){return new ar(e.name,e.label)}a(bx,"multiselect");var Rr=class Rr extends B{constructor(t,n){super("location",t,n);}granularity(t){return this.attr.granularity=t,this}defaultCountry(t){return this.attr.defaultCountry=t,this}allowedCountries(t){return this.attr.allowedCountries=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Rr,"LocationAttributeBuilder");var sr=Rr;function gx(e){return new sr(e.name,e.label)}a(gx,"location");var vr=class vr extends B{constructor(t,n){super("user",t,n),this.attr.types=["user","agent"];}types(t){let n=[...new Set(t)];if(n.length===0)throw new Error("[AttributeBuilder] user.types must contain at least one type.");return this.attr.types=n,this}multiple(){return this.attr.multiple=true,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(vr,"UserAttributeBuilder");var cr=vr;function yx(e){return new cr(e.name,e.label)}a(yx,"user");var Cr=class Cr extends B{to(t,n){let r={object:t,...n};return this.attr.targets?.push(r),this}toAny(){return this.attr.targets=[{object:ye}],this}qualifyWith(...t){let n=this.attr.targets;if(!n||n.length===0)throw new Error('.qualifyWith() must be called AFTER .to(). Example: relation({ name: "companies" }).to("companies").qualifyWith(...)');return this.attr.properties=Ht(t),this}bilateral(t){let n=this.attr.targets;if(!n||n.length===0)throw new Error('.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })');if(n.length>1)throw new Error("Bilateral relations are not supported for polymorphic relations (multiple .to() targets).");if(ko(this.attr))throw new Error("Bilateral relations are not supported for universal relations (.toAny()).");return this.attr.bilateral=t,this}};a(Cr,"BaseRelationAttributeBuilder");var on=Cr,Er=class Er extends on{constructor(t,n){super("relation",t,n),this.attr.cardinality="one",this.attr.targets=[];}many(){let t=new lr(this.attr.name,this.attr.label??"",{targets:this.attr.targets,isRequired:this.attr.required});return this.attr.system===false&&t.runtime(),this.attr.hidden&&t.hidden(),this.attr.placeholder&&t.placeholder(this.attr.placeholder),this.attr.description&&t.description(this.attr.description),this.attr.icon&&t.icon(this.attr.icon),this.attr.order!==void 0&&t.order(this.attr.order),this.attr.metadata&&t.metadata(this.attr.metadata),t}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Er,"SingleRelationAttributeBuilder");var ur=Er,Nr=class Nr extends on{constructor(t,n,r){super("relation",t,n),this.attr.cardinality="many",this.attr.targets=r?.targets??[],this.attr.defaultValue=[],r?.isRequired&&this.setRequired(true);}maxItems(t){return this.attr.maxItems=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Nr,"MultiRelationAttributeBuilder");var lr=Nr;function Xe(e){return typeof e=="string"?new rn(e,void 0):new ur(e.name,e.label)}a(Xe,"relation");var Dr=class Dr extends B{constructor(t,n){super("formula",t,n),this.attr.required=false;}expression(t){return this.attr.expression=t,this}returns(t){return this.attr.returnType=t,this}decimals(t){return this.attr.decimals=t,this}required(){throw new Error("Formula attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.")}optional(){return this}};a(Dr,"FormulaAttributeBuilder");var dr=Dr;function hx(e){return new dr(e.name,e.label)}a(hx,"formula");var Or=class Or extends B{constructor(t,n){super("rollup",t,n),this.attr.required=false;}from(t){return this.attr.relationAttribute=t,this}aggregate(t){return this.attr.targetAttribute=t,this}using(t){return this.attr.function=t,this}decimals(t){return this.attr.decimals=t,this}path(t){return this.attr.relationPath=t,this}targetType(t){return this.attr.targetAttributeType=t,this}targetOptions(t){return this.attr.targetAttributeOptions=t,this}targetCurrency(t){return this.attr.targetCurrencyCode=t,this}build(){let t=this.attr.function,n=this.attr.targetAttributeType;if(t==="original"&&n!==void 0&&n!=="select"&&n!=="status"&&n!=="multiselect"){let r=this.attr.relationAttribute??"relation",o=this.attr.targetAttribute??"field";throw new b(`Rollup "${this.attr.name}": .using("original") only supports a "select", "status", or "multiselect" target, but .targetType("${n}") was given. To surface a plain ${n} value from a related record, use a formula instead \u2014 e.g. formula({ name: "${this.attr.name}", label: "\u2026" }).expression("${r}.${o}").`,a$2.VALIDATION_FAILED)}return super.build()}required(){throw new Error("Rollup attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.")}optional(){return this}};a(Or,"RollupAttributeBuilder");var pr=Or;function Ax(e){return new pr(e.name,e.label)}a(Ax,"rollup");var kr=class kr extends B{constructor(t,n){super("document",t,n);}accepts(t){return this.attr.accepts=t,this}maxFileSize(t){return this.attr.maxFileSize=t,this}qualifyWith(...t){return this.attr.properties=Ht(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(kr,"DocumentAttributeBuilder");var mr=kr;function ma(e){return new mr(e.name,e.label)}a(ma,"document");function ba(e,t,n){let r=Array.isArray(e)?e:[e],[o,...a]=r;return {type:"slot",slotId:o,additionalSlotIds:a.length>0?a:void 0,attribute:t,label:n?.label,required:n?.required,tooltip:n?.tooltip}}a(ba,"buildSlotFieldRef");var Mr=class Mr{constructor(t,n,r){this._finalized=false;this.stepBuilder=t,this.rowData={id:n,order:r,type:"fields",fields:[]};}field(t,n,r){return this.rowData.fields.push(ba(t,n,r)),this}freeField(t,n){let o={type:"free",attribute:t.build(),label:n?.label,required:n?.required,prefillExpression:n?.prefillExpression};return this.rowData.fields.push(o),this}row(t){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).row(t)}heading(t,n){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).heading(t,n)}separator(){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).separator()}text(t){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).text(t)}endRow(){return this._finalized?this.stepBuilder:(this._finalized=true,this.stepBuilder._finalizeRow(this.rowData))}};a(Mr,"FormRowBuilder");var jr=Mr,Fr=class Fr{constructor(t,n,r){this.rowOrder=0;this.formBuilder=t,this.stepData={id:n,label:r,rows:[]};}description(t){return this.stepData.description=t,this}field(t,n,r){this.rowOrder++;let o=`row-${this.stepData.id}-${this.rowOrder}`,a=ba(t,n,r),s={id:o,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}freeField(t,n){this.rowOrder++;let r=`row-${this.stepData.id}-${this.rowOrder}`,a={type:"free",attribute:t.build(),label:n?.label,required:n?.required,prefillExpression:n?.prefillExpression},s={id:r,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}row(t){return this.rowOrder++,new jr(this,t,this.rowOrder)}heading(t,n){this.rowOrder++;let r={id:`heading-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"heading",content:t,level:n};return this.stepData.rows.push(r),this}separator(){this.rowOrder++;let t={id:`sep-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"separator"};return this.stepData.rows.push(t),this}text(t){this.rowOrder++;let n={id:`text-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"text",content:t};return this.stepData.rows.push(n),this}step(t,n){return this.formBuilder._finalizeStep(this.stepData).step(t,n)}build(){return this.formBuilder._finalizeStep(this.stepData).build()}_finalizeRow(t){return t.fields.length>0&&this.stepData.rows.push(t),this}_getData(){return this.stepData}};a(Fr,"FormStepBuilder");var _r=Fr,Vr=class Vr{constructor(t,n){this.data={slots:[],steps:[],status:"draft",version:1};this.validateName(t),this.data.name=t,this.data.label=n;}description(t){return this.data.description=t,this}icon(t){return this.data.icon=t,this}status(t){return this.data.status=t,this}metadata(t){return this.data.metadata=t,this}slot(t,n,r){if(this.data.slots.some(a=>a.id===t))throw new Error(`[FormBuilder] Duplicate slot id: "${t}"`);let o={id:t,objectName:n,label:r.label,mode:r.mode??"create",color:r.color,icon:r.icon};return this.data.slots.push(o),this}step(t,n){if(this.data.steps.some(r=>r.id===t))throw new Error(`[FormBuilder] Duplicate step id: "${t}"`);return new _r(this,t,n)}build(){return this.validateRequiredData(),this.validateSlotReferences(),this.validateFreeFields(),this.validatePrefillExpressions(),this.data}_finalizeStep(t){return this.data.steps.push(t),this}validateName(t){let n=z.string().min(1,"Form name cannot be empty").max(63,"Form name is too long (max 63 characters)").regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,{message:"Invalid form name format. Name must be in kebab-case: 'client-onboarding', 'contact-creation'"});try{n.parse(t);}catch(r){throw r instanceof z.ZodError?new Error(`[FormBuilder] ${r.issues[0].message}`):r}}validateRequiredData(){if(this.data.slots.length===0)throw new Error("[FormBuilder] At least one slot is required. Use .slot() to add slots.");if(this.data.steps.length===0)throw new Error("[FormBuilder] At least one step is required. Use .step() to add steps.")}validateSlotReferences(){let t=new Map(this.data.slots.map(n=>[n.id,n.objectName]));for(let n of this.data.steps)for(let r of n.rows)if(Yt(r))for(let o of r.fields){if(o.type!=="slot")continue;let a=Uo(o);for(let c of a)if(!t.has(c))throw new Error(`[FormBuilder] Step "${n.id}" references unknown slot "${c}". Declare it with .slot("${c}", ...) first.`);let s=new Set(a.map(c=>t.get(c)));if(s.size>1)throw new Error(`[FormBuilder] Step "${n.id}" field on attribute "${o.attribute}" targets slots of different objects (${[...s].join(", ")}). A multi-slot field must target slots of the same object.`)}}validatePrefillExpressions(){let t=[...Qt,"join"];for(let n of this.data.steps)for(let r of n.rows)if(Yt(r))for(let o of r.fields){if(!Bn(o)||!o.prefillExpression)continue;let a=o.prefillExpression,s=`prefillExpression on free field "${o.attribute.name}" in step "${n.id}"`;if(!Xt(a))throw new Error(`[FormBuilder] ${s} must contain at least one {{ attribute }} interpolation.`);if(/\{\{\s*\}\}/.test(a))throw new Error(`[FormBuilder] ${s} contains empty {{ }} interpolation.`);for(let c of a.matchAll(/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g)){let u=c[1];if(!t.includes(u))throw new Error(`[FormBuilder] ${s} uses invalid pipe "${u}". Valid pipes: ${t.join(", ")}`)}}}validateFreeFields(){let t=new Set(Vn);for(let n of this.data.steps)for(let r of n.rows)if(Yt(r)){for(let o of r.fields)if(Bn(o)){let a=o.attribute.type;if(t.has(a))throw new Error(`[FormBuilder] Free field in step "${n.id}" uses forbidden attribute type "${a}". Forbidden types: ${Vn.join(", ")}`)}}}};a(Vr,"FormBuilder");var Pr=Vr;function vx(e,t){return new Pr(e,t)}a(vx,"form");function Wu(e){return {text:"toString",richtext:"toString",number:"toNumber",currency:"toNumber",date:"toDate",checkbox:"toBoolean"}[e]}a(Wu,"resolveBuiltInTransform");var Br=class Br{constructor(t){this.operations=[];this.touchedAttributes=new Set;this.version=t;}assertNotTouched(t,n){if(this.touchedAttributes.has(t))throw new h(`[MigrationBuilder] Conflicting operations on attribute "${t}": it was already modified earlier in this migration (attempted: ${n}).`,[])}renameAttribute(t,n){return this.assertNotTouched(t,"rename_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"rename_attribute",from:t,to:n}),this}changeType(t,n,r,o){this.assertNotTouched(t,"change_type"),this.touchedAttributes.add(t);let a=o?.transform?Wu(r):void 0;return this.operations.push({type:"change_type",name:t,from:n,to:r,transform:a}),this}removeAttribute(t){return this.assertNotTouched(t,"remove_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"remove_attribute",name:t}),this}addAttribute(t){return this.assertNotTouched(t.name,"add_attribute"),this.touchedAttributes.add(t.name),this.operations.push({type:"add_attribute",attribute:t}),this}updateConfig(t,n){return this.assertNotTouched(t,"update_config"),this.touchedAttributes.add(t),this.operations.push({type:"update_config",name:t,from:{},to:n}),this}build(){return {version:this.version,operations:[...this.operations]}}};a(Br,"MigrationBuilder");var sn=Br;function Gu(e){let{name:t,labelExpression:n,embeddingExpression:r}=e;if(!n)throw new b(`Object "${t}" must have a labelExpression. The labelExpression defines how records are displayed in lists and relations (e.g. "{{ name }}").`,a$2.VALIDATION_FAILED);let o=Ye.safeParse(n);if(!o.success){let a=o.error.issues[0]?.message??"Invalid labelExpression";throw new b(`Invalid labelExpression for "${t}": ${a}`,a$2.VALIDATION_FAILED)}if(r!==void 0){let a=Ye.safeParse(r);if(!a.success){let s=a.error.issues[0]?.message??"Invalid embeddingExpression";throw new b(`Invalid embeddingExpression for "${t}": ${s}`,a$2.VALIDATION_FAILED)}}}a(Gu,"validateObjectExpressions");var Lr=class Lr{constructor(t){this._migrations=[];this._sealed=false;this._toleratedAttributes=[];this.validateName(t.name),this.obj={name:t.name,label:t.label,attributes:[],system:true},t.id&&(this.obj.id=t.id);}get"~standard"(){let t=e$1(this.build());return tn(t)}description(t){return this.obj.description=t,this}pluralLabel(t){return this._pluralLabel=t,this}icon(t){return this.obj.icon=t,this}runtime(){return this.obj.system=false,this}sealed(){return this._sealed=true,this}tolerate(t){return this._toleratedAttributes=[...this._toleratedAttributes,...t],this}attribute(t){return this.pushAttributes([t]),this}attributes(t){return this.pushAttributes(t),this}pushAttributes(t){let n=t.map(r=>"build"in r&&typeof r.build=="function"?r.build():r);en([...this.obj.attributes,...n],r=>r.name,r=>new r$1("attribute",r,`Object "${this.obj.name}": duplicate attribute name "${r}"`)),this.obj.attributes.push(...n);}metadata(t){return this.obj.metadata={...this.obj.metadata,...t},this}order(t){return this.obj.metadata={...this.obj.metadata,order:t},this}hidden(){return this.obj.metadata={...this.obj.metadata,hidden:true},this}labelExpression(t){return this._labelExpression=t,this}embeddingExpression(t){return this._embeddingExpression=t,this}documentLayout(t){if(t.presets)for(let n of t.presets)ga(n.id,n.structure,1);return this.obj.documentLayout=t,this}migration(t,n){if(t<2)throw new Error(`[ObjectBuilder] Migration version must be >= 2 (version 1 is implicit). Got: ${t}`);if(this._migrations.some(a=>a.version===t))throw new Error(`[ObjectBuilder] Duplicate migration version: ${t}`);let o=new sn(t);return n(o),this._migrations.push(o.build()),this}build(){if(!this.obj.name)throw new h("[ObjectBuilder] Missing required field: name",[{path:["name"],message:"name is required"}]);if(!this.obj.label)throw new h("[ObjectBuilder] Missing required field: label",[{path:["label"],message:"label is required"}]);Gu({name:this.obj.name,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression});let t=[...this._migrations].sort((r,o)=>r.version-o.version);for(let r=0;r<t.length;r++){let o=r+2;if(t[r].version!==o)throw new Error(`[ObjectBuilder] Migration versions must be sequential starting at 2. Expected version ${o}, got ${t[r].version}.`)}let n=t.length>0?t[t.length-1].version:1;return {...this.obj,pluralLabel:this._pluralLabel,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression,schema_version:n,migrations:t,sealed:this._sealed,toleratedAttributes:this._toleratedAttributes}}validateName(t){t!==void 0&&At(t);}};a(Lr,"ObjectBuilder");var St=Lr;function Bx(e){if(w$1(e.name))throw new s$1(e.name,"builder");return new St(e)}a(Bx,"object");function ga(e,t,n){let r=a((a,s)=>{throw new h(a,[{path:["documentLayout","presets",e],message:s}])},"fail");n>5&&r(`Preset structure exceeds max depth of ${5}`,"Preset structure too deep");let o=new Set;for(let a of t){let s=a.title.trim();s.length===0&&r("Folder preset node title is required","Empty folder title"),s.includes("/")&&r("Folder preset node title cannot contain /",`Folder title contains /: "${s}"`),o.has(s)&&r("Folder preset sibling titles must be unique",`Duplicate folder title: "${s}"`),o.add(s),a.children&&a.children.length>0&&ga(e,a.children,n+1);}}a(ga,"validatePresetStructure");function ue(e,t){try{return structuredClone(e)}catch{let n="Builder configuration must contain cloneable data";throw new h(n,[{path:t,message:n}])}}a(ue,"cloneBuilderValue");function he(e,t){if(typeof e!="string"||e.trim().length===0)throw new h("Name must not be blank",[{path:t,message:"Name must not be blank"}])}a(he,"requireBuilderName");function Ze(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new h("Invalid content configuration",[{path:t,message:"Expected content configuration"}]);for(let c of ["name","label","placement"])if(Object.hasOwn(e,c)){let u=`Independent content configuration cannot define ${c}`;throw new h(u,[{path:[...t,c],message:u}])}let n=ca$1.safeParse({...e,name:"content",placement:"main"});if(!n.success)throw h.fromZodErrors(n.error.issues.map(c=>({path:[...t,...c.path.map(String)],message:c.message})));n.data.type==="form"&&n.data.groups.forEach((c,u)=>he(c.name,[...t,"groups",String(u),"name"]));let{name:r,label:o,placement:a,...s}=n.data;return ue(s,t)}a(Ze,"validateContentConfiguration");function Ur(e,t){return Ze(e,t),ue(e,t)}a(Ur,"validateLiteralContent");function It(e,t,n){if(t!=="record"){let r=`Content "${e}" requires record context`;throw new h(r,[{path:n,message:r}])}}a(It,"requireRecordContentContext");function Ku(e){let t=e.openMode??"page";return {openMode:t,createMode:e.createMode??t}}a(Ku,"resolveContentNavigation");function Yu(e,t){return [...new Set(t)].filter(n=>e.actions===void 0||e.actions.includes(n))}a(Yu,"resolveCollectionActions");var ve=class ve{constructor(t,n=[]){this.kind="view";this.data=ue(t,["views","0"]),this.extensions=n.map(r=>r&&{...r});}for(t){return new ve({...this.data,object:t},this.extensions)}default(){return new ve({...this.data,default:true},this.extensions)}description(t){return new ve({...this.data,description:t},this.extensions)}icon(t){return new ve({...this.data,icon:t},this.extensions)}place(t,n,r,o){let a=["views","0","contents",String(this.data.contents.length)],s,c;try{r!==null&&typeof r=="object"&&"build"in r&&typeof r.build=="function"?(s=Ze(r.build(),a),c=r.extension):s=Ze(r,a);}catch(d){throw d instanceof h?new h(d.message,d.errors.map(f=>({...f,path:f.path[0]==="content"?[...a,...f.path.slice(1)]:f.path}))):d}let u={...s,name:t,label:n,placement:o},m=[...this.data.contents,u];return new ve({...this.data,contents:m},[...this.extensions,c])}tab(t,n,r){return this.place(t,n,r,"main")}aside(t,n,r){return this.place(t,n,r,"aside")}build(){let t=["views","0"];he(this.data.name,[...t,"name"]),he(this.data.object,[...t,"object"]);let n=ea$1.safeParse(this.data);if(!n.success)throw h.fromZodErrors(n.error.issues.map(r=>({path:[...t,...r.path.map(String)],message:r.message})));return this.data.contents.forEach((r,o)=>{let a=[...t,"contents",String(o)];he(r.name,[...a,"name"]),r.type==="form"&&r.groups.forEach((c,u)=>he(c.name,[...a,"groups",String(u),"name"])),(r.type==="custom"?this.extensions[o]?.requiresRecord:r.type==="collection"?r.source.relation!==void 0:true)&&It(r.name,this.data.context,a);}),{kind:"view",definition:ue(this.data,t)}}};a(ve,"ViewBuilder");var cn=ve;function le(e,t){return new cn({name:e,label:t,object:void 0,context:"record",contents:[]})}a(le,"detailView");function de(e,t){return new cn({name:e,label:t,object:void 0,context:"collection",contents:[]})}a(de,"listView");function rT(e){return he(e,["relationProperty"]),{relationProperty:e}}a(rT,"relationProperty");var Rt=class Rt{constructor(t,n){this.data=ue(t,["content"]),this.extension=n===void 0?void 0:Object.freeze({name:n.name,requiresRecord:n.requiresRecord,parameters:n.parameters});}set(t){return new Rt({...this.data,...t},this.extension)}icon(t){return this.set({icon:t})}object(t){return this.data.type==="forms"?this.set({objectName:t}):this.set({source:{object:t}})}related(t){return this.set({source:{relation:t}})}layout(t){let{layout:n,groupByAttribute:r,columnSizing:o,kanbanColumnOrder:a,kanbanColumnVisibility:s,kanbanPinnedColumns:c,...u}={...this.data,layout:void 0,groupByAttribute:void 0,columnSizing:void 0,kanbanColumnOrder:void 0,kanbanColumnVisibility:void 0,kanbanPinnedColumns:void 0};return new Rt({...u,...t},this.extension)}table(){return this.layout({layout:"table"})}list(){return this.layout({layout:"list"})}kanban(t){return this.layout({layout:"kanban",groupByAttribute:t})}columns(...t){return this.set({columns:t})}filter(t){return this.set({filters:t})}sort(t,n="asc"){let o=[..."sorts"in this.data&&Array.isArray(this.data.sorts)?this.data.sorts:[],{attribute:t,direction:n}];return this.set({sorts:o})}actions(...t){return this.set({actions:t})}openMode(t){return this.set({openMode:t})}createMode(t){return this.set({createMode:t})}visibility(t){return this.set({visibility:t})}descriptionAttribute(t){return this.set({descriptionAttribute:t})}displayAttributes(...t){return this.set({displayAttributes:t})}columnSizing(t){return this.set({columnSizing:t})}kanbanColumnOrder(...t){return this.set({kanbanColumnOrder:t})}kanbanColumnVisibility(t){return this.set({kanbanColumnVisibility:t})}kanbanPinnedColumns(...t){return this.set({kanbanPinnedColumns:t})}formColumns(t){return this.set({formColumns:t})}density(t){return this.set({density:t})}titleAttribute(t){return this.set({titleAttribute:t})}allowUpload(t){return this.set({allowUpload:t})}allowRemove(t){return this.set({allowRemove:t})}hideAttachments(t){return this.set({hideAttachments:t})}relations(...t){return this.set({relations:t})}build(){let t=Ur(this.data,["content"]);if(this.extension&&t.type==="custom"){let n=this.extension.parameters.safeParse(ue(t.parameters??{},["content","parameters"]));if(!n.success)throw h.fromZodErrors(n.error.issues.map(r=>({path:["content","parameters",...r.path.map(String)],message:r.message})))}return t}};a(Rt,"ContentBuilder");var te=Rt,Me=class Me{constructor(t,n,r,o={}){this.data=ue({name:t,label:n,fields:r,...o},["group"]);}field(t,n){let{name:r,label:o,fields:a,...s}=this.data;return new Me(r,o,[...a,{attribute:t,...n}],s)}fields(...t){let{name:n,label:r,fields:o,...a}=this.data;return new Me(n,r,[...o,...t.map(s=>({attribute:s}))],a)}description(t){return new Me(this.data.name,this.data.label,this.data.fields,{...this.presentation(),description:t})}collapsible(t=false){return new Me(this.data.name,this.data.label,this.data.fields,{...this.presentation(),collapsible:true,collapsed:t})}presentation(){let{name:t,label:n,fields:r,...o}=this.data;return o}build(){he(this.data.name,["group","name"]);try{Ur({type:"form",groups:[this.data]},["group"]);}catch(t){throw t instanceof h?new h(t.message,t.errors.map(n=>({...n,path:n.path[1]==="groups"?["group",...n.path.slice(3)]:n.path}))):t}return ue(this.data,["group"])}};a(Me,"GroupBuilder");var $r=Me;function pe(e,t){return new $r(e,t,[])}a(pe,"group");function Hu(){return new te({type:"collection"})}a(Hu,"collection");function Ju(...e){let t=e.map(n=>"build"in n?n.build():n);return new te({type:"form",groups:t})}a(Ju,"form");function Qu(){return new te({type:"activity"})}a(Qu,"activity");function Xu(e){return new te({type:"richtext",attribute:e})}a(Xu,"richtext");function Zu(){return new te({type:"documents"})}a(Zu,"documents");function el(){return new te({type:"forms"})}a(el,"forms");function tl(...e){return new te({type:"emails",emailAttributes:e})}a(tl,"emails");function nl(...e){return new te({type:"meetings",emailAttributes:e})}a(nl,"meetings");function rl(e,t){if(typeof e!="object"||e===null||typeof e.name!="string")throw new h("Expected registered extension declaration",[{path:["content","extension"],message:"Expected registered extension declaration"}]);let n=Ze({type:"custom",extension:e.name,parameters:t},["content"]);if(n.type!=="custom")throw new h("Expected custom content",[]);let r=new te({...n,extension:e.name},e);return r.build(),r}a(rl,"custom");var k={collection:Hu,form:Ju,activity:Qu,richtext:Xu,documents:Zu,forms:el,emails:tl,meetings:nl,custom:rl};function il(e){if(!/^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z]$/.test(e))throw new Error(`Invalid flag name "${e}". Flag names must be kebab-case (e.g., "architect-mode", "ai-features").`)}a(il,"validateFlagName");var Kr=class Kr{constructor(t,n,r){il(t),this.flag={name:t,valueType:n,defaultValue:r,allowedLevels:["global","tenant","user"]};}label(t){return this.flag.label=t,this}description(t){return this.flag.description=t,this}category(t){return this.flag.category=t,this}system(){return this.flag.system=true,this}tenantScoped(){return this.flag.allowedLevels=["global","tenant"],this}globalOnly(){return this.flag.allowedLevels=["global"],this}allowedLevels(t){return this.flag.allowedLevels=[...t],this}build(){if(!this.flag.label?.trim())throw new Error(`Flag "${this.flag.name}" must have a label. Use .label("Human-readable label").`);return {...this.flag,allowedLevels:[...this.flag.allowedLevels||[]]}}};a(Kr,"BaseFlagBuilder");var et=Kr,Yr=class Yr extends et{constructor(t){super(t,"boolean",false);}defaultValue(t){return this.flag.defaultValue=t,this}enabledByDefault(){return this.flag.defaultValue=true,this}};a(Yr,"BooleanFlagBuilder");var qr=Yr,Hr=class Hr extends et{constructor(t){super(t,"string","");}defaultValue(t){return this.flag.defaultValue=t,this}};a(Hr,"StringFlagBuilder");var zr=Hr,Jr=class Jr extends et{constructor(t){super(t,"number",0);}defaultValue(t){return this.flag.defaultValue=t,this}};a(Jr,"NumberFlagBuilder");var Wr=Jr,Qr=class Qr extends et{constructor(t,n){super(t,"json",n);}defaultValue(t){return this.flag.defaultValue=t,this}};a(Qr,"JsonFlagBuilder");var Gr=Qr;function ol(e){return new qr(e)}a(ol,"booleanFlag");function al(e){return new zr(e)}a(al,"stringFlag");function sl(e){return new Wr(e)}a(sl,"numberFlag");function cl(e,t){return new Gr(e,t)}a(cl,"jsonFlag");function Xr(e){return new r$1("feature flag",e,`Flag "${e}" is already registered. Each flag name must be unique.`)}a(Xr,"duplicateFlagError");function Zr(e){return {...e,allowedLevels:[...e.allowedLevels]}}a(Zr,"cloneFlagDefinition");var ei=class ei{constructor(){this.flags=new Map;}register(t){if(this.flags.has(t.name))throw Xr(t.name);this.flags.set(t.name,Zr(t));}registerAll(t){let n=new Set;for(let r of t){if(this.flags.has(r.name)||n.has(r.name))throw Xr(r.name);n.add(r.name);}for(let r of t)this.register(r);}get(t){let n=this.flags.get(t);return n?Zr(n):void 0}getOrThrow(t){let n=this.get(t);if(!n)throw new c$2("Feature flag",t,void 0,`Flag "${t}" is not registered. Available flags: ${this.listNames().join(", ")}`);return n}has(t){return this.flags.has(t)}list(){return Array.from(this.flags.values(),Zr)}listNames(){return Array.from(this.flags.keys())}unregister(t){return this.flags.delete(t)}clear(){this.flags.clear();}get size(){return this.flags.size}};a(ei,"FlagRegistry");var vt=ei,ul=new vt;function ll(){return new vt}a(ll,"createFlagRegistry");function un(){return {global:new Map,tenant:new Map,user:new Map}}a(un,"emptyOverrides");function dl(e,t){return e.expiresAt===void 0||e.expiresAt.getTime()>t}a(dl,"isActiveOverride");function ti(e,t){let n=new Map;for(let r of e){if(!dl(r,t))continue;let o=r.flagName;n.has(o)||n.set(o,r);}return n}a(ti,"indexOverrides");var ni=class ni{constructor(t){this.repository=t.repository,this.registry=t.registry,this.staticDefaults=new Map(t.staticDefaults?.map(n=>[n.name,n.value])??[]);}async resolveAll(t={}){let n=this.collectFlagNames(),r=this.repository&&n.size>0?await this.getAllOverrides(t,[...n]):un();return this.resolveNames(n,r,t)}resolveAllStatic(){return this.resolveNames(this.collectFlagNames(),un(),{})}collectFlagNames(){let t=new Set;for(let n of this.registry.listNames())t.add(n);for(let n of this.staticDefaults.keys())t.add(n);return t}resolveNames(t,n,r){let o=new Map;for(let a of t)o.set(a,this.resolveValue(a,n,r));return o}async resolve(t,n={}){let r=this.repository?await this.getAllOverrides(n,[t]):un();return this.resolveWithSource(t,r,n)}async isEnabled(t,n={}){return (await this.resolve(t,n)).value===true}async getValue(t,n={}){return (await this.resolve(t,n)).value}async setOverride(t,n,r,o={}){if(!this.repository)throw new b("Cannot set override: no FeatureFlagsRepository configured. Add featureFlags to your DatabaseAdapter to enable runtime overrides.",a$2.CONFIGURATION_REQUIRED);let a=this.registry.get(t);if(a&&!a.allowedLevels.includes(n)){let s=`Flag "${t}" does not allow ${n}-level overrides. Allowed levels: ${a.allowedLevels.join(", ")}`;throw new h(s,[{path:["level"],message:s}])}if(a?.system){let s=`Flag "${t}" is a system flag and cannot be overridden via API.`;throw new h(s,[{path:["flagName"],message:s}])}await this.repository.setOverride({flagName:t,level:n,value:r,targetId:o.targetId,expiresAt:o.expiresAt,createdBy:o.createdBy});}async deleteOverride(t,n,r){if(!this.repository)throw new b("Cannot delete override: no FeatureFlagsRepository configured.",a$2.CONFIGURATION_REQUIRED);await this.repository.deleteOverride(t,n,r);}async getAllOverrides(t,n){if(!this.repository)return un();let[r,o,a]=await Promise.all([this.repository.getOverrides({level:"global",flagNames:n}),t.tenantId?this.repository.getOverrides({level:"tenant",targetId:t.tenantId,flagNames:n}):Promise.resolve([]),t.userId?this.repository.getOverrides({level:"user",targetId:t.userId,flagNames:n}):Promise.resolve([])]),s=Date.now();return {global:ti(r,s),tenant:ti(o,s),user:ti(a,s)}}resolveValue(t,n,r){return this.resolveWithSource(t,n,r).value}resolveWithSource(t,n,r){let o=this.registry.get(t),a=o?.allowedLevels??["global","tenant","user"];if(r.userId&&a.includes("user")){let s=n.user.get(t);if(s)return {name:t,value:s.value,source:"user",sourceId:r.userId}}if(r.tenantId&&a.includes("tenant")){let s=n.tenant.get(t);if(s)return {name:t,value:s.value,source:"tenant",sourceId:r.tenantId}}if(a.includes("global")){let s=n.global.get(t);if(s)return {name:t,value:s.value,source:"global"}}return this.staticDefaults.has(t)?{name:t,value:this.staticDefaults.get(t),source:"default"}:{name:t,value:o?.defaultValue??void 0,source:"default"}}};a(ni,"FlagService");var ln=ni;function pl(e){return new ln(e)}a(pl,"createFlagService");var ya=Symbol("stndrds.native-object");function ii(e){return Object.defineProperty(e,ya,{value:true,enumerable:false}),e}a(ii,"markNativeDefinition");var ai=class ai extends St{build(){return ii(super.build())}};a(ai,"NativeObjectBuilder");var ri=ai;function me(e){return new ri(e)}a(me,"nativeObject");function oi(e){return e[ya]===true}a(oi,"isNativeDefinition");function si(e){let t=structuredClone(e);return oi(e)?ii(t):t}a(si,"cloneObjectDefinition");var ui=class ui{constructor(){this.objects=new Map;}register(t){let r=(Array.isArray(t)?t:[t]).map(a=>"build"in a&&typeof a.build=="function"?a.build():a),o=new Set;for(let a of r){if(this.validate(a),o.has(a.name))throw new r$1("object",a.name,`[NativeObjectRegistry] Duplicate object name "${a.name}" within a single register() batch.`);o.add(a.name);}for(let a of r)this.objects.set(a.name,si(a));return this}validate(t){if(!t.system){let n=`[NativeObjectRegistry] Cannot register object "${t.name}" (id: ${t.id}): missing system flag.
|
|
14
|
-
Native objects must have system=true. Did you call .runtime() on the builder? Remove that call \u2014 objects are system:true by default.`;throw new h(n,[])}if(w$1(t.name)&&!
|
|
12
|
+
Reserved names: ${B$1.join(", ")}`)}a(St,"validateAttributeName");function Yo(e){if(!e||e.length===0)throw new Error("[AttributeBuilder] Attribute label cannot be empty");if(e.length>Go)throw new Error(`[AttributeBuilder] Attribute label is too long (max ${Go} characters)`)}a(Yo,"validateLabel");function Ho(e,t){if(!Cu.has(e))throw new Error(`[AttributeBuilder] Invalid icon "${e}" in ${t}.
|
|
13
|
+
Icon must be one of the predefined icons from @stndrds/constants.`)}a(Ho,"validateIconName");function $e(e,t){let n=new Set;for(let r of t){if(!r.value?.trim())throw new Error(`[AttributeBuilder] Option in "${e}" has an empty or missing value.`);if(!r.label?.trim())throw new Error(`[AttributeBuilder] Option "${r.value}" in "${e}" has an empty or missing label.`);if(n.has(r.value))throw new Error(`[AttributeBuilder] Duplicate option value "${r.value}" in "${e}".`);n.add(r.value);}for(let r of t){if(r.inverse===void 0)continue;let o=t.find(a=>a.value===r.inverse);if(!o)throw new Error(`[AttributeBuilder] Option "${r.value}" in "${e}" has inverse "${r.inverse}" which does not match any option value.`);if(o.inverse!==r.value)throw new Error(`[AttributeBuilder] Inverse mismatch in "${e}": "${r.value}" points to "${r.inverse}", but "${r.inverse}" points to "${o.inverse??"(none)"}". Inverse pairs must be symmetric.`)}}a($e,"validateOptions");var Jo={maxConcurrentRuns:3,retryPolicy:{maxRetries:3,backoffMs:1e3,backoffMultiplier:2},timeoutMs:3e5},Kn=class Kn{constructor(t){if(!t.name||t.name.trim().length===0)throw new h("Agent name is required",[]);this.bp={name:t.name,system:true,visibility:"workspace",triggers:[]};}description(t){return this.bp.description=t,this}label(t){return this.bp.label=t,this}icon(t){return this.bp.icon=t,this}systemPrompt(t){return this.bp.systemPrompt=t,this}model(t,n,r){return this.bp.model={provider:t,model:n,...r},this}tools(t){return this.bp.tools=[...t],this}schedule(t){return this.bp.schedule={...t,enabled:t.enabled??true},this}config(t){let n=this.bp.config??Jo,r=t.inference===void 0?n.inference:{...n.inference,...t.inference};return this.bp.config={...n,...t,...r===void 0?{}:{inference:r}},this}delegation(t){return Object.assign(this.bp,t),this}mcpServers(t){return this.bp.mcpServers=Array.isArray(t)?[...t]:t,this}approval(t){return this.bp.approval={...So,...this.bp.approval,...t},this}visibility(t){return this.bp.visibility=t,this}requiresPermission(t,n){return this.bp.requiredPermission={resource:t,action:n},this}trigger(t,n,r){return this.bp.triggers.push({name:t,eventType:n,...r,enabled:r?.enabled??true}),this}runtime(){return this.bp.system=false,this}build(){if(!this.bp.systemPrompt)throw new h(`Agent "${this.bp.name}": systemPrompt is required`,[]);if(!this.bp.model)throw new h(`Agent "${this.bp.name}": model is required`,[]);if(this.bp.system&&this.bp.visibility==="private")throw new h(`Agent "${this.bp.name}": system agents must use workspace visibility`,[]);return en(this.bp.triggers,t=>t.name,t=>new h(`Agent "${this.bp.name}": duplicate trigger name "${t}"`,[])),{...this.bp,visibility:this.bp.visibility??"workspace",config:this.bp.config??Jo,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};a(Kn,"AgentBuilder");var Gn=Kn;function OA(e){return new Gn(e)}a(OA,"agent");var Nu="@stndrds/schema";function tn(e){return {version:1,vendor:Nu,validate:a(t=>{let n=e.safeParse(t);return n.success?{value:n.data}:{issues:n.error.issues.map(r=>({message:r.message,path:r.path}))}},"validate")}}a(tn,"createStandardSchemaProps");function _A(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"].version===1}a(_A,"isStandardSchema");var dr=class dr{get"~standard"(){let t=c$2(this.build());return tn(t)}constructor(t,n,r){St(n),Yo(r),this.attr={name:n,label:r,type:t,required:false,system:true};}setRequired(t){this.attr.required=t;}asRequiredState(){return this}asPhantomState(){return this}runtime(){return this.attr.system=false,this}hidden(){return this.attr.hidden=true,this}placeholder(t){return this.attr.placeholder=t,this}description(t){return this.attr.description=t,this}icon(t){return Ho(t,`attribute "${this.attr.name}"`),this.attr.icon=t,this}order(t){return this.attr.order=t,this}defaultValue(t){return ("defaultValue"in this.attr||!["formula","rollup"].includes(this.attr.type))&&(this.attr.defaultValue=t),this}metadata(t){return this.attr.metadata=t,this}build(){return this.attr}};a(dr,"BaseAttributeBuilder");var B=dr,pr=class pr extends B{constructor(t,n){super("text",t,n);}minLength(t){return this.attr.minLength=t,this}maxLength(t){return this.attr.maxLength=t,this}pattern(t){return this.attr.pattern=t,this.attr.format=void 0,this}multiline(t=true){return this.attr.multiline=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}email(){return this.attr.format="email",this.attr.pattern=void 0,this}url(){return this.attr.format="url",this.attr.pattern=void 0,this}slug(){return this.attr.format="slug",this.attr.pattern=void 0,this}};a(pr,"TextAttributeBuilder");var Yn=pr;function w(e){return new Yn(e.name,e.label)}a(w,"text");var mr=class mr extends B{constructor(t,n){super("richtext",t,n);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(mr,"RichtextAttributeBuilder");var Hn=mr;function De(e){return new Hn(e.name,e.label)}a(De,"richtext");var fr=class fr extends B{constructor(t,n){super("number",t,n);}min(t){return this.attr.min=t,this}max(t){return this.attr.max=t,this}integer(){return this.attr.unit="integer",this.attr.decimals=0,this}decimal(t=2){return this.attr.unit="decimal",this.attr.decimals=t,this}percentage(){return this.attr.unit="percentage",this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(fr,"NumberAttributeBuilder");var Jn=fr;function rn(e){return new Jn(e.name,e.label)}a(rn,"number");var br=class br extends B{constructor(t,n){super("checkbox",t,n);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(br,"CheckboxAttributeBuilder");var Qn=br;function Qo(e){return new Qn(e.name,e.label)}a(Qo,"checkbox");var gr=class gr extends B{constructor(t,n){super("date",t,n);}format(t){return this.attr.dateFormat=t,this}minDate(t){return this.attr.minDate=t,this}maxDate(t){return this.attr.maxDate=t,this}endDate(){return this.attr.endDate=true,this.asPhantomState()}includeTime(){return this.attr.includeTime=true,this}timeFormat(t){return this.attr.timeFormat=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(gr,"DateAttributeBuilder");var Xn=gr;function oe(e){return new Xn(e.name,e.label)}a(oe,"date");var yr=class yr extends B{constructor(t,n){super("phone",t,n);}defaultCountry(t){return this.attr.defaultCountryCode=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(yr,"PhoneAttributeBuilder");var Zn=yr;function qA(e){return new Zn(e.name,e.label)}a(qA,"phone");var hr=class hr extends B{constructor(t,n){super("currency",t,n);}defaultCurrency(t){return this.attr.defaultCurrency=t,this}allowedCurrencies(t){return this.attr.allowedCurrencies=t,this}allowNegative(t=true){return this.attr.allowNegative=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(hr,"CurrencyAttributeBuilder");var er=hr;function zA(e){return new er(e.name,e.label)}a(zA,"currency");var Ar=class Ar extends B{constructor(t,n){super("status",t,n);}options(t){let n=t;return $e(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return $e(this.attr.name??"unknown",n),this.attr.options.push(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Ar,"StatusAttributeBuilder");var tr=Ar;function WA(e){return new tr(e.name,e.label)}a(WA,"status");var xr=class xr extends B{constructor(t,n){super("select",t,n);}options(t){let n=t;return $e(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return $e(this.attr.name??"unknown",n),this.attr.options.push(t),this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(xr,"SelectAttributeBuilder");var nr=xr;function pe(e){return new nr(e.name,e.label)}a(pe,"select");var Tr=class Tr extends B{constructor(t,n){super("multiselect",t,n);}options(t){let n=t;return $e(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return $e(this.attr.name??"unknown",n),this.attr.options.push(t),this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Tr,"MultiselectAttributeBuilder");var rr=Tr;function GA(e){return new rr(e.name,e.label)}a(GA,"multiselect");var wr=class wr extends B{constructor(t,n){super("location",t,n);}granularity(t){return this.attr.granularity=t,this}defaultCountry(t){return this.attr.defaultCountry=t,this}allowedCountries(t){return this.attr.allowedCountries=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(wr,"LocationAttributeBuilder");var ir=wr;function KA(e){return new ir(e.name,e.label)}a(KA,"location");var Sr=class Sr extends B{constructor(t,n){super("user",t,n),this.attr.types=["user","agent"];}types(t){let n=[...new Set(t)];if(n.length===0)throw new Error("[AttributeBuilder] user.types must contain at least one type.");return this.attr.types=n,this}multiple(){return this.attr.multiple=true,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Sr,"UserAttributeBuilder");var or=Sr;function YA(e){return new or(e.name,e.label)}a(YA,"user");var Ir=class Ir extends B{to(t,n){let r={object:t,...n};return this.attr.targets?.push(r),this}toAny(){return this.attr.targets=[{object:we}],this}qualifyWith(...t){let n=this.attr.targets;if(!n||n.length===0)throw new Error('.qualifyWith() must be called AFTER .to(). Example: relation({ name: "companies" }).to("companies").qualifyWith(...)');return this.attr.properties=Ht(t),this}bilateral(t){let n=this.attr.targets;if(!n||n.length===0)throw new Error('.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })');if(n.length>1)throw new Error("Bilateral relations are not supported for polymorphic relations (multiple .to() targets).");if(To(this.attr))throw new Error("Bilateral relations are not supported for universal relations (.toAny()).");let r=n[0]?.object;if(!r)throw new h("Bilateral relation requires one target object",[{path:["bilateral","object"],message:"Bilateral relation requires one target object"}]);if(t.object&&t.object!==r){let o=`Bilateral inverse object ${t.object} must match relation target ${r}`;throw new h(o,[{path:["bilateral","object"],message:o}])}return this.attr.bilateral={...t,object:r},this}};a(Ir,"BaseRelationAttributeBuilder");var nn=Ir,Rr=class Rr extends nn{constructor(t,n){super("relation",t,n),this.attr.cardinality="one",this.attr.targets=[];}many(){let t=new sr(this.attr.name,this.attr.label??"",{targets:this.attr.targets,isRequired:this.attr.required});return this.attr.system===false&&t.runtime(),this.attr.hidden&&t.hidden(),this.attr.placeholder&&t.placeholder(this.attr.placeholder),this.attr.description&&t.description(this.attr.description),this.attr.icon&&t.icon(this.attr.icon),this.attr.order!==void 0&&t.order(this.attr.order),this.attr.metadata&&t.metadata(this.attr.metadata),t}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Rr,"SingleRelationAttributeBuilder");var ar=Rr,Cr=class Cr extends nn{constructor(t,n,r){super("relation",t,n),this.attr.cardinality="many",this.attr.targets=r?.targets??[],this.attr.defaultValue=[],r?.isRequired&&this.setRequired(true);}maxItems(t){return this.attr.maxItems=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Cr,"MultiRelationAttributeBuilder");var sr=Cr;function rt(e){return new ar(e.name,e.label)}a(rt,"relation");var vr=class vr extends B{constructor(t,n){super("formula",t,n),this.attr.required=false;}expression(t){return this.attr.expression=t,this}returns(t){return this.attr.returnType=t,this}decimals(t){return this.attr.decimals=t,this}required(){throw new Error("Formula attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.")}optional(){return this}};a(vr,"FormulaAttributeBuilder");var cr=vr;function HA(e){return new cr(e.name,e.label)}a(HA,"formula");var Er=class Er extends B{constructor(t,n){super("rollup",t,n),this.attr.required=false;}from(t){return this.attr.relationAttribute=t,this}aggregate(t){return this.attr.targetAttribute=t,this}using(t){return this.attr.function=t,this}decimals(t){return this.attr.decimals=t,this}path(t){return this.attr.relationPath=t,this}targetType(t){return this.attr.targetAttributeType=t,this}targetOptions(t){return this.attr.targetAttributeOptions=t,this}targetCurrency(t){return this.attr.targetCurrencyCode=t,this}build(){let t=this.attr.function,n=this.attr.targetAttributeType;if(t==="original"&&n!==void 0&&n!=="select"&&n!=="status"&&n!=="multiselect"){let r=this.attr.relationAttribute??"relation",o=this.attr.targetAttribute??"field";throw new b(`Rollup "${this.attr.name}": .using("original") only supports a "select", "status", or "multiselect" target, but .targetType("${n}") was given. To surface a plain ${n} value from a related record, use a formula instead \u2014 e.g. formula({ name: "${this.attr.name}", label: "\u2026" }).expression("${r}.${o}").`,a$2.VALIDATION_FAILED)}return super.build()}required(){throw new Error("Rollup attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.")}optional(){return this}};a(Er,"RollupAttributeBuilder");var ur=Er;function JA(e){return new ur(e.name,e.label)}a(JA,"rollup");var Nr=class Nr extends B{constructor(t,n){super("document",t,n);}accepts(t){return this.attr.accepts=t,this}maxFileSize(t){return this.attr.maxFileSize=t,this}qualifyWith(...t){return this.attr.properties=Ht(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Nr,"DocumentAttributeBuilder");var lr=Nr;function Xo(e){return new lr(e.name,e.label)}a(Xo,"document");function ea(e,t,n){let r=Array.isArray(e)?e:[e],[o,...a]=r;return {type:"slot",slotId:o,additionalSlotIds:a.length>0?a:void 0,attribute:t,label:n?.label,required:n?.required,tooltip:n?.tooltip}}a(ea,"buildSlotFieldRef");var jr=class jr{constructor(t,n,r){this._finalized=false;this.stepBuilder=t,this.rowData={id:n,order:r,type:"fields",fields:[]};}field(t,n,r){return this.rowData.fields.push(ea(t,n,r)),this}freeField(t,n){let o={type:"free",attribute:t.build(),label:n?.label,required:n?.required,prefillExpression:n?.prefillExpression};return this.rowData.fields.push(o),this}row(t){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).row(t)}heading(t,n){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).heading(t,n)}separator(){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).separator()}text(t){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).text(t)}endRow(){return this._finalized?this.stepBuilder:(this._finalized=true,this.stepBuilder._finalizeRow(this.rowData))}};a(jr,"FormRowBuilder");var Dr=jr,_r=class _r{constructor(t,n,r){this.rowOrder=0;this.formBuilder=t,this.stepData={id:n,label:r,rows:[]};}description(t){return this.stepData.description=t,this}field(t,n,r){this.rowOrder++;let o=`row-${this.stepData.id}-${this.rowOrder}`,a=ea(t,n,r),s={id:o,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}freeField(t,n){this.rowOrder++;let r=`row-${this.stepData.id}-${this.rowOrder}`,a={type:"free",attribute:t.build(),label:n?.label,required:n?.required,prefillExpression:n?.prefillExpression},s={id:r,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}row(t){return this.rowOrder++,new Dr(this,t,this.rowOrder)}heading(t,n){this.rowOrder++;let r={id:`heading-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"heading",content:t,level:n};return this.stepData.rows.push(r),this}separator(){this.rowOrder++;let t={id:`sep-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"separator"};return this.stepData.rows.push(t),this}text(t){this.rowOrder++;let n={id:`text-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"text",content:t};return this.stepData.rows.push(n),this}step(t,n){return this.formBuilder._finalizeStep(this.stepData).step(t,n)}build(){return this.formBuilder._finalizeStep(this.stepData).build()}_finalizeRow(t){return t.fields.length>0&&this.stepData.rows.push(t),this}_getData(){return this.stepData}};a(_r,"FormStepBuilder");var Or=_r,Pr=class Pr{constructor(t,n){this.data={slots:[],steps:[],status:"draft",version:1};this.validateName(t),this.data.name=t,this.data.label=n;}description(t){return this.data.description=t,this}icon(t){return this.data.icon=t,this}status(t){return this.data.status=t,this}metadata(t){return this.data.metadata=t,this}slot(t,n,r){if(this.data.slots.some(a=>a.id===t))throw new Error(`[FormBuilder] Duplicate slot id: "${t}"`);let o={id:t,objectName:n,label:r.label,mode:r.mode??"create",color:r.color,icon:r.icon};return this.data.slots.push(o),this}step(t,n){if(this.data.steps.some(r=>r.id===t))throw new Error(`[FormBuilder] Duplicate step id: "${t}"`);return new Or(this,t,n)}build(){return this.validateRequiredData(),this.validateSlotReferences(),this.validateFreeFields(),this.validatePrefillExpressions(),this.data}_finalizeStep(t){return this.data.steps.push(t),this}validateName(t){let n=z.string().min(1,"Form name cannot be empty").max(63,"Form name is too long (max 63 characters)").regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,{message:"Invalid form name format. Name must be in kebab-case: 'client-onboarding', 'contact-creation'"});try{n.parse(t);}catch(r){throw r instanceof z.ZodError?new Error(`[FormBuilder] ${r.issues[0].message}`):r}}validateRequiredData(){if(this.data.slots.length===0)throw new Error("[FormBuilder] At least one slot is required. Use .slot() to add slots.");if(this.data.steps.length===0)throw new Error("[FormBuilder] At least one step is required. Use .step() to add steps.")}validateSlotReferences(){let t=new Map(this.data.slots.map(n=>[n.id,n.objectName]));for(let n of this.data.steps)for(let r of n.rows)if(Yt(r))for(let o of r.fields){if(o.type!=="slot")continue;let a=Oo(o);for(let c of a)if(!t.has(c))throw new Error(`[FormBuilder] Step "${n.id}" references unknown slot "${c}". Declare it with .slot("${c}", ...) first.`);let s=new Set(a.map(c=>t.get(c)));if(s.size>1)throw new Error(`[FormBuilder] Step "${n.id}" field on attribute "${o.attribute}" targets slots of different objects (${[...s].join(", ")}). A multi-slot field must target slots of the same object.`)}}validatePrefillExpressions(){let t=[...Qt,"join"];for(let n of this.data.steps)for(let r of n.rows)if(Yt(r))for(let o of r.fields){if(!Vn(o)||!o.prefillExpression)continue;let a=o.prefillExpression,s=`prefillExpression on free field "${o.attribute.name}" in step "${n.id}"`;if(!Xt(a))throw new Error(`[FormBuilder] ${s} must contain at least one {{ attribute }} interpolation.`);if(/\{\{\s*\}\}/.test(a))throw new Error(`[FormBuilder] ${s} contains empty {{ }} interpolation.`);for(let c of a.matchAll(/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g)){let u=c[1];if(!t.includes(u))throw new Error(`[FormBuilder] ${s} uses invalid pipe "${u}". Valid pipes: ${t.join(", ")}`)}}}validateFreeFields(){let t=new Set(Fn);for(let n of this.data.steps)for(let r of n.rows)if(Yt(r)){for(let o of r.fields)if(Vn(o)){let a=o.attribute.type;if(t.has(a))throw new Error(`[FormBuilder] Free field in step "${n.id}" uses forbidden attribute type "${a}". Forbidden types: ${Fn.join(", ")}`)}}}};a(Pr,"FormBuilder");var kr=Pr;function rx(e,t){return new kr(e,t)}a(rx,"form");function Du(e){return {text:"toString",richtext:"toString",number:"toNumber",currency:"toNumber",date:"toDate",checkbox:"toBoolean"}[e]}a(Du,"resolveBuiltInTransform");var Mr=class Mr{constructor(t){this.operations=[];this.touchedAttributes=new Set;this.version=t;}assertNotTouched(t,n){if(this.touchedAttributes.has(t))throw new h(`[MigrationBuilder] Conflicting operations on attribute "${t}": it was already modified earlier in this migration (attempted: ${n}).`,[])}renameAttribute(t,n){return this.assertNotTouched(t,"rename_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"rename_attribute",from:t,to:n}),this}changeType(t,n,r,o){this.assertNotTouched(t,"change_type"),this.touchedAttributes.add(t);let a=o?.transform?Du(r):void 0;return this.operations.push({type:"change_type",name:t,from:n,to:r,transform:a}),this}removeAttribute(t){return this.assertNotTouched(t,"remove_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"remove_attribute",name:t}),this}addAttribute(t){return this.assertNotTouched(t.name,"add_attribute"),this.touchedAttributes.add(t.name),this.operations.push({type:"add_attribute",attribute:t}),this}updateConfig(t,n){return this.assertNotTouched(t,"update_config"),this.touchedAttributes.add(t),this.operations.push({type:"update_config",name:t,from:{},to:n}),this}build(){return {version:this.version,operations:[...this.operations]}}};a(Mr,"MigrationBuilder");var on=Mr;function Ou(e){let{name:t,labelExpression:n,embeddingExpression:r}=e;if(!n)throw new b(`Object "${t}" must have a labelExpression. The labelExpression defines how records are displayed in lists and relations (e.g. "{{ name }}").`,a$2.VALIDATION_FAILED);let o=et.safeParse(n);if(!o.success){let a=o.error.issues[0]?.message??"Invalid labelExpression";throw new b(`Invalid labelExpression for "${t}": ${a}`,a$2.VALIDATION_FAILED)}if(r!==void 0){let a=et.safeParse(r);if(!a.success){let s=a.error.issues[0]?.message??"Invalid embeddingExpression";throw new b(`Invalid embeddingExpression for "${t}": ${s}`,a$2.VALIDATION_FAILED)}}}a(Ou,"validateObjectExpressions");var Fr=class Fr{constructor(t){this._migrations=[];this._sealed=false;this._toleratedAttributes=[];this.validateName(t.name),this.obj={name:t.name,label:t.label,attributes:[],system:true},t.id&&(this.obj.id=t.id);}get"~standard"(){let t=e(this.build());return tn(t)}description(t){return this.obj.description=t,this}pluralLabel(t){return this._pluralLabel=t,this}icon(t){return this.obj.icon=t,this}runtime(){return this.obj.system=false,this}sealed(){return this._sealed=true,this}tolerate(t){return this._toleratedAttributes=[...this._toleratedAttributes,...t],this}attribute(t){return this.pushAttributes([t]),this}attributes(t){return this.pushAttributes(t),this}pushAttributes(t){let n=t.map(r=>"build"in r&&typeof r.build=="function"?r.build():r);en([...this.obj.attributes,...n],r=>r.name,r$1=>new r("attribute",r$1,`Object "${this.obj.name}": duplicate attribute name "${r$1}"`)),this.obj.attributes.push(...n);}metadata(t){return this.obj.metadata={...this.obj.metadata,...t},this}order(t){return this.obj.metadata={...this.obj.metadata,order:t},this}hidden(){return this.obj.metadata={...this.obj.metadata,hidden:true},this}labelExpression(t){return this._labelExpression=t,this}embeddingExpression(t){return this._embeddingExpression=t,this}documentLayout(t){if(t.presets)for(let n of t.presets)ta(n.id,n.structure,1);return this.obj.documentLayout=t,this}migration(t,n){if(t<2)throw new Error(`[ObjectBuilder] Migration version must be >= 2 (version 1 is implicit). Got: ${t}`);if(this._migrations.some(a=>a.version===t))throw new Error(`[ObjectBuilder] Duplicate migration version: ${t}`);let o=new on(t);return n(o),this._migrations.push(o.build()),this}build(){if(!this.obj.name)throw new h("[ObjectBuilder] Missing required field: name",[{path:["name"],message:"name is required"}]);if(!this.obj.label)throw new h("[ObjectBuilder] Missing required field: label",[{path:["label"],message:"label is required"}]);Ou({name:this.obj.name,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression});let t=[...this._migrations].sort((r,o)=>r.version-o.version);for(let r=0;r<t.length;r++){let o=r+2;if(t[r].version!==o)throw new Error(`[ObjectBuilder] Migration versions must be sequential starting at 2. Expected version ${o}, got ${t[r].version}.`)}let n=t.length>0?t[t.length-1].version:1;return {...this.obj,pluralLabel:this._pluralLabel,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression,schema_version:n,migrations:t,sealed:this._sealed,toleratedAttributes:this._toleratedAttributes}}validateName(t){t!==void 0&&wt(t);}};a(Fr,"ObjectBuilder");var It=Fr;function gx(e){if(w$1(e.name))throw new s(e.name,"builder");return new It(e)}a(gx,"object");function ta(e,t,n){let r=a((a,s)=>{throw new h(a,[{path:["documentLayout","presets",e],message:s}])},"fail");n>5&&r(`Preset structure exceeds max depth of ${5}`,"Preset structure too deep");let o=new Set;for(let a of t){let s=a.title.trim();s.length===0&&r("Folder preset node title is required","Empty folder title"),s.includes("/")&&r("Folder preset node title cannot contain /",`Folder title contains /: "${s}"`),o.has(s)&&r("Folder preset sibling titles must be unique",`Duplicate folder title: "${s}"`),o.add(s),a.children&&a.children.length>0&&ta(e,a.children,n+1);}}a(ta,"validatePresetStructure");function me(e,t){try{return structuredClone(e)}catch{let n="Builder configuration must contain cloneable data";throw new h(n,[{path:t,message:n}])}}a(me,"cloneBuilderValue");function Se(e,t){if(typeof e!="string"||e.trim().length===0)throw new h("Name must not be blank",[{path:t,message:"Name must not be blank"}])}a(Se,"requireBuilderName");function it(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new h("Invalid content configuration",[{path:t,message:"Expected content configuration"}]);for(let c of ["name","label","placement"])if(Object.hasOwn(e,c)){let u=`Independent content configuration cannot define ${c}`;throw new h(u,[{path:[...t,c],message:u}])}let n=ca$1.safeParse({...e,name:"content",placement:"main"});if(!n.success)throw h.fromZodErrors(n.error.issues.map(c=>({path:[...t,...c.path.map(String)],message:c.message})));n.data.type==="form"&&n.data.groups.forEach((c,u)=>Se(c.name,[...t,"groups",String(u),"name"]));let{name:r,label:o,placement:a,...s}=n.data;return me(s,t)}a(it,"validateContentConfiguration");function Vr(e,t){return it(e,t),me(e,t)}a(Vr,"validateLiteralContent");function Rt(e,t,n){if(t!=="record"){let r=`Content "${e}" requires record context`;throw new h(r,[{path:n,message:r}])}}a(Rt,"requireRecordContentContext");function ku(e){let t=e.openMode??"page";return {openMode:t,createMode:e.createMode??t}}a(ku,"resolveContentNavigation");function ju(e,t){return [...new Set(t)].filter(n=>e.actions===void 0||e.actions.includes(n))}a(ju,"resolveCollectionActions");var Oe=class Oe{constructor(t,n=[]){this.kind="view";this.data=me(t,["views","0"]),this.extensions=n.map(r=>r&&{...r});}for(t){return new Oe({...this.data,object:t},this.extensions)}default(){return new Oe({...this.data,default:true},this.extensions)}description(t){return new Oe({...this.data,description:t},this.extensions)}icon(t){return new Oe({...this.data,icon:t},this.extensions)}place(t,n,r,o){let a=["views","0","contents",String(this.data.contents.length)],s,c;try{r!==null&&typeof r=="object"&&"build"in r&&typeof r.build=="function"?(s=it(r.build(),a),c=r.extension):s=it(r,a);}catch(m){throw m instanceof h?new h(m.message,m.errors.map(p=>({...p,path:p.path[0]==="content"?[...a,...p.path.slice(1)]:p.path}))):m}let u={...s,name:t,label:n,placement:o},d=[...this.data.contents,u];return new Oe({...this.data,contents:d},[...this.extensions,c])}tab(t,n,r){return this.place(t,n,r,"main")}aside(t,n,r){return this.place(t,n,r,"aside")}build(){let t=["views","0"];Se(this.data.name,[...t,"name"]),Se(this.data.object,[...t,"object"]);let n=ea$1.safeParse(this.data);if(!n.success)throw h.fromZodErrors(n.error.issues.map(r=>({path:[...t,...r.path.map(String)],message:r.message})));return this.data.contents.forEach((r,o)=>{let a=[...t,"contents",String(o)];Se(r.name,[...a,"name"]),r.type==="form"&&r.groups.forEach((c,u)=>Se(c.name,[...a,"groups",String(u),"name"])),(r.type==="custom"?this.extensions[o]?.requiresRecord:r.type==="collection"?r.source.relation!==void 0:true)&&Rt(r.name,this.data.context,a);}),{kind:"view",definition:me(this.data,t)}}};a(Oe,"ViewBuilder");var an=Oe;function fe(e,t){return new an({name:e,label:t,object:void 0,context:"record",contents:[]})}a(fe,"detailView");function be(e,t){return new an({name:e,label:t,object:void 0,context:"collection",contents:[]})}a(be,"listView");function _x(e){return Se(e,["relationProperty"]),{relationProperty:e}}a(_x,"relationProperty");var Ct=class Ct{constructor(t,n){this.data=me(t,["content"]),this.extension=n===void 0?void 0:Object.freeze({name:n.name,requiresRecord:n.requiresRecord,parameters:n.parameters});}set(t){return new Ct({...this.data,...t},this.extension)}icon(t){return this.set({icon:t})}object(t){return this.data.type==="forms"?this.set({objectName:t}):this.set({source:{object:t}})}related(t){return this.set({source:{relation:t}})}layout(t){let{layout:n,groupByAttribute:r,columnSizing:o,kanbanColumnOrder:a,kanbanColumnVisibility:s,kanbanPinnedColumns:c,...u}={...this.data,layout:void 0,groupByAttribute:void 0,columnSizing:void 0,kanbanColumnOrder:void 0,kanbanColumnVisibility:void 0,kanbanPinnedColumns:void 0};return new Ct({...u,...t},this.extension)}table(){return this.layout({layout:"table"})}list(){return this.layout({layout:"list"})}kanban(t){return this.layout({layout:"kanban",groupByAttribute:t})}columns(...t){return this.set({columns:t})}filter(t){return this.set({filters:t})}sort(t,n="asc"){let o=[..."sorts"in this.data&&Array.isArray(this.data.sorts)?this.data.sorts:[],{attribute:t,direction:n}];return this.set({sorts:o})}actions(...t){return this.set({actions:t})}openMode(t){return this.set({openMode:t})}createMode(t){return this.set({createMode:t})}visibility(t){return this.set({visibility:t})}descriptionAttribute(t){return this.set({descriptionAttribute:t})}displayAttributes(...t){return this.set({displayAttributes:t})}columnSizing(t){return this.set({columnSizing:t})}kanbanColumnOrder(...t){return this.set({kanbanColumnOrder:t})}kanbanColumnVisibility(t){return this.set({kanbanColumnVisibility:t})}kanbanPinnedColumns(...t){return this.set({kanbanPinnedColumns:t})}formColumns(t){return this.set({formColumns:t})}density(t){return this.set({density:t})}titleAttribute(t){return this.set({titleAttribute:t})}allowUpload(t){return this.set({allowUpload:t})}allowRemove(t){return this.set({allowRemove:t})}hideAttachments(t){return this.set({hideAttachments:t})}relations(...t){return this.set({relations:t})}build(){let t=Vr(this.data,["content"]);if(this.extension&&t.type==="custom"){let n=this.extension.parameters.safeParse(me(t.parameters??{},["content","parameters"]));if(!n.success)throw h.fromZodErrors(n.error.issues.map(r=>({path:["content","parameters",...r.path.map(String)],message:r.message})))}return t}};a(Ct,"ContentBuilder");var ae=Ct,Ue=class Ue{constructor(t,n,r,o={}){this.data=me({name:t,label:n,fields:r,...o},["group"]);}field(t,n){let{name:r,label:o,fields:a,...s}=this.data;return new Ue(r,o,[...a,{attribute:t,...n}],s)}fields(...t){let{name:n,label:r,fields:o,...a}=this.data;return new Ue(n,r,[...o,...t.map(s=>({attribute:s}))],a)}description(t){return new Ue(this.data.name,this.data.label,this.data.fields,{...this.presentation(),description:t})}collapsible(t=false){return new Ue(this.data.name,this.data.label,this.data.fields,{...this.presentation(),collapsible:true,collapsed:t})}presentation(){let{name:t,label:n,fields:r,...o}=this.data;return o}build(){Se(this.data.name,["group","name"]);try{Vr({type:"form",groups:[this.data]},["group"]);}catch(t){throw t instanceof h?new h(t.message,t.errors.map(n=>({...n,path:n.path[1]==="groups"?["group",...n.path.slice(3)]:n.path}))):t}return me(this.data,["group"])}};a(Ue,"GroupBuilder");var Br=Ue;function ge(e,t){return new Br(e,t,[])}a(ge,"group");function _u(){return new ae({type:"collection"})}a(_u,"collection");function Pu(...e){let t=e.map(n=>"build"in n?n.build():n);return new ae({type:"form",groups:t})}a(Pu,"form");function Mu(){return new ae({type:"activity"})}a(Mu,"activity");function Fu(e){return new ae({type:"richtext",attribute:e})}a(Fu,"richtext");function Vu(){return new ae({type:"documents"})}a(Vu,"documents");function Bu(){return new ae({type:"forms"})}a(Bu,"forms");function Lu(...e){return new ae({type:"emails",emailAttributes:e})}a(Lu,"emails");function $u(...e){return new ae({type:"meetings",emailAttributes:e})}a($u,"meetings");function Uu(e,t){if(typeof e!="object"||e===null||typeof e.name!="string")throw new h("Expected registered extension declaration",[{path:["content","extension"],message:"Expected registered extension declaration"}]);let n=it({type:"custom",extension:e.name,parameters:t},["content"]);if(n.type!=="custom")throw new h("Expected custom content",[]);let r=new ae({...n,extension:e.name},e);return r.build(),r}a(Uu,"custom");var N={collection:_u,form:Pu,activity:Mu,richtext:Fu,documents:Vu,forms:Bu,emails:Lu,meetings:$u,custom:Uu};function qu(e){if(!/^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z]$/.test(e))throw new Error(`Invalid flag name "${e}". Flag names must be kebab-case (e.g., "architect-mode", "ai-features").`)}a(qu,"validateFlagName");var zr=class zr{constructor(t,n,r){qu(t),this.flag={name:t,valueType:n,defaultValue:r,allowedLevels:["global","tenant","user"]};}label(t){return this.flag.label=t,this}description(t){return this.flag.description=t,this}category(t){return this.flag.category=t,this}system(){return this.flag.system=true,this}tenantScoped(){return this.flag.allowedLevels=["global","tenant"],this}globalOnly(){return this.flag.allowedLevels=["global"],this}allowedLevels(t){return this.flag.allowedLevels=[...t],this}build(){if(!this.flag.label?.trim())throw new Error(`Flag "${this.flag.name}" must have a label. Use .label("Human-readable label").`);return {...this.flag,allowedLevels:[...this.flag.allowedLevels||[]]}}};a(zr,"BaseFlagBuilder");var ot=zr,Wr=class Wr extends ot{constructor(t){super(t,"boolean",false);}defaultValue(t){return this.flag.defaultValue=t,this}enabledByDefault(){return this.flag.defaultValue=true,this}};a(Wr,"BooleanFlagBuilder");var Lr=Wr,Gr=class Gr extends ot{constructor(t){super(t,"string","");}defaultValue(t){return this.flag.defaultValue=t,this}};a(Gr,"StringFlagBuilder");var $r=Gr,Kr=class Kr extends ot{constructor(t){super(t,"number",0);}defaultValue(t){return this.flag.defaultValue=t,this}};a(Kr,"NumberFlagBuilder");var Ur=Kr,Yr=class Yr extends ot{constructor(t,n){super(t,"json",n);}defaultValue(t){return this.flag.defaultValue=t,this}};a(Yr,"JsonFlagBuilder");var qr=Yr;function zu(e){return new Lr(e)}a(zu,"booleanFlag");function Wu(e){return new $r(e)}a(Wu,"stringFlag");function Gu(e){return new Ur(e)}a(Gu,"numberFlag");function Ku(e,t){return new qr(e,t)}a(Ku,"jsonFlag");function Hr(e){return new r("feature flag",e,`Flag "${e}" is already registered. Each flag name must be unique.`)}a(Hr,"duplicateFlagError");function Jr(e){return {...e,allowedLevels:[...e.allowedLevels]}}a(Jr,"cloneFlagDefinition");var Qr=class Qr{constructor(){this.flags=new Map;}register(t){if(this.flags.has(t.name))throw Hr(t.name);this.flags.set(t.name,Jr(t));}registerAll(t){let n=new Set;for(let r of t){if(this.flags.has(r.name)||n.has(r.name))throw Hr(r.name);n.add(r.name);}for(let r of t)this.register(r);}get(t){let n=this.flags.get(t);return n?Jr(n):void 0}getOrThrow(t){let n=this.get(t);if(!n)throw new c$3("Feature flag",t,void 0,`Flag "${t}" is not registered. Available flags: ${this.listNames().join(", ")}`);return n}has(t){return this.flags.has(t)}list(){return Array.from(this.flags.values(),Jr)}listNames(){return Array.from(this.flags.keys())}unregister(t){return this.flags.delete(t)}clear(){this.flags.clear();}get size(){return this.flags.size}};a(Qr,"FlagRegistry");var vt=Qr,Yu=new vt;function Hu(){return new vt}a(Hu,"createFlagRegistry");function sn(){return {global:new Map,tenant:new Map,user:new Map}}a(sn,"emptyOverrides");function Ju(e,t){return e.expiresAt===void 0||e.expiresAt.getTime()>t}a(Ju,"isActiveOverride");function Xr(e,t){let n=new Map;for(let r of e){if(!Ju(r,t))continue;let o=r.flagName;n.has(o)||n.set(o,r);}return n}a(Xr,"indexOverrides");var Zr=class Zr{constructor(t){this.repository=t.repository,this.registry=t.registry,this.staticDefaults=new Map(t.staticDefaults?.map(n=>[n.name,n.value])??[]);}async resolveAll(t={}){let n=this.collectFlagNames(),r=this.repository&&n.size>0?await this.getAllOverrides(t,[...n]):sn();return this.resolveNames(n,r,t)}resolveAllStatic(){return this.resolveNames(this.collectFlagNames(),sn(),{})}collectFlagNames(){let t=new Set;for(let n of this.registry.listNames())t.add(n);for(let n of this.staticDefaults.keys())t.add(n);return t}resolveNames(t,n,r){let o=new Map;for(let a of t)o.set(a,this.resolveValue(a,n,r));return o}async resolve(t,n={}){let r=this.repository?await this.getAllOverrides(n,[t]):sn();return this.resolveWithSource(t,r,n)}async isEnabled(t,n={}){return (await this.resolve(t,n)).value===true}async getValue(t,n={}){return (await this.resolve(t,n)).value}async setOverride(t,n,r,o={}){if(!this.repository)throw new b("Cannot set override: no FeatureFlagsRepository configured. Add featureFlags to your DatabaseAdapter to enable runtime overrides.",a$2.CONFIGURATION_REQUIRED);let a=this.registry.get(t);if(a&&!a.allowedLevels.includes(n)){let s=`Flag "${t}" does not allow ${n}-level overrides. Allowed levels: ${a.allowedLevels.join(", ")}`;throw new h(s,[{path:["level"],message:s}])}if(a?.system){let s=`Flag "${t}" is a system flag and cannot be overridden via API.`;throw new h(s,[{path:["flagName"],message:s}])}await this.repository.setOverride({flagName:t,level:n,value:r,targetId:o.targetId,expiresAt:o.expiresAt,createdBy:o.createdBy});}async deleteOverride(t,n,r){if(!this.repository)throw new b("Cannot delete override: no FeatureFlagsRepository configured.",a$2.CONFIGURATION_REQUIRED);await this.repository.deleteOverride(t,n,r);}async getAllOverrides(t,n){if(!this.repository)return sn();let[r,o,a]=await Promise.all([this.repository.getOverrides({level:"global",flagNames:n}),t.tenantId?this.repository.getOverrides({level:"tenant",targetId:t.tenantId,flagNames:n}):Promise.resolve([]),t.userId?this.repository.getOverrides({level:"user",targetId:t.userId,flagNames:n}):Promise.resolve([])]),s=Date.now();return {global:Xr(r,s),tenant:Xr(o,s),user:Xr(a,s)}}resolveValue(t,n,r){return this.resolveWithSource(t,n,r).value}resolveWithSource(t,n,r){let o=this.registry.get(t),a=o?.allowedLevels??["global","tenant","user"];if(r.userId&&a.includes("user")){let s=n.user.get(t);if(s)return {name:t,value:s.value,source:"user",sourceId:r.userId}}if(r.tenantId&&a.includes("tenant")){let s=n.tenant.get(t);if(s)return {name:t,value:s.value,source:"tenant",sourceId:r.tenantId}}if(a.includes("global")){let s=n.global.get(t);if(s)return {name:t,value:s.value,source:"global"}}return this.staticDefaults.has(t)?{name:t,value:this.staticDefaults.get(t),source:"default"}:{name:t,value:o?.defaultValue??void 0,source:"default"}}};a(Zr,"FlagService");var cn=Zr;function Qu(e){return new cn(e)}a(Qu,"createFlagService");var na=Symbol("stndrds.native-object");function ti(e){return Object.defineProperty(e,na,{value:true,enumerable:false}),e}a(ti,"markNativeDefinition");var ri=class ri extends It{build(){return ti(super.build())}};a(ri,"NativeObjectBuilder");var ei=ri;function ye(e){return new ei(e)}a(ye,"nativeObject");function ni(e){return e[na]===true}a(ni,"isNativeDefinition");function ii(e){let t=structuredClone(e);return ni(e)?ti(t):t}a(ii,"cloneObjectDefinition");var ai=class ai{constructor(){this.objects=new Map;}register(t){let r$1=(Array.isArray(t)?t:[t]).map(a=>"build"in a&&typeof a.build=="function"?a.build():a),o=new Set;for(let a of r$1){if(this.validate(a),o.has(a.name))throw new r("object",a.name,`[NativeObjectRegistry] Duplicate object name "${a.name}" within a single register() batch.`);o.add(a.name);}for(let a of r$1)this.objects.set(a.name,ii(a));return this}validate(t){if(!t.system){let n=`[NativeObjectRegistry] Cannot register object "${t.name}" (id: ${t.id}): missing system flag.
|
|
14
|
+
Native objects must have system=true. Did you call .runtime() on the builder? Remove that call \u2014 objects are system:true by default.`;throw new h(n,[])}if(w$1(t.name)&&!ni(t))throw new s(t.name,"registry");if(this.objects.has(t.name)){let n=this.objects.get(t.name),r$1=`[NativeObjectRegistry] Duplicate object name "${t.name}":
|
|
15
15
|
- Existing: "${n?.label}" (id: ${n?.id})
|
|
16
16
|
- New: "${t.label}" (id: ${t.id})
|
|
17
|
-
Please use unique names for each native object.`;throw new r
|
|
18
|
-
Available objects: ${this.listNames().join(", ")}`;throw new c$
|
|
19
|
-
`)}debug(t){let n=this.summary();return t?.(n),n}};a(
|
|
17
|
+
Please use unique names for each native object.`;throw new r("object",t.name,r$1)}}getByName(t){let n=this.objects.get(t);return n?ii(n):void 0}getByNameOrThrow(t){let n=this.getByName(t);if(!n){let r=`[NativeObjectRegistry] Native object "${t}" not found.
|
|
18
|
+
Available objects: ${this.listNames().join(", ")}`;throw new c$3("Native object",t,a$2.OBJECT_NOT_FOUND,r)}return n}getAll(){return Array.from(this.objects.values(),ii)}listNames(){return Array.from(this.objects.keys())}has(t){return this.objects.has(t)}get size(){return this.objects.size}clear(){this.objects.clear();}summary(){let t=this.getAll();return [`[NativeObjectRegistry] ${this.size} native object(s) registered:`,...t.map(n=>` - ${n.name}: "${n.label}" (${n.attributes.length} attributes)`)].join(`
|
|
19
|
+
`)}debug(t){let n=this.summary();return t?.(n),n}};a(ai,"NativeObjectRegistryClass");var oi=ai,uT=new oi;var ra=new WeakSet;function W(e){return ra.add(e.definition),e}a(W,"markSystemView");function ia(e){return typeof e=="object"&&e!==null&&ra.has(e)}a(ia,"isSystemViewDefinition");var oa=`## Overview
|
|
20
20
|
|
|
21
21
|
Describe in one or two sentences what this skill does and the outcome it produces. The agent reads this page when it uses the skill \u2014 write instructions for the agent, not documentation for people.
|
|
22
22
|
|
|
@@ -47,15 +47,15 @@ Show at least one concrete example of the skill applied well.
|
|
|
47
47
|
|
|
48
48
|
- Never \u2026
|
|
49
49
|
- Do not \u2026
|
|
50
|
-
`,
|
|
50
|
+
`,el=ye({name:"skill",label:"Skill"}).sealed().icon("book-open").order(Number.MAX_SAFE_INTEGER).pluralLabel("Skills").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
|
|
51
51
|
{{ description }}
|
|
52
|
-
{{ content }}`).attribute(w({name:"name",label:"Name"}).maxLength(SKILL_NAME_MAX_LENGTH).required()).attribute(w({name:"description",label:"Description"}).multiline().maxLength(SKILL_DESCRIPTION_MAX_LENGTH).required().placeholder('What this skill does and when to use it \u2014 e.g. "Drafts replies to customer complaints. Use when asked to answer an unhappy customer."')).attribute(
|
|
52
|
+
{{ content }}`).attribute(w({name:"name",label:"Name"}).maxLength(SKILL_NAME_MAX_LENGTH).required()).attribute(w({name:"description",label:"Description"}).multiline().maxLength(SKILL_DESCRIPTION_MAX_LENGTH).required().placeholder('What this skill does and when to use it \u2014 e.g. "Drafts replies to customer complaints. Use when asked to answer an unhappy customer."')).attribute(De({name:"content",label:"Content"}).defaultValue(oa)).build(),tl=W(fe("skill-detail","Skill").for("skill").default().tab("content","Content",N.richtext("content").titleAttribute("name")).tab("files","Files",N.documents()).tab("activity","Activity",N.activity()).aside("details","Details",N.form(ge("details","Details").fields("name","description"))).build()),nl=W(be("skill-list","Skills").for("skill").default().tab("workspace","Skills",N.collection().object("skill").list().icon("list").visibility("workspace").columns("name","description").descriptionAttribute("description").displayAttributes("createdBy","updatedAt").sort("name")).tab("mine","My skills",N.collection().object("skill").list().icon("lock").visibility("private").columns("name","description").descriptionAttribute("description").displayAttributes("createdBy","updatedAt").sort("name")).build());var ol=ye({name:"memory",label:"Memory"}).sealed().icon("database").order(Number.MAX_SAFE_INTEGER).pluralLabel("Memories").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
|
|
53
53
|
{{ description }}
|
|
54
|
-
{{ content }}`).migration(2,e=>e.changeType("content","text","richtext")).attribute(w({name:"name",label:"Name"}).maxLength(MEMORY_NAME_MAX_LENGTH).required()).attribute(w({name:"description",label:"Description"}).multiline().maxLength(MEMORY_DESCRIPTION_MAX_LENGTH).required()).attribute(
|
|
55
|
-
{{ description }}`).attribute(w({name:"name",label:"Name"}).required()).attribute(w({name:"description",label:"Description"}).multiline()).build(),
|
|
56
|
-
{{ description }}`).attribute(w({name:"name",label:"Name"}).required()).attribute(w({name:"description",label:"Description"}).multiline()).attribute(
|
|
54
|
+
{{ content }}`).migration(2,e=>e.changeType("content","text","richtext")).attribute(w({name:"name",label:"Name"}).maxLength(MEMORY_NAME_MAX_LENGTH).required()).attribute(w({name:"description",label:"Description"}).multiline().maxLength(MEMORY_DESCRIPTION_MAX_LENGTH).required()).attribute(De({name:"content",label:"Content"})).attribute(pe({name:"kind",label:"Kind"}).options([{value:"fact",label:"Fact"},{value:"preference",label:"Preference"},{value:"feedback",label:"Feedback"},{value:"reference",label:"Reference"}])).attribute(rt({name:"subjects",label:"Subjects"}).toAny().many()).attribute(rt({name:"links",label:"Links"}).to("memory").many()).attribute(pe({name:"source",label:"Source"}).options([{value:"explicit",label:"Saved by an agent"},{value:"extracted",label:"Extracted from a session"},{value:"corroborated",label:"Corroborated across users"},{value:"curated",label:"Curated by Dreamer"}])).attribute(oe({name:"validFrom",label:"Valid from"}).includeTime()).attribute(oe({name:"invalidAt",label:"Invalid at"}).includeTime()).attribute(rt({name:"supersededBy",label:"Superseded by"}).to("memory")).attribute(w({name:"provenance",label:"Provenance"}).multiline()).attribute(pe({name:"reviewState",label:"Review state"}).options([{value:"needs_review",label:"Needs review"},{value:"skill_candidate",label:"Skill candidate"}])).attribute(w({name:"reviewReason",label:"Review reason"}).multiline()).attribute(oe({name:"curatedAt",label:"Curated at"}).includeTime()).attribute(oe({name:"reviewAfter",label:"Review after"}).includeTime()).attribute(w({name:"curationFingerprint",label:"Curation fingerprint"})).build(),aa={combinator:"and",rules:[{attribute:"invalidAt",operator:"is_empty",value:null},{attribute:"reviewState",operator:"is_empty",value:null}]},al=W(fe("memory-detail","Memory").for("memory").default().tab("content","Content",N.richtext("content").titleAttribute("name")).aside("details","Details",N.form(ge("details","Details").fields("description","kind","source","provenance","reviewState","reviewReason","validFrom","invalidAt","supersededBy","curatedAt","reviewAfter","subjects","links"))).build()),sl=W(be("memory-list","Memories").for("memory").default().tab("workspace","Memories",N.collection().object("memory").list().icon("list").visibility("workspace").columns("name","kind","description","createdAt").descriptionAttribute("description").displayAttributes("kind","subjects","createdAt").filter(aa).sort("name")).tab("mine","My memories",N.collection().object("memory").list().icon("lock").visibility("private").columns("name","kind","description","createdAt").descriptionAttribute("description").displayAttributes("kind","subjects","createdAt").filter(aa).sort("name")).tab("review","To review",N.collection().object("memory").table().icon("question-circle").columns("name","reviewState","reviewReason","updatedAt").filter({combinator:"and",rules:[{attribute:"invalidAt",operator:"is_empty",value:null},{attribute:"reviewState",operator:"is_not_empty",value:null}]}).sort("updatedAt","desc")).tab("history","History",N.collection().object("memory").table().icon("archive").columns("name","kind","invalidAt","supersededBy").filter({combinator:"and",rules:[{attribute:"invalidAt",operator:"is_not_empty",value:null}]}).sort("invalidAt","desc")).build());var at="drives",cl=ye({name:at,label:"Drive"}).sealed().icon("folder").hidden().pluralLabel("Drives").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
|
|
55
|
+
{{ description }}`).attribute(w({name:"name",label:"Name"}).required()).attribute(w({name:"description",label:"Description"}).multiline()).build(),ul=W(fe("drive-detail","Drive").for(at).default().tab("documents","Documents",N.documents()).aside("details","Details",N.form(ge("details","Details").field("description"))).build()),ll=W(be("drive-list","Drives").for(at).default().tab("workspace","Shared",N.collection().object(at).table().icon("users").visibility("workspace").columns("name","description","updatedAt").sort("name")).tab("mine","My drives",N.collection().object(at).table().icon("lock").visibility("private").columns("name","description","updatedAt").sort("name")).build());var st="artifact",pl=ye({name:st,label:"Artifact"}).sealed().icon("package").pluralLabel("Artifacts").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
|
|
56
|
+
{{ description }}`).attribute(w({name:"name",label:"Name"}).required()).attribute(w({name:"description",label:"Description"}).multiline()).attribute(pe({name:"kind",label:"Kind"}).options([{value:"web",label:"Web",color:"blue"},{value:"presentation",label:"Presentation",color:"purple"},{value:"document",label:"Document",color:"sky"},{value:"spreadsheet",label:"Spreadsheet",color:"green"},{value:"image",label:"Image",color:"pink"},{value:"code",label:"Code",color:"slate"},{value:"other",label:"Other",color:"gray"}]).required()).attribute(pe({name:"retention",label:"Retention"}).options([{value:"ephemeral",label:"Ephemeral",color:"gray"},{value:"conversation",label:"Conversation",color:"blue"},{value:"persistent",label:"Persistent",color:"green"}]).defaultValue("conversation").required()).attribute(rn({name:"currentRevision",label:"Current revision"}).integer().min(1)).attribute(oe({name:"expiresAt",label:"Expires at"}).includeTime().hidden()).attribute(w({name:"sourceSessionId",label:"Source session"}).hidden()).attribute(w({name:"sourceMessageId",label:"Source message"}).hidden()).attribute(w({name:"initialToolCallId",label:"Initial tool call"}).hidden()).attribute(Xo({name:"versions",label:"Versions"}).qualifyWith(rn({name:"revision",label:"Revision"}).integer().min(1).required(),w({name:"toolCallId",label:"Tool call"}).hidden(),w({name:"sourceFileId",label:"Source file"}).hidden(),w({name:"previewFileId",label:"Preview file"}).hidden(),w({name:"fileIds",label:"File manifest"}).hidden(),w({name:"entrypoint",label:"Entrypoint"}).hidden(),w({name:"sourceMessageId",label:"Source message"}).hidden(),w({name:"artifactName",label:"Artifact name"}).hidden(),w({name:"artifactDescription",label:"Artifact description"}).hidden(),w({name:"artifactKind",label:"Artifact kind"}).hidden(),w({name:"displayMode",label:"Display mode"}).hidden(),w({name:"displayInteraction",label:"Display interaction"}).hidden(),w({name:"displaySize",label:"Display size"}).hidden(),rn({name:"displayAspectRatio",label:"Display aspect ratio"}).hidden())).build(),sa={name:"artifact_preview",requiresRecord:true,parameters:z.object({}).strict()},ml=W(fe("artifact-detail","Artifact").for(st).default().tab("preview","Preview",N.custom(sa,{})).tab("versions","Versions",N.documents().allowUpload(false).allowRemove(false).hideAttachments(true)).tab("activity","Activity",N.activity()).aside("details","Details",N.form(ge("details","Details").field("description",{readOnly:true}).field("kind",{readOnly:true}).field("retention",{readOnly:true}).field("currentRevision",{readOnly:true}).field("createdBy",{readOnly:true}).field("updatedAt",{readOnly:true}))).build()),fl=W(be("artifact-list","Artifacts").for(st).default().tab("mine","My artifacts",N.collection().object(st).list().icon("lock").visibility("private").actions().columns("name","kind","currentRevision","updatedAt").descriptionAttribute("description").displayAttributes("kind","currentRevision","updatedAt").sort("updatedAt","desc")).tab("workspace","Workspace",N.collection().object(st).list().icon("list").visibility("workspace").actions().columns("name","kind","currentRevision","updatedAt").descriptionAttribute("description").displayAttributes("kind","currentRevision","updatedAt").sort("updatedAt","desc")).build());var ct="meeting",C={title:"title",description:"description",location:"location",startsAt:"startsAt",endsAt:"endsAt",isAllDay:"isAllDay",status:"status",organizerAddress:"organizerAddress",organizerName:"organizerName",conferenceProvider:"conferenceProvider",conferenceJoinUrl:"conferenceJoinUrl",htmlLink:"htmlLink",participants:"participants",providerEventId:"providerEventId",icalUid:"icalUid",recurringEventId:"recurringEventId",connectionId:"connectionId",recordingOverride:"recordingOverride",endedAnnouncedAt:"endedAnnouncedAt",summary:"summary",transcript:"transcript",linkedRecords:"linkedRecords"},ua="meeting-list",la="calendar-sync",da="meeting-detail",ca=[C.title,C.startsAt,C.endsAt,C.status],bl=ye({name:ct,label:"Meeting"}).sealed().hidden().metadata({platformOwned:{editable:[C.linkedRecords],source:la}}).icon("calendar").pluralLabel("Meetings").labelExpression("{{ title }}").embeddingExpression(`{{ title }}
|
|
57
57
|
{{ description }}
|
|
58
58
|
{{ participants }}
|
|
59
|
-
{{ summary }}`).attribute(w({name:C.title,label:"Title"}).required()).attribute(
|
|
60
|
-
Available views: ${a}`)}getAll(){return Array.from(this.views.values()).flatMap(t=>Array.from(t.values(),
|
|
61
|
-
`)}debug(t){let n=this.summary();return t?.(n),n}throwDuplicate(t,n){let r=li(t,n);throw new r$1("view",r,`[ViewRegistry] Duplicate view: "${n}" for object "${t}"`)}};a(pi,"ViewRegistry");var di=pi,jl=new di;function Ca(e,t){if(t.suppressed)return null;let n=t.workspaceDefinition??t.sourceDefinition;return n===null?null:{...structuredClone(n),name:e}}a(Ca,"contentDefinition");function Ct(e){let{name:t,...n}=e;return structuredClone(n)}a(Ct,"storedContentDefinition");function Et(e){let t={main:0,aside:0};return {origin:"runtime",mainOrderCustomized:false,asideOrderCustomized:false,contents:Object.fromEntries(e.map(n=>[n.name,{sourceDefinition:null,workspaceDefinition:Ct(n),suppressed:false,sourcePosition:null,workspacePosition:t[n.placement]++}]))}}a(Et,"workspaceViewAuthoring");function mi(e){let t=Object.entries(e.contents).flatMap(([n,r])=>{let o=Ca(n,r);return o?[{definition:o,...r}]:[]});return ["main","aside"].flatMap(n=>{let r=n==="main"?e.mainOrderCustomized:e.asideOrderCustomized;return t.filter(o=>o.definition.placement===n).sort((o,a)=>{let s=r?o.workspacePosition:o.sourcePosition,c=r?a.workspacePosition:a.sourcePosition;if(s!==null&&c!==null&&s!==c)return s-c;if(s!==null&&c===null)return -1;if(c!==null&&s===null)return 1;let u=o.sourcePosition??o.workspacePosition,m=a.sourcePosition??a.workspacePosition;return u!==null&&m!==null&&u!==m?u-m:u!==null&&m===null?-1:m!==null&&u===null?1:o.definition.name.localeCompare(a.definition.name)}).map(o=>o.definition)})}a(mi,"resolveViewContents");function bi(e,t){throw new h(t,[{path:e,message:t}])}a(bi,"reject");function fi(e,t){e.trim().length===0&&bi(t,"API name must not be empty");}a(fi,"requireName");function Nt(e){let t=new Map;e.objects.forEach((s,c)=>{if(fi(s.name,["objects",String(c),"name"]),t.has(s.name))throw new r$1("object",s.name);let u=new Set;s.attributes.forEach((m,d)=>{if(fi(m.name,["objects",String(c),"attributes",String(d),"name"]),u.has(m.name))throw new r$1("attribute",m.name);u.add(m.name);}),t.set(s.name,u);});let n=new Set;(e.reservedObjects??[]).forEach((s,c)=>{let u=["reservedObjects",String(c)];fi(s,u),t.has(s)||(e.mode!=="draft"&&bi(u,`Unresolved reserved object "${s}"`),n.add(s));});let r=e.relations.map((s,c)=>Qe(s,["relations",String(c)])),o=new Set,a=new Map;return r.forEach((s,c)=>{if(o.has(s.name))throw new r$1("relation",s.name);o.add(s.name);for(let u of [0,1]){let m=s.endpoints[u],d=t.get(m.object);d||n.has(m.object)||bi(["relations",String(c),"endpoints",String(u),"object"],`Unknown object "${m.object}"`);let f=a.get(m.object);if(f||(f=new Map,a.set(m.object,f)),d?.has(m.name)||f.has(m.name))throw new r$1("attribute",m.name);f.set(m.name,{relation:s,slot:u,target:s.endpoints[u===0?1:0].object});}}),{relations:r,unresolvedObjects:[...n].sort(),resolveEndpoint(s,c){return a.get(s)?.get(c)}}}a(Nt,"createStructuredRelationCatalogue");var _l=new Map(d$1().map(e=>[e.name,e]));function Ae(e,t){throw new h(t,[{path:e,message:t}])}a(Ae,"reject");function it(e,t){e.trim().length===0&&Ae(t,"API name must not be empty");}a(it,"requireName");function Pl(e,t,n){let r=new Map;return e.forEach((o,a)=>{if(it(o.name,[...n,String(a),"name"]),r.has(o.name))throw new r$1(t,o.name);r.set(o.name,o);}),r}a(Pl,"indexUnique");function Z(e,t,n,r){if(it(t,n),!e)return;let o=e.attributes?.get(t)??_l.get(t)??e.resolveEndpoint(t);if(!o){if(!e.attributes)return;Ae(n,`Unknown attribute "${e.name}.${t}"`);}return r&&("slot"in o?r!=="relation":o.type!==r)&&Ae(n,`Attribute "${e.name}.${t}" must have type ${r}`),o}a(Z,"requireAttribute");function gi(e){let t=e.mode??"published",n=Nt({objects:e.objects,relations:e.relations??[],reservedObjects:e.reservedObjects,mode:t}),r=new Map;e.objects.forEach(d=>{r.set(d.name,{name:d.name,attributes:new Map(d.attributes.map(f=>[f.name,f])),resolveEndpoint(f){return n.resolveEndpoint(d.name,f)}});}),n.unresolvedObjects.forEach(d=>{r.set(d,{name:d,resolveEndpoint(f){return n.resolveEndpoint(d,f)}});});let o=Pl(e.extensions??[],"extension",["extensions"]);function a$1(d,f){it(d,f);let g=r.get(d);return g||Ae(f,`Unknown object "${d}"`),g}a(a$1,"resolveObject");let s=t==="draft"?da$1:ea$1,c=new Map,u=new Map;return {views:e.views.map((d,f)=>{let g=["views",String(f)],N=s.safeParse(d);if(!N.success)throw new h("Invalid content view",N.error.issues.map(S=>({path:[...g,...S.path.map(String)],message:S.message,code:S.code})));let h$1=N.data;it(h$1.name,[...g,"name"]);let y=a$1(h$1.object,[...g,"object"]),A=c.get(h$1.object)??new Set;if(A.has(h$1.name))throw new r$1("view",`${h$1.object}.${h$1.name}`);if(A.add(h$1.name),c.set(h$1.object,A),h$1.default){let S=u.get(h$1.object)??new Set;if(S.has(h$1.context))throw new r$1("default view",`${h$1.object}.${h$1.context}`);S.add(h$1.context),u.set(h$1.object,S);}return h$1.contents.forEach((S,M)=>{let F=[...g,"contents",String(M)];it(S.name,[...F,"name"]),Ml(S,F,y,h$1.context,o,a$1);}),h$1}),unresolvedObjects:n.unresolvedObjects}}a(gi,"validateContentViewCatalogue");function Ml(e,t,n,r,o,a$1){function s(){It(e.name,r,t);}if(a(s,"requireRecord"),e.type==="custom"){let c=o.get(e.extension);c||Ae([...t,"extension"],`Unknown extension "${e.extension}"`),c.requiresRecord&&s();let u=c.parameters.safeParse(structuredClone(e.parameters??{}));if(!u.success)throw new h("Invalid extension parameters",u.error.issues.map(m=>({path:[...t,"parameters",...m.path.map(String)],message:m.message,code:m.code})));return}if(e.type==="collection"){let c,u;if(e.source.object!==void 0)c=a$1(e.source.object,[...t,"source","object"]);else {s();let m=[...t,"source","relation"],d=Z(n,e.source.relation,m,"relation");d&&"slot"in d?(u=d,c=a$1(d.target,m)):d?.type==="relation"&&((d.targets.length!==1||d.targets[0].object==="*")&&Ae(m,`Relation "${d.name}" requires one concrete collection target`),c=a$1(d.targets[0].object,m));}e.columns?.forEach((m,d)=>{let f=[...t,"columns",String(d)];if(typeof m=="string"){Z(c,m,f);return}let g=[...f,"relationProperty"];u||Ae(g,"Relation property columns require a relation source"),u.relation.properties?.definitions.some(N=>N.name===m.relationProperty)||Ae(g,`Unknown relation property "${m.relationProperty}"`);}),e.displayAttributes?.forEach((m,d)=>Z(c,m,[...t,"displayAttributes",String(d)])),e.sorts?.forEach((m,d)=>Z(c,m.attribute,[...t,"sorts",String(d),"attribute"])),e.filters?.rules.forEach((m,d)=>Z(c,m.attribute,[...t,"filters","rules",String(d),"attribute"])),e.descriptionAttribute!==void 0&&Z(c,e.descriptionAttribute,[...t,"descriptionAttribute"]),e.layout==="kanban"&&Z(c,e.groupByAttribute,[...t,"groupByAttribute"]);return}switch(s(),e.type){case "form":e.groups.forEach((c,u)=>{let m=[...t,"groups",String(u)];it(c.name,[...m,"name"]),c.fields.forEach((d,f)=>Z(n,d.attribute,[...m,"fields",String(f),"attribute"]));});break;case "richtext":Z(n,e.attribute,[...t,"attribute"],"richtext"),e.titleAttribute!==void 0&&Z(n,e.titleAttribute,[...t,"titleAttribute"],"text");break;case "emails":case "meetings":e.emailAttributes.forEach((c,u)=>Z(n,c,[...t,"emailAttributes",String(u)],"text"));break;case "documents":e.relations?.forEach((c,u)=>Z(n,c,[...t,"relations",String(u)],"relation"));break;case "forms":e.objectName!==void 0&&a$1(e.objectName,[...t,"objectName"]);break;case "activity":break;default:Ae(t,`Unknown content type: ${String(e)}`);}}a(Ml,"validateContent");function yi(e){return structuredClone(e)}a(yi,"cloneFormDefinition");var hi=class hi{constructor(){this.forms=new Map;}register(t){let n=Array.isArray(t)?t:[t];for(let r of n){if(this.forms.has(r.name))throw new r$1("form",r.name,`[FormRegistry] Duplicate form: "${r.name}"`);this.forms.set(r.name,yi(r));}return this}get(t){let n=this.forms.get(t);return n?yi(n):void 0}getAll(){return Array.from(this.forms.values(),yi)}listNames(){return Array.from(this.forms.keys())}};a(hi,"FormRegistry");var Dt=hi;var Ea=new Dt;function zw(e,t){return `${e}:${t}`}a(zw,"formatAgentStreamFrameId");function Ww(e){let t=e.lastIndexOf(":");if(t<=0)return null;let n=e.slice(0,t),r=Number(e.slice(t+1));return !Number.isInteger(r)||r<=0?null:{streamId:n,sequence:r}}a(Ww,"parseAgentStreamFrameId");var Yw=204800,Hw=256;function xi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(xi,"isRecord");function Ti(e,t){let n=Object.keys(e);return n.length===t.length&&n.every(r=>t.includes(r))}a(Ti,"hasExactKeys");function Ai(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}a(Ai,"isPositiveInteger");function Na(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}a(Na,"isNonNegativeInteger");function Fl(e){return xi(e)&&Ti(e,["kind","startOffset","endOffset"])?(e.kind==="text"||e.kind==="reasoning")&&Na(e.startOffset)&&Na(e.endOffset)&&e.endOffset>=e.startOffset:false}a(Fl,"isContentRange");function Vl(e){if(!xi(e))return false;let t=e.content===void 0?["sequence","chunk"]:["sequence","content","chunk"];return Ti(e,t)&&Ai(e.sequence)&&e.chunk!==void 0&&(e.content===void 0||Fl(e.content))}a(Vl,"isBatchItem");function Bl(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return}}a(Bl,"encodedSize");function Jw(e){if(!(xi(e)&&Ti(e,["schemaVersion","batchId","tenantId","sessionId","streamId","sequenceStart","sequenceEnd","items"]))||e.schemaVersion!==1||typeof e.batchId!="string"||e.batchId.trim()===""||typeof e.tenantId!="string"||e.tenantId.trim()===""||typeof e.sessionId!="string"||e.sessionId.trim()===""||typeof e.streamId!="string"||e.streamId.trim()===""||!Ai(e.sequenceStart)||!Ai(e.sequenceEnd)||!Array.isArray(e.items)||e.items.length===0||e.items.length>256||!e.items.every(Vl))return false;let t=0;for(let r of e.items){if(r.sequence<=t)return false;t=r.sequence;}if(e.items[0]?.sequence!==e.sequenceStart||e.items.at(-1)?.sequence!==e.sequenceEnd)return false;let n=Bl(e);return n!==void 0&&n<=204800}a(Jw,"isAgentUIMessageBatch");function Da(e){switch(e.kind){case "workspace":return `workspace:${encodeURIComponent(e.tenantId)}`;case "object":return `object:${encodeURIComponent(e.objectId)}`;case "record":return `record:${encodeURIComponent(e.objectId)}:${encodeURIComponent(e.recordId)}`;case "view":return `view:${encodeURIComponent(e.viewId)}`;case "user":return `user:${encodeURIComponent(e.actorId)}`;case "conversation":return `conversation:${encodeURIComponent(e.sessionId)}`;case "architect-draft":return e.scope==="actor"?`architect-draft:actor:${encodeURIComponent(e.actorId)}`:`architect-draft:session:${encodeURIComponent(e.sessionId)}`}}a(Da,"liveChannelKey");function Zw(e){return e.sessionId?Da({kind:"architect-draft",scope:"session",sessionId:e.sessionId}):e.actorId?Da({kind:"architect-draft",scope:"actor",actorId:e.actorId}):null}a(Zw,"architectDraftChannelKey");function Ce(e){try{return decodeURIComponent(e)}catch{return null}}a(Ce,"decodeLiveChannelPart");function Oa(e){let t=e.split(":");if(t[0]==="workspace"&&t.length===2&&t[1]){let n=Ce(t[1]);return n?{kind:"workspace",tenantId:n}:null}if(t[0]==="object"&&t.length===2&&t[1]){let n=Ce(t[1]);return n?{kind:"object",objectId:n}:null}if(t[0]==="record"&&t.length===3&&t[1]&&t[2]){let n=Ce(t[1]),r=Ce(t[2]);return n&&r?{kind:"record",objectId:n,recordId:r}:null}if(t[0]==="view"&&t.length===2&&t[1]){let n=Ce(t[1]);return n?{kind:"view",viewId:n}:null}if(t[0]==="user"&&t.length===2&&t[1]){let n=Ce(t[1]);return n?{kind:"user",actorId:n}:null}if(t[0]==="architect-draft"&&t.length===3&&t[2]){let n=Ce(t[2]);return n?t[1]==="actor"?{kind:"architect-draft",scope:"actor",actorId:n}:t[1]==="session"?{kind:"architect-draft",scope:"session",sessionId:n}:null:null}if(t[0]==="conversation"&&t.length===2&&t[1]){let n=Ce(t[1]);return n?{kind:"conversation",sessionId:n}:null}return null}a(Oa,"parseLiveChannelKey");var Ll={"record.patch":true,"relation.endpoint.changed":true,"record.deleted":true,"record.removed":true,"record.created":true,"view.projection.stale":true,"agent.session.patch":true,"notification.created":true,"notification.recipient.patch":true,"notification.count.patch":true,"notification.inbox.archived":true,"reflex.state.changed":true,"reflex.run.completed":true,"reflex.authoring.progress":true,"architect.draft.updated":true,"meeting.recording.patch":true,"wallet.state":true,"channel.revoked":true},Ul=Object.keys(Ll),$l=["membership-unknown","sort-unknown","permissions-changed"],ql=["permission-revoked","workspace-left","object-deleted"],zl=["inboxState","workState","lockedAt","lockedByActorId","readAt","archivedAt","snoozedUntil","completedAt","dismissedAt","updatedAt"],Wl=["type","objectId","recordId","recordVersion"],Gl=["type","objectId","recordId","recordVersion","record"],Kl=["id","objectId","visibility","ownedBy","label","values","metadata","createdAt","updatedAt","createdBy","lastUpdatedBy","schemaVersion"],Yl=["type","targetActorId","archivedCount","version","updatedAt"];function Hl(e){return typeof e=="string"&&Ul.includes(e)}a(Hl,"isLiveEventType");function rS(e){return U(e)&&Hl(e.type)?Jl(e.type,e):false}a(rS,"isLiveEventPayload");function Jl(e,t){if(!U(t))return false;switch(e){case "record.patch":return rd(t);case "relation.endpoint.changed":return t.type==="relation.endpoint.changed"&&D(t,"objectId")&&D(t,"objectName")&&D(t,"recordId")&&D(t,"endpoint")&&L(t,"writeVersion")&&kt(t,["type","objectId","objectName","recordId","endpoint","writeVersion"]);case "record.deleted":return id(t);case "record.removed":return od(t);case "record.created":return sd(t);case "view.projection.stale":return cd(t);case "agent.session.patch":return ud(t);case "notification.created":return md(t);case "notification.recipient.patch":return fd(t);case "notification.count.patch":return bd(t);case "notification.inbox.archived":return gd(t);case "reflex.state.changed":return wd(t);case "reflex.run.completed":return Sd(t);case "reflex.authoring.progress":return Id(t);case "architect.draft.updated":return xd(t);case "meeting.recording.patch":return vd(t);case "wallet.state":return Nd(t);case "channel.revoked":return Dd(t);default:return false}}a(Jl,"isLiveEventPayloadForType");function U(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(U,"isRecord");function Y(e){return typeof e=="string"}a(Y,"isString");function Ot(e){return Y(e)&&e.length>0}a(Ot,"isNonEmptyString");function wi(e){return e===null||Y(e)}a(wi,"isNullableString");function Ql(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}a(Ql,"isVersion");function fe(e){if(!Y(e))return false;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}a(fe,"isIsoDateString");function ot(e){return e===null||fe(e)}a(ot,"isNullableIsoDateString");function D(e,t){return Y(e[t])}a(D,"hasString");function ne(e,t){return Ot(e[t])}a(ne,"hasNonEmptyString");function L(e,t){return Ql(e[t])}a(L,"hasVersion");function G(e,t){return fe(e[t])}a(G,"hasIsoDateString");function j(e,t,n){return !Object.hasOwn(e,t)||n(e[t])}a(j,"hasOptional");function kt(e,t){return Object.keys(e).every(n=>t.includes(n))}a(kt,"hasOnlyKeys");function H(e,t){return typeof e=="string"&&t.includes(e)}a(H,"isOneOf");function Xl(e){return H(e,Co)}a(Xl,"isNotificationKind");function Zl(e){return H(e,Eo)}a(Zl,"isNotificationPriority");function ed(e){return H(e,No)}a(ed,"isNotificationSensitivity");function ka(e){return H(e,Do)}a(ka,"isNotificationInboxState");function ja(e){return H(e,Oo)}a(ja,"isNotificationWorkState");function td(e){return U(e)&&D(e,"type")&&D(e,"id")}a(td,"isNotificationSubject");function nd(e){return U(e)&&D(e,"fieldKey")&&Object.hasOwn(e,"value")&&L(e,"version")}a(nd,"isRecordFieldPatch");function rd(e){return e.type==="record.patch"&&D(e,"objectId")&&D(e,"recordId")&&L(e,"recordVersion")&&j(e,"label",Y)&&j(e,"metadata",U)&&j(e,"fieldsWithheld",t=>t===true)&&Array.isArray(e.fieldPatches)&&e.fieldPatches.every(nd)&&D(e,"updatedAt")}a(rd,"isRecordPatchPayload");function id(e){return e.type==="record.deleted"&&D(e,"objectId")&&D(e,"recordId")&&L(e,"recordVersion")&&D(e,"deletedAt")}a(id,"isRecordDeletedPayload");function od(e){return e.type==="record.removed"&&kt(e,Wl)&&D(e,"objectId")&&D(e,"recordId")&&L(e,"recordVersion")}a(od,"isRecordRemovedPayload");function ad(e){return U(e)&&kt(e,Kl)&&D(e,"id")&&D(e,"objectId")&&H(e.visibility,["workspace","private"])&&wi(e.ownedBy)&&(e.visibility==="workspace"&&e.ownedBy===null||e.visibility==="private"&&Ot(e.ownedBy))&&D(e,"label")&&U(e.values)&&j(e,"metadata",U)&&G(e,"createdAt")&&G(e,"updatedAt")&&j(e,"createdBy",Y)&&j(e,"lastUpdatedBy",Y)&&L(e,"schemaVersion")}a(ad,"isRecordLiveSnapshot");function sd(e){return e.type==="record.created"&&kt(e,Gl)&&D(e,"objectId")&&D(e,"recordId")&&L(e,"recordVersion")&&ad(e.record)&&e.record.id===e.recordId&&e.record.objectId===e.objectId}a(sd,"isRecordCreatedPayload");function cd(e){return e.type==="view.projection.stale"&&D(e,"viewId")&&H(e.reason,$l)}a(cd,"isViewProjectionStalePayload");function ud(e){return e.type==="agent.session.patch"&&D(e,"sessionId")&&U(e.patch)&&L(e,"version")&&D(e,"updatedAt")}a(ud,"isAgentSessionPatchPayload");function ld(e){return U(e)&&D(e,"id")&&D(e,"tenantId")&&j(e,"senderActorId",Y)&&j(e,"rootActorId",Y)&&j(e,"triggeredByActorId",Y)&&Xl(e.kind)&&D(e,"type")&&j(e,"subject",td)&&D(e,"title")&&j(e,"summary",Y)&&U(e.payload)&&Zl(e.priority)&&ed(e.sensitivity)&&j(e,"threadKey",Y)&&j(e,"idempotencyKey",Y)&&j(e,"expiresAt",fe)&&G(e,"createdAt")&&G(e,"updatedAt")}a(ld,"isLiveNotification");function dd(e){return U(e)&&D(e,"id")&&D(e,"tenantId")&&D(e,"notificationId")&&D(e,"recipientActorId")&&ka(e.inboxState)&&ja(e.workState)&&j(e,"lockedAt",fe)&&j(e,"lockedByActorId",Y)&&j(e,"readAt",fe)&&j(e,"archivedAt",fe)&&j(e,"snoozedUntil",fe)&&j(e,"completedAt",fe)&&j(e,"dismissedAt",fe)&&G(e,"createdAt")&&G(e,"updatedAt")}a(dd,"isLiveNotificationRecipient");function pd(e){return U(e)?Object.keys(e).every(t=>zl.includes(t))&&j(e,"inboxState",ka)&&j(e,"workState",ja)&&j(e,"lockedAt",ot)&&j(e,"lockedByActorId",wi)&&j(e,"readAt",ot)&&j(e,"archivedAt",ot)&&j(e,"snoozedUntil",ot)&&j(e,"completedAt",ot)&&j(e,"dismissedAt",ot)&&j(e,"updatedAt",fe):false}a(pd,"isNotificationRecipientPatch");function md(e){let t=ld(e.notification)?e.notification:null;return e.type==="notification.created"&&t!==null&&Array.isArray(e.recipients)&&e.recipients.length>0&&e.recipients.every(n=>dd(n)&&n.notificationId===t.id)&&L(e,"version")&&G(e,"updatedAt")}a(md,"isNotificationCreatedPayload");function fd(e){return e.type==="notification.recipient.patch"&&D(e,"recipientId")&&D(e,"recipientActorId")&&pd(e.patch)&&L(e,"version")&&G(e,"updatedAt")}a(fd,"isNotificationRecipientPatchPayload");function bd(e){return e.type==="notification.count.patch"&&D(e,"targetActorId")&&L(e,"unread")&&L(e,"pendingWork")&&L(e,"version")&&G(e,"updatedAt")}a(bd,"isNotificationCountPatchPayload");function gd(e){return e.type==="notification.inbox.archived"&&kt(e,Yl)&&ne(e,"targetActorId")&&L(e,"archivedCount")&&L(e,"version")&&G(e,"updatedAt")}a(gd,"isNotificationInboxArchivedPayload");var yd=["armed","disarmed"],hd=["authoring","compiling","replaying","promoted","failed"],Ad=["promoted","lkg"];function xd(e){if(e.type!=="architect.draft.updated"||!U(e.receipt))return false;let t=e.receipt;return Array.isArray(t.operationIds)&&t.operationIds.every(Ot)&&U(t.revision)&&ne(t.revision,"draftId")&&L(t.revision,"version")&&Array.isArray(t.changedTargets)&&t.changedTargets.every(n=>U(n)&&Ot(n.token)&&Td(n.target))}a(xd,"isArchitectDraftUpdatedPayload");function Td(e){if(!U(e))return false;let t=Object.keys(e);return t.every(n=>Ot(e[n]))?ne(e,"viewName")?ne(e,"objectName")&&t.every(n=>["objectName","viewName","contentName"].includes(n)):ne(e,"objectName")?t.length===1:ne(e,"objectId")&&t.length<=2&&t.every(n=>["objectId","attributeName","attributeId","recordId"].includes(n)):false}a(Td,"isNamedTarget");function wd(e){return e.type==="reflex.state.changed"&&ne(e,"reflexId")&&H(e.state,yd)&&G(e,"updatedAt")}a(wd,"isReflexStateChangedPayload");function Sd(e){return e.type==="reflex.run.completed"&&ne(e,"reflexId")&&ne(e,"runId")&&H(e.served,Ad)&&L(e,"version")&&L(e,"wallMs")&&G(e,"completedAt")}a(Sd,"isReflexRunCompletedPayload");function Id(e){return e.type==="reflex.authoring.progress"&&ne(e,"reflexId")&&H(e.status,hd)&&G(e,"updatedAt")}a(Id,"isReflexAuthoringProgressPayload");var Rd=["none","scheduled","recording","completed","failed"];function vd(e){return e.type==="meeting.recording.patch"&&ne(e,"meetingId")&&H(e.status,Rd)&&wi(e.failureReason)&&G(e,"updatedAt")}a(vd,"isMeetingRecordingPatchPayload");var Cd=["ok","low","exhausted","paused"],Ed=["metering-only","contract","wallet"];function Nd(e){return e.type==="wallet.state"&&H(e.status,Cd)&&H(e.mode,Ed)&&G(e,"updatedAt")}a(Nd,"isWalletStatePayload");function Dd(e){return e.type==="channel.revoked"&&D(e,"channel")&&H(e.reason,ql)}a(Dd,"isChannelRevokedPayload");function Si(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Si,"isRecord");function Od(e){let{channel:t}=e;return typeof t=="string"&&Oa(t)?t:null}a(Od,"payloadChannel");function sS(e){return Si(e)?Od(e):null}a(sS,"getLiveProtocolPayloadChannel");function cS(e){return Si(e)?typeof e.id=="string"&&e.id.length>0&&typeof e.channel=="string"&&typeof e.type=="string"&&typeof e.tenantId=="string"&&e.tenantId.length>0&&typeof e.occurredAt=="string"&&Si(e.payload):false}a(cS,"isLiveEventEnvelope");var dS=["if","concat","sum","avg","count","min","max","earliest","latest","unique","first","percent_empty","percent_not_empty","count_empty","count_not_empty","count_unique"],jt={if:{name:"if",returnType:"branch",minArgs:3,maxArgs:3},concat:{name:"concat",returnType:{kind:"scalar",type:"text"},minArgs:1},sum:{name:"sum",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},avg:{name:"avg",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count:{name:"count",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},min:{name:"min",returnType:"source_item",minArgs:1,maxArgs:1},max:{name:"max",returnType:"source_item",minArgs:1,maxArgs:1},earliest:{name:"earliest",returnType:{kind:"scalar",type:"date"},minArgs:1,maxArgs:1},latest:{name:"latest",returnType:{kind:"scalar",type:"date"},minArgs:1,maxArgs:1},unique:{name:"unique",returnType:"argument",minArgs:1,maxArgs:1},first:{name:"first",returnType:"source_item",minArgs:1,maxArgs:1},percent_empty:{name:"percent_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},percent_not_empty:{name:"percent_not_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_empty:{name:"count_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_not_empty:{name:"count_not_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_unique:{name:"count_unique",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1}};function pn(e){return Object.hasOwn(jt,e)}a(pn,"isComputedFunctionName");var Ci=class Ci extends Error{constructor(t){super(t),this.name="ComputedFormulaCompileError";}};a(Ci,"ComputedFormulaCompileError");var I=Ci;function fn(e){let t=kd(e.expression),n=mn(t,e.schema),r=ep(n.valueType);if(r!==e.returnType)throw new I(`Computed formula "${e.attributeName}" returns "${r}", expected "${e.returnType}"`);if(La(e.returnType)&&n.optionsSource===void 0)throw new I(`Computed formula "${e.attributeName}" returns "${e.returnType}" without optionsSource`);let o=n.optionsSource===void 0?[]:[{kind:"options",source:n.optionsSource}],a=vi([...n.dependencies,...o]);return {kind:"formula",attributeName:e.attributeName,expression:e.expression,returnType:e.returnType,valueType:n.valueType,dependencies:a,ast:t,...n.optionsSource?{optionsSource:n.optionsSource}:{},...n.targetAttributeType?{targetAttributeType:n.targetAttributeType}:{},dependenciesHash:tp({expression:e.expression,returnType:e.returnType,dependencies:a})}}a(fn,"compileComputedFormula");function Ba(e){let t=new Map(e.map(o=>[o.attributeName,o])),n=new Set,r=a((o,a)=>{let s=a.indexOf(o);if(s!==-1){let m=[...a.slice(s),o];throw new I(`Computed field cycle detected: ${m.join(" -> ")}`)}if(n.has(o))return;let c=t.get(o);if(c===void 0)return;let u=[...a,o];for(let m of c.dependencies)m.kind==="computed"&&r(m.attributeName,u);n.add(o);},"visit");for(let o of e)r(o.attributeName,[]);}a(Ba,"assertAcyclicComputedDependencies");function kd(e){try{return b$1(e)}catch(t){throw t instanceof Error?new I(t.message):t}}a(kd,"parseCompileFormula");function mn(e,t){switch(e.kind){case "literal":return {valueType:jd(e.value),dependencies:[],...typeof e.value=="string"?{literalString:e.value}:{}};case "path":return _d(e.parts,t);case "call":return Ld(e.functionName,e.args,t);case "binary":return Wd(e.operator,mn(e.left,t),mn(e.right,t));default:return e}}a(mn,"inferNode");function jd(e){switch(typeof e){case "string":return {kind:"scalar",type:"text"};case "number":return {kind:"scalar",type:"number"};case "boolean":return {kind:"scalar",type:"boolean"};case "object":return {kind:"scalar",type:"text"};default:return e}}a(jd,"literalToValueType");function _d(e,t){if(e.length===1){let n=e[0],r=Ii(t,n);if(r===void 0)throw new I(`Unknown attribute "${n}" on object "${t.objectName}"`);return r.type==="relation"?{valueType:Fd(),dependencies:[{kind:"relation",relationName:r.name,cardinality:_a(r)}],targetAttributeType:r.type}:{valueType:Pa(r),dependencies:[Md(r)],optionsSource:Ma(t.objectName,r),targetAttributeType:r.type}}if(e.length===2){let[n,r]=e,o=Ii(t,n);if(o===void 0)throw new I(`Unknown attribute "${n}" on object "${t.objectName}"`);if(o.type!=="relation")throw new I(`Attribute "${n}" on object "${t.objectName}" is not a relation`);let a=Pd(o);if(a===void 0)throw new I(`Relation "${n}" on object "${t.objectName}" is missing targetObjectName`);let s=t.relatedObjects?.[a];if(s===void 0)throw new I(`Unknown related object "${a}"`);let c=Ii(s,r);if(c===void 0)throw new I(`Unknown attribute "${r}" on object "${s.objectName}"`);let u=Pa(c);return {valueType:o.cardinality==="many"?Bd(u):u,dependencies:[{kind:"relation",relationName:n,targetAttributeName:r,cardinality:_a(o)}],optionsSource:Ma(s.objectName,c),targetAttributeType:c.type}}throw new I("Computed paths support at most one relation hop")}a(_d,"inferPath");function Ii(e,t){return e.attributes.find(n=>n.name===t)}a(Ii,"findAttribute");function Pd(e){if(e.targetObjectName!==void 0)return e.targetObjectName;if(e.targets?.length===1){let[t]=e.targets;return t?.object==="*"?void 0:t?.object}}a(Pd,"getRelationTargetObjectName");function _a(e){return e.cardinality??"one"}a(_a,"relationCardinality");function Md(e){return e.type==="formula"||e.type==="rollup"?{kind:"computed",attributeName:e.name}:{kind:"local",attributeName:e.name}}a(Md,"localDependencyFor");function Pa(e){if(e.type==="formula"||e.type==="rollup"){if(e.returnType===void 0)throw new I(`Computed attribute "${e.name}" is missing returnType`);return Vd(e.returnType)}switch(e.type){case "number":case "currency":return {kind:"scalar",type:"number"};case "checkbox":return {kind:"scalar",type:"boolean"};case "date":return {kind:"scalar",type:"date"};case "select":case "status":return {kind:"scalar",type:"select"};case "multiselect":return {kind:"collection",itemType:"select"};case "text":case "richtext":case "phone":case "user":case "location":case "relation":case "document":return {kind:"scalar",type:"text"};default:return e.type}}a(Pa,"attributeToValueType");function Fd(){return {kind:"collection",itemType:"text"}}a(Fd,"relationToValueType");function Vd(e){return e==="multiselect"?{kind:"collection",itemType:"select"}:{kind:"scalar",type:e}}a(Vd,"returnTypeToValueType");function Bd(e){return e.kind==="collection"?e:{kind:"collection",itemType:e.type}}a(Bd,"asCollectionValueType");function Ma(e,t){if(t.type==="formula"||t.type==="rollup")return La(t.returnType)?t.optionsSource:void 0;if(!(t.type!=="select"&&t.type!=="status"&&t.type!=="multiselect"))return t.optionsSource??{objectName:e,attributeName:t.name,...t.id?{attributeId:t.id}:{}}}a(Ma,"optionsSourceForAttribute");function Ld(e,t,n){if(!pn(e))throw new I(`Unknown computed function "${e}"`);let r=jt[e];if(t.length<r.minArgs||r.maxArgs!==void 0&&t.length>r.maxArgs){let a=r.maxArgs===void 0||r.maxArgs===r.minArgs?String(r.minArgs):`${r.minArgs}-${r.maxArgs}`;throw new I(`Function "${e}" expects ${a} arguments, received ${t.length}`)}let o=t.map(a=>mn(a,n));return Ud(e,o)}a(Ld,"inferCall");function Ud(e,t){let n=vi(t.flatMap(r=>r.dependencies));switch(e){case "if":return $d(t,n);case "concat":return Gd(t,`Function "${e}" does not accept collection values`),{valueType:{kind:"scalar",type:"text"},dependencies:n};case "sum":case "avg":return Fa(e,t[0],"number"),{valueType:{kind:"scalar",type:"number"},dependencies:n};case "count":case "count_empty":case "count_not_empty":case "count_unique":case "percent_empty":case "percent_not_empty":return Yd(e,t[0]),{valueType:{kind:"scalar",type:"number"},dependencies:n};case "min":case "max":return Kd(e,t[0]),{valueType:Hd(t[0]),dependencies:n,optionsSource:t[0].optionsSource,targetAttributeType:t[0].targetAttributeType};case "earliest":case "latest":return Fa(e,t[0],"date"),{valueType:{kind:"scalar",type:"date"},dependencies:n,targetAttributeType:t[0].targetAttributeType};case "unique":return qd(t[0],n);case "first":return zd(t[0],n);default:return e}}a(Ud,"inferFunctionReturn");function $d(e,t){Ri(e[0].valueType,"boolean",'Function "if" condition must be boolean');let n=e[1],r=e[2],o=Qd(n,r),a=Xd(n,r);if(o===void 0)throw new I('Function "if" branches must return the same type');return {valueType:o,dependencies:t,...a?{optionsSource:a}:{},targetAttributeType:n.targetAttributeType??r.targetAttributeType}}a($d,"inferIfFunction");function qd(e,t){if(e.valueType.kind!=="collection"||e.valueType.itemType!=="select")throw new I('Function "unique" expects a select collection');return {valueType:{kind:"collection",itemType:"select"},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}a(qd,"inferUniqueFunction");function zd(e,t){if(e.valueType.kind!=="collection")throw new I('Function "first" expects a collection');return {valueType:{kind:"scalar",type:e.valueType.itemType},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}a(zd,"inferFirstFunction");function Wd(e,t,n){let r=vi([...t.dependencies,...n.dependencies]),o=e==="+"||e==="-"||e==="*"||e==="/";if(t.valueType.kind==="collection"||n.valueType.kind==="collection")throw new I(`Cannot use collection values with ${o?"arithmetic":"comparison"} operator "${e}"`);if(o)return e==="+"&&(t.valueType.type==="text"||n.valueType.type==="text")?{valueType:{kind:"scalar",type:"text"},dependencies:r}:(Ri(t.valueType,"number",`Operator "${e}" expects number operands`),Ri(n.valueType,"number",`Operator "${e}" expects number operands`),{valueType:{kind:"scalar",type:"number"},dependencies:r});if(e==="=="||e==="!="){if(t.valueType.type!==n.valueType.type)throw new I(`Operator "${e}" expects operands with the same scalar type`);return {valueType:{kind:"scalar",type:"boolean"},dependencies:r}}if((t.valueType.type!=="number"||n.valueType.type!=="number")&&(t.valueType.type!=="date"||n.valueType.type!=="date"))throw new I(`Operator "${e}" expects number or date operands of the same type`);return {valueType:{kind:"scalar",type:"boolean"},dependencies:r}}a(Wd,"inferBinary");function Gd(e,t){for(let n of e)if(n.valueType.kind==="collection")throw new I(t)}a(Gd,"ensureNoCollections");function Fa(e,t,n){if((t.valueType.kind==="collection"?t.valueType.itemType:t.valueType.type)!==n)throw new I(`Function "${e}" expects ${n} values`)}a(Fa,"ensureCollectionOrScalarType");function Kd(e,t){if(t.valueType.kind!=="collection")throw new I(`Function "${e}" expects a collection`);let n=t.valueType.itemType;if(n!=="number"&&n!=="date")throw new I(`Function "${e}" expects number or date values`)}a(Kd,"ensureMinMaxSource");function Yd(e,t){if(t.valueType.kind!=="collection")throw new I(`Function "${e}" expects a collection`)}a(Yd,"ensureCollectionSource");function Ri(e,t,n){if(e.kind!=="scalar"||e.type!==t)throw new I(n)}a(Ri,"ensureScalarType");function Hd(e){return e.valueType.kind==="scalar"?e.valueType:{kind:"scalar",type:e.valueType.itemType}}a(Hd,"sourceItemValueType");function Jd(e,t){return e.kind==="scalar"?t.kind==="scalar"&&e.type===t.type:t.kind==="collection"&&e.itemType===t.itemType}a(Jd,"sameValueType");function Qd(e,t){if(Jd(e.valueType,t.valueType)||Va(e,t))return e.valueType;if(Va(t,e))return t.valueType}a(Qd,"resolveIfBranchValueType");function Va(e,t){return e.valueType.kind==="scalar"&&e.valueType.type==="select"&&t.valueType.kind==="scalar"&&t.valueType.type==="text"&&t.literalString!==void 0}a(Va,"isSelectScalarWithStringLiteral");function Xd(e,t){let n=e.optionsSource,r=t.optionsSource;if(n!==void 0&&r!==void 0&&!Zd(n,r))throw new I('Function "if" branches use incompatible options sources');return n??r}a(Xd,"resolveIfOptionsSource");function Zd(e,t){return e.objectName===t.objectName&&e.attributeName===t.attributeName&&e.attributeId===t.attributeId}a(Zd,"sameOptionsSource");function La(e){return e==="select"||e==="multiselect"}a(La,"isSelectLikeReturnType");function ep(e){if(e.kind==="scalar")return e.type;if(e.itemType==="select")return "multiselect";throw new I(`Collection item type "${e.itemType}" cannot be used as a computed return type`)}a(ep,"valueTypeToReturnType");function vi(e){let t=new Set,n=[];for(let r of e){let o=JSON.stringify(_t(r));t.has(o)||(t.add(o),n.push(r));}return n}a(vi,"uniqueDependencies");function tp(e){let t=e.dependencies.map(n=>_t(n)).sort((n,r)=>Ua(JSON.stringify(n),JSON.stringify(r)));return JSON.stringify(_t({expression:e.expression,returnType:e.returnType,dependencies:t}))}a(tp,"createDependenciesHash");function _t(e){return Array.isArray(e)?e.map(t=>_t(t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>Ua(t,n)).map(([t,n])=>[t,_t(n)])):e}a(_t,"stableNormalize");function Ua(e,t){return e<t?-1:e>t?1:0}a(Ua,"compareStrings");function np(e){return e.function==="count"?`count(${e.relationAttribute})`:`${op(e.function)}(${e.relationAttribute}.${e.targetAttribute})`}a(np,"rollupToFormulaExpression");function rp(e,t){if(e.function==="count")return "number";let n=ap(e,t);switch(e.function){case "countValues":case "countEmpty":case "percentEmpty":case "percentNotEmpty":case "countUniqueValues":return "number";case "sum":case "avg":return "number";case "earliest":case "latest":return "date";case "original":if(!cp(n.type))throw new I('Rollup "original" requires a select, status, or multiselect target');return "multiselect";default:return e.function}}a(rp,"inferRollupReturnType");function qa(e,t){let n=np(e),r=rp(e,t);return {...fn({attributeName:e.name,expression:n,returnType:r,schema:ip(e,t)}),kind:"rollup"}}a(qa,"compileRollupAttribute");function ip(e,t){return {...t,attributes:t.attributes.map(n=>n.name===e.relationAttribute&&n.type==="relation"?{...n,cardinality:"many"}:n)}}a(ip,"schemaWithRollupRelationAsMany");function op(e){switch(e){case "sum":case "avg":case "earliest":case "latest":return e;case "original":return "unique";case "countValues":return "count_not_empty";case "countEmpty":return "count_empty";case "percentEmpty":return "percent_empty";case "percentNotEmpty":return "percent_not_empty";case "countUniqueValues":return "count_unique";default:return e}}a(op,"rollupFunctionToFormulaFunction");function ap(e,t){let n=$a(t,e.relationAttribute);if(n===void 0)throw new I(`Unknown relation attribute "${e.relationAttribute}" on object "${t.objectName}"`);if(n.type!=="relation")throw new I(`Attribute "${e.relationAttribute}" on object "${t.objectName}" is not a relation`);let r=sp(n);if(r===void 0)throw new I(`Relation "${e.relationAttribute}" on object "${t.objectName}" is missing targetObjectName`);let o=t.relatedObjects?.[r];if(o===void 0)throw new I(`Unknown related object "${r}"`);let a=$a(o,e.targetAttribute);if(a===void 0)throw new I(`Unknown attribute "${e.targetAttribute}" on object "${o.objectName}"`);return a}a(ap,"findRollupTargetAttribute");function $a(e,t){return e.attributes.find(n=>n.name===t)}a($a,"findAttribute");function sp(e){if(e.targetObjectName!==void 0)return e.targetObjectName;if(e.targets?.length===1){let[t]=e.targets;return t?.object==="*"?void 0:t?.object}}a(sp,"getRelationTargetObjectName");function cp(e){return e==="select"||e==="status"||e==="multiselect"}a(cp,"isSelectLikeAttributeType");function xe(e,t){switch(e.kind){case "literal":return e.value;case "path":return lp(t,e.parts);case "binary":return dp(e.operator,xe(e.left,t),xe(e.right,t));case "call":return up(e.functionName,e.args,t);default:return e}}a(xe,"evaluateAst");function up(e,t,n){if(mp(e),fp(e,t.length),e==="if"){let r=xe(t[0],n);return r===null?null:xe(r?t[1]:t[2],n)}return bp(e,t.map(r=>xe(r,n)))}a(up,"evaluateCallNode");function lp(e,t){return t.reduce((n,r)=>Ha(n,r),e)}a(lp,"resolvePath");function Ha(e,t){if(Array.isArray(e))return e.map(r=>Ha(r,t));if(!Ya(e))return null;if(Object.hasOwn(e,t))return e[t]??null;let n=e.values;return Ya(n)&&Object.hasOwn(n,t)?n[t]??null:null}a(Ha,"resolvePathPart");function dp(e,t,n){switch(e){case "+":return pp(t,n);case "-":return gn(t,n,(r,o)=>r-o);case "*":return gn(t,n,(r,o)=>r*o);case "/":return gn(t,n,(r,o)=>r/o);case ">":return bn(t,n,r=>r>0);case "<":return bn(t,n,r=>r<0);case ">=":return bn(t,n,r=>r>=0);case "<=":return bn(t,n,r=>r<=0);case "==":return za(t,n);case "!=":{let r=za(t,n);return r===null?null:!r}default:return e}}a(dp,"evaluateBinary");function pp(e,t){return typeof e=="string"||typeof t=="string"?`${e??""}${t??""}`:gn(e,t,(n,r)=>n+r)}a(pp,"add");function bn(e,t,n){let r=Ja(e,t);return r===null?null:n(r)}a(bn,"compareWith");function Ja(e,t){if(!at([e,t]))return null;let n=st(e),r=st(t);if(n!==null&&r!==null)return n-r;let o=Di(e),a=Di(t);return o&&a?o.getTime()-a.getTime():null}a(Ja,"compare");function za(e,t){return e===t?true:e==null||t===null||t===void 0?false:at([e,t])?Ja(e,t)===0:null}a(za,"equalScalar");function mp(e){if(!pn(e))throw new Error(`Unknown computed function "${e}"`)}a(mp,"assertComputedFunctionName");function fp(e,t){let{minArgs:n,maxArgs:r}=jt[e];if(t>=n&&t<=(r??Number.POSITIVE_INFINITY))return;let o=r===void 0?`at least ${n}`:`between ${n} and ${r}`;throw new Error(`Function "${e}" expects ${o} arguments, received ${t}`)}a(fp,"validateArity");function bp(e,t){switch(e){case "concat":return t.filter(n=>n!=null).map(String).join("");case "sum":return at(t)?Ei(t).reduce((n,r)=>n+r,0):null;case "avg":{if(!at(t))return null;let n=Ei(t);return n.length>0?n.reduce((r,o)=>r+o,0)/n.length:null}case "count":return Fe(t[0]).length;case "min":return Wa(t,"min");case "max":return Wa(t,"max");case "earliest":return Ni(t,"min");case "latest":return Ni(t,"max");case "unique":return Ka(Fe(t[0]));case "first":return Fe(t[0]).find(n=>n!=null)??null;case "percent_empty":return Ga(t[0],true);case "percent_not_empty":return Ga(t[0],false);case "count_empty":return Fe(t[0]).filter(a$1).length;case "count_not_empty":return Fe(t[0]).filter(n=>!a$1(n)).length;case "count_unique":return Ka(Fe(t[0])).length;default:return e}}a(bp,"evaluateCall");function Ei(e){return yn(e).map(st).filter(t=>t!==null)}a(Ei,"numericValues");function at(e){let t=new Set;for(let n of yn(e))Oi(n)&&t.add(Qa(n));return t.size<=1}a(at,"areCommensurable");function Qa(e){return e.code.toUpperCase()}a(Qa,"currencyCode");function gn(e,t,n){if(!at([e,t]))return null;let r=st(e),o=st(t);if(r===null||o===null)return null;let a=n(r,o);return Number.isFinite(a)?a:null}a(gn,"numericBinary");function Wa(e,t){if(!at(e))return null;let n=Ei(e);return n.length>0?t==="min"?Math.min(...n):Math.max(...n):Ni(e,t)}a(Wa,"minMax");function Ni(e,t){let n=yn(e).map(Di).filter(a=>a!==null);if(n.length===0)return null;let r=n.map(a=>a.getTime()),o=t==="min"?Math.min(...r):Math.max(...r);return new Date(o).toISOString()}a(Ni,"dateMinMax");function Ga(e,t){let n=Fe(e);return n.length===0?0:n.filter(o=>a$1(o)===t).length/n.length}a(Ga,"percentByEmptyState");function Ka(e){let t=new Set,n=[];for(let r of e){if(a$1(r))continue;let o=gp(r);t.has(o)||(t.add(o),n.push(r));}return n}a(Ka,"uniqueNonEmpty");function Fe(e){return e==null?[]:Array.isArray(e)?yn(e):[e]}a(Fe,"collectionItems");function yn(e){return e.flat(Number.POSITIVE_INFINITY)}a(yn,"flatten");function st(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&e.trim()!==""){let t=Number(e);return Number.isFinite(t)?t:null}return Oi(e)&&Number.isFinite(e.value)?e.value:null}a(st,"toFiniteNumber");function Oi(e){return typeof e=="object"&&e!==null&&typeof e.value=="number"&&typeof e.code=="string"}a(Oi,"isCurrencyValue");function Di(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e!="string"){let n=Ke(e);if(n===null)return null;let r=new Date(n);return Number.isNaN(r.getTime())?null:r}let t=new Date(e);return Number.isNaN(t.getTime())?null:t}a(Di,"toDate");function gp(e){if(Oi(e))return `currency:${Qa(e)}:${e.value}`;let t=st(e);return t!==null?`number:${t}`:e instanceof Date?`date:${e.toISOString()}`:`${typeof e}:${JSON.stringify(e)}`}a(gp,"uniqueKey");function Ya(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Ya,"isPlainRecord");function yp(e,t,n){if(e==null)return null;let r=a(o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean"||o instanceof Date?String(o):null,"stringifyScalar");switch(t){case "number":{let o=typeof e=="number"?e:Number(e);return Number.isNaN(o)?null:n!==void 0?Number(o.toFixed(n)):o}case "boolean":return !!e;case "date":return e instanceof Date?e.toISOString():typeof e=="string"?e:null;case "text":return String(e);case "select":if(Array.isArray(e)){for(let o of e){if(o==null)continue;let a=r(o);if(a!==null)return a}return null}return r(e);case "multiselect":return Array.isArray(e)?e.flatMap(o=>{if(o==null)return [];let a=r(o);return a===null?[]:[a]}):r(e)===null?[]:[String(e)];default:{let o=t;throw new Error(`Unsupported computed return type: ${o}`)}}}a(yp,"formatComputedResult");function RS(e,t){return xe(e,t)}a(RS,"evaluateComputedAst");function vS(e,t){return xe(b$1(e),t)}a(vS,"evaluateComputedFormula");function CS(e,t,n,r){try{let o=xe(b$1(e),t);return {value:n?yp(o,n,r):o}}catch(o){return {value:null,error:o instanceof Error?o.message:String(o)}}}a(CS,"evaluateComputedFormulaWithResult");var DS=[{name:"if",signature:"if(condition, then, else)",description:"Conditional value",category:"logic",example:"if(amount > 100, 'big', 'small')"},{name:"concat",signature:"concat(a, b, ...)",description:"Join values into text",category:"text",example:"concat(firstName, ' ', lastName)"},{name:"sum",signature:"sum(collection)",description:"Total of values",category:"number",example:"sum(orders.amount)"},{name:"avg",signature:"avg(collection)",description:"Average of values",category:"number",example:"avg(orders.amount)"},{name:"min",signature:"min(collection)",description:"Smallest value",category:"number",example:"min(orders.amount)"},{name:"max",signature:"max(collection)",description:"Largest value",category:"number",example:"max(orders.amount)"},{name:"count",signature:"count(collection)",description:"Number of items",category:"collection",example:"count(orders)"},{name:"count_empty",signature:"count_empty(collection)",description:"Items with no value",category:"collection",example:"count_empty(orders.note)"},{name:"count_not_empty",signature:"count_not_empty(collection)",description:"Items with a value",category:"collection",example:"count_not_empty(orders.note)"},{name:"count_unique",signature:"count_unique(collection)",description:"Distinct values",category:"collection",example:"count_unique(orders.status)"},{name:"percent_empty",signature:"percent_empty(collection)",description:"Fraction with no value",category:"collection",example:"percent_empty(orders.note)"},{name:"percent_not_empty",signature:"percent_not_empty(collection)",description:"Fraction with a value",category:"collection",example:"percent_not_empty(orders.note)"},{name:"unique",signature:"unique(collection)",description:"Distinct values as a list",category:"collection",example:"unique(orders.status)"},{name:"first",signature:"first(collection)",description:"First non-empty value",category:"collection",example:"first(orders.status)"},{name:"earliest",signature:"earliest(collection)",description:"Earliest date",category:"date",example:"earliest(orders.closeDate)"},{name:"latest",signature:"latest(collection)",description:"Latest date",category:"date",example:"latest(orders.closeDate)"}];var Xa=a(e=>a$1(e)||Array.isArray(e)&&e.length===0,"isEmpty"),J=a(e=>e==null?"":String(e),"toStr"),xn=a(e=>{if(a$1(e))return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null},"toNum"),Tn=a(e=>{if(e==null)return null;let t=e instanceof Date?e:new Date(String(e));return Number.isNaN(t.getTime())?null:t},"toDate"),hn=a(e=>Array.isArray(e)?e:e==null?[]:[e],"toArr"),hp=a((e,t,n)=>{let r=xn(e),o=xn(t);return r!==null&&o!==null&&n(r,o)},"compareNumbers"),Ap=a((e,t,n)=>{let r=Tn(e),o=Tn(t);return r!==null&&o!==null&&n(r.getTime(),o.getTime())},"compareDates"),Za=a((e,t,n)=>{if(n.type==="number"||n.type==="currency"){let r=xn(e),o=xn(t);if(r!==null&&o!==null)return r===o}return J(e)===J(t)},"equalsForAttr");function _S(e,t){return e?e==="checkbox":typeof t=="boolean"}a(_S,"isCheckboxEquality");var An=a(e=>({appliesTo:["number","currency","date","formula"],evaluateInMemory:a((t,n,r)=>r.type==="date"?Ap(t,n,e):hp(t,n,e),"evaluateInMemory")}),"orderingSpec"),wn={is:{appliesTo:["text","phone","number","currency","checkbox","status","select","date","user","relation","formula"],evaluateInMemory:a((e,t,n)=>n.type==="checkbox"?e===true==(t===true):Za(e,t,n),"evaluateInMemory")},is_not:{appliesTo:["text","phone","number","currency","status","select","date","user","relation","formula"],evaluateInMemory:a((e,t,n)=>!Za(e,t,n),"evaluateInMemory")},contains:{appliesTo:["text","phone","formula"],evaluateInMemory:a((e,t)=>J(e).toLowerCase().includes(J(t).toLowerCase()),"evaluateInMemory")},not_contains:{appliesTo:["text","phone","formula"],evaluateInMemory:a((e,t)=>!J(e).toLowerCase().includes(J(t).toLowerCase()),"evaluateInMemory")},starts_with:{appliesTo:["text","phone"],evaluateInMemory:a((e,t)=>J(e).toLowerCase().startsWith(J(t).toLowerCase()),"evaluateInMemory")},ends_with:{appliesTo:["text"],evaluateInMemory:a((e,t)=>J(e).toLowerCase().endsWith(J(t).toLowerCase()),"evaluateInMemory")},is_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:a(e=>Xa(e),"evaluateInMemory")},is_not_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:a(e=>!Xa(e),"evaluateInMemory")},less_than:An((e,t)=>e<t),greater_than:An((e,t)=>e>t),less_or_equal:An((e,t)=>e<=t),greater_or_equal:An((e,t)=>e>=t),is_within:{appliesTo:["date"],evaluateInMemory:a((e,t)=>{let n=Tn(e),r=S(t);return n&&r?n.getTime()>=r.startMs&&n.getTime()<r.endMs:false},"evaluateInMemory")},on_day_month:{appliesTo:["date"],evaluateInMemory:a((e,t)=>{let n=Tn(e);if(!n)return false;let r=t;return n.getMonth()+1===r.month&&n.getDate()===r.day},"evaluateInMemory")},any_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:a((e,t)=>{let n=hn(t).map(J);return hn(e).map(J).some(o=>n.includes(o))},"evaluateInMemory")},none_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:a((e,t)=>{let n=hn(t).map(J);return !hn(e).map(J).some(o=>n.includes(o))},"evaluateInMemory")}};var xp=a((e,t)=>({id:`system:${e}`,name:e,label:e,type:t,system:true}),"systemAttribute"),Tp=[...Object.entries(V$1).map(([e,t])=>xp(e,t))];function WS(e,t,n){let r=t;return wp(e,{...t.values,id:t.id,objectId:t.objectId,objectName:r.objectName,tenantId:r.tenantId,label:t.label,createdAt:t.createdAt,updatedAt:t.updatedAt,createdBy:t.createdBy,lastUpdatedBy:t.lastUpdatedBy,deletedAt:t.deletedAt,deletedBy:t.deletedBy,visibility:t.visibility,ownedBy:t.ownedBy},[...n,...Tp])}a(WS,"evaluateRecordFilterState");function wp(e,t,n){if(e.rules.length===0)return true;let r=new Map(n.map(a=>[a.name,a])),o=e.combinator==="or"?"some":"every";return e.rules[o](a=>Sp(a,t,r))}a(wp,"evaluateFilterState");function Sp(e,t,n){let r=n.get(e.attribute);if(!r)return false;if(e.property&&r.type==="location"){if(!(g(e.property)&&h$1(e.operator)))return false;let c=wn[e.operator];if(!c)return false;let u=t[e.attribute],m=typeof u=="object"&&u!==null?u[e.property]:void 0;return ki(c,"text",e.operator,m,e.value,r)}if(e.property){let c=qo(r).find(N=>N.name===e.property);if(!c)return false;let u=K(e.operator),m=wn[u];if(!m?.appliesTo.includes(c.type))return false;let d=t[e.attribute],g=(Array.isArray(d)?d:d==null?[]:[d]).some(N=>{if(typeof N!="object"||N===null)return false;let h=N.props;return typeof h!="object"||h===null?false:ki(m,c.type,u,h[e.property],e.value,c)});return (e.quantifier??J$1(e.operator))==="none"?!g:g}let o=wn[e.operator];if(!o||!o.appliesTo.includes(r.type))return false;let a=t[e.attribute],s=r.type==="relation"||r.type==="document"||r.type==="user"?vp(a):a;return ki(o,r.type,e.operator,s,e.value,r)}a(Sp,"evaluateRule");function ki(e,t,n,r,o,a){let[s,c]=Ip(t,n,r,o);return t==="phone"&&c===""&&n==="contains"?false:t==="phone"&&c===""&&n==="not_contains"?true:e.evaluateInMemory(s,c,a)}a(ki,"evaluateNormalizedComparands");function Ip(e,t,n,r){return e==="date"&&(t==="is"||t==="is_not")?[es(n),es(r)]:e==="phone"?Rp(n,r):[ts(e,n),ts(e,r)]}a(Ip,"normalizeOperatorComparands");function es(e){let t=Ie(e)?Ke(e):e;if(t instanceof Date)return Number.isNaN(t.getTime())?null:t.toISOString().slice(0,10);if(typeof t!="string"||t==="")return null;if(/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let n=new Date(t);return Number.isNaN(n.getTime())?null:n.toISOString().slice(0,10)}a(es,"normalizeUtcCalendarDay");function Rp(e,t){let n=typeof t=="object"&&t!==null?t:{},r=typeof n.countryCode=="string"?n.countryCode:void 0,o=a(a=>{let s=typeof a=="object"&&a!==null?a:{phoneNumber:a};if(typeof s.phoneNumber!="string")return null;if(!r)return a$3(s.phoneNumber);let c=typeof s.countryCode=="string"?s.countryCode:r;return `${c}:${b$2(s.phoneNumber,c)}`},"normalizeOne");return [o(e),o(t)]}a(Rp,"normalizePhoneComparands");function ts(e,t){return e==="currency"?H$1(t):e==="date"?Ie(t)?Ke(t):t instanceof Date?Number.isNaN(t.getTime())?null:t.toISOString():t:t}a(ts,"normalizeComparableValue");function vp(e){let t=a(n=>typeof n!="object"||n===null?n:n.id,"normalizeOne");return Array.isArray(e)?e.map(t):t(e)}a(vp,"normalizeReferenceIds");var ns="today";function Sn(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(e)}a(Sn,"dateInTimezone");function Cp(e,t){if(!("defaultValue"in e))return;let{defaultValue:n}=e;return e.type!=="date"||n!==ns?n:e.includeTime?t.now.toISOString():Sn(t.now,t.timezone)}a(Cp,"resolveAttributeDefaultValue");function ZS(e,t,n){if(e.combinator==="or"&&e.rules.length>1)return {};let r=new Map(t.map(a=>[a.name,a])),o={};for(let a of e.rules){if(a.property!==void 0||Object.hasOwn(o,a.attribute))continue;let s=r.get(a.attribute);if(!s)continue;let c=Ep(a,n);c!==void 0&&(o[a.attribute]=j$2(s).storage.cardinality==="many"?[c]:c);}return o}a(ZS,"deriveCreateDefaultsFromFilters");function Ep(e,t){if(e.operator==="is")return D$1(e.value)?rs(e.value,t):e.value===null||Array.isArray(e.value)?void 0:e.value;if(e.operator==="any_of"){if(!Array.isArray(e.value)||e.value.length!==1)return;let n=e.value[0];return D$1(n)?rs(n,t):n}}a(Ep,"extractDeterministicValue");function rs(e,t){if(t){if(e.dynamic==="actor")return t.userId;if(e.anchor==="today")return Sn(t.now,t.timezone);if(e.anchor==="now")return t.now.toISOString()}}a(rs,"resolveDynamicValue");function nI(e){let t=[];return e.canModify&&t.push("modify"),e.canSend&&t.push("send"),t}a(nI,"requestedCapabilities");var rI={status:"connector_status",error:"connector_error",provider:"connector_provider"};var Np=(t=>(t.Desktop="desktop",t))(Np||{});function sI(e){return e==="gmail"||e==="outlook"}a(sI,"isMailProvider");var Dp=["threads","messages"];function cI(e){return Dp.includes(e)}a(cI,"isMailboxListMode");var Op=["reply","reply_all"];function uI(e){return Op.includes(e)}a(uI,"isReplyMode");var lI=2e5,dI=998;var fI=["force","skip"],bI=["none","all","external_only"],gI="x-fake-signature",yI={override:null,status:"none",failureReason:null,botId:null};var kp=/^Session \d+$/;function is(e){let t=e.replace(/\s+/g," ").trim().replace(/[.!?]+$/,"");return t?t.length>60?`${t.slice(0,59).trimEnd()}...`:t:"New conversation"}a(is,"buildAgentFallbackTitle");function jp(e){let t=e.generated?.trim();return t&&!kp.test(t)?t:e.firstUserText?is(e.firstUserText):e.emptyLabel}a(jp,"conversationDisplayTitle");var ji=/^[a-z0-9][a-z0-9-]{0,62}$/;function _p(e){if(!ji.test(e))throw new h(`Invalid schema source id "${e}": expected a lowercase slug matching ${ji}`,[])}a(_p,"assertSchemaSourceId");function II(e){let{attributeRemovals:t,objectRemovals:n,renames:r}=e.destructive;return t.length>0||n.length>0||r.length>0}a(II,"hasDestructiveEntries");var re={objectAdditions:20,totalMutations:500,serializedBytes:512*1024};function Pi(e){return e instanceof Error?e.message:String(e)}a(Pi,"errorMessage");var Pp=z.enum(["text","richtext","number","checkbox","date","phone","currency","status","location","select","multiselect","user","relation","formula","rollup","document"]).describe('The attribute\'s data type. Determines which keys `config` accepts and requires: `status`/`select`/`multiselect` need a non-empty `options` array (each `status` option carrying its own `group`); `relation` needs `targets` (non-empty) and `cardinality` ("one" or "many"); `formula` needs `expression` and `returnType`; `rollup` needs `targetAttribute` and `function`. Every other type accepts only the shared presentation keys (`placeholder`, `defaultValue`, `icon`, ...) plus a few type-specific optionals (e.g. `number.decimals`, `date.dateFormat`). An attribute\'s type can never be changed later through this tool \u2014 only through a code migration \u2014 so pick it correctly now.');var as=z.string().min(1).superRefine((e,t)=>{try{xt(e);}catch(n){t.addIssue({code:z.ZodIssueCode.custom,message:Pi(n)});}}).describe('The attribute\'s machine name \u2014 the record\'s field key, and what `{{ name }}` refers to in a labelExpression. Must be a valid identifier: starts with a letter or underscore, then only letters/digits/underscores ("montantHt", "first_name", "FIRST_NAME" are valid; "first-name", "first name", "123name" are not). Max 63 characters. Cannot be a name reserved by the record shape itself (id, createdAt, updatedAt, createdBy, lastUpdatedBy, objectId, label, embeddingText, values, metadata, deletedAt, deletedBy, schemaVersion).'),Mp=z.string().min(1).superRefine((e,t)=>{w$1(e)&&t.addIssue({code:z.ZodIssueCode.custom,message:`"${e}" is a reserved object name (${C$1.join(", ")}) and cannot be used for a new object.`});try{At(e);}catch(n){t.addIssue({code:z.ZodIssueCode.custom,message:Pi(n)});}}).describe(`The new object's machine name: kebab-case slug, lowercase letters/digits/hyphens only, starting with a letter ("products", "user-profiles", "order-items" are valid; "Products", "userProfiles", "user_profiles" are not). Max 63 characters. Cannot be a name the platform reserves for its own system objects, and cannot already exist.`);function ss(e){return e.superRefine((t,n)=>{try{let r=x(t.type,{...t.config??{},description:t.description}),o=Object.keys(t.config??{}).filter(a=>!Object.hasOwn(r,a));o.length>0&&n.addIssue({code:"unrecognized_keys",keys:o,path:["config"],message:`Unrecognized attribute config key${o.length===1?"":"s"}: ${o.join(", ")}`});}catch(r){if(r instanceof h){for(let o of r.errors)n.addIssue({code:z.ZodIssueCode.custom,path:["config",...o.path.map(a=>/^\d+$/.test(a)?Number(a):a)],message:`Config for type "${t.type}" is invalid or incomplete: ${o.message}`});return}n.addIssue({code:z.ZodIssueCode.custom,path:["config"],message:`Config for type "${t.type}" is invalid or incomplete: ${Pi(r)}`});}})}a(ss,"withConfigCheck");var cs=z.object({objectName:z.string().min(1).describe("Name of the existing (or, elsewhere in the same plan, newly created) object this attribute is added to. Ignored for an attribute declared inline in `additive.objects[].attributes` \u2014 there the parent object's own `name` is used instead."),name:as,label:z.string().min(1).max(128).describe("Human-readable display label shown in the UI. 1-128 characters, cannot be empty."),type:Pp,config:z.record(z.string(),z.unknown()).optional().describe('Type-specific configuration; required keys depend on `type` (see `type`\'s description). Shared optional keys on every type: `placeholder`, `defaultValue`, `icon`, `order`, `hidden`, `archived`, `deprecated`, `metadata`. Per-type keys: `text` \u2014 `multiline`, `minLength`, `maxLength`, `pattern`, `format` ("email"|"url"|"slug"); `number` \u2014 `renderAs` ("number"|"rating"), `min`, `max`, `unit`, `decimals`; `date` \u2014 `dateFormat`, `minDate`, `maxDate`, `includeTime`, `endDate`, `timeFormat` ("12h"|"24h"); `phone` \u2014 `defaultCountryCode` (3-letter); `currency` \u2014 `defaultCurrency`, `allowedCurrencies`, `allowNegative`; `status`/`select`/`multiselect` \u2014 `options` (REQUIRED, non-empty array of `{ value, label, color }`, unique `value`s; for `status` every OPTION also carries `group` as idle|in_progress|finished \u2014 `group` belongs on each option, never on `config` itself; select/multiselect accept `renderAs: "badges"`); `location` \u2014 `granularity`, `defaultCountry`, `allowedCountries`; `user` \u2014 `types` ("user"|"agent"), `multiple`; `relation` \u2014 `targets` (REQUIRED, non-empty array of `{ object }`) and `cardinality` (REQUIRED, "one"|"many"); `formula` \u2014 `expression` (REQUIRED formula string) and `returnType` (REQUIRED); `rollup` \u2014 `targetAttribute` (REQUIRED) and `function` (REQUIRED, e.g. "sum"|"avg"|"count"); `document` \u2014 `properties`, `accepts`, `maxFileSize`. Omit entirely for `richtext`/`checkbox`, which take no type-specific keys.'),required:z.boolean().optional().describe("Whether the attribute must have a value on every record. Defaults to false (optional)."),description:z.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),Fp=ss(cs),Vp=ss(cs.omit({objectName:true})),Bp=z.object({name:Mp,label:z.string().min(1).describe('Human-readable singular display label (e.g. "Devis").'),pluralLabel:z.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:z.string().optional().describe("Help text describing what this object represents."),icon:e.describe("Required icon name for the object. Must be a catalogue value \u2014 call `search_icons` and use a name it returns verbatim. A name that is not in the catalogue is rejected without any hint as to what would have worked, so never guess one."),labelExpression:Ye.describe('Template used to render a human-readable label for every record of this object \u2014 e.g. shown in relations, search results, and breadcrumbs. MUST contain at least one `{{ attributeName }}` interpolation referencing an attribute this object will actually have (either declared in this same `attributes` array, or an existing attribute if this is an update) \u2014 a plain string with no `{{ }}` at all (e.g. "Devis") is rejected. Interpolations cannot be empty (`{{ }}` is rejected) and only these pipes are allowed: UPPER, LOWER, capitalize, trim, prefix:"...", suffix:"...", wrap:"..." "...", default:"...". `{{ a || b }}` falls back to `b` when `a` is empty. Examples: "{{ firstName }} {{ lastName }}", "{{ numero | UPPER }}", "{{ name || reference }}".'),attributes:z.array(Vp).default([]).describe("Attributes to create on this new object, inline. Same rules as a standalone entry in `additive.attributes`, minus `objectName` (implied by this object). At least one attribute referenced by `labelExpression` should be included here.")}).strict(),us=z.object({attributeRemovals:z.array(z.object({objectName:z.string().min(1).describe("Object the attribute is removed from."),attributeName:z.string().min(1).describe("Attribute to delete, together with every record's stored value for it. Must not be a system (code-declared) attribute, and must not be referenced by the object's own `labelExpression` or `embeddingExpression` \u2014 update those first.")}).strict()).default([]).describe("Attributes to permanently delete. Irreversible: record values for the attribute are purged."),objectRemovals:z.array(z.object({objectName:z.string().min(1).describe("Object to delete entirely, together with all its records. Must not be a system (code-declared) object, and must not still be targeted by a `relation` attribute on another object \u2014 retarget or remove that relation first.")}).strict()).default([]).describe("Objects to permanently delete, records included. Irreversible."),renames:z.array(z.object({objectName:z.string().min(1).describe("Object the renamed attribute belongs to."),from:z.string().min(1).describe("Current attribute name. Must already exist and not be a system attribute."),to:as.describe("New attribute name \u2014 same identifier rules as any attribute `name` (see `name` on a planned attribute), and must not collide with another name already on the object, including one added elsewhere in this same plan.")}).strict()).default([]).describe("Attribute renames. Every reference to the old name (labelExpression, views, formulas) must be updated separately \u2014 a rename does not follow references automatically.")}).strict().default({attributeRemovals:[],objectRemovals:[],renames:[]}),ls=z.string().min(1).describe("ONE sentence naming the intent of the change \u2014 what it is for, not what it contains. The human approving it has already watched every entry land in the preview window and can read every row of the plan itself, so a recap tells them nothing they do not have. A second sentence is warranted only when `destructive` is non-empty: say plainly what will be lost (e.g. 'deletes the \"ancienMontant\" column and its data on every devis'). Never restate the plan \u2014 explain intent."),ds=z.object({objects:z.array(Bp).default([]),attributes:z.array(Fp).default([])}).strict().default({objects:[],attributes:[]});function _i(e,t=[],n=new WeakSet){if(e===null||typeof e=="string"||typeof e=="boolean")return null;if(typeof e=="number")return Number.isFinite(e)?null:{path:t,message:"Plan input contains a non-finite number"};if(typeof e!="object")return {path:t,message:"Plan input must contain only JSON-safe values"};if(n.has(e))return {path:t,message:"Plan input cannot contain circular references"};if(Array.isArray(e)){n.add(e);for(let s of Reflect.ownKeys(e))if(s!=="length"&&(typeof s=="symbol"||!/^(0|[1-9]\d*)$/.test(s)))return n.delete(e),{path:[...t,s],message:"Plan input arrays cannot contain non-index JSON properties"};for(let s=0;s<e.length;s++){if(!Object.hasOwn(e,s))return n.delete(e),{path:[...t,s],message:"Plan input cannot contain sparse arrays"};let c=_i(e[s],[...t,s],n);if(c)return n.delete(e),c}return n.delete(e),null}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return {path:t,message:"Plan input must contain only plain JSON objects"};n.add(e);let o=e,a=Reflect.ownKeys(o);for(let s of a){let c=Object.getOwnPropertyDescriptor(o,s);if(typeof s=="symbol"||!(c?.enumerable&&"value"in c))return n.delete(e),{path:[...t,s],message:"Plan input objects must contain enumerable JSON data properties only"}}for(let s of a.sort()){let c=_i(o[s],[...t,s],n);if(c)return n.delete(e),c}return n.delete(e),null}a(_i,"findJsonSafetyIssue");function Lp(e){let t=[];return e.additive.objects.forEach((n,r)=>{t.push(["additive","objects",r]),n.attributes.forEach((o,a)=>{t.push(["additive","objects",r,"attributes",a]);});}),e.additive.attributes.forEach((n,r)=>{t.push(["additive","attributes",r]);}),e.destructive.attributeRemovals.forEach((n,r)=>{t.push(["destructive","attributeRemovals",r]);}),e.destructive.objectRemovals.forEach((n,r)=>{t.push(["destructive","objectRemovals",r]);}),e.destructive.renames.forEach((n,r)=>{t.push(["destructive","renames",r]);}),t}a(Lp,"mutationPaths");function ps(e,t){e.additive.objects.length>re.objectAdditions&&t.addIssue({code:"too_big",origin:"array",maximum:re.objectAdditions,inclusive:true,path:["additive","objects",re.objectAdditions],message:`A schema plan can add at most ${re.objectAdditions} objects`});let n=Lp(e);n.length>re.totalMutations&&t.addIssue({code:"too_big",origin:"array",maximum:re.totalMutations,inclusive:true,path:n[re.totalMutations],message:`A schema plan can contain at most ${re.totalMutations} mutations; received ${n.length}`});}a(ps,"addPlanLimitIssues");function ms(e,t){let n=_i(e);if(n)return t.addIssue({code:"custom",path:n.path,message:n.message}),z.NEVER;let r=new TextEncoder().encode(b$3(e)).byteLength;return r>re.serializedBytes?(t.addIssue({code:"too_big",origin:"string",maximum:re.serializedBytes,inclusive:true,path:[],message:`A schema plan can serialize to at most ${re.serializedBytes} UTF-8 bytes; received ${r}`}),z.NEVER):e}a(ms,"boundSerializedPlanInput");var os=z.object({schemaPlanVersion:z.literal(2).describe("Required proposal contract version."),summary:ls,additive:ds,destructive:us}).strict().superRefine(ps),MI=Object.assign(z.preprocess(ms,os),{shape:os.shape}),Up=z.object({schemaPlanVersion:z.literal(2),summary:ls,additive:ds,destructive:us}).strict().superRefine(ps),FI=z.preprocess(ms,Up);var UI=z.object({objectName:z.string().min(1),recordId:z.uuid(),endpoint:z.string().min(1)}).strict(),In=z.record(z.string(),z.unknown()),Mi=z.number().int().positive(),$p=z.discriminatedUnion("type",[z.object({type:z.literal("attach"),targetId:z.uuid(),properties:In.optional()}).strict(),z.object({type:z.literal("detach"),targetId:z.uuid(),expectedEdgeRevision:Mi}).strict(),z.object({type:z.literal("replace_target"),previousTargetId:z.uuid(),targetId:z.uuid(),expectedEdgeRevision:Mi,properties:In.optional()}).strict(),z.object({type:z.literal("properties"),targetId:z.uuid(),expectedEdgeRevision:Mi,properties:In}).strict()]),$I=z.object({expectedWriteVersion:z.number().int().nonnegative(),change:$p}).strict(),qI=z.object({expectedWriteVersion:z.number().int().nonnegative(),data:z.record(z.string(),z.unknown()),properties:In.optional(),visibility:z.enum(["private","workspace"]).optional()}).strict(),zI=z.object({}).strict(),WI=z.object({objectName:z.string().min(1),recordIds:z.array(z.uuid()).max(100),endpoints:z.array(z.string().min(1)).max(20)}).strict();function Ve(e,t){throw new h(t,[{path:e,message:t}])}a(Ve,"reject");function Rn(e){throw new h(`Unsupported schema reference variant ${String(e)}`,[])}a(Rn,"exhaustive");function QI(e){let t=new Map(e.objects.map(c=>[c.name,c]));e.relations.forEach((c,u)=>c.endpoints.forEach((m,d)=>{t.has(m.object)||Ve(["relations",String(u),"endpoints",String(d),"object"],`Unknown schema reference ${JSON.stringify({kind:"object",object:m.object})}`);}));let n=Nt(e),r=[];function o(c,u,m){function d(y,A,S){(y.kind==="object"?t.has(y.object):y.kind==="attribute"?t.get(y.object)?.attributes.some(F=>F.name===y.attribute):y.kind==="relation"?e.relations.some(F=>F.name===y.relation):true)||Ve([...u,...S],`Unknown schema reference ${JSON.stringify(y)}`),r.push({owner:c,target:y,category:A,path:S,...m===void 0?{}:{layer:m}});}a(d,"add");function f(y,A,S,M){let F=n.resolveEndpoint(y,A);d(F?{kind:"relation",relation:F.relation.name}:{kind:"attribute",object:y,attribute:A},S,M);}a(f,"attribute");function g(y,A,S,M,F){f(y,A,S,M);let $t=n.resolveEndpoint(y,A);if($t)return $t.target;let Oe=t.get(y)?.attributes.find(cc=>cc.name===A);return Oe?.type!=="relation"&&Ve([...u,...M],`Invalid schema reference path "${F}"`),(Oe.targets.length!==1||Oe.targets[0].object==="*")&&Ve([...u,...M],`Ambiguous schema reference path "${F}"`),Oe.targets[0].object}a(g,"traverse");function N(y,A,S,M){let F=y;for(let[$t,Oe]of A.entries())$t===A.length-1?f(F,Oe,S,M):F=g(F,Oe,S,M,A.join("."));}a(N,"attributePath");function h(y,A,S){switch(A.kind){case "literal":return;case "path":N(y,A.parts,"computed",S);return;case "call":for(let M of A.args)h(y,M,S);return;case "binary":h(y,A.left,S),h(y,A.right,S);return;default:Rn(A);}}return a(h,"formula"),{add:d,attribute:f,traverse:g,attributePath:N,formula:h}}a(o,"visitor"),e.objects.forEach((c,u)=>{let m=["objects",String(u)],d=o({kind:"object",object:c.name},m);for(let f of ["labelExpression","embeddingExpression"]){let g=c[f];if(g)for(let N of ht(g))d.attributePath(c.name,N.split("."),"business",[f]);}c.attributes.forEach((f,g)=>{let N=[...m,"attributes",String(g)],h=o({kind:"attribute",object:c.name,attribute:f.name},N);switch(f.type){case "relation":f.targets.forEach((y,A)=>{if(y.object!=="*"&&h.add({kind:"object",object:y.object},"structural",["targets",String(A),"object"]),y.displayTemplate)for(let S of ht(y.displayTemplate))h.attributePath(y.object,S.split("."),"business",["targets",String(A),"displayTemplate"]);for(let S of Object.keys(y.filter??{}))h.attribute(y.object,S,"business",["targets",String(A),"filter",S]);});break;case "formula":{let y;try{y=b$1(f.expression);}catch(A){Ve([...N,"expression"],A instanceof Error?A.message:String(A));}h.formula(c.name,y,["expression"]),a$1(f,h);break}case "rollup":{let y=f.relationPath??f.relationAttribute,A=c.name;for(let S of y.split("."))A=h.traverse(A,S,"computed",[f.relationPath===void 0?"relationAttribute":"relationPath"],y);h.attributePath(A,f.targetAttribute.split("."),"computed",["targetAttribute"]),a$1(f,h);break}case "text":case "richtext":case "number":case "checkbox":case "date":case "phone":case "currency":case "status":case "location":case "select":case "multiselect":case "user":case "document":break;default:Rn(f);}});});function a$1(c,u){c.optionsSource&&(u.add({kind:"object",object:c.optionsSource.objectName},"computed",["optionsSource","objectName"]),u.attribute(c.optionsSource.objectName,c.optionsSource.attributeName,"computed",["optionsSource","attributeName"]));}a(a$1,"visitOptions"),e.relations.forEach((c,u)=>{let m=o({kind:"relation",relation:c.name},["relations",String(u)]);c.endpoints.forEach((d,f)=>m.add({kind:"object",object:d.object},"structural",["endpoints",String(f),"object"]));});function s(c,u,m){o({kind:"view",object:c.object,view:c.name},u,m).add({kind:"object",object:c.object},"structural",["object"]),c.contents.forEach((d,f)=>{let g=o({kind:"content",object:c.object,view:c.name,content:d.name},[...u,"contents",String(f)],m);function N(h,y,A,S){h?.forEach((M,F)=>g.attribute(y,M,A,[S,String(F)]));}switch(a(N,"names"),d.type){case "collection":{let h;switch(d.source.object!==void 0?(h=d.source.object,g.add({kind:"object",object:h},"source",["source","object"])):h=g.traverse(c.object,d.source.relation,"source",["source","relation"],d.source.relation),d.columns?.forEach((y,A)=>{if(typeof y=="string"){g.attribute(h,y,"display",["columns",String(A)]);return}let S=d.source.relation===void 0?void 0:n.resolveEndpoint(c.object,d.source.relation),M=["columns",String(A),"relationProperty"];S||Ve([...u,"contents",String(f),...M],"Relation property columns require a relation source"),S.relation.properties?.definitions.some(F=>F.name===y.relationProperty)||Ve([...u,"contents",String(f),...M],`Unknown relation property "${y.relationProperty}"`),g.add({kind:"relation",relation:S.relation.name},"display",M);}),N(d.displayAttributes,h,"display","displayAttributes"),d.descriptionAttribute!==void 0&&g.attribute(h,d.descriptionAttribute,"display",["descriptionAttribute"]),d.filters?.rules.forEach((y,A)=>g.attribute(h,y.attribute,"business",["filters","rules",String(A),"attribute"])),d.sorts?.forEach((y,A)=>g.attribute(h,y.attribute,"business",["sorts",String(A),"attribute"])),d.layout){case "table":case "list":if(d.columnSizing)for(let y of Object.keys(d.columnSizing))g.attribute(h,y,"display",["columnSizing",y]);break;case "kanban":g.attribute(h,d.groupByAttribute,"business",["groupByAttribute"]);break;default:Rn(d);}break}case "form":d.groups.forEach((h,y)=>h.fields.forEach((A,S)=>g.attribute(c.object,A.attribute,"display",["groups",String(y),"fields",String(S),"attribute"])));break;case "richtext":g.attribute(c.object,d.attribute,"source",["attribute"]),d.titleAttribute!==void 0&&g.attribute(c.object,d.titleAttribute,"display",["titleAttribute"]);break;case "documents":N(d.relations,c.object,"business","relations");break;case "forms":d.objectName!==void 0&&g.add({kind:"object",object:d.objectName},"source",["objectName"]);break;case "emails":case "meetings":N(d.emailAttributes,c.object,"business","emailAttributes");break;case "activity":case "custom":break;default:Rn(d);}});}return a(s,"viewReferences"),e.views.forEach((c,u)=>s(c,["views",String(u)])),e.retainedViews?.forEach(({definition:c,layer:u},m)=>s(c,["retainedViews",String(m),"definition"],u)),r}a(QI,"collectSchemaReferences");var O=z.number().finite().nonnegative(),bs=z.enum(_o),Fi=z.enum(Po),Vi=z.enum(Mo),gs=z.object({provider:bs,model:z.string().min(1)}).strict(),rR=z.object({speed:Fi.optional(),reasoning:Vi.optional()}).strict(),ys=z.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),qp=z.object({model:gs.optional(),speed:Fi.optional(),reasoning:Vi.optional(),imageModel:ys.optional()}).strict(),iR=qp.refine(e=>e.model!==void 0||e.speed!==void 0||e.reasoning!==void 0||e.imageModel!==void 0,{message:"At least one inference override is required"}),oR=z.object({model:gs.nullable().optional(),speed:Fi.nullable().optional(),reasoning:Vi.nullable().optional(),imageModel:ys.nullable().optional()}).strict().refine(e=>Object.keys(e).length>0&&Object.values(e).every(t=>t!==void 0),{message:"At least one inference override is required"}),hs=z.object({label:z.string(),denied:z.boolean().optional(),deletion:z.object({target:z.string().optional(),count:O.optional(),restorableDays:O.optional()}).strict().optional(),counts:z.record(z.string(),O).optional(),warnings:z.array(z.string()).optional()}).strict(),zp=z.union([z.object({type:z.literal("text"),text:z.string()}).strict(),z.object({type:z.literal("reasoning"),text:z.string()}).strict(),z.object({type:z.literal("system"),code:z.enum(Fn)}).strict(),z.object({type:z.literal("error"),error:z.string(),errorClass:z.string().optional()}).strict(),z.object({type:z.literal("tool"),toolCallId:z.string(),name:z.string(),args:z.record(z.string(),z.unknown()),result:z.unknown().optional(),error:z.string().optional(),errorCode:z.enum(["output_limit_reached","interrupted"]).optional(),state:z.enum(["streaming","running","completed","error","pending","approval-requested","approval-responded","approval-dispatched"]),durationMs:O.optional(),approvalId:z.string().optional(),approvalImpact:hs.optional(),approved:z.boolean().optional(),approvalReason:z.string().optional(),approvalRelaxableByAuto:z.boolean().optional()}).strict(),z.object({type:z.literal("file"),fileId:z.string(),name:z.string(),mimeType:z.string()}).strict(),z.object({type:z.literal("compaction"),state:z.literal("in-progress"),reason:z.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:O.optional(),reportedTokens:O.optional()}).strict(),z.object({type:z.literal("compaction"),state:z.literal("completed"),tokensBefore:O,tokensAfter:O,tokensSaved:O,strategy:z.enum(["no-op","summary","truncation"]),durationMs:O,summary:z.string().optional()}).strict(),z.object({type:z.literal("compaction"),state:z.literal("failed"),reason:z.string(),durationMs:O.optional()}).strict()]),Wp=z.object({id:z.string(),name:z.string(),mimeType:z.string(),size:O}).strict(),Gp=z.object({id:z.string(),type:z.string().transform(e=>e),entityId:z.string(),label:z.string(),objectName:z.string().optional(),startIndex:O,endIndex:O}).strict(),Kp=z.object({provider:bs,model:z.string(),maxTokens:O.optional(),contextWindow:O.optional()}).strict(),Yp=z.union([z.date(),z.string().datetime({offset:true}).transform(e=>new Date(e))]),fs=z.object({id:z.string(),sessionId:z.string(),tenantId:z.string().optional(),runId:z.string().optional(),role:z.enum(["user","assistant","system","tool"]),parts:z.array(zp),attachments:z.array(Wp).optional(),mentions:z.array(Gp).optional(),model:Kp.optional(),tokenUsage:z.object({input:O,output:O}).strict().optional(),metadata:z.record(z.string(),z.unknown()).optional(),createdAt:Yp}).strict(),Hp=z.object({id:z.string(),description:z.string(),status:z.enum(["pending","in_progress","completed","blocked"]),result:z.string().optional(),updatedAt:O.optional()}).strict(),Jp=z.object({id:z.string(),sessionId:z.string(),status:z.enum(["active","completed","abandoned"]),todos:z.array(Hp),version:O,createdAt:z.string(),updatedAt:z.string(),completedAt:z.string().optional()}).strict(),As={"session-named":z.object({name:z.string()}).strict(),"compaction-start":z.object({reason:z.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:O.optional(),reportedTokens:O.optional()}).strict(),"compaction-end":z.object({tokensBefore:O,tokensAfter:O,tokensSaved:O,strategy:z.enum(["no-op","summary","truncation"]),durationMs:O,summary:z.string().optional()}).strict(),"compaction-failed":z.object({reason:z.string()}).strict(),usage:z.object({messageId:z.string().min(1).optional(),inputTokens:O,outputTokens:O,totalTokens:O,cacheReadTokens:O.optional(),cacheCreationTokens:O.optional(),contextWindow:O,residentTokens:O,utilization:z.number().finite().min(0).max(1),costUsd:O.optional()}).strict(),"message-persisted":z.object({message:fs}).strict(),"message-updated":z.object({message:fs}).strict(),"todo-plan-update":z.object({plan:Jp}).strict(),"approval-context":z.object({approvalId:z.string(),toolCallId:z.string(),impact:hs.optional(),relaxableByAuto:z.boolean().optional()}).strict(),"session-state":z.object({state:z.object({phase:z.enum(["queued","running","parked","terminal"]),parkedOn:z.enum(["human","agents"]).optional(),humanRequestIds:z.array(z.string()).optional(),outcome:z.enum(["completed","failed","cancelled","timeout","expired"]).optional()}).strict(),version:z.number().int().positive(),updatedAt:z.string().datetime({offset:true})}).strict()};function Qp(e){return e in As}a(Qp,"isAgentUIDataName");function Xp(e){return new h("Invalid agent UI message chunk",e.map(t=>({path:t.path.map(String),message:t.message,code:t.code})))}a(Xp,"agentUIValidationError");function Zp(e){if(typeof e!="object"||e===null||typeof e.type!="string")throw new h("Invalid agent UI message chunk",[{path:["type"],message:"Expected UI message chunk type",code:"invalid_type"}]);let t=e.type;if(!t.startsWith("data-"))throw new h("Invalid agent UI message chunk",[{path:["type"],message:"Expected agent data chunk type",code:"invalid_value"}]);let n=t.slice(5);if(!Qp(n))throw new h("Invalid agent UI message chunk",[{path:["type"],message:`Unknown agent UI data type: ${n}`,code:"invalid_value"}]);let r=z.object({type:z.literal(`data-${n}`),id:z.string().optional(),data:As[n],transient:z.boolean().optional()}).strict().safeParse(e);if(!r.success)throw Xp(r.error.issues);return r.data}a(Zp,"assertCustomAgentUIMessageChunk");function aR(e,t,n){return Zp({type:`data-${e}`,...n?.id!==void 0?{id:n.id}:{},data:t,...n?.transient!==void 0?{transient:n.transient}:{}})}a(aR,"agentDataChunk");function Bi(e){return e}a(Bi,"defineOperation");function V(e,t,n){let r=t==="atomic"?"none":t==="local"?"if-not-visible":"follow";return o=>{let a=n?.(o);return {impact:t,navigation:r,focus:{...e(o),...a===void 0?{}:{propertyPath:a}}}}}a(V,"definePresentation");function em(e){return {id:e.id??e.name,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon}}}a(em,"toDraftableObject");function tm(e){let t=e.id??e.name;return (e.attributes??[]).map(n=>nm(n,t))}a(tm,"toDraftableAttributes");function Ee(e){return {id:e.id,name:e.name,label:e.label,type:e.attributeType,...e.config}}a(Ee,"toAttribute");function nm(e,t){let{id:n,name:r,label:o,type:a,...s}=e;return {id:e.id??e.name,objectId:t,name:e.name,label:e.label??e.name,attributeType:e.type,config:s}}a(nm,"toDraftableAttribute");function xs(e){let t=e[0];return t?`{{ ${t.name} }}`:"{{ id }}"}a(xs,"draftedLabelExpression");function Li(e,t){let n=t.filter(r=>r.objectId===e.id);return {id:e.id,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},labelExpression:xs(n),attributes:n.map((r,o)=>{let a=Ee(r);return a.order===void 0?{...a,order:o}:a})}}a(Li,"draftedObjectDefinition");function rm(e,t,n=Et(e.contents)){return structuredClone({...e,...t,authoring:n})}a(rm,"toDraftableView");function ct(e){let{id:t,revision:n,contentIds:r,contentRevisions:o,derived:a,authoring:s,...c}=e;return structuredClone(c)}a(ct,"draftedViewDefinition");function im(e,t){return {...e,...ct(t)}}a(im,"fromDraftableView");var Pt={id:z.string().min(1),objectName:z.string().min(1),viewName:z.string().min(1)},Mt={...Pt,contentName:z.string().min(1)},Is=z.union([z.object({before:z.string().min(1)}).strict(),z.object({after:z.string().min(1)}).strict(),z.object({end:z.literal(true)}).strict()]),Be=a(e=>({objectName:e.objectName,viewName:e.viewName}),"viewFocus"),Ne=a(e=>({...Be(e),contentName:e.contentName}),"contentFocus");function ie(e,t){throw new h(t,[{path:e,message:t}])}a(ie,"invalid");function Te(e,t,n,r){let o=e.views.findIndex(u=>u.object===t.objectName&&u.name===t.viewName);o<0&&ie(["viewName"],"View is not in the draftable state"),e.views[o].authoring||ie(["authoring"],"Missing view authoring baseline");let{derived:a,...s}=r(structuredClone(e.views[o]));s.contents=mi(s.authoring);let c=e.views.map((u,m)=>m===o?s:u);return gi({extensions:[...n.extensions],objects:e.objects.map(u=>Li(u,e.attributes.filter(m=>m.objectId===u.id))),relations:[...e.relations],views:c.map(ct)}),{...e,views:c}}a(Te,"change");function Le(e,t){let n=Object.hasOwn(e.authoring.contents,t)?e.authoring.contents[t]:void 0;return n||ie(["contentName"],"Content is not in the draftable state"),n}a(Le,"contentState");function Ui(e,t,n){for(let r of n)e.authoring[r==="main"?"mainOrderCustomized":"asideOrderCustomized"]=true,t.filter(o=>o.placement===r).forEach((o,a)=>{Le(e,o.name).workspacePosition=a;});}a(Ui,"setOrder");function $i(e,t){let n=e.contents.find(r=>r.name===t);return n||ie(["contentName"],"Content is not in the draftable state"),n}a($i,"find");function Rs(e,t,n){let r=e.filter(s=>s.name!==t.name),o=r.filter(s=>s.placement===t.placement),a=o.length;if(!("end"in n)){let s="before"in n?n.before:n.after;a=o.findIndex(c=>c.name===s),a<0&&ie(["target"],"Order target is not in this placement"),"after"in n&&a++;}return o.splice(a,0,t),t.placement==="main"?[...o,...r.filter(s=>s.placement==="aside")]:[...r.filter(s=>s.placement==="main"),...o]}a(Rs,"placed");var om=z.unknown().transform((e,t)=>{let n=ca$1.safeParse(typeof e=="object"&&e!==null?{...e,name:"candidate"}:e);if(!n.success){for(let a of n.error.issues)t.addIssue({code:"custom",path:a.path,message:a.message});return z.NEVER}if(typeof e=="object"&&e!==null&&"name"in e)return t.addIssue({code:"custom",path:["name"],message:"Content name is the operation target"}),z.NEVER;let{name:r,...o}=n.data;return o}),vs=z.object({...Mt,type:z.literal("replace_view_content"),definition:om}).strict(),am={type:"replace_view_content",schema:vs,focus:Ne,presentation:V(Ne,"local"),describe:a(e=>`Replace ${e.objectName}.${e.viewName}.${e.contentName}`,"describe"),apply:a((e,t,n)=>Te(e,t,n,r=>($i(r,t.contentName).placement!==t.definition.placement&&ie(["definition","placement"],"Use move_view_content to change placement"),Le(r,t.contentName).workspaceDefinition=structuredClone(t.definition),{...r,contents:r.contents.map(a=>a.name===t.contentName?{...t.definition,name:t.contentName}:a),contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}})),"apply")},Cs=z.object({...Pt,type:z.literal("add_view_content"),content:ca$1,target:Is}).strict(),Ts=a(e=>({...Be(e),contentName:e.content.name}),"addFocus"),sm={type:"add_view_content",schema:Cs,focus:Ts,presentation:V(Ts,"structural"),describe:a(e=>`Add ${e.content.name}`,"describe"),apply:a((e,t,n)=>Te(e,t,n,r=>{if(Object.hasOwn(r.authoring.contents,t.content.name))throw new r$1("content",t.content.name);r.authoring.contents={...r.authoring.contents,[t.content.name]:{sourceDefinition:null,workspaceDefinition:Ct(t.content),suppressed:false,sourcePosition:null,workspacePosition:0}};let o=Rs(r.contents,t.content,t.target);return Ui(r,o,[t.content.placement]),{...r,revision:r.revision+1,contents:o,contentIds:{...r.contentIds,[t.content.name]:JSON.stringify(["draft-content",t.id])},contentRevisions:{...r.contentRevisions,[t.content.name]:1}}}),"apply")},Es=z.object({...Mt,type:z.literal("remove_view_content")}).strict(),cm={type:"remove_view_content",schema:Es,focus:Ne,presentation:V(Ne,"structural"),describe:a(e=>`Remove ${e.contentName}`,"describe"),apply:a((e,t,n)=>Te(e,t,n,r=>{let o=$i(r,t.contentName),a=Le(r,t.contentName),s=r.contents.filter(f=>f.name!==t.contentName);if(Ui(r,s,[o.placement]),a.sourceDefinition!==null)return a.workspaceDefinition=null,a.suppressed=true,{...r,revision:r.revision+1,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}};delete r.authoring.contents[t.contentName];let{[t.contentName]:c,...u}=r.contentIds,{[t.contentName]:m,...d}=r.contentRevisions;return {...r,revision:r.revision+1,contents:r.contents.filter(f=>f.name!==t.contentName),contentIds:u,contentRevisions:d}}),"apply")},Ns=z.object({...Mt,type:z.literal("move_view_content"),placement:z.enum(["main","aside"]),target:Is}).strict(),um={type:"move_view_content",schema:Ns,focus:Ne,presentation:V(Ne,"structural"),describe:a(e=>`Move ${e.contentName}`,"describe"),apply:a((e,t,n)=>Te(e,t,n,r=>{let o=$i(r,t.contentName);o.placement!==t.placement&&(Le(r,t.contentName).workspaceDefinition={...Ct(o),placement:t.placement});let a=Rs(r.contents,{...o,placement:t.placement},t.target);return Ui(r,a,[...new Set([o.placement,t.placement])]),{...r,revision:r.revision+1,contents:a,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+ +(o.placement!==t.placement)}}}),"apply")},Ds=z.object({...Pt,type:z.literal("update_view_metadata"),changes:z.object({label:z.string().min(1).optional(),description:z.string().optional(),icon:e.nullable().optional()}).strict().refine(e=>Object.keys(e).length>0)}).strict(),lm={type:"update_view_metadata",schema:Ds,focus:Be,presentation:V(Be,"atomic"),describe:a(e=>`Update ${e.viewName}`,"describe"),apply:a((e,t,n)=>Te(e,t,n,r=>{let{icon:o,...a}=t.changes,s={...r,...a,revision:r.revision+1};if(o===null){let{icon:c,...u}=s;return u}return o===void 0?s:{...s,icon:o}}),"apply")},Os=z.string().refine(e=>e.trim().length>0,"API name must not be blank"),ks=z.object({...Pt,type:z.literal("rename_view"),newName:Os}).strict(),ws=a(e=>({objectName:e.objectName,viewName:e.newName}),"renameViewFocus"),dm={type:"rename_view",schema:ks,focus:ws,presentation:V(ws,"structural"),describe:a(e=>`Rename view ${e.viewName} to ${e.newName}`,"describe"),apply:a((e,t,n)=>Te(e,t,n,r=>t.newName===r.name?r:(r.authoring.origin==="code"&&ie(["newName"],"Source-owned API names must be changed in their declaration"),e.views.some(o=>o.object===t.objectName&&o.name===t.newName)&&ie(["newName"],"View API name is already used"),{...r,name:t.newName,revision:r.revision+1})),"apply")},js=z.object({...Mt,type:z.literal("rename_view_content"),newName:Os}).strict(),Ss=a(e=>({...Be(e),contentName:e.newName}),"renameContentFocus"),pm={type:"rename_view_content",schema:js,focus:Ss,presentation:V(Ss,"structural"),describe:a(e=>`Rename content ${e.contentName} to ${e.newName}`,"describe"),apply:a((e,t,n)=>Te(e,t,n,r=>{let o=Le(r,t.contentName);if(t.newName===t.contentName)return r;o.sourceDefinition!==null&&ie(["newName"],"Source-owned API names must be changed in their declaration"),Object.hasOwn(r.authoring.contents,t.newName)&&ie(["newName"],"Content API name is already used");let a=r.contentIds[t.contentName],s=r.contentRevisions[t.contentName];return delete r.authoring.contents[t.contentName],delete r.contentIds[t.contentName],delete r.contentRevisions[t.contentName],r.authoring.contents={...r.authoring.contents,[t.newName]:o},{...r,revision:r.revision+1,contentIds:{...r.contentIds,[t.newName]:a},contentRevisions:{...r.contentRevisions,[t.newName]:s+1}}}),"apply")},_s=z.object({...Mt,type:z.literal("reset_view_content")}).strict(),mm={type:"reset_view_content",schema:_s,focus:Ne,presentation:V(Ne,"structural"),describe:a(e=>`Reset ${e.contentName} to source`,"describe"),apply:a((e,t,n)=>Te(e,t,n,r=>{let o=Le(r,t.contentName);return o.sourceDefinition===null&&ie(["contentName"],"Content has no source to reset to"),o.workspaceDefinition===null&&!o.suppressed&&o.workspacePosition===null?r:(o.workspaceDefinition=null,o.suppressed=false,o.workspacePosition=null,{...r,revision:r.revision+1,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}})}),"apply")},Ps=z.object({...Pt,type:z.literal("reset_view_order"),placement:z.enum(["main","aside"])}).strict(),fm={type:"reset_view_order",schema:Ps,focus:Be,presentation:V(Be,"structural"),describe:a(e=>`Reset ${e.placement} order`,"describe"),apply:a((e,t,n)=>Te(e,t,n,r=>{let o=t.placement==="main"?"mainOrderCustomized":"asideOrderCustomized";if(!r.authoring[o])return r;r.authoring[o]=false;for(let a of r.contents.filter(s=>s.placement===t.placement)){let s=Le(r,a.name);s.sourceDefinition!==null&&(s.workspacePosition=null);}return {...r,revision:r.revision+1}}),"apply")},qi=z.discriminatedUnion("type",[vs,Cs,Es,Ns,Ds,ks,js,_s,Ps]),ut=[am,sm,cm,um,lm,dm,pm,mm,fm];function Ms(e,t){return e.objects.find(n=>n.id===t)}a(Ms,"findObject");var bm=new Set(["formula","rollup"]);function lt(e){return bm.has(e.attributeType)}a(lt,"isComputedAttribute");var Fs={sum:"number",avg:"number",count:"number",countValues:"number",countUniqueValues:"number",countEmpty:"number",percentEmpty:"number",percentNotEmpty:"number",earliest:"date",latest:"date",original:"multiselect"};function gm(e){return typeof e=="string"&&e in Fs?Fs[e]:void 0}a(gm,"rollupReturnTypeOf");function Bs(e,t){let n=Ms(e,t);if(!n)throw new h(`Object "${t}" is not in the draftable state`,[]);return n}a(Bs,"requireObject");function vn(e){return e.config??{}}a(vn,"configOf");function oe(e){let t=vn(e).targets;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.object=="string"):[]}a(oe,"relationTargets");function dt(e){let t=oe(e).filter(n=>n.object!==ye);return t.length===1?t[0]?.object:void 0}a(dt,"relationTargetObjectName");function ym(e){let t=vn(e),n=e.attributeType,r={name:e.name,type:n,id:e.id},o=t.optionsSource;if(n==="relation"){let a=dt(e);return {...r,...t.cardinality==="one"||t.cardinality==="many"?{cardinality:t.cardinality}:{},...a===void 0?{}:{targetObjectName:a},targets:oe(e)}}if(n==="formula")return {...r,...t.returnType===void 0?{}:{returnType:t.returnType},...o===void 0?{}:{optionsSource:o}};if(n==="rollup"){let a=gm(t.function);return {...r,...a===void 0?{}:{returnType:a},...o===void 0?{}:{optionsSource:o}}}return n==="select"||n==="status"||n==="multiselect"?{...r,...Array.isArray(t.options)?{options:t.options}:{}}:r}a(ym,"toCompileAttribute");function Vs(e,t){return {objectName:e.name,attributes:t.filter(n=>n.objectId===e.id).map(ym)}}a(Vs,"toCompileObject");function zi(e,t){let n=Bs(e,t);return {...Vs(n,e.attributes),relatedObjects:Object.fromEntries(e.objects.map(r=>[r.name,Vs(r,e.attributes)]))}}a(zi,"computedCompileSchemaOf");function hm(e){return {id:e.id,name:e.name,label:e.label,type:"rollup",...vn(e)}}a(hm,"toRollupAttribute");function Ls(e){try{return e()}catch(t){throw t instanceof I?new h(t.message,[]):t}}a(Ls,"asValidationError");function Cn(e,t){let n=zi(e,t.objectId);return Ls(()=>Us(t,n))}a(Cn,"computedPlanOf");function Us(e,t){if(e.attributeType==="rollup")return qa(hm(e),t);let n=vn(e);return fn({attributeName:e.name,expression:String(n.expression??""),returnType:n.returnType,schema:t})}a(Us,"compilePlan");function Wi(e){Ls(()=>Ba(e.map(t=>({attributeName:t.attributeName,dependencies:t.dependencies}))));}a(Wi,"assertAcyclicComputed");function Am(e,t){switch(e.kind){case "local":case "computed":return e.attributeName===t;case "relation":return e.relationName===t;case "options":return false;default:return e}}a(Am,"dependencyNames");function Ft(e,t){let n=zi(e,t),r=[];for(let o of e.attributes)if(!(o.objectId!==t||!lt(o)))try{r.push(Us(o,n));}catch(a){if(!(a instanceof I))throw a}return r}a(Ft,"compilablePlansOf");function Gi(e,t,n){let r=Bs(e,t),o=[];for(let a of Ft(e,t))a.attributeName!==n&&a.dependencies.some(s=>Am(s,n))&&o.push(a.attributeName);for(let a of e.objects)if(a.id!==t)for(let s of Ft(e,a.id))s.dependencies.some(u=>{if(u.kind!=="relation"||u.targetAttributeName!==n)return false;let m=e.attributes.find(d=>d.objectId===a.id&&d.name===u.relationName&&d.attributeType==="relation");return m!==void 0&&dt(m)===r.name})&&o.push(`${a.name}.${s.attributeName}`);return o}a(Gi,"dependentsOf");function Vt(e){let t=e.config?.bilateral;if(typeof t!="object"||t===null)return;let{object:n,attribute:r}=t;return typeof n=="string"&&typeof r=="string"?{object:n,attribute:r}:void 0}a(Vt,"bilateralDeclarationOf");function xm(e,t){return t!==void 0&&e.attributeType===t.attributeType&&Tm(e,t)}a(xm,"sameAttribute");function Tm(e,t){return JSON.stringify(e.config??{})===JSON.stringify(t.config??{})}a(Tm,"sameConfig");function wm(e,t){let n=a(r=>xm(r,e.attributes.find(o=>o.id===r.id)),"untouched");for(let r of t.attributes){if(r.attributeType!=="relation")continue;let o=Vt(r);if(o===void 0||n(r))continue;let s=t.objects.find(N=>N.id===r.objectId)?.name??r.objectId,c=t.objects.find(N=>N.name===o.object),u=t.attributes.find(N=>N.objectId===c?.id&&N.name===o.attribute),m=`relation "${s}.${r.name}" declares inverse "${o.object}.${o.attribute}"`;if(u===void 0)throw new h(`${m}, which object "${o.object}" does not have; draft it first`,[]);if(u.attributeType!=="relation")throw new h(`${m}, which is not a relation`,[]);let d=Vt(u);if(!(oe(u).some(N=>N.object===s)&&(n(u)?d===void 0||d.object===s&&d.attribute===r.name:d?.object===s&&d.attribute===r.name)))throw new h(`${m}, which does not point back to "${s}.${r.name}"`,[])}}a(wm,"assertBilateralPairs");var Sm=0x100000001b3n,Im=0xffffffffffffffffn;function $s(e,t){let n=t;for(let r of new TextEncoder().encode(e))n^=BigInt(r),n=n*Smℑreturn n}a($s,"fnv1a64");function Ki(e,t){let n=`${e.toLowerCase()}:${t}`,r=$s(n,0xcbf29ce484222325n).toString(16).padStart(16,"0"),o=$s(`${t}:${n}`,0x84222325cbf29ce4n).toString(16).padStart(16,"0"),a=r+o,s=(Number.parseInt(a[16],16)&3|8).toString(16);return [a.slice(0,8),a.slice(8,12),`8${a.slice(13,16)}`,`${s}${a.slice(17,20)}`,a.slice(20,32)].join("-")}a(Ki,"viewIdFor");function Ue(e){return {list:Ki(e,"list"),detail:Ki(e,"detail")}}a(Ue,"defaultViewIdsFor");function Yi(e,t,n,r){let a=r.filter(c=>c.objectId===n.id).filter(c=>j$2(Ee(c)).presentation.formField).map(c=>({attribute:c.name})),s=e==="collection"?[{name:"all",type:"collection",placement:"main",label:"All",layout:"table",source:{object:n.name}}]:a.length?[{name:"form",type:"form",placement:"main",label:"Details",groups:[{name:"general",label:"General",fields:a}]}]:[{name:"activity",type:"activity",placement:"main",label:"Activity"}];return {id:t,object:n.name,name:e==="collection"?"default_list":"default_detail",label:n.label,context:e,default:true,contents:s,authoring:Et(s),revision:1,contentIds:Object.fromEntries(s.map(c=>[c.name,JSON.stringify(["draft-content",t,c.name])])),contentRevisions:Object.fromEntries(s.map(c=>[c.name,1])),derived:true}}a(Yi,"derivedView");function Hi(e,t){let n=Ue(e.id);return [Yi("collection",n.list,e,t),Yi("record",n.detail,e,t)]}a(Hi,"defaultViewsFor");function Ji(e,t,n){return Yi(e.context,e.id,t,n)}a(Ji,"regenerateDerived");var qs={id:z.string().min(1)};function pt(e,t){let n=e.objects.find(r=>r.id===t);if(!n)throw new h(`Object "${t}" is not in the draftable state`,[]);return n}a(pt,"requireObject");function Qi(e,t,n){return {...e,attributes:[...n],views:e.views.map(r=>r.derived&&r.object===t.name?Ji(r,t,n):r)}}a(Qi,"withDerivedViews");function En(e){return {objectId:e.objectId}}a(En,"objectFocus");function Nn(e){return {objectId:e.objectId,recordId:e.recordId}}a(Nn,"recordFocus");function zs(e){return {objectId:e.objectId,attributeId:e.attributeId}}a(zs,"attributeFocus");function Dn(e){return {objectId:e.objectId,attributeName:e.attribute}}a(Dn,"existingAttributeFocus");function vm(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}a(vm,"firstChangedProperty");function Cm(e,t){if(!e.derived)for(let n of e.contents){if(n.type==="collection"&&(n.columns?.includes(t)||n.displayAttributes?.includes(t)||n.sorts?.some(r=>r.attribute===t)))return `content "${n.name}"`;if(n.type==="form"&&n.groups.some(r=>r.fields.some(o=>o.attribute===t)))return `content "${n.name}"`;if(n.type==="richtext"&&(n.attribute===t||n.titleAttribute===t))return `content "${n.name}"`}}a(Cm,"handShapedUse");function Em(e,t,n){let r=n.config??{},o=n.name;if(r.relationPath!==void 0)throw new h(`rollup "${o}": relationPath is not supported yet`,[]);let a=r.relationAttribute;if(typeof a!="string"||a.length===0)throw new h(`rollup "${o}" needs a relation attribute; none is configured on object "${t.name}"`,[]);let s=e.attributes.find(f=>f.objectId===t.id&&f.name===a&&f.attributeType==="relation");if(!s)throw new h(`rollup "${o}" needs a relation attribute; "${a}" is not a relation of object "${t.name}"`,[]);let c=dt(s);if(c===void 0){let f=oe(s).filter(g=>g.object!=="*").length;throw new h(`rollup "${o}" needs a relation with one target object; "${a}" targets ${f}`,[])}if(r.function==="count")return;let u=e.objects.find(f=>f.name===c),m=r.targetAttribute;if(!(u!==void 0&&e.attributes.some(f=>f.objectId===u.id&&f.name===m)))throw new h(`rollup "${o}" targets attribute "${m}", which object "${c}" does not have`,[])}a(Em,"assertRollupShape");function Nm(e,t){let n=e.config??{};if(e.attributeType==="rollup")return n.relationAttribute===t;let r=typeof n.expression=="string"?n.expression:"";return new RegExp(`(^|[^A-Za-z0-9_])${t}\\.`).test(r)}a(Nm,"traversesRelation");function Gs(e,t){let n=pt(e,t.objectId);if(t.attributeType==="relation"){for(let o of oe(t))if(o.object!==ye&&!e.objects.some(a=>a.name===o.object))throw new h(`object "${o.object}" is unknown; create it first`,[]);let r=Vt(t)?.object;if(r!==void 0&&r!==ye&&!e.objects.some(o=>o.name===r))throw new h(`object "${r}" is unknown; create it first`,[]);for(let o of e.attributes)o.objectId!==t.objectId||!lt(o)||Nm(o,t.name)&&Cn(e,o);}else if(lt(t))t.attributeType==="rollup"&&Em(e,n,t),Cn(e,t);else return;Wi(Ft(e,t.objectId));}a(Gs,"assertConfigFolds");var $e={...qs,objectId:z.string().uuid()},Dm=z.object({...$e,type:z.literal("add_object"),name:Zt,label:z.string().min(1),icon:z.string().min(1).optional()}),Om={type:"add_object",schema:Dm,apply:a((e,t)=>{if(e.objects.some(r=>r.name===t.name))throw new h(`Object "${t.name}" already exists`,[]);if(e.objects.some(r=>r.id===t.objectId))throw new h(`Object id "${t.objectId}" is already taken`,[]);let n={id:t.objectId,name:t.name,label:t.label,...t.icon===void 0?{}:{icon:t.icon}};return {...e,objects:[...e.objects,n],views:[...e.views,...Hi(n,e.attributes)]}},"apply"),focus:En,presentation:V(En,"structural"),describe:a(e=>`Cr\xE9e l'objet \xAB ${e.label} \xBB`,"describe")},km=z.object({...$e,type:z.literal("update_object"),changes:z.object({label:z.string().min(1).optional(),icon:z.string().min(1).optional()}).refine(e=>Object.keys(e).length>0,"update_object needs at least one change")}),Ws=a(e=>({objectId:e.objectId}),"updateObjectFocus"),jm={type:"update_object",schema:km,apply:a((e,t)=>(pt(e,t.objectId),{...e,objects:e.objects.map(n=>n.id===t.objectId?{...n,...t.changes}:n)}),"apply"),focus:Ws,presentation:V(Ws,"atomic",vm),describe:a(e=>e.changes.label?`Renomme l'objet en \xAB ${e.changes.label} \xBB`:"Modifie l'objet","describe")},_m=z.object({...$e,type:z.literal("remove_object")}),Pm={type:"remove_object",schema:_m,apply:a((e,t)=>{pt(e,t.objectId);let n=e.objects.find(r=>r.id===t.objectId)?.name;for(let r of e.attributes){if(r.objectId===t.objectId||r.attributeType!=="relation"||!oe(r).some(a=>a.object===n))continue;let o=e.objects.find(a=>a.id===r.objectId);throw new h(`object "${n}" is targeted by attribute "${o?.name}.${r.name}"; remove that attribute first`,[])}return {...e,objects:e.objects.filter(r=>r.id!==t.objectId),attributes:e.attributes.filter(r=>r.objectId!==t.objectId),sampleRecords:e.sampleRecords.filter(r=>r.objectId!==t.objectId),views:e.views.filter(r=>r.object!==n)}},"apply"),focus:En,presentation:V(En,"structural"),describe:a(e=>`Supprime l'objet ${e.objectId}`,"describe")},Ks=Kt;function Ys(e,t){try{x(e,t);}catch(n){throw n instanceof h?new h(n.message,n.errors.map(r=>({...r,path:["config",...r.path??[]]}))):n}}a(Ys,"assertConfigParses");var Mm=z.object({...$e,type:z.literal("add_attribute"),attributeId:z.string().min(1),name:Gn,label:z.string().min(1),attributeType:z.enum(Ks),config:z.record(z.string(),z.unknown()).optional()}).superRefine((e,t)=>{try{Ys(e.attributeType,e.config??{});}catch(n){if(n instanceof h){for(let r of n.errors)t.addIssue({code:"custom",message:r.message,path:[...r.path]});return}throw n}}),Fm={type:"add_attribute",schema:Mm,apply:a((e,t)=>{let n=pt(e,t.objectId);if(e.attributes.some(s=>s.objectId===t.objectId&&s.name===t.name))throw new h(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);let r={id:t.attributeId,objectId:t.objectId,name:t.name,label:t.label,attributeType:t.attributeType,...t.config===void 0?{}:{config:t.config}};for(let s of e.sampleRecords)s.objectId===t.objectId&&Qs(s.id,r,s.values);let o=[...e.attributes,r],a=Qi(e,n,o);return Gs(a,r),a},"apply"),focus:zs,presentation:V(zs,"local"),describe:a(e=>`Ajoute l'attribut \xAB ${e.label} \xBB`,"describe")},Hs={...$e,attribute:Gn};function Js(e,t,n,r){let o=pt(e,t);if(n===void 0)throw new h(`${r} now addresses the attribute by name; remove this operation and append it again with "attribute"`,[]);let a=e.attributes.find(s=>s.objectId===t&&s.name===n);if(!a)throw new h(`Attribute "${n}" is not on object "${t}"`,[]);return {object:o,attribute:a}}a(Js,"requireAttribute");var Vm=z.object({...Hs,type:z.literal("update_attribute"),changes:z.object({label:z.string().min(1).optional(),config:z.record(z.string(),z.unknown()).optional()}).refine(e=>Object.keys(e).length>0,"update_attribute needs at least one change")}),Bm={type:"update_attribute",schema:Vm,apply:a((e,t)=>{let{object:n,attribute:r}=Js(e,t.objectId,t.attribute,"update_attribute");t.changes.config!==void 0&&Ys(r.attributeType,t.changes.config);let o={...r,...t.changes},a=e.attributes.map(c=>c===r?o:c),s=Qi(e,n,a);return Gs(s,o),s},"apply"),focus:Dn,presentation:V(Dn,"atomic"),describe:a(e=>e.changes.label?`Renomme l'attribut \xAB ${e.attribute} \xBB en \xAB ${e.changes.label} \xBB`:`Modifie l'attribut \xAB ${e.attribute} \xBB`,"describe")},Lm=z.object({...Hs,type:z.literal("remove_attribute")}),Um={type:"remove_attribute",schema:Lm,apply:a((e,t)=>{let{object:n,attribute:r}=Js(e,t.objectId,t.attribute,"remove_attribute"),[o]=Gi(e,t.objectId,r.name);if(o!==void 0)throw new h(`attribute "${r.name}" is used by "${o}"; remove that first`,[]);for(let u of e.views){if(u.object!==n.name)continue;let m=Cm(u,r.name);if(m!==void 0)throw new h(`attribute "${r.name}" is used by view "${u.id}" (${m}); remove it from the view first`,[])}let a=e.sampleRecords.find(u=>u.objectId===r.objectId&&r.name in u.values);if(a)throw new h(`Attribute "${r.name}" is still used by sample record "${a.id}"`,[]);let s=e.attributes.filter(u=>u!==r),c={...e,views:e.views.map(u=>u)};return Qi(c,n,s)},"apply"),focus:Dn,presentation:V(Dn,"local"),describe:a(e=>`Supprime l'attribut \xAB ${e.attribute} \xBB`,"describe")};function $m(e,t,n,r){let o=Ee(n);try{c$1(o);}catch{return}let a=g$1(o,r);if(a.success)return;let s=a.errors??[],c=s.map(u=>u.path.length>1?`${u.path.join(".")}: ${u.message}`:u.message).join(", ");throw new h(`Sample record "${e}" has an invalid value for "${t}": ${c}`,s.map(u=>({path:u.path,message:u.message})))}a($m,"assertSampleValue");function Qs(e,t,n){if(t.config?.required===true&&t.config?.defaultValue===void 0&&!(t.name in n&&n[t.name]!==void 0))throw new h(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}a(Qs,"assertRequiredCovered");function Xi(e){return (Array.isArray(e)?e:[e]).flatMap(n=>{if(typeof n=="string")return [n];if(typeof n=="object"&&n!==null){let r=n.id;if(typeof r=="string")return [r]}return []})}a(Xi,"relationValueIds");function qm(e,t,n,r){if(n.attributeType!=="relation"||r===void 0||r===null)return;let o=dt(n),a=e.objects.find(c=>c.name===o);if(!a)return;let s=e.views.some(c=>c.id===Ue(a.id).list);for(let c of Xi(r)){let u=e.sampleRecords.find(d=>d.id===c);if(u?.objectId!==a.id&&(u!==void 0||s))throw new h(`sample record "${t}" references unknown sample "${c}"`,[])}}a(qm,"assertUnknownSampleReference");var zm=z.object({...$e,type:z.literal("add_sample_record"),recordId:z.string().uuid(),values:z.record(z.string(),z.unknown()),publication:z.enum(["preview","requested-data"]).optional()}),Wm={type:"add_sample_record",schema:zm,apply:a((e,t)=>{if(pt(e,t.objectId),e.sampleRecords.some(r=>r.id===t.recordId))throw new h(`Sample record "${t.recordId}" already exists`,[]);let n=new Map(e.attributes.filter(r=>r.objectId===t.objectId).map(r=>[r.name,r]));for(let[r,o]of Object.entries(t.values)){let a=n.get(r);if(!a)throw new h(`Sample record "${t.recordId}" uses unknown attribute "${r}"`,[]);if(lt(a))throw new h(`attribute "${a.name}" is computed and cannot be set on a sample record`,[]);qm(e,t.recordId,a,o),$m(t.recordId,r,a,o);}for(let r of n.values())Qs(t.recordId,r,t.values);return {...e,sampleRecords:[...e.sampleRecords,{id:t.recordId,objectId:t.objectId,values:t.values,...t.publication===void 0?{}:{publication:t.publication}}]}},"apply"),focus:Nn,presentation:V(Nn,"local"),describe:a(()=>"Ajoute un exemple","describe")};function Gm(e,t){return new Set(e.attributes.filter(n=>n.objectId===t&&n.attributeType==="relation").map(n=>n.name))}a(Gm,"relationNamesOf");function Km(e,t){for(let n of e.sampleRecords){if(n.id===t)continue;let r=Gm(e,n.objectId);for(let[o,a]of Object.entries(n.values))if(r.has(o)&&Xi(a).includes(t))throw new h(`sample record "${t}" is referenced by sample record "${n.id}"; remove that first`,[])}}a(Km,"assertSampleNotReferenced");var Ym=z.object({...$e,type:z.literal("remove_sample_record"),recordId:z.string().min(1)}),Hm={type:"remove_sample_record",schema:Ym,apply:a((e,t)=>{if(!e.sampleRecords.some(n=>n.id===t.recordId&&n.objectId===t.objectId))throw new h(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,[]);return Km(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(n=>n.id!==t.recordId)}},"apply"),focus:Nn,presentation:V(Nn,"local"),describe:a(()=>"Retire un exemple","describe")},mt=[Om,jm,Pm,Fm,Bm,Um,Wm,Hm];function Jm(){let e=new Map;for(let t of [...mt,...ut]){if(e.has(t.type))throw new r$1("architect operation",t.type);e.set(t.type,t);}return e}a(Jm,"build");var Bt=Jm(),Qm=[...Bt.keys()];function Lt(e){let t=Bt.get(e.type);if(!t)throw new h(`Operation "${e.id}" has unknown type "${e.type}"`,[]);return t}a(Lt,"defOf");function Zi(e,t,n={extensions:[]}){return t.reduce((r,o)=>Lt(o).apply(r,o,n),e)}a(Zi,"applyOperations");function eo(e){return Lt(e).focus(e)}a(eo,"focusOf");function Xm(e,t){return e.map(n=>Lt(n).describe(n,t))}a(Xm,"describeOperations");function Zm(e){if(typeof e!="object"||e===null||!("type"in e))throw new h("An operation must be an object carrying a type",[]);let t=e.type;if(typeof t!="string")throw new h("An operation's type must be a string",[]);let n=Bt.get(t);if(!n)throw new h(`Unknown operation type "${t}"`,[]);let r=n.schema.safeParse(e);if(!r.success)throw new h(`Operation "${t}" is invalid: ${r.error.issues.map(o=>`${o.path.join(".")} ${o.message}`).join("; ")}`,[]);return r.data}a(Zm,"parseOperation");var ft=a(e=>z.tuple([z.literal(e),z.string()]),"pair"),ef=z.union([z.tuple([z.literal("content"),z.string(),z.string(),z.string()]),z.tuple([z.literal("view"),z.string(),z.string()]),z.tuple([z.literal("attribute"),z.string(),z.string()]),z.tuple([z.literal("sample"),z.string(),z.string()]),ft("object"),ft("object-name"),ft("object-schema"),ft("object-tree"),ft("attribute-id"),ft("relation")]);function Ut(e){return e.viewName&&e.objectName?JSON.stringify(e.contentName?["content",e.objectName,e.viewName,e.contentName]:["view",e.objectName,e.viewName]):e.attributeName&&e.objectId?JSON.stringify(["attribute",e.objectId,e.attributeName]):e.attributeId?JSON.stringify(["attribute-id",e.attributeId]):e.recordId&&e.objectId?JSON.stringify(["sample",e.objectId,e.recordId]):e.objectId?JSON.stringify(["object",e.objectId]):e.objectName?JSON.stringify(["object-name",e.objectName]):null}a(Ut,"proposalTargetKey");function Xs(e,t,n,r,o){if(n&&typeof n=="object")if("source"in n&&n.source&&typeof n.source=="object"){if("object"in n.source&&typeof n.source.object=="string"&&o(n.source.object),"relation"in n.source&&typeof n.source.relation=="string"){let a=n.source.relation,s=e.relations.find(c=>c.endpoints.some(u=>u.object===t&&u.name===a));if(s){r("relation",s.name);let c=s.endpoints.findIndex(u=>u.object===t&&u.name===a);o(s.endpoints[c===0?1:0].object);}else o(t);}}else "type"in n&&n.type==="forms"?o("objectName"in n&&typeof n.objectName=="string"?n.objectName:t):"type"in n&&["form","richtext","emails","meetings","documents"].includes(String(n.type))&&o(t);}a(Xs,"addContentDependencies");function tf(e,t){let n=new Set,r=a((...a)=>n.add(JSON.stringify(a)),"add"),o=a(a=>{let s=e.objects.find(c=>c.name===a);s?r("object-schema",s.id):r("object-name",a);},"schemaFor");for(let a of t){let s=eo(a);if(a.type==="rename_view"||a.type==="rename_view_content"){let d=qi.parse(a),f=Ut({objectName:d.objectName,viewName:d.viewName,...d.type==="rename_view_content"?{contentName:d.contentName}:{}});f&&n.add(f);}let c=Ut(s);if(c&&n.add(c),s.viewName&&s.objectName){a.type!=="replace_view_content"&&r("view",s.objectName,s.viewName);let d=e.objects.find(f=>f.name===s.objectName);if(d?r("object",d.id):r("object-name",s.objectName),Xs(e,s.objectName,a.definition??a.content,r,o),a.type==="reset_view_content"&&typeof a.contentName=="string"){let f=e.views.find(g=>g.object===a.objectName&&g.name===a.viewName);Xs(e,s.objectName,f?.authoring.contents[a.contentName]?.sourceDefinition,r,o);}}s.objectId&&r("object",s.objectId),s.objectId&&(a.type==="remove_object"||a.type.includes("sample_record"))&&r("object-tree",s.objectId),a.type==="add_object"&&typeof a.name=="string"&&r("object-name",a.name);let u=a.changes&&typeof a.changes=="object"?a.changes:null,m=a.type==="add_attribute"?a.config:u&&"config"in u?u.config:null;if(m&&typeof m=="object"&&"targets"in m&&Array.isArray(m.targets))for(let d of m.targets)d&&typeof d.object=="string"&&d.object!=="*"&&r("object-name",d.object);}return [...n]}a(tf,"requiredTargetKeys");function nf(e,t){return Object.fromEntries(t.map(n=>[n,b$3(On(e,n))]))}a(nf,"targetTokensFor");function On(e,t){let n;try{n=JSON.parse(t);}catch{throw new h(`Invalid proposal target key "${t}"`,[])}let r=ef.safeParse(n);if(!r.success)throw new h(`Invalid proposal target key "${t}"`,[]);let[o,a,s,c]=r.data,u=e.objects.find(f=>f.id===a);if(o==="object")return u??null;if(o==="object-name")return e.objects.find(f=>f.name===a)??null;if(o==="relation")return e.relations.find(f=>f.name===a)??null;if(o==="attribute-id")return e.attributes.find(f=>f.id===a)??null;if(o==="attribute")return e.attributes.find(f=>f.objectId===a&&f.name===s)??null;if(o==="sample")return e.sampleRecords.find(f=>f.objectId===a&&f.id===s)??null;if(o==="object-schema"||o==="object-tree"){if(!u)return null;let f=e.attributes.filter(g=>g.objectId===a);return o==="object-schema"?{object:u,attributes:f.toSorted((g,N)=>g.name.localeCompare(N.name))}:{object:u,attributes:f,views:e.views.filter(g=>g.object===u.name),sampleRecords:e.sampleRecords.filter(g=>g.objectId===a)}}let m=e.views.find(f=>f.object===a&&f.name===s);if(!m)return null;if(o==="view")return {id:m.id,revision:m.revision,definition:{...ct(m),contents:m.contents.map(({name:f,placement:g})=>({name:f,placement:g}))}};let d=m.contents.find(f=>f.name===c);return c!==void 0&&Object.hasOwn(m.contentIds,c)?{id:m.contentIds[c],revision:m.contentRevisions[c],definition:d??null}:null}a(On,"targetSnapshot");function to(e){return Lt(e).presentation(e)}a(to,"presentationOf");function rf(e){let t=e.map(to);return new Set(t.map(({focus:r})=>r.viewName?JSON.stringify([r.objectName,r.viewName]):r.objectId).filter(r=>r!==void 0)).size>1||t.some(({impact:r})=>r==="structural")?"structural":t.some(({impact:r})=>r==="local")?"local":"atomic"}a(rf,"episodeImpactOf");function Zs(e,t){let n=Ut(t);return n===null?null:On(e,n)}a(Zs,"snapshotArchitectTarget");function of(e,t,n={extensions:[]}){let r=e;return t.map(o=>{let a=to(o),s=Zs(r,a.focus);r=Zi(r,[o],n);let c=Zs(r,a.focus);return {operationId:o.id,operationType:o.type,presentation:a,before:s,after:c}})}a(of,"deriveArchitectChanges");var ae=z.string().min(1),af=z.union([z.object({objectName:ae,viewName:ae,contentName:ae.optional()}).strict(),z.object({objectId:ae}).strict(),z.object({objectName:ae}).strict(),z.object({objectId:ae,attributeName:ae}).strict(),z.object({objectId:ae,attributeId:ae}).strict(),z.object({objectId:ae,recordId:ae}).strict()]);function sf(e){let t=af.safeParse(e);if(!t.success)throw new h("Invalid scoped target",[{path:["target"],message:"Expected exactly one named target branch"}]);return t.data}a(sf,"parseNamedTarget");var tc=z.object({type:z.literal("remove_operation"),operationId:z.string().min(1).describe("The id of a stored operation to drop from the draft")});function nc(e,t=[]){return [...e.map(n=>n.schema),...t].map(uf)}a(nc,"membersOf");function kn(e){return z.discriminatedUnion("type",e)}a(kn,"unionOf");function cf(e){return e instanceof z.ZodString&&e.format==="uuid"}a(cf,"isUuidString");function uf(e){let t={};for(let[n,r]of Object.entries(e.shape)){if(!cf(r))continue;let o=z.string().min(1);t[n]=r.description===void 0?o:o.describe(r.description);}return Object.keys(t).length===0?e:e.safeExtend(t)}a(uf,"relaxUuidKeys");var lf={add_object:["objectId"],add_sample_record:["recordId"]};function ec(e){let t={};for(let n of lf[e.shape.type.value]??[]){let r=e.shape[n];r instanceof z.ZodString&&(t[n]=r.optional());}return Object.keys(t).length===0?e:e.safeExtend(t)}a(ec,"relaxMintedKeys");var rc=nc(mt,[tc]),ic=nc(ut),oc=kn(rc),ac=kn(ic),df={schema:oc,view:ac},pf={schema:kn(rc.map(ec)),view:kn(ic.map(ec))},mf=new Map([...mt.map(e=>[e.type,"schema"]),["remove_operation","schema"],...ut.map(e=>[e.type,"view"])]);function ff(e){return mf.get(e)??null}a(ff,"familyOf");function bf(e){let t=[];for(let n of e.objects){let r=e.views.filter(o=>o.object===n.name&&o.context==="collection").flatMap(o=>o.contents).filter(o=>o.type==="collection");r.length===0&&t.push(`Object "${n.label}" has no collection content: add_view_content.`);for(let o of e.attributes.filter(a=>a.objectId===n.id))j$2(Ee(o)).presentation.tableCell&&r.length&&!r.some(a=>a.columns?.includes(o.name))&&t.push(`Attribute "${o.label}" on "${n.label}" is in no collection column set: replace_view_content.`),o.attributeType==="document"&&!e.views.some(a=>a.object===n.name&&a.contents.some(s=>s.type==="documents"))&&t.push(`Object "${n.label}" has no documents content: add_view_content.`);}return t}a(bf,"stillMissing");function gf(e){let t=e.config??{};if(e.attributeType==="relation")return `\u2192 ${oe(e).map(n=>n.object).join("|")}`;if(e.attributeType==="formula")return typeof t.expression=="string"?t.expression:void 0;if(e.attributeType==="rollup")return t.function==="count"?`count(${t.relationAttribute})`:`${t.function}(${t.relationAttribute}.${t.targetAttribute})`}a(gf,"attributeDetail");function yf(e){let t=e.config?.options,n=gf(e);return {name:e.name,label:e.label,type:e.attributeType,...Array.isArray(t)?{options:t.map(r=>r.value)}:{},...n===void 0?{}:{detail:n}}}a(yf,"summarizeAttribute");function hf(e,t,n){let r=Ue(e.id),o=n.some(a=>a.id===r.list);return {id:e.id,name:e.name,label:e.label,attributes:t.filter(a=>a.objectId===e.id).map(yf),...o?{viewIds:r}:{}}}a(hf,"summarizeObject");function Af(e,t){if(!t.some(n=>n.name===e.object))throw new h(`View "${e.name}" names an object outside the draft scope`,[]);return {id:e.id,name:e.name,context:e.context,objectName:e.object,label:e.label,derived:e.derived===true,contents:e.contents.map(({name:n,type:r,placement:o,label:a})=>({name:n,type:r,placement:o,label:a}))}}a(Af,"summarizeView");function xf(e,t){let n=new Map;for(let r of e.sampleRecords)n.set(r.objectId,(n.get(r.objectId)??0)+1);return {objects:e.objects.map(r=>hf(r,e.attributes,e.views)),views:e.views.map(r=>Af(r,e.objects)),sampleRecords:[...n.entries()].map(([r,o])=>({objectId:r,count:o})),operationCount:t}}a(xf,"summarizeDraft");var Tf=["draft_schema"],wf="publish_architect_draft",Sf="discard_architect_draft",If="request_design_review",Rf="get_architect_draft";var Q=z.string().refine(e=>e.trim().length>0,"Must not be blank"),sc=z.union([z.tuple([z.literal("object"),Q]),z.tuple([z.literal("attribute"),Q,Q]),z.tuple([z.literal("relation"),Q]),z.tuple([z.literal("view"),Q,Q]),z.tuple([z.literal("content"),Q,Q,Q])]),vf=z.object({label:Q,pluralLabel:z.string().optional(),description:z.string().optional(),icon:e.optional(),labelExpression:z.string(),embeddingExpression:z.string().optional(),sealed:z.boolean().optional(),toleratedAttributes:z.array(Q).optional(),metadata:z.record(z.string(),z.unknown()).optional(),schema_version:z.number().int().nonnegative(),migrations:z.array(z.record(z.string(),z.unknown())),documentLayout:z.record(z.string(),z.unknown()).optional()}).strict();function ze(e){throw new h(e,[])}a(ze,"failure");function Cf(e$1){return z.custom(t=>{let n=z.record(z.string(),z.unknown()).parse(t);for(let r of e$1[0]==="view"?["object","name"]:["name"])Object.hasOwn(n,r)&&ze(`Invalid schema state: unrecognized definition key ${r}`);switch(e$1[0]){case "object":vf.parse(n);break;case "attribute":{let r=z.enum(Kt).parse(n.type);u(r).extend({type:z.literal(r),label:Q,required:z.boolean().optional(),unique:z.boolean().optional(),icon:e.optional()}).strict().parse(n);break}case "relation":Qe({...n,name:e$1[1]});break;case "view":{let{contents:r,...o}=n,a=z.array(Q).parse(r);new Set(a).size!==a.length&&ze("Invalid schema state: duplicate content membership"),da$1.parse({...o,object:e$1[1],name:e$1[2],contents:[]});break}case "content":ca$1.parse({...n,name:e$1[3]});break}return true})}a(Cf,"definitionSchema");function jn(e,t){let n=JSON.stringify(e.address),r=JSON.stringify(t.address);return n<r?-1:n>r?1:0}a(jn,"compareSchemaStateEntries");function Ef(e){return {modelVersion:1,hashVersion:1,entries:[...e].sort(jn).filter(t=>t.source!==null).map(({address:t,source:n})=>({address:t,source:n}))}}a(Ef,"schemaStateSourcePayload");function Nf(e){let t=z.record(z.string(),z.unknown()).parse(e);for(let[a,s]of [["modelVersion","model"],["hashVersion","hash"]])t[a]!==1&&ze(`Unsupported schema ${s} version: expected 1, received ${t[a]===void 0?"missing":String(t[a])}`);let n=z.object({modelVersion:z.literal(1),hashVersion:z.literal(1),tenant:Q,sourceFingerprint:z.string().regex(/^[a-f0-9]{64}$/),entries:z.array(z.unknown())}).strict().safeParse(e);if(!n.success){let a=n.error.issues.find(s=>s.code==="unrecognized_keys");throw a?.code==="unrecognized_keys"&&ze(`Invalid schema state: unrecognized key ${a.keys[0]}`),h.fromZodErrors(n.error.issues.map(s=>({path:s.path.map(String),message:s.message})))}let r=new Set,o=n.data.entries.map(a=>{let s=sc.parse(z.object({address:z.unknown()}).parse(a).address),c=JSON.stringify(s);r.has(c)&&ze(`Invalid schema state: duplicate address ${c}`),r.add(c);let u=Cf(s).nullable(),m=s[0]==="object"||s[0]==="attribute"?z.object({id:z.string().uuid(),updatedAt:z.string().datetime()}).strict():z.object({id:z.string().uuid(),revision:z.number().int().nonnegative()}).strict(),d=z.object({address:sc,source:u,effective:u,status:z.enum(["source","runtime","copy","suppressed"]),sourceOwner:z.union([z.literal("core"),z.string().regex(/^(bundle|source):.+$/)]).nullable(),guard:m.nullable()}).strict().parse(a);(d.status==="runtime"&&(d.source!==null||d.effective===null||d.sourceOwner!==null)||d.status==="suppressed"&&(s[0]!=="content"||d.source===null||d.effective!==null||d.guard===null)||d.status==="copy"&&(d.source===null||d.effective===null)||d.effective!==null&&d.guard===null||d.source===null&&d.effective===null)&&ze(`Invalid schema state: inconsistent status at ${c}`);let f=d.sourceOwner;f!==null&&f!=="core"&&!f.startsWith("bundle:")&&!f.startsWith("source:")&&ze("Invalid source owner");let g=f===null||f==="core"?f:f.startsWith("bundle:")?`bundle:${f.slice(7)}`:`source:${f.slice(7)}`;return {...d,sourceOwner:g}});return {...n.data,entries:o.sort(jn)}}a(Nf,"parseState");function Df(e){try{return Nf(e)}catch(t){throw t instanceof z.ZodError?h.fromZodErrors(t.issues.map(n=>({path:n.path.map(String),message:n.message}))):t}}a(Df,"parseSchemaState");function Of(e){let t=[];for(let n of [...e.entries].sort(jn)){let r=n.source===null?"added":n.status==="suppressed"?"suppressed":n.effective===null?"removed":b$3(n.source)!==b$3(n.effective)?"changed":n.status==="copy"?"copied":null;r&&t.push({...n,change:r});}return {modelVersion:1,tenant:e.tenant,sourceFingerprint:e.sourceFingerprint,changes:t}}a(Of,"diffSchemaState");export{Yw as AGENT_UI_BATCH_MAX_BYTES,Hw as AGENT_UI_BATCH_MAX_ITEMS,Go as ALLOWED_PROPERTY_TYPES,Un as ALL_ACTIONS,Qm as ALL_OPERATION_TYPES,wA as ALL_SYSTEM_RESOURCES,Zg as ARTIFACT_FILE_ROLES,Qg as ARTIFACT_KINDS,Nl as ARTIFACT_LIST_VIEW,Cl as ARTIFACT_OBJECT,nt as ARTIFACT_OBJECT_NAME,wa as ARTIFACT_PREVIEW_EXTENSION,Xg as ARTIFACT_RETENTIONS,El as ARTIFACT_VIEW,Kt as ATTRIBUTE_TYPES,bg as AUDIT_ACTIONS,fg as AUDIT_RESOURCE_TYPES,Kn as AgentBuilder,ig as BEHAVIOR_PROPERTIES,iu as BYTE_UNIT_LABELS,zc as CLAIMABLE_SESSION_STATUSES,jt as COMPUTED_FUNCTIONS,DS as COMPUTED_FUNCTION_METADATA,dS as COMPUTED_FUNCTION_NAMES,rI as CONNECTOR_CALLBACK_PARAM,zo as COUNT_MODES,I as ComputedFormulaCompileError,te as ContentBuilder,xA as DB_COLUMN_FIELDS,aa as DEFAULT_AGENT_EXECUTION_CONFIG,jo as DEFAULT_APPROVAL_POLICY,Hg as DEFAULT_DICTATION_LIMITS,Ho as DEFAULT_LABEL_FALLBACK,Zc as DEFAULT_MEETING_BOT_DISPLAY_NAME,_u as DEFAULT_ROLES,RA as DEFAULT_ROLE_DESCRIPTIONS,IA as DEFAULT_ROLE_LABELS,vA as DEFAULT_ROLE_PERMISSIONS,Ny as DEFAULT_TENANT_SETTINGS,Kg as DICTATION_FINALIZATION_TIMEOUT_MS,Ug as DICTATION_FRAME_BYTES,qg as DICTATION_MAX_BUFFER_BYTES,$g as DICTATION_MAX_FRAME_BYTES,zg as DICTATION_MAX_TRANSCRIPT_BYTES,Yg as DICTATION_MODEL_ID,Gg as DICTATION_PREPARATION_TIMEOUT_MS,Lg as DICTATION_SAMPLE_RATE,Wg as DICTATION_TICKET_TTL_MS,Sf as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,Vh as DOCUMENT_SYSTEM_ATTRIBUTES,Ks as DRAFTABLE_ATTRIBUTE_TYPES,Tf as DRAFT_WRITE_TOOL_NAMES,Rl as DRIVE_LIST_VIEW,Sl as DRIVE_OBJECT,tt as DRIVE_OBJECT_NAME,Il as DRIVE_VIEW,Jt as EMPTY_VALUE_PLACEHOLDER,Vy as ESTIMATED_COUNT_CAP,gI as FAKE_MEETING_BOT_SIGNATURE_HEADER,df as FAMILY_INPUTS,pf as FAMILY_WIRE_INPUTS,Vn as FORM_FORBIDDEN_ATTRIBUTE_TYPES,vt as FlagRegistry,ln as FlagService,Pr as FormBuilder,Dt as FormRegistry,jr as FormRowBuilder,_r as FormStepBuilder,Rf as GET_ARCHITECT_DRAFT_TOOL_NAME,$r as GroupBuilder,rg as IDENTITY_PROPERTIES,_y as IMAGE_FORMATS,Mo as INFERENCE_REASONING_OPTIONS,Po as INFERENCE_SPEEDS,Ul as LIVE_EVENT_TYPES,Dp as MAILBOX_LIST_MODES,lI as MAIL_DRAFT_BODY_MAX_CHARS,dI as MAIL_SUBJECT_MAX_CHARS,Bo as MAX_PRESET_DEPTH,Dg as MAX_TODOS,kg as MAX_TODO_DESCRIPTION_CHARS,Og as MAX_TODO_ID_CHARS,C as MEETING_ATTRIBUTES,va as MEETING_DETAIL_VIEW_ID,kl as MEETING_LIST_VIEW,Ia as MEETING_LIST_VIEW_ID,Dl as MEETING_OBJECT,rt as MEETING_OBJECT_NAME,Ol as MEETING_VIEW,Ra as MEETING_WRITE_SOURCE,wl as MEMORY_LIST_VIEW,xl as MEMORY_OBJECT,Tl as MEMORY_VIEW,Np as McpOAuthCompletionMode,Kc as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,Yc as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,Do as NOTIFICATION_INBOX_STATES,Co as NOTIFICATION_KINDS,Eo as NOTIFICATION_PRIORITIES,No as NOTIFICATION_SENSITIVITIES,tg as NOTIFICATION_TYPES_V1,$c as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,Lc as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,Uc as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,Oo as NOTIFICATION_WORK_STATES,yI as NO_RECORDING,$o as NoopGeocodingAdapter,Zt as OBJECT_NAME_SCHEMA,Wc as OPEN_TOOL_PART_STATES,Bt as OPERATION_REGISTRY,wn as OPERATOR_SPECS,St as ObjectBuilder,og as PRESENTATION_PROPERTIES,_o as PROVIDER_NAMES,wf as PUBLISH_ARCHITECT_DRAFT_TOOL_NAME,Wh as QUALIFIED_SEPARATOR,Uy as QUOTA_KEYS,fI as RECORDING_OVERRIDES,bI as RECORDING_POLICIES,ea as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,ye as RELATION_TARGET_ANY,tc as REMOVE_OPERATION_SCHEMA,Op as REPLY_MODES,If as REQUEST_DESIGN_REVIEW_TOOL_NAME,rn as RelationBuilder,mt as SCHEMA_OPERATIONS,oc as SCHEMA_OPERATION_INPUT,re as SCHEMA_PLAN_LIMITS,ji as SCHEMA_SOURCE_ID_PATTERN,Mg as SESSION_STATE_STREAM_ID,qc as SESSION_TERMINAL_STATUSES,xa as SKILL_CONTENT_TEMPLATE,yl as SKILL_LIST_VIEW,bl as SKILL_OBJECT,gl as SKILL_VIEW,Lu as STANDARD_SCHEMA_VENDOR,Fn as SYSTEM_PART_CODES,X as SYSTEM_RESOURCES,SA as SYSTEM_RESOURCE_LABELS,ns as TODAY_DEFAULT,Sg as TODO_PLAN_STATUSES,Ng as TODO_STATUSES,Fo as TOOL_APPROVAL_STATES,Oy as USER_STATUSES,ky as USER_WORK_POSTURES,ut as VIEW_OPERATIONS,ac as VIEW_OPERATION_INPUT,cn as ViewBuilder,Sy as accessLevelToActions,wy as actionsToAccessLevel,BA as agent,aR as agentDataChunk,Ig as agentDisplayName,rR as agentInferencePreferencesSchema,Wp as agentMessageAttachmentSchema,zp as agentMessagePartSchema,qp as agentSessionInferenceOverridesInputSchema,iR as agentSessionInferenceOverridesSchema,fs as agentSessionMessageSchema,Xp as agentUIValidationError,Zi as applyOperations,Yo as applyPipes,vu as applyRelationProps,Zw as architectDraftChannelKey,Wi as assertAcyclicComputed,Ba as assertAcyclicComputedDependencies,wm as assertBilateralPairs,Zp as assertCustomAgentUIMessageChunk,_p as assertSchemaSourceId,Vt as bilateralDeclarationOf,ol as booleanFlag,is as buildAgentFallbackTitle,ju as buildPermissionFlags,Ht as buildPropertySchema,Kh as buildQualifiedAttribute,qi as canonicalViewOperationSchema,pa as checkbox,QI as collectSchemaReferences,Gc as compareAgentSessionMessages,jn as compareSchemaStateEntries,Ft as compilablePlansOf,fn as compileComputedFormula,qa as compileRollupAttribute,ru as computeByteMagnitude,zi as computedCompileSchemaOf,Cn as computedPlanOf,k as content,Ca as contentDefinition,jp as conversationDisplayTitle,ll as createFlagRegistry,pl as createFlagService,tn as createStandardSchemaProps,Nt as createStructuredRelationCatalogue,mx as currency,As as customDataChunkSchemas,ee as date,Sn as dateInTimezone,Ke as dateValueStart,Ue as defaultViewIdsFor,Hi as defaultViewsFor,Bi as defineOperation,V as definePresentation,Gi as dependentsOf,of as deriveArchitectChanges,ZS as deriveCreateDefaultsFromFilters,Ou as deriveInitials,Xm as describeOperations,us as destructiveSchema,le as detailView,Of as diffSchemaState,ma as document,xs as draftedLabelExpression,Li as draftedObjectDefinition,ct as draftedViewDefinition,Yp as durableDateSchema,$p as endpointChangeSchema,WI as endpointLabelBatchBodySchema,$I as endpointMutationBodySchema,zI as endpointReadQuerySchema,rf as episodeImpactOf,RS as evaluateComputedAst,vS as evaluateComputedFormula,CS as evaluateComputedFormulaWithResult,wp as evaluateFilterState,WS as evaluateRecordFilterState,ht as extractAttributeNames,Zo as extractValueRefs,ff as familyOf,ul as flagRegistry,eo as focusOf,vx as form,Xc as formFieldFlatKey,Qc as formFieldKey,Ea as formRegistry,zw as formatAgentStreamFrameId,Ko as formatAttributeValue,Ph as formatByteSize,yp as formatComputedResult,du as formatLocationValue,hx as formula,im as fromDraftableView,Iu as getEditableLabelAttribute,ny as getErrorMessage,sS as getLiveProtocolPayloadChannel,ku as getRecordCreatorPrincipalId,Xo as getSingleAttributeFromExpression,Uo as getSlotFieldTargets,Nu as getUserDisplayName,pe as group,II as hasDestructiveEntries,vy as hasOptions,ys as imageModelIdSchema,He as includesAction,lg as inferInverseCardinality,rp as inferRollupReturnType,Vi as inferenceReasoningSchema,Fi as inferenceSpeedSchema,Qp as isAgentUIDataName,Jw as isAgentUIMessageBatch,dg as isAttributeSortable,ug as isBilateralRelation,_S as isCheckboxEquality,wg as isClaimableSessionStatus,lt as isComputedAttribute,pn as isComputedFunctionName,Ie as isDateRangeValue,CA as isDefaultRole,Bh as isDocumentAttribute,tu as isEmptyObject,ay as isFormDefinition,Yt as isFormFieldsRow,Bn as isFormFreeFieldRef,my as isFormHeadingRow,fy as isFormSeparatorRow,Lo as isFormSlotFieldRef,by as isFormTextRow,Xt as isLabelExpression,cS as isLiveEventEnvelope,rS as isLiveEventPayload,Jl as isLiveEventPayloadForType,Hl as isLiveEventType,sI as isMailProvider,cI as isMailboxListMode,Wo as isNotEmpty,Rg as isOpenToolPartState,Ya as isPlainRecord,uI as isReplyMode,$A as isStandardSchema,Cg as isSystemPartCode,Tg as isTerminalSessionStatus,hg as isTerminalState,vg as isToolApprovalState,ko as isUniversalRelation,cl as jsonFlag,xg as legacyStatusToSessionState,de as listView,Da as liveChannelKey,gx as location,Lh as matchesAccepts,Gp as mentionReferenceSchema,Kp as modelDefinitionSchema,gs as modelReferenceSchema,bx as multiselect,UI as namedEndpointSchema,Jc as nativeAgentUIPartIdMetadataKey,ou as normalizeDateValue,an as number,sl as numberFlag,Bx as object,Eg as orderAgentSessionMessages,Ww as parseAgentStreamFrameId,eu as parseCountMode,Oa as parseLiveChannelKey,sf as parseNamedTarget,Fg as parseNativeAgentUIPartIdsMetadata,Zm as parseOperation,Fy as parseOptionalCountMode,Gh as parseQualifiedAttribute,Df as parseSchemaState,FI as persistedSchemaPlanSchema,px as phone,Fp as plannedAttributeSchema,Vp as plannedInlineAttributeSchema,Bp as plannedObjectSchema,to as presentationOf,Ut as proposalTargetKey,bs as providerNameSchema,Eu as qualifiedPropertyDefs,ly as readFormFieldValue,Ji as regenerateDerived,jT as registry,qI as relatedCreationBodySchema,Xe as relation,rT as relationProperty,Cu as relationPropertyDefs,dt as relationTargetObjectName,oe as relationTargets,cg as relationTargetsOf,Xi as relationValueIds,qn as renderLabelExpression,nI as requestedCapabilities,It as requireRecordContentContext,tf as requiredTargetKeys,Cp as resolveAttributeDefaultValue,Yu as resolveCollectionActions,Ku as resolveContentNavigation,uy as resolveFieldRequired,qo as resolvePropertyDefinitions,mi as resolveViewContents,Re as richtext,Ax as rollup,np as rollupToFormulaExpression,MI as schemaPlanSchema,Ef as schemaStateSourcePayload,ce as select,oR as sessionInferencePatchSchema,Ag as sessionStateToLegacyStatus,fx as status,bf as stillMissing,Ct as storedContentDefinition,al as stringFlag,xf as summarizeDraft,On as targetSnapshot,nf as targetTokensFor,w as text,Ee as toAttribute,tm as toDraftableAttributes,em as toDraftableObject,rm as toDraftableView,nu as toUndefinedIfEmpty,Hp as todoItemSchema,Jp as todoPlanSchema,hs as toolImpactSchema,yx as user,xt as validateAttributeName,gi as validateContentViewCatalogue,hu as validateLabelExpression,Gu as validateObjectExpressions,At as validateObjectName,Qe as validateStructuredRelationDefinition,Bu as validateViewName,Ki as viewIdFor,li as viewIdentityKey,jl as viewRegistry,Et as workspaceViewAuthoring};
|
|
59
|
+
{{ summary }}`).attribute(w({name:C.title,label:"Title"}).required()).attribute(De({name:C.description,label:"Description"})).attribute(De({name:C.summary,label:"Summary"}).hidden()).attribute(De({name:C.transcript,label:"Transcript"}).hidden()).attribute(w({name:C.location,label:"Location"})).attribute(oe({name:C.startsAt,label:"Starts at"}).includeTime()).attribute(oe({name:C.endsAt,label:"Ends at"}).includeTime()).attribute(Qo({name:C.isAllDay,label:"All day"})).attribute(pe({name:C.status,label:"Status"}).options([{value:"confirmed",label:"Confirmed"},{value:"tentative",label:"Tentative"},{value:"cancelled",label:"Cancelled"}])).attribute(w({name:C.organizerAddress,label:"Organizer address"}).email()).attribute(w({name:C.organizerName,label:"Organizer"})).attribute(w({name:C.conferenceProvider,label:"Conference provider"})).attribute(w({name:C.conferenceJoinUrl,label:"Join link"}).url()).attribute(w({name:C.htmlLink,label:"Open in calendar"}).url()).attribute(w({name:C.participants,label:"Participants"}).multiline()).attribute(w({name:C.providerEventId,label:"Provider event id"}).hidden()).attribute(w({name:C.icalUid,label:"iCal UID"}).hidden()).attribute(w({name:C.recurringEventId,label:"Recurring event id"}).hidden()).attribute(w({name:C.connectionId,label:"Connection id"})).attribute(pe({name:C.recordingOverride,label:"Recording"}).options([{value:"force",label:"Force"},{value:"skip",label:"Skip"}]).hidden()).attribute(oe({name:C.endedAnnouncedAt,label:"Ended announced at"}).includeTime().hidden()).attribute(rt({name:C.linkedRecords,label:"Linked records"}).toAny().many().qualifyWith(w({name:"source",label:"Source"}).hidden())).build(),gl=W(fe(da,"Meeting").for(ct).default().tab("description","Description",N.richtext(C.description).titleAttribute(C.title)).tab("summary","Summary",N.richtext(C.summary)).tab("transcript","Transcript",N.richtext(C.transcript)).aside("details","Details",N.form(ge("details","Details").fields(C.startsAt,C.endsAt,C.linkedRecords))).build()),yl=W(be(ua,"Meetings").for(ct).default().tab("workspace","Shared",N.collection().object(ct).table().icon("users").visibility("workspace").columns(...ca).sort(C.startsAt,"desc")).tab("mine","My meetings",N.collection().object(ct).table().icon("lock").visibility("private").columns(...ca).sort(C.startsAt,"desc")).build());function si(e,t){return JSON.stringify([e,t])}a(si,"viewIdentityKey");function un(e){return structuredClone(e)}a(un,"cloneDeclaration");var ui=class ui{constructor(){this.views=new Map;this.systemNames=new Map;}register(t){let r$1=(Array.isArray(t)?t:[t]).map((s,c)=>this.prepare(s,c)),o=new Map,a=new Set;for(let{declaration:s}of r$1){let{object:c,name:u,context:d,default:m}=s.definition,p=o.get(c)??new Set;if((this.views.get(c)?.has(u)||p.has(u))&&this.throwDuplicate(c,u),p.add(u),o.set(c,p),!m)continue;let b=JSON.stringify([c,d]);if(this.getByObjectNameAndContext(c,d).some(g=>g.definition.default)||a.has(b))throw new r("default view",b,`[ViewRegistry] Duplicate default view for object "${c}" in context "${d}"`);a.add(b);}for(let s of r$1)this.commit(s);return this}prepare(t,n){if(typeof t!="object"||t===null||t.kind!=="view"||Object.keys(t).some(o=>o!=="kind"&&o!=="definition")){let o="Expected an exact view declaration";throw new h(o,[{path:["views",String(n)],message:o}])}let r=ea$1.safeParse(t.definition);if(!r.success)throw h.fromZodErrors(r.error.issues.map(o=>({path:["views",String(n),"definition",...o.path.map(String)],message:o.message})));return {declaration:un(t),system:ia(t.definition)}}commit({declaration:t,system:n}){let{object:r,name:o}=t.definition,a=this.views.get(r)??new Map;if(a.set(o,t),this.views.set(r,a),n){let s=this.systemNames.get(r)??new Set;s.add(o),this.systemNames.set(r,s);}}getByObjectName(t){return Array.from(this.views.get(t)?.values()??[],un)}getByObjectNameAndContext(t,n){return this.getByObjectName(t).filter(r=>r.definition.context===n)}get(t,n){let r=this.views.get(t)?.get(n);return r&&un(r)}getOrThrow(t,n){let r=this.get(t,n);if(r)return r;let a=this.getByObjectName(t).map(({definition:s})=>`${s.name} (${s.context})`).join(", ")||"(none)";throw new c$3("View",`${t}:${n}`,void 0,`[ViewRegistry] View "${n}" not found for object "${t}".
|
|
60
|
+
Available views: ${a}`)}getAll(){return Array.from(this.views.values()).flatMap(t=>Array.from(t.values(),un))}has(t,n){return this.views.get(t)?.has(n)??false}hasObject(t){return this.views.has(t)}get size(){let t=0;for(let n of this.views.values())t+=n.size;return t}listObjectNames(){return Array.from(this.views.keys())}getDefault(t,n){let r=this.getByObjectNameAndContext(t,n);return r.find(o=>o.definition.default)??r[0]}isSystem(t,n){return this.systemNames.get(t)?.has(n)??false}isSystemDeclaration(t){return this.isSystem(t.definition.object,t.definition.name)}clear(){this.views.clear(),this.systemNames.clear();}summary(){let t=[`[ViewRegistry] ${this.size} view(s) registered:`];for(let n of this.listObjectNames()){let r=this.getByObjectName(n).map(({definition:o})=>{let a=o.default?" (default)":"";return `${o.name}:${o.context}${a}`});t.push(` ${n}: ${r.join(", ")}`);}return t.join(`
|
|
61
|
+
`)}debug(t){let n=this.summary();return t?.(n),n}throwDuplicate(t,n){let r$1=si(t,n);throw new r("view",r$1,`[ViewRegistry] Duplicate view: "${n}" for object "${t}"`)}};a(ui,"ViewRegistry");var ci=ui,hl=new ci;function pa(e,t){if(t.suppressed)return null;let n=t.workspaceDefinition??t.sourceDefinition;return n===null?null:{...structuredClone(n),name:e}}a(pa,"contentDefinition");function Et(e){let{name:t,...n}=e;return structuredClone(n)}a(Et,"storedContentDefinition");function Nt(e){let t={main:0,aside:0};return {origin:"runtime",mainOrderCustomized:false,asideOrderCustomized:false,contents:Object.fromEntries(e.map(n=>[n.name,{sourceDefinition:null,workspaceDefinition:Et(n),suppressed:false,sourcePosition:null,workspacePosition:t[n.placement]++}]))}}a(Nt,"workspaceViewAuthoring");function li(e){let t=Object.entries(e.contents).flatMap(([n,r])=>{let o=pa(n,r);return o?[{definition:o,...r}]:[]});return ["main","aside"].flatMap(n=>{let r=n==="main"?e.mainOrderCustomized:e.asideOrderCustomized;return t.filter(o=>o.definition.placement===n).sort((o,a)=>{let s=r?o.workspacePosition:o.sourcePosition,c=r?a.workspacePosition:a.sourcePosition;if(s!==null&&c!==null&&s!==c)return s-c;if(s!==null&&c===null)return -1;if(c!==null&&s===null)return 1;let u=o.sourcePosition??o.workspacePosition,d=a.sourcePosition??a.workspacePosition;return u!==null&&d!==null&&u!==d?u-d:u!==null&&d===null?-1:d!==null&&u===null?1:o.definition.name.localeCompare(a.definition.name)}).map(o=>o.definition)})}a(li,"resolveViewContents");function ma(e,t){return e.attributes.find(n=>n.name===t&&n.type==="relation")}a(ma,"findRelationAttribute");function fa(e,t=[e.name,"targets"]){if(e.targets.length!==1||e.targets[0].object==="*"){let n=`Relation "${e.name}" requires one concrete collection target`;throw new h(n,[{path:t,message:n}])}return e.targets[0].object}a(fa,"requireSingleRelationTarget");var Al=new Map(d().map(e=>[e.name,e]));function Ie(e,t){throw new h(t,[{path:e,message:t}])}a(Ie,"reject");function ke(e,t){e.trim().length===0&&Ie(t,"API name must not be empty");}a(ke,"requireName");function ba(e,t,n){let r$1=new Map;return e.forEach((o,a)=>{if(ke(o.name,[...n,String(a),"name"]),r$1.has(o.name))throw new r(t,o.name);r$1.set(o.name,o);}),r$1}a(ba,"indexUnique");function re(e,t,n,r){if(ke(t,n),!e)return;let o=e.attributes?.get(t)??Al.get(t);if(!o){if(!e.attributes)return;Ie(n,`Unknown attribute "${e.name}.${t}"`);}return r&&o.type!==r&&Ie(n,`Attribute "${e.name}.${t}" must have type ${r}`),o}a(re,"requireAttribute");function di(e){let t=e.mode??"published",n=new Map;e.objects.forEach((m,p)=>{if(ke(m.name,["objects",String(p),"name"]),n.has(m.name))throw new r("object",m.name);n.set(m.name,{name:m.name,attributes:ba(m.attributes,"attribute",["objects",String(p),"attributes"])});});let r$1=new Set;(e.reservedObjects??[]).forEach((m,p)=>{let b=["reservedObjects",String(p)];ke(m,b),!n.has(m)&&(t!=="draft"&&Ie(b,`Unresolved reserved object "${m}"`),r$1.add(m),n.set(m,{name:m}));});let o=ba(e.extensions??[],"extension",["extensions"]);function a$1(m,p){ke(m,p);let b=n.get(m);return b||Ie(p,`Unknown object "${m}"`),b}a(a$1,"resolveObject");let s=t==="draft"?da$1:ea$1,c=new Map,u=new Map;return {views:e.views.map((m,p)=>{let b=["views",String(p)],y=s.safeParse(m);if(!y.success)throw new h("Invalid content view",y.error.issues.map(v=>({path:[...b,...v.path.map(String)],message:v.message,code:v.code})));let g=y.data;ke(g.name,[...b,"name"]);let A=a$1(g.object,[...b,"object"]),x=c.get(g.object)??new Set;if(x.has(g.name))throw new r("view",`${g.object}.${g.name}`);if(x.add(g.name),c.set(g.object,x),g.default){let v=u.get(g.object)??new Set;if(v.has(g.context))throw new r("default view",`${g.object}.${g.context}`);v.add(g.context),u.set(g.object,v);}return g.contents.forEach((v,_)=>{let F=[...b,"contents",String(_)];ke(v.name,[...F,"name"]),xl(v,F,A,g.context,o,a$1);}),g}),unresolvedObjects:[...r$1].sort()}}a(di,"validateContentViewCatalogue");function xl(e,t,n,r,o,a$1){function s(){Rt(e.name,r,t);}if(a(s,"requireRecord"),e.type==="custom"){let c=o.get(e.extension);c||Ie([...t,"extension"],`Unknown extension "${e.extension}"`),c.requiresRecord&&s();let u=c.parameters.safeParse(structuredClone(e.parameters??{}));if(!u.success)throw new h("Invalid extension parameters",u.error.issues.map(d=>({path:[...t,"parameters",...d.path.map(String)],message:d.message,code:d.code})));return}if(e.type==="collection"){let c,u;if(e.source.object!==void 0)c=a$1(e.source.object,[...t,"source","object"]);else {s();let d=[...t,"source","relation"],m=re(n,e.source.relation,d,"relation");m?.type==="relation"&&(u=m,c=a$1(fa(m,d),d));}e.columns?.forEach((d,m)=>{let p=[...t,"columns",String(m)];if(typeof d=="string"){re(c,d,p);return}let b=[...p,"relationProperty"];u||Ie(b,"Relation property columns require a relation source"),u.properties?.definitions.some(y=>y.name===d.relationProperty)||Ie(b,`Unknown relation property "${d.relationProperty}"`);}),e.displayAttributes?.forEach((d,m)=>re(c,d,[...t,"displayAttributes",String(m)])),e.sorts?.forEach((d,m)=>re(c,d.attribute,[...t,"sorts",String(m),"attribute"])),e.filters?.rules.forEach((d,m)=>re(c,d.attribute,[...t,"filters","rules",String(m),"attribute"])),e.descriptionAttribute!==void 0&&re(c,e.descriptionAttribute,[...t,"descriptionAttribute"]),e.layout==="kanban"&&re(c,e.groupByAttribute,[...t,"groupByAttribute"]);return}switch(s(),e.type){case "form":e.groups.forEach((c,u)=>{let d=[...t,"groups",String(u)];ke(c.name,[...d,"name"]),c.fields.forEach((m,p)=>re(n,m.attribute,[...d,"fields",String(p),"attribute"]));});break;case "richtext":re(n,e.attribute,[...t,"attribute"],"richtext"),e.titleAttribute!==void 0&&re(n,e.titleAttribute,[...t,"titleAttribute"],"text");break;case "emails":case "meetings":e.emailAttributes.forEach((c,u)=>re(n,c,[...t,"emailAttributes",String(u)],"text"));break;case "documents":e.relations?.forEach((c,u)=>re(n,c,[...t,"relations",String(u)],"relation"));break;case "forms":e.objectName!==void 0&&a$1(e.objectName,[...t,"objectName"]);break;case "activity":break;default:Ie(t,`Unknown content type: ${String(e)}`);}}a(xl,"validateContent");function pi(e){return structuredClone(e)}a(pi,"cloneFormDefinition");var mi=class mi{constructor(){this.forms=new Map;}register(t){let n=Array.isArray(t)?t:[t];for(let r$1 of n){if(this.forms.has(r$1.name))throw new r("form",r$1.name,`[FormRegistry] Duplicate form: "${r$1.name}"`);this.forms.set(r$1.name,pi(r$1));}return this}get(t){let n=this.forms.get(t);return n?pi(n):void 0}getAll(){return Array.from(this.forms.values(),pi)}listNames(){return Array.from(this.forms.keys())}};a(mi,"FormRegistry");var Dt=mi;var ga=new Dt;function Aw(e,t){return `${e}:${t}`}a(Aw,"formatAgentStreamFrameId");function xw(e){let t=e.lastIndexOf(":");if(t<=0)return null;let n=e.slice(0,t),r=Number(e.slice(t+1));return !Number.isInteger(r)||r<=0?null:{streamId:n,sequence:r}}a(xw,"parseAgentStreamFrameId");var Sw=204800,Iw=256;function bi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(bi,"isRecord");function gi(e,t){let n=Object.keys(e);return n.length===t.length&&n.every(r=>t.includes(r))}a(gi,"hasExactKeys");function fi(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}a(fi,"isPositiveInteger");function ya(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}a(ya,"isNonNegativeInteger");function Tl(e){return bi(e)&&gi(e,["kind","startOffset","endOffset"])?(e.kind==="text"||e.kind==="reasoning")&&ya(e.startOffset)&&ya(e.endOffset)&&e.endOffset>=e.startOffset:false}a(Tl,"isContentRange");function wl(e){if(!bi(e))return false;let t=e.content===void 0?["sequence","chunk"]:["sequence","content","chunk"];return gi(e,t)&&fi(e.sequence)&&e.chunk!==void 0&&(e.content===void 0||Tl(e.content))}a(wl,"isBatchItem");function Sl(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return}}a(Sl,"encodedSize");function Rw(e){if(!(bi(e)&&gi(e,["schemaVersion","batchId","tenantId","sessionId","streamId","sequenceStart","sequenceEnd","items"]))||e.schemaVersion!==1||typeof e.batchId!="string"||e.batchId.trim()===""||typeof e.tenantId!="string"||e.tenantId.trim()===""||typeof e.sessionId!="string"||e.sessionId.trim()===""||typeof e.streamId!="string"||e.streamId.trim()===""||!fi(e.sequenceStart)||!fi(e.sequenceEnd)||!Array.isArray(e.items)||e.items.length===0||e.items.length>256||!e.items.every(wl))return false;let t=0;for(let r of e.items){if(r.sequence<=t)return false;t=r.sequence;}if(e.items[0]?.sequence!==e.sequenceStart||e.items.at(-1)?.sequence!==e.sequenceEnd)return false;let n=Sl(e);return n!==void 0&&n<=204800}a(Rw,"isAgentUIMessageBatch");function ha(e){switch(e.kind){case "workspace":return `workspace:${encodeURIComponent(e.tenantId)}`;case "object":return `object:${encodeURIComponent(e.objectId)}`;case "record":return `record:${encodeURIComponent(e.objectId)}:${encodeURIComponent(e.recordId)}`;case "view":return `view:${encodeURIComponent(e.viewId)}`;case "user":return `user:${encodeURIComponent(e.actorId)}`;case "conversation":return `conversation:${encodeURIComponent(e.sessionId)}`;case "architect-draft":return e.scope==="actor"?`architect-draft:actor:${encodeURIComponent(e.actorId)}`:`architect-draft:session:${encodeURIComponent(e.sessionId)}`}}a(ha,"liveChannelKey");function Ew(e){return e.sessionId?ha({kind:"architect-draft",scope:"session",sessionId:e.sessionId}):e.actorId?ha({kind:"architect-draft",scope:"actor",actorId:e.actorId}):null}a(Ew,"architectDraftChannelKey");function je(e){try{return decodeURIComponent(e)}catch{return null}}a(je,"decodeLiveChannelPart");function Aa(e){let t=e.split(":");if(t[0]==="workspace"&&t.length===2&&t[1]){let n=je(t[1]);return n?{kind:"workspace",tenantId:n}:null}if(t[0]==="object"&&t.length===2&&t[1]){let n=je(t[1]);return n?{kind:"object",objectId:n}:null}if(t[0]==="record"&&t.length===3&&t[1]&&t[2]){let n=je(t[1]),r=je(t[2]);return n&&r?{kind:"record",objectId:n,recordId:r}:null}if(t[0]==="view"&&t.length===2&&t[1]){let n=je(t[1]);return n?{kind:"view",viewId:n}:null}if(t[0]==="user"&&t.length===2&&t[1]){let n=je(t[1]);return n?{kind:"user",actorId:n}:null}if(t[0]==="architect-draft"&&t.length===3&&t[2]){let n=je(t[2]);return n?t[1]==="actor"?{kind:"architect-draft",scope:"actor",actorId:n}:t[1]==="session"?{kind:"architect-draft",scope:"session",sessionId:n}:null:null}if(t[0]==="conversation"&&t.length===2&&t[1]){let n=je(t[1]);return n?{kind:"conversation",sessionId:n}:null}return null}a(Aa,"parseLiveChannelKey");var Il={"record.patch":true,"record.deleted":true,"record.removed":true,"record.created":true,"view.projection.stale":true,"agent.session.patch":true,"notification.created":true,"notification.recipient.patch":true,"notification.count.patch":true,"notification.inbox.archived":true,"reflex.state.changed":true,"reflex.run.completed":true,"reflex.authoring.progress":true,"architect.draft.updated":true,"meeting.recording.patch":true,"wallet.state":true,"channel.revoked":true},Rl=Object.keys(Il),Cl=["membership-unknown","sort-unknown","permissions-changed"],vl=["permission-revoked","workspace-left","object-deleted"],El=["inboxState","workState","lockedAt","lockedByActorId","readAt","archivedAt","snoozedUntil","completedAt","dismissedAt","updatedAt"],Nl=["type","objectId","recordId","recordVersion"],Dl=["type","objectId","recordId","recordVersion","record"],Ol=["id","objectId","visibility","ownedBy","label","values","metadata","createdAt","updatedAt","createdBy","lastUpdatedBy","schemaVersion"],kl=["type","targetActorId","archivedCount","version","updatedAt"];function jl(e){return typeof e=="string"&&Rl.includes(e)}a(jl,"isLiveEventType");function kw(e){return $(e)&&jl(e.type)?_l(e.type,e):false}a(kw,"isLiveEventPayload");function _l(e,t){if(!$(t))return false;switch(e){case "record.patch":return $l(t);case "record.deleted":return Ul(t);case "record.removed":return ql(t);case "record.created":return Wl(t);case "view.projection.stale":return Gl(t);case "agent.session.patch":return Kl(t);case "notification.created":return Ql(t);case "notification.recipient.patch":return Xl(t);case "notification.count.patch":return Zl(t);case "notification.inbox.archived":return ed(t);case "reflex.state.changed":return ad(t);case "reflex.run.completed":return sd(t);case "reflex.authoring.progress":return cd(t);case "architect.draft.updated":return id(t);case "meeting.recording.patch":return ld(t);case "wallet.state":return md(t);case "channel.revoked":return fd(t);default:return false}}a(_l,"isLiveEventPayloadForType");function $(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a($,"isRecord");function J(e){return typeof e=="string"}a(J,"isString");function Ot(e){return J(e)&&e.length>0}a(Ot,"isNonEmptyString");function yi(e){return e===null||J(e)}a(yi,"isNullableString");function Pl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}a(Pl,"isVersion");function he(e){if(!J(e))return false;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}a(he,"isIsoDateString");function ut(e){return e===null||he(e)}a(ut,"isNullableIsoDateString");function O(e,t){return J(e[t])}a(O,"hasString");function se(e,t){return Ot(e[t])}a(se,"hasNonEmptyString");function U(e,t){return Pl(e[t])}a(U,"hasVersion");function G(e,t){return he(e[t])}a(G,"hasIsoDateString");function D(e,t,n){return !Object.hasOwn(e,t)||n(e[t])}a(D,"hasOptional");function ln(e,t){return Object.keys(e).every(n=>t.includes(n))}a(ln,"hasOnlyKeys");function Q(e,t){return typeof e=="string"&&t.includes(e)}a(Q,"isOneOf");function Ml(e){return Q(e,go)}a(Ml,"isNotificationKind");function Fl(e){return Q(e,yo)}a(Fl,"isNotificationPriority");function Vl(e){return Q(e,ho)}a(Vl,"isNotificationSensitivity");function xa(e){return Q(e,Ao)}a(xa,"isNotificationInboxState");function Ta(e){return Q(e,xo)}a(Ta,"isNotificationWorkState");function Bl(e){return $(e)&&O(e,"type")&&O(e,"id")}a(Bl,"isNotificationSubject");function Ll(e){return $(e)&&O(e,"fieldKey")&&Object.hasOwn(e,"value")&&U(e,"version")}a(Ll,"isRecordFieldPatch");function $l(e){return e.type==="record.patch"&&O(e,"objectId")&&O(e,"recordId")&&U(e,"recordVersion")&&D(e,"label",J)&&D(e,"metadata",$)&&D(e,"fieldsWithheld",t=>t===true)&&Array.isArray(e.fieldPatches)&&e.fieldPatches.every(Ll)&&O(e,"updatedAt")}a($l,"isRecordPatchPayload");function Ul(e){return e.type==="record.deleted"&&O(e,"objectId")&&O(e,"recordId")&&U(e,"recordVersion")&&O(e,"deletedAt")}a(Ul,"isRecordDeletedPayload");function ql(e){return e.type==="record.removed"&&ln(e,Nl)&&O(e,"objectId")&&O(e,"recordId")&&U(e,"recordVersion")}a(ql,"isRecordRemovedPayload");function zl(e){return $(e)&&ln(e,Ol)&&O(e,"id")&&O(e,"objectId")&&Q(e.visibility,["workspace","private"])&&yi(e.ownedBy)&&(e.visibility==="workspace"&&e.ownedBy===null||e.visibility==="private"&&Ot(e.ownedBy))&&O(e,"label")&&$(e.values)&&D(e,"metadata",$)&&G(e,"createdAt")&&G(e,"updatedAt")&&D(e,"createdBy",J)&&D(e,"lastUpdatedBy",J)&&U(e,"schemaVersion")}a(zl,"isRecordLiveSnapshot");function Wl(e){return e.type==="record.created"&&ln(e,Dl)&&O(e,"objectId")&&O(e,"recordId")&&U(e,"recordVersion")&&zl(e.record)&&e.record.id===e.recordId&&e.record.objectId===e.objectId}a(Wl,"isRecordCreatedPayload");function Gl(e){return e.type==="view.projection.stale"&&O(e,"viewId")&&Q(e.reason,Cl)}a(Gl,"isViewProjectionStalePayload");function Kl(e){return e.type==="agent.session.patch"&&O(e,"sessionId")&&$(e.patch)&&U(e,"version")&&O(e,"updatedAt")}a(Kl,"isAgentSessionPatchPayload");function Yl(e){return $(e)&&O(e,"id")&&O(e,"tenantId")&&D(e,"senderActorId",J)&&D(e,"rootActorId",J)&&D(e,"triggeredByActorId",J)&&Ml(e.kind)&&O(e,"type")&&D(e,"subject",Bl)&&O(e,"title")&&D(e,"summary",J)&&$(e.payload)&&Fl(e.priority)&&Vl(e.sensitivity)&&D(e,"threadKey",J)&&D(e,"idempotencyKey",J)&&D(e,"expiresAt",he)&&G(e,"createdAt")&&G(e,"updatedAt")}a(Yl,"isLiveNotification");function Hl(e){return $(e)&&O(e,"id")&&O(e,"tenantId")&&O(e,"notificationId")&&O(e,"recipientActorId")&&xa(e.inboxState)&&Ta(e.workState)&&D(e,"lockedAt",he)&&D(e,"lockedByActorId",J)&&D(e,"readAt",he)&&D(e,"archivedAt",he)&&D(e,"snoozedUntil",he)&&D(e,"completedAt",he)&&D(e,"dismissedAt",he)&&G(e,"createdAt")&&G(e,"updatedAt")}a(Hl,"isLiveNotificationRecipient");function Jl(e){return $(e)?Object.keys(e).every(t=>El.includes(t))&&D(e,"inboxState",xa)&&D(e,"workState",Ta)&&D(e,"lockedAt",ut)&&D(e,"lockedByActorId",yi)&&D(e,"readAt",ut)&&D(e,"archivedAt",ut)&&D(e,"snoozedUntil",ut)&&D(e,"completedAt",ut)&&D(e,"dismissedAt",ut)&&D(e,"updatedAt",he):false}a(Jl,"isNotificationRecipientPatch");function Ql(e){let t=Yl(e.notification)?e.notification:null;return e.type==="notification.created"&&t!==null&&Array.isArray(e.recipients)&&e.recipients.length>0&&e.recipients.every(n=>Hl(n)&&n.notificationId===t.id)&&U(e,"version")&&G(e,"updatedAt")}a(Ql,"isNotificationCreatedPayload");function Xl(e){return e.type==="notification.recipient.patch"&&O(e,"recipientId")&&O(e,"recipientActorId")&&Jl(e.patch)&&U(e,"version")&&G(e,"updatedAt")}a(Xl,"isNotificationRecipientPatchPayload");function Zl(e){return e.type==="notification.count.patch"&&O(e,"targetActorId")&&U(e,"unread")&&U(e,"pendingWork")&&U(e,"version")&&G(e,"updatedAt")}a(Zl,"isNotificationCountPatchPayload");function ed(e){return e.type==="notification.inbox.archived"&&ln(e,kl)&&se(e,"targetActorId")&&U(e,"archivedCount")&&U(e,"version")&&G(e,"updatedAt")}a(ed,"isNotificationInboxArchivedPayload");var td=["armed","disarmed"],nd=["authoring","compiling","replaying","promoted","failed"],rd=["promoted","lkg"];function id(e){if(e.type!=="architect.draft.updated"||!$(e.receipt))return false;let t=e.receipt;return Array.isArray(t.operationIds)&&t.operationIds.every(Ot)&&$(t.revision)&&se(t.revision,"draftId")&&U(t.revision,"version")&&Array.isArray(t.changedTargets)&&t.changedTargets.every(n=>$(n)&&Ot(n.token)&&od(n.target))}a(id,"isArchitectDraftUpdatedPayload");function od(e){if(!$(e))return false;let t=Object.keys(e);return t.every(n=>Ot(e[n]))?se(e,"viewName")?se(e,"objectName")&&t.every(n=>["objectName","viewName","contentName"].includes(n)):se(e,"objectName")?t.length===1:se(e,"objectId")&&t.length<=2&&t.every(n=>["objectId","attributeName","attributeId","recordId"].includes(n)):false}a(od,"isNamedTarget");function ad(e){return e.type==="reflex.state.changed"&&se(e,"reflexId")&&Q(e.state,td)&&G(e,"updatedAt")}a(ad,"isReflexStateChangedPayload");function sd(e){return e.type==="reflex.run.completed"&&se(e,"reflexId")&&se(e,"runId")&&Q(e.served,rd)&&U(e,"version")&&U(e,"wallMs")&&G(e,"completedAt")}a(sd,"isReflexRunCompletedPayload");function cd(e){return e.type==="reflex.authoring.progress"&&se(e,"reflexId")&&Q(e.status,nd)&&G(e,"updatedAt")}a(cd,"isReflexAuthoringProgressPayload");var ud=["none","scheduled","recording","completed","failed"];function ld(e){return e.type==="meeting.recording.patch"&&se(e,"meetingId")&&Q(e.status,ud)&&yi(e.failureReason)&&G(e,"updatedAt")}a(ld,"isMeetingRecordingPatchPayload");var dd=["ok","low","exhausted","paused"],pd=["metering-only","contract","wallet"];function md(e){return e.type==="wallet.state"&&Q(e.status,dd)&&Q(e.mode,pd)&&G(e,"updatedAt")}a(md,"isWalletStatePayload");function fd(e){return e.type==="channel.revoked"&&O(e,"channel")&&Q(e.reason,vl)}a(fd,"isChannelRevokedPayload");function hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(hi,"isRecord");function bd(e){let{channel:t}=e;return typeof t=="string"&&Aa(t)?t:null}a(bd,"payloadChannel");function Mw(e){return hi(e)?bd(e):null}a(Mw,"getLiveProtocolPayloadChannel");function Fw(e){return hi(e)?typeof e.id=="string"&&e.id.length>0&&typeof e.channel=="string"&&typeof e.type=="string"&&typeof e.tenantId=="string"&&e.tenantId.length>0&&typeof e.occurredAt=="string"&&hi(e.payload):false}a(Fw,"isLiveEventEnvelope");var Lw=["if","concat","sum","avg","count","min","max","earliest","latest","unique","first","percent_empty","percent_not_empty","count_empty","count_not_empty","count_unique"],kt={if:{name:"if",returnType:"branch",minArgs:3,maxArgs:3},concat:{name:"concat",returnType:{kind:"scalar",type:"text"},minArgs:1},sum:{name:"sum",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},avg:{name:"avg",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count:{name:"count",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},min:{name:"min",returnType:"source_item",minArgs:1,maxArgs:1},max:{name:"max",returnType:"source_item",minArgs:1,maxArgs:1},earliest:{name:"earliest",returnType:{kind:"scalar",type:"date"},minArgs:1,maxArgs:1},latest:{name:"latest",returnType:{kind:"scalar",type:"date"},minArgs:1,maxArgs:1},unique:{name:"unique",returnType:"argument",minArgs:1,maxArgs:1},first:{name:"first",returnType:"source_item",minArgs:1,maxArgs:1},percent_empty:{name:"percent_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},percent_not_empty:{name:"percent_not_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_empty:{name:"count_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_not_empty:{name:"count_not_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_unique:{name:"count_unique",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1}};function dn(e){return Object.hasOwn(kt,e)}a(dn,"isComputedFunctionName");var wi=class wi extends Error{constructor(t){super(t),this.name="ComputedFormulaCompileError";}};a(wi,"ComputedFormulaCompileError");var S=wi;function mn(e){let t=gd(e.expression),n=pn(t,e.schema),r=Vd(n.valueType);if(r!==e.returnType)throw new S(`Computed formula "${e.attributeName}" returns "${r}", expected "${e.returnType}"`);if(Ea(e.returnType)&&n.optionsSource===void 0)throw new S(`Computed formula "${e.attributeName}" returns "${e.returnType}" without optionsSource`);let o=n.optionsSource===void 0?[]:[{kind:"options",source:n.optionsSource}],a=Ti([...n.dependencies,...o]);return {kind:"formula",attributeName:e.attributeName,expression:e.expression,returnType:e.returnType,valueType:n.valueType,dependencies:a,ast:t,...n.optionsSource?{optionsSource:n.optionsSource}:{},...n.targetAttributeType?{targetAttributeType:n.targetAttributeType}:{},dependenciesHash:Bd({expression:e.expression,returnType:e.returnType,dependencies:a})}}a(mn,"compileComputedFormula");function va(e){let t=new Map(e.map(o=>[o.attributeName,o])),n=new Set,r=a((o,a)=>{let s=a.indexOf(o);if(s!==-1){let d=[...a.slice(s),o];throw new S(`Computed field cycle detected: ${d.join(" -> ")}`)}if(n.has(o))return;let c=t.get(o);if(c===void 0)return;let u=[...a,o];for(let d of c.dependencies)d.kind==="computed"&&r(d.attributeName,u);n.add(o);},"visit");for(let o of e)r(o.attributeName,[]);}a(va,"assertAcyclicComputedDependencies");function gd(e){try{return e$1(e)}catch(t){throw t instanceof Error?new S(t.message):t}}a(gd,"parseCompileFormula");function pn(e,t){switch(e.kind){case "literal":return {valueType:yd(e.value),dependencies:[],...typeof e.value=="string"?{literalString:e.value}:{}};case "path":return hd(e.parts,t);case "call":return Id(e.functionName,e.args,t);case "binary":return Nd(e.operator,pn(e.left,t),pn(e.right,t));default:return e}}a(pn,"inferNode");function yd(e){switch(typeof e){case "string":return {kind:"scalar",type:"text"};case "number":return {kind:"scalar",type:"number"};case "boolean":return {kind:"scalar",type:"boolean"};case "object":return {kind:"scalar",type:"text"};default:return e}}a(yd,"literalToValueType");function hd(e,t){if(e.length===1){let n=e[0],r=Ai(t,n);if(r===void 0)throw new S(`Unknown attribute "${n}" on object "${t.objectName}"`);return r.type==="relation"?{valueType:Td(),dependencies:[{kind:"relation",relationName:r.name,cardinality:wa(r)}],targetAttributeType:r.type}:{valueType:Sa(r),dependencies:[xd(r)],optionsSource:Ia(t.objectName,r),targetAttributeType:r.type}}if(e.length===2){let[n,r]=e,o=Ai(t,n);if(o===void 0)throw new S(`Unknown attribute "${n}" on object "${t.objectName}"`);if(o.type!=="relation")throw new S(`Attribute "${n}" on object "${t.objectName}" is not a relation`);let a=Ad(o);if(a===void 0)throw new S(`Relation "${n}" on object "${t.objectName}" is missing targetObjectName`);let s=t.relatedObjects?.[a];if(s===void 0)throw new S(`Unknown related object "${a}"`);let c=Ai(s,r);if(c===void 0)throw new S(`Unknown attribute "${r}" on object "${s.objectName}"`);let u=Sa(c);return {valueType:o.cardinality==="many"?Sd(u):u,dependencies:[{kind:"relation",relationName:n,targetAttributeName:r,cardinality:wa(o)}],optionsSource:Ia(s.objectName,c),targetAttributeType:c.type}}throw new S("Computed paths support at most one relation hop")}a(hd,"inferPath");function Ai(e,t){return e.attributes.find(n=>n.name===t)}a(Ai,"findAttribute");function Ad(e){if(e.targetObjectName!==void 0)return e.targetObjectName;if(e.targets?.length===1){let[t]=e.targets;return t?.object==="*"?void 0:t?.object}}a(Ad,"getRelationTargetObjectName");function wa(e){return e.cardinality??"one"}a(wa,"relationCardinality");function xd(e){return e.type==="formula"||e.type==="rollup"?{kind:"computed",attributeName:e.name}:{kind:"local",attributeName:e.name}}a(xd,"localDependencyFor");function Sa(e){if(e.type==="formula"||e.type==="rollup"){if(e.returnType===void 0)throw new S(`Computed attribute "${e.name}" is missing returnType`);return wd(e.returnType)}switch(e.type){case "number":case "currency":return {kind:"scalar",type:"number"};case "checkbox":return {kind:"scalar",type:"boolean"};case "date":return {kind:"scalar",type:"date"};case "select":case "status":return {kind:"scalar",type:"select"};case "multiselect":return {kind:"collection",itemType:"select"};case "text":case "richtext":case "phone":case "user":case "location":case "relation":case "document":return {kind:"scalar",type:"text"};default:return e.type}}a(Sa,"attributeToValueType");function Td(){return {kind:"collection",itemType:"text"}}a(Td,"relationToValueType");function wd(e){return e==="multiselect"?{kind:"collection",itemType:"select"}:{kind:"scalar",type:e}}a(wd,"returnTypeToValueType");function Sd(e){return e.kind==="collection"?e:{kind:"collection",itemType:e.type}}a(Sd,"asCollectionValueType");function Ia(e,t){if(t.type==="formula"||t.type==="rollup")return Ea(t.returnType)?t.optionsSource:void 0;if(!(t.type!=="select"&&t.type!=="status"&&t.type!=="multiselect"))return t.optionsSource??{objectName:e,attributeName:t.name,...t.id?{attributeId:t.id}:{}}}a(Ia,"optionsSourceForAttribute");function Id(e,t,n){if(!dn(e))throw new S(`Unknown computed function "${e}"`);let r=kt[e];if(t.length<r.minArgs||r.maxArgs!==void 0&&t.length>r.maxArgs){let a=r.maxArgs===void 0||r.maxArgs===r.minArgs?String(r.minArgs):`${r.minArgs}-${r.maxArgs}`;throw new S(`Function "${e}" expects ${a} arguments, received ${t.length}`)}let o=t.map(a=>pn(a,n));return Rd(e,o)}a(Id,"inferCall");function Rd(e,t){let n=Ti(t.flatMap(r=>r.dependencies));switch(e){case "if":return Cd(t,n);case "concat":return Dd(t,`Function "${e}" does not accept collection values`),{valueType:{kind:"scalar",type:"text"},dependencies:n};case "sum":case "avg":return Ra(e,t[0],"number"),{valueType:{kind:"scalar",type:"number"},dependencies:n};case "count":case "count_empty":case "count_not_empty":case "count_unique":case "percent_empty":case "percent_not_empty":return kd(e,t[0]),{valueType:{kind:"scalar",type:"number"},dependencies:n};case "min":case "max":return Od(e,t[0]),{valueType:jd(t[0]),dependencies:n,optionsSource:t[0].optionsSource,targetAttributeType:t[0].targetAttributeType};case "earliest":case "latest":return Ra(e,t[0],"date"),{valueType:{kind:"scalar",type:"date"},dependencies:n,targetAttributeType:t[0].targetAttributeType};case "unique":return vd(t[0],n);case "first":return Ed(t[0],n);default:return e}}a(Rd,"inferFunctionReturn");function Cd(e,t){xi(e[0].valueType,"boolean",'Function "if" condition must be boolean');let n=e[1],r=e[2],o=Pd(n,r),a=Md(n,r);if(o===void 0)throw new S('Function "if" branches must return the same type');return {valueType:o,dependencies:t,...a?{optionsSource:a}:{},targetAttributeType:n.targetAttributeType??r.targetAttributeType}}a(Cd,"inferIfFunction");function vd(e,t){if(e.valueType.kind!=="collection"||e.valueType.itemType!=="select")throw new S('Function "unique" expects a select collection');return {valueType:{kind:"collection",itemType:"select"},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}a(vd,"inferUniqueFunction");function Ed(e,t){if(e.valueType.kind!=="collection")throw new S('Function "first" expects a collection');return {valueType:{kind:"scalar",type:e.valueType.itemType},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}a(Ed,"inferFirstFunction");function Nd(e,t,n){let r=Ti([...t.dependencies,...n.dependencies]),o=e==="+"||e==="-"||e==="*"||e==="/";if(t.valueType.kind==="collection"||n.valueType.kind==="collection")throw new S(`Cannot use collection values with ${o?"arithmetic":"comparison"} operator "${e}"`);if(o)return e==="+"&&(t.valueType.type==="text"||n.valueType.type==="text")?{valueType:{kind:"scalar",type:"text"},dependencies:r}:(xi(t.valueType,"number",`Operator "${e}" expects number operands`),xi(n.valueType,"number",`Operator "${e}" expects number operands`),{valueType:{kind:"scalar",type:"number"},dependencies:r});if(e==="=="||e==="!="){if(t.valueType.type!==n.valueType.type)throw new S(`Operator "${e}" expects operands with the same scalar type`);return {valueType:{kind:"scalar",type:"boolean"},dependencies:r}}if((t.valueType.type!=="number"||n.valueType.type!=="number")&&(t.valueType.type!=="date"||n.valueType.type!=="date"))throw new S(`Operator "${e}" expects number or date operands of the same type`);return {valueType:{kind:"scalar",type:"boolean"},dependencies:r}}a(Nd,"inferBinary");function Dd(e,t){for(let n of e)if(n.valueType.kind==="collection")throw new S(t)}a(Dd,"ensureNoCollections");function Ra(e,t,n){if((t.valueType.kind==="collection"?t.valueType.itemType:t.valueType.type)!==n)throw new S(`Function "${e}" expects ${n} values`)}a(Ra,"ensureCollectionOrScalarType");function Od(e,t){if(t.valueType.kind!=="collection")throw new S(`Function "${e}" expects a collection`);let n=t.valueType.itemType;if(n!=="number"&&n!=="date")throw new S(`Function "${e}" expects number or date values`)}a(Od,"ensureMinMaxSource");function kd(e,t){if(t.valueType.kind!=="collection")throw new S(`Function "${e}" expects a collection`)}a(kd,"ensureCollectionSource");function xi(e,t,n){if(e.kind!=="scalar"||e.type!==t)throw new S(n)}a(xi,"ensureScalarType");function jd(e){return e.valueType.kind==="scalar"?e.valueType:{kind:"scalar",type:e.valueType.itemType}}a(jd,"sourceItemValueType");function _d(e,t){return e.kind==="scalar"?t.kind==="scalar"&&e.type===t.type:t.kind==="collection"&&e.itemType===t.itemType}a(_d,"sameValueType");function Pd(e,t){if(_d(e.valueType,t.valueType)||Ca(e,t))return e.valueType;if(Ca(t,e))return t.valueType}a(Pd,"resolveIfBranchValueType");function Ca(e,t){return e.valueType.kind==="scalar"&&e.valueType.type==="select"&&t.valueType.kind==="scalar"&&t.valueType.type==="text"&&t.literalString!==void 0}a(Ca,"isSelectScalarWithStringLiteral");function Md(e,t){let n=e.optionsSource,r=t.optionsSource;if(n!==void 0&&r!==void 0&&!Fd(n,r))throw new S('Function "if" branches use incompatible options sources');return n??r}a(Md,"resolveIfOptionsSource");function Fd(e,t){return e.objectName===t.objectName&&e.attributeName===t.attributeName&&e.attributeId===t.attributeId}a(Fd,"sameOptionsSource");function Ea(e){return e==="select"||e==="multiselect"}a(Ea,"isSelectLikeReturnType");function Vd(e){if(e.kind==="scalar")return e.type;if(e.itemType==="select")return "multiselect";throw new S(`Collection item type "${e.itemType}" cannot be used as a computed return type`)}a(Vd,"valueTypeToReturnType");function Ti(e){let t=new Set,n=[];for(let r of e){let o=JSON.stringify(jt(r));t.has(o)||(t.add(o),n.push(r));}return n}a(Ti,"uniqueDependencies");function Bd(e){let t=e.dependencies.map(n=>jt(n)).sort((n,r)=>Na(JSON.stringify(n),JSON.stringify(r)));return JSON.stringify(jt({expression:e.expression,returnType:e.returnType,dependencies:t}))}a(Bd,"createDependenciesHash");function jt(e){return Array.isArray(e)?e.map(t=>jt(t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>Na(t,n)).map(([t,n])=>[t,jt(n)])):e}a(jt,"stableNormalize");function Na(e,t){return e<t?-1:e>t?1:0}a(Na,"compareStrings");function Ld(e){return e.function==="count"?`count(${e.relationAttribute})`:`${qd(e.function)}(${e.relationAttribute}.${e.targetAttribute})`}a(Ld,"rollupToFormulaExpression");function $d(e,t){if(e.function==="count")return "number";let n=zd(e,t);switch(e.function){case "countValues":case "countEmpty":case "percentEmpty":case "percentNotEmpty":case "countUniqueValues":return "number";case "sum":case "avg":return "number";case "earliest":case "latest":return "date";case "original":if(!Gd(n.type))throw new S('Rollup "original" requires a select, status, or multiselect target');return "multiselect";default:return e.function}}a($d,"inferRollupReturnType");function Oa(e,t){let n=Ld(e),r=$d(e,t);return {...mn({attributeName:e.name,expression:n,returnType:r,schema:Ud(e,t)}),kind:"rollup"}}a(Oa,"compileRollupAttribute");function Ud(e,t){return {...t,attributes:t.attributes.map(n=>n.name===e.relationAttribute&&n.type==="relation"?{...n,cardinality:"many"}:n)}}a(Ud,"schemaWithRollupRelationAsMany");function qd(e){switch(e){case "sum":case "avg":case "earliest":case "latest":return e;case "original":return "unique";case "countValues":return "count_not_empty";case "countEmpty":return "count_empty";case "percentEmpty":return "percent_empty";case "percentNotEmpty":return "percent_not_empty";case "countUniqueValues":return "count_unique";default:return e}}a(qd,"rollupFunctionToFormulaFunction");function zd(e,t){let n=Da(t,e.relationAttribute);if(n===void 0)throw new S(`Unknown relation attribute "${e.relationAttribute}" on object "${t.objectName}"`);if(n.type!=="relation")throw new S(`Attribute "${e.relationAttribute}" on object "${t.objectName}" is not a relation`);let r=Wd(n);if(r===void 0)throw new S(`Relation "${e.relationAttribute}" on object "${t.objectName}" is missing targetObjectName`);let o=t.relatedObjects?.[r];if(o===void 0)throw new S(`Unknown related object "${r}"`);let a=Da(o,e.targetAttribute);if(a===void 0)throw new S(`Unknown attribute "${e.targetAttribute}" on object "${o.objectName}"`);return a}a(zd,"findRollupTargetAttribute");function Da(e,t){return e.attributes.find(n=>n.name===t)}a(Da,"findAttribute");function Wd(e){if(e.targetObjectName!==void 0)return e.targetObjectName;if(e.targets?.length===1){let[t]=e.targets;return t?.object==="*"?void 0:t?.object}}a(Wd,"getRelationTargetObjectName");function Gd(e){return e==="select"||e==="status"||e==="multiselect"}a(Gd,"isSelectLikeAttributeType");function Re(e,t){switch(e.kind){case "literal":return e.value;case "path":return Yd(t,e.parts);case "binary":return Hd(e.operator,Re(e.left,t),Re(e.right,t));case "call":return Kd(e.functionName,e.args,t);default:return e}}a(Re,"evaluateAst");function Kd(e,t,n){if(Qd(e),Xd(e,t.length),e==="if"){let r=Re(t[0],n);return r===null?null:Re(r?t[1]:t[2],n)}return Zd(e,t.map(r=>Re(r,n)))}a(Kd,"evaluateCallNode");function Yd(e,t){return t.reduce((n,r)=>Fa(n,r),e)}a(Yd,"resolvePath");function Fa(e,t){if(Array.isArray(e))return e.map(r=>Fa(r,t));if(!Ma(e))return null;if(Object.hasOwn(e,t))return e[t]??null;let n=e.values;return Ma(n)&&Object.hasOwn(n,t)?n[t]??null:null}a(Fa,"resolvePathPart");function Hd(e,t,n){switch(e){case "+":return Jd(t,n);case "-":return bn(t,n,(r,o)=>r-o);case "*":return bn(t,n,(r,o)=>r*o);case "/":return bn(t,n,(r,o)=>r/o);case ">":return fn(t,n,r=>r>0);case "<":return fn(t,n,r=>r<0);case ">=":return fn(t,n,r=>r>=0);case "<=":return fn(t,n,r=>r<=0);case "==":return ka(t,n);case "!=":{let r=ka(t,n);return r===null?null:!r}default:return e}}a(Hd,"evaluateBinary");function Jd(e,t){return typeof e=="string"||typeof t=="string"?`${e??""}${t??""}`:bn(e,t,(n,r)=>n+r)}a(Jd,"add");function fn(e,t,n){let r=Va(e,t);return r===null?null:n(r)}a(fn,"compareWith");function Va(e,t){if(!lt([e,t]))return null;let n=dt(e),r=dt(t);if(n!==null&&r!==null)return n-r;let o=Ri(e),a=Ri(t);return o&&a?o.getTime()-a.getTime():null}a(Va,"compare");function ka(e,t){return e===t?true:e==null||t===null||t===void 0?false:lt([e,t])?Va(e,t)===0:null}a(ka,"equalScalar");function Qd(e){if(!dn(e))throw new Error(`Unknown computed function "${e}"`)}a(Qd,"assertComputedFunctionName");function Xd(e,t){let{minArgs:n,maxArgs:r}=kt[e];if(t>=n&&t<=(r??Number.POSITIVE_INFINITY))return;let o=r===void 0?`at least ${n}`:`between ${n} and ${r}`;throw new Error(`Function "${e}" expects ${o} arguments, received ${t}`)}a(Xd,"validateArity");function Zd(e,t){switch(e){case "concat":return t.filter(n=>n!=null).map(String).join("");case "sum":return lt(t)?Si(t).reduce((n,r)=>n+r,0):null;case "avg":{if(!lt(t))return null;let n=Si(t);return n.length>0?n.reduce((r,o)=>r+o,0)/n.length:null}case "count":return qe(t[0]).length;case "min":return ja(t,"min");case "max":return ja(t,"max");case "earliest":return Ii(t,"min");case "latest":return Ii(t,"max");case "unique":return Pa(qe(t[0]));case "first":return qe(t[0]).find(n=>n!=null)??null;case "percent_empty":return _a(t[0],true);case "percent_not_empty":return _a(t[0],false);case "count_empty":return qe(t[0]).filter(a$1).length;case "count_not_empty":return qe(t[0]).filter(n=>!a$1(n)).length;case "count_unique":return Pa(qe(t[0])).length;default:return e}}a(Zd,"evaluateCall");function Si(e){return gn(e).map(dt).filter(t=>t!==null)}a(Si,"numericValues");function lt(e){let t=new Set;for(let n of gn(e))Ci(n)&&t.add(Ba(n));return t.size<=1}a(lt,"areCommensurable");function Ba(e){return e.code.toUpperCase()}a(Ba,"currencyCode");function bn(e,t,n){if(!lt([e,t]))return null;let r=dt(e),o=dt(t);if(r===null||o===null)return null;let a=n(r,o);return Number.isFinite(a)?a:null}a(bn,"numericBinary");function ja(e,t){if(!lt(e))return null;let n=Si(e);return n.length>0?t==="min"?Math.min(...n):Math.max(...n):Ii(e,t)}a(ja,"minMax");function Ii(e,t){let n=gn(e).map(Ri).filter(a=>a!==null);if(n.length===0)return null;let r=n.map(a=>a.getTime()),o=t==="min"?Math.min(...r):Math.max(...r);return new Date(o).toISOString()}a(Ii,"dateMinMax");function _a(e,t){let n=qe(e);return n.length===0?0:n.filter(o=>a$1(o)===t).length/n.length}a(_a,"percentByEmptyState");function Pa(e){let t=new Set,n=[];for(let r of e){if(a$1(r))continue;let o=ep(r);t.has(o)||(t.add(o),n.push(r));}return n}a(Pa,"uniqueNonEmpty");function qe(e){return e==null?[]:Array.isArray(e)?gn(e):[e]}a(qe,"collectionItems");function gn(e){return e.flat(Number.POSITIVE_INFINITY)}a(gn,"flatten");function dt(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&e.trim()!==""){let t=Number(e);return Number.isFinite(t)?t:null}return Ci(e)&&Number.isFinite(e.value)?e.value:null}a(dt,"toFiniteNumber");function Ci(e){return typeof e=="object"&&e!==null&&typeof e.value=="number"&&typeof e.code=="string"}a(Ci,"isCurrencyValue");function Ri(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e!="string"){let n=Ze(e);if(n===null)return null;let r=new Date(n);return Number.isNaN(r.getTime())?null:r}let t=new Date(e);return Number.isNaN(t.getTime())?null:t}a(Ri,"toDate");function ep(e){if(Ci(e))return `currency:${Ba(e)}:${e.value}`;let t=dt(e);return t!==null?`number:${t}`:e instanceof Date?`date:${e.toISOString()}`:`${typeof e}:${JSON.stringify(e)}`}a(ep,"uniqueKey");function Ma(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Ma,"isPlainRecord");function tp(e,t,n){if(e==null)return null;let r=a(o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean"||o instanceof Date?String(o):null,"stringifyScalar");switch(t){case "number":{let o=typeof e=="number"?e:Number(e);return Number.isNaN(o)?null:n!==void 0?Number(o.toFixed(n)):o}case "boolean":return !!e;case "date":return e instanceof Date?e.toISOString():typeof e=="string"?e:null;case "text":return String(e);case "select":if(Array.isArray(e)){for(let o of e){if(o==null)continue;let a=r(o);if(a!==null)return a}return null}return r(e);case "multiselect":return Array.isArray(e)?e.flatMap(o=>{if(o==null)return [];let a=r(o);return a===null?[]:[a]}):r(e)===null?[]:[String(e)];default:{let o=t;throw new Error(`Unsupported computed return type: ${o}`)}}}a(tp,"formatComputedResult");function eS(e,t){return Re(e,t)}a(eS,"evaluateComputedAst");function tS(e,t){return Re(e$1(e),t)}a(tS,"evaluateComputedFormula");function nS(e,t,n,r){try{let o=Re(e$1(e),t);return {value:n?tp(o,n,r):o}}catch(o){return {value:null,error:o instanceof Error?o.message:String(o)}}}a(nS,"evaluateComputedFormulaWithResult");var oS=[{name:"if",signature:"if(condition, then, else)",description:"Conditional value",category:"logic",example:"if(amount > 100, 'big', 'small')"},{name:"concat",signature:"concat(a, b, ...)",description:"Join values into text",category:"text",example:"concat(firstName, ' ', lastName)"},{name:"sum",signature:"sum(collection)",description:"Total of values",category:"number",example:"sum(orders.amount)"},{name:"avg",signature:"avg(collection)",description:"Average of values",category:"number",example:"avg(orders.amount)"},{name:"min",signature:"min(collection)",description:"Smallest value",category:"number",example:"min(orders.amount)"},{name:"max",signature:"max(collection)",description:"Largest value",category:"number",example:"max(orders.amount)"},{name:"count",signature:"count(collection)",description:"Number of items",category:"collection",example:"count(orders)"},{name:"count_empty",signature:"count_empty(collection)",description:"Items with no value",category:"collection",example:"count_empty(orders.note)"},{name:"count_not_empty",signature:"count_not_empty(collection)",description:"Items with a value",category:"collection",example:"count_not_empty(orders.note)"},{name:"count_unique",signature:"count_unique(collection)",description:"Distinct values",category:"collection",example:"count_unique(orders.status)"},{name:"percent_empty",signature:"percent_empty(collection)",description:"Fraction with no value",category:"collection",example:"percent_empty(orders.note)"},{name:"percent_not_empty",signature:"percent_not_empty(collection)",description:"Fraction with a value",category:"collection",example:"percent_not_empty(orders.note)"},{name:"unique",signature:"unique(collection)",description:"Distinct values as a list",category:"collection",example:"unique(orders.status)"},{name:"first",signature:"first(collection)",description:"First non-empty value",category:"collection",example:"first(orders.status)"},{name:"earliest",signature:"earliest(collection)",description:"Earliest date",category:"date",example:"earliest(orders.closeDate)"},{name:"latest",signature:"latest(collection)",description:"Latest date",category:"date",example:"latest(orders.closeDate)"}];var La=a(e=>a$1(e)||Array.isArray(e)&&e.length===0,"isEmpty"),X=a(e=>e==null?"":String(e),"toStr"),An=a(e=>{if(a$1(e))return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null},"toNum"),xn=a(e=>{if(e==null)return null;let t=e instanceof Date?e:new Date(String(e));return Number.isNaN(t.getTime())?null:t},"toDate"),yn=a(e=>Array.isArray(e)?e:e==null?[]:[e],"toArr"),np=a((e,t,n)=>{let r=An(e),o=An(t);return r!==null&&o!==null&&n(r,o)},"compareNumbers"),rp=a((e,t,n)=>{let r=xn(e),o=xn(t);return r!==null&&o!==null&&n(r.getTime(),o.getTime())},"compareDates"),$a=a((e,t,n)=>{if(n.type==="number"||n.type==="currency"){let r=An(e),o=An(t);if(r!==null&&o!==null)return r===o}return X(e)===X(t)},"equalsForAttr");function uS(e,t){return e?e==="checkbox":typeof t=="boolean"}a(uS,"isCheckboxEquality");var hn=a(e=>({appliesTo:["number","currency","date","formula"],evaluateInMemory:a((t,n,r)=>r.type==="date"?rp(t,n,e):np(t,n,e),"evaluateInMemory")}),"orderingSpec"),Tn={is:{appliesTo:["text","phone","number","currency","checkbox","status","select","date","user","relation","formula"],evaluateInMemory:a((e,t,n)=>n.type==="checkbox"?e===true==(t===true):$a(e,t,n),"evaluateInMemory")},is_not:{appliesTo:["text","phone","number","currency","status","select","date","user","relation","formula"],evaluateInMemory:a((e,t,n)=>!$a(e,t,n),"evaluateInMemory")},contains:{appliesTo:["text","phone","formula"],evaluateInMemory:a((e,t)=>X(e).toLowerCase().includes(X(t).toLowerCase()),"evaluateInMemory")},not_contains:{appliesTo:["text","phone","formula"],evaluateInMemory:a((e,t)=>!X(e).toLowerCase().includes(X(t).toLowerCase()),"evaluateInMemory")},starts_with:{appliesTo:["text","phone"],evaluateInMemory:a((e,t)=>X(e).toLowerCase().startsWith(X(t).toLowerCase()),"evaluateInMemory")},ends_with:{appliesTo:["text"],evaluateInMemory:a((e,t)=>X(e).toLowerCase().endsWith(X(t).toLowerCase()),"evaluateInMemory")},is_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:a(e=>La(e),"evaluateInMemory")},is_not_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:a(e=>!La(e),"evaluateInMemory")},less_than:hn((e,t)=>e<t),greater_than:hn((e,t)=>e>t),less_or_equal:hn((e,t)=>e<=t),greater_or_equal:hn((e,t)=>e>=t),is_within:{appliesTo:["date"],evaluateInMemory:a((e,t)=>{let n=xn(e),r=S$1(t);return n&&r?n.getTime()>=r.startMs&&n.getTime()<r.endMs:false},"evaluateInMemory")},on_day_month:{appliesTo:["date"],evaluateInMemory:a((e,t)=>{let n=xn(e);if(!n)return false;let r=t;return n.getMonth()+1===r.month&&n.getDate()===r.day},"evaluateInMemory")},any_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:a((e,t)=>{let n=yn(t).map(X);return yn(e).map(X).some(o=>n.includes(o))},"evaluateInMemory")},none_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:a((e,t)=>{let n=yn(t).map(X);return !yn(e).map(X).some(o=>n.includes(o))},"evaluateInMemory")}};var ip=a((e,t)=>({id:`system:${e}`,name:e,label:e,type:t,system:true}),"systemAttribute"),op=[...Object.entries(V$1).map(([e,t])=>ip(e,t))];function xS(e,t,n){let r=t;return ap(e,{...t.values,id:t.id,objectId:t.objectId,objectName:r.objectName,tenantId:r.tenantId,label:t.label,createdAt:t.createdAt,updatedAt:t.updatedAt,createdBy:t.createdBy,lastUpdatedBy:t.lastUpdatedBy,deletedAt:t.deletedAt,deletedBy:t.deletedBy,visibility:t.visibility,ownedBy:t.ownedBy},[...n,...op])}a(xS,"evaluateRecordFilterState");function ap(e,t,n){if(e.rules.length===0)return true;let r=new Map(n.map(a=>[a.name,a])),o=e.combinator==="or"?"some":"every";return e.rules[o](a=>sp(a,t,r))}a(ap,"evaluateFilterState");function sp(e,t,n){let r=n.get(e.attribute);if(!r)return false;if(e.property&&r.type==="location"){if(!(g(e.property)&&h$1(e.operator)))return false;let c=Tn[e.operator];if(!c)return false;let u=t[e.attribute],d=typeof u=="object"&&u!==null?u[e.property]:void 0;return vi(c,"text",e.operator,d,e.value,r)}if(e.property){let c=jo(r).find(y=>y.name===e.property);if(!c)return false;let u=K(e.operator),d=Tn[u];if(!d?.appliesTo.includes(c.type))return false;let m=t[e.attribute],b=(Array.isArray(m)?m:m==null?[]:[m]).some(y=>{if(typeof y!="object"||y===null)return false;let g=y.props;return typeof g!="object"||g===null?false:vi(d,c.type,u,g[e.property],e.value,c)});return (e.quantifier??J$1(e.operator))==="none"?!b:b}let o=Tn[e.operator];if(!o||!o.appliesTo.includes(r.type))return false;let a=t[e.attribute],s=r.type==="relation"||r.type==="document"||r.type==="user"?lp(a):a;return vi(o,r.type,e.operator,s,e.value,r)}a(sp,"evaluateRule");function vi(e,t,n,r,o,a){let[s,c]=cp(t,n,r,o);return t==="phone"&&c===""&&n==="contains"?false:t==="phone"&&c===""&&n==="not_contains"?true:e.evaluateInMemory(s,c,a)}a(vi,"evaluateNormalizedComparands");function cp(e,t,n,r){return e==="date"&&(t==="is"||t==="is_not")?[Ua(n),Ua(r)]:e==="phone"?up(n,r):[qa(e,n),qa(e,r)]}a(cp,"normalizeOperatorComparands");function Ua(e){let t=Ne(e)?Ze(e):e;if(t instanceof Date)return Number.isNaN(t.getTime())?null:t.toISOString().slice(0,10);if(typeof t!="string"||t==="")return null;if(/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let n=new Date(t);return Number.isNaN(n.getTime())?null:n.toISOString().slice(0,10)}a(Ua,"normalizeUtcCalendarDay");function up(e,t){let n=typeof t=="object"&&t!==null?t:{},r=typeof n.countryCode=="string"?n.countryCode:void 0,o=a(a=>{let s=typeof a=="object"&&a!==null?a:{phoneNumber:a};if(typeof s.phoneNumber!="string")return null;if(!r)return a$3(s.phoneNumber);let c=typeof s.countryCode=="string"?s.countryCode:r;return `${c}:${b$1(s.phoneNumber,c)}`},"normalizeOne");return [o(e),o(t)]}a(up,"normalizePhoneComparands");function qa(e,t){return e==="currency"?H(t):e==="date"?Ne(t)?Ze(t):t instanceof Date?Number.isNaN(t.getTime())?null:t.toISOString():t:t}a(qa,"normalizeComparableValue");function lp(e){let t=a(n=>typeof n!="object"||n===null?n:n.id,"normalizeOne");return Array.isArray(e)?e.map(t):t(e)}a(lp,"normalizeReferenceIds");var za="today";function wn(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(e)}a(wn,"dateInTimezone");function dp(e,t){if(!("defaultValue"in e))return;let{defaultValue:n}=e;return e.type!=="date"||n!==za?n:e.includeTime?t.now.toISOString():wn(t.now,t.timezone)}a(dp,"resolveAttributeDefaultValue");function ES(e,t,n){if(e.combinator==="or"&&e.rules.length>1)return {};let r=new Map(t.map(a=>[a.name,a])),o={};for(let a of e.rules){if(a.property!==void 0||Object.hasOwn(o,a.attribute))continue;let s=r.get(a.attribute);if(!s)continue;let c=pp(a,n);c!==void 0&&(o[a.attribute]=j(s).storage.cardinality==="many"?[c]:c);}return o}a(ES,"deriveCreateDefaultsFromFilters");function pp(e,t){if(e.operator==="is")return D$1(e.value)?Wa(e.value,t):e.value===null||Array.isArray(e.value)?void 0:e.value;if(e.operator==="any_of"){if(!Array.isArray(e.value)||e.value.length!==1)return;let n=e.value[0];return D$1(n)?Wa(n,t):n}}a(pp,"extractDeterministicValue");function Wa(e,t){if(t){if(e.dynamic==="actor")return t.userId;if(e.anchor==="today")return wn(t.now,t.timezone);if(e.anchor==="now")return t.now.toISOString()}}a(Wa,"resolveDynamicValue");function OS(e){let t=[];return e.canModify&&t.push("modify"),e.canSend&&t.push("send"),t}a(OS,"requestedCapabilities");var kS={status:"connector_status",error:"connector_error",provider:"connector_provider"};var mp=(t=>(t.Desktop="desktop",t))(mp||{});function MS(e){return e==="gmail"||e==="outlook"}a(MS,"isMailProvider");var fp=["threads","messages"];function FS(e){return fp.includes(e)}a(FS,"isMailboxListMode");var bp=["reply","reply_all"];function VS(e){return bp.includes(e)}a(VS,"isReplyMode");var BS=2e5,LS=998;var qS=["force","skip"],zS=["none","all","external_only"],WS="x-fake-signature",GS={override:null,status:"none",failureReason:null,botId:null};var gp=/^Session \d+$/;function Ga(e){let t=e.replace(/\s+/g," ").trim().replace(/[.!?]+$/,"");return t?t.length>60?`${t.slice(0,59).trimEnd()}...`:t:"New conversation"}a(Ga,"buildAgentFallbackTitle");function yp(e){let t=e.generated?.trim();return t&&!gp.test(t)?t:e.firstUserText?Ga(e.firstUserText):e.emptyLabel}a(yp,"conversationDisplayTitle");var Ei=/^[a-z0-9][a-z0-9-]{0,62}$/;function hp(e){if(!Ei.test(e))throw new h(`Invalid schema source id "${e}": expected a lowercase slug matching ${Ei}`,[])}a(hp,"assertSchemaSourceId");function ZS(e){let{attributeRemovals:t,objectRemovals:n,renames:r}=e.destructive;return t.length>0||n.length>0||r.length>0}a(ZS,"hasDestructiveEntries");var ce={objectAdditions:20,totalMutations:500,serializedBytes:512*1024};function Di(e){return e instanceof Error?e.message:String(e)}a(Di,"errorMessage");var Ap=z.enum(["text","richtext","number","checkbox","date","phone","currency","status","location","select","multiselect","user","relation","formula","rollup","document"]).describe('The attribute\'s data type. Determines which keys `config` accepts and requires: `status`/`select`/`multiselect` need a non-empty `options` array (each `status` option carrying its own `group`); `relation` needs `targets` (non-empty) and `cardinality` ("one" or "many"); `formula` needs `expression` and `returnType`; `rollup` needs `targetAttribute` and `function`. Every other type accepts only the shared presentation keys (`placeholder`, `defaultValue`, `icon`, ...) plus a few type-specific optionals (e.g. `number.decimals`, `date.dateFormat`). An attribute\'s type can never be changed later through this tool \u2014 only through a code migration \u2014 so pick it correctly now.');var Ya=z.string().min(1).superRefine((e,t)=>{try{St(e);}catch(n){t.addIssue({code:z.ZodIssueCode.custom,message:Di(n)});}}).describe('The attribute\'s machine name \u2014 the record\'s field key, and what `{{ name }}` refers to in a labelExpression. Must be a valid identifier: starts with a letter or underscore, then only letters/digits/underscores ("montantHt", "first_name", "FIRST_NAME" are valid; "first-name", "first name", "123name" are not). Max 63 characters. Cannot be a name reserved by the record shape itself (id, createdAt, updatedAt, createdBy, lastUpdatedBy, objectId, label, embeddingText, values, metadata, deletedAt, deletedBy, schemaVersion).'),xp=z.string().min(1).superRefine((e,t)=>{w$1(e)&&t.addIssue({code:z.ZodIssueCode.custom,message:`"${e}" is a reserved object name (${C$1.join(", ")}) and cannot be used for a new object.`});try{wt(e);}catch(n){t.addIssue({code:z.ZodIssueCode.custom,message:Di(n)});}}).describe(`The new object's machine name: kebab-case slug, lowercase letters/digits/hyphens only, starting with a letter ("products", "user-profiles", "order-items" are valid; "Products", "userProfiles", "user_profiles" are not). Max 63 characters. Cannot be a name the platform reserves for its own system objects, and cannot already exist.`);function Ha(e){return e.superRefine((t,n)=>{try{let r=n$1(t.type,{...t.config??{},description:t.description}),o=Object.keys(t.config??{}).filter(a=>!Object.hasOwn(r,a));o.length>0&&n.addIssue({code:"unrecognized_keys",keys:o,path:["config"],message:`Unrecognized attribute config key${o.length===1?"":"s"}: ${o.join(", ")}`});}catch(r){if(r instanceof h){for(let o of r.errors)n.addIssue({code:z.ZodIssueCode.custom,path:["config",...o.path.map(a=>/^\d+$/.test(a)?Number(a):a)],message:`Config for type "${t.type}" is invalid or incomplete: ${o.message}`});return}n.addIssue({code:z.ZodIssueCode.custom,path:["config"],message:`Config for type "${t.type}" is invalid or incomplete: ${Di(r)}`});}})}a(Ha,"withConfigCheck");var Ja=z.object({objectName:z.string().min(1).describe("Name of the existing (or, elsewhere in the same plan, newly created) object this attribute is added to. Ignored for an attribute declared inline in `additive.objects[].attributes` \u2014 there the parent object's own `name` is used instead."),name:Ya,label:z.string().min(1).max(128).describe("Human-readable display label shown in the UI. 1-128 characters, cannot be empty."),type:Ap,config:z.record(z.string(),z.unknown()).optional().describe('Type-specific configuration; required keys depend on `type` (see `type`\'s description). Shared optional keys on every type: `placeholder`, `defaultValue`, `icon`, `order`, `hidden`, `archived`, `deprecated`, `metadata`. Per-type keys: `text` \u2014 `multiline`, `minLength`, `maxLength`, `pattern`, `format` ("email"|"url"|"slug"); `number` \u2014 `renderAs` ("number"|"rating"), `min`, `max`, `unit`, `decimals`; `date` \u2014 `dateFormat`, `minDate`, `maxDate`, `includeTime`, `endDate`, `timeFormat` ("12h"|"24h"); `phone` \u2014 `defaultCountryCode` (3-letter); `currency` \u2014 `defaultCurrency`, `allowedCurrencies`, `allowNegative`; `status`/`select`/`multiselect` \u2014 `options` (REQUIRED, non-empty array of `{ value, label, color }`, unique `value`s; for `status` every OPTION also carries `group` as idle|in_progress|finished \u2014 `group` belongs on each option, never on `config` itself; select/multiselect accept `renderAs: "badges"`); `location` \u2014 `granularity`, `defaultCountry`, `allowedCountries`; `user` \u2014 `types` ("user"|"agent"), `multiple`; `relation` \u2014 `targets` (REQUIRED, non-empty array of `{ object }`) and `cardinality` (REQUIRED, "one"|"many"); `formula` \u2014 `expression` (REQUIRED formula string) and `returnType` (REQUIRED); `rollup` \u2014 `targetAttribute` (REQUIRED) and `function` (REQUIRED, e.g. "sum"|"avg"|"count"); `document` \u2014 `properties`, `accepts`, `maxFileSize`. Omit entirely for `richtext`/`checkbox`, which take no type-specific keys.'),required:z.boolean().optional().describe("Whether the attribute must have a value on every record. Defaults to false (optional)."),description:z.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),Tp=Ha(Ja),wp=Ha(Ja.omit({objectName:true})),Sp=z.object({name:xp,label:z.string().min(1).describe('Human-readable singular display label (e.g. "Devis").'),pluralLabel:z.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:z.string().optional().describe("Help text describing what this object represents."),icon:c.describe("Required icon name for the object. Must be a catalogue value \u2014 call `search_icons` and use a name it returns verbatim. A name that is not in the catalogue is rejected without any hint as to what would have worked, so never guess one."),labelExpression:et.describe('Template used to render a human-readable label for every record of this object \u2014 e.g. shown in relations, search results, and breadcrumbs. MUST contain at least one `{{ attributeName }}` interpolation referencing an attribute this object will actually have (either declared in this same `attributes` array, or an existing attribute if this is an update) \u2014 a plain string with no `{{ }}` at all (e.g. "Devis") is rejected. Interpolations cannot be empty (`{{ }}` is rejected) and only these pipes are allowed: UPPER, LOWER, capitalize, trim, prefix:"...", suffix:"...", wrap:"..." "...", default:"...". `{{ a || b }}` falls back to `b` when `a` is empty. Examples: "{{ firstName }} {{ lastName }}", "{{ numero | UPPER }}", "{{ name || reference }}".'),attributes:z.array(wp).default([]).describe("Attributes to create on this new object, inline. Same rules as a standalone entry in `additive.attributes`, minus `objectName` (implied by this object). At least one attribute referenced by `labelExpression` should be included here.")}).strict(),Qa=z.object({attributeRemovals:z.array(z.object({objectName:z.string().min(1).describe("Object the attribute is removed from."),attributeName:z.string().min(1).describe("Attribute to delete, together with every record's stored value for it. Must not be a system (code-declared) attribute, and must not be referenced by the object's own `labelExpression` or `embeddingExpression` \u2014 update those first.")}).strict()).default([]).describe("Attributes to permanently delete. Irreversible: record values for the attribute are purged."),objectRemovals:z.array(z.object({objectName:z.string().min(1).describe("Object to delete entirely, together with all its records. Must not be a system (code-declared) object, and must not still be targeted by a `relation` attribute on another object \u2014 retarget or remove that relation first.")}).strict()).default([]).describe("Objects to permanently delete, records included. Irreversible."),renames:z.array(z.object({objectName:z.string().min(1).describe("Object the renamed attribute belongs to."),from:z.string().min(1).describe("Current attribute name. Must already exist and not be a system attribute."),to:Ya.describe("New attribute name \u2014 same identifier rules as any attribute `name` (see `name` on a planned attribute), and must not collide with another name already on the object, including one added elsewhere in this same plan.")}).strict()).default([]).describe("Attribute renames. Every reference to the old name (labelExpression, views, formulas) must be updated separately \u2014 a rename does not follow references automatically.")}).strict().default({attributeRemovals:[],objectRemovals:[],renames:[]}),Xa=z.string().min(1).describe("ONE sentence naming the intent of the change \u2014 what it is for, not what it contains. The human approving it has already watched every entry land in the preview window and can read every row of the plan itself, so a recap tells them nothing they do not have. A second sentence is warranted only when `destructive` is non-empty: say plainly what will be lost (e.g. 'deletes the \"ancienMontant\" column and its data on every devis'). Never restate the plan \u2014 explain intent."),Za=z.object({objects:z.array(Sp).default([]),attributes:z.array(Tp).default([])}).strict().default({objects:[],attributes:[]});function Ni(e,t=[],n=new WeakSet){if(e===null||typeof e=="string"||typeof e=="boolean")return null;if(typeof e=="number")return Number.isFinite(e)?null:{path:t,message:"Plan input contains a non-finite number"};if(typeof e!="object")return {path:t,message:"Plan input must contain only JSON-safe values"};if(n.has(e))return {path:t,message:"Plan input cannot contain circular references"};if(Array.isArray(e)){n.add(e);for(let s of Reflect.ownKeys(e))if(s!=="length"&&(typeof s=="symbol"||!/^(0|[1-9]\d*)$/.test(s)))return n.delete(e),{path:[...t,s],message:"Plan input arrays cannot contain non-index JSON properties"};for(let s=0;s<e.length;s++){if(!Object.hasOwn(e,s))return n.delete(e),{path:[...t,s],message:"Plan input cannot contain sparse arrays"};let c=Ni(e[s],[...t,s],n);if(c)return n.delete(e),c}return n.delete(e),null}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return {path:t,message:"Plan input must contain only plain JSON objects"};n.add(e);let o=e,a=Reflect.ownKeys(o);for(let s of a){let c=Object.getOwnPropertyDescriptor(o,s);if(typeof s=="symbol"||!(c?.enumerable&&"value"in c))return n.delete(e),{path:[...t,s],message:"Plan input objects must contain enumerable JSON data properties only"}}for(let s of a.sort()){let c=Ni(o[s],[...t,s],n);if(c)return n.delete(e),c}return n.delete(e),null}a(Ni,"findJsonSafetyIssue");function Ip(e){let t=[];return e.additive.objects.forEach((n,r)=>{t.push(["additive","objects",r]),n.attributes.forEach((o,a)=>{t.push(["additive","objects",r,"attributes",a]);});}),e.additive.attributes.forEach((n,r)=>{t.push(["additive","attributes",r]);}),e.destructive.attributeRemovals.forEach((n,r)=>{t.push(["destructive","attributeRemovals",r]);}),e.destructive.objectRemovals.forEach((n,r)=>{t.push(["destructive","objectRemovals",r]);}),e.destructive.renames.forEach((n,r)=>{t.push(["destructive","renames",r]);}),t}a(Ip,"mutationPaths");function es(e,t){e.additive.objects.length>ce.objectAdditions&&t.addIssue({code:"too_big",origin:"array",maximum:ce.objectAdditions,inclusive:true,path:["additive","objects",ce.objectAdditions],message:`A schema plan can add at most ${ce.objectAdditions} objects`});let n=Ip(e);n.length>ce.totalMutations&&t.addIssue({code:"too_big",origin:"array",maximum:ce.totalMutations,inclusive:true,path:n[ce.totalMutations],message:`A schema plan can contain at most ${ce.totalMutations} mutations; received ${n.length}`});}a(es,"addPlanLimitIssues");function ts(e,t){let n=Ni(e);if(n)return t.addIssue({code:"custom",path:n.path,message:n.message}),z.NEVER;let r=new TextEncoder().encode(b$2(e)).byteLength;return r>ce.serializedBytes?(t.addIssue({code:"too_big",origin:"string",maximum:ce.serializedBytes,inclusive:true,path:[],message:`A schema plan can serialize to at most ${ce.serializedBytes} UTF-8 bytes; received ${r}`}),z.NEVER):e}a(ts,"boundSerializedPlanInput");var Ka=z.object({schemaPlanVersion:z.literal(2).describe("Required proposal contract version."),summary:Xa,additive:Za,destructive:Qa}).strict().superRefine(es),dI=Object.assign(z.preprocess(ts,Ka),{shape:Ka.shape}),Rp=z.object({schemaPlanVersion:z.literal(2),summary:Xa,additive:Za,destructive:Qa}).strict().superRefine(es),pI=z.preprocess(ts,Rp);function pt(e,t){throw new h(t,[{path:e,message:t}])}a(pt,"reject");function Sn(e){throw new h(`Unsupported schema reference variant ${String(e)}`,[])}a(Sn,"exhaustive");function AI(e){let t=new Map(e.objects.map(s=>[s.name,s])),n=[];function r(s,c,u){function d(g,A,x){(g.kind==="object"?t.has(g.object):g.kind==="attribute"?t.get(g.object)?.attributes.some(_=>_.name===g.attribute):true)||pt([...c,...x],`Unknown schema reference ${JSON.stringify(g)}`),n.push({owner:s,target:g,category:A,path:x,...u===void 0?{}:{layer:u}});}a(d,"add");function m(g,A,x,v){d({kind:"attribute",object:g,attribute:A},x,v);}a(m,"attribute");function p(g,A,x,v,_){m(g,A,x,v);let F=t.get(g)?.attributes.find(K=>K.name===A);return F?.type!=="relation"&&pt([...c,...v],`Invalid schema reference path "${_}"`),(F.targets.length!==1||F.targets[0].object==="*")&&pt([...c,...v],`Ambiguous schema reference path "${_}"`),F.targets[0].object}a(p,"traverse");function b(g,A,x,v){let _=g;for(let[F,K]of A.entries())F===A.length-1?m(_,K,x,v):_=p(_,K,x,v,A.join("."));}a(b,"attributePath");function y(g,A,x){switch(A.kind){case "literal":return;case "path":b(g,A.parts,"computed",x);return;case "call":for(let v of A.args)y(g,v,x);return;case "binary":y(g,A.left,x),y(g,A.right,x);return;default:Sn(A);}}return a(y,"formula"),{add:d,attribute:m,traverse:p,attributePath:b,formula:y}}a(r,"visitor"),e.objects.forEach((s,c)=>{let u=["objects",String(c)],d=r({kind:"object",object:s.name},u);for(let m of ["labelExpression","embeddingExpression"]){let p=s[m];if(p)for(let b of Tt(p))d.attributePath(s.name,b.split("."),"business",[m]);}s.attributes.forEach((m,p)=>{let b=[...u,"attributes",String(p)],y=r({kind:"attribute",object:s.name,attribute:m.name},b);switch(m.type){case "relation":m.targets.forEach((g,A)=>{if(g.object!=="*"&&y.add({kind:"object",object:g.object},"structural",["targets",String(A),"object"]),g.displayTemplate)for(let x of Tt(g.displayTemplate))y.attributePath(g.object,x.split("."),"business",["targets",String(A),"displayTemplate"]);for(let x of Object.keys(g.filter??{}))y.attribute(g.object,x,"business",["targets",String(A),"filter",x]);});break;case "formula":{let g;try{g=e$1(m.expression);}catch(A){pt([...b,"expression"],A instanceof Error?A.message:String(A));}y.formula(s.name,g,["expression"]),o(m,y);break}case "rollup":{let g=m.relationPath??m.relationAttribute,A=s.name;for(let x of g.split("."))A=y.traverse(A,x,"computed",[m.relationPath===void 0?"relationAttribute":"relationPath"],g);y.attributePath(A,m.targetAttribute.split("."),"computed",["targetAttribute"]),o(m,y);break}case "text":case "richtext":case "number":case "checkbox":case "date":case "phone":case "currency":case "status":case "location":case "select":case "multiselect":case "user":case "document":break;default:Sn(m);}});});function o(s,c){s.optionsSource&&(c.add({kind:"object",object:s.optionsSource.objectName},"computed",["optionsSource","objectName"]),c.attribute(s.optionsSource.objectName,s.optionsSource.attributeName,"computed",["optionsSource","attributeName"]));}a(o,"visitOptions");function a$1(s,c,u){r({kind:"view",object:s.object,view:s.name},c,u).add({kind:"object",object:s.object},"structural",["object"]),s.contents.forEach((d,m)=>{let p=r({kind:"content",object:s.object,view:s.name,content:d.name},[...c,"contents",String(m)],u);function b(y,g,A,x){y?.forEach((v,_)=>p.attribute(g,v,A,[x,String(_)]));}switch(a(b,"names"),d.type){case "collection":{let y;switch(d.source.object!==void 0?(y=d.source.object,p.add({kind:"object",object:y},"source",["source","object"])):y=p.traverse(s.object,d.source.relation,"source",["source","relation"],d.source.relation),d.columns?.forEach((g,A)=>{if(typeof g=="string"){p.attribute(y,g,"display",["columns",String(A)]);return}let x=t.get(s.object),v=d.source.relation===void 0||!x?void 0:ma(x,d.source.relation),_=["columns",String(A),"relationProperty"];v||pt([...c,"contents",String(m),..._],"Relation property columns require a relation source"),v.properties?.definitions.some(F=>F.name===g.relationProperty)||pt([...c,"contents",String(m),..._],`Unknown relation property "${g.relationProperty}"`),p.add({kind:"attribute",object:s.object,attribute:v.name},"display",_);}),b(d.displayAttributes,y,"display","displayAttributes"),d.descriptionAttribute!==void 0&&p.attribute(y,d.descriptionAttribute,"display",["descriptionAttribute"]),d.filters?.rules.forEach((g,A)=>p.attribute(y,g.attribute,"business",["filters","rules",String(A),"attribute"])),d.sorts?.forEach((g,A)=>p.attribute(y,g.attribute,"business",["sorts",String(A),"attribute"])),d.layout){case "table":case "list":if(d.columnSizing)for(let g of Object.keys(d.columnSizing))p.attribute(y,g,"display",["columnSizing",g]);break;case "kanban":p.attribute(y,d.groupByAttribute,"business",["groupByAttribute"]);break;default:Sn(d);}break}case "form":d.groups.forEach((y,g)=>y.fields.forEach((A,x)=>p.attribute(s.object,A.attribute,"display",["groups",String(g),"fields",String(x),"attribute"])));break;case "richtext":p.attribute(s.object,d.attribute,"source",["attribute"]),d.titleAttribute!==void 0&&p.attribute(s.object,d.titleAttribute,"display",["titleAttribute"]);break;case "documents":b(d.relations,s.object,"business","relations");break;case "forms":d.objectName!==void 0&&p.add({kind:"object",object:d.objectName},"source",["objectName"]);break;case "emails":case "meetings":b(d.emailAttributes,s.object,"business","emailAttributes");break;case "activity":case "custom":break;default:Sn(d);}});}return a(a$1,"viewReferences"),e.views.forEach((s,c)=>a$1(s,["views",String(c)])),e.retainedViews?.forEach(({definition:s,layer:c},u)=>a$1(s,["retainedViews",String(u),"definition"],c)),n}a(AI,"collectSchemaReferences");var ns=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function L(e,t,n){throw new h(n,[{path:[...e.split("."),t],message:n}])}a(L,"reject");function Oi(e){return e.join("|")}a(Oi,"pairKey");function ki(e,t){return [e,t].sort()}a(ki,"pairedAddresses");function Cp(e){let t=new Map,n=new Map,r=new Set;for(let o of e){let a=Oi(o.addresses);(!ns.test(o.id)||o.addresses[0]===o.addresses[1]!=(o.symmetric===true))&&L(o.addresses[0],"pair",`Invalid stored pair identity for ${a}`),(t.has(a)||n.has(o.id)&&n.get(o.id)!==a||o.addresses.some(s=>r.has(s)))&&L(o.addresses[0],"pair",`Duplicate stored pair identity for ${a}`),o.addresses.includes(o.ownerAddress)||L(o.addresses[0],"pair",`Invalid property owner for ${a}`),t.set(a,o),n.set(o.id,a);for(let s of o.addresses)r.add(s);}return t}a(Cp,"validateExistingPairs");function vp(e,t){let n=new Set(e.flatMap(s=>s.addresses)),r=new Map,o=new Set;for(let{from:s,to:c}of t)(!n.has(s)||s===c||r.has(s)||o.has(c))&&L(s,"rename",`Invalid or duplicate relation attribute rename ${s} to ${c}`),r.set(s,c),o.add(c);let a$1=a(s=>r.get(s)??s,"mapped");return e.map(s=>({...s,addresses:ki(a$1(s.addresses[0]),a$1(s.addresses[1])),ownerAddress:a$1(s.ownerAddress),generatedAddresses:s.generatedAddresses.map(a$1)}))}a(vp,"remapExistingPairs");function Ep(e,t,n){return e.type==="relation"&&e.bilateral?.object===t&&e.bilateral.attribute===n&&e.targets.length===1&&e.targets[0]?.object===t}a(Ep,"isReciprocal");function Np(e,t,n){let r=e.bilateral;r||L(`${t}.${e.name}`,"bilateral","Missing inverse address");let o={type:"relation",name:r.attribute,label:r.label??r.attribute,required:false,targets:[{object:t}],bilateral:{object:t,attribute:e.name,cardinality:e.cardinality},order:n};return (r.cardinality??wo(e.cardinality))==="one"?{...o,cardinality:"one"}:{...o,cardinality:"many"}}a(Np,"generateInverse");function Dp(e,t,n,r,o){e.bilateral?.cardinality&&e.bilateral.cardinality!==t.cardinality&&L(r,"cardinality",`${n} declares ${r} as ${e.bilateral.cardinality}, but ${r} declares ${t.cardinality}`),t.bilateral?.cardinality&&t.bilateral.cardinality!==e.cardinality&&L(n,"cardinality",`${r} declares ${n} as ${t.bilateral.cardinality}, but ${n} declares ${e.cardinality}`),e.bilateral?.label&&e.bilateral.label!==t.label&&L(r,"label",`${n} declares a different label for ${r}`),t.bilateral?.label&&t.bilateral.label!==e.label&&L(n,"label",`${r} declares a different label for ${n}`),e.properties&&t.properties&&!j$1(e.properties,t.properties)&&!o&&L(r,"properties",`${n} and ${r} declare different qualified properties`),e.bilateral?.storageOwner===t.bilateral?.storageOwner&&e.bilateral?.storageOwner!==void 0&&L(r,"storageOwner",`${n} and ${r} cannot both own or both disown qualified properties`);}a(Dp,"checkExplicitDeclarations");function Op(e,t,n,r,o,a){return o?o.ownerAddress:e.bilateral?.storageOwner===true||t.bilateral?.storageOwner===false?n:e.bilateral?.storageOwner===false||t.bilateral?.storageOwner===true?r:a?n:ki(n,r)[0]}a(Op,"chooseOwner");function kp(e){if(!e.metadata)return;let{relationPairId:t,relationGenerated:n,...r}=e.metadata;e.metadata=Object.keys(r).length>0?r:void 0;}a(kp,"stripUntrustedPairMetadata");function jp(e,t,n,r,o,a){a.has(n)&&a.has(r)&&!j$1(e.properties,t.properties)&&L(r,"properties",`${n} and ${r} edit different qualified properties`);let s=a.has(n)||o.has(n)&&!o.has(r)&&!a.has(r),c=a.has(r)||o.has(r)&&!o.has(n)&&!a.has(n),u=s?e.properties:c?t.properties:e.properties??t.properties;u?(e.properties=structuredClone(u),t.properties=structuredClone(u)):(delete e.properties,delete t.properties);}a(jp,"reconcileProperties");function ji(e){let t=structuredClone(e.objects),n=new Map;for(let p of t){if(n.has(p.name))throw new r("object",p.name);n.set(p.name,p);let b=new Set;for(let y of p.attributes){if(b.has(y.name))throw new r("attribute",y.name);b.add(y.name),kp(y);}}let r$1=vp(e.existingPairs??[],e.addressRenames??[]),o=Cp(r$1),a=new Set(r$1.flatMap(p=>p.generatedAddresses)),s=new Set(e.propertyEditAddresses??[]),c=new Set(e.explicitAddresses??t.flatMap(p=>p.attributes.filter(b=>!a.has(`${p.name}.${b.name}`)).map(b=>`${p.name}.${b.name}`))),u=t.flatMap(p=>p.attributes.filter(b=>b.type==="relation"&&!!b.bilateral).map(b=>({object:p,attribute:b,address:`${p.name}.${b.name}`}))).sort((p,b)=>p.address.localeCompare(b.address)),d=new Map,m=new Map;for(let{object:p,attribute:b,address:y}of u){let g=b.bilateral?.object;(!g||g==="*"||b.targets.length!==1||b.targets[0]?.object!==g)&&L(y,"targets",`Bilateral target of ${y} must be one concrete object`);let A=n.get(g);A||L(y,"bilateral",`Unknown inverse object ${g} for ${y}`);let x=`${g}.${b.bilateral?.attribute}`,v=y===x;v&&b.cardinality!=="many"&&L(y,"cardinality",`Symmetric self relation ${y} must be many`),v&&b.bilateral?.cardinality&&b.bilateral.cardinality!==b.cardinality&&L(y,"bilateral",`Symmetric self relation ${y} needs matching cardinality`);let _=ki(y,x),F=Oi(_);if(d.has(F))continue;let K=A.attributes.find(xe=>xe.name===b.bilateral?.attribute);if(K&&!Ep(K,p.name,b.name))throw new r("attribute",x);let Je=!(K&&c.has(x));K||(K=Np(b,p.name,A.attributes.length),A.attributes.push(K));let Y=K;!v&&c.has(y)&&c.has(x)&&Dp(b,Y,y,x,s.has(y)!==s.has(x));let k=o.get(F),P=k?.id??e.nextPairId(_),ie=r$1.find(xe=>xe.id===P&&Oi(xe.addresses)!==F);(!ns.test(P)||ie||m.has(P)&&m.get(P)!==F)&&L(y,"pair",`Invalid or duplicate pair identity for ${y} and ${x}`),m.set(P,F);let ee=v?y:Op(b,Y,y,x,k,Je);b.bilateral&&Y.bilateral||L(y,"bilateral",`Missing reciprocal configuration for ${y} and ${x}`),b.bilateral={...b.bilateral,cardinality:Y.cardinality,label:Y.label,storageOwner:ee===y},Y.bilateral={...Y.bilateral,cardinality:b.cardinality,label:b.label,storageOwner:ee===x},jp(b,Y,y,x,c,s),b.metadata={...b.metadata,relationPairId:P},Y.metadata={...Y.metadata,relationPairId:P},d.set(F,{id:P,addresses:_,ownerAddress:ee,generatedAddresses:_.filter(xe=>!c.has(xe)),...v?{symmetric:true}:{}});}return {objects:t,pairs:[...d.values()].sort((p,b)=>p.addresses[0].localeCompare(b.addresses[0]))}}a(ji,"reconcileRelationAttributes");var E=z.number().finite().nonnegative(),is=z.enum(Io),_i=z.enum(Ro),Pi=z.enum(Co),os=z.object({provider:is,model:z.string().min(1)}).strict(),DI=z.object({speed:_i.optional(),reasoning:Pi.optional()}).strict(),as=z.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),_p=z.object({model:os.optional(),speed:_i.optional(),reasoning:Pi.optional(),imageModel:as.optional()}).strict(),OI=_p.refine(e=>e.model!==void 0||e.speed!==void 0||e.reasoning!==void 0||e.imageModel!==void 0,{message:"At least one inference override is required"}),kI=z.object({model:os.nullable().optional(),speed:_i.nullable().optional(),reasoning:Pi.nullable().optional(),imageModel:as.nullable().optional()}).strict().refine(e=>Object.keys(e).length>0&&Object.values(e).every(t=>t!==void 0),{message:"At least one inference override is required"}),ss=z.object({label:z.string(),denied:z.boolean().optional(),deletion:z.object({target:z.string().optional(),count:E.optional(),restorableDays:E.optional()}).strict().optional(),counts:z.record(z.string(),E).optional(),warnings:z.array(z.string()).optional()}).strict(),Pp=z.union([z.object({type:z.literal("text"),text:z.string()}).strict(),z.object({type:z.literal("reasoning"),text:z.string()}).strict(),z.object({type:z.literal("system"),code:z.enum(Mn)}).strict(),z.object({type:z.literal("error"),error:z.string(),errorClass:z.string().optional()}).strict(),z.object({type:z.literal("tool"),toolCallId:z.string(),name:z.string(),args:z.record(z.string(),z.unknown()),result:z.unknown().optional(),error:z.string().optional(),errorCode:z.enum(["output_limit_reached","interrupted"]).optional(),state:z.enum(["streaming","running","completed","error","pending","approval-requested","approval-responded","approval-dispatched"]),durationMs:E.optional(),approvalId:z.string().optional(),approvalImpact:ss.optional(),approved:z.boolean().optional(),approvalReason:z.string().optional(),approvalRelaxableByAuto:z.boolean().optional()}).strict(),z.object({type:z.literal("file"),fileId:z.string(),name:z.string(),mimeType:z.string()}).strict(),z.object({type:z.literal("compaction"),state:z.literal("in-progress"),reason:z.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:E.optional(),reportedTokens:E.optional()}).strict(),z.object({type:z.literal("compaction"),state:z.literal("completed"),tokensBefore:E,tokensAfter:E,tokensSaved:E,strategy:z.enum(["no-op","summary","truncation"]),durationMs:E,summary:z.string().optional()}).strict(),z.object({type:z.literal("compaction"),state:z.literal("failed"),reason:z.string(),durationMs:E.optional()}).strict()]),Mp=z.object({id:z.string(),name:z.string(),mimeType:z.string(),size:E}).strict(),Fp=z.object({id:z.string(),type:z.string().transform(e=>e),entityId:z.string(),label:z.string(),objectName:z.string().optional(),startIndex:E,endIndex:E}).strict(),Vp=z.object({provider:is,model:z.string(),maxTokens:E.optional(),contextWindow:E.optional()}).strict(),Bp=z.union([z.date(),z.string().datetime({offset:true}).transform(e=>new Date(e))]),rs=z.object({id:z.string(),sessionId:z.string(),tenantId:z.string().optional(),runId:z.string().optional(),role:z.enum(["user","assistant","system","tool"]),parts:z.array(Pp),attachments:z.array(Mp).optional(),mentions:z.array(Fp).optional(),model:Vp.optional(),tokenUsage:z.object({input:E,output:E}).strict().optional(),metadata:z.record(z.string(),z.unknown()).optional(),createdAt:Bp}).strict(),Lp=z.object({id:z.string(),description:z.string(),status:z.enum(["pending","in_progress","completed","blocked"]),result:z.string().optional(),updatedAt:E.optional()}).strict(),$p=z.object({id:z.string(),sessionId:z.string(),status:z.enum(["active","completed","abandoned"]),todos:z.array(Lp),version:E,createdAt:z.string(),updatedAt:z.string(),completedAt:z.string().optional()}).strict(),cs={"session-named":z.object({name:z.string()}).strict(),"compaction-start":z.object({reason:z.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:E.optional(),reportedTokens:E.optional()}).strict(),"compaction-end":z.object({tokensBefore:E,tokensAfter:E,tokensSaved:E,strategy:z.enum(["no-op","summary","truncation"]),durationMs:E,summary:z.string().optional()}).strict(),"compaction-failed":z.object({reason:z.string()}).strict(),usage:z.object({messageId:z.string().min(1).optional(),inputTokens:E,outputTokens:E,totalTokens:E,cacheReadTokens:E.optional(),cacheCreationTokens:E.optional(),contextWindow:E,residentTokens:E,utilization:z.number().finite().min(0).max(1),costUsd:E.optional()}).strict(),"message-persisted":z.object({message:rs}).strict(),"message-updated":z.object({message:rs}).strict(),"todo-plan-update":z.object({plan:$p}).strict(),"approval-context":z.object({approvalId:z.string(),toolCallId:z.string(),impact:ss.optional(),relaxableByAuto:z.boolean().optional()}).strict(),"session-state":z.object({state:z.object({phase:z.enum(["queued","running","parked","terminal"]),parkedOn:z.enum(["human","agents"]).optional(),humanRequestIds:z.array(z.string()).optional(),outcome:z.enum(["completed","failed","cancelled","timeout","expired"]).optional()}).strict(),version:z.number().int().positive(),updatedAt:z.string().datetime({offset:true})}).strict()};function Up(e){return e in cs}a(Up,"isAgentUIDataName");function qp(e){return new h("Invalid agent UI message chunk",e.map(t=>({path:t.path.map(String),message:t.message,code:t.code})))}a(qp,"agentUIValidationError");function zp(e){if(typeof e!="object"||e===null||typeof e.type!="string")throw new h("Invalid agent UI message chunk",[{path:["type"],message:"Expected UI message chunk type",code:"invalid_type"}]);let t=e.type;if(!t.startsWith("data-"))throw new h("Invalid agent UI message chunk",[{path:["type"],message:"Expected agent data chunk type",code:"invalid_value"}]);let n=t.slice(5);if(!Up(n))throw new h("Invalid agent UI message chunk",[{path:["type"],message:`Unknown agent UI data type: ${n}`,code:"invalid_value"}]);let r=z.object({type:z.literal(`data-${n}`),id:z.string().optional(),data:cs[n],transient:z.boolean().optional()}).strict().safeParse(e);if(!r.success)throw qp(r.error.issues);return r.data}a(zp,"assertCustomAgentUIMessageChunk");function jI(e,t,n){return zp({type:`data-${e}`,...n?.id!==void 0?{id:n.id}:{},data:t,...n?.transient!==void 0?{transient:n.transient}:{}})}a(jI,"agentDataChunk");function Mi(e){return e}a(Mi,"defineOperation");function V(e,t,n){let r=t==="atomic"?"none":t==="local"?"if-not-visible":"follow";return o=>{let a=n?.(o);return {impact:t,navigation:r,focus:{...e(o),...a===void 0?{}:{propertyPath:a}}}}}a(V,"definePresentation");function Wp(e){return {id:e.id??e.name,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon}}}a(Wp,"toDraftableObject");function Gp(e){let t=e.id??e.name;return (e.attributes??[]).map(n=>Fi(n,t))}a(Gp,"toDraftableAttributes");function Z(e){return {id:e.id,name:e.name,label:e.label,type:e.attributeType,...e.config}}a(Z,"toAttribute");function Fi(e,t){let{id:n,name:r,label:o,type:a,...s}=e;return {id:e.id??e.name,objectId:t,name:e.name,label:e.label??e.name,attributeType:e.type,config:s}}a(Fi,"toDraftableAttribute");function us(e){let t=e[0];return t?`{{ ${t.name} }}`:"{{ id }}"}a(us,"draftedLabelExpression");function Vi(e,t){let n=t.filter(r=>r.objectId===e.id);return {id:e.id,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},labelExpression:us(n),attributes:n.map((r,o)=>{let a=Z(r);return a.order===void 0?{...a,order:o}:a})}}a(Vi,"draftedObjectDefinition");function Kp(e,t,n=Nt(e.contents)){return structuredClone({...e,...t,authoring:n})}a(Kp,"toDraftableView");function mt(e){let{id:t,revision:n,contentIds:r,contentRevisions:o,derived:a,authoring:s,...c}=e;return structuredClone(c)}a(mt,"draftedViewDefinition");function Yp(e,t){return {...e,...mt(t)}}a(Yp,"fromDraftableView");var _t={id:z.string().min(1),objectName:z.string().min(1),viewName:z.string().min(1)},Pt={..._t,contentName:z.string().min(1)},ms=z.union([z.object({before:z.string().min(1)}).strict(),z.object({after:z.string().min(1)}).strict(),z.object({end:z.literal(true)}).strict()]),ze=a(e=>({objectName:e.objectName,viewName:e.viewName}),"viewFocus"),_e=a(e=>({...ze(e),contentName:e.contentName}),"contentFocus");function ue(e,t){throw new h(t,[{path:e,message:t}])}a(ue,"invalid");function Ce(e,t,n,r){let o=e.views.findIndex(u=>u.object===t.objectName&&u.name===t.viewName);o<0&&ue(["viewName"],"View is not in the draftable state"),e.views[o].authoring||ue(["authoring"],"Missing view authoring baseline");let{derived:a,...s}=r(structuredClone(e.views[o]));s.contents=li(s.authoring);let c=e.views.map((u,d)=>d===o?s:u);return di({extensions:[...n.extensions],objects:e.objects.map(u=>Vi(u,e.attributes.filter(d=>d.objectId===u.id))),views:c.map(mt)}),{...e,views:c}}a(Ce,"change");function We(e,t){let n=Object.hasOwn(e.authoring.contents,t)?e.authoring.contents[t]:void 0;return n||ue(["contentName"],"Content is not in the draftable state"),n}a(We,"contentState");function Bi(e,t,n){for(let r of n)e.authoring[r==="main"?"mainOrderCustomized":"asideOrderCustomized"]=true,t.filter(o=>o.placement===r).forEach((o,a)=>{We(e,o.name).workspacePosition=a;});}a(Bi,"setOrder");function Li(e,t){let n=e.contents.find(r=>r.name===t);return n||ue(["contentName"],"Content is not in the draftable state"),n}a(Li,"find");function fs(e,t,n){let r=e.filter(s=>s.name!==t.name),o=r.filter(s=>s.placement===t.placement),a=o.length;if(!("end"in n)){let s="before"in n?n.before:n.after;a=o.findIndex(c=>c.name===s),a<0&&ue(["target"],"Order target is not in this placement"),"after"in n&&a++;}return o.splice(a,0,t),t.placement==="main"?[...o,...r.filter(s=>s.placement==="aside")]:[...r.filter(s=>s.placement==="main"),...o]}a(fs,"placed");var Hp=z.unknown().transform((e,t)=>{let n=ca$1.safeParse(typeof e=="object"&&e!==null?{...e,name:"candidate"}:e);if(!n.success){for(let a of n.error.issues)t.addIssue({code:"custom",path:a.path,message:a.message});return z.NEVER}if(typeof e=="object"&&e!==null&&"name"in e)return t.addIssue({code:"custom",path:["name"],message:"Content name is the operation target"}),z.NEVER;let{name:r,...o}=n.data;return o}),bs=z.object({...Pt,type:z.literal("replace_view_content"),definition:Hp}).strict(),Jp={type:"replace_view_content",schema:bs,focus:_e,presentation:V(_e,"local"),describe:a(e=>`Replace ${e.objectName}.${e.viewName}.${e.contentName}`,"describe"),apply:a((e,t,n)=>Ce(e,t,n,r=>(Li(r,t.contentName).placement!==t.definition.placement&&ue(["definition","placement"],"Use move_view_content to change placement"),We(r,t.contentName).workspaceDefinition=structuredClone(t.definition),{...r,contents:r.contents.map(a=>a.name===t.contentName?{...t.definition,name:t.contentName}:a),contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}})),"apply")},gs=z.object({..._t,type:z.literal("add_view_content"),content:ca$1,target:ms}).strict(),ls=a(e=>({...ze(e),contentName:e.content.name}),"addFocus"),Qp={type:"add_view_content",schema:gs,focus:ls,presentation:V(ls,"structural"),describe:a(e=>`Add ${e.content.name}`,"describe"),apply:a((e,t,n)=>Ce(e,t,n,r$1=>{if(Object.hasOwn(r$1.authoring.contents,t.content.name))throw new r("content",t.content.name);r$1.authoring.contents={...r$1.authoring.contents,[t.content.name]:{sourceDefinition:null,workspaceDefinition:Et(t.content),suppressed:false,sourcePosition:null,workspacePosition:0}};let o=fs(r$1.contents,t.content,t.target);return Bi(r$1,o,[t.content.placement]),{...r$1,revision:r$1.revision+1,contents:o,contentIds:{...r$1.contentIds,[t.content.name]:JSON.stringify(["draft-content",t.id])},contentRevisions:{...r$1.contentRevisions,[t.content.name]:1}}}),"apply")},ys=z.object({...Pt,type:z.literal("remove_view_content")}).strict(),Xp={type:"remove_view_content",schema:ys,focus:_e,presentation:V(_e,"structural"),describe:a(e=>`Remove ${e.contentName}`,"describe"),apply:a((e,t,n)=>Ce(e,t,n,r=>{let o=Li(r,t.contentName),a=We(r,t.contentName),s=r.contents.filter(p=>p.name!==t.contentName);if(Bi(r,s,[o.placement]),a.sourceDefinition!==null)return a.workspaceDefinition=null,a.suppressed=true,{...r,revision:r.revision+1,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}};delete r.authoring.contents[t.contentName];let{[t.contentName]:c,...u}=r.contentIds,{[t.contentName]:d,...m}=r.contentRevisions;return {...r,revision:r.revision+1,contents:r.contents.filter(p=>p.name!==t.contentName),contentIds:u,contentRevisions:m}}),"apply")},hs=z.object({...Pt,type:z.literal("move_view_content"),placement:z.enum(["main","aside"]),target:ms}).strict(),Zp={type:"move_view_content",schema:hs,focus:_e,presentation:V(_e,"structural"),describe:a(e=>`Move ${e.contentName}`,"describe"),apply:a((e,t,n)=>Ce(e,t,n,r=>{let o=Li(r,t.contentName);o.placement!==t.placement&&(We(r,t.contentName).workspaceDefinition={...Et(o),placement:t.placement});let a=fs(r.contents,{...o,placement:t.placement},t.target);return Bi(r,a,[...new Set([o.placement,t.placement])]),{...r,revision:r.revision+1,contents:a,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+ +(o.placement!==t.placement)}}}),"apply")},As=z.object({..._t,type:z.literal("update_view_metadata"),changes:z.object({label:z.string().min(1).optional(),description:z.string().optional(),icon:c.nullable().optional()}).strict().refine(e=>Object.keys(e).length>0)}).strict(),em={type:"update_view_metadata",schema:As,focus:ze,presentation:V(ze,"atomic"),describe:a(e=>`Update ${e.viewName}`,"describe"),apply:a((e,t,n)=>Ce(e,t,n,r=>{let{icon:o,...a}=t.changes,s={...r,...a,revision:r.revision+1};if(o===null){let{icon:c,...u}=s;return u}return o===void 0?s:{...s,icon:o}}),"apply")},xs=z.string().refine(e=>e.trim().length>0,"API name must not be blank"),Ts=z.object({..._t,type:z.literal("rename_view"),newName:xs}).strict(),ds=a(e=>({objectName:e.objectName,viewName:e.newName}),"renameViewFocus"),tm={type:"rename_view",schema:Ts,focus:ds,presentation:V(ds,"structural"),describe:a(e=>`Rename view ${e.viewName} to ${e.newName}`,"describe"),apply:a((e,t,n)=>Ce(e,t,n,r=>t.newName===r.name?r:(r.authoring.origin==="code"&&ue(["newName"],"Source-owned API names must be changed in their declaration"),e.views.some(o=>o.object===t.objectName&&o.name===t.newName)&&ue(["newName"],"View API name is already used"),{...r,name:t.newName,revision:r.revision+1})),"apply")},ws=z.object({...Pt,type:z.literal("rename_view_content"),newName:xs}).strict(),ps=a(e=>({...ze(e),contentName:e.newName}),"renameContentFocus"),nm={type:"rename_view_content",schema:ws,focus:ps,presentation:V(ps,"structural"),describe:a(e=>`Rename content ${e.contentName} to ${e.newName}`,"describe"),apply:a((e,t,n)=>Ce(e,t,n,r=>{let o=We(r,t.contentName);if(t.newName===t.contentName)return r;o.sourceDefinition!==null&&ue(["newName"],"Source-owned API names must be changed in their declaration"),Object.hasOwn(r.authoring.contents,t.newName)&&ue(["newName"],"Content API name is already used");let a=r.contentIds[t.contentName],s=r.contentRevisions[t.contentName];return delete r.authoring.contents[t.contentName],delete r.contentIds[t.contentName],delete r.contentRevisions[t.contentName],r.authoring.contents={...r.authoring.contents,[t.newName]:o},{...r,revision:r.revision+1,contentIds:{...r.contentIds,[t.newName]:a},contentRevisions:{...r.contentRevisions,[t.newName]:s+1}}}),"apply")},Ss=z.object({...Pt,type:z.literal("reset_view_content")}).strict(),rm={type:"reset_view_content",schema:Ss,focus:_e,presentation:V(_e,"structural"),describe:a(e=>`Reset ${e.contentName} to source`,"describe"),apply:a((e,t,n)=>Ce(e,t,n,r=>{let o=We(r,t.contentName);return o.sourceDefinition===null&&ue(["contentName"],"Content has no source to reset to"),o.workspaceDefinition===null&&!o.suppressed&&o.workspacePosition===null?r:(o.workspaceDefinition=null,o.suppressed=false,o.workspacePosition=null,{...r,revision:r.revision+1,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}})}),"apply")},Is=z.object({..._t,type:z.literal("reset_view_order"),placement:z.enum(["main","aside"])}).strict(),im={type:"reset_view_order",schema:Is,focus:ze,presentation:V(ze,"structural"),describe:a(e=>`Reset ${e.placement} order`,"describe"),apply:a((e,t,n)=>Ce(e,t,n,r=>{let o=t.placement==="main"?"mainOrderCustomized":"asideOrderCustomized";if(!r.authoring[o])return r;r.authoring[o]=false;for(let a of r.contents.filter(s=>s.placement===t.placement)){let s=We(r,a.name);s.sourceDefinition!==null&&(s.workspacePosition=null);}return {...r,revision:r.revision+1}}),"apply")},$i=z.discriminatedUnion("type",[bs,gs,ys,hs,As,Ts,ws,Ss,Is]),ft=[Jp,Qp,Xp,Zp,em,tm,nm,rm,im];function Rs(e,t){return e.objects.find(n=>n.id===t)}a(Rs,"findObject");var om=new Set(["formula","rollup"]);function bt(e){return om.has(e.attributeType)}a(bt,"isComputedAttribute");var Cs={sum:"number",avg:"number",count:"number",countValues:"number",countUniqueValues:"number",countEmpty:"number",percentEmpty:"number",percentNotEmpty:"number",earliest:"date",latest:"date",original:"multiselect"};function am(e){return typeof e=="string"&&e in Cs?Cs[e]:void 0}a(am,"rollupReturnTypeOf");function Es(e,t){let n=Rs(e,t);if(!n)throw new h(`Object "${t}" is not in the draftable state`,[]);return n}a(Es,"requireObject");function In(e){return e.config??{}}a(In,"configOf");function le(e){let t=In(e).targets;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.object=="string"):[]}a(le,"relationTargets");function gt(e){let t=le(e).filter(n=>n.object!==we);return t.length===1?t[0]?.object:void 0}a(gt,"relationTargetObjectName");function sm(e){let t=In(e),n=e.attributeType,r={name:e.name,type:n,id:e.id},o=t.optionsSource;if(n==="relation"){let a=gt(e);return {...r,...t.cardinality==="one"||t.cardinality==="many"?{cardinality:t.cardinality}:{},...a===void 0?{}:{targetObjectName:a},targets:le(e)}}if(n==="formula")return {...r,...t.returnType===void 0?{}:{returnType:t.returnType},...o===void 0?{}:{optionsSource:o}};if(n==="rollup"){let a=am(t.function);return {...r,...a===void 0?{}:{returnType:a},...o===void 0?{}:{optionsSource:o}}}return n==="select"||n==="status"||n==="multiselect"?{...r,...Array.isArray(t.options)?{options:t.options}:{}}:r}a(sm,"toCompileAttribute");function vs(e,t){return {objectName:e.name,attributes:t.filter(n=>n.objectId===e.id).map(sm)}}a(vs,"toCompileObject");function Ui(e,t){let n=Es(e,t);return {...vs(n,e.attributes),relatedObjects:Object.fromEntries(e.objects.map(r=>[r.name,vs(r,e.attributes)]))}}a(Ui,"computedCompileSchemaOf");function cm(e){return {id:e.id,name:e.name,label:e.label,type:"rollup",...In(e)}}a(cm,"toRollupAttribute");function Ns(e){try{return e()}catch(t){throw t instanceof S?new h(t.message,[]):t}}a(Ns,"asValidationError");function Rn(e,t){let n=Ui(e,t.objectId);return Ns(()=>Ds(t,n))}a(Rn,"computedPlanOf");function Ds(e,t){if(e.attributeType==="rollup")return Oa(cm(e),t);let n=In(e);return mn({attributeName:e.name,expression:String(n.expression??""),returnType:n.returnType,schema:t})}a(Ds,"compilePlan");function qi(e){Ns(()=>va(e.map(t=>({attributeName:t.attributeName,dependencies:t.dependencies}))));}a(qi,"assertAcyclicComputed");function um(e,t){switch(e.kind){case "local":case "computed":return e.attributeName===t;case "relation":return e.relationName===t;case "options":return false;default:return e}}a(um,"dependencyNames");function Mt(e,t){let n=Ui(e,t),r=[];for(let o of e.attributes)if(!(o.objectId!==t||!bt(o)))try{r.push(Ds(o,n));}catch(a){if(!(a instanceof S))throw a}return r}a(Mt,"compilablePlansOf");function zi(e,t,n){let r=Es(e,t),o=[];for(let a of Mt(e,t))a.attributeName!==n&&a.dependencies.some(s=>um(s,n))&&o.push(a.attributeName);for(let a of e.objects)if(a.id!==t)for(let s of Mt(e,a.id))s.dependencies.some(u=>{if(u.kind!=="relation"||u.targetAttributeName!==n)return false;let d=e.attributes.find(m=>m.objectId===a.id&&m.name===u.relationName&&m.attributeType==="relation");return d!==void 0&>(d)===r.name})&&o.push(`${a.name}.${s.attributeName}`);return o}a(zi,"dependentsOf");function Ae(e){let t=e.config?.bilateral;if(typeof t!="object"||t===null)return;let{object:n,attribute:r}=t;return typeof n=="string"&&typeof r=="string"?{object:n,attribute:r}:void 0}a(Ae,"bilateralDeclarationOf");function lm(e,t){return t!==void 0&&e.attributeType===t.attributeType&&dm(e,t)}a(lm,"sameAttribute");function dm(e,t){return JSON.stringify(e.config??{})===JSON.stringify(t.config??{})}a(dm,"sameConfig");function pm(e,t){let n=a(r=>lm(r,e.attributes.find(o=>o.id===r.id)),"untouched");for(let r of t.attributes){if(r.attributeType!=="relation")continue;let o=Ae(r);if(o===void 0||n(r))continue;let s=t.objects.find(y=>y.id===r.objectId)?.name??r.objectId,c=t.objects.find(y=>y.name===o.object),u=t.attributes.find(y=>y.objectId===c?.id&&y.name===o.attribute),d=`relation "${s}.${r.name}" declares inverse "${o.object}.${o.attribute}"`;if(u===void 0)throw new h(`${d}, which object "${o.object}" does not have; draft it first`,[]);if(u.attributeType!=="relation")throw new h(`${d}, which is not a relation`,[]);let m=Ae(u);if(!(le(u).some(y=>y.object===s)&&(n(u)?m===void 0||m.object===s&&m.attribute===r.name:m?.object===s&&m.attribute===r.name)))throw new h(`${d}, which does not point back to "${s}.${r.name}"`,[])}}a(pm,"assertBilateralPairs");var mm=0x100000001b3n,fm=0xffffffffffffffffn;function Os(e,t){let n=t;for(let r of new TextEncoder().encode(e))n^=BigInt(r),n=n*mm&fm;return n}a(Os,"fnv1a64");function Wi(e,t){return Cn(t,e.toLowerCase())}a(Wi,"viewIdFor");function Cn(e,t){let n=`${t}:${e}`,r=Os(n,0xcbf29ce484222325n).toString(16).padStart(16,"0"),o=Os(`${e}:${n}`,0x84222325cbf29ce4n).toString(16).padStart(16,"0"),a=r+o,s=(Number.parseInt(a[16],16)&3|8).toString(16);return [a.slice(0,8),a.slice(8,12),`8${a.slice(13,16)}`,`${s}${a.slice(17,20)}`,a.slice(20,32)].join("-")}a(Cn,"draftEntityIdFor");function Ge(e){return {list:Wi(e,"list"),detail:Wi(e,"detail")}}a(Ge,"defaultViewIdsFor");function Gi(e,t,n,r){let a=r.filter(c=>c.objectId===n.id).filter(c=>j(Z(c)).presentation.formField).map(c=>({attribute:c.name})),s=e==="collection"?[{name:"all",type:"collection",placement:"main",label:"All",layout:"table",source:{object:n.name}}]:a.length?[{name:"form",type:"form",placement:"main",label:"Details",groups:[{name:"general",label:"General",fields:a}]}]:[{name:"activity",type:"activity",placement:"main",label:"Activity"}];return {id:t,object:n.name,name:e==="collection"?"default_list":"default_detail",label:n.label,context:e,default:true,contents:s,authoring:Nt(s),revision:1,contentIds:Object.fromEntries(s.map(c=>[c.name,JSON.stringify(["draft-content",t,c.name])])),contentRevisions:Object.fromEntries(s.map(c=>[c.name,1])),derived:true}}a(Gi,"derivedView");function Ki(e,t){let n=Ge(e.id);return [Gi("collection",n.list,e,t),Gi("record",n.detail,e,t)]}a(Ki,"defaultViewsFor");function Ft(e,t,n){return Gi(e.context,e.id,t,n)}a(Ft,"regenerateDerived");function Yi(e){return e.attributeType==="relation"&&Z(e).metadata?.relationGenerated===true}a(Yi,"isGeneratedDraftRelation");function ks(e,t){let n=Ae(t);if(!n)return [t];let r=e.objects.find(c=>c.id===t.objectId),o=e.objects.find(c=>c.name===n.object),a=e.attributes.find(c=>c.objectId===o?.id&&c.name===n.attribute);if(!a||a===t)return [t];let s=Ae(a);return s&&s.object===r?.name&&s.attribute===t.name?[t,a]:[t]}a(ks,"pairedDraftAttributes");function Hi(e,t,n,r,o=false){let a$1=Z(t),s=r&&Z(r),c=r&&Ae(r),u=Ae(t);if(c&&(c.object!==u?.object||c.attribute!==u?.attribute))throw new h("Changing a bilateral address requires removing the existing pair first",[]);if(a$1.type!=="relation"||!a$1.bilateral)return e;let d=e.objects.find(k=>k.id===t.objectId),m=e.objects.find(k=>k.name===a$1.bilateral?.object);if(!(d&&m))throw new h("Both objects must exist before materializing a relation pair",[]);let p=`${d.name}.${t.name}`,b=a$1.bilateral.attribute,y=`${m.name}.${b}`,g=e.attributes.find(k=>k.objectId===m.id&&k.name===b),A=s?.metadata?.relationPairId,x=typeof A=="string"?A:Cn("relation-pair",`${n}:${t.id}`),v=[p,y].sort(),_=typeof A=="string"?{id:x,addresses:v,ownerAddress:s?.type==="relation"&&s.bilateral?.storageOwner===false?y:p,generatedAddresses:[],...p===y?{symmetric:true}:{}}:void 0,F=[...new Map([d,m].map(k=>[k.id,k])).values()].map(k=>({name:k.name,attributes:[t,...g&&g.id!==t.id?[g]:[]].filter(P=>P.objectId===k.id).map(Z)})),K=ji({objects:F,existingPairs:_?[_]:[],...r&&!o?{explicitAddresses:[p],propertyEditAddresses:[p]}:{},nextPairId:a(()=>x,"nextPairId")}),Je=new Map;for(let k of K.objects){let P=k.name===d.name?d.id:m.id;for(let ie of k.attributes){let ee=e.attributes.find(Ut=>Ut.objectId===P&&Ut.name===ie.name),xe=ee?.id===t.id?r??ee:ee,Xs={...bm(ie,ee&&Z(ee)),metadata:{...ie.metadata,...xe&&Yi(xe)&&!(o&&ee?.id===t.id)||!ee?{relationGenerated:true}:{}},id:ee?.id??Cn("relation-attribute",`${x}:${P}:${ie.name}`),...ee?{}:{order:e.attributes.filter(Ut=>Ut.objectId===P).length}};Je.set(`${P}.${ie.name}`,Fi(Xs,P));}}let Y=e.attributes.map(k=>{let P=`${k.objectId}.${k.name}`,ie=Je.get(P);return Je.delete(P),ie??k});return Y.push(...Je.values()),{...e,attributes:Y,views:e.views.map(k=>{let P=[d,m].find(ie=>ie.name===k.object);return k.derived&&P?Ft(k,P,Y):k})}}a(Hi,"reconcileDraftRelationAttribute");function bm(e,t){if(e.type!=="relation"||!e.bilateral||t?.type!=="relation"||!t.bilateral)return e;let{label:n,cardinality:r,...o}=e.bilateral;return {...e,bilateral:{...o,...t.bilateral.label===void 0?{}:{label:n},...t.bilateral.cardinality===void 0?{}:{cardinality:r}}}}a(bm,"preserveDeclarationHints");var js={id:z.string().min(1)};function Pe(e,t){let n=e.objects.find(r=>r.id===t);if(!n)throw new h(`Object "${t}" is not in the draftable state`,[]);return n}a(Pe,"requireObject");function Ji(e,t,n){return {...e,attributes:[...n],views:e.views.map(r=>r.derived&&r.object===t.name?Ft(r,t,n):r)}}a(Ji,"withDerivedViews");function vn(e){return {objectId:e.objectId}}a(vn,"objectFocus");function En(e){return {objectId:e.objectId,recordId:e.recordId}}a(En,"recordFocus");function _s(e){return {objectId:e.objectId,attributeName:e.name}}a(_s,"attributeFocus");function Nn(e){return {objectId:e.objectId,attributeName:e.attribute}}a(Nn,"existingAttributeFocus");function ym(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}a(ym,"firstChangedProperty");function hm(e,t){if(!e.derived)for(let n of e.contents){if(n.type==="collection"&&(n.columns?.includes(t)||n.displayAttributes?.includes(t)||n.sorts?.some(r=>r.attribute===t)))return `content "${n.name}"`;if(n.type==="form"&&n.groups.some(r=>r.fields.some(o=>o.attribute===t)))return `content "${n.name}"`;if(n.type==="richtext"&&(n.attribute===t||n.titleAttribute===t))return `content "${n.name}"`}}a(hm,"handShapedUse");function Am(e,t,n){let r=n.config??{},o=n.name;if(r.relationPath!==void 0)throw new h(`rollup "${o}": relationPath is not supported yet`,[]);let a=r.relationAttribute;if(typeof a!="string"||a.length===0)throw new h(`rollup "${o}" needs a relation attribute; none is configured on object "${t.name}"`,[]);let s=e.attributes.find(p=>p.objectId===t.id&&p.name===a&&p.attributeType==="relation");if(!s)throw new h(`rollup "${o}" needs a relation attribute; "${a}" is not a relation of object "${t.name}"`,[]);let c=gt(s);if(c===void 0){let p=le(s).filter(b=>b.object!=="*").length;throw new h(`rollup "${o}" needs a relation with one target object; "${a}" targets ${p}`,[])}if(r.function==="count")return;let u=e.objects.find(p=>p.name===c),d=r.targetAttribute;if(!(u!==void 0&&e.attributes.some(p=>p.objectId===u.id&&p.name===d)))throw new h(`rollup "${o}" targets attribute "${d}", which object "${c}" does not have`,[])}a(Am,"assertRollupShape");function xm(e,t){let n=e.config??{};if(e.attributeType==="rollup")return n.relationAttribute===t;let r=typeof n.expression=="string"?n.expression:"";return new RegExp(`(^|[^A-Za-z0-9_])${t}\\.`).test(r)}a(xm,"traversesRelation");function Ms(e,t){let n=Pe(e,t.objectId);if(t.attributeType==="relation"){for(let o of le(t))if(o.object!==we&&!e.objects.some(a=>a.name===o.object))throw new h(`object "${o.object}" is unknown; create it first`,[]);let r=Ae(t)?.object;if(r!==void 0&&r!==we&&!e.objects.some(o=>o.name===r))throw new h(`object "${r}" is unknown; create it first`,[]);for(let o of e.attributes)o.objectId!==t.objectId||!bt(o)||xm(o,t.name)&&Rn(e,o);}else if(bt(t))t.attributeType==="rollup"&&Am(e,n,t),Rn(e,t);else return;qi(Mt(e,t.objectId));}a(Ms,"assertConfigFolds");var Ke={...js,objectId:z.string().uuid()},Tm=z.object({...Ke,type:z.literal("add_object"),name:Zt,label:z.string().min(1),icon:z.string().min(1).optional()}),wm={type:"add_object",schema:Tm,apply:a((e,t)=>{if(e.objects.some(r=>r.name===t.name))throw new h(`Object "${t.name}" already exists`,[]);if(e.objects.some(r=>r.id===t.objectId))throw new h(`Object id "${t.objectId}" is already taken`,[]);let n={id:t.objectId,name:t.name,label:t.label,...t.icon===void 0?{}:{icon:t.icon}};return {...e,objects:[...e.objects,n],views:[...e.views,...Ki(n,e.attributes)]}},"apply"),focus:vn,presentation:V(vn,"structural"),describe:a(e=>`Cr\xE9e l'objet \xAB ${e.label} \xBB`,"describe")},Sm=z.object({...Ke,type:z.literal("update_object"),changes:z.object({label:z.string().min(1).optional(),icon:z.string().min(1).optional()}).refine(e=>Object.keys(e).length>0,"update_object needs at least one change")}),Ps=a(e=>({objectId:e.objectId}),"updateObjectFocus"),Im={type:"update_object",schema:Sm,apply:a((e,t)=>(Pe(e,t.objectId),{...e,objects:e.objects.map(n=>n.id===t.objectId?{...n,...t.changes}:n)}),"apply"),focus:Ps,presentation:V(Ps,"atomic",ym),describe:a(e=>e.changes.label?`Renomme l'objet en \xAB ${e.changes.label} \xBB`:"Modifie l'objet","describe")},Rm=z.object({...Ke,type:z.literal("remove_object")}),Cm={type:"remove_object",schema:Rm,apply:a((e,t)=>{Pe(e,t.objectId);let n=e.objects.find(r=>r.id===t.objectId)?.name;for(let r of e.attributes){if(r.objectId===t.objectId||r.attributeType!=="relation"||!le(r).some(a=>a.object===n))continue;let o=e.objects.find(a=>a.id===r.objectId);throw new h(`object "${n}" is targeted by attribute "${o?.name}.${r.name}"; remove that attribute first`,[])}return {...e,objects:e.objects.filter(r=>r.id!==t.objectId),attributes:e.attributes.filter(r=>r.objectId!==t.objectId),sampleRecords:e.sampleRecords.filter(r=>r.objectId!==t.objectId),views:e.views.filter(r=>r.object!==n)}},"apply"),focus:vn,presentation:V(vn,"structural"),describe:a(e=>`Supprime l'objet ${e.objectId}`,"describe")},Fs=Kt;function Vs(e,t){try{n$1(e,t);}catch(n){throw n instanceof h?new h(n.message,n.errors.map(r=>({...r,path:["config",...r.path??[]]}))):n}}a(Vs,"assertConfigParses");var vm=z.object({...Ke,type:z.literal("add_attribute"),attributeId:z.string().min(1),name:Wn,label:z.string().min(1),attributeType:z.enum(Fs),config:z.record(z.string(),z.unknown()).optional()}).superRefine((e,t)=>{try{Vs(e.attributeType,e.config??{});}catch(n){if(n instanceof h){for(let r of n.errors)t.addIssue({code:"custom",message:r.message,path:[...r.path]});return}throw n}}),Em={type:"add_attribute",schema:vm,apply:a((e,t)=>{let n=Pe(e,t.objectId),r=e.attributes.find(c=>c.objectId===t.objectId&&c.name===t.name);if(r&&!Yi(r))throw new h(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);let o={id:r?.id??t.attributeId,objectId:t.objectId,name:t.name,label:t.label,attributeType:t.attributeType,...t.config===void 0?{}:{config:t.config}};for(let c of e.sampleRecords)c.objectId===t.objectId&&$s(c.id,o,c.values);let a=r?e.attributes.map(c=>c===r?o:c):[...e.attributes,o],s=Ji(e,n,a);return Ms(s,o),Hi(s,o,t.id,r,true)},"apply"),focus:_s,presentation:V(_s,"local"),describe:a(e=>`Ajoute l'attribut \xAB ${e.label} \xBB`,"describe")},Bs={...Ke,attribute:Wn};function Ls(e,t,n,r){let o=Pe(e,t);if(n===void 0)throw new h(`${r} now addresses the attribute by name; remove this operation and append it again with "attribute"`,[]);let a=e.attributes.find(s=>s.objectId===t&&s.name===n);if(!a)throw new h(`Attribute "${n}" is not on object "${t}"`,[]);return {object:o,attribute:a}}a(Ls,"requireAttribute");var Nm=z.object({...Bs,type:z.literal("update_attribute"),changes:z.object({label:z.string().min(1).optional(),config:z.record(z.string(),z.unknown()).optional()}).refine(e=>Object.keys(e).length>0,"update_attribute needs at least one change")}),Dm={type:"update_attribute",schema:Nm,apply:a((e,t)=>{let{object:n,attribute:r}=Ls(e,t.objectId,t.attribute,"update_attribute");t.changes.config!==void 0&&Vs(r.attributeType,t.changes.config);let o={...r,...t.changes},a=e.attributes.map(c=>c===r?o:c),s=Ji(e,n,a);return Ms(s,o),Hi(s,o,t.id,r)},"apply"),focus:Nn,presentation:V(Nn,"atomic"),describe:a(e=>e.changes.label?`Renomme l'attribut \xAB ${e.attribute} \xBB en \xAB ${e.changes.label} \xBB`:`Modifie l'attribut \xAB ${e.attribute} \xBB`,"describe")},Om=z.object({...Bs,type:z.literal("remove_attribute")}),km={type:"remove_attribute",schema:Om,apply:a((e,t)=>{let{attribute:n}=Ls(e,t.objectId,t.attribute,"remove_attribute"),r=ks(e,n);for(let s of r){let c=Pe(e,s.objectId),[u]=zi(e,s.objectId,s.name);if(u!==void 0)throw new h(`attribute "${s.name}" is used by "${u}"; remove that first`,[]);for(let m of e.views){if(m.object!==c.name)continue;let p=hm(m,s.name);if(p!==void 0)throw new h(`attribute "${s.name}" is used by view "${m.id}" (${p}); remove it from the view first`,[])}let d=e.sampleRecords.find(m=>m.objectId===s.objectId&&s.name in m.values);if(d)throw new h(`Attribute "${s.name}" is still used by sample record "${d.id}"`,[])}let o=e.attributes.filter(s=>!r.includes(s)),a={...e,views:e.views.map(s=>s)};return r.reduce((s,c)=>Ji(s,Pe(e,c.objectId),o),a)},"apply"),focus:Nn,presentation:V(Nn,"local"),describe:a(e=>`Supprime l'attribut \xAB ${e.attribute} \xBB`,"describe")};function jm(e,t,n,r){let o=Z(n);try{c$2(o);}catch{return}let a=g$1(o,r);if(a.success)return;let s=a.errors??[],c=s.map(u=>u.path.length>1?`${u.path.join(".")}: ${u.message}`:u.message).join(", ");throw new h(`Sample record "${e}" has an invalid value for "${t}": ${c}`,s.map(u=>({path:u.path,message:u.message})))}a(jm,"assertSampleValue");function $s(e,t,n){if(t.config?.required===true&&t.config?.defaultValue===void 0&&!(t.name in n&&n[t.name]!==void 0))throw new h(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}a($s,"assertRequiredCovered");function Qi(e){return (Array.isArray(e)?e:[e]).flatMap(n=>{if(typeof n=="string")return [n];if(typeof n=="object"&&n!==null){let r=n.id;if(typeof r=="string")return [r]}return []})}a(Qi,"relationValueIds");function _m(e,t,n,r){n.attributeType!=="relation"||r===void 0||r===null||Pm(e,t,gt(n),r);}a(_m,"assertUnknownSampleReference");function Pm(e,t,n,r){let o=e.objects.find(s=>s.name===n);if(!o)return;let a=e.views.some(s=>s.id===Ge(o.id).list);for(let s of Qi(r)){let c=e.sampleRecords.find(d=>d.id===s);if(c?.objectId!==o.id&&(c!==void 0||a))throw new h(`sample record "${t}" references unknown sample "${s}"`,[])}}a(Pm,"assertSampleTarget");var Mm=z.object({...Ke,type:z.literal("add_sample_record"),recordId:z.string().uuid(),values:z.record(z.string(),z.unknown()),publication:z.enum(["preview","requested-data"]).optional()}),Fm={type:"add_sample_record",schema:Mm,apply:a((e,t)=>{if(Pe(e,t.objectId),e.sampleRecords.some(r=>r.id===t.recordId))throw new h(`Sample record "${t.recordId}" already exists`,[]);let n=new Map(e.attributes.filter(r=>r.objectId===t.objectId).map(r=>[r.name,r]));for(let[r,o]of Object.entries(t.values)){let a=n.get(r);if(!a)throw new h(`Sample record "${t.recordId}" uses unknown attribute "${r}"`,[]);if(bt(a))throw new h(`attribute "${a.name}" is computed and cannot be set on a sample record`,[]);_m(e,t.recordId,a,o),jm(t.recordId,r,a,o);}for(let r of n.values())$s(t.recordId,r,t.values);return {...e,sampleRecords:[...e.sampleRecords,{id:t.recordId,objectId:t.objectId,values:t.values,...t.publication===void 0?{}:{publication:t.publication}}]}},"apply"),focus:En,presentation:V(En,"local"),describe:a(()=>"Ajoute un exemple","describe")};function Vm(e,t){return new Set([...e.attributes.filter(n=>n.objectId===t&&n.attributeType==="relation").map(n=>n.name)])}a(Vm,"relationNamesOf");function Bm(e,t){for(let n of e.sampleRecords){if(n.id===t)continue;let r=Vm(e,n.objectId);for(let[o,a]of Object.entries(n.values))if(r.has(o)&&Qi(a).includes(t))throw new h(`sample record "${t}" is referenced by sample record "${n.id}"; remove that first`,[])}}a(Bm,"assertSampleNotReferenced");var Lm=z.object({...Ke,type:z.literal("remove_sample_record"),recordId:z.string().min(1)}),$m={type:"remove_sample_record",schema:Lm,apply:a((e,t)=>{if(!e.sampleRecords.some(n=>n.id===t.recordId&&n.objectId===t.objectId))throw new h(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,[]);return Bm(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(n=>n.id!==t.recordId)}},"apply"),focus:En,presentation:V(En,"local"),describe:a(()=>"Retire un exemple","describe")},yt=[wm,Im,Cm,Em,Dm,km,Fm,$m];function Um(){let e=new Map;for(let t of [...yt,...ft]){if(e.has(t.type))throw new r("architect operation",t.type);e.set(t.type,t);}return e}a(Um,"build");var Vt=Um(),qm=[...Vt.keys()];function Bt(e){let t=Vt.get(e.type);if(!t)throw new h(`Operation "${e.id}" has unknown type "${e.type}"`,[]);return t}a(Bt,"defOf");function Xi(e,t,n={extensions:[]}){return t.reduce((r,o)=>Bt(o).apply(r,o,n),e)}a(Xi,"applyOperations");function Zi(e){return Bt(e).focus(e)}a(Zi,"focusOf");function zm(e,t){return e.map(n=>Bt(n).describe(n,t))}a(zm,"describeOperations");function Wm(e){if(typeof e!="object"||e===null||!("type"in e))throw new h("An operation must be an object carrying a type",[]);let t=e.type;if(typeof t!="string")throw new h("An operation's type must be a string",[]);let n=Vt.get(t);if(!n)throw new h(`Unknown operation type "${t}"`,[]);let r=n.schema.safeParse(e);if(!r.success)throw new h(`Operation "${t}" is invalid: ${r.error.issues.map(o=>`${o.path.join(".")} ${o.message}`).join("; ")}`,[]);return r.data}a(Wm,"parseOperation");var Lt=a(e=>z.tuple([z.literal(e),z.string()]),"pair"),Gm=z.union([z.tuple([z.literal("content"),z.string(),z.string(),z.string()]),z.tuple([z.literal("view"),z.string(),z.string()]),z.tuple([z.literal("attribute"),z.string(),z.string()]),z.tuple([z.literal("sample"),z.string(),z.string()]),Lt("object"),Lt("object-name"),Lt("object-schema"),Lt("object-tree"),Lt("attribute-id")]);function $t(e){return e.viewName&&e.objectName?JSON.stringify(e.contentName?["content",e.objectName,e.viewName,e.contentName]:["view",e.objectName,e.viewName]):e.attributeName&&e.objectId?JSON.stringify(["attribute",e.objectId,e.attributeName]):e.attributeId?JSON.stringify(["attribute-id",e.attributeId]):e.recordId&&e.objectId?JSON.stringify(["sample",e.objectId,e.recordId]):e.objectId?JSON.stringify(["object",e.objectId]):e.objectName?JSON.stringify(["object-name",e.objectName]):null}a($t,"proposalTargetKey");function Us(e,t,n,r){if(n&&typeof n=="object")if("source"in n&&n.source&&typeof n.source=="object"){if("object"in n.source&&typeof n.source.object=="string"&&r(n.source.object),"relation"in n.source&&typeof n.source.relation=="string"){let o=n.source.relation;r(t);let a=e.objects.find(c=>c.name===t),s=e.attributes.find(c=>c.objectId===a?.id&&c.name===o);if(s?.attributeType==="relation"&&Array.isArray(s.config?.targets))for(let c of s.config.targets)c&&typeof c.object=="string"&&c.object!=="*"&&r(c.object);}}else "type"in n&&n.type==="forms"?r("objectName"in n&&typeof n.objectName=="string"?n.objectName:t):"type"in n&&["form","richtext","emails","meetings","documents"].includes(String(n.type))&&r(t);}a(Us,"addContentDependencies");function Km(e,t,n,r,o){if(["add_attribute","update_attribute","remove_attribute"].includes(t.type)){let a=e.attributes.find(c=>c.objectId===n.objectId&&c.name===n.attributeName),s=r&&typeof r=="object"&&"bilateral"in r?r.bilateral:a?.config?.bilateral;if((t.attributeType==="relation"||a?.attributeType==="relation")&&s&&typeof s=="object"&&"object"in s&&typeof s.object=="string"){n.objectId&&o("object-tree",n.objectId);let c=e.objects.find(u=>u.name===s.object);c?o("object-tree",c.id):o("object-name",s.object);}}}a(Km,"addBilateralDependencies");function Ym(e,t){let n=new Set,r=a((...a)=>n.add(JSON.stringify(a)),"add"),o=a(a=>{let s=e.objects.find(c=>c.name===a);s?r("object-schema",s.id):r("object-name",a);},"schemaFor");for(let a of t){let s=Zi(a);if(a.type==="rename_view"||a.type==="rename_view_content"){let m=$i.parse(a),p=$t({objectName:m.objectName,viewName:m.viewName,...m.type==="rename_view_content"?{contentName:m.contentName}:{}});p&&n.add(p);}let c=$t(s);if(c&&n.add(c),s.viewName&&s.objectName){a.type!=="replace_view_content"&&r("view",s.objectName,s.viewName);let m=e.objects.find(p=>p.name===s.objectName);if(m?r("object",m.id):r("object-name",s.objectName),Us(e,s.objectName,a.definition??a.content,o),a.type==="reset_view_content"&&typeof a.contentName=="string"){let p=e.views.find(b=>b.object===a.objectName&&b.name===a.viewName);Us(e,s.objectName,p?.authoring.contents[a.contentName]?.sourceDefinition,o);}}s.objectId&&r("object",s.objectId),s.objectId&&(a.type==="remove_object"||a.type.includes("sample_record"))&&r("object-tree",s.objectId),a.type==="add_object"&&typeof a.name=="string"&&r("object-name",a.name);let u=a.changes&&typeof a.changes=="object"?a.changes:null,d=a.type==="add_attribute"?a.config:u&&"config"in u?u.config:null;if(Km(e,a,s,d,r),d&&typeof d=="object"&&"targets"in d&&Array.isArray(d.targets))for(let m of d.targets)m&&typeof m.object=="string"&&m.object!=="*"&&r("object-name",m.object);}return [...n]}a(Ym,"requiredTargetKeys");function Hm(e,t){return Object.fromEntries(t.map(n=>[n,b$2(Dn(e,n))]))}a(Hm,"targetTokensFor");function Dn(e,t){let n;try{n=JSON.parse(t);}catch{throw new h(`Invalid proposal target key "${t}"`,[])}let r=Gm.safeParse(n);if(!r.success)throw new h(`Invalid proposal target key "${t}"`,[]);let[o,a,s,c]=r.data,u=e.objects.find(p=>p.id===a);if(o==="object")return u??null;if(o==="object-name")return e.objects.find(p=>p.name===a)??null;if(o==="attribute-id")return e.attributes.find(p=>p.id===a)??null;if(o==="attribute")return e.attributes.find(p=>p.objectId===a&&p.name===s)??null;if(o==="sample")return e.sampleRecords.find(p=>p.objectId===a&&p.id===s)??null;if(o==="object-schema"||o==="object-tree"){if(!u)return null;let p=e.attributes.filter(b=>b.objectId===a);return o==="object-schema"?{object:u,attributes:p.toSorted((b,y)=>b.name.localeCompare(y.name))}:{object:u,attributes:p,views:e.views.filter(b=>b.object===u.name),sampleRecords:e.sampleRecords.filter(b=>b.objectId===a)}}let d=e.views.find(p=>p.object===a&&p.name===s);if(!d)return null;if(o==="view")return {id:d.id,revision:d.revision,definition:{...mt(d),contents:d.contents.map(({name:p,placement:b})=>({name:p,placement:b}))}};let m=d.contents.find(p=>p.name===c);return c!==void 0&&Object.hasOwn(d.contentIds,c)?{id:d.contentIds[c],revision:d.contentRevisions[c],definition:m??null}:null}a(Dn,"targetSnapshot");function eo(e){return Bt(e).presentation(e)}a(eo,"presentationOf");function Jm(e){let t=e.map(eo);return new Set(t.map(({focus:r})=>r.viewName?JSON.stringify([r.objectName,r.viewName]):r.objectId).filter(r=>r!==void 0)).size>1||t.some(({impact:r})=>r==="structural")?"structural":t.some(({impact:r})=>r==="local")?"local":"atomic"}a(Jm,"episodeImpactOf");function qs(e,t){let n=$t(t);return n===null?null:Dn(e,n)}a(qs,"snapshotArchitectTarget");function Qm(e,t,n={extensions:[]}){let r=e;return t.map(o=>{let a=eo(o),s=qs(r,a.focus);r=Xi(r,[o],n);let c=qs(r,a.focus);return {operationId:o.id,operationType:o.type,presentation:a,before:s,after:c}})}a(Qm,"deriveArchitectChanges");var de=z.string().min(1),Xm=z.union([z.object({objectName:de,viewName:de,contentName:de.optional()}).strict(),z.object({objectId:de}).strict(),z.object({objectName:de}).strict(),z.object({objectId:de,attributeName:de}).strict(),z.object({objectId:de,attributeId:de}).strict(),z.object({objectId:de,recordId:de}).strict()]);function Zm(e){let t=Xm.safeParse(e);if(!t.success)throw new h("Invalid scoped target",[{path:["target"],message:"Expected exactly one named target branch"}]);return t.data}a(Zm,"parseNamedTarget");var Ws=z.object({type:z.literal("remove_operation"),operationId:z.string().min(1).describe("The id of a stored operation to drop from the draft")});function Gs(e,t=[]){return [...e.map(n=>n.schema),...t].map(tf)}a(Gs,"membersOf");function On(e){return z.discriminatedUnion("type",e)}a(On,"unionOf");function ef(e){return e instanceof z.ZodString&&e.format==="uuid"}a(ef,"isUuidString");function tf(e){let t={};for(let[n,r]of Object.entries(e.shape)){if(!ef(r))continue;let o=z.string().min(1);t[n]=r.description===void 0?o:o.describe(r.description);}return Object.keys(t).length===0?e:e.safeExtend(t)}a(tf,"relaxUuidKeys");var nf={add_object:["objectId"],add_sample_record:["recordId"]};function zs(e){let t={};for(let n of nf[e.shape.type.value]??[]){let r=e.shape[n];r instanceof z.ZodString&&(t[n]=r.optional());}return Object.keys(t).length===0?e:e.safeExtend(t)}a(zs,"relaxMintedKeys");var Ks=Gs(yt,[Ws]),Ys=Gs(ft),Hs=On(Ks),Js=On(Ys),rf={schema:Hs,view:Js},of={schema:On(Ks.map(zs)),view:On(Ys.map(zs))},af=new Map([...yt.map(e=>[e.type,"schema"]),["remove_operation","schema"],...ft.map(e=>[e.type,"view"])]);function sf(e){return af.get(e)??null}a(sf,"familyOf");function cf(e){let t=[];for(let n of e.objects){let r=e.views.filter(o=>o.object===n.name&&o.context==="collection").flatMap(o=>o.contents).filter(o=>o.type==="collection");r.length===0&&t.push(`Object "${n.label}" has no collection content: add_view_content.`);for(let o of e.attributes.filter(a=>a.objectId===n.id))j(Z(o)).presentation.tableCell&&r.length&&!r.some(a=>a.columns?.includes(o.name))&&t.push(`Attribute "${o.label}" on "${n.label}" is in no collection column set: replace_view_content.`),o.attributeType==="document"&&!e.views.some(a=>a.object===n.name&&a.contents.some(s=>s.type==="documents"))&&t.push(`Object "${n.label}" has no documents content: add_view_content.`);}return t}a(cf,"stillMissing");function uf(e){let t=e.config??{};if(e.attributeType==="relation")return `\u2192 ${le(e).map(n=>n.object).join("|")}`;if(e.attributeType==="formula")return typeof t.expression=="string"?t.expression:void 0;if(e.attributeType==="rollup")return t.function==="count"?`count(${t.relationAttribute})`:`${t.function}(${t.relationAttribute}.${t.targetAttribute})`}a(uf,"attributeDetail");function lf(e){let t=e.config?.options,n=uf(e);return {name:e.name,label:e.label,type:e.attributeType,...Array.isArray(t)?{options:t.map(r=>r.value)}:{},...n===void 0?{}:{detail:n}}}a(lf,"summarizeAttribute");function df(e,t,n){let r=Ge(e.id),o=n.some(a=>a.id===r.list);return {id:e.id,name:e.name,label:e.label,attributes:t.filter(a=>a.objectId===e.id).map(lf),...o?{viewIds:r}:{}}}a(df,"summarizeObject");function pf(e,t){if(!t.some(n=>n.name===e.object))throw new h(`View "${e.name}" names an object outside the draft scope`,[]);return {id:e.id,name:e.name,context:e.context,objectName:e.object,label:e.label,derived:e.derived===true,contents:e.contents.map(({name:n,type:r,placement:o,label:a})=>({name:n,type:r,placement:o,label:a}))}}a(pf,"summarizeView");function mf(e,t){let n=new Map;for(let r of e.sampleRecords)n.set(r.objectId,(n.get(r.objectId)??0)+1);return {objects:e.objects.map(r=>df(r,e.attributes,e.views)),views:e.views.map(r=>pf(r,e.objects)),sampleRecords:[...n.entries()].map(([r,o])=>({objectId:r,count:o})),operationCount:t}}a(mf,"summarizeDraft");var ff=["draft_schema"],bf="publish_architect_draft",gf="discard_architect_draft",yf="request_design_review",hf="get_architect_draft";var ne=z.string().refine(e=>e.trim().length>0,"Must not be blank"),Qs=z.union([z.tuple([z.literal("object"),ne]),z.tuple([z.literal("attribute"),ne,ne]),z.tuple([z.literal("view"),ne,ne]),z.tuple([z.literal("content"),ne,ne,ne])]),Af=z.object({label:ne,pluralLabel:z.string().optional(),description:z.string().optional(),icon:c.optional(),labelExpression:z.string(),embeddingExpression:z.string().optional(),sealed:z.boolean().optional(),toleratedAttributes:z.array(ne).optional(),metadata:z.record(z.string(),z.unknown()).optional(),schema_version:z.number().int().nonnegative(),migrations:z.array(z.record(z.string(),z.unknown())),documentLayout:z.record(z.string(),z.unknown()).optional()}).strict();function He(e){throw new h(e,[])}a(He,"failure");function xf(e){return z.custom(t=>{let n=z.record(z.string(),z.unknown()).parse(t);for(let r of e[0]==="view"?["object","name"]:["name"])Object.hasOwn(n,r)&&He(`Invalid schema state: unrecognized definition key ${r}`);switch(e[0]){case "object":Af.parse(n);break;case "attribute":{let r=z.enum(Kt).parse(n.type);k(r).extend({type:z.literal(r),label:ne,required:z.boolean().optional(),unique:z.boolean().optional(),icon:c.optional()}).strict().parse(n);break}case "view":{let{contents:r,...o}=n,a=z.array(ne).parse(r);new Set(a).size!==a.length&&He("Invalid schema state: duplicate content membership"),da$1.parse({...o,object:e[1],name:e[2],contents:[]});break}case "content":ca$1.parse({...n,name:e[3]});break}return true})}a(xf,"definitionSchema");function kn(e,t){let n=JSON.stringify(e.address),r=JSON.stringify(t.address);return n<r?-1:n>r?1:0}a(kn,"compareSchemaStateEntries");function Tf(e){return {modelVersion:1,hashVersion:1,entries:[...e].sort(kn).filter(t=>t.source!==null).map(({address:t,source:n})=>({address:t,source:n}))}}a(Tf,"schemaStateSourcePayload");function wf(e){let t=z.record(z.string(),z.unknown()).parse(e);for(let[a,s]of [["modelVersion","model"],["hashVersion","hash"]])t[a]!==1&&He(`Unsupported schema ${s} version: expected 1, received ${t[a]===void 0?"missing":String(t[a])}`);let n=z.object({modelVersion:z.literal(1),hashVersion:z.literal(1),tenant:ne,sourceFingerprint:z.string().regex(/^[a-f0-9]{64}$/),entries:z.array(z.unknown())}).strict().safeParse(e);if(!n.success){let a=n.error.issues.find(s=>s.code==="unrecognized_keys");throw a?.code==="unrecognized_keys"&&He(`Invalid schema state: unrecognized key ${a.keys[0]}`),h.fromZodErrors(n.error.issues.map(s=>({path:s.path.map(String),message:s.message})))}let r=new Set,o=n.data.entries.map(a=>{let s=Qs.parse(z.object({address:z.unknown()}).parse(a).address),c=JSON.stringify(s);r.has(c)&&He(`Invalid schema state: duplicate address ${c}`),r.add(c);let u=xf(s).nullable(),d=s[0]==="object"||s[0]==="attribute"?z.object({id:z.string().uuid(),updatedAt:z.string().datetime()}).strict():z.object({id:z.string().uuid(),revision:z.number().int().nonnegative()}).strict(),m=z.object({address:Qs,source:u,effective:u,status:z.enum(["source","runtime","copy","suppressed"]),sourceOwner:z.union([z.literal("core"),z.string().regex(/^(bundle|source):.+$/)]).nullable(),guard:d.nullable()}).strict().parse(a);(m.status==="runtime"&&(m.source!==null||m.effective===null||m.sourceOwner!==null)||m.status==="suppressed"&&(s[0]!=="content"||m.source===null||m.effective!==null||m.guard===null)||m.status==="copy"&&(m.source===null||m.effective===null)||m.effective!==null&&m.guard===null||m.source===null&&m.effective===null)&&He(`Invalid schema state: inconsistent status at ${c}`);let p=m.sourceOwner;p!==null&&p!=="core"&&!p.startsWith("bundle:")&&!p.startsWith("source:")&&He("Invalid source owner");let b=p===null||p==="core"?p:p.startsWith("bundle:")?`bundle:${p.slice(7)}`:`source:${p.slice(7)}`;return {...m,sourceOwner:b}});return {...n.data,entries:o.sort(kn)}}a(wf,"parseState");function Sf(e){try{return wf(e)}catch(t){throw t instanceof z.ZodError?h.fromZodErrors(t.issues.map(n=>({path:n.path.map(String),message:n.message}))):t}}a(Sf,"parseSchemaState");function If(e){let t=[];for(let n of [...e.entries].sort(kn)){let r=n.source===null?"added":n.status==="suppressed"?"suppressed":n.effective===null?"removed":b$2(n.source)!==b$2(n.effective)?"changed":n.status==="copy"?"copied":null;r&&t.push({...n,change:r});}return {modelVersion:1,tenant:e.tenant,sourceFingerprint:e.sourceFingerprint,changes:t}}a(If,"diffSchemaState");export{Sw as AGENT_UI_BATCH_MAX_BYTES,Iw as AGENT_UI_BATCH_MAX_ITEMS,Mo as ALLOWED_PROPERTY_TYPES,Ln as ALL_ACTIONS,qm as ALL_OPERATION_TYPES,fA as ALL_SYSTEM_RESOURCES,Kg as ARTIFACT_FILE_ROLES,Wg as ARTIFACT_KINDS,fl as ARTIFACT_LIST_VIEW,pl as ARTIFACT_OBJECT,st as ARTIFACT_OBJECT_NAME,sa as ARTIFACT_PREVIEW_EXTENSION,Gg as ARTIFACT_RETENTIONS,ml as ARTIFACT_VIEW,Kt as ATTRIBUTE_TYPES,ug as AUDIT_ACTIONS,cg as AUDIT_RESOURCE_TYPES,Gn as AgentBuilder,Zb as BEHAVIOR_PROPERTIES,Kc as BYTE_UNIT_LABELS,jc as CLAIMABLE_SESSION_STATUSES,kt as COMPUTED_FUNCTIONS,oS as COMPUTED_FUNCTION_METADATA,Lw as COMPUTED_FUNCTION_NAMES,kS as CONNECTOR_CALLBACK_PARAM,_o as COUNT_MODES,S as ComputedFormulaCompileError,ae as ContentBuilder,pA as DB_COLUMN_FIELDS,Jo as DEFAULT_AGENT_EXECUTION_CONFIG,So as DEFAULT_APPROVAL_POLICY,qg as DEFAULT_DICTATION_LIMITS,Bo as DEFAULT_LABEL_FALLBACK,Uc as DEFAULT_MEETING_BOT_DISPLAY_NAME,Su as DEFAULT_ROLES,yA as DEFAULT_ROLE_DESCRIPTIONS,gA as DEFAULT_ROLE_LABELS,hA as DEFAULT_ROLE_PERMISSIONS,Sy as DEFAULT_TENANT_SETTINGS,$g as DICTATION_FINALIZATION_TIMEOUT_MS,Pg as DICTATION_FRAME_BYTES,Fg as DICTATION_MAX_BUFFER_BYTES,Mg as DICTATION_MAX_FRAME_BYTES,Vg as DICTATION_MAX_TRANSCRIPT_BYTES,Ug as DICTATION_MODEL_ID,Lg as DICTATION_PREPARATION_TIMEOUT_MS,_g as DICTATION_SAMPLE_RATE,Bg as DICTATION_TICKET_TTL_MS,gf as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,Dh as DOCUMENT_SYSTEM_ATTRIBUTES,Fs as DRAFTABLE_ATTRIBUTE_TYPES,ff as DRAFT_WRITE_TOOL_NAMES,ll as DRIVE_LIST_VIEW,cl as DRIVE_OBJECT,at as DRIVE_OBJECT_NAME,ul as DRIVE_VIEW,Jt as EMPTY_VALUE_PLACEHOLDER,ky as ESTIMATED_COUNT_CAP,WS as FAKE_MEETING_BOT_SIGNATURE_HEADER,rf as FAMILY_INPUTS,of as FAMILY_WIRE_INPUTS,Fn as FORM_FORBIDDEN_ATTRIBUTE_TYPES,vt as FlagRegistry,cn as FlagService,kr as FormBuilder,Dt as FormRegistry,Dr as FormRowBuilder,Or as FormStepBuilder,hf as GET_ARCHITECT_DRAFT_TOOL_NAME,Br as GroupBuilder,Xb as IDENTITY_PROPERTIES,Ey as IMAGE_FORMATS,Co as INFERENCE_REASONING_OPTIONS,Ro as INFERENCE_SPEEDS,Rl as LIVE_EVENT_TYPES,fp as MAILBOX_LIST_MODES,BS as MAIL_DRAFT_BODY_MAX_CHARS,LS as MAIL_SUBJECT_MAX_CHARS,No as MAX_PRESET_DEPTH,Ig as MAX_TODOS,Cg as MAX_TODO_DESCRIPTION_CHARS,Rg as MAX_TODO_ID_CHARS,C as MEETING_ATTRIBUTES,da as MEETING_DETAIL_VIEW_ID,yl as MEETING_LIST_VIEW,ua as MEETING_LIST_VIEW_ID,bl as MEETING_OBJECT,ct as MEETING_OBJECT_NAME,gl as MEETING_VIEW,la as MEETING_WRITE_SOURCE,sl as MEMORY_LIST_VIEW,ol as MEMORY_OBJECT,al as MEMORY_VIEW,mp as McpOAuthCompletionMode,sr as MultiRelationAttributeBuilder,Mc as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,Fc as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,Ao as NOTIFICATION_INBOX_STATES,go as NOTIFICATION_KINDS,yo as NOTIFICATION_PRIORITIES,ho as NOTIFICATION_SENSITIVITIES,Jb as NOTIFICATION_TYPES_V1,Oc as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,Nc as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,Dc as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,xo as NOTIFICATION_WORK_STATES,GS as NO_RECORDING,ko as NoopGeocodingAdapter,Zt as OBJECT_NAME_SCHEMA,_c as OPEN_TOOL_PART_STATES,Vt as OPERATION_REGISTRY,Tn as OPERATOR_SPECS,It as ObjectBuilder,eg as PRESENTATION_PROPERTIES,Io as PROVIDER_NAMES,bf as PUBLISH_ARCHITECT_DRAFT_TOOL_NAME,Fh as QUALIFIED_SEPARATOR,Py as QUOTA_KEYS,qS as RECORDING_OVERRIDES,zS as RECORDING_POLICIES,zo as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,we as RELATION_TARGET_ANY,Ws as REMOVE_OPERATION_SCHEMA,bp as REPLY_MODES,yf as REQUEST_DESIGN_REVIEW_TOOL_NAME,yt as SCHEMA_OPERATIONS,Hs as SCHEMA_OPERATION_INPUT,ce as SCHEMA_PLAN_LIMITS,Ei as SCHEMA_SOURCE_ID_PATTERN,Dg as SESSION_STATE_STREAM_ID,kc as SESSION_TERMINAL_STATUSES,oa as SKILL_CONTENT_TEMPLATE,nl as SKILL_LIST_VIEW,el as SKILL_OBJECT,tl as SKILL_VIEW,Nu as STANDARD_SCHEMA_VENDOR,Mn as SYSTEM_PART_CODES,te as SYSTEM_RESOURCES,bA as SYSTEM_RESOURCE_LABELS,ar as SingleRelationAttributeBuilder,za as TODAY_DEFAULT,yg as TODO_PLAN_STATUSES,Sg as TODO_STATUSES,vo as TOOL_APPROVAL_STATES,Ry as USER_STATUSES,Cy as USER_WORK_POSTURES,ft as VIEW_OPERATIONS,Js as VIEW_OPERATION_INPUT,an as ViewBuilder,yy as accessLevelToActions,gy as actionsToAccessLevel,OA as agent,jI as agentDataChunk,hg as agentDisplayName,DI as agentInferencePreferencesSchema,Mp as agentMessageAttachmentSchema,Pp as agentMessagePartSchema,_p as agentSessionInferenceOverridesInputSchema,OI as agentSessionInferenceOverridesSchema,rs as agentSessionMessageSchema,qp as agentUIValidationError,Xi as applyOperations,Vo as applyPipes,bu as applyRelationProps,Ew as architectDraftChannelKey,qi as assertAcyclicComputed,va as assertAcyclicComputedDependencies,pm as assertBilateralPairs,zp as assertCustomAgentUIMessageChunk,hp as assertSchemaSourceId,Ae as bilateralDeclarationOf,zu as booleanFlag,Ga as buildAgentFallbackTitle,wu as buildPermissionFlags,Ht as buildPropertySchema,Bh as buildQualifiedAttribute,$i as canonicalViewOperationSchema,Qo as checkbox,AI as collectSchemaReferences,Pc as compareAgentSessionMessages,kn as compareSchemaStateEntries,Mt as compilablePlansOf,mn as compileComputedFormula,Oa as compileRollupAttribute,Gc as computeByteMagnitude,Ui as computedCompileSchemaOf,Rn as computedPlanOf,N as content,pa as contentDefinition,yp as conversationDisplayTitle,Hu as createFlagRegistry,Qu as createFlagService,tn as createStandardSchemaProps,zA as currency,cs as customDataChunkSchemas,oe as date,wn as dateInTimezone,Ze as dateValueStart,Ge as defaultViewIdsFor,Ki as defaultViewsFor,Mi as defineOperation,V as definePresentation,zi as dependentsOf,Qm as deriveArchitectChanges,ES as deriveCreateDefaultsFromFilters,xu as deriveInitials,zm as describeOperations,Qa as destructiveSchema,fe as detailView,If as diffSchemaState,Xo as document,us as draftedLabelExpression,Vi as draftedObjectDefinition,mt as draftedViewDefinition,Bp as durableDateSchema,Jm as episodeImpactOf,eS as evaluateComputedAst,tS as evaluateComputedFormula,nS as evaluateComputedFormulaWithResult,ap as evaluateFilterState,xS as evaluateRecordFilterState,Tt as extractAttributeNames,qo as extractValueRefs,sf as familyOf,ma as findRelationAttribute,Yu as flagRegistry,Zi as focusOf,rx as form,$c as formFieldFlatKey,Lc as formFieldKey,ga as formRegistry,Aw as formatAgentStreamFrameId,Fo as formatAttributeValue,vh as formatByteSize,tp as formatComputedResult,eu as formatLocationValue,HA as formula,Yp as fromDraftableView,mu as getEditableLabelAttribute,Jg as getErrorMessage,Mw as getLiveProtocolPayloadChannel,Tu as getRecordCreatorPrincipalId,Uo as getSingleAttributeFromExpression,Oo as getSlotFieldTargets,hu as getUserDisplayName,ge as group,ZS as hasDestructiveEntries,xy as hasOptions,as as imageModelIdSchema,tt as includesAction,wo as inferInverseCardinality,$d as inferRollupReturnType,Pi as inferenceReasoningSchema,_i as inferenceSpeedSchema,Up as isAgentUIDataName,Rw as isAgentUIMessageBatch,og as isAttributeSortable,ig as isBilateralRelation,uS as isCheckboxEquality,gg as isClaimableSessionStatus,bt as isComputedAttribute,dn as isComputedFunctionName,Ne as isDateRangeValue,AA as isDefaultRole,Oh as isDocumentAttribute,zc as isEmptyObject,ey as isFormDefinition,Yt as isFormFieldsRow,Vn as isFormFreeFieldRef,sy as isFormHeadingRow,cy as isFormSeparatorRow,Do as isFormSlotFieldRef,uy as isFormTextRow,Xt as isLabelExpression,Fw as isLiveEventEnvelope,kw as isLiveEventPayload,_l as isLiveEventPayloadForType,jl as isLiveEventType,MS as isMailProvider,FS as isMailboxListMode,Po as isNotEmpty,Ag as isOpenToolPartState,Ma as isPlainRecord,VS as isReplyMode,_A as isStandardSchema,Tg as isSystemPartCode,bg as isTerminalSessionStatus,pg as isTerminalState,xg as isToolApprovalState,To as isUniversalRelation,Ku as jsonFlag,fg as legacyStatusToSessionState,be as listView,ha as liveChannelKey,KA as location,kh as matchesAccepts,Fp as mentionReferenceSchema,Vp as modelDefinitionSchema,os as modelReferenceSchema,GA as multiselect,Bc as nativeAgentUIPartIdMetadataKey,Yc as normalizeDateValue,rn as number,Gu as numberFlag,gx as object,wg as orderAgentSessionMessages,xw as parseAgentStreamFrameId,qc as parseCountMode,Aa as parseLiveChannelKey,Zm as parseNamedTarget,Og as parseNativeAgentUIPartIdsMetadata,Wm as parseOperation,Oy as parseOptionalCountMode,Vh as parseQualifiedAttribute,Sf as parseSchemaState,pI as persistedSchemaPlanSchema,qA as phone,Tp as plannedAttributeSchema,wp as plannedInlineAttributeSchema,Sp as plannedObjectSchema,eo as presentationOf,$t as proposalTargetKey,is as providerNameSchema,yu as qualifiedPropertyDefs,iy as readFormFieldValue,ji as reconcileRelationAttributes,Ft as regenerateDerived,uT as registry,rt as relation,_x as relationProperty,gu as relationPropertyDefs,gt as relationTargetObjectName,le as relationTargets,rg as relationTargetsOf,Qi as relationValueIds,Un as renderLabelExpression,OS as requestedCapabilities,Rt as requireRecordContentContext,fa as requireSingleRelationTarget,Ym as requiredTargetKeys,dp as resolveAttributeDefaultValue,ju as resolveCollectionActions,ku as resolveContentNavigation,ry as resolveFieldRequired,jo as resolvePropertyDefinitions,li as resolveViewContents,De as richtext,JA as rollup,Ld as rollupToFormulaExpression,dI as schemaPlanSchema,Tf as schemaStateSourcePayload,pe as select,kI as sessionInferencePatchSchema,mg as sessionStateToLegacyStatus,WA as status,cf as stillMissing,Et as storedContentDefinition,Wu as stringFlag,mf as summarizeDraft,Dn as targetSnapshot,Hm as targetTokensFor,w as text,Z as toAttribute,Gp as toDraftableAttributes,Wp as toDraftableObject,Kp as toDraftableView,Wc as toUndefinedIfEmpty,Lp as todoItemSchema,$p as todoPlanSchema,ss as toolImpactSchema,YA as user,St as validateAttributeName,di as validateContentViewCatalogue,su as validateLabelExpression,Ou as validateObjectExpressions,wt as validateObjectName,Eu as validateViewName,Wi as viewIdFor,si as viewIdentityKey,hl as viewRegistry,Nt as workspaceViewAuthoring};
|