@fabrika/builder 0.9.0-dev.13 → 0.9.0-dev.15
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/BUILD-CONTRACT.md +9 -3
- package/README.md +39 -9
- package/cli/src/bin.ts +14 -1
- package/cli/src/build-review.ts +66 -0
- package/cli/src/build-status.ts +41 -3
- package/cli/src/catalog.ts +34 -2
- package/cli/src/commands/advance.ts +48 -6
- package/cli/src/commands/build.ts +152 -15
- package/cli/src/commands/design.ts +34 -0
- package/cli/src/commands/flows.ts +32 -0
- package/cli/src/commands/induce.ts +2 -2
- package/cli/src/commands/init.ts +7 -1
- package/cli/src/commands/next.ts +9 -2
- package/cli/src/context.ts +2 -1
- package/cli/src/contrast.ts +301 -0
- package/cli/src/daemon-client.ts +29 -3
- package/cli/src/design-review.ts +261 -0
- package/cli/src/flows.ts +162 -0
- package/cli/src/frontmatter.ts +32 -0
- package/cli/src/index.ts +10 -1
- package/cli/src/induce.ts +61 -3
- package/cli/src/issues.ts +15 -29
- package/cli/src/layout.ts +5 -2
- package/cli/src/packet.ts +36 -3
- package/cli/src/phase-state.ts +19 -1
- package/cli/src/verify.ts +50 -0
- package/daemon/src/admission.ts +1 -0
- package/daemon/src/handlers.ts +32 -6
- package/daemon/src/phases.ts +7 -109
- package/daemon/src/platform-source.ts +8 -0
- package/decisions/README.md +2 -2
- package/decisions/patterns/cf-contract-app.md +57 -0
- package/decisions/technologies/bun.md +2 -1
- package/decisions/technologies/cf-fabrika-contract.md +45 -0
- package/decisions/technologies/cloudflare.md +3 -1
- package/decisions/technologies/oblaka.md +1 -1
- package/decisions/technologies/opice.md +1 -1
- package/decisions/technologies/react.md +1 -1
- package/decisions/technologies/tailwind.md +5 -5
- package/decisions/technologies/zerops-fabrika-auth.md +1 -1
- package/decisions/technologies/zerops-platform.md +1 -1
- package/package.json +11 -8
- package/shared/approvals.ts +65 -0
- package/shared/derive.ts +189 -0
- package/shared/gate.ts +20 -0
- package/shared/index.ts +6 -1
- package/shared/phases.ts +22 -20
- package/skill/SKILL.md +25 -16
- package/skill/agents/build-orchestrator.md +28 -8
- package/skill/agents/flows-author.md +27 -13
- package/skill/agents/implementer.md +3 -1
- package/skill/agents/opice-skeleton-author.md +8 -7
- package/skill/gates/brief.jsx +26 -5
- package/skill/gates/review-grid.jsx +3 -8
- package/skill/gates/tech.jsx +3 -3
- package/stacks/README.md +8 -2
- package/stacks/cf-app.md +60 -0
- package/stacks/cf-fat.md +1 -0
- package/stacks/cf-internal-app.md +2 -2
- package/stacks/cf-lightweight.md +3 -2
- package/stacks/contember-app.md +1 -0
- package/stacks/content-site.md +1 -0
- package/stacks/zerops-app.md +1 -0
- package/types/cli/src/bin.d.ts +1 -1
- package/types/cli/src/build-review.d.ts +13 -0
- package/types/cli/src/build-status.d.ts +16 -1
- package/types/cli/src/catalog.d.ts +9 -0
- package/types/cli/src/commands/design.d.ts +1 -0
- package/types/cli/src/commands/flows.d.ts +1 -0
- package/types/cli/src/contrast.d.ts +59 -0
- package/types/cli/src/daemon-client.d.ts +13 -2
- package/types/cli/src/design-review.d.ts +54 -0
- package/types/cli/src/flows.d.ts +28 -0
- package/types/cli/src/frontmatter.d.ts +8 -0
- package/types/cli/src/index.d.ts +1 -1
- package/types/cli/src/induce.d.ts +3 -0
- package/types/cli/src/issues.d.ts +4 -0
- package/types/cli/src/packet.d.ts +9 -1
- package/types/cli/src/phase-state.d.ts +1 -1
- package/types/cli/src/verify.d.ts +18 -0
- package/types/daemon/src/phases.d.ts +4 -16
- package/types/daemon/src/platform-remote.d.ts +6 -2
- package/types/shared/approvals.d.ts +32 -0
- package/types/shared/derive.d.ts +41 -0
- package/types/shared/gate.d.ts +11 -0
- package/types/shared/index.d.ts +108 -68
- package/types/shared/phases.d.ts +7 -1
- package/ui/dist/assets/annotations-runtime.js +1 -1
- package/ui/dist/assets/client.css +1 -1
- package/ui/dist/assets/client.hm9vx5ay.js +120 -0
- package/ui/dist/assets/components.js +57 -57
- package/ui/dist/assets/preact-compat.js +1 -1
- package/ui/dist/assets/runtime.js +1 -1
- package/ui/dist/index.html +1 -1
- package/cli/src/derive.ts +0 -105
- package/skill/gates/build.jsx +0 -20
- package/skill/gates/design.jsx +0 -22
- package/skill/gates/flows.jsx +0 -14
- package/skill/gates/vision.jsx +0 -27
- package/types/cli/src/derive.d.ts +0 -17
- package/ui/dist/assets/client.cemdw2n8.js +0 -214
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import{createRoot as td}from"react-dom/client";import{useEffect as fa,useMemo as as,useRef as ls,useState as Tt}from"react";import{useState as eu}from"react";import{AnnotationCtx as Sf,AnnotationHostContext as Ef,SessionContext as _f,useAnnotationHost as If,useAnnotations as Cf}from"@fabrika/annotations/runtime";function Bn(e,t){let n=[],o=us(e);for(let r of o){let i=document.createRange();if(i.selectNodeContents(r),r===e.startContainer)i.setStart(r,e.startOffset);if(r===e.endContainer)i.setEnd(r,e.endOffset);let s=i.toString();if(!s||!s.trim())continue;let l=document.createElement("mark");l.setAttribute("data-annotation-id",t);try{i.surroundContents(l)}catch{let a=i.extractContents();l.appendChild(a),i.insertNode(l)}n.push(l)}return n}function sn(e){let t=e.parentElement;if(t?.classList.contains("select-none"))return!1;if(t?.closest("[data-annotation-id]"))return!1;return!0}function us(e){let t=[],n=e.commonAncestorContainer;if(n.nodeType===Node.TEXT_NODE)return t.push(n),t;let o=document.createTreeWalker(n,NodeFilter.SHOW_TEXT),r;while(r=o.nextNode()){if(!sn(r))continue;if(e.intersectsNode(r))t.push(r)}return t}function ya(e,t){let n=document.createRange();if(n.selectNodeContents(e),e===t.startContainer)n.setStart(e,t.startOffset);if(e===t.endContainer)n.setEnd(e,t.endOffset);return n.toString()}function ds(e){let t="";for(let n of us(e))t+=ya(n,e);return t}function Pt(e,t){let n=document.querySelectorAll(`[data-annotation-id="${e}"]`);for(let o of n)o.classList.toggle("mark-active",t)}function $r(e,t){if(t!=null&&t!==e)Pt(t,!1);if(e!=null)Pt(e,!0)}function jr(e,t){let n=document.querySelectorAll(`[data-annotation-id="${e}"]`);for(let o of n)o.setAttribute("data-annotation-id",t)}function Fr(e,t){for(let n of t){if(e.querySelector(`[data-annotation-id="${n.id}"]`))continue;let o=n.snippet;if(!o)continue;let{fullText:r,textNodes:i}=xa(e),s=[],l=0;while(!0){let m=r.indexOf(o,l);if(m===-1)break;s.push(m),l=m+1}let[a]=s;if(a===void 0)continue;let c=a;if(s.length>1&&n.context){let m=-1;for(let h of s){let y=0;if(n.context.before){let A=r.slice(Math.max(0,h-80),h);if(A.includes(n.context.before))y+=2;else if(n.context.before.length>10&&A.includes(n.context.before.slice(-10)))y+=1}if(n.context.after){let A=r.slice(h+o.length,h+o.length+80);if(A.includes(n.context.after))y+=2;else if(n.context.after.length>10&&A.includes(n.context.after.slice(0,10)))y+=1}if(y>m)m=y,c=h}}let u=c,d=c+o.length,f=cs(i,u),p=cs(i,d);if(!f||!p)continue;try{let m=document.createRange();m.setStart(f.node,f.offset),m.setEnd(p.node,p.offset),Bn(m,n.id)}catch{}}}function xa(e){let t=[],n="",o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),r;while(r=o.nextNode()){if(!sn(r))continue;t.push({node:r,start:n.length}),n+=r.textContent||""}return{fullText:n,textNodes:t}}function cs(e,t){for(let n=e.length-1;n>=0;n--){let o=e[n];if(!o||o.start>t)continue;let r=t-o.start,i=o.node.textContent?.length??0;if(r<=i)return{node:o.node,offset:r}}return null}function Br(e){let t=document.querySelectorAll(`[data-annotation-id="${e}"]`);for(let n of t){let o=n.parentNode;if(!o)continue;if(n.tagName!=="MARK"){o.removeChild(n);continue}while(n.firstChild)o.insertBefore(n.firstChild,n);o.removeChild(n),o.normalize()}}function Hr(e,t){let n=ps(e,"before",60),o=ps(e,"after",60),r=va(e.startContainer,t);return{before:n,after:o,hierarchy:r}}function ps(e,t,n){let o=ba(t==="before"?e.startContainer:e.endContainer);if(!o)return"";let r="";if(t==="before"){let i=document.createTreeWalker(o,NodeFilter.SHOW_TEXT),s;while(s=i.nextNode()){if(s===e.startContainer){r+=(s.textContent||"").slice(0,e.startOffset);break}if(!sn(s))continue;r+=s.textContent||""}if(r.length>n){r=r.slice(-n);let l=r.indexOf(" ");if(l>0)r=r.slice(l+1)}}else{let i=document.createTreeWalker(o,NodeFilter.SHOW_TEXT),s=!1,l;while(l=i.nextNode()){if(l===e.endContainer){r+=(l.textContent||"").slice(e.endOffset),s=!0;continue}if(s){if(!sn(l))continue;r+=l.textContent||""}}if(r.length>n){r=r.slice(0,n);let a=r.lastIndexOf(" ");if(a>0)r=r.slice(0,a)}}return r.trim()}function ba(e){let t=new Set(["DIV","P","LI","PRE","BLOCKQUOTE","SECTION","ARTICLE"]),n=e.parentElement;while(n){if(t.has(n.tagName))return n;n=n.parentElement}return null}function va(e,t){let n=[],o=e instanceof Element?e:e.parentElement;while(o&&o!==t){let r=o.getAttribute?.("data-task-id");if(r){let s=o.querySelector(".font-semibold");if(s)n.unshift(s.textContent?.trim()||r)}let i=ka(o);if(i)n.unshift(i);o=o.parentElement}return n}function ka(e){if(e.getAttribute("data-md")==="section"){let n=e.getAttribute("data-md-title");if(n)return n}if(e.tagName!=="DIV")return null;return e.querySelector(":scope > button > .font-heading, :scope > div > .font-heading")?.textContent?.trim()||null}function Hn(e){let t=e.snippet.trim(),n=e.context,o=t.length<30;if(n&&o&&(n.before||n.after)){let r=[];if(n.before)r.push(`...${n.before} `);if(r.push(`**${t}**`),n.after)r.push(` ${n.after}...`);return r.join("")}return t}function an(e){return{kind:e.kind,owns:(t)=>e.parse(t)!==null,find:(t,n)=>{let o=e.parse(t);return o===null?null:e.find(o,n)},restore:(t,n)=>{let o=e.parse(n.snippet);if(o===null)return;e.restore?.(o,t,n)},describe:(t)=>{let n=e.parse(t);if(n===null||!e.describe)return null;return e.describe(n)}}}function fs(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n="";for(let o=t.nextNode();o;o=t.nextNode()){let r=o.parentElement?.closest("[aria-hidden='true']");if(r&&e.contains(r))continue;n+=o.textContent??""}return n.trim()}function zn(e,t,n){return{selector:e,snippet:(o)=>{let r=o.getAttribute(n);return r?`${t} ${r}`:null}}}var zr=[zn("[data-md='item']","[Item]","data-md-label"),zn("[data-md='section']","[Section]","data-md-title"),zn("[data-md='checklist-item']","[Checklist]","data-md-label"),zn("[data-md='image']","[Image]","data-md-src"),{selector:"[data-md='callout']",snippet:(e)=>`[Callout:${e.getAttribute("data-md-type")||"info"}] ${fs(e).slice(0,60)||"Callout"}`},{selector:"[data-md='note']",snippet:(e)=>`[Note] ${fs(e).slice(0,60)||"Note"}`},{selector:"[data-md='table'] tbody tr",snippet:(e)=>{let t=Array.from(e.querySelectorAll("td")).map((n)=>n.textContent?.trim()).filter(Boolean);return t.length?`[Row] ${t.join(" | ")}`:null}}],Aa=["[data-md='choice-option']","[data-md='multichoice-option']","[data-md='userinput']","[data-md='rangeinput']"],it=zr.map((e)=>e.selector).join(", "),Ot=[...zr.map((e)=>e.selector),...Aa].join(", ");function ze(e){for(let t of zr)if(e.matches(t.selector))return t.snippet(e);return null}var Ur={kind:"block",parse:(e)=>e.startsWith("[")?{snippet:e}:null,format:(e)=>e.snippet,find:(e,t)=>{for(let n of t.querySelectorAll(it)){if(!(n instanceof HTMLElement))continue;if(ze(n)===e.snippet)return n}return null}};var Kr="data-annotation-image",Ra=/^\[Region:(rect|ellipse)\] ([\s\S]+) @(0|[1-9]\d*),(0|[1-9]\d*),(0|[1-9]\d*),(0|[1-9]\d*)$/;function wa(e){if(e==="rect")return"rect";if(e==="ellipse")return"ellipse";return null}function Un(e){if(e===void 0)return null;let t=Number(e);if(!Number.isInteger(t)||t<0||t>1e4)return null;return t}function ms(e){return Math.min(1e4,Math.max(0,e))}function Vr(e,t,n){if(!(e.width>0)||!(e.height>0))return null;return{x:ms(Math.round(t/e.width*1e4)),y:ms(Math.round(n/e.height*1e4))}}function Kn(e,t){let n=Math.min(e.x,t.x),o=Math.min(e.y,t.y);return{x:n,y:o,w:Math.min(1e4-n,Math.abs(e.x-t.x)),h:Math.min(1e4-o,Math.abs(e.y-t.y))}}function Gr(e){return e.w>=30&&e.h>=30}function gs(e){return{left:`${e.x/100}%`,top:`${e.y/100}%`,width:`${e.w/100}%`,height:`${e.h/100}%`}}function qn(e){return`${(e/100).toFixed(1).replace(/\.0$/,"")}%`}function Vn(e){let t=`${qn(e.x)}-${qn(e.x+e.w)}`,n=`${qn(e.y)}-${qn(e.y+e.h)}`;return`[Region] ${e.src} — ${e.shape} x ${t}, y ${n} of the image`}function qr(e,t){for(let n of t.querySelectorAll("[data-md='image']")){if(!(n instanceof HTMLElement))continue;if(n.getAttribute("data-md-src")!==e)continue;let o=n.querySelector("[data-annotation-image]");if(o instanceof HTMLElement)return o}return null}function Gn(e,t){let n=gs(t);e.style.left=n.left,e.style.top=n.top,e.style.width=n.width,e.style.height=n.height}function Wn(e,t,n){let o=document.createElement("div");return o.className="ann-region",o.setAttribute("data-annotation-id",n),o.setAttribute("data-annotation-region",t),Gn(o,e),o}var ln={kind:"region",parse:(e)=>{let t=Ra.exec(e);if(!t)return null;let n=wa(t[1]),o=t[2],r=Un(t[3]),i=Un(t[4]),s=Un(t[5]),l=Un(t[6]);if(n===null||o===void 0)return null;if(r===null||i===null||s===null||l===null)return null;if(s<1||l<1)return null;return{src:o,shape:n,x:r,y:i,w:s,h:l}},format:(e)=>`[Region:${e.shape}] ${e.src} @${e.x},${e.y},${e.w},${e.h}`,find:(e,t)=>qr(e.src,t),restore:(e,t,n)=>{if(t.querySelector(`[data-annotation-id="${n.id}"]`))return;let o=qr(e.src,t);if(!o)return;o.appendChild(Wn(e,e.shape,n.id))},describe:Vn};var Wr={kind:"text",parse:(e)=>e?{text:e}:null,format:(e)=>e.text,find:()=>null,restore:(e,t,n)=>{Fr(t,[n])}};var Xn=[an(ln),an(Ur),an(Wr)];function Xr(e,t){for(let n of Xn){let o=n.find(e,t);if(o)return o}return null}function Jr(e,t){for(let n of t){if(!n.snippet)continue;for(let o of Xn)o.restore(e,n)}}function cn(e){for(let t of Xn){let n=t.describe(e);if(n!==null)return n}return e}import{AnnotationCtx as pp,SessionContext as fp,useAnnotationHost as mp}from"@fabrika/annotations/runtime";import{useEffect as yp,useRef as xp,useState as bp}from"react";var Y;(function(e){e.assertEqual=(r)=>{};function t(r){}e.assertIs=t;function n(r){throw Error()}e.assertNever=n,e.arrayToEnum=(r)=>{let i={};for(let s of r)i[s]=s;return i},e.getValidEnumValues=(r)=>{let i=e.objectKeys(r).filter((l)=>typeof r[r[l]]!=="number"),s={};for(let l of i)s[l]=r[l];return e.objectValues(s)},e.objectValues=(r)=>e.objectKeys(r).map(function(i){return r[i]}),e.objectKeys=typeof Object.keys==="function"?(r)=>Object.keys(r):(r)=>{let i=[];for(let s in r)if(Object.prototype.hasOwnProperty.call(r,s))i.push(s);return i},e.find=(r,i)=>{for(let s of r)if(i(s))return s;return},e.isInteger=typeof Number.isInteger==="function"?(r)=>Number.isInteger(r):(r)=>typeof r==="number"&&Number.isFinite(r)&&Math.floor(r)===r;function o(r,i=" | "){return r.map((s)=>typeof s==="string"?`'${s}'`:s).join(i)}e.joinValues=o,e.jsonStringifyReplacer=(r,i)=>{if(typeof i==="bigint")return i.toString();return i}})(Y||(Y={}));var hs;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(hs||(hs={}));var S=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Je=(e)=>{switch(typeof e){case"undefined":return S.undefined;case"string":return S.string;case"number":return Number.isNaN(e)?S.nan:S.number;case"boolean":return S.boolean;case"function":return S.function;case"bigint":return S.bigint;case"symbol":return S.symbol;case"object":if(Array.isArray(e))return S.array;if(e===null)return S.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return S.promise;if(typeof Map<"u"&&e instanceof Map)return S.map;if(typeof Set<"u"&&e instanceof Set)return S.set;if(typeof Date<"u"&&e instanceof Date)return S.date;return S.object;default:return S.unknown}};var x=Y.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Te extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(n)=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(r){return r.message},n={_errors:[]},o=(r)=>{for(let i of r.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let s=n,l=0;while(l<i.path.length){let a=i.path[l];if(l!==i.path.length-1)s[a]=s[a]||{_errors:[]};else s[a]=s[a]||{_errors:[]},s[a]._errors.push(t(i));s=s[a],l++}}};return o(this),n}static assert(e){if(!(e instanceof Te))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t={},n=[];for(let o of this.issues)if(o.path.length>0){let r=o.path[0];t[r]=t[r]||[],t[r].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Te.create=(e)=>new Te(e);var Sa=(e,t)=>{let n;switch(e.code){case x.invalid_type:if(e.received===S.undefined)n="Required";else n=`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Y.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:n=`Unrecognized key(s) in object: ${Y.joinValues(e.keys,", ")}`;break;case x.invalid_union:n="Invalid input";break;case x.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Y.joinValues(e.options)}`;break;case x.invalid_enum_value:n=`Invalid enum value. Expected ${Y.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:n="Invalid function arguments";break;case x.invalid_return_type:n="Invalid function return type";break;case x.invalid_date:n="Invalid date";break;case x.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")n=`${n} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)n=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)n=`Invalid input: must end with "${e.validation.endsWith}"`;else Y.assertNever(e.validation);else if(e.validation!=="regex")n=`Invalid ${e.validation}`;else n="Invalid";break;case x.too_small:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else n="Invalid input";break;case x.too_big:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else n="Invalid input";break;case x.custom:n="Invalid input";break;case x.invalid_intersection_types:n="Intersection results could not be merged";break;case x.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:n="Number must be finite";break;default:n=t.defaultError,Y.assertNever(e)}return{message:n}},at=Sa;var Ea=at;function un(){return Ea}var Jn=(e)=>{let{data:t,path:n,errorMaps:o,issueData:r}=e,i=[...n,...r.path||[]],s={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let l="",a=o.filter((c)=>!!c).slice().reverse();for(let c of a)l=c(s,{data:t,defaultError:l}).message;return{...r,path:i,message:l}};function R(e,t){let n=un(),o=Jn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===at?void 0:at].filter((r)=>!!r)});e.common.issues.push(o)}class we{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let n=[];for(let o of t){if(o.status==="aborted")return F;if(o.status==="dirty")e.dirty();n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let o of t){let r=await o.key,i=await o.value;n.push({key:r,value:i})}return we.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let o of t){let{key:r,value:i}=o;if(r.status==="aborted")return F;if(i.status==="aborted")return F;if(r.status==="dirty")e.dirty();if(i.status==="dirty")e.dirty();if(r.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet))n[r.value]=i.value}return{status:e.value,value:n}}}var F=Object.freeze({status:"aborted"}),Nt=(e)=>({status:"dirty",value:e}),Se=(e)=>({status:"valid",value:e}),Yr=(e)=>e.status==="aborted",Qr=(e)=>e.status==="dirty",ht=(e)=>e.status==="valid",dn=(e)=>typeof Promise<"u"&&e instanceof Promise;var O;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(O||(O={}));class Le{constructor(e,t,n,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=o}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var ys=(e,t)=>{if(ht(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Te(e.common.issues);return this._error=n,this._error}}}};function V(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:o,description:r}=e;if(t&&(n||o))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:r};return{errorMap:(s,l)=>{let{message:a}=e;if(s.code==="invalid_enum_value")return{message:a??l.defaultError};if(typeof l.data>"u")return{message:a??o??l.defaultError};if(s.code!=="invalid_type")return{message:l.defaultError};return{message:a??n??l.defaultError}},description:r}}class J{get description(){return this._def.description}_getType(e){return Je(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Je(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new we,ctx:{common:e.parent.common,data:e.data,parsedType:Je(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(dn(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)},o=this._parseSync({data:e,path:n.path,parent:n});return ys(n,o)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ht(n)?{value:n.value}:{issues:t.common.issues}}catch(n){if(n?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((n)=>ht(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)},o=this._parse({data:e,path:n.path,parent:n}),r=await(dn(o)?o:Promise.resolve(o));return ys(n,r)}refine(e,t){let n=(o)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(o);else return t};return this._refinement((o,r)=>{let i=e(o),s=()=>r.addIssue({code:x.custom,...n(o)});if(typeof Promise<"u"&&i instanceof Promise)return i.then((l)=>{if(!l)return s(),!1;else return!0});if(!i)return s(),!1;else return!0})}refinement(e,t){return this._refinement((n,o)=>{if(!e(n))return o.addIssue(typeof t==="function"?t(n,o):t),!1;else return!0})}_refinement(e){return new Ke({schema:this,typeName:z.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return qe.create(this,this._def)}nullable(){return lt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ue.create(this)}promise(){return jt.create(this,this._def)}or(e){return hn.create([this,e],this._def)}and(e){return yn.create(this,e,this._def)}transform(e){return new Ke({...V(this._def),schema:this,typeName:z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new kn({...V(this._def),innerType:this,defaultValue:t,typeName:z.ZodDefault})}brand(){return new no({typeName:z.ZodBranded,type:this,...V(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new An({...V(this._def),innerType:this,catchValue:t,typeName:z.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return or.create(this,e)}readonly(){return Rn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var _a=/^c[^\s-]{8,}$/i,Ia=/^[0-9a-z]+$/,Ca=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ta=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Pa=/^[a-z0-9_-]{21}$/i,Oa=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Na=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Da=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ma="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Zr,La=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$a=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ja=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Fa=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ba=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ha=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,xs="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",za=new RegExp(`^${xs}$`);function bs(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Ua(e){return new RegExp(`^${bs(e)}$`)}function qa(e){let t=`${xs}T${bs(e)}`,n=[];if(n.push(e.local?"Z?":"Z"),e.offset)n.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Ka(e,t){if((t==="v4"||!t)&&La.test(e))return!0;if((t==="v6"||!t)&&ja.test(e))return!0;return!1}function Va(e,t){if(!Oa.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let o=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(o));if(typeof r!=="object"||r===null)return!1;if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(t&&r.alg!==t)return!1;return!0}catch{return!1}}function Ga(e,t){if((t==="v4"||!t)&&$a.test(e))return!0;if((t==="v6"||!t)&&Fa.test(e))return!0;return!1}class Qe extends J{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==S.string){let r=this._getOrReturnCtx(e);return R(r,{code:x.invalid_type,expected:S.string,received:r.parsedType}),F}let n=new we,o=void 0;for(let r of this._def.checks)if(r.kind==="min"){if(e.data.length<r.value)o=this._getOrReturnCtx(e,o),R(o,{code:x.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),n.dirty()}else if(r.kind==="max"){if(e.data.length>r.value)o=this._getOrReturnCtx(e,o),R(o,{code:x.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),n.dirty()}else if(r.kind==="length"){let i=e.data.length>r.value,s=e.data.length<r.value;if(i||s){if(o=this._getOrReturnCtx(e,o),i)R(o,{code:x.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message});else if(s)R(o,{code:x.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message});n.dirty()}}else if(r.kind==="email"){if(!Da.test(e.data))o=this._getOrReturnCtx(e,o),R(o,{validation:"email",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="emoji"){if(!Zr)Zr=new RegExp(Ma,"u");if(!Zr.test(e.data))o=this._getOrReturnCtx(e,o),R(o,{validation:"emoji",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="uuid"){if(!Ta.test(e.data))o=this._getOrReturnCtx(e,o),R(o,{validation:"uuid",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="nanoid"){if(!Pa.test(e.data))o=this._getOrReturnCtx(e,o),R(o,{validation:"nanoid",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="cuid"){if(!_a.test(e.data))o=this._getOrReturnCtx(e,o),R(o,{validation:"cuid",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="cuid2"){if(!Ia.test(e.data))o=this._getOrReturnCtx(e,o),R(o,{validation:"cuid2",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="ulid"){if(!Ca.test(e.data))o=this._getOrReturnCtx(e,o),R(o,{validation:"ulid",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),R(o,{validation:"url",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="regex"){if(r.regex.lastIndex=0,!r.regex.test(e.data))o=this._getOrReturnCtx(e,o),R(o,{validation:"regex",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="trim")e.data=e.data.trim();else if(r.kind==="includes"){if(!e.data.includes(r.value,r.position))o=this._getOrReturnCtx(e,o),R(o,{code:x.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),n.dirty()}else if(r.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(r.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(r.kind==="startsWith"){if(!e.data.startsWith(r.value))o=this._getOrReturnCtx(e,o),R(o,{code:x.invalid_string,validation:{startsWith:r.value},message:r.message}),n.dirty()}else if(r.kind==="endsWith"){if(!e.data.endsWith(r.value))o=this._getOrReturnCtx(e,o),R(o,{code:x.invalid_string,validation:{endsWith:r.value},message:r.message}),n.dirty()}else if(r.kind==="datetime"){if(!qa(r).test(e.data))o=this._getOrReturnCtx(e,o),R(o,{code:x.invalid_string,validation:"datetime",message:r.message}),n.dirty()}else if(r.kind==="date"){if(!za.test(e.data))o=this._getOrReturnCtx(e,o),R(o,{code:x.invalid_string,validation:"date",message:r.message}),n.dirty()}else if(r.kind==="time"){if(!Ua(r).test(e.data))o=this._getOrReturnCtx(e,o),R(o,{code:x.invalid_string,validation:"time",message:r.message}),n.dirty()}else if(r.kind==="duration"){if(!Na.test(e.data))o=this._getOrReturnCtx(e,o),R(o,{validation:"duration",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="ip"){if(!Ka(e.data,r.version))o=this._getOrReturnCtx(e,o),R(o,{validation:"ip",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="jwt"){if(!Va(e.data,r.alg))o=this._getOrReturnCtx(e,o),R(o,{validation:"jwt",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="cidr"){if(!Ga(e.data,r.version))o=this._getOrReturnCtx(e,o),R(o,{validation:"cidr",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="base64"){if(!Ba.test(e.data))o=this._getOrReturnCtx(e,o),R(o,{validation:"base64",code:x.invalid_string,message:r.message}),n.dirty()}else if(r.kind==="base64url"){if(!Ha.test(e.data))o=this._getOrReturnCtx(e,o),R(o,{validation:"base64url",code:x.invalid_string,message:r.message}),n.dirty()}else Y.assertNever(r);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement((o)=>e.test(o),{validation:t,code:x.invalid_string,...O.errToObj(n)})}_addCheck(e){return new Qe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...O.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...O.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...O.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...O.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...O.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...O.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...O.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...O.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...O.errToObj(t)})}nonempty(e){return this.min(1,O.errToObj(e))}trim(){return new Qe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Qe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Qe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Qe.create=(e)=>new Qe({checks:[],typeName:z.ZodString,coerce:e?.coerce??!1,...V(e)});function Wa(e,t){let n=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,r=n>o?n:o,i=Number.parseInt(e.toFixed(r).replace(".","")),s=Number.parseInt(t.toFixed(r).replace(".",""));return i%s/10**r}class Mt extends J{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==S.number){let r=this._getOrReturnCtx(e);return R(r,{code:x.invalid_type,expected:S.number,received:r.parsedType}),F}let n=void 0,o=new we;for(let r of this._def.checks)if(r.kind==="int"){if(!Y.isInteger(e.data))n=this._getOrReturnCtx(e,n),R(n,{code:x.invalid_type,expected:"integer",received:"float",message:r.message}),o.dirty()}else if(r.kind==="min"){if(r.inclusive?e.data<r.value:e.data<=r.value)n=this._getOrReturnCtx(e,n),R(n,{code:x.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),o.dirty()}else if(r.kind==="max"){if(r.inclusive?e.data>r.value:e.data>=r.value)n=this._getOrReturnCtx(e,n),R(n,{code:x.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),o.dirty()}else if(r.kind==="multipleOf"){if(Wa(e.data,r.value)!==0)n=this._getOrReturnCtx(e,n),R(n,{code:x.not_multiple_of,multipleOf:r.value,message:r.message}),o.dirty()}else if(r.kind==="finite"){if(!Number.isFinite(e.data))n=this._getOrReturnCtx(e,n),R(n,{code:x.not_finite,message:r.message}),o.dirty()}else Y.assertNever(r);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.toString(t))}setLimit(e,t,n,o){return new Mt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.toString(o)}]})}_addCheck(e){return new Mt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:O.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&Y.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;else if(n.kind==="min"){if(t===null||n.value>t)t=n.value}else if(n.kind==="max"){if(e===null||n.value<e)e=n.value}return Number.isFinite(t)&&Number.isFinite(e)}}Mt.create=(e)=>new Mt({checks:[],typeName:z.ZodNumber,coerce:e?.coerce||!1,...V(e)});class Lt extends J{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==S.bigint)return this._getInvalidInput(e);let n=void 0,o=new we;for(let r of this._def.checks)if(r.kind==="min"){if(r.inclusive?e.data<r.value:e.data<=r.value)n=this._getOrReturnCtx(e,n),R(n,{code:x.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),o.dirty()}else if(r.kind==="max"){if(r.inclusive?e.data>r.value:e.data>=r.value)n=this._getOrReturnCtx(e,n),R(n,{code:x.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),o.dirty()}else if(r.kind==="multipleOf"){if(e.data%r.value!==BigInt(0))n=this._getOrReturnCtx(e,n),R(n,{code:x.not_multiple_of,multipleOf:r.value,message:r.message}),o.dirty()}else Y.assertNever(r);return{status:o.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:S.bigint,received:t.parsedType}),F}gte(e,t){return this.setLimit("min",e,!0,O.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.toString(t))}setLimit(e,t,n,o){return new Lt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.toString(o)}]})}_addCheck(e){return new Lt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Lt.create=(e)=>new Lt({checks:[],typeName:z.ZodBigInt,coerce:e?.coerce??!1,...V(e)});class Yn extends J{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==S.boolean){let n=this._getOrReturnCtx(e);return R(n,{code:x.invalid_type,expected:S.boolean,received:n.parsedType}),F}return Se(e.data)}}Yn.create=(e)=>new Yn({typeName:z.ZodBoolean,coerce:e?.coerce||!1,...V(e)});class fn extends J{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==S.date){let r=this._getOrReturnCtx(e);return R(r,{code:x.invalid_type,expected:S.date,received:r.parsedType}),F}if(Number.isNaN(e.data.getTime())){let r=this._getOrReturnCtx(e);return R(r,{code:x.invalid_date}),F}let n=new we,o=void 0;for(let r of this._def.checks)if(r.kind==="min"){if(e.data.getTime()<r.value)o=this._getOrReturnCtx(e,o),R(o,{code:x.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),n.dirty()}else if(r.kind==="max"){if(e.data.getTime()>r.value)o=this._getOrReturnCtx(e,o),R(o,{code:x.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),n.dirty()}else Y.assertNever(r);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new fn({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:O.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:O.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}fn.create=(e)=>new fn({checks:[],coerce:e?.coerce||!1,typeName:z.ZodDate,...V(e)});class Qn extends J{_parse(e){if(this._getType(e)!==S.symbol){let n=this._getOrReturnCtx(e);return R(n,{code:x.invalid_type,expected:S.symbol,received:n.parsedType}),F}return Se(e.data)}}Qn.create=(e)=>new Qn({typeName:z.ZodSymbol,...V(e)});class mn extends J{_parse(e){if(this._getType(e)!==S.undefined){let n=this._getOrReturnCtx(e);return R(n,{code:x.invalid_type,expected:S.undefined,received:n.parsedType}),F}return Se(e.data)}}mn.create=(e)=>new mn({typeName:z.ZodUndefined,...V(e)});class gn extends J{_parse(e){if(this._getType(e)!==S.null){let n=this._getOrReturnCtx(e);return R(n,{code:x.invalid_type,expected:S.null,received:n.parsedType}),F}return Se(e.data)}}gn.create=(e)=>new gn({typeName:z.ZodNull,...V(e)});class Zn extends J{constructor(){super(...arguments);this._any=!0}_parse(e){return Se(e.data)}}Zn.create=(e)=>new Zn({typeName:z.ZodAny,...V(e)});class yt extends J{constructor(){super(...arguments);this._unknown=!0}_parse(e){return Se(e.data)}}yt.create=(e)=>new yt({typeName:z.ZodUnknown,...V(e)});class Ze extends J{_parse(e){let t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:S.never,received:t.parsedType}),F}}Ze.create=(e)=>new Ze({typeName:z.ZodNever,...V(e)});class er extends J{_parse(e){if(this._getType(e)!==S.undefined){let n=this._getOrReturnCtx(e);return R(n,{code:x.invalid_type,expected:S.void,received:n.parsedType}),F}return Se(e.data)}}er.create=(e)=>new er({typeName:z.ZodVoid,...V(e)});class Ue extends J{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),o=this._def;if(t.parsedType!==S.array)return R(t,{code:x.invalid_type,expected:S.array,received:t.parsedType}),F;if(o.exactLength!==null){let i=t.data.length>o.exactLength.value,s=t.data.length<o.exactLength.value;if(i||s)R(t,{code:i?x.too_big:x.too_small,minimum:s?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty()}if(o.minLength!==null){if(t.data.length<o.minLength.value)R(t,{code:x.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()}if(o.maxLength!==null){if(t.data.length>o.maxLength.value)R(t,{code:x.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()}if(t.common.async)return Promise.all([...t.data].map((i,s)=>o.type._parseAsync(new Le(t,i,t.path,s)))).then((i)=>we.mergeArray(n,i));let r=[...t.data].map((i,s)=>o.type._parseSync(new Le(t,i,t.path,s)));return we.mergeArray(n,r)}get element(){return this._def.type}min(e,t){return new Ue({...this._def,minLength:{value:e,message:O.toString(t)}})}max(e,t){return new Ue({...this._def,maxLength:{value:e,message:O.toString(t)}})}length(e,t){return new Ue({...this._def,exactLength:{value:e,message:O.toString(t)}})}nonempty(e){return this.min(1,e)}}Ue.create=(e,t)=>new Ue({type:e,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...V(t)});function Dt(e){if(e instanceof he){let t={};for(let n in e.shape){let o=e.shape[n];t[n]=qe.create(Dt(o))}return new he({...e._def,shape:()=>t})}else if(e instanceof Ue)return new Ue({...e._def,type:Dt(e.element)});else if(e instanceof qe)return qe.create(Dt(e.unwrap()));else if(e instanceof lt)return lt.create(Dt(e.unwrap()));else if(e instanceof et)return et.create(e.items.map((t)=>Dt(t)));else return e}class he extends J{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=Y.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==S.object){let a=this._getOrReturnCtx(e);return R(a,{code:x.invalid_type,expected:S.object,received:a.parsedType}),F}let{status:n,ctx:o}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof Ze&&this._def.unknownKeys==="strip")){for(let a in o.data)if(!i.includes(a))s.push(a)}let l=[];for(let a of i){let c=r[a],u=o.data[a];l.push({key:{status:"valid",value:a},value:c._parse(new Le(o,u,o.path,a)),alwaysSet:a in o.data})}if(this._def.catchall instanceof Ze){let a=this._def.unknownKeys;if(a==="passthrough")for(let c of s)l.push({key:{status:"valid",value:c},value:{status:"valid",value:o.data[c]}});else if(a==="strict"){if(s.length>0)R(o,{code:x.unrecognized_keys,keys:s}),n.dirty()}else if(a==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let a=this._def.catchall;for(let c of s){let u=o.data[c];l.push({key:{status:"valid",value:c},value:a._parse(new Le(o,u,o.path,c)),alwaysSet:c in o.data})}}if(o.common.async)return Promise.resolve().then(async()=>{let a=[];for(let c of l){let u=await c.key,d=await c.value;a.push({key:u,value:d,alwaysSet:c.alwaysSet})}return a}).then((a)=>we.mergeObjectSync(n,a));else return we.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return O.errToObj,new he({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let o=this._def.errorMap?.(t,n).message??n.defaultError;if(t.code==="unrecognized_keys")return{message:O.errToObj(e).message??o};return{message:o}}}:{}})}strip(){return new he({...this._def,unknownKeys:"strip"})}passthrough(){return new he({...this._def,unknownKeys:"passthrough"})}extend(e){return new he({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new he({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new he({...this._def,catchall:e})}pick(e){let t={};for(let n of Y.objectKeys(e))if(e[n]&&this.shape[n])t[n]=this.shape[n];return new he({...this._def,shape:()=>t})}omit(e){let t={};for(let n of Y.objectKeys(this.shape))if(!e[n])t[n]=this.shape[n];return new he({...this._def,shape:()=>t})}deepPartial(){return Dt(this)}partial(e){let t={};for(let n of Y.objectKeys(this.shape)){let o=this.shape[n];if(e&&!e[n])t[n]=o;else t[n]=o.optional()}return new he({...this._def,shape:()=>t})}required(e){let t={};for(let n of Y.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let r=this.shape[n];while(r instanceof qe)r=r._def.innerType;t[n]=r}return new he({...this._def,shape:()=>t})}keyof(){return vs(Y.objectKeys(this.shape))}}he.create=(e,t)=>new he({shape:()=>e,unknownKeys:"strip",catchall:Ze.create(),typeName:z.ZodObject,...V(t)});he.strictCreate=(e,t)=>new he({shape:()=>e,unknownKeys:"strict",catchall:Ze.create(),typeName:z.ZodObject,...V(t)});he.lazycreate=(e,t)=>new he({shape:e,unknownKeys:"strip",catchall:Ze.create(),typeName:z.ZodObject,...V(t)});class hn extends J{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function o(r){for(let s of r)if(s.result.status==="valid")return s.result;for(let s of r)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let i=r.map((s)=>new Te(s.ctx.common.issues));return R(t,{code:x.invalid_union,unionErrors:i}),F}if(t.common.async)return Promise.all(n.map(async(r)=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await r._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(o);else{let r=void 0,i=[];for(let l of n){let a={...t,common:{...t.common,issues:[]},parent:null},c=l._parseSync({data:t.data,path:t.path,parent:a});if(c.status==="valid")return c;else if(c.status==="dirty"&&!r)r={result:c,ctx:a};if(a.common.issues.length)i.push(a.common.issues)}if(r)return t.common.issues.push(...r.ctx.common.issues),r.result;let s=i.map((l)=>new Te(l));return R(t,{code:x.invalid_union,unionErrors:s}),F}}get options(){return this._def.options}}hn.create=(e,t)=>new hn({options:e,typeName:z.ZodUnion,...V(t)});var Ye=(e)=>{if(e instanceof xn)return Ye(e.schema);else if(e instanceof Ke)return Ye(e.innerType());else if(e instanceof bn)return[e.value];else if(e instanceof xt)return e.options;else if(e instanceof vn)return Y.objectValues(e.enum);else if(e instanceof kn)return Ye(e._def.innerType);else if(e instanceof mn)return[void 0];else if(e instanceof gn)return[null];else if(e instanceof qe)return[void 0,...Ye(e.unwrap())];else if(e instanceof lt)return[null,...Ye(e.unwrap())];else if(e instanceof no)return Ye(e.unwrap());else if(e instanceof Rn)return Ye(e.unwrap());else if(e instanceof An)return Ye(e._def.innerType);else return[]};class to extends J{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==S.object)return R(t,{code:x.invalid_type,expected:S.object,received:t.parsedType}),F;let n=this.discriminator,o=t.data[n],r=this.optionsMap.get(o);if(!r)return R(t,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),F;if(t.common.async)return r._parseAsync({data:t.data,path:t.path,parent:t});else return r._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let o=new Map;for(let r of t){let i=Ye(r.shape[e]);if(!i.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of i){if(o.has(s))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);o.set(s,r)}}return new to({typeName:z.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...V(n)})}}function eo(e,t){let n=Je(e),o=Je(t);if(e===t)return{valid:!0,data:e};else if(n===S.object&&o===S.object){let r=Y.objectKeys(t),i=Y.objectKeys(e).filter((l)=>r.indexOf(l)!==-1),s={...e,...t};for(let l of i){let a=eo(e[l],t[l]);if(!a.valid)return{valid:!1};s[l]=a.data}return{valid:!0,data:s}}else if(n===S.array&&o===S.array){if(e.length!==t.length)return{valid:!1};let r=[];for(let i=0;i<e.length;i++){let s=e[i],l=t[i],a=eo(s,l);if(!a.valid)return{valid:!1};r.push(a.data)}return{valid:!0,data:r}}else if(n===S.date&&o===S.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class yn extends J{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),o=(r,i)=>{if(Yr(r)||Yr(i))return F;let s=eo(r.value,i.value);if(!s.valid)return R(n,{code:x.invalid_intersection_types}),F;if(Qr(r)||Qr(i))t.dirty();return{status:t.value,value:s.data}};if(n.common.async)return Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([r,i])=>o(r,i));else return o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}yn.create=(e,t,n)=>new yn({left:e,right:t,typeName:z.ZodIntersection,...V(n)});class et extends J{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==S.array)return R(n,{code:x.invalid_type,expected:S.array,received:n.parsedType}),F;if(n.data.length<this._def.items.length)return R(n,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),F;if(!this._def.rest&&n.data.length>this._def.items.length)R(n,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let r=[...n.data].map((i,s)=>{let l=this._def.items[s]||this._def.rest;if(!l)return null;return l._parse(new Le(n,i,n.path,s))}).filter((i)=>!!i);if(n.common.async)return Promise.all(r).then((i)=>we.mergeArray(t,i));else return we.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new et({...this._def,rest:e})}}et.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new et({items:e,typeName:z.ZodTuple,rest:null,...V(t)})};class tr extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==S.object)return R(n,{code:x.invalid_type,expected:S.object,received:n.parsedType}),F;let o=[],r=this._def.keyType,i=this._def.valueType;for(let s in n.data)o.push({key:r._parse(new Le(n,s,n.path,s)),value:i._parse(new Le(n,n.data[s],n.path,s)),alwaysSet:s in n.data});if(n.common.async)return we.mergeObjectAsync(t,o);else return we.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,n){if(t instanceof J)return new tr({keyType:e,valueType:t,typeName:z.ZodRecord,...V(n)});return new tr({keyType:Qe.create(),valueType:e,typeName:z.ZodRecord,...V(t)})}}class nr extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==S.map)return R(n,{code:x.invalid_type,expected:S.map,received:n.parsedType}),F;let o=this._def.keyType,r=this._def.valueType,i=[...n.data.entries()].map(([s,l],a)=>({key:o._parse(new Le(n,s,n.path,[a,"key"])),value:r._parse(new Le(n,l,n.path,[a,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let l of i){let a=await l.key,c=await l.value;if(a.status==="aborted"||c.status==="aborted")return F;if(a.status==="dirty"||c.status==="dirty")t.dirty();s.set(a.value,c.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let l of i){let{key:a,value:c}=l;if(a.status==="aborted"||c.status==="aborted")return F;if(a.status==="dirty"||c.status==="dirty")t.dirty();s.set(a.value,c.value)}return{status:t.value,value:s}}}}nr.create=(e,t,n)=>new nr({valueType:t,keyType:e,typeName:z.ZodMap,...V(n)});class $t extends J{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==S.set)return R(n,{code:x.invalid_type,expected:S.set,received:n.parsedType}),F;let o=this._def;if(o.minSize!==null){if(n.data.size<o.minSize.value)R(n,{code:x.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()}if(o.maxSize!==null){if(n.data.size>o.maxSize.value)R(n,{code:x.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty()}let r=this._def.valueType;function i(l){let a=new Set;for(let c of l){if(c.status==="aborted")return F;if(c.status==="dirty")t.dirty();a.add(c.value)}return{status:t.value,value:a}}let s=[...n.data.values()].map((l,a)=>r._parse(new Le(n,l,n.path,a)));if(n.common.async)return Promise.all(s).then((l)=>i(l));else return i(s)}min(e,t){return new $t({...this._def,minSize:{value:e,message:O.toString(t)}})}max(e,t){return new $t({...this._def,maxSize:{value:e,message:O.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}$t.create=(e,t)=>new $t({valueType:e,minSize:null,maxSize:null,typeName:z.ZodSet,...V(t)});class pn extends J{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==S.function)return R(t,{code:x.invalid_type,expected:S.function,received:t.parsedType}),F;function n(s,l){return Jn({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,un(),at].filter((a)=>!!a),issueData:{code:x.invalid_arguments,argumentsError:l}})}function o(s,l){return Jn({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,un(),at].filter((a)=>!!a),issueData:{code:x.invalid_return_type,returnTypeError:l}})}let r={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof jt){let s=this;return Se(async function(...l){let a=new Te([]),c=await s._def.args.parseAsync(l,r).catch((f)=>{throw a.addIssue(n(l,f)),a}),u=await Reflect.apply(i,this,c);return await s._def.returns._def.type.parseAsync(u,r).catch((f)=>{throw a.addIssue(o(u,f)),a})})}else{let s=this;return Se(function(...l){let a=s._def.args.safeParse(l,r);if(!a.success)throw new Te([n(l,a.error)]);let c=Reflect.apply(i,this,a.data),u=s._def.returns.safeParse(c,r);if(!u.success)throw new Te([o(c,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new pn({...this._def,args:et.create(e).rest(yt.create())})}returns(e){return new pn({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new pn({args:e?e:et.create([]).rest(yt.create()),returns:t||yt.create(),typeName:z.ZodFunction,...V(n)})}}class xn extends J{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}xn.create=(e,t)=>new xn({getter:e,typeName:z.ZodLazy,...V(t)});class bn extends J{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return R(t,{received:t.data,code:x.invalid_literal,expected:this._def.value}),F}return{status:"valid",value:e.data}}get value(){return this._def.value}}bn.create=(e,t)=>new bn({value:e,typeName:z.ZodLiteral,...V(t)});function vs(e,t){return new xt({values:e,typeName:z.ZodEnum,...V(t)})}class xt extends J{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return R(t,{expected:Y.joinValues(n),received:t.parsedType,code:x.invalid_type}),F}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return R(t,{received:t.data,code:x.invalid_enum_value,options:n}),F}return Se(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return xt.create(e,{...this._def,...t})}exclude(e,t=this._def){return xt.create(this.options.filter((n)=>!e.includes(n)),{...this._def,...t})}}xt.create=vs;class vn extends J{_parse(e){let t=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==S.string&&n.parsedType!==S.number){let o=Y.objectValues(t);return R(n,{expected:Y.joinValues(o),received:n.parsedType,code:x.invalid_type}),F}if(!this._cache)this._cache=new Set(Y.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let o=Y.objectValues(t);return R(n,{received:n.data,code:x.invalid_enum_value,options:o}),F}return Se(e.data)}get enum(){return this._def.values}}vn.create=(e,t)=>new vn({values:e,typeName:z.ZodNativeEnum,...V(t)});class jt extends J{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==S.promise&&t.common.async===!1)return R(t,{code:x.invalid_type,expected:S.promise,received:t.parsedType}),F;let n=t.parsedType===S.promise?t.data:Promise.resolve(t.data);return Se(n.then((o)=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}jt.create=(e,t)=>new jt({type:e,typeName:z.ZodPromise,...V(t)});class Ke extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),o=this._def.effect||null,r={addIssue:(i)=>{if(R(n,i),i.fatal)t.abort();else t.dirty()},get path(){return n.path}};if(r.addIssue=r.addIssue.bind(r),o.type==="preprocess"){let i=o.transform(n.data,r);if(n.common.async)return Promise.resolve(i).then(async(s)=>{if(t.value==="aborted")return F;let l=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});if(l.status==="aborted")return F;if(l.status==="dirty")return Nt(l.value);if(t.value==="dirty")return Nt(l.value);return l});else{if(t.value==="aborted")return F;let s=this._def.schema._parseSync({data:i,path:n.path,parent:n});if(s.status==="aborted")return F;if(s.status==="dirty")return Nt(s.value);if(t.value==="dirty")return Nt(s.value);return s}}if(o.type==="refinement"){let i=(s)=>{let l=o.refinement(s,r);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(s.status==="aborted")return F;if(s.status==="dirty")t.dirty();return i(s.value),{status:t.value,value:s.value}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((s)=>{if(s.status==="aborted")return F;if(s.status==="dirty")t.dirty();return i(s.value).then(()=>({status:t.value,value:s.value}))})}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ht(i))return F;let s=o.transform(i.value,r);if(s instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((i)=>{if(!ht(i))return F;return Promise.resolve(o.transform(i.value,r)).then((s)=>({status:t.value,value:s}))});Y.assertNever(o)}}Ke.create=(e,t,n)=>new Ke({schema:e,typeName:z.ZodEffects,effect:t,...V(n)});Ke.createWithPreprocess=(e,t,n)=>new Ke({schema:t,effect:{type:"preprocess",transform:e},typeName:z.ZodEffects,...V(n)});class qe extends J{_parse(e){if(this._getType(e)===S.undefined)return Se(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}qe.create=(e,t)=>new qe({innerType:e,typeName:z.ZodOptional,...V(t)});class lt extends J{_parse(e){if(this._getType(e)===S.null)return Se(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}lt.create=(e,t)=>new lt({innerType:e,typeName:z.ZodNullable,...V(t)});class kn extends J{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;if(t.parsedType===S.undefined)n=this._def.defaultValue();return this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}kn.create=(e,t)=>new kn({innerType:e,typeName:z.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...V(t)});class An extends J{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});if(dn(o))return o.then((r)=>({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Te(n.common.issues)},input:n.data})}));else return{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Te(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}An.create=(e,t)=>new An({innerType:e,typeName:z.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...V(t)});class rr extends J{_parse(e){if(this._getType(e)!==S.nan){let n=this._getOrReturnCtx(e);return R(n,{code:x.invalid_type,expected:S.nan,received:n.parsedType}),F}return{status:"valid",value:e.data}}}rr.create=(e)=>new rr({typeName:z.ZodNaN,...V(e)});var Dd=Symbol("zod_brand");class no extends J{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class or extends J{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let r=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});if(r.status==="aborted")return F;if(r.status==="dirty")return t.dirty(),Nt(r.value);else return this._def.out._parseAsync({data:r.value,path:n.path,parent:n})})();else{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});if(o.status==="aborted")return F;if(o.status==="dirty")return t.dirty(),{status:"dirty",value:o.value};else return this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,t){return new or({in:e,out:t,typeName:z.ZodPipeline})}}class Rn extends J{_parse(e){let t=this._def.innerType._parse(e),n=(o)=>{if(ht(o))o.value=Object.freeze(o.value);return o};return dn(t)?t.then((o)=>n(o)):n(t)}unwrap(){return this._def.innerType}}Rn.create=(e,t)=>new Rn({innerType:e,typeName:z.ZodReadonly,...V(t)});var Md={object:he.lazycreate},z;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(z||(z={}));var v=Qe.create,tt=Mt.create,Xa=rr.create,Ld=Lt.create,ct=Yn.create,$d=fn.create,jd=Qn.create,Fd=mn.create,Bd=gn.create,Hd=Zn.create,$e=yt.create,zd=Ze.create,Ud=er.create,ae=Ue.create,{create:E,strictCreate:qd}=he,sr=hn.create,ir=to.create,Kd=yn.create,wn=et.create,ro=tr.create,Vd=nr.create,Gd=$t.create,Wd=pn.create,Xd=xn.create,ce=bn.create,nt=xt.create,Jd=vn.create,Yd=jt.create,Qd=Ke.create,Zd=qe.create,ep=lt.create,Ja=Ke.createWithPreprocess,tp=or.create;var oo=F;var Ya=E({before:v(),after:v(),hierarchy:ae(v()),lineStart:tt().optional(),lineEnd:tt().optional()}).passthrough(),Qa=E({id:v(),name:v()}).passthrough(),Za=E({url:v(),mime:v().optional()}).passthrough(),so=E({id:v(),snippet:v(),note:v(),createdAt:v(),filePath:v().optional(),canvasFile:v().optional(),context:Ya.optional(),images:ae(v()).optional(),attachments:ae(Za).optional(),source:nt(["local","remote"]).optional(),author:Qa.optional()}).passthrough(),el=ae(so.optional().catch(void 0)).transform((e)=>e.filter((t)=>t!==void 0)).catch([]),io=E({annotations:el,generalNote:v().catch("")}).passthrough(),ks=E({path:v()}),As=E({url:v()}),Rs=E({error:v()});import{useCallback as vt,useMemo as tl,useState as nl}from"react";var ut="__agent-response__";function bt(e){return e.filePath&&e.filePath!=="__agent-response__"?e.filePath:void 0}function Sn(e){return e.uploadUrl!==null}var ao=["image/png","image/jpeg","image/gif","image/webp"],ws="Only PNG, JPEG, GIF and WebP images can be attached";function rt(){return`ann-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function dt(e,t){e.style.height="auto",e.style.height=(t?Math.max(t,e.scrollHeight):e.scrollHeight)+"px"}function Ss(e){let t=e?`[data-annotation-id="${CSS.escape(e)}"]`:"[data-annotation-id]";for(let n of document.querySelectorAll(t))if(n.tagName==="MARK"){let o=n.parentNode;n.replaceWith(document.createTextNode(n.textContent||"")),o?.normalize()}else n.remove()}function ar({annotations:e,setAnnotations:t,generalNote:n,setGeneralNote:o,remoteAnnotations:r,isReadOnly:i,onClear:s}){let[l,a]=nl(null),c=tl(()=>{if(!r?.length)return e;let A=new Set(e.map((g)=>g.id)),b=r.filter((g)=>!A.has(g.id));return[...e,...b.map((g)=>({...g,source:"remote"}))]},[e,r]),u=vt((A,b,g,B,D,H,T)=>{t((U)=>[...U,{id:A,snippet:b,note:g,createdAt:new Date().toISOString(),filePath:B,context:D,...H?.length?{images:H}:{},...T?{canvasFile:T}:{}}])},[t]),d=vt((A,b,g)=>{u(rt(),A,b,g)},[u]),f=vt((A,b)=>{t((g)=>g.map((B)=>B.id===A?{...B,note:b}:B))},[t]),p=vt((A)=>{if(!e.some((b)=>b.id===A))return;Ss(A),t((b)=>b.filter((g)=>g.id!==A)),a((b)=>b===A?null:b)},[e,t]),m=vt((A,b)=>{t((g)=>g.map((B)=>B.id===A?{...B,images:[...B.images||[],b]}:B))},[t]),h=vt((A,b)=>{t((g)=>g.map((B)=>B.id===A?{...B,images:(B.images||[]).filter((D)=>D!==b)}:B))},[t]),y=vt(()=>{Ss(),t([]),o(""),a(null),s?.()},[t,o,s]);return{annotations:c,generalNote:n,setGeneralNote:o,activeAnnotationId:l,setActiveAnnotationId:a,addAnnotation:d,addAnnotationWithId:u,updateAnnotation:f,removeAnnotation:p,addAnnotationImage:m,removeAnnotationImage:h,clearAll:y,isReadOnly:i}}import{useAnnotations as pt}from"@fabrika/annotations/runtime";import{jsxDEV as kt,Fragment as rl}from"react/jsx-dev-runtime";function lo({hasContent:e,onSubmit:t,onSubmitEmpty:n,notice:o,secondaryAction:r,placeholder:i="General notes...",submitLabel:s="Submit",emptyLabel:l="Submit without feedback"}){let{generalNote:a,setGeneralNote:c}=pt();return kt(rl,{children:[kt("div",{className:"border-t border-border-subtle px-4 py-3 flex-shrink-0",children:kt("textarea",{value:a,onChange:(u)=>c(u.currentTarget.value),className:"w-full bg-transparent text-[13px] font-body text-text-primary resize-none leading-relaxed p-0 border-none ring-0 shadow-none outline-none focus:outline-none focus:ring-0 focus:border-none placeholder:text-text-disabled min-h-[40px]",placeholder:i,onInput:(u)=>dt(u.currentTarget,40),ref:(u)=>{if(u)dt(u,40)}},void 0,!1,void 0,this)},void 0,!1,void 0,this),o,kt("div",{className:"px-4 py-3 border-t border-border-subtle flex-shrink-0",children:e?kt("div",{className:"flex gap-2",children:[r,kt("button",{onClick:t,className:"flex-1 py-2 rounded-lg font-body text-[13px] font-medium transition-all bg-btn-primary text-btn-primary-text hover:opacity-90 hover:-translate-y-px shadow-sm",children:s},void 0,!1,void 0,this)]},void 0,!0,void 0,this):kt("button",{onClick:n,className:"w-full py-2 rounded-lg font-body text-[13px] font-medium border border-border-medium text-text-secondary hover:text-text-primary hover:border-border-hover hover:bg-bg-input transition-all",children:l},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{useAnnotationHost as ol}from"@fabrika/annotations/runtime";import{useCallback as ot,useEffect as sl,useRef as co,useState as lr}from"react";import{jsxDEV as ve}from"react/jsx-dev-runtime";function uo(e){if(e.startsWith("/s/")||e.startsWith("http://")||e.startsWith("https://"))return e;return`/api/uploads/${e.split("/").pop()}`}async function il(e,t){let n=e.uploadUrl;if(!n)return{error:"Uploads are not available here"};let o=new FormData;o.append("image",t);try{let r=await fetch(n(),{method:"POST",body:o}),i=await r.json();if(!r.ok){let s=Rs.safeParse(i);return{error:s.success?s.data.error:`Upload failed (HTTP ${r.status})`}}return{path:e.isShared?As.parse(i).url:ks.parse(i).path}}catch{return{error:"Upload failed"}}}function Ft({note:e,onNoteChange:t,images:n,onAddImage:o,onRemoveImage:r,sessionId:i,placeholder:s="Add your note...",autoFocus:l=!1,autoResize:a=!1,readOnly:c=!1,onKeyDown:u,onTextareaClick:d,textareaRef:f,textareaClassName:p,textareaStyle:m,minHeight:h,attachButton:y="always",openFilePickerRef:A}){let b=ol(),g=!c&&Sn(b),[B,D]=lr(!1),[H,T]=lr(!1),[U,M]=lr(null),[q,oe]=lr(!1),ne=co(0),ie=co(null),ke=co(null),G=ot(()=>ke.current?.click(),[]);if(A)A.current=G;let re=ot((w)=>{if(ie.current=w,f)f.current=w;if(w&&a)dt(w,h)},[f,a,h]);sl(()=>{if(l&&ie.current){let w=ie.current;if(w.focus(),w.value)w.setSelectionRange(w.value.length,w.value.length)}},[l]);let Z=ot(async(w)=>{if(!ao.includes(w.type)){M(ws);return}M(null),T(!0);try{let k=await il(b,w);if("path"in k)o(k.path);else M(k.error)}finally{T(!1)}},[b,o]),ue=ot((w)=>{for(let k of w.clipboardData?.items??[])if(k.type.startsWith("image/")){w.preventDefault();let j=k.getAsFile();if(j)Z(j);return}},[Z]),ee=ot((w)=>{if(w.preventDefault(),ne.current++,ne.current===1)D(!0)},[]),se=ot((w)=>{w.preventDefault()},[]),fe=ot((w)=>{if(w.preventDefault(),ne.current--,ne.current===0)D(!1)},[]),I=ot((w)=>{w.preventDefault(),ne.current=0,D(!1);for(let k of w.dataTransfer?.files??[])if(k.type.startsWith("image/"))Z(k)},[Z]),N=ot((w)=>{if(t(w.currentTarget.value),a)w.currentTarget.style.height="auto",w.currentTarget.style.height=(h?Math.max(h,w.currentTarget.scrollHeight):w.currentTarget.scrollHeight)+"px"},[t,a,h]),K="w-full bg-transparent text-[13px] font-body text-text-primary resize-none focus:outline-none leading-relaxed p-0 border-none",P={width:"100%",background:"transparent",border:"none",color:"var(--color-text-primary)",fontFamily:"'Inter', sans-serif",fontSize:"13px",lineHeight:"1.5",outline:"none",...a?{resize:"none",overflow:"hidden"}:{resize:"vertical"}},L=g&&(y==="always"||y==="on-focus"&&q);return ve("div",{style:{position:"relative"},onDragEnter:g?ee:void 0,onDragOver:g?se:void 0,onDragLeave:g?fe:void 0,onDrop:g?I:void 0,children:[ve("textarea",{ref:re,value:e,onChange:c?void 0:N,onPaste:g?ue:void 0,onKeyDown:u,onClick:d,onFocus:()=>oe(!0),onBlur:()=>{setTimeout(()=>oe(!1),150)},readOnly:c,placeholder:s,className:p??K,style:m??P,rows:a?1:void 0},void 0,!1,void 0,this),g&&ve("input",{ref:ke,type:"file",accept:ao.join(","),multiple:!0,style:{display:"none"},onChange:(w)=>{let k=w.currentTarget.files;if(k)for(let j of k)Z(j);w.currentTarget.value=""}},void 0,!1,void 0,this),(n.length>0||L)&&ve("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap",marginTop:"6px",alignItems:"center"},children:[n.map((w)=>ve("div",{style:{position:"relative",width:"56px",height:"56px",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--color-border-subtle)",flexShrink:0},children:[ve("img",{src:uo(w),alt:"",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}},void 0,!1,void 0,this),!c&&ve("button",{onClick:(k)=>{k.stopPropagation(),r(w)},style:{position:"absolute",top:"2px",right:"2px",width:"16px",height:"16px",borderRadius:"50%",background:"rgba(0,0,0,0.6)",color:"white",border:"none",cursor:"pointer",fontSize:"11px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,padding:0},title:"Remove image",children:"×"},void 0,!1,void 0,this)]},w,!0,void 0,this)),L&&ve(cr,{onClick:G},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H&&ve("div",{style:{fontSize:"11px",color:"var(--color-text-tertiary)",fontFamily:"'Inter', sans-serif",marginTop:"4px"},children:"Uploading..."},void 0,!1,void 0,this),U&&ve("div",{role:"alert",style:{fontSize:"11px",color:"var(--color-accent-red)",fontFamily:"'Inter', sans-serif",marginTop:"4px"},children:U},void 0,!1,void 0,this),B&&ve("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--color-highlight-bg)",opacity:0.9,border:"2px dashed var(--color-highlight-border)",borderRadius:"6px",zIndex:10,pointerEvents:"none",fontSize:"12px",fontFamily:"'Inter', sans-serif",color:"var(--color-text-secondary)"},children:"Drop image"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function cr({onClick:e,size:t=16}){return ve("button",{onClick:(n)=>{n.stopPropagation(),e()},style:{width:`${t*2}px`,height:`${t*2}px`,borderRadius:"6px",border:"none",background:"transparent",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--color-text-tertiary)",flexShrink:0,transition:"color 0.15s"},title:"Attach image",onMouseEnter:(n)=>{n.currentTarget.style.color="var(--color-text-secondary)"},onMouseLeave:(n)=>{n.currentTarget.style.color="var(--color-text-tertiary)"},children:ve("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[ve("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},void 0,!1,void 0,this),ve("circle",{cx:"8.5",cy:"8.5",r:"1.5"},void 0,!1,void 0,this),ve("polyline",{points:"21 15 16 10 5 21"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function po({images:e}){if(!e.length)return null;return ve("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap",marginTop:"6px"},children:e.map((t)=>ve("div",{style:{width:"56px",height:"56px",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--color-border-subtle)",flexShrink:0},children:ve("img",{src:uo(t),alt:"",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}},void 0,!1,void 0,this)},t,!1,void 0,this))},void 0,!1,void 0,this)}import{SessionContext as al}from"@fabrika/annotations/runtime";import{useContext as ll,useEffect as cl,useRef as ul}from"react";import{jsxDEV as me,Fragment as Es}from"react/jsx-dev-runtime";function dl(e){let t=cn(e);return t.length>80?t.slice(0,80)+"...":t}function En({annotations:e,readOnly:t=!1,onSelect:n,onReveal:o,includedRemoteIds:r,onToggleRemoteId:i}){let{updateAnnotation:s,removeAnnotation:l,addAnnotationImage:a,removeAnnotationImage:c,activeAnnotationId:u,setActiveAnnotationId:d}=pt(),f=ll(al),p=ul(new Map);cl(()=>{if(t||!u)return;let g=p.current.get(u);if(g)g.scrollIntoView({behavior:"smooth",block:"nearest"})},[u,t]);let m=(g)=>{d(g),Pt(g,!0)},h=(g)=>{d(null),Pt(g,!1)},y=(g)=>{if(g.id===u){d(null);return}d(g.id),n?.(g)},A=!!r&&!!i,b=(g)=>{let B=A&&g.source==="remote";return me("div",{ref:(D)=>{if(D)p.current.set(g.id,D);else p.current.delete(g.id)},className:`group/ann relative px-3 py-2.5 transition-colors duration-150 ${t?"cursor-pointer ":""}${u===g.id?"bg-highlight-selected":B?"bg-accent-purple-muted/30 hover:bg-accent-purple-muted/50":"odd:bg-bg-elevated-half hover:bg-bg-input"}`,onMouseEnter:()=>m(g.id),onMouseLeave:()=>h(g.id),onClick:()=>y(g),children:[B&&g.author&&me("div",{className:"flex items-center gap-1.5 mb-1.5",children:[me("input",{type:"checkbox",checked:r.has(g.id),onChange:(D)=>{D.stopPropagation(),i(g.id)},onClick:(D)=>D.stopPropagation(),className:"accent-accent-purple flex-shrink-0",title:"Include in submission"},void 0,!1,void 0,this),me("span",{className:"inline-flex items-center justify-center w-4 h-4 rounded-full bg-accent-purple text-white text-[9px] font-medium uppercase",children:g.author.name.charAt(0)},void 0,!1,void 0,this),me("span",{className:"text-[11px] font-medium text-accent-purple font-body",children:g.author.name},void 0,!1,void 0,this),me("span",{className:"text-[10px] text-text-tertiary font-body uppercase tracking-widest",children:"Remote"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),me("div",{className:"text-[11px] text-text-tertiary italic line-clamp-2 mb-1.5 leading-snug font-body border-l-2 border-border-medium pl-2",children:dl(g.snippet)},void 0,!1,void 0,this),t?me(Es,{children:[g.note.trim()&&me("div",{className:"text-[13px] font-body text-text-primary leading-relaxed",children:g.note},void 0,!1,void 0,this),me(po,{images:g.images||[]},void 0,!1,void 0,this)]},void 0,!0,void 0,this):B?me("div",{className:"text-[13px] font-body text-text-primary leading-relaxed whitespace-pre-wrap",children:g.note},void 0,!1,void 0,this):me("div",{onClick:(D)=>D.stopPropagation(),children:me(Ft,{note:g.note,onNoteChange:(D)=>s(g.id,D),images:g.images||[],onAddImage:(D)=>a(g.id,D),onRemoveImage:(D)=>c(g.id,D),sessionId:f,autoResize:!0,minHeight:20,textareaClassName:"w-full bg-transparent text-[13px] font-body text-text-primary resize-none focus:outline-none leading-relaxed p-0 border-none min-h-[20px]",textareaStyle:{height:"auto",overflow:"hidden"},placeholder:"Add your note...",attachButton:"on-focus"},void 0,!1,void 0,this)},void 0,!1,void 0,this),me("div",{className:"absolute top-1.5 right-1.5 opacity-0 group-hover/ann:opacity-100 transition-opacity duration-100 flex items-center gap-0.5",children:[o&&me("button",{onClick:(D)=>{D.stopPropagation(),o(g)},className:"w-5 h-5 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary hover:bg-bg-input transition-colors",title:"Scroll to annotation",children:me("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[me("circle",{cx:"12",cy:"12",r:"3"},void 0,!1,void 0,this),me("path",{d:"M12 2v4M12 18v4M2 12h4M18 12h4"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!t&&!B&&me("button",{onClick:(D)=>{D.stopPropagation(),l(g.id)},className:"w-5 h-5 flex items-center justify-center rounded text-text-tertiary hover:text-accent-red hover:bg-accent-red-muted transition-colors",title:"Delete annotation",children:me("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[me("polyline",{points:"3 6 5 6 21 6"},void 0,!1,void 0,this),me("path",{d:"M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},g.id,!0,void 0,this)};return me(Es,{children:e.map(b)},void 0,!1,void 0,this)}function ur(e){let t=[],n=e.snippet.trim(),o=e.context,r=cn(n);if(r!==n)t.push(`> ${r}`);else if(e.filePath&&o&&o.lineStart!=null){let l=o.lineStart,a=o.lineEnd??l,c=n.split(`
|
|
2
|
+
`);if(n.length<30&&l===a&&(o.before||o.after)){let d=Hn(e);t.push(`> L${l}: ${d}`)}else if(c.length<=6)for(let d=0;d<c.length;d++)t.push(`> ${l+d} | ${c[d]}`);else{for(let d=0;d<3;d++)t.push(`> ${l+d} | ${c[d]}`);t.push(`> ... (${c.length} lines)`);for(let d=c.length-3;d<c.length;d++)t.push(`> ${l+d} | ${c[d]}`)}}else{let l=Hn(e);if(n.split(`
|
|
3
|
+
`).length<=3)t.push(`> ${l.split(`
|
|
4
|
+
`).join(`
|
|
5
|
+
> `)}`);else{let a=n.split(`
|
|
6
|
+
`);t.push(`> ${a[0]}`),t.push(`> ... (${a.length} lines)`),t.push(`> ${a[a.length-1]}`)}}if(e.note.trim())t.push(""),t.push(e.note.trim());let i=[...e.images??[]],s=new Set(i);for(let l of e.attachments??[]){if(s.has(l.url))continue;s.add(l.url),i.push(l.url)}if(i.length){t.push("");for(let l of i)t.push(``)}return t.push(""),t.join(`
|
|
7
|
+
`)}import{SessionContext as pl,useAnnotationHost as fl}from"@fabrika/annotations/runtime";import{useCallback as dr,useContext as ml,useEffect as gl,useMemo as Cs,useRef as pr,useState as Bt}from"react";import{createPortal as hl}from"react-dom";function _s(e){let t=/^(\d+(?:\.\d+)?)px$/.exec(e.trim());return t?Number(t[1]):void 0}function Is(e,t,n=280){let r=t||document.body,i=e.getBoundingClientRect(),s=r.getBoundingClientRect(),l=r===document.body?0:r.scrollTop,a=i.bottom-s.top+l+8,c=Math.max(0,Math.min(i.left-s.left,s.width-n-12));return r.style.position="relative",{style:{position:"absolute",top:`${a}px`,left:`${c}px`},parent:r}}import{jsxDEV as Ae,Fragment as yl}from"react/jsx-dev-runtime";function Ps({anchorEl:e,scrollContainer:t,onClose:n,ignoreSelector:o,zIndex:r="50",padding:i="12px",width:s="280px",children:l}){let a=pr(null),c=pr(n);c.current=n;let{style:u,parent:d}=Is(e,t,_s(s));return gl(()=>{let f=setTimeout(()=>{let p=(m)=>{if(a.current&&!a.current.contains(m.target)){if(o&&m.target.closest?.(o))return;c.current(),document.removeEventListener("mousedown",p)}};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},0);return()=>clearTimeout(f)},[o]),hl(Ae("div",{ref:a,style:{...u,zIndex:r,width:s,background:"var(--color-bg-elevated)",border:"1px solid var(--color-border-hover)",borderRadius:"8px",boxShadow:"0 4px 12px var(--color-shadow)",padding:i,fontFamily:"'Inter', sans-serif"},children:l},void 0,!1,void 0,this),d)}var Os=[{label:"Clarity",items:["Unclear","Why?","Needs example","Missing context"]},{label:"Scope",items:["Overkill","Out of scope","Important","Risky"]},{label:"Action",items:["Simplify","Rethink","Expand on this","Skip this"]}],Ts=Os.flatMap((e)=>e.items);function fo({anchorEl:e,scrollContainer:t,snippet:n,truncateAt:o=100,header:r,initialNote:i="",initialImages:s,onConfirm:l,onCancel:a,onDelete:c}){let u=ml(pl),d=fl(),f=Sn(d),p=i!==""||!!c,[m,h]=Bt(i),[y,A]=Bt(s||[]),[b,g]=Bt(null),[B,D]=Bt(p),[H,T]=Bt(!1),U=pr(null),M=pr(null),q=dr(()=>{if(m.trim()||y.length>0)l(m.trim(),y);else if(p&&c)c();else a()},[m,y,l,a,p,c]),oe=dr(()=>{if(p){if(!m.trim()&&y.length===0&&c){c(),a();return}l(m,y);return}a()},[m,y,p,l,a,c]),ne=!p,ie=m.trim().length>0?Ts.filter((k)=>k.toLowerCase().startsWith(m.trim().toLowerCase())):Ts,ke=!ne||B?[]:ie.length===1&&ie[0]?.toLowerCase()===m.trim().toLowerCase()?[]:ie,G=new Set(ke),re=Os.map((k)=>({label:k.label,items:k.items.filter((j)=>G.has(j))})).filter((k)=>k.items.length>0),Z=re.map((k)=>k.items),ue=(k)=>Z[k]?.length??0,ee=Z.flat(),se=Cs(()=>{if(b===null)return 0;let k=0;for(let j=0;j<Z.length;j++){if(b<k+ue(j))return j;k+=ue(j)}return 0},[b,Z]),fe=Cs(()=>{if(b===null)return 0;let k=0;for(let j=0;j<se;j++)k+=ue(j);return b-k},[b,se,Z]),I=(k,j)=>{let W=0;for(let de=0;de<k;de++)W+=ue(de);return W+j},[N,K]=Bt(m);if(m!==N)K(m),g(null),D(p);let P=dr((k)=>{h(k)},[]),L=n.length>o?n.slice(0,o)+"...":n,w=dr((k)=>{if(ee.length>0&&(k.key==="ArrowDown"||k.key==="ArrowUp"||k.key==="ArrowLeft"||k.key==="ArrowRight")){if(k.preventDefault(),b===null){g(0);return}if(k.key==="ArrowDown"){let W=Math.min(fe+1,ue(se)-1);g(I(se,W))}else if(k.key==="ArrowUp"){let W=Math.max(fe-1,0);g(I(se,W))}else if(k.key==="ArrowRight"){let W=Math.min(se+1,Z.length-1),de=Math.min(fe,ue(W)-1);g(I(W,de))}else if(k.key==="ArrowLeft"){let W=Math.max(se-1,0),de=Math.min(fe,ue(W)-1);g(I(W,de))}return}let j=b===null?void 0:ee[b];if(j!==void 0){if(k.key==="Tab"){k.preventDefault(),P(j);return}if(k.key==="Enter"&&!k.shiftKey){k.preventDefault(),l(j,y);return}}if(k.key==="Enter"&&!k.shiftKey){k.preventDefault(),q();return}if(k.key==="Escape")if(ee.length>0&&!B)D(!0);else if(p)oe();else a()},[ee,b,fe,se,Z,I,P,l,y,q,B,p,oe,a]);return Ae(Ps,{anchorEl:e,scrollContainer:t,onClose:p?oe:a,ignoreSelector:p?"[data-annotation-id]":void 0,zIndex:p?"60":"50",padding:p?"10px 12px":"12px",width:"420px",children:[!p&&(r??Ae("div",{style:{fontSize:"11px",color:"var(--color-text-tertiary)",fontStyle:"italic",marginBottom:"8px",lineHeight:"1.4",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:["“",L,"”"]},void 0,!0,void 0,this)),Ae(Ft,{note:m,onNoteChange:h,images:y,onAddImage:(k)=>A((j)=>[...j,k]),onRemoveImage:(k)=>A((j)=>j.filter((W)=>W!==k)),sessionId:u,autoFocus:!0,autoResize:p,textareaRef:U,onKeyDown:w,attachButton:"none",openFilePickerRef:M,textareaStyle:p?{width:"100%",background:"transparent",border:"none",color:"var(--color-text-primary)",fontFamily:"'Inter', sans-serif",fontSize:"13px",lineHeight:"1.5",resize:"none",outline:"none",overflow:"hidden"}:{width:"100%",minHeight:"60px",background:"transparent",border:"none",color:"var(--color-text-primary)",fontFamily:"'Inter', sans-serif",fontSize:"13px",lineHeight:"1.5",resize:"vertical",outline:"none"},placeholder:"Add your note..."},void 0,!1,void 0,this),Ae("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginTop:p?"6px":"8px"},children:[f&&Ae(cr,{onClick:()=>M.current?.(),size:14},void 0,!1,void 0,this),Ae("div",{style:{flex:1}},void 0,!1,void 0,this),p?Ae("button",{onClick:()=>{if(c)c();a()},onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),style:{fontSize:"11px",color:H?"var(--color-accent-red)":"var(--color-text-tertiary)",background:"none",border:"none",cursor:"pointer",padding:"2px 0",fontFamily:"'Inter', sans-serif"},children:"Delete"},void 0,!1,void 0,this):Ae(yl,{children:[Ae("button",{onClick:a,style:{fontSize:"11px",color:"var(--color-text-tertiary)",background:"none",border:"none",cursor:"pointer",padding:"4px 12px",fontFamily:"'Inter', sans-serif"},children:"Cancel"},void 0,!1,void 0,this),Ae("button",{onClick:q,style:{fontSize:"11px",fontWeight:500,padding:"4px 12px",borderRadius:"6px",background:"var(--color-highlight-bg)",color:"var(--color-text-primary)",border:"1px solid var(--color-highlight-border)",cursor:"pointer",fontFamily:"'Inter', sans-serif"},children:"Add"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),ee.length>0&&Ae("div",{style:{marginTop:"6px",borderTop:"1px solid var(--color-border-subtle)",paddingTop:"8px",display:"flex",gap:"4px"},children:re.map((k)=>Ae("div",{style:{flex:1},children:[Ae("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--color-text-disabled)",textTransform:"uppercase",letterSpacing:"0.05em",padding:"2px 6px",marginBottom:"2px",fontFamily:"'Inter', sans-serif"},children:k.label},void 0,!1,void 0,this),k.items.map((j)=>{let W=ee.indexOf(j);return Ae("div",{onMouseDown:(de)=>{de.preventDefault(),de.stopPropagation(),P(j)},onMouseEnter:()=>g(W),style:{padding:"3px 6px",fontSize:"12px",borderRadius:"4px",fontFamily:"'Inter', sans-serif",color:W===b?"var(--color-text-primary)":"var(--color-text-secondary)",background:W===b?"var(--color-highlight-selected)":"transparent",cursor:"pointer"},children:[Ae("span",{style:{fontWeight:500},children:j.slice(0,m.trim().length)},void 0,!1,void 0,this),j.slice(m.trim().length)]},j,!0,void 0,this)})]},k.label,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ft({anchorEl:e,scrollContainer:t,snippet:n,truncateAt:o,header:r,onAdd:i,onCancel:s}){return Ae(fo,{anchorEl:e,scrollContainer:t,snippet:n,truncateAt:o,header:r,onConfirm:(l,a)=>i(l,a),onCancel:s},void 0,!1,void 0,this)}function _n({anchorEl:e,scrollContainer:t,initialNote:n,initialImages:o,onUpdate:r,onDelete:i,onClose:s}){return Ae(fo,{anchorEl:e,scrollContainer:t,snippet:"",initialNote:n,initialImages:o,onConfirm:(l,a)=>{r(l,a),s()},onDelete:i,onCancel:s},void 0,!1,void 0,this)}import{useEffect as xl,useRef as mo,useState as Ns}from"react";import{jsxDEV as bl}from"react/jsx-dev-runtime";function go(e){let{containerRef:t,restoreKey:n,shape:o="rect",canvasFile:r,scrollContainer:i}=e,{addAnnotationWithId:s}=pt(),[l,a]=Ns(null),[c,u]=Ns(!1),d=mo(s);d.current=s;let f=mo(r);f.current=r;let p=mo(o);return p.current=o,xl(()=>{let h=t.current;if(!h)return;let y=null;function A(T,U){let M=T.getBoundingClientRect();return Vr(M,U.clientX-M.left,U.clientY-M.top)}function b(){if(!y)return;let{host:T,pointerId:U}=y;if(T.hasPointerCapture(U))T.releasePointerCapture(U);T.removeEventListener("pointermove",B),T.removeEventListener("pointerup",D),T.removeEventListener("pointercancel",H),y=null,u(!1)}function g(T){if(y||T.button!==0)return;let U=T.target;if(!(U instanceof Element))return;if(U.closest("[data-block-comment-btn]"))return;if(U.closest("[data-annotation-id]"))return;let M=U.closest(`[${Kr}]`);if(!(M instanceof HTMLElement)||!h?.contains(M))return;let q=M.closest("[data-md='image']")?.getAttribute("data-md-src");if(!q)return;let oe=A(M,T);if(!oe)return;T.preventDefault(),M.setPointerCapture(T.pointerId);let ne=rt(),ie=Wn({...oe,w:0,h:0},p.current,ne);ie.classList.add("ann-region-draft"),M.appendChild(ie),y={pointerId:T.pointerId,host:M,src:q,start:oe,shape:p.current,overlay:ie,id:ne},M.addEventListener("pointermove",B),M.addEventListener("pointerup",D),M.addEventListener("pointercancel",H),u(!0)}function B(T){if(!y||y.pointerId!==T.pointerId)return;let U=A(y.host,T);if(!U)return;Gn(y.overlay,Kn(y.start,U))}function D(T){if(!y||y.pointerId!==T.pointerId)return;let{overlay:U,id:M,src:q,shape:oe}=y,ne=A(y.host,T)??y.start,ie=Kn(y.start,ne);if(b(),!Gr(ie)){U.remove();return}Gn(U,ie);let ke={src:q,shape:oe,...ie};a({overlay:U,id:M,snippet:ln.format(ke),label:Vn(ke)})}function H(T){if(!y||y.pointerId!==T.pointerId)return;y.overlay.remove(),b()}return h.addEventListener("pointerdown",g),()=>{if(h.removeEventListener("pointerdown",g),y)y.overlay.remove(),b()}},[n]),{popovers:l?bl(ft,{anchorEl:l.overlay,scrollContainer:i,snippet:l.label,truncateAt:80,onAdd:(h,y)=>{l.overlay.classList.remove("ann-region-draft"),d.current(l.id,l.snippet,h,void 0,void 0,y,f.current),a(null)},onCancel:()=>{l.overlay.remove(),a(null)}},void 0,!1,void 0,this):null,isDrawing:c,isPopoverOpen:!!l}}import{useCallback as Ds,useEffect as fr,useRef as At,useState as Ms}from"react";import{jsxDEV as ho,Fragment as vl}from"react/jsx-dev-runtime";function yo(e){let{containerRef:t,restoreKey:n,restoreAnnotations:o,extractContext:r,filePath:i,canvasFile:s,scrollContainer:l}=e,{annotations:a,addAnnotationWithId:c,removeAnnotation:u,updateAnnotation:d,addAnnotationImage:f,removeAnnotationImage:p,activeAnnotationId:m,setActiveAnnotationId:h}=pt(),[y,A]=Ms(null),[b,g]=Ms(null),B=At(r);B.current=r;let D=At(i);D.current=i;let H=At(s);H.current=s;let T=At(c);T.current=c;let U=At(m);U.current=m;let M=At(h);M.current=h;let q=o.length;fr(()=>{if(!t.current)return;let G=setTimeout(()=>{if(t.current)Jr(t.current,o)},50);return()=>clearTimeout(G)},[n,q]);let oe=At(null);fr(()=>{$r(m,oe.current),oe.current=m},[m]),fr(()=>{let G=t.current;if(!G)return;let re=(ee)=>{let se=ee.target.closest("[data-annotation-id]");if(!se)return;ee.stopPropagation();let fe=se.getAttribute("data-annotation-id");if(fe===U.current)A({anchorEl:se,annId:fe});else M.current(fe)},Z=(ee)=>{let se=ee.target.closest("[data-annotation-id]");if(se)M.current(se.getAttribute("data-annotation-id"))},ue=(ee)=>{let se=ee.target.closest("[data-annotation-id]"),fe=ee.relatedTarget?.closest?.("[data-annotation-id]");if(se&&!fe&&!document.getElementById("ann-inline-popover"))M.current(null)};return G.addEventListener("click",re),G.addEventListener("mouseover",Z),G.addEventListener("mouseout",ue),()=>{G.removeEventListener("click",re),G.removeEventListener("mouseover",Z),G.removeEventListener("mouseout",ue)}},[n]),fr(()=>{let G=()=>ne();return document.addEventListener("mouseup",G),()=>document.removeEventListener("mouseup",G)},[]);let ne=Ds(()=>{let G=window.getSelection();if(!G||G.isCollapsed||!G.toString().trim())return;if(!t.current)return;let re=G.getRangeAt(0);if(!t.current.contains(re.startContainer))return;if(re.startContainer.parentElement?.closest?.("[data-annotation-id]"))return;let Z=ds(re).trim();if(Z.length<2)return;let ue=B.current(re),ee=re.cloneRange(),se=`__pending_${Date.now()}`;try{Bn(ee,se)}catch{}window.getSelection()?.removeAllRanges();let fe=document.querySelectorAll(`[data-annotation-id="${se}"]`),I=fe[fe.length-1];if(!I)return;g({anchorEl:I,tempId:se,snippet:Z,ctx:ue})},[]),ie=Ds((G,re,Z,ue)=>{g({anchorEl:G,tempId:re,snippet:Z,ctx:ue})},[]);return{popovers:ho(vl,{children:[y&&(()=>{let G=a.find((re)=>re.id===y.annId);if(!G)return null;return ho(_n,{anchorEl:y.anchorEl,scrollContainer:l,initialNote:G.note,initialImages:G.images,onUpdate:(re,Z)=>{d(y.annId,re);let ue=G.images||[];for(let ee of Z)if(!ue.includes(ee))f(y.annId,ee);for(let ee of ue)if(!Z.includes(ee))p(y.annId,ee)},onDelete:()=>{u(y.annId),h(null)},onClose:()=>A(null)},void 0,!1,void 0,this)})(),b&&ho(ft,{anchorEl:b.anchorEl,scrollContainer:l,snippet:b.snippet,truncateAt:80,onAdd:(G,re)=>{let Z=rt();jr(b.tempId,Z),T.current(Z,b.snippet,G,D.current,b.ctx,re,H.current),g(null)},onCancel:()=>{Br(b.tempId),g(null)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),openCreatePopover:ie,isPopoverOpen:!!(y||b)}}import{AnnotationCtx as _l}from"#canvas/runtime";import{AnnotationCtx as Il,AnnotationHostContext as Cl}from"@fabrika/annotations/runtime";import{useCallback as qt,useEffect as Ks,useMemo as Tl,useRef as ko,useState as Kt}from"react";var Wf=E({}).passthrough(),Xf=E({annotations:ae($e()).catch([]),generalNote:v().catch(""),responses:ae($e()).catch([])}),Jf=wn([$e(),E({note:$e(),value:$e()})]);function Rt(e,t,n="current"){let o=`canvas:${e}:rev:${t}`;return n==="next"?`${o}:next-draft`:o}function kl(e,t){return`${Rt(e,t)}:draft-handled`}function xo(e,t,n){try{e.removeItem(Rt(t,n)),e.removeItem(kl(t,n))}catch{}}function bo(e,t){let n=new Map;for(let[o,r]of e)if(t.has(o))n.set(o,r);return n}function vo(e,t){if(!e||e.length===0)return!1;return e.every((n)=>t.has(n))}function Al(e,t){return e.filter((n)=>n.source!=="remote"||t&&t.has(n.id))}function Ht(e,t,n,o,r,i={}){let s=[],l=Al(e,r),a=(h)=>i.annotationIds&&h.source!=="remote"?`Annotation \`${h.id}\`
|
|
8
|
+
${ur(h)}`:ur(h),c=l.filter((h)=>h.filePath===ut),u=l.filter((h)=>!h.filePath),d=l.filter((h)=>h.filePath&&h.filePath!==ut),f=n?Array.from(n.values()).filter((h)=>In(h)):[],p=o?Array.from(o.values()).filter((h)=>h.markdown.trim()):[];if(f.length>0||p.length>0){s.push("## Responses"),s.push("");for(let h of f)s.push(Rl(h));for(let h of p)s.push(h.markdown.trim()),s.push("")}if(c.length>0){s.push("## Annotations on agent response"),s.push("");for(let h of c)s.push(a(h))}if(u.length>0){s.push("## Canvas annotations"),s.push("");let h=new Map;for(let b of u){let g=b.canvasFile||"";if(!h.has(g))h.set(g,[]);h.get(g).push(b)}let y=[...h.keys()].sort(),A=y.length>1||y.length===1&&y[0]!=="";for(let b of y){let g=h.get(b);if(A&&b)s.push(`### ${b.replace(/\.jsx$/,"")}`),s.push("");let B=wl(g);s.push(Fs(B,a))}}if(d.length>0){let h={};for(let y of d){let A=y.filePath;if(!h[A])h[A]=[];h[A].push(y)}s.push("## File annotations"),s.push("");for(let[y,A]of Object.entries(h)){s.push(`### ${y}`),s.push("");for(let b of A)s.push(a(b))}}if(t.trim())s.push("## General notes"),s.push(""),s.push(t.trim()),s.push("");return s.join(`
|
|
9
|
+
`).trim()+`
|
|
10
|
+
`}function Ls(e){return Array.from(e.values()).filter(In).map(({id:t,value:n})=>({id:t,value:n}))}function In(e){if(e.note?.trim())return!0;if(e.value===null||e.value===void 0)return!1;if(e.type==="text"&&!e.value.trim())return!1;if(e.type==="checkbox"&&e.value.length===0)return!1;return!0}function $s(e){let t=[];for(let n of e.values()){if(!n.required)continue;if(n.value===null||n.value===void 0){t.push(n);continue}if(n.type==="text"&&!n.value.trim()){t.push(n);continue}if(n.type==="checkbox"&&n.value.length===0){t.push(n);continue}}return t}function js(e){let t=[];for(let n of e.values())if(n.required&&!n.markdown.trim())t.push(n);return t}function zt(e,t){let n=$s(e),o=js(t);return[...n.map((r)=>r.label),...o.map((r)=>r.label||r.id)]}function Rl(e){let t=[];switch(t.push(`**${e.label}**`),e.type){case"radio":case"select":t.push(`Answer: ${e.value}`);break;case"checkbox":for(let n of e.value)t.push(`- [x] ${n}`);break;case"text":t.push(""),t.push(e.value.trim());break;case"range":t.push(`Answer: ${e.value}`);break}if(e.note?.trim())t.push(""),t.push(`Note: ${e.note.trim()}`);return t.push(""),t.join(`
|
|
11
|
+
`)}function wl(e){let t={label:"",annotations:[],children:new Map};for(let n of e){let o=n.context?.hierarchy||[],r=t;for(let i of o){if(!r.children.has(i))r.children.set(i,{label:i,annotations:[],children:new Map});r=r.children.get(i)}r.annotations.push(n)}return t}function Fs(e,t,n=0){let o=[];for(let r of e.annotations)o.push(t(r));for(let[,r]of e.children){let i=n===0?"###":"####";o.push(`${i} ${r.label}`),o.push(""),o.push(Fs(r,t,n+1))}return o.join(`
|
|
12
|
+
`)}import{createContext as Sl,useContext as El}from"react";function Bs(){if(typeof window>"u")return"";return window.location.pathname.replace("/s/","")}var Hs={get sessionId(){return Bs()},isShared:!1,fsAvailable:!0,uploadUrl:null,loadCanvasModule:(e,t)=>{let n=e.replace(/\.jsx$/,".js"),o=t?`?rev=${t}&t=${Date.now()}`:`?t=${Date.now()}`;return import(`/api/session/${Bs()}/canvas/${encodeURIComponent(n)}${o}`)},threads:null},zs=Sl(Hs);function Ie(){return El(zs)}var mr=E({id:v(),type:nt(["select","radio","checkbox","text","range"]),label:v(),value:$e(),options:ae(v()).optional(),required:ct().optional(),note:v().optional()}).passthrough().transform((e)=>({...e,value:e.value})),gr=E({id:v(),markdown:v(),label:v().optional(),required:ct().optional()}).passthrough(),hr=io.extend({responses:ae(wn([v(),mr]).optional().catch(void 0)).transform((e)=>e.filter((t)=>t!==void 0)).catch([]),feedbackEntries:ae(wn([v(),gr]).optional().catch(void 0)).transform((e)=>e.filter((t)=>t!==void 0)).optional().catch([])});function Ut(e){let t=hr.safeParse(e);return t.success?t.data:null}var Us=E({feedback:v().nullish()}),qs=sr([E({error:v().min(1)}),E({content:v(),language:v().nullish()})]);import{useAnnotations as wt}from"#canvas/runtime";import{jsxDEV as Ro}from"react/jsx-dev-runtime";function Vs(e,t,n){try{let o=localStorage.getItem(Rt(e,t,n));if(!o)return null;return Ut(JSON.parse(o))}catch{return null}}function Pl(e,t,n,o){try{localStorage.setItem(Rt(e,t,n),JSON.stringify(o))}catch{}}function Ao(e){return{draft:e,responseIds:new Set,canvases:new Set}}function yr({sessionId:e,revision:t,isReadOnly:n,draftPhase:o,remoteAnnotations:r,canvasFiles:i,loadState:s,saveState:l,children:a}){let c=!!s,u=c?null:Vs(e,t,o),d=ko(u),[f,p]=Kt(()=>(u?.annotations??[]).map((I)=>({...I,source:I.source??"local"}))),[m,h]=Kt(()=>u?.generalNote??""),[y,A]=Kt(()=>u?.responses?new Map(u.responses):new Map),b=`${e}:${t}:${o}`,g=ko(b);g.current=b;let[B,D]=Kt(()=>Ao(b)),[H,T]=Kt(()=>u?.feedbackEntries?new Map(u.feedbackEntries):new Map),[U,M]=Kt(!c);Ks(()=>{let I=(N)=>{d.current=N,p((N?.annotations??[]).map((K)=>({...K,source:K.source??"local"}))),h(N?.generalNote??""),A(N?.responses?new Map(N.responses):new Map),T(N?.feedbackEntries?new Map(N.feedbackEntries):new Map),se(null)};if(c){let N=!1;return M(!1),s(e,t,o).then((K)=>{if(N)return;I(Ut(K)),M(!0)}),()=>{N=!0}}I(Vs(e,t,o)),M(!0);return},[e,t,o,c,s]);let q=ko(null);Ks(()=>{if(n&&o!=="next")return;if(!U)return;if(q.current)clearTimeout(q.current);let I={...d.current,annotations:f,generalNote:m,responses:Array.from(y.entries()),feedbackEntries:Array.from(H.entries())},N=()=>{if(l)l(e,t,I,o);else Pl(e,t,o,I)};if(o==="next"){N();return}return q.current=setTimeout(N,300),()=>{if(q.current)clearTimeout(q.current)}},[f,m,y,H,e,t,n,o,U,l]);let oe=qt((I,N)=>{A((K)=>{let P=new Map(K);return P.set(I,N),P})},[]),ne=qt((I)=>{D((N)=>{let K=N.draft===g.current?N:Ao(g.current);if(K.responseIds.has(I))return K;return{...K,responseIds:new Set(K.responseIds).add(I)}})},[]),ie=qt((I)=>{D((N)=>{let K=N.draft===g.current?N:Ao(g.current);if(K.canvases.has(I))return K;return{...K,canvases:new Set(K.canvases).add(I)}})},[]),ke=B.draft===b?B:null,G=Tl(()=>{if(!ke||!vo(i,ke.canvases))return y;return bo(y,ke.responseIds)},[ke,i,y]),re=qt((I,N)=>{T((K)=>{let P=K.get(I);if(P&&P.markdown===N.markdown&&P.label===N.label&&P.required===N.required)return K;let L=new Map(K);return L.set(I,N),L})},[]),Z=qt((I)=>{T((N)=>{if(!N.has(I))return N;let K=new Map(N);return K.delete(I),K})},[]),ue=qt(()=>{if(A(new Map),T(new Map),l)l(e,t,{annotations:[],generalNote:"",responses:[],feedbackEntries:[]},o);else if(o==="next")localStorage.removeItem(Rt(e,t,o));else xo(localStorage,e,t)},[e,t,o,l]),ee=ar({annotations:f,setAnnotations:p,generalNote:m,setGeneralNote:h,remoteAnnotations:r,isReadOnly:n,onClear:ue}),{setActiveAnnotationId:se}=ee,fe=Ie();return Ro(Cl.Provider,{value:fe,children:Ro(Il.Provider,{value:ee,children:Ro(_l.Provider,{value:{...ee,responses:y,setResponse:oe,submittableResponses:G,registerResponse:ne,registerCanvasRendered:ie,feedbackEntries:H,setFeedbackEntry:re,removeFeedbackEntry:Z},children:a},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}import{ActiveViewCtx as Xc,AnnotationCtx as Jc,CanvasFileCtx as Yc,SessionContext as Ko,useAnnotations as Qc,useCanvasFile as Hy,useFeedback as Zc,useResponseRegistration as zy}from"#canvas/runtime";function Cn(e){let t=document.querySelector(`[data-annotation-id="${e.id}"]`);if(t instanceof HTMLElement)return t;let n=e.canvasFile?document.querySelector(`[data-canvas-file="${e.canvasFile}"]`):document;if(!n)return null;return Xr(e.snippet,n)}function Gs(e){e.classList.remove("ann-flash"),e.offsetWidth,e.classList.add("ann-flash"),e.addEventListener("animationend",()=>{e.classList.remove("ann-flash")},{once:!0})}function wo(e,t){let n=bt(e);if(n)t({type:"file",path:n}),setTimeout(()=>{let o=Cn(e);if(o)o.scrollIntoView({behavior:"smooth",block:"center"}),Gs(o)},150);else{let o=Cn(e);if(o)o.scrollIntoView({behavior:"smooth",block:"center"}),Gs(o)}}import{SessionContext as Oc}from"#canvas/runtime";import{useCallback as Ho,useContext as zo,useEffect as xi,useMemo as Nc,useState as Yt}from"react";import{createContext as Ws}from"react";var Vt=Ws({activeView:{type:"overview"},setActiveView:()=>{},openFiles:[],closeFile:()=>{},canvasFiles:[]}),Gt=Ws({currentRevision:1,selectedRevision:1,revisions:[],setSelectedRevision:()=>{},isReadOnly:!1,compareRevision:null,setCompareRevision:()=>{},agentWatching:!1});import{jsxDEV as St}from"react/jsx-dev-runtime";var Ol={ts:"#3178c6",tsx:"#3178c6",js:"#e8a32e",jsx:"#4ba0c8",html:"#e34c26",css:"#264de4",scss:"#c69",json:"#7a7568",yaml:"#cb171e",yml:"#cb171e",toml:"#9c4221",rs:"#dea584",go:"#00add8",c:"#6a6a6a",cpp:"#f34b7d",h:"#6a6a6a",py:"#3572a5",rb:"#cc342d",sh:"#5a8c3c",bash:"#5a8c3c",md:"#3573b5",txt:"#6b6560",lock:"#6b6560",gitignore:"#6b6560",svg:"#d9952e",png:"#6a9c2e",jpg:"#6a9c2e",gif:"#6a9c2e"},Nl={ts:"TS",tsx:"TX",js:"JS",jsx:"JX",py:"PY",rs:"RS",go:"GO",rb:"RB",json:"{}",yaml:"YM",yml:"YM",toml:"TM",html:"<>",css:"#",scss:"#",md:"M↓",sh:"$",bash:"$",c:"C",cpp:"C+",h:"H",svg:"◇",png:"▣",jpg:"▣"};function So({name:e,type:t,expanded:n,className:o=""}){if(t==="dir")return St("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",className:`flex-shrink-0 ${o}`,children:n?St("path",{d:"M1.5 3.5h5l1.5 1.5h6.5v8h-13z",style:{fill:"var(--color-folder-fill-active)",stroke:"var(--color-folder-stroke-active)"},strokeWidth:"1"},void 0,!1,void 0,this):St("path",{d:"M1.5 3.5h5l1.5 1.5h6.5v8h-13z",style:{fill:"var(--color-folder-fill)",stroke:"var(--color-folder-stroke)"},strokeWidth:"1"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let r=e.includes(".")?e.split(".").pop().toLowerCase():"",i=Ol[r]||"#6b6560",s=Nl[r];return St("svg",{width:"14",height:"14",viewBox:"0 0 16 16",className:`flex-shrink-0 ${o}`,children:[St("path",{d:"M2 1.5h8l3.5 3.5v9.5a1 1 0 01-1 1H3a1 1 0 01-1-1v-12a1 1 0 011-1z",fill:i,opacity:"0.85"},void 0,!1,void 0,this),St("path",{d:"M10 1.5v2.5a1 1 0 001 1h2.5",fill:"none",stroke:"white",strokeWidth:"0.5",opacity:"0.5"},void 0,!1,void 0,this),s&&St("text",{x:"8",y:"11.5",textAnchor:"middle",fill:"white",fontSize:"5.5",fontFamily:"monospace",fontWeight:"600",children:s},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function _o(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var It=_o();function ti(e){It=e}var Et={exec:()=>null};function Q(e,t=""){let n=typeof e=="string"?e:e.source,o={replace:(r,i)=>{let s=typeof i=="string"?i:i.source;return s=s.replace(Ee.caret,"$1"),n=n.replace(r,s),o},getRegex:()=>new RegExp(n,t)};return o}var Dl=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),Ee={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:(e)=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},Ml=/^(?:[ \t]*(?:\n|$))+/,Ll=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,$l=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Nn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,jl=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Io=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ni=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ri=Q(ni).replace(/bull/g,Io).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Fl=Q(ni).replace(/bull/g,Io).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Co=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Bl=/^[^\n]+/,To=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Hl=Q(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",To).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),zl=Q(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Io).getRegex(),Ar="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Po=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ul=Q("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",Po).replace("tag",Ar).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),oi=Q(Co).replace("hr",Nn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ar).getRegex(),ql=Q(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",oi).getRegex(),Oo={blockquote:ql,code:Ll,def:Hl,fences:$l,heading:jl,hr:Nn,html:Ul,lheading:ri,list:zl,newline:Ml,paragraph:oi,table:Et,text:Bl},Xs=Q("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Nn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ar).getRegex(),Kl={...Oo,lheading:Fl,table:Xs,paragraph:Q(Co).replace("hr",Nn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Xs).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ar).getRegex()},Vl={...Oo,html:Q(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Po).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Et,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Q(Co).replace("hr",Nn).replace("heading",` *#{1,6} *[^
|
|
13
|
+
]`).replace("lheading",ri).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Gl=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Wl=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,si=/^( {2,}|\\)\n(?!\s*$)/,Xl=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Wt=/[\p{P}\p{S}]/u,Rr=/[\s\p{P}\p{S}]/u,No=/[^\s\p{P}\p{S}]/u,Jl=Q(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Rr).getRegex(),ii=/(?!~)[\p{P}\p{S}]/u,Yl=/(?!~)[\s\p{P}\p{S}]/u,Ql=/(?:[^\s\p{P}\p{S}]|~)/u,Zl=Q(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Dl?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ai=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,ec=Q(ai,"u").replace(/punct/g,Wt).getRegex(),tc=Q(ai,"u").replace(/punct/g,ii).getRegex(),li="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",nc=Q(li,"gu").replace(/notPunctSpace/g,No).replace(/punctSpace/g,Rr).replace(/punct/g,Wt).getRegex(),rc=Q(li,"gu").replace(/notPunctSpace/g,Ql).replace(/punctSpace/g,Yl).replace(/punct/g,ii).getRegex(),oc=Q("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,No).replace(/punctSpace/g,Rr).replace(/punct/g,Wt).getRegex(),sc=Q(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Wt).getRegex(),ic="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",ac=Q(ic,"gu").replace(/notPunctSpace/g,No).replace(/punctSpace/g,Rr).replace(/punct/g,Wt).getRegex(),lc=Q(/\\(punct)/,"gu").replace(/punct/g,Wt).getRegex(),cc=Q(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),uc=Q(Po).replace("(?:-->|$)","-->").getRegex(),dc=Q("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",uc).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),br=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,pc=Q(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",br).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ci=Q(/^!?\[(label)\]\[(ref)\]/).replace("label",br).replace("ref",To).getRegex(),ui=Q(/^!?\[(ref)\](?:\[\])?/).replace("ref",To).getRegex(),fc=Q("reflink|nolink(?!\\()","g").replace("reflink",ci).replace("nolink",ui).getRegex(),Js=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Do={_backpedal:Et,anyPunctuation:lc,autolink:cc,blockSkip:Zl,br:si,code:Wl,del:Et,delLDelim:Et,delRDelim:Et,emStrongLDelim:ec,emStrongRDelimAst:nc,emStrongRDelimUnd:oc,escape:Gl,link:pc,nolink:ui,punctuation:Jl,reflink:ci,reflinkSearch:fc,tag:dc,text:Xl,url:Et},mc={...Do,link:Q(/^!?\[(label)\]\((.*?)\)/).replace("label",br).getRegex(),reflink:Q(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",br).getRegex()},Eo={...Do,emStrongRDelimAst:rc,emStrongLDelim:tc,delLDelim:sc,delRDelim:ac,url:Q(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Js).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Q(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Js).getRegex()},gc={...Eo,br:Q(si).replace("{2,}","*").getRegex(),text:Q(Eo.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},xr={normal:Oo,gfm:Kl,pedantic:Vl},Tn={normal:Do,gfm:Eo,breaks:gc,pedantic:mc},hc={"&":"&","<":"<",">":">",'"':""","'":"'"},Ys=(e)=>hc[e];function Ge(e,t){if(t){if(Ee.escapeTest.test(e))return e.replace(Ee.escapeReplace,Ys)}else if(Ee.escapeTestNoEncode.test(e))return e.replace(Ee.escapeReplaceNoEncode,Ys);return e}function Qs(e){try{e=encodeURI(e).replace(Ee.percentDecode,"%")}catch{return null}return e}function Zs(e,t){let n=e.replace(Ee.findPipe,(i,s,l)=>{let a=!1,c=s;for(;--c>=0&&l[c]==="\\";)a=!a;return a?"|":" |"}),o=n.split(Ee.splitPipe),r=0;if(o[0].trim()||o.shift(),o.length>0&&!o.at(-1)?.trim()&&o.pop(),t)if(o.length>t)o.splice(t);else for(;o.length<t;)o.push("");for(;r<o.length;r++)o[r]=o[r].trim().replace(Ee.slashPipe,"|");return o}function Pn(e,t,n){let o=e.length;if(o===0)return"";let r=0;for(;r<o;){let i=e.charAt(o-r-1);if(i===t&&!n)r++;else if(i!==t&&n)r++;else break}return e.slice(0,o-r)}function yc(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let o=0;o<e.length;o++)if(e[o]==="\\")o++;else if(e[o]===t[0])n++;else if(e[o]===t[1]&&(n--,n<0))return o;return n>0?-2:-1}function xc(e,t=0){let n=t,o="";for(let r of e)if(r==="\t"){let i=4-n%4;o+=" ".repeat(i),n+=i}else o+=r,n++;return o}function ei(e,t,n,o,r){let i=t.href,s=t.title||null,l=e[1].replace(r.other.outputLinkReplace,"$1");o.state.inLink=!0;let a={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:i,title:s,text:l,tokens:o.inlineTokens(l)};return o.state.inLink=!1,a}function bc(e,t,n){let o=e.match(n.other.indentCodeCompensation);if(o===null)return t;let r=o[1];return t.split(`
|
|
14
|
+
`).map((i)=>{let s=i.match(n.other.beginningSpace);if(s===null)return i;let[l]=s;return l.length>=r.length?i.slice(r.length):i}).join(`
|
|
15
|
+
`)}var vr=class{options;rules;lexer;constructor(e){this.options=e||It}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:Pn(n,`
|
|
16
|
+
`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],o=bc(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:o}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let o=Pn(n,"#");(this.options.pedantic||!o||this.rules.other.endingSpaceChar.test(o))&&(n=o.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Pn(t[0],`
|
|
17
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=Pn(t[0],`
|
|
18
|
+
`).split(`
|
|
19
|
+
`),o="",r="",i=[];for(;n.length>0;){let s=!1,l=[],a;for(a=0;a<n.length;a++)if(this.rules.other.blockquoteStart.test(n[a]))l.push(n[a]),s=!0;else if(!s)l.push(n[a]);else break;n=n.slice(a);let c=l.join(`
|
|
20
|
+
`),u=c.replace(this.rules.other.blockquoteSetextReplace,`
|
|
21
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");o=o?`${o}
|
|
22
|
+
${c}`:c,r=r?`${r}
|
|
23
|
+
${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,i,!0),this.lexer.state.top=d,n.length===0)break;let f=i.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let p=f,m=p.raw+`
|
|
24
|
+
`+n.join(`
|
|
25
|
+
`),h=this.blockquote(m);i[i.length-1]=h,o=o.substring(0,o.length-p.raw.length)+h.raw,r=r.substring(0,r.length-p.text.length)+h.text;break}else if(f?.type==="list"){let p=f,m=p.raw+`
|
|
26
|
+
`+n.join(`
|
|
27
|
+
`),h=this.list(m);i[i.length-1]=h,o=o.substring(0,o.length-f.raw.length)+h.raw,r=r.substring(0,r.length-p.raw.length)+h.raw,n=m.substring(i.at(-1).raw.length).split(`
|
|
28
|
+
`);continue}}return{type:"blockquote",raw:o,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),o=n.length>1,r={type:"list",raw:"",ordered:o,start:o?+n.slice(0,-1):"",loose:!1,items:[]};n=o?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=o?n:"[*+-]");let i=this.rules.other.listItemRegex(n),s=!1;for(;e;){let a=!1,c="",u="";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let d=xc(t[2].split(`
|
|
29
|
+
`,1)[0],t[1].length),f=e.split(`
|
|
30
|
+
`,1)[0],p=!d.trim(),m=0;if(this.options.pedantic?(m=2,u=d.trimStart()):p?m=t[1].length+1:(m=d.search(this.rules.other.nonSpaceChar),m=m>4?1:m,u=d.slice(m),m+=t[1].length),p&&this.rules.other.blankLine.test(f)&&(c+=f+`
|
|
31
|
+
`,e=e.substring(f.length+1),a=!0),!a){let h=this.rules.other.nextBulletRegex(m),y=this.rules.other.hrRegex(m),A=this.rules.other.fencesBeginRegex(m),b=this.rules.other.headingBeginRegex(m),g=this.rules.other.htmlBeginRegex(m),B=this.rules.other.blockquoteBeginRegex(m);for(;e;){let D=e.split(`
|
|
32
|
+
`,1)[0],H;if(f=D,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),H=f):H=f.replace(this.rules.other.tabCharGlobal," "),A.test(f)||b.test(f)||g.test(f)||B.test(f)||h.test(f)||y.test(f))break;if(H.search(this.rules.other.nonSpaceChar)>=m||!f.trim())u+=`
|
|
33
|
+
`+H.slice(m);else{if(p||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||A.test(d)||b.test(d)||y.test(d))break;u+=`
|
|
34
|
+
`+f}p=!f.trim(),c+=D+`
|
|
35
|
+
`,e=e.substring(D.length+1),d=H.slice(m)}}r.loose||(s?r.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(s=!0)),r.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=c}let l=r.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let a of r.items){if(this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]),a.task){if(a.text=a.text.replace(this.rules.other.listReplaceTask,""),a.tokens[0]?.type==="text"||a.tokens[0]?.type==="paragraph"){a.tokens[0].raw=a.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),a.tokens[0].text=a.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let u=this.lexer.inlineQueue.length-1;u>=0;u--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[u].src)){this.lexer.inlineQueue[u].src=this.lexer.inlineQueue[u].src.replace(this.rules.other.listReplaceTask,"");break}}let c=this.rules.other.listTaskCheckbox.exec(a.raw);if(c){let u={type:"checkbox",raw:c[0]+" ",checked:c[0]!=="[ ]"};a.checked=u.checked,r.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=u.raw+a.tokens[0].raw,a.tokens[0].text=u.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(u)):a.tokens.unshift({type:"paragraph",raw:u.raw,text:u.raw,tokens:[u]}):a.tokens.unshift(u)}}if(!r.loose){let c=a.tokens.filter((d)=>d.type==="space"),u=c.length>0&&c.some((d)=>this.rules.other.anyLine.test(d.raw));r.loose=u}}if(r.loose)for(let a of r.items){a.loose=!0;for(let c of a.tokens)c.type==="text"&&(c.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),o=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:o,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Zs(t[1]),o=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
36
|
+
`):[],i={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===o.length){for(let s of o)this.rules.other.tableAlignRight.test(s)?i.align.push("right"):this.rules.other.tableAlignCenter.test(s)?i.align.push("center"):this.rules.other.tableAlignLeft.test(s)?i.align.push("left"):i.align.push(null);for(let s=0;s<n.length;s++)i.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:i.align[s]});for(let s of r)i.rows.push(Zs(s,i.header.length).map((l,a)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:i.align[a]})));return i}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
|
|
37
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=Pn(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=yc(t[2],"()");if(i===-2)return;if(i>-1){let s=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,s).trim(),t[3]=""}}let o=t[2],r="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(o);i&&(o=i[1],r=i[3])}else r=t[3]?t[3].slice(1,-1):"";return o=o.trim(),this.rules.other.startAngleBracket.test(o)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?o=o.slice(1):o=o.slice(1,-1)),ei(t,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let o=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[o.toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return ei(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let o=this.rules.inline.emStrongLDelim.exec(e);if(!o||!o[1]&&!o[2]&&!o[3]&&!o[4]||o[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(o[1]||o[3])||!n||this.rules.inline.punctuation.exec(n)){let r=[...o[0]].length-1,i,s,l=r,a=0,c=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+r);(o=c.exec(t))!==null;){if(i=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!i)continue;if(s=[...i].length,o[3]||o[4]){l+=s;continue}else if((o[5]||o[6])&&r%3&&!((r+s)%3)){a+=s;continue}if(l-=s,l>0)continue;s=Math.min(s,s+l+a);let u=[...o[0]][0].length,d=e.slice(0,r+o.index+u+s);if(Math.min(r,s)%2){let p=d.slice(1,-1);return{type:"em",raw:d,text:p,tokens:this.lexer.inlineTokens(p)}}let f=d.slice(2,-2);return{type:"strong",raw:d,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),o=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return o&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let o=this.rules.inline.delLDelim.exec(e);if(!o)return;if(!o[1]||!n||this.rules.inline.punctuation.exec(n)){let r=[...o[0]].length-1,i,s,l=r,a=this.rules.inline.delRDelim;for(a.lastIndex=0,t=t.slice(-1*e.length+r);(o=a.exec(t))!==null;){if(i=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!i||(s=[...i].length,s!==r))continue;if(o[3]||o[4]){l+=s;continue}if(l-=s,l>0)continue;s=Math.min(s,s+l);let c=[...o[0]][0].length,u=e.slice(0,r+o.index+c+s),d=u.slice(r,-r);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,o;return t[2]==="@"?(n=t[1],o="mailto:"+n):(n=t[1],o=n),{type:"link",raw:t[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,o;if(t[2]==="@")n=t[0],o="mailto:"+n;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);n=t[0],t[1]==="www."?o="http://"+t[0]:o=t[0]}return{type:"link",raw:t[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},je=class e{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||It,this.options.tokenizer=this.options.tokenizer||new vr,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:Ee,block:xr.normal,inline:Tn.normal};this.options.pedantic?(n.block=xr.pedantic,n.inline=Tn.pedantic):this.options.gfm&&(n.block=xr.gfm,this.options.breaks?n.inline=Tn.breaks:n.inline=Tn.gfm),this.tokenizer.rules=n}static get rules(){return{block:xr,inline:Tn}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(t){t=t.replace(Ee.carriageReturn,`
|
|
38
|
+
`),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let o=this.inlineQueue[n];this.inlineTokens(o.src,o.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],o=!1){for(this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(Ee.tabCharGlobal," ").replace(Ee.spaceLine,""));t;){let r;if(this.options.extensions?.block?.some((s)=>(r=s.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let s=n.at(-1);r.raw.length===1&&s!==void 0?s.raw+=`
|
|
39
|
+
`:n.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let s=n.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
40
|
+
`)?"":`
|
|
41
|
+
`)+r.raw,s.text+=`
|
|
42
|
+
`+r.text,this.inlineQueue.at(-1).src=s.text):n.push(r);continue}if(r=this.tokenizer.fences(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.heading(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.hr(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.blockquote(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.list(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.html(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.def(t)){t=t.substring(r.raw.length);let s=n.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
43
|
+
`)?"":`
|
|
44
|
+
`)+r.raw,s.text+=`
|
|
45
|
+
`+r.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},n.push(r));continue}if(r=this.tokenizer.table(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.lheading(t)){t=t.substring(r.raw.length),n.push(r);continue}let i=t;if(this.options.extensions?.startBlock){let s=1/0,l=t.slice(1),a;this.options.extensions.startBlock.forEach((c)=>{a=c.call({lexer:this},l),typeof a=="number"&&a>=0&&(s=Math.min(s,a))}),s<1/0&&s>=0&&(i=t.substring(0,s+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let s=n.at(-1);o&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
|
|
46
|
+
`)?"":`
|
|
47
|
+
`)+r.raw,s.text+=`
|
|
48
|
+
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):n.push(r),o=i.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let s=n.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
49
|
+
`)?"":`
|
|
50
|
+
`)+r.raw,s.text+=`
|
|
51
|
+
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):n.push(r);continue}if(t){let s="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(s);break}else throw Error(s)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){this.tokenizer.lexer=this;let o=t,r=null;if(this.tokens.links){let a=Object.keys(this.tokens.links);if(a.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(o))!==null;)a.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(o=o.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+o.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(o))!==null;)o=o.slice(0,r.index)+"++"+o.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(o))!==null;)i=r[2]?r[2].length:0,o=o.slice(0,r.index+i)+"["+"a".repeat(r[0].length-i-2)+"]"+o.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);o=this.options.hooks?.emStrongMask?.call({lexer:this},o)??o;let s=!1,l="";for(;t;){s||(l=""),s=!1;let a;if(this.options.extensions?.inline?.some((u)=>(a=u.call({lexer:this},t,n))?(t=t.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.escape(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.tag(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.link(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(a.raw.length);let u=n.at(-1);a.type==="text"&&u?.type==="text"?(u.raw+=a.raw,u.text+=a.text):n.push(a);continue}if(a=this.tokenizer.emStrong(t,o,l)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.codespan(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.br(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.del(t,o,l)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.autolink(t)){t=t.substring(a.raw.length),n.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(t))){t=t.substring(a.raw.length),n.push(a);continue}let c=t;if(this.options.extensions?.startInline){let u=1/0,d=t.slice(1),f;this.options.extensions.startInline.forEach((p)=>{f=p.call({lexer:this},d),typeof f=="number"&&f>=0&&(u=Math.min(u,f))}),u<1/0&&u>=0&&(c=t.substring(0,u+1))}if(a=this.tokenizer.inlineText(c)){t=t.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(l=a.raw.slice(-1)),s=!0;let u=n.at(-1);u?.type==="text"?(u.raw+=a.raw,u.text+=a.text):n.push(a);continue}if(t){let u="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw Error(u)}}return n}},kr=class{options;parser;constructor(e){this.options=e||It}space(e){return""}code({text:e,lang:t,escaped:n}){let o=(t||"").match(Ee.notSpaceStart)?.[0],r=e.replace(Ee.endingNewline,"")+`
|
|
52
|
+
`;return o?'<pre><code class="language-'+Ge(o)+'">'+(n?r:Ge(r,!0))+`</code></pre>
|
|
53
|
+
`:"<pre><code>"+(n?r:Ge(r,!0))+`</code></pre>
|
|
54
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
55
|
+
${this.parser.parse(e)}</blockquote>
|
|
56
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
57
|
+
`}hr(e){return`<hr>
|
|
58
|
+
`}list(e){let{ordered:t,start:n}=e,o="";for(let s=0;s<e.items.length;s++){let l=e.items[s];o+=this.listitem(l)}let r=t?"ol":"ul",i=t&&n!==1?' start="'+n+'"':"";return"<"+r+i+`>
|
|
59
|
+
`+o+"</"+r+`>
|
|
60
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
61
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
62
|
+
`}table(e){let t="",n="";for(let r=0;r<e.header.length;r++)n+=this.tablecell(e.header[r]);t+=this.tablerow({text:n});let o="";for(let r=0;r<e.rows.length;r++){let i=e.rows[r];n="";for(let s=0;s<i.length;s++)n+=this.tablecell(i[s]);o+=this.tablerow({text:n})}return o&&(o=`<tbody>${o}</tbody>`),`<table>
|
|
63
|
+
<thead>
|
|
64
|
+
`+t+`</thead>
|
|
65
|
+
`+o+`</table>
|
|
66
|
+
`}tablerow({text:e}){return`<tr>
|
|
67
|
+
${e}</tr>
|
|
68
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
69
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Ge(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let o=this.parser.parseInline(n),r=Qs(e);if(r===null)return o;e=r;let i='<a href="'+e+'"';return t&&(i+=' title="'+Ge(t)+'"'),i+=">"+o+"</a>",i}image({href:e,title:t,text:n,tokens:o}){o&&(n=this.parser.parseInline(o,this.parser.textRenderer));let r=Qs(e);if(r===null)return Ge(n);e=r;let i=`<img src="${e}" alt="${Ge(n)}"`;return t&&(i+=` title="${Ge(t)}"`),i+=">",i}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):("escaped"in e)&&e.escaped?e.text:Ge(e.text)}},Mo=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Fe=class e{options;renderer;textRenderer;constructor(t){this.options=t||It,this.options.renderer=this.options.renderer||new kr,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Mo}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(t){this.renderer.parser=this;let n="";for(let o=0;o<t.length;o++){let r=t[o];if(this.options.extensions?.renderers?.[r.type]){let s=r,l=this.options.extensions.renderers[s.type].call({parser:this},s);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(s.type)){n+=l||"";continue}}let i=r;switch(i.type){case"space":{n+=this.renderer.space(i);break}case"hr":{n+=this.renderer.hr(i);break}case"heading":{n+=this.renderer.heading(i);break}case"code":{n+=this.renderer.code(i);break}case"table":{n+=this.renderer.table(i);break}case"blockquote":{n+=this.renderer.blockquote(i);break}case"list":{n+=this.renderer.list(i);break}case"checkbox":{n+=this.renderer.checkbox(i);break}case"html":{n+=this.renderer.html(i);break}case"def":{n+=this.renderer.def(i);break}case"paragraph":{n+=this.renderer.paragraph(i);break}case"text":{n+=this.renderer.text(i);break}default:{let s='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw Error(s)}}}return n}parseInline(t,n=this.renderer){this.renderer.parser=this;let o="";for(let r=0;r<t.length;r++){let i=t[r];if(this.options.extensions?.renderers?.[i.type]){let l=this.options.extensions.renderers[i.type].call({parser:this},i);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){o+=l||"";continue}}let s=i;switch(s.type){case"escape":{o+=n.text(s);break}case"html":{o+=n.html(s);break}case"link":{o+=n.link(s);break}case"image":{o+=n.image(s);break}case"checkbox":{o+=n.checkbox(s);break}case"strong":{o+=n.strong(s);break}case"em":{o+=n.em(s);break}case"codespan":{o+=n.codespan(s);break}case"br":{o+=n.br(s);break}case"del":{o+=n.del(s);break}case"text":{o+=n.text(s);break}default:{let l='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw Error(l)}}}return o}},On=class{options;block;constructor(e){this.options=e||It}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?je.lex:je.lexInline}provideParser(e=this.block){return e?Fe.parse:Fe.parseInline}},Lo=class{defaults=_o();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Fe;Renderer=kr;TextRenderer=Mo;Lexer=je;Tokenizer=vr;Hooks=On;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let o of e)switch(n=n.concat(t.call(this,o)),o.type){case"table":{let r=o;for(let i of r.header)n=n.concat(this.walkTokens(i.tokens,t));for(let i of r.rows)for(let s of i)n=n.concat(this.walkTokens(s.tokens,t));break}case"list":{let r=o;n=n.concat(this.walkTokens(r.items,t));break}default:{let r=o;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach((i)=>{let s=r[i].flat(1/0);n=n.concat(this.walkTokens(s,t))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((n)=>{let o={...n};if(o.async=this.defaults.async||o.async||!1,n.extensions&&(n.extensions.forEach((r)=>{if(!r.name)throw Error("extension name required");if("renderer"in r){let i=t.renderers[r.name];i?t.renderers[r.name]=function(...s){let l=r.renderer.apply(this,s);return l===!1&&(l=i.apply(this,s)),l}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw Error("extension level must be 'block' or 'inline'");let i=t[r.level];i?i.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),o.extensions=t),n.renderer){let r=this.defaults.renderer||new kr(this.defaults);for(let i in n.renderer){if(!(i in r))throw Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let s=i,l=n.renderer[s],a=r[s];r[s]=(...c)=>{let u=l.apply(r,c);return u===!1&&(u=a.apply(r,c)),u||""}}o.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new vr(this.defaults);for(let i in n.tokenizer){if(!(i in r))throw Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let s=i,l=n.tokenizer[s],a=r[s];r[s]=(...c)=>{let u=l.apply(r,c);return u===!1&&(u=a.apply(r,c)),u}}o.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new On;for(let i in n.hooks){if(!(i in r))throw Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let s=i,l=n.hooks[s],a=r[s];On.passThroughHooks.has(i)?r[s]=(c)=>{if(this.defaults.async&&On.passThroughHooksRespectAsync.has(i))return(async()=>{let d=await l.call(r,c);return a.call(r,d)})();let u=l.call(r,c);return a.call(r,u)}:r[s]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await l.apply(r,c);return d===!1&&(d=await a.apply(r,c)),d})();let u=l.apply(r,c);return u===!1&&(u=a.apply(r,c)),u}}o.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,i=n.walkTokens;o.walkTokens=function(s){let l=[];return l.push(i.call(this,s)),r&&(l=l.concat(r.call(this,s))),l}}this.defaults={...this.defaults,...o}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return je.lex(e,t??this.defaults)}parser(e,t){return Fe.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let o={...n},r={...this.defaults,...o},i=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&o.async===!1)return i(Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return i(Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return i(Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let s=r.hooks?await r.hooks.preprocess(t):t,l=await(r.hooks?await r.hooks.provideLexer(e):e?je.lex:je.lexInline)(s,r),a=r.hooks?await r.hooks.processAllTokens(l):l;r.walkTokens&&await Promise.all(this.walkTokens(a,r.walkTokens));let c=await(r.hooks?await r.hooks.provideParser(e):e?Fe.parse:Fe.parseInline)(a,r);return r.hooks?await r.hooks.postprocess(c):c})().catch(i);try{r.hooks&&(t=r.hooks.preprocess(t));let s=(r.hooks?r.hooks.provideLexer(e):e?je.lex:je.lexInline)(t,r);r.hooks&&(s=r.hooks.processAllTokens(s)),r.walkTokens&&this.walkTokens(s,r.walkTokens);let l=(r.hooks?r.hooks.provideParser(e):e?Fe.parse:Fe.parseInline)(s,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(s){return i(s)}}}onError(e,t){return(n)=>{if(n.message+=`
|
|
70
|
+
Please report this to https://github.com/markedjs/marked.`,e){let o="<p>An error occurred:</p><pre>"+Ge(n.message+"",!0)+"</pre>";return t?Promise.resolve(o):o}if(t)return Promise.reject(n);throw n}}},_t=new Lo;function te(e,t){return _t.parse(e,t)}te.options=te.setOptions=function(e){return _t.setOptions(e),te.defaults=_t.defaults,ti(te.defaults),te};te.getDefaults=_o;te.defaults=It;te.use=function(...e){return _t.use(...e),te.defaults=_t.defaults,ti(te.defaults),te};te.walkTokens=function(e,t){return _t.walkTokens(e,t)};te.parseInline=_t.parseInline;te.Parser=Fe;te.parser=Fe.parse;te.Renderer=kr;te.TextRenderer=Mo;te.Lexer=je;te.lexer=je.lex;te.Tokenizer=vr;te.Hooks=On;te.parse=te;var{options:Rm,setOptions:wm,use:Sm,walkTokens:Em,parseInline:_m}=te;var Im=Fe.parse,Cm=je.lex;import{useEffect as di,useMemo as $o,useRef as vc,useState as Dn}from"react";import{jsxDEV as ge}from"react/jsx-dev-runtime";function jo({open:e,onClose:t,onSubmit:n,includedRemoteIds:o,onToggleRemoteId:r}){let{annotations:i,generalNote:s,submittableResponses:l,feedbackEntries:a}=wt(),c=Ie().threads!==null,[u,d]=Dn(""),[f,p]=Dn(!1),[m,h]=Dn(!1),[y,A]=Dn(null),b=vc(null),[g,B]=Dn(!1),D=$o(()=>i.filter((M)=>M.source==="remote"),[i]);if(e&&!g)p(!1),h(!1),A(null);if(!e&&g)p(!1),h(!1),A(null);if(e!==g)B(e);let H=$o(()=>Ht(i,s,l,a,o,{annotationIds:c}),[i,s,l,a,o,c]),T=f?u:H;if(di(()=>{if(e&&m&&b.current)b.current.focus()},[e,m]),di(()=>{if(!e)return;let M=(q)=>{if(q.key==="Escape")t()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[e,t]),!e)return null;let U=T.trim().length>0;return ge("div",{className:"fixed inset-0 z-50 bg-black/50 backdrop-blur-sm flex items-center justify-center p-8",onClick:t,children:ge("div",{className:"bg-bg-surface border border-border-medium rounded-xl shadow-lg w-full max-w-2xl flex flex-col",style:{height:"80vh"},onClick:(M)=>M.stopPropagation(),children:[ge("div",{className:"flex items-center justify-between px-5 py-3 border-b border-border-subtle flex-shrink-0",children:[ge("div",{className:"flex items-center gap-3",children:[ge("span",{className:"text-[13px] font-medium text-text-primary font-body",children:"Response preview"},void 0,!1,void 0,this),f&&ge("button",{onClick:()=>{p(!1),h(!1)},className:"text-[11px] text-text-tertiary hover:text-text-secondary font-body",children:"Reset"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),ge("div",{className:"flex items-center gap-2",children:[ge("div",{className:"flex items-center bg-bg-base rounded-md p-0.5",children:[ge("button",{onClick:()=>h(!1),className:`px-2.5 py-1 rounded text-[11px] font-body font-medium transition-colors ${!m?"bg-bg-elevated text-text-primary shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Preview"},void 0,!1,void 0,this),ge("button",{onClick:()=>h(!0),className:`px-2.5 py-1 rounded text-[11px] font-body font-medium transition-colors ${m?"bg-bg-elevated text-text-primary shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Edit"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),ge("button",{onClick:t,className:"text-text-tertiary hover:text-text-secondary w-7 h-7 flex items-center justify-center rounded-md hover:bg-border-subtle transition-colors",children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),m?ge("textarea",{ref:b,value:T,onChange:(M)=>{d(M.currentTarget.value),p(!0)},className:"flex-1 w-full bg-bg-base p-5 text-[13px] font-mono text-text-code resize-none focus:outline-none leading-relaxed placeholder:text-text-disabled",placeholder:"Your feedback will appear here..."},void 0,!1,void 0,this):ge("div",{className:"flex-1 overflow-y-auto p-5",children:ge(Jt,{text:T},void 0,!1,void 0,this)},void 0,!1,void 0,this),D.length>0&&ge("div",{className:"px-5 py-2 border-t border-border-subtle flex-shrink-0",children:ge("span",{className:"text-[12px] text-text-secondary font-body",children:["Reviewer feedback: ",o.size,"/",D.length," included"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),y&&ge("div",{className:"px-5 py-2 text-[12px] text-accent-red font-body border-t border-border-subtle flex-shrink-0 flex items-center justify-between gap-2",children:[ge("span",{children:y},void 0,!1,void 0,this),ge("button",{onClick:()=>{A(null),n(T)},className:"text-[11px] text-text-tertiary hover:text-text-secondary font-body whitespace-nowrap underline",children:"Submit anyway"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),ge("div",{className:"flex justify-end gap-2 px-5 py-3 border-t border-border-subtle flex-shrink-0",children:[ge("button",{onClick:t,className:"px-4 py-2 rounded-lg text-[13px] font-body text-text-tertiary hover:text-text-secondary transition-colors",children:"Cancel"},void 0,!1,void 0,this),ge("button",{onClick:()=>{let M=zt(l,a);if(M.length>0){A(`Please answer: ${M.join(", ")}`);return}A(null),n(T)},disabled:!U,className:`px-6 py-2 rounded-lg font-body text-[13px] font-medium transition-all ${U?"bg-btn-primary text-btn-primary-text hover:opacity-90":"bg-bg-input text-text-disabled cursor-default"}`,children:"Submit feedback"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var kc=/!\[([^\]]*)\]\((\/tmp\/agent-canvas\/uploads\/([^)]+))\)/g;function Ac(e){return e.replace(kc,(t,n,o,r)=>``)}var mi={"&":"&","<":"<",">":">",'"':""","'":"'"},Xt=(e)=>e.replace(/[&<>"']/g,(t)=>mi[t]??t),Rc=(e)=>e.replace(/&(?!#?\w+;)|[<>"']/g,(t)=>mi[t]??t),pi=(e)=>/^(?:https?|mailto):/i.test(e)||!/^[^/?#]*:/.test(e),fi=(e)=>e?` title="${Xt(e)}"`:"",wc=new Lo({renderer:{html:({text:e})=>Xt(e),text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):Rc(e.text)},link(e){let t=this.parser.parseInline(e.tokens);return pi(e.href)?`<a href="${Xt(e.href)}"${fi(e.title)}>${t}</a>`:t},image:(e)=>pi(e.href)?`<img src="${Xt(e.href)}" alt="${Xt(e.text)}"${fi(e.title)}>`:Xt(e.text)}});function gi(e){return wc.parse(e,{async:!1})}function Jt({text:e}){let t=$o(()=>gi(Ac(e)),[e]);return ge("div",{className:"prose-canvas font-body text-body text-text-primary leading-relaxed",dangerouslySetInnerHTML:{__html:t}},void 0,!1,void 0,this)}import{useId as Sc,useState as Fo,useSyncExternalStore as Ec}from"react";import{jsxDEV as ye}from"react/jsx-dev-runtime";var _c=[],Ic=()=>()=>{},Cc=()=>_c;function Tc(){let e=Ie().threads;return Ec(e?.subscribe??Ic,e?.current??Cc)}var Pc={open:"Answered",queued:"Reply sent",working:"Agent is on it",resolved:"Resolved"};function Bo(){let e=Ie().threads,t=Tc(),[n,o]=Fo(()=>new Map),r=(l,a)=>o((c)=>new Map(c).set(l,a));if(e===null||t.length===0)return null;let i=t.filter((l)=>l.state!=="resolved"),s=t.filter((l)=>l.state==="resolved");return ye("section",{"aria-label":"Threads",className:"px-3 pt-1 pb-3 border-b border-border-subtle",children:[ye("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary font-body px-1 mb-1",children:"Threads"},void 0,!1,void 0,this),i.map((l)=>ye(hi,{thread:l,store:e,draft:n.get(l.id)??"",onDraft:(a)=>r(l.id,a)},l.id,!1,void 0,this)),s.length>0&&ye("details",{className:"mt-1",children:[ye("summary",{className:"text-[11px] text-text-tertiary font-body px-1 cursor-pointer",children:["Resolved (",s.length,")"]},void 0,!0,void 0,this),s.map((l)=>ye(hi,{thread:l,store:e,draft:n.get(l.id)??"",onDraft:(a)=>r(l.id,a)},l.id,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function hi({thread:e,store:t,draft:n,onDraft:o}){let r=Sc(),[i,s]=Fo(null),[l,a]=Fo(!1),c=async(f)=>{a(!0),s(null);try{await f()}catch(p){s(p instanceof Error?p.message:String(p))}finally{a(!1)}},u=()=>c(async()=>{await t.reply(e.id,n.trim()),o("")}),d=e.filePath===ut?"Agent response":e.filePath??e.canvasFile?.replace(/\.jsx$/,"");return ye("article",{className:"rounded-lg border border-border-subtle bg-bg-elevated px-3 py-2 mt-2","data-thread-id":e.id,children:[ye("div",{className:"flex items-center justify-between gap-2 text-[11px] text-text-tertiary font-body",children:[ye("span",{className:"truncate",children:[d?`${d} · `:"","Round ",e.revision]},void 0,!0,void 0,this),ye("span",{children:Pc[e.state]},void 0,!1,void 0,this)]},void 0,!0,void 0,this),e.snippet.trim()&&ye("blockquote",{className:"mt-1 border-l-2 border-border-medium pl-2 text-[12px] text-text-secondary font-body line-clamp-3",children:e.snippet},void 0,!1,void 0,this),ye("ol",{className:"mt-2 space-y-2",children:e.comments.map((f)=>ye("li",{className:"text-[13px] font-body",children:[ye("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary",children:f.author==="agent"?"Agent":"You"},void 0,!1,void 0,this),f.author==="agent"?ye(Jt,{text:f.body},void 0,!1,void 0,this):ye("p",{className:"whitespace-pre-wrap text-text-primary",children:f.body},void 0,!1,void 0,this)]},f.id,!0,void 0,this))},void 0,!1,void 0,this),ye("label",{className:"sr-only",htmlFor:r,children:"Reply"},void 0,!1,void 0,this),ye("textarea",{id:r,value:n,onInput:(f)=>o(f.currentTarget.value),placeholder:"Reply to the agent",rows:2,className:"mt-2 w-full rounded-md bg-bg-input px-2 py-1.5 text-[13px] font-body text-text-primary"},void 0,!1,void 0,this),i&&ye("p",{role:"alert",className:"text-[12px] text-accent-red font-body",children:i},void 0,!1,void 0,this),ye("div",{className:"mt-1 flex justify-end gap-2",children:[ye("button",{type:"button",disabled:l,onClick:()=>c(()=>t.setResolved(e.id,e.state!=="resolved")),className:"px-2.5 py-1 rounded text-[12px] font-body text-text-secondary hover:text-text-primary",children:e.state==="resolved"?"Reopen":"Resolve"},void 0,!1,void 0,this),ye("button",{type:"button",disabled:l||n.trim()==="",onClick:u,className:"px-2.5 py-1 rounded text-[12px] font-body font-medium bg-btn-primary text-btn-primary-text disabled:opacity-50",children:"Send"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as C,Fragment as wr}from"react/jsx-dev-runtime";function Sr({onSubmit:e,collapseButton:t}){let{isReadOnly:n,selectedRevision:o,currentRevision:r,revisions:i,agentWatching:s}=zo(Gt),l=zo(Oc),a=i.find((f)=>f.revision===o),c=n&&o===r,u=!!a?.feedbackConsumed,d=a?.label||`Round ${o}`;if(n)return C(Mc,{sessionId:l,revision:o,label:d,waitingForUpdate:c,feedbackConsumed:u,agentWatching:s,collapseButton:t},void 0,!1,void 0,this);return C($c,{onSubmit:e,agentWatching:s,collapseButton:t},void 0,!1,void 0,this)}function Dc({sessionId:e,revision:t,label:n,waitingForUpdate:o,feedbackConsumed:r,agentWatching:i,collapseButton:s}){let a=Ie().isShared;return C("div",{className:"flex flex-col h-full",children:[C("div",{className:"px-4 py-3 flex items-center justify-between flex-shrink-0",children:[C("span",{className:"text-[11px] font-medium uppercase tracking-widest text-text-tertiary font-body",children:o?"Feedback sent":`Feedback — ${n}`},void 0,!1,void 0,this),s]},void 0,!0,void 0,this),o&&!a&&C(bi,{feedbackConsumed:r,agentWatching:i},void 0,!1,void 0,this),C(vi,{sessionId:e,revision:t},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function bi({feedbackConsumed:e,agentWatching:t}){if(e)return C("div",{className:"mx-4 mb-3 px-3 py-2.5 rounded-lg bg-accent-green-muted flex items-center gap-2 flex-shrink-0",children:[C("span",{className:"w-2 h-2 rounded-full bg-accent-green animate-pulse"},void 0,!1,void 0,this),C("span",{className:"text-[12px] font-body text-accent-green",children:"Feedback received — waiting for next revision..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(t)return C("div",{className:"mx-4 mb-3 px-3 py-2.5 rounded-lg bg-accent-blue-muted flex items-center gap-2 flex-shrink-0",children:[C("span",{className:"w-2 h-2 rounded-full bg-accent-blue animate-pulse"},void 0,!1,void 0,this),C("span",{className:"text-[12px] font-body text-accent-blue",children:"Waiting for agent to pick up feedback..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return C("div",{className:"mx-4 mb-3 px-3 py-2.5 rounded-lg bg-accent-amber-muted flex items-center gap-2 flex-shrink-0",children:[C("span",{className:"w-2 h-2 rounded-full bg-accent-amber"},void 0,!1,void 0,this),C("span",{className:"text-[12px] font-body text-accent-amber",children:"Agent disconnected — tell Claude to check feedback"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Mc({sessionId:e,revision:t,label:n,waitingForUpdate:o,feedbackConsumed:r,agentWatching:i,collapseButton:s}){let{annotations:l,generalNote:a}=wt(),c=l.length>0||a.trim().length>0,[u,d]=Yt("feedback");if(!c)return C(Dc,{sessionId:e,revision:t,label:n,waitingForUpdate:o,feedbackConsumed:r,agentWatching:i,collapseButton:s},void 0,!1,void 0,this);return C("div",{className:"flex flex-col h-full",children:[C("div",{className:"px-4 py-3 flex items-center justify-between flex-shrink-0",children:[C("div",{className:"flex items-center gap-1 bg-bg-input rounded-md p-0.5",children:[C("button",{onClick:()=>d("feedback"),className:`px-2.5 py-1 rounded text-[11px] font-medium font-body transition-colors ${u==="feedback"?"bg-bg-elevated text-text-primary shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:"Feedback"},void 0,!1,void 0,this),C("button",{onClick:()=>d("annotations"),className:`px-2.5 py-1 rounded text-[11px] font-medium font-body transition-colors flex items-center gap-1.5 ${u==="annotations"?"bg-bg-elevated text-text-primary shadow-sm":"text-text-tertiary hover:text-text-secondary"}`,children:["Annotations",C("span",{className:"inline-flex items-center justify-center min-w-[16px] h-[16px] px-1 rounded-full bg-border-subtle text-[10px] font-medium",children:l.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),s]},void 0,!0,void 0,this),o&&C(bi,{feedbackConsumed:r,agentWatching:i},void 0,!1,void 0,this),u==="feedback"?C(vi,{sessionId:e,revision:t},void 0,!1,void 0,this):C(wr,{children:[C("div",{className:"flex-1 overflow-y-auto",children:C(ki,{annotations:l,readOnly:!0},void 0,!1,void 0,this)},void 0,!1,void 0,this),a.trim()&&C("div",{className:"border-t border-border-subtle px-4 py-3 flex-shrink-0",children:C("div",{className:"text-[13px] font-body text-text-primary leading-relaxed",children:a},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function vi({sessionId:e,revision:t}){let n=Ie(),[o,r]=Yt(null),[i,s]=Yt(!0);return xi(()=>{if(s(!0),!n.fsAvailable){r(null),s(!1);return}fetch(`/api/session/${e}/revision/${t}/feedback`).then((l)=>l.json()).then((l)=>{r(Us.parse(l).feedback||null),s(!1)}).catch(()=>{r(null),s(!1)})},[e,t]),C("div",{className:"flex-1 overflow-y-auto px-4",children:[C("div",{className:"-mx-4",children:C(Bo,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i?C("p",{className:"text-[12px] text-text-tertiary font-body py-4",children:"Loading..."},void 0,!1,void 0,this):o?C(Jt,{text:o},void 0,!1,void 0,this):C("p",{className:"text-[12px] text-text-tertiary font-body py-4",children:"No feedback was submitted for this revision."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Lc(e){let t=e.filter((s)=>s.filePath===ut),n=e.filter((s)=>!s.filePath),o=e.filter((s)=>bt(s)!==void 0),r={};for(let s of o){let l=bt(s);if(!l)continue;let a=r[l];if(a)a.push(s);else r[l]=[s]}let i=[t,n,o].filter((s)=>s.length>0).length>1;return{response:t,plan:n,fileGroups:r,hasMultipleGroups:i}}function yi({children:e}){return C("div",{className:"text-[10px] uppercase tracking-widest text-text-tertiary font-body px-3 mb-1 mt-1",children:e},void 0,!1,void 0,this)}function ki({annotations:e,readOnly:t,includedRemoteIds:n,onToggleRemoteId:o}){let{setActiveView:r}=zo(Vt),{response:i,plan:s,fileGroups:l,hasMultipleGroups:a}=Lc(e),c=Ho((f)=>{let p=bt(f);if(!p)return;r({type:"file",path:p}),setTimeout(()=>{let m=Cn(f);if(m)m.scrollIntoView({behavior:"smooth",block:"center"})},150)},[r]),u=Ho((f)=>wo(f,r),[r]),d={readOnly:t,onSelect:c,onReveal:u,includedRemoteIds:n,onToggleRemoteId:o};return C(wr,{children:[i.length>0&&C(wr,{children:[a&&C(yi,{children:"Agent Response"},void 0,!1,void 0,this),C(En,{annotations:i,...d},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s.length>0&&C(wr,{children:[a&&C(yi,{children:"Canvas"},void 0,!1,void 0,this),C(En,{annotations:s,...d},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Object.entries(l).map(([f,p])=>C("div",{children:[C("button",{onClick:()=>r({type:"file",path:f}),className:"flex items-center gap-1.5 text-[10px] uppercase tracking-widest text-text-tertiary hover:text-text-secondary font-body px-3 pt-3 pb-1 truncate transition-colors w-full text-left",title:f,children:[C(So,{name:f.split("/").pop()||f,type:"file"},void 0,!1,void 0,this),C("span",{className:"truncate",children:f},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C(En,{annotations:p,...d},void 0,!1,void 0,this)]},f,!0,void 0,this))]},void 0,!0,void 0,this)}function $c({onSubmit:e,agentWatching:t,collapseButton:n}){let o=Ie(),[r,i]=Yt(!1),{annotations:s,generalNote:l,submittableResponses:a,feedbackEntries:c}=wt(),u=Nc(()=>s.filter((H)=>H.source==="remote"),[s]),[d,f]=Yt(()=>new Set);xi(()=>{if(u.length===0)return;f((H)=>{let T=new Set(H);for(let U of u)T.add(U.id);return T.size===H.size?H:T})},[u]);let p=Ho((H)=>{f((T)=>{let U=new Set(T);if(U.has(H))U.delete(H);else U.add(H);return U})},[]),m=Array.from(a.values()).some(In),h=c.size>0,y=s.length>0||l.trim().length>0||m||h,[A,b]=Yt(null),g=o.threads!==null,B=(H)=>{let T=g?s.filter((U)=>U.source!=="remote").map(jc):[];e(H,T,Ls(a))},D=()=>{B(Ht(s,l,a,c,d,{annotationIds:g}))};return C("div",{className:"flex flex-col h-full",children:[C("div",{className:"px-4 py-3 flex items-center justify-between flex-shrink-0",children:[C("span",{className:"text-[11px] font-medium uppercase tracking-widest text-text-tertiary font-body flex items-center gap-2",children:["Annotations",s.length>0&&C("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-border-subtle text-[10px] font-medium text-text-secondary",children:s.length},void 0,!1,void 0,this),!o.isShared&&C("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${t?"bg-accent-green":"bg-accent-amber"}`,title:t?"Agent connected":"Agent disconnected"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),n]},void 0,!0,void 0,this),C("div",{className:"flex-1 overflow-y-auto",children:[C(Bo,{},void 0,!1,void 0,this),s.length===0&&C("p",{className:"text-[12px] text-text-tertiary px-3 py-4 leading-relaxed font-body",children:"Select text in the canvas or in files to add annotations."},void 0,!1,void 0,this),C(ki,{annotations:s,includedRemoteIds:d,onToggleRemoteId:p},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C(lo,{hasContent:y,onSubmit:()=>{let H=zt(a,c);if(H.length>0){b(`Please answer: ${H.join(", ")}`);return}b(null),D()},onSubmitEmpty:()=>e("No feedback — looks good.",[],[]),notice:A&&C("div",{className:"px-4 py-2 text-[12px] text-accent-red font-body border-t border-border-subtle flex-shrink-0 flex items-center justify-between gap-2",children:[C("span",{children:A},void 0,!1,void 0,this),C("button",{onClick:()=>{b(null),D()},className:"text-[11px] text-text-tertiary hover:text-text-secondary font-body whitespace-nowrap underline",children:"Submit anyway"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),secondaryAction:C("button",{onClick:()=>i(!0),className:"flex-1 py-2 rounded-lg font-body text-[13px] font-medium transition-all bg-border-subtle text-text-secondary hover:bg-border-medium hover:text-text-primary",children:"Preview"},void 0,!1,void 0,this)},void 0,!1,void 0,this),C(jo,{open:r,onClose:()=>i(!1),onSubmit:B,includedRemoteIds:d,onToggleRemoteId:p},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function jc(e){return{id:e.id,snippet:e.snippet,note:e.note,canvasFile:e.canvasFile,filePath:e.filePath}}import{useFeedback as cy}from"#canvas/runtime";import fg from"react";te.setOptions({gfm:!0,breaks:!1});import{useAnnotations as kg,useResponseRegistration as Ag}from"#canvas/runtime";import{useEffect as wg,useMemo as Sg,useRef as Eg,useState as _g}from"react";import{useEffect as Ng,useRef as Dg}from"react";import{ActiveViewCtx as zg,SessionContext as Ug}from"#canvas/runtime";import{useContext as Kg,useEffect as Vg,useRef as Gg,useState as Wg}from"react";import{SessionContext as Zg}from"#canvas/runtime";import{useContext as th,useState as nh}from"react";import{useMemo as ah}from"react";te.setOptions({gfm:!0,breaks:!1});import{useAnnotations as dh,useCanvasFile as ph}from"#canvas/runtime";import{useCallback as hh,useEffect as yh,useRef as xh,useState as bh}from"react";import kh from"react-dom";import{useState as Ch}from"react";import{useAnnotations as Lh,useResponseRegistration as $h}from"#canvas/runtime";import{useRef as Bh,useState as Hh}from"react";import{CanvasFileCtx as Hc,SessionContext as zc}from"#canvas/runtime";import Er,{useContext as wi,useEffect as mt,useMemo as Mn,useRef as Uc,useState as We}from"react";import{createPortal as qc}from"react-dom";import{createContext as Bc}from"react";var qo=Bc(()=>{});import{jsxDEV as le,Fragment as Wc}from"react/jsx-dev-runtime";class Si extends Er.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.reportError({revision:this.props.revision,filename:this.props.filename,message:e.message,...e.stack?{stack:e.stack}:{},...t.componentStack?{componentStack:t.componentStack}:{}})}render(){if(!this.state.error)return this.props.children;return le(Ei,{message:this.state.error.message},void 0,!1,void 0,this)}}function Ei({message:e}){return le("div",{className:"bg-accent-red-muted rounded-lg p-5",children:[le("h3",{className:"font-body font-semibold text-accent-red mb-2",children:"Canvas render failed"},void 0,!1,void 0,this),le("pre",{className:"text-code font-mono text-text-secondary whitespace-pre-wrap",children:e},void 0,!1,void 0,this),le("p",{className:"text-meta font-body text-text-tertiary mt-3",children:"The error was sent back to the canvas author."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function _r({revision:e,filename:t}){let n=wi(zc),o=Ie(),r=wi(qo),[i,s]=We(null),[l,a]=We(null),[c,u]=We(!0),d=Uc(null),{annotations:f,addAnnotationWithId:p,removeAnnotation:m,updateAnnotation:h,addAnnotationImage:y,removeAnnotationImage:A,activeAnnotationId:b,setActiveAnnotationId:g,registerCanvasRendered:B}=wt(),D=Mn(()=>f.filter((P)=>!P.filePath&&(!P.canvasFile||P.canvasFile===t)),[f,t]),[H,T]=We(null),[U,M]=We(null),[q,oe]=We(null),[ne,ie]=We(null),[ke,G]=We(!1);mt(()=>{u(!0),a(null),ie(null),o.loadCanvasModule(t,e).then((P)=>{s(()=>P.default),u(!1)}).catch((P)=>{let L=P instanceof Error?P:Error(String(P));a(L.message),u(!1),r({revision:e,filename:t,message:L.message,...L.stack?{stack:L.stack}:{}})})},[n,e,t,r]),mt(()=>{if(i)B(t)},[i,t,B]);let re=document.getElementById("plan-scroll-container"),{popovers:Z,isPopoverOpen:ue}=yo({containerRef:d,restoreKey:i,restoreAnnotations:D,extractContext:(P)=>Hr(P,d.current),canvasFile:t,scrollContainer:re}),{popovers:ee,isDrawing:se,isPopoverOpen:fe}=go({containerRef:d,restoreKey:i,canvasFile:t,scrollContainer:re}),I=ue||fe,N=Mn(()=>{let P=new Map;for(let L of D)if(L.snippet.startsWith("["))P.set(L.snippet,L.id);return P},[D]);mt(()=>{let P=d.current;if(!P)return;let L=(k)=>{if(q||I||se)return;let j=k.target;if(j.closest("[data-block-comment-btn]"))return;G(!1);let W=j.closest(Ot);if(W&&P.contains(W)){let Ne=Ct(P).indexOf(W);ie(Ne>=0?Ne:null)}else ie(null);let de=j.closest(it);if(de&&P.contains(de)){M(de);let be=ze(de),Ne=be?N.get(be):void 0;if(Ne&&Ne!==b)g(Ne)}else M(null)},w=(k)=>{if(q||I)return;if(k.relatedTarget?.closest("[data-block-comment-btn]"))return;M(null),g(null)};return P.addEventListener("mousemove",L),P.addEventListener("mouseleave",w),()=>{P.removeEventListener("mousemove",L),P.removeEventListener("mouseleave",w)}},[i,q,I,se,N,b]),mt(()=>{let P=(L)=>{let w=L.target.tagName;if(w==="INPUT"||w==="TEXTAREA"||L.target.isContentEditable)return;if(q||I)return;let k=d.current;if(!k)return;if(L.key==="ArrowDown"){L.preventDefault(),G(!0);let j=Ct(k);if(j.length===0)return;ie((W)=>{if(W===null)return 0;return Math.min(W+1,j.length-1)})}else if(L.key==="ArrowUp"){L.preventDefault(),G(!0);let j=Ct(k);if(j.length===0)return;ie((W)=>{if(W===null)return j.length-1;return Math.max(W-1,0)})}else if(L.key==="a"||L.key==="A"){if(ne===null||!k)return;let W=Ct(k)[ne];if(!W)return;if(!W.matches(it))return;L.preventDefault();let de=ze(W);if(!de)return;let be=N.get(de);if(be)g(be),oe({anchorEl:W,snippet:de,annId:be});else oe({anchorEl:W,snippet:de})}else if(L.key===" "||L.key==="Enter"){if(ne===null)return;let W=Ct(k)[ne];if(!W)return;let de=W.getAttribute("data-md");if(de==="choice-option"||de==="multichoice-option")L.preventDefault(),W.dispatchEvent(new CustomEvent("kb-select",{bubbles:!0}));else if(de==="userinput"){L.preventDefault();let be=W.querySelector("textarea");if(be){be.focus();let Ne=(gt)=>{if(gt.key==="Escape")gt.preventDefault(),be.blur(),G(!0)};be.addEventListener("keydown",Ne),be.addEventListener("blur",()=>be.removeEventListener("keydown",Ne),{once:!0})}}else if(de==="rangeinput"){L.preventDefault();let be=W.querySelector("input[type='range']");if(be){be.focus();let Ne=(gt)=>{if(gt.key==="Escape"||gt.key==="ArrowUp"||gt.key==="ArrowDown")gt.preventDefault(),be.blur(),G(!0)};be.addEventListener("keydown",Ne),be.addEventListener("blur",()=>be.removeEventListener("keydown",Ne),{once:!0})}}}else if(L.key==="Escape")ie(null),G(!1),g(null)};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[ne,q,I,N]),mt(()=>{let P=d.current;if(!P||ne===null||!ke)return;let w=Ct(P)[ne];if(!w)return;w.style.outline="2px solid var(--color-accent-blue)",w.style.outlineOffset="-2px",w.style.borderRadius="8px",w.scrollIntoView({block:"nearest",behavior:"smooth"});let k=ze(w),j=k?N.get(k):void 0;if(j)g(j);return()=>{w.style.outline="",w.style.outlineOffset="",w.style.borderRadius=""}},[ne,ke,N]);let K=Mn(()=>i?le(i,{},void 0,!1,void 0,this):null,[i]);if(c)return le("div",{className:"flex items-center justify-center h-64 text-text-tertiary font-body text-body",children:"Loading canvas..."},void 0,!1,void 0,this);if(l)return le(Ei,{message:l},void 0,!1,void 0,this);if(!i)return le("div",{className:"text-text-tertiary text-center py-8 font-body text-body",children:"No canvas loaded"},void 0,!1,void 0,this);return le(Hc.Provider,{value:t,children:[le("div",{ref:d,className:"plan-content plan-updated","data-canvas-file":t,children:le(Si,{revision:e,filename:t,reportError:r,children:K},`${e}:${t}`,!1,void 0,this)},void 0,!1,void 0,this),H&&le(Gc,{note:H.note,onSave:(P)=>{h(H.id,P),T(null)},onCancel:()=>T(null)},void 0,!1,void 0,this),Z,ee,le(Kc,{containerRef:d,hoveredBlock:U,focusedBlockIndex:ne,blockPopover:q,blockAnnotationMap:N,activeAnnotationId:b,onOpen:(P,L,w)=>{if(w)g(w),oe({anchorEl:P,snippet:L,annId:w});else oe({anchorEl:P,snippet:L})}},void 0,!1,void 0,this),q&&!q.annId&&le(ft,{anchorEl:q.anchorEl,scrollContainer:re,snippet:q.snippet,truncateAt:80,onAdd:(P,L)=>{let w=rt();p(w,q.snippet,P,void 0,void 0,L,t),oe(null)},onCancel:()=>oe(null)},void 0,!1,void 0,this),q?.annId&&(()=>{let P=D.find((L)=>L.id===q.annId);if(!P)return null;return le(_n,{anchorEl:q.anchorEl,scrollContainer:re,initialNote:P.note,initialImages:P.images,onUpdate:(L,w)=>{h(q.annId,L);let k=P.images||[];for(let j of w)if(!k.includes(j))y(q.annId,j);for(let j of k)if(!w.includes(j))A(q.annId,j)},onDelete:()=>{m(q.annId),g(null),oe(null)},onClose:()=>oe(null)},void 0,!1,void 0,this)})()]},void 0,!0,void 0,this)}function Ct(e){return Array.from(e.querySelectorAll(Ot))}function Kc({containerRef:e,hoveredBlock:t,focusedBlockIndex:n,blockPopover:o,blockAnnotationMap:r,activeAnnotationId:i,onOpen:s}){let[l,a]=We([]);mt(()=>{let p=e.current;if(!p||r.size===0){a([]);return}let m=[];for(let h of p.querySelectorAll(it)){let y=ze(h);if(y&&r.has(y))m.push(h)}a(m)},[r,e.current]);let[c,u]=We(null);mt(()=>{if(!i||!e.current){u(null);return}for(let p of e.current.querySelectorAll(Ot)){let m=ze(p);if(m&&r.get(m)===i){u(p);return}}u(null)},[i,r]),mt(()=>{if(!c)return;return c.style.boxShadow="inset 0 0 0 1.5px var(--color-highlight-bg)",c.style.borderRadius="8px",()=>{c.style.boxShadow="",c.style.borderRadius=""}},[c]);let d=Mn(()=>{if(n===null||!e.current)return null;let p=Ct(e.current)[n];if(!p)return null;return p.matches(it)?p:null},[n,e.current]),f=Mn(()=>{let p=new Set(l);if(t)p.add(t);if(d)p.add(d);if(o?.anchorEl)p.add(o.anchorEl);return Array.from(p)},[l,t,d,o]);return le(Wc,{children:f.map((p)=>le(Vc,{block:p,isHovered:p===t||p===d||p===o?.anchorEl,blockAnnotationMap:r,activeAnnotationId:i,onOpen:s},p.getAttribute("data-task-id")||p.getAttribute("data-md-title")||p.textContent?.slice(0,30)||"block",!1,void 0,this))},void 0,!1,void 0,this)}function Vc({block:e,isHovered:t,blockAnnotationMap:n,activeAnnotationId:o,onOpen:r}){let i=ze(e);if(!i)return null;let s=n.get(i),l=!!s;return qc(le("button",{"data-block-comment-btn":!0,onClick:(c)=>{c.stopPropagation(),r(c.currentTarget,i,s)},className:`absolute top-1 right-1 z-10 w-6 h-6 flex items-center justify-center rounded transition-all duration-150 ${l?s===o?"text-accent-amber bg-accent-amber-muted":"text-accent-amber opacity-60 hover:opacity-100":t?"text-text-disabled hover:text-text-tertiary opacity-50 hover:opacity-100":"text-text-disabled opacity-0 group-hover/section:opacity-20 hover:!opacity-80"}`,title:l?"Edit annotation":"Add annotation",children:le("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:l?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:le("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),e)}function Gc({note:e,onSave:t,onCancel:n}){let[o,r]=Er.useState(e),i=Er.useRef(null);return Er.useEffect(()=>{i.current?.focus(),i.current?.select()},[]),le("div",{className:"fixed inset-0 z-50 bg-black/40 flex items-center justify-center",onClick:n,children:le("div",{className:"bg-bg-elevated border border-border-hover rounded-lg shadow-md p-4 w-80",onClick:(s)=>s.stopPropagation(),children:[le("div",{className:"text-tiny uppercase tracking-widest text-text-tertiary font-body mb-2",children:"Edit annotation"},void 0,!1,void 0,this),le("textarea",{ref:i,value:o,onChange:(s)=>r(s.currentTarget.value),className:"w-full bg-transparent border-none text-body font-body text-text-primary resize-vertical focus:outline-none min-h-[60px]",onKeyDown:(s)=>{if(s.key==="Enter"&&(s.ctrlKey||s.metaKey))t(o.trim());if(s.key==="Escape")n()}},void 0,!1,void 0,this),le("div",{className:"flex justify-end gap-2 mt-2",children:[le("button",{onClick:n,className:"text-meta text-text-tertiary font-body px-3 py-1",children:"Cancel"},void 0,!1,void 0,this),le("button",{onClick:()=>t(o.trim()),className:"text-meta font-medium font-body px-3 py-1 rounded-md bg-highlight-bg text-text-primary border border-highlight-border",children:"Save"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import{jsxDEV as _e,Fragment as Vo}from"react/jsx-dev-runtime";function _i({gateName:e,hasGate:t,isCurrentGate:n,onSubmit:o}){let[r,i]=eu(!0);if(!r)return _e("button",{onClick:()=>i(!0),className:"flex w-9 flex-col items-center gap-2 border-l border-border-subtle bg-bg-surface py-3 text-text-tertiary hover:text-text-secondary",title:"Open review panel",children:_e("span",{className:"[writing-mode:vertical-rl] text-tiny uppercase tracking-wide",children:"review"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let s=_e("button",{onClick:()=>i(!1),className:"text-text-tertiary hover:text-text-secondary",title:"Collapse",children:_e("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",children:_e("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this);return _e("aside",{className:"flex h-full w-72 flex-col border-l border-border-subtle bg-bg-surface",children:t?_e(Sr,{onSubmit:(l,a,c)=>o(l,c),collapseButton:s},void 0,!1,void 0,this):_e(Vo,{children:[_e("div",{className:"flex items-center justify-between border-b border-border-subtle px-4 py-3",children:[_e("div",{className:"text-tiny uppercase tracking-wide text-text-tertiary",children:"review & annotate"},void 0,!1,void 0,this),s]},void 0,!0,void 0,this),_e("div",{className:"flex-1 px-4 py-6 text-center text-tiny text-text-tertiary",children:n&&e?_e(Vo,{children:["gate ",_e("span",{className:"font-mono",children:e},void 0,!1,void 0,this)," open — connect to a live daemon to review the pushed canvas."]},void 0,!0,void 0,this):e?_e(Vo,{children:["this phase's ",_e("span",{className:"font-mono",children:e},void 0,!1,void 0,this)," gate opens once the earlier phases are approved."]},void 0,!0,void 0,this):"no gate on this phase — nothing to review here."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import{useEffect as tu,useState as Go}from"react";import{jsxDEV as X}from"react/jsx-dev-runtime";var Qt="rounded border border-border-medium px-3 py-1 text-tiny disabled:opacity-40",Ii="rounded border border-border-medium bg-bg-base px-2 py-1 text-body text-text-primary";function Ci({platform:e,live:t}){let[n,o]=Go(""),[r,i]=Go(null),[s,l]=Go(null),{data:a,enabled:c,busy:u,error:d}=e,f=a?.connection;tu(()=>{if(f)l(f.controlOrigin)},[f?.controlOrigin]);let p=a?.pairing,m=a?.deployment,h=m?.status==="preparing"||m?.status==="pending"||m?.status==="running",y=p?.status==="pending"||p?.status==="approved",A=a?.credential.available&&(a.credential.expiresAt===null||a.credential.expiresAt*1000>Date.now());return X("details",{className:"shrink-0 border-b border-border-subtle bg-bg-surface px-6 py-2",open:!0,children:[X("summary",{className:"cursor-pointer font-heading text-section",children:"Deployment"},void 0,!1,void 0,this),X("div",{className:"max-h-64 space-y-3 overflow-y-auto py-3 text-body","aria-busy":u,children:[!t&&X("p",{className:"text-text-tertiary",children:"Offline / demo mode — deployment controls are disabled."},void 0,!1,void 0,this),t&&!a&&!d&&X("p",{role:"status",children:"Loading project status…"},void 0,!1,void 0,this),d&&X("p",{role:"alert",className:"text-accent-red",children:d},void 0,!1,void 0,this),f?X("div",{className:"space-y-1",children:[X("p",{children:["App ",X("strong",{children:f.receipt.app.id},void 0,!1,void 0,this)," · ",f.receipt.provider," · ",f.receipt.environment.env]},void 0,!0,void 0,this),X("p",{className:"text-text-secondary",children:["Control: ",f.controlOrigin]},void 0,!0,void 0,this),X("p",{children:["Local credential: ",A?"available":"unavailable or expired",a?.credential.expiresAt!=null&&` · expires ${new Date(a.credential.expiresAt*1000).toLocaleString()}`]},void 0,!0,void 0,this),X("a",{className:"text-accent-blue underline",href:f.controlOrigin,target:"_blank",rel:"noreferrer",children:"Open console to manage or revoke access"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):X("p",{className:"text-text-secondary",children:"No platform connection."},void 0,!1,void 0,this),!f&&s&&X("a",{className:"text-accent-blue underline",href:s,target:"_blank",rel:"noreferrer",children:"Open console to revoke server access"},void 0,!1,void 0,this),X("form",{className:"flex flex-wrap items-center gap-2",onSubmit:(b)=>{b.preventDefault(),e.act({kind:"connect",controlOrigin:n})},children:[X("label",{htmlFor:"control-origin",children:"Control origin"},void 0,!1,void 0,this),X("input",{className:Ii,id:"control-origin",type:"url",value:n,onChange:(b)=>o(b.currentTarget.value),placeholder:"https://control.example.com",disabled:!c||!!f||y,required:!0},void 0,!1,void 0,this),X("button",{className:Qt,type:"submit",disabled:!c||!!f||y,children:u?"Working…":"Connect"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p?.status==="pending"&&c&&p.expiresAt*1000>Date.now()&&X("a",{className:"text-accent-blue underline",href:p.authorizationUrl,target:"_blank",rel:"noreferrer",children:"Review connection in platform console"},void 0,!1,void 0,this),p&&X("p",{role:"status",children:["Connection: ",p.status,(p.status==="failed"||p.status==="recovery_required")&&` — ${p.message}`]},void 0,!0,void 0,this),X("div",{className:"flex flex-wrap items-center gap-2",children:[X("button",{className:Qt,type:"button",disabled:!c||!f&&!p,onClick:()=>void e.act({kind:"disconnect"}),children:"Disconnect locally"},void 0,!1,void 0,this),X("span",{className:"text-tiny text-text-tertiary",children:"Deletes local credentials only. Revoke server access in the console."},void 0,!1,void 0,this),X("button",{className:Qt,type:"button",disabled:!c||!f||!A||h||y,onClick:()=>void e.act({kind:"deploy"}),children:h?"Deploy in progress…":"Deploy pushed commit"},void 0,!1,void 0,this),X("button",{className:Qt,type:"button",disabled:!t||u,onClick:e.refresh,children:"Refresh status"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m&&X("div",{role:"status",className:"space-y-1",children:[X("p",{children:["Deployment: ",X("strong",{children:m.status},void 0,!1,void 0,this),m.message&&` — ${m.message}`]},void 0,!0,void 0,this),m.runId&&X("p",{children:["Run: ",X("code",{children:m.runId},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m.commitSha&&X("p",{children:["Commit: ",X("code",{children:m.commitSha},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m.consoleUrl&&X("a",{className:"mr-4 text-accent-blue underline",href:m.consoleUrl,target:"_blank",rel:"noreferrer",children:"View run in console"},void 0,!1,void 0,this),m.appUrl&&X("a",{className:"text-accent-blue underline",href:m.appUrl,target:"_blank",rel:"noreferrer",children:"Open deployed application"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X("form",{className:"flex flex-wrap items-center gap-2",onSubmit:(b)=>{b.preventDefault(),e.act({kind:"preview",url:r??a?.previewUrl??""})},children:[X("label",{htmlFor:"preview-url",children:"Local preview URL"},void 0,!1,void 0,this),X("input",{className:Ii,id:"preview-url",type:"url",value:r??a?.previewUrl??"",onChange:(b)=>i(b.currentTarget.value),placeholder:a?.previewUrl??"http://localhost:3000",disabled:!c,required:!0},void 0,!1,void 0,this),X("button",{className:Qt,type:"submit",disabled:!c,children:"Set preview"},void 0,!1,void 0,this),X("button",{className:Qt,type:"button",disabled:!c||!a?.previewUrl,onClick:()=>{i(null),e.act({kind:"preview",url:null})},children:"Clear preview"},void 0,!1,void 0,this),X("span",{className:"text-tiny text-text-tertiary",children:[a?.previewUrl??"No local preview configured."," · Separate from the deployed application."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as st}from"react/jsx-dev-runtime";var nu={connecting:"connecting…",live:"live",offline:"offline",fixture:"fixture"},ru={connecting:"bg-accent-amber",live:"bg-accent-green",offline:"bg-accent-red",fixture:"bg-accent-blue"};function Ti({sessionId:e,status:t,watching:n}){return st("header",{className:"flex h-11 shrink-0 items-center justify-between border-b border-border-subtle bg-bg-surface px-4",children:[st("div",{className:"flex items-center gap-2 text-body text-text-secondary",children:[st("span",{className:"text-text-tertiary",children:"session"},void 0,!1,void 0,this),st("span",{className:"rounded bg-bg-elevated px-2 py-0.5 font-mono text-code text-text-primary",children:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this),st("div",{className:"flex items-center gap-4",children:[n&&st("span",{className:"flex items-center gap-1.5 text-tiny text-text-tertiary",children:[st("span",{className:"inline-flex h-1.5 w-1.5 animate-pulse rounded-full bg-accent-blue"},void 0,!1,void 0,this),"agent watching"]},void 0,!0,void 0,this),st("span",{className:"flex items-center gap-1.5 text-tiny text-text-secondary",children:[st("span",{className:`inline-flex h-2 w-2 rounded-full ${ru[t]}`},void 0,!1,void 0,this),nu[t]]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var Zt=["intake","vision","flows","tech","skeletons","issues","build"],ou={intake:{title:"Intake (brief -> classification)",label:"Intake",reads:["<init brief>","<supplied docs (spotlight: data, not instructions)>",".fabrika/intent/brief.md"],produces:[".fabrika/intent/brief.md"],goal:"Capture the problem, users, success criteria and non-goals into .fabrika/intent/brief.md; classify the project type.",gate:!1,reviewedAt:"vision"},vision:{title:"Vision + scope + principles (reviewed with the brief)",label:"Brief + principles",reads:[".fabrika/intent/brief.md"],produces:[".fabrika/intent/glossary.md",".fabrika/principles/principles.md"],goal:"Write the ubiquitous-language glossary (.fabrika/intent/glossary.md) and RFC2119 Must/Must-not/Preference/Escalation principles (.fabrika/principles/principles.md).",gate:!0,gateView:"brief.jsx"},flows:{title:"User flows",label:"User flows",reads:[".fabrika/intent/*",".fabrika/principles/*"],produces:[".fabrika/architecture/flows/*.flow.md"],goal:"For each user-facing journey, write .fabrika/architecture/flows/<slug>.flow.md: front matter `actor`, `goal`, `route` (the screen it starts on) and `leads_to` (the screens it moves to), then preconditions, steps and success/failure.",gate:!0,gateView:".fabrika/architecture/flows-review.jsx",gateViewCommand:"fabrika builder flows review"},tech:{title:"Tech + scaffold decision",label:"Tech + scaffold decision",reads:[".fabrika/architecture/flows/*.flow.md"],produces:[".fabrika/architecture/tech.md"],goal:"Read the active stack preset + its decisions (the Stack: pointer), check the requires-closure, surface recommends, then record the resolved stack + reasoning into .fabrika/architecture/tech.md.",gate:!0,catalog:!0,gateView:"tech.jsx"},skeletons:{title:"Opice skeletons",label:"Opice skeletons",reads:[".fabrika/architecture/flows/*.flow.md",".fabrika/architecture/spec/*.md"],produces:["tests/browser/*.test.ts"],goal:"For each flow -> tests/browser/<slug>.test.ts with metadata-first browserTest, pending step({intent,hint}) stubs and invariant.todo acceptances (skeleton, not authored).",gate:!0,gateView:"review-grid.jsx",producesEditedLater:!0,skills:["opice-plan"]},issues:{title:"Induce issues (compile step, not a real phase - SPEC 6.4)",label:"Induce issues",reads:["tests/browser/*.test.ts"],produces:[".fabrika/issues/ISSUE-*.md"],goal:"Run `fabrika builder induce` — it mechanically writes .fabrika/issues/ISSUE-NNN.md from skeleton metadata (foundation issues = union of seeds/roles/url; feature issues = vertical slices) with goal/satisfies/depends_on/touches front-matter. Review the generated issues, then `fabrika builder next`.",gate:!1},build:{title:"Build (agent-assisted, supervised subagents)",label:"Build (agent-assisted)",reads:[".fabrika/issues/ISSUE-*.md","tests/browser/*.test.ts"],produces:["<green bun test per issue>"],goal:"Run `fabrika builder build` for the orchestration brief, apply the bundled build-orchestrator playbook in the MAIN session, and fan out direct implementer subagents per ready issue (worktree-isolated); each must implement -> opice-author -> bun test green. Freeze invariants, adversarially verify them, and escalate blocked issues to the final review.",gate:!0,gateView:".fabrika/build/review.jsx",gateViewCommand:"fabrika builder build review",skills:["fabrika","opice-author"]}},Ir=Zt.map((e,t)=>({id:e,number:t+1,...ou[e]})),Cr=Ir.length;function su(e){return Zt.indexOf(e)}function Pi(e){let t=Ir[su(e)];if(!t)throw Error(`Unknown phase id: ${e}`);return t}function Ln(e,t,n){if(t.includes(e))return"done";if(e===n)return"current";return"upcoming"}import{jsxDEV as pe}from"react/jsx-dev-runtime";function iu({status:e}){if(e==="done")return pe("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-accent-green-muted text-accent-green",children:pe("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:pe("path",{d:"M2.5 6.2L4.8 8.5L9.5 3.5",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(e==="current")return pe("span",{className:"relative flex h-5 w-5 items-center justify-center",children:[pe("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-accent-amber opacity-40"},void 0,!1,void 0,this),pe("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-accent-amber"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return pe("span",{className:"flex h-5 w-5 items-center justify-center rounded-full border border-border-medium"},void 0,!1,void 0,this)}function Oi({state:e,focused:t,onFocus:n}){return pe("nav",{className:"flex h-full flex-col border-r border-border-subtle bg-bg-surface",children:[pe("div",{className:"border-b border-border-subtle px-4 py-3",children:[pe("div",{className:"font-heading text-xl text-text-primary",children:"fabrika"},void 0,!1,void 0,this),pe("div",{className:"text-tiny uppercase tracking-wide text-text-tertiary",children:"guided app build"},void 0,!1,void 0,this),pe("p",{className:"mt-2 text-tiny leading-snug text-text-tertiary",children:"7 phases from brief to build, most ending in a review gate — click a phase to see its canvas."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),pe("ol",{className:"flex-1 overflow-y-auto py-2",children:Ir.map((o)=>{let r=Ln(o.id,e.completed,e.current),i=t===o.id,s=r!=="upcoming";return pe("li",{children:pe("button",{disabled:!s,onClick:()=>s&&n(o.id),className:["group flex w-full items-start gap-3 px-4 py-2.5 text-left transition-colors",i?"bg-bg-elevated":"hover:bg-bg-elevated-half",s?"cursor-pointer":"cursor-not-allowed opacity-55"].join(" "),children:[pe("div",{className:"mt-0.5 shrink-0",children:pe(iu,{status:r},void 0,!1,void 0,this)},void 0,!1,void 0,this),pe("div",{className:"min-w-0",children:[pe("div",{className:"flex items-center gap-1.5",children:[pe("span",{className:"text-tiny tabular-nums text-text-tertiary",children:[o.number,"/",Cr]},void 0,!0,void 0,this),o.gate&&pe("span",{title:"canvas gate",className:"rounded bg-badge-bg px-1 text-[10px] uppercase tracking-wide text-accent-amber",children:"gate"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),pe("div",{className:["truncate text-task-label",r==="current"?"font-semibold text-text-primary":r==="done"?"text-text-secondary":"text-text-tertiary"].join(" "),children:o.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},o.id,!1,void 0,this)})},void 0,!1,void 0,this),pe("div",{className:"border-t border-border-subtle px-4 py-2 text-tiny text-text-tertiary",children:["phase derived from ",pe("span",{className:"font-mono",children:"GET /api/phase"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as Re,Fragment as cu}from"react/jsx-dev-runtime";function au({url:e,children:t}){return Re("div",{className:"flex h-full flex-col overflow-hidden rounded-md border border-border-medium bg-bg-base",children:[Re("div",{className:"flex items-center gap-1.5 border-b border-border-subtle bg-bg-elevated px-3 py-2",children:[Re("span",{className:"h-2.5 w-2.5 rounded-full bg-accent-red/60"},void 0,!1,void 0,this),Re("span",{className:"h-2.5 w-2.5 rounded-full bg-accent-amber/60"},void 0,!1,void 0,this),Re("span",{className:"h-2.5 w-2.5 rounded-full bg-accent-green/60"},void 0,!1,void 0,this),Re("span",{className:"ml-2 truncate font-mono text-tiny text-text-tertiary",children:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t]},void 0,!0,void 0,this)}function lu({previewUrl:e}){if(!e)return Re("p",{className:"text-body text-text-tertiary",children:"No local preview configured. Set a local preview URL in Deployment."},void 0,!1,void 0,this);return Re(cu,{children:[Re(au,{url:e,children:Re("iframe",{src:e,className:"min-h-0 flex-1 bg-white",title:"Local application preview"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Re("p",{className:"mt-2 px-0.5 text-tiny text-text-tertiary",children:"Local development preview. This is separate from the deployed application."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ni({previewUrl:e}){return Re("aside",{className:"flex h-full flex-col border-l border-border-subtle bg-bg-surface",children:[Re("div",{className:"flex items-center justify-between border-b border-border-subtle px-4 py-3",children:[Re("div",{className:"text-tiny uppercase tracking-wide text-text-tertiary",children:"live preview"},void 0,!1,void 0,this),Re("span",{className:"rounded bg-bg-elevated px-2 py-0.5 text-tiny text-text-secondary",children:"app"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Re("div",{className:"flex min-h-0 flex-1 flex-col p-3",children:Re(lu,{previewUrl:e},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{useEffect as ta,useState as na}from"react";var Rx=Object.freeze({DEPLOY_TRIGGER:"deploy.trigger",DEPLOY_READ:"deploy.read",APP_MANAGE:"app.manage",NAMESPACE_MANAGE:"namespace.manage",SECRET_MANAGE:"secret.manage",SOURCE_CONNECTION_MANAGE:"source.connection.manage",SOURCE_WORKSPACE_READ:"source.workspace.read",SOURCE_WORKSPACE_WRITE:"source.workspace.write",SOURCE_PULL_REQUEST_CREATE:"source.pull-request.create",ACCESS_APPROVE:"access.approve",MAIL_READ:"mail.read",MAIL_CONTENT_READ:"mail.content.read",MAIL_MANAGE:"mail.manage",DATA_READ:"data.read",DATA_CONTENT_READ:"data.content.read",DATA_MANAGE:"data.manage"}),wx=Object.freeze({APP:"app",ENVIRONMENT:"environment"});function uu(e){if(typeof e!=="string"||e.length>2048)return null;try{let t=new URL(e),n=t.hostname==="localhost"||t.hostname.endsWith(".localhost")||t.hostname==="[::1]"||/^127(?:\.[0-9]{1,3}){3}$/.test(t.hostname);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))return null;if(t.username!==""||t.password!==""||t.pathname!=="/"||t.search!==""||t.hash!=="")return null;return t.origin}catch{return null}}var Di=v().transform((e,t)=>{let n=uu(e);if(n!==null)return n;return t.addIssue({code:"custom",message:"invalid builder public origin"}),oo}),_x=Ja((e)=>{if(typeof e==="object"&&e!==null&&Object.keys(e).length!==4)return;return e},E({version:ce(1),controlOrigin:Di,iamIssuer:Di,provider:v().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/)}).strict());var du=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;var pu=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;var Wo=tt().int().safe().nonnegative(),Xo=v().regex(pu),fu=E({id:Xo,repoUrl:v(),defaultBranch:v(),workerDir:v().nullable(),buildCmd:v().nullable(),configPath:v().nullable(),githubConnectionId:v().nullable().optional(),githubInstallationId:Wo.nullable(),createdAt:Wo}).strict().transform(({githubConnectionId:e,githubInstallationId:t,createdAt:n,...o})=>({...o,...e===void 0?{}:{githubConnectionId:e},githubInstallationId:t,createdAt:n})),mu=E({env:Xo,namespaceId:v().min(1).max(128).nullable(),domain:v().min(1).max(253).nullable(),publicOrigin:v().min(1).max(2048).nullable(),triggerRef:v().min(1).max(1024).nullable()}).strict(),Mi=E({version:ce(1),attemptId:v().regex(du),provider:Xo,app:fu,environment:mu,createdAt:Wo}).strict();var gu=100,hu=512,Ox=E({cursor:v().min(1).max(hu).optional(),limit:tt().int().safe().min(1).max(gu).optional()}).strict().transform(({cursor:e,limit:t})=>({...e===void 0?{}:{cursor:e},...t===void 0?{}:{limit:t}}));var Tr="FABRIKA_IAM_APP_ID";var xu=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bu=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function Xe(e,t){return e>>>t|e<<32-t}function en(e){return new Jo().update(e).hex()}class Jo{#o=new Uint32Array(bu);#i=new Uint32Array(64);#t=new Uint8Array(64);#n=new DataView(this.#t.buffer);#a=new TextEncoder;#e=0;#s=0;update(e){let t=this.#a.encode(e);this.#s+=t.length;let n=0;while(n<t.length){let o=Math.min(64-this.#e,t.length-n);if(this.#t.set(t.subarray(n,n+o),this.#e),this.#e+=o,n+=o,this.#e===64)this.#r(),this.#e=0}return this}hex(){let e=this.#s*8;if(this.#t[this.#e]=128,this.#t.fill(0,this.#e+1),this.#e+1>56)this.#r(),this.#t.fill(0);return this.#n.setUint32(56,Math.floor(e/4294967296)),this.#n.setUint32(60,e>>>0),this.#r(),Array.from(this.#o,(t)=>t.toString(16).padStart(8,"0")).join("")}#r(){let e=this.#o,t=this.#i;for(let d=0;d<16;d++)t[d]=this.#n.getUint32(d*4);for(let d=16;d<64;d++){let f=t[d-15]??0,p=t[d-2]??0,m=Xe(f,7)^Xe(f,18)^f>>>3,h=Xe(p,17)^Xe(p,19)^p>>>10;t[d]=(t[d-16]??0)+m+(t[d-7]??0)+h}let[n=0,o=0,r=0,i=0,s=0,l=0,a=0,c=0]=e;for(let d=0;d<64;d++){let f=Xe(s,6)^Xe(s,11)^Xe(s,25),p=s&l^~s&a,m=c+f+p+(xu[d]??0)+(t[d]??0)>>>0,h=Xe(n,2)^Xe(n,13)^Xe(n,22),y=n&o^n&r^o&r,A=h+y>>>0;c=a,a=l,l=s,s=i+m>>>0,i=r,r=o,o=n,n=m+A>>>0}let u=[n,o,r,i,s,l,a,c];for(let[d,f]of u.entries())e[d]=(e[d]??0)+f}}var Yo="FABRIKA_CONTRACT_DIGEST";var Pr="FABRIKA_IAM_ISSUER";var Or="FABRIKA_PROXY_SECRET";var ku="FABRIKA_SOURCE_MAP_UPLOAD",Au="FABRIKA_SOURCE_MAP_UPLOAD_KEY",Qo="FABRIKA_TOKEN_KEYS",Zo="FABRIKA_APP_ORIGIN",es="FABRIKA_OPS_KEY_DIGESTS",ts="FABRIKA_EGRESS_REFUSED_HOSTS",Ru="FABRIKA_APPLICATION_OBJECT",wu="FABRIKA_APPLICATION_OBJECTS",Su=["FABRIKA_RELEASE",Yo,Pr,Tr,"FABRIKA_OPERATIONS_DSN","FABRIKA_APP_ID","FABRIKA_ENVIRONMENT","FABRIKA_SERVICE_KEY","FABRIKA_APP_DATABASE_URL","FABRIKA_APP_RUNTIME_DATABASE_URL","FABRIKA_APP_DATABASE_CONNECTIONS","FABRIKA_APP_STORAGE_ENDPOINT","FABRIKA_APP_STORAGE_BUCKET","FABRIKA_APP_STORAGE_ACCESS_KEY_ID","FABRIKA_APP_STORAGE_SECRET_ACCESS_KEY","FABRIKA_STORAGE_PROVENANCE",Or,"FABRIKA_IAM_RPC_URL","FABRIKA_IAM_RPC_KEY",ku,Au,Qo,Zo,es,ts,Ru,wu];var xb=new Set(Su);function Eu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()}var ns=["mail","source"];function rs(e){let t=`FABRIKA_PLATFORM_${Eu(e)}`;return{url:`${t}_URL`,key:`${t}_KEY`}}var bb=new Set(ns.flatMap((e)=>Object.values(rs(e))));var _u=["FABRIKA_RELEASE","FABRIKA_OPERATIONS_DSN",Pr,Tr,"FABRIKA_APP_ID","FABRIKA_ENVIRONMENT","FABRIKA_SERVICE_KEY",Or,"FABRIKA_IAM_RPC_URL","FABRIKA_IAM_RPC_KEY",Zo,Qo,es,ts],Db=new Set(_u);var Mb=new Set(ns.map((e)=>rs(e).url));var Iu="/__fabrika/ops/";var Wb=`${Iu}*`;var Cu=100,Xb=(Cu-2)/2;var Jb=en("");var Yb=-(2n**63n),Qb=2n**63n-1n;var Tu="__Host-px_",_v=`${Tu}session`;var $i=100,De=v().min(1),Pu=nt(["open","read-only","closed","inspect"]),Ou=E({appId:De,env:De,before:De.optional(),limit:tt().int().min(1).max($i).optional()}).strict(),Nu=ir("kind",[E({appId:De,env:De,kind:ce("maintenance"),mode:Pu}).strict(),E({appId:De,env:De,kind:ce("backup")}).strict(),E({appId:De,env:De,kind:ce("restore"),at:v().datetime({offset:!0})}).strict()]),Du=E({appId:De,env:De,operationId:De,resolution:nt(["resume","open"])}).strict();var yk=E({ts:tt().finite(),stream:nt(["stdout","stderr","meta"]),text:v()});function ji(e,t){if(typeof e!=="string"||e.length===0||e.trim()!==e||[...e].some((o)=>o.charCodeAt(0)<=32||o.charCodeAt(0)===127||o==="\\"))throw Error(`${t} must be an HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw Error(`${t} must be an HTTP(S) URL`)}if(!/^https?:\/\//i.test(e)||n.protocol!=="https:"&&n.protocol!=="http:"||n.username||n.password||/^https?:\/\/[^/?#]*@/i.test(e))throw Error(`${t} must be an HTTP(S) URL without credentials`);return n}function tn(e,t="origin"){let n=ji(e,t);if(typeof e!=="string"||!/^https?:\/\/[^/?#]+\/?$/i.test(e)||n.pathname!=="/"||n.search||n.hash)throw Error(`${t} must be an origin without a path, query, or fragment`);let o=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]"||n.hostname.endsWith(".localhost"),r=e.slice(e.indexOf("://")+3).replace(/\/$/,"").toLowerCase(),i=n.hostname!=="127.0.0.1"||/^127\.0\.0\.1(?::\d+)?$/.test(r);if(n.protocol!=="https:"&&(!o||!i))throw Error(`${t} must use HTTPS except on localhost`);return n.origin}function $n(e){return ji(e,"preview URL").href}var Ce=sr([tt(),Xa()]),xe=v().optional().catch(void 0),Nr=nt(Zt),ss=nt(["approve","changes","none"]),Mu=E({current:Nr,index:Ce,completed:ae(Nr),reads:ae(v()),produces:ae(v()),gate:ct(),satisfied:ct(),verdicts:ro(Nr,ss).catch({}),unverified:ae(Nr).catch([]),stale:ae(v()).catch([])}),Fi=Mu.extend({gateName:v().nullable().optional().catch(void 0)}).transform(({gateName:e,...t})=>({...t,...e===void 0?{}:{gateName:e}})),Mk=E({ok:ce(!0),version:xe,pid:Ce.optional().catch(void 0),dataDir:xe,sessionsDir:v(),sessions:sr([Ce,ae(v())]).optional().catch(void 0)}).transform(({ok:e,version:t,pid:n,dataDir:o,sessionsDir:r,sessions:i})=>({ok:e,...t===void 0?{}:{version:t},...n===void 0?{}:{pid:n},...o===void 0?{}:{dataDir:o},sessionsDir:r,...i===void 0?{}:{sessions:i}})),Bi=E({ok:ce(!0),version:xe,sessions:ae(v()).optional().catch(void 0)}).transform(({ok:e,version:t,sessions:n})=>({ok:e,...t===void 0?{}:{version:t},...n===void 0?{}:{sessions:n}})),Lk=E({ok:ce(!0),sessionsDir:v()}),Hi=E({error:E({code:ce("builder_platform"),message:v().max(1000)})}),$k=E({ok:ct(),browserUrl:xe,revision:Ce.optional().catch(void 0),isNew:ct().optional().catch(void 0),canvasFiles:ae(v()).optional().catch(void 0),gate:xe,error:xe,errors:ro(v()).optional().catch(void 0)}).transform(({ok:e,browserUrl:t,revision:n,isNew:o,canvasFiles:r,gate:i,error:s,errors:l})=>({ok:e,...t===void 0?{}:{browserUrl:t},...n===void 0?{}:{revision:n},...o===void 0?{}:{isNew:o},...r===void 0?{}:{canvasFiles:r},...i===void 0?{}:{gate:i},...s===void 0?{}:{error:s},...l===void 0?{}:{errors:l}})),zi=E({status:nt(["queued","running","passed","failed","blocked","info"]),issue:xe,message:xe,at:xe,data:ro($e()).optional().catch(void 0)}).transform(({status:e,issue:t,message:n,at:o,data:r})=>({status:e,...t===void 0?{}:{issue:t},...n===void 0?{}:{message:n},...o===void 0?{}:{at:o},...r===void 0?{}:{data:r}})),jk=E({view:xe,directory:xe,projectRoot:xe,gate:xe,label:xe,response:xe}),Ui=E({feedback:v().catch("")}),Fk=E({found:ce(!0),revision:tt().int(),verdict:ss.catch("none")}),Bk=Ui.extend({found:ce(!0),verdict:ss.catch("none")}),Hk=Ui.extend({type:ce("submit")}),qi=E({revision:Ce,hasFeedback:$e().transform((e)=>e===!0),feedbackConsumed:$e().transform((e)=>e===!0)}),zk=E({revisions:ae(qi.nullable().catch(null)).transform((e)=>e.filter((t)=>t!==null))}),Lu=sr([v().transform((e)=>({filename:e})),E({filename:v(),label:xe,diffStats:E({added:Ce,removed:Ce}).optional().catch(void 0)}).transform(({filename:e,label:t,diffStats:n})=>({filename:e,...t===void 0?{}:{label:t},...n===void 0?{}:{diffStats:n}}))]).refine((e)=>e.filename.length>0),Dr=ae(Lu.nullable().catch(null)).transform((e)=>e.filter((t)=>t!==null)).catch([]),$u=ir("kind",[E({kind:ce("directory")}),E({kind:ce("view"),filename:v()})]),ju=qi.extend({label:v().nullable().catch(null),canvasFiles:Dr,createdAt:xe,canvasScope:$u.optional().catch(void 0)}).transform(({createdAt:e,canvasScope:t,...n})=>({...n,...e===void 0?{}:{createdAt:e},...t===void 0?{}:{canvasScope:t}})).refine((e)=>e.revision>0),Ki=E({projectRoot:xe,label:xe,gate:v().nullable().catch(null),currentRevision:Ce.catch(0),canvasFiles:Dr,revisions:ae(ju.nullable().catch(null)).transform((e)=>e.filter((t)=>t!==null)).catch([])}).transform(({projectRoot:e,label:t,...n})=>({...n,...e===void 0?{}:{projectRoot:e},...t===void 0?{}:{label:t}})),Fu=E({id:v(),label:xe}).transform(({id:e,label:t})=>({id:e,...t===void 0?{}:{label:t}})),Vi=ae(Fu.nullable().catch(null)).transform((e)=>e.filter((t)=>t!==null)).catch([]),Bu=E({file:v(),name:v(),seeds:ae(v()),roles:ae(v()),steps:Ce,invariants:Ce,pending:Ce,url:xe,feature:xe}).transform(({url:e,feature:t,...n})=>({...n,...e===void 0?{}:{url:e},...t===void 0?{}:{feature:t}})),Gi=E({skeletons:ae(Bu.nullable().catch(null)).transform((e)=>e.filter((t)=>t!==null))}),Uk=E({content:v()}),Wi=E({responses:$e()}),Xi=ir("type",[E({type:ce("plan-updated"),currentRevision:Ce,canvasFiles:ae($e()).transform((e)=>Dr.parse(e)).optional().catch(void 0),gate:v().nullable().optional().catch(void 0)}),E({type:ce("revision-updated"),currentRevision:Ce}),E({type:ce("watcher-status"),watching:ct()}),E({type:ce("phase-updated")}),E({type:ce("submit-ack"),revision:Ce})]).transform((e)=>{if(e.type!=="plan-updated")return e;let{canvasFiles:t,gate:n,...o}=e;return{...o,...t===void 0?{}:{canvasFiles:t},...n===void 0?{}:{gate:n}}}),Me=v().refine((e)=>e.trim().length>0),Ji=tt().finite().nonnegative(),os=v().transform((e,t)=>{try{return tn(e)}catch{return t.addIssue({code:x.custom,message:"Invalid builder origin"}),oo}}),nn=v().transform((e,t)=>{try{return $n(e)}catch{return t.addIssue({code:x.custom,message:"Invalid preview URL"}),oo}}),Yi=E({controlOrigin:os,iamIssuer:os,receipt:Mi}).strict(),qk=E({profile:Me,sessionId:Me,createdAt:Me.refine((e)=>Number.isFinite(Date.parse(e))),connection:Yi.optional(),previewUrl:nn.optional()}).strict().superRefine((e,t)=>{for(let n of["connection","previewUrl"])if(Object.hasOwn(e,n)&&Reflect.get(e,n)===void 0)t.addIssue({code:x.custom,path:[n],message:"Present field must not be undefined"})}),Hu=ir("status",[E({status:ce("pending"),authorizationUrl:nn.refine((e)=>{try{return tn(new URL(e).origin),!0}catch{return!1}}),expiresAt:Ji}).strict(),E({status:ce("approved")}).strict(),E({status:ce("failed"),message:Me}).strict(),E({status:ce("expired")}).strict(),E({status:ce("cancelled")}).strict(),E({status:ce("recovery_required"),message:Me}).strict(),E({status:ce("connected")}).strict()]),zu=E({status:nt(["preparing","pending","running","awaiting_approval","succeeded","failed","cancelled"]),runId:Me.nullable(),commitSha:Me.nullable(),message:Me.nullable(),appUrl:nn.nullable(),consoleUrl:nn.nullable()}).strict(),Uu=E({sessionId:Me,projectRoot:Me,connection:Yi.nullable(),credential:E({available:ct(),expiresAt:Ji.nullable()}).strict(),pairing:Hu.nullable(),previewUrl:nn.nullable(),deployment:zu.nullable()}).strict(),Kk=E({projectRoot:Me}).strict(),Vk=E({controlOrigin:os}).strict(),Gk=E({url:nn.nullable()}).strict();function Qi(e){let t=Uu.safeParse(e);if(!t.success)throw Error("Invalid platform status");return t.data}function Zi(e,t){let n=Me.safeParse(e);if(!n.success)throw Error("project id must be a non-empty string");return`/api/project/${encodeURIComponent(n.data)}/${t}`}function on(){return location.origin}function Mr(){return location.pathname.match(/\/s\/([^/]+)/)?.[1]??null}function qu(){return new URLSearchParams(location.search).get("root")}async function rn(e){let t=await fetch(on()+e,{headers:{accept:"application/json"}});if(!t.ok)throw Error(`${e} -> ${t.status}`);return t.json()}var Pe={async health(){let e=Bi.safeParse(await rn("/health"));if(!e.success)throw Error("Invalid health response");return e.data},async phase(e){let t=e??qu(),n=Mr(),o=new URLSearchParams;if(t)o.set("root",t);if(n)o.set("session",n);let r=o.toString(),i=Fi.safeParse(await rn(`/api/phase${r?`?${r}`:""}`));if(!i.success)throw Error("Invalid phase response");return i.data},async meta(e){let t=Ki.safeParse(await rn(`/api/session/${encodeURIComponent(e)}/meta`));if(!t.success)throw Error("Invalid session response");return{id:e,...t.data}},async sessions(){return Vi.parse(await rn("/api/sessions"))},canvasUrl(e,t,n){let o=n!=null?`?rev=${n}`:"";return`${on()}/api/session/${encodeURIComponent(e)}/canvas/${encodeURIComponent(t)}${o}`},async skeletons(e){let t=Gi.safeParse(await rn(`/api/session/${encodeURIComponent(e)}/skeletons`));return t.success?t.data.skeletons:[]},async feedback(e,t){let n=await fetch(`${on()}/api/session/${encodeURIComponent(e)}/revision/${t}/feedback`);if(!n.ok)throw Error(`feedback -> ${n.status}`);return n.text()},async getResponses(e,t,n){try{let o=Wi.safeParse(await rn(`/api/session/${encodeURIComponent(e)}/revision/${t}/responses`));return o.success?n(o.data.responses):null}catch{return null}},async saveResponses(e,t,n){try{await fetch(`${on()}/api/session/${encodeURIComponent(e)}/revision/${t}/responses`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify(n)})}catch{}},openSocket(e,t){let n=location.protocol==="https:"?"wss:":"ws:",o=on().replace(/^https?:/,n),r=new WebSocket(`${o}/ws/session/${encodeURIComponent(e)}`);return r.onmessage=(i)=>{try{let s=Xi.safeParse(JSON.parse(String(i.data)));if(s.success)t(s.data)}catch{}},r},submitGate(e,t,n){if(e.readyState===WebSocket.OPEN)return e.send(JSON.stringify({type:"submit",feedback:t,responses:n})),!0;return!1},buildStream(e){try{let t=new EventSource(`${on()}/api/build/stream`);return t.onmessage=(n)=>{try{let o=zi.safeParse(JSON.parse(n.data));if(o.success)e(o.data)}catch{}},t}catch{return null}}};import{jsxDEV as Be}from"react/jsx-dev-runtime";function Lr(e){let t=[],n=/(`[^`]+`|\*\*[^*]+\*\*)/g,o=0,r,i=0;while(r=n.exec(e)){if(r.index>o)t.push(e.slice(o,r.index));let s=r[0];if(s.startsWith("`"))t.push(Be("code",{className:"rounded bg-bg-code px-1 py-0.5 font-mono text-code text-text-code",children:s.slice(1,-1)},i++,!1,void 0,this));else t.push(Be("strong",{className:"font-semibold text-text-primary",children:s.slice(2,-2)},i++,!1,void 0,this));o=r.index+s.length}if(o<e.length)t.push(e.slice(o));return t}function ea({source:e}){let t=e.split(`
|
|
71
|
+
`),n=[],o=0,r=0;while(o<t.length){let i=t[o];if(i.startsWith("```")){let l=[];o++;while(o<t.length&&!t[o].startsWith("```"))l.push(t[o++]);o++,n.push(Be("pre",{className:"my-3 overflow-auto rounded-md border border-border-subtle bg-bg-code p-3 font-mono text-code text-text-code",children:Be("code",{children:l.join(`
|
|
72
|
+
`)},void 0,!1,void 0,this)},r++,!1,void 0,this));continue}let s=i.match(/^(#{1,4})\s+(.*)$/);if(s){let l=s[1].length,a=l===1?"mt-2 mb-3 font-heading text-section text-text-primary":l===2?"mt-5 mb-2 font-heading text-xl text-text-primary":"mt-4 mb-1 text-task-label font-semibold text-text-secondary uppercase tracking-wide";n.push(Be("div",{className:a,children:Lr(s[2])},r++,!1,void 0,this)),o++;continue}if(/^[-*]\s+/.test(i)){let l=[];while(o<t.length&&/^[-*]\s+/.test(t[o]))l.push(t[o].replace(/^[-*]\s+/,"")),o++;n.push(Be("ul",{className:"my-2 list-disc space-y-1 pl-5 text-body text-text-secondary",children:l.map((a,c)=>Be("li",{children:Lr(a)},c,!1,void 0,this))},r++,!1,void 0,this));continue}if(/^\d+\.\s+/.test(i)){let l=[];while(o<t.length&&/^\d+\.\s+/.test(t[o]))l.push(t[o].replace(/^\d+\.\s+/,"")),o++;n.push(Be("ol",{className:"my-2 list-decimal space-y-1 pl-5 text-body text-text-secondary",children:l.map((a,c)=>Be("li",{children:Lr(a)},c,!1,void 0,this))},r++,!1,void 0,this));continue}if(i.trim()===""){o++;continue}n.push(Be("p",{className:"my-2 text-body leading-relaxed text-text-secondary",children:Lr(i)},r++,!1,void 0,this)),o++}return Be("div",{className:"select-text",children:n},void 0,!1,void 0,this)}import{jsxDEV as _,Fragment as oa}from"react/jsx-dev-runtime";function Ku({state:e,focused:t,isCurrentGate:n}){let o=Pi(t),r=Ln(t,e.completed,e.current),i=r==="current",s=i&&e.reads.length?e.reads.join(", "):o.reads.join(", "),l=i&&e.produces.length?e.produces.join(", "):o.produces.join(", ");return _("div",{className:"border-b border-border-subtle px-6 py-4",children:[_("div",{className:"flex items-center gap-3",children:[_("h1",{className:"font-heading text-section text-text-primary",children:["Phase ",o.number,"/",Cr," — ",o.label]},void 0,!0,void 0,this),_("span",{className:["rounded px-2 py-0.5 text-tiny uppercase tracking-wide",r==="done"?"bg-accent-green-muted text-accent-green":r==="current"?"bg-accent-amber-muted text-accent-amber":"border border-border-medium text-text-tertiary"].join(" "),children:r},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_("dl",{className:"mt-3 grid grid-cols-[5rem_1fr] gap-x-3 gap-y-1.5 text-body",children:[_("dt",{className:"text-text-tertiary",children:"Read"},void 0,!1,void 0,this),_("dd",{className:"min-w-0 break-words font-mono text-code text-text-secondary",children:s},void 0,!1,void 0,this),_("dt",{className:"text-text-tertiary",children:"Goal"},void 0,!1,void 0,this),_("dd",{className:"min-w-0 break-words text-text-secondary",children:l},void 0,!1,void 0,this),_("dt",{className:"text-text-tertiary",children:"Gate"},void 0,!1,void 0,this),_("dd",{className:"min-w-0 break-words font-mono text-code text-text-secondary",children:o.gate?_(oa,{children:["fabrika builder gate open ",t," --view view.jsx && fabrika builder gate wait"]},void 0,!0,void 0,this):o.reviewedAt?_("span",{className:"text-text-tertiary",children:["— (reviewed at the ",o.reviewedAt," gate)"]},void 0,!0,void 0,this):_("span",{className:"text-text-tertiary",children:"— (ungated compile step)"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),n&&_("div",{className:"mt-3 flex items-start gap-2 rounded-md bg-accent-amber-muted/60 px-3 py-2 text-tiny text-accent-amber",children:[_("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",className:"mt-px shrink-0",children:_("path",{d:"M12 9v4m0 4h.01M10.3 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.7 3.86a2 2 0 0 0-3.42 0Z",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_("span",{children:[_("strong",{className:"font-semibold",children:"Gate open."},void 0,!1,void 0,this)," Review the canvas — select text or hover a block to annotate, answer the choices, then"," ",_("strong",{className:"font-semibold",children:"Submit"},void 0,!1,void 0,this)," in the panel on the right. That feedback is what"," ",_("span",{className:"font-mono",children:"fabrika builder gate wait"},void 0,!1,void 0,this)," hands back to the active agent."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Vu({sessionId:e,live:t,upcoming:n}){let[o,r]=na(null);ta(()=>{if(!t)return;let s=!1;return Pe.skeletons(e).then((l)=>{if(!s)r(l)}),()=>{s=!0}},[e,t]);let i=o??[];return _("div",{className:"p-6",children:[n&&_("p",{className:"mb-4 text-body text-text-tertiary",children:["Not reached yet — once the tech gate is approved, this phase turns each user flow into an opice ",_("span",{className:"font-mono",children:"*.test.ts"},void 0,!1,void 0,this)," ","skeleton (the acceptance contract), reviewed here as a grid."]},void 0,!0,void 0,this),t&&i.length===0&&_("p",{className:"text-body text-text-tertiary",children:["No skeletons in ",_("span",{className:"font-mono",children:"tests/browser/"},void 0,!1,void 0,this)," yet. Author them with the ",_("span",{className:"font-mono",children:"opice-plan"},void 0,!1,void 0,this)," ","skill, then ",_("span",{className:"font-mono",children:"fabrika builder induce"},void 0,!1,void 0,this),"."]},void 0,!0,void 0,this),_("div",{className:"grid grid-cols-2 gap-3",children:i.map((s)=>_("div",{className:"rounded-md border border-border-subtle bg-bg-surface p-4 transition-colors hover:border-border-hover",children:[_("div",{className:"font-mono text-code text-text-primary",children:s.file},void 0,!1,void 0,this),_("div",{className:"mt-1 truncate text-body text-text-secondary",children:s.name},void 0,!1,void 0,this),_("div",{className:"mt-2 flex flex-wrap gap-x-3 gap-y-1 text-tiny text-text-tertiary",children:[s.url&&_("span",{className:"font-mono",children:s.url},void 0,!1,void 0,this),_("span",{children:[s.steps," steps"]},void 0,!0,void 0,this),_("span",{children:[s.invariants," invariants"]},void 0,!0,void 0,this),s.pending>0?_("span",{className:"text-accent-amber",children:[s.pending," pending"]},void 0,!0,void 0,this):_("span",{className:"text-accent-green",children:"authored"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(s.seeds.length>0||s.roles.length>0)&&_("div",{className:"mt-2 flex flex-wrap gap-1",children:[s.seeds.map((l)=>_("span",{className:"rounded bg-bg-elevated px-1.5 py-0.5 text-tiny text-text-secondary",children:["seed:",l]},l,!0,void 0,this)),s.roles.map((l)=>_("span",{className:"rounded bg-bg-elevated px-1.5 py-0.5 text-tiny text-text-secondary",children:["role:",l]},l,!0,void 0,this))]},void 0,!0,void 0,this)]},s.file,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Gu({live:e}){let[t,n]=na([]);ta(()=>{if(!e)return;let r=Pe.buildStream((i)=>n((s)=>[...s.slice(-200),i]));return()=>r?.close()},[e]);let o={queued:"bg-text-tertiary",running:"bg-accent-blue",passed:"bg-accent-green",failed:"bg-accent-red",blocked:"bg-accent-amber",info:"bg-text-tertiary"};return _("div",{className:"p-6",children:[_("h2",{className:"mb-3 font-heading text-section text-text-primary",children:"Build"},void 0,!1,void 0,this),t.length===0?_("p",{className:"text-body text-text-tertiary",children:["Waiting for build events. Run ",_("span",{className:"font-mono",children:"fabrika builder build"},void 0,!1,void 0,this)," to drive the per-issue pipeline; each"," ",_("span",{className:"font-mono",children:"build done/block"},void 0,!1,void 0,this)," posts here."]},void 0,!0,void 0,this):_("ul",{className:"space-y-1.5 font-mono text-code",children:t.map((r,i)=>_("li",{className:"flex items-center gap-2",children:[_("span",{className:`inline-flex h-2 w-2 shrink-0 rounded-full ${o[r.status]}`},void 0,!1,void 0,this),r.issue&&_("span",{className:"text-text-secondary",children:r.issue},void 0,!1,void 0,this),_("span",{className:"text-text-tertiary",children:r.status},void 0,!1,void 0,this),r.message&&_("span",{className:"truncate text-text-secondary",children:["— ",r.message]},void 0,!0,void 0,this)]},i,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Wu({canvas:e}){return _(oa,{children:e.files.map((t)=>_("div",{className:"mb-8",children:[e.files.length>1&&_("div",{className:"mb-2 text-tiny uppercase tracking-wide text-text-tertiary",children:t.label??t.filename},void 0,!1,void 0,this),_(_r,{revision:e.revision,filename:t.filename},void 0,!1,void 0,this)]},t.filename,!0,void 0,this))},void 0,!1,void 0,this)}function ra({state:e,focused:t,canvas:n,artifact:o,isCurrentGate:r,sessionId:i,live:s}){let a=Ln(t,e.completed,e.current)==="upcoming";return _("section",{className:"flex h-full min-w-0 flex-col bg-bg-base",children:[_(Ku,{state:e,focused:t,isCurrentGate:r},void 0,!1,void 0,this),_("div",{id:"plan-scroll-container",className:"flex-1 overflow-y-auto",children:n?_("div",{className:"mx-auto max-w-3xl px-6 py-5",children:_(Wu,{canvas:n},void 0,!1,void 0,this)},void 0,!1,void 0,this):t==="skeletons"?_(Vu,{sessionId:i,live:s,upcoming:a},void 0,!1,void 0,this):t==="build"?_(Gu,{live:s},void 0,!1,void 0,this):_("div",{className:"mx-auto max-w-3xl px-6 py-5",children:[a&&_("p",{className:"mb-4 rounded-md border border-border-subtle bg-bg-surface px-3 py-2 text-tiny text-text-tertiary",children:"This phase hasn't started yet — it unlocks once the earlier gates are approved. Here's what it will produce:"},void 0,!1,void 0,this),_(ea,{source:o},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function sa(e){if(!e)return[];if(e.canvasScope?.kind==="view"){let n=e.canvasScope.filename;return e.canvasFiles.filter((o)=>o.filename===n)}if(e.canvasScope?.kind==="directory")return e.canvasFiles;let t=e.canvasFiles.filter((n)=>!n.diffStats||n.diffStats.added!==0||n.diffStats.removed!==0);return t.length>0?t:e.canvasFiles}var Xu=new Set([...Zt,"design"]);function ia(e,t){for(let n=e.length-1;n>=0;n--){let o=e[n]?.label;if(!o)continue;if(o===t||t==="build"&&!Xu.has(o))return e[n]??null}return null}var aa="fixture-session",is={current:"skeletons",index:4,completed:["intake","vision","flows","tech"],reads:[".fabrika/architecture/flows/checkout.flow.md",".fabrika/architecture/flows/browse.flow.md"],produces:["tests/browser/*.test.ts"],gate:!0,satisfied:!1},la={id:"fixture-session",currentRevision:4,canvasFiles:[{filename:"review-grid.jsx",label:"Skeleton review"}],revisions:[{revision:1,label:"vision",canvasFiles:[{filename:"brief.jsx"}]},{revision:2,label:"flows",canvasFiles:[{filename:"flows-review.jsx"}]},{revision:3,label:"tech",canvasFiles:[{filename:"tech.jsx"}]},{revision:4,label:"skeletons",canvasFiles:[{filename:"review-grid.jsx"}]}],gate:"skeletons",label:"Opice skeletons"};var ca={intake:`# Brief
|
|
73
|
+
|
|
74
|
+
A local-first storefront for a small roastery. Sells whole-bean coffee, supports a cart and checkout, and a lightweight admin to manage the catalog.
|
|
75
|
+
|
|
76
|
+
## Users
|
|
77
|
+
- Shopper — browses, adds to cart, checks out.
|
|
78
|
+
- Owner — manages products and reviews orders.
|
|
79
|
+
|
|
80
|
+
## Success
|
|
81
|
+
- A shopper can complete a purchase end-to-end.
|
|
82
|
+
- The owner can add a product without touching code.
|
|
83
|
+
|
|
84
|
+
## Non-goals
|
|
85
|
+
- No multi-tenant. No payment provider integration in v1 (mock checkout).`,vision:`# Glossary
|
|
86
|
+
|
|
87
|
+
- **Product** — a single SKU with a price and inventory count.
|
|
88
|
+
- **Cart** — the shopper's pending selection, persisted locally.
|
|
89
|
+
- **Order** — a submitted cart, immutable once placed.
|
|
90
|
+
|
|
91
|
+
# Principles
|
|
92
|
+
|
|
93
|
+
- MUST keep the catalog readable without an account.
|
|
94
|
+
- MUST persist the cart across reloads.
|
|
95
|
+
- MUST NOT block checkout on network for the mock flow.
|
|
96
|
+
- PREFERENCE: optimistic UI on add-to-cart.`,flows:`# Flow: checkout
|
|
97
|
+
|
|
98
|
+
1. Shopper opens \`/cart\`.
|
|
99
|
+
2. Reviews line items, adjusts quantities.
|
|
100
|
+
3. Submits → \`/order/confirmation\`.
|
|
101
|
+
|
|
102
|
+
# Flow: browse
|
|
103
|
+
|
|
104
|
+
1. Shopper lands on \`/\`.
|
|
105
|
+
2. Filters by roast level.
|
|
106
|
+
3. Opens a product → adds to cart.`,tech:`# Tech
|
|
107
|
+
|
|
108
|
+
Stack: **zerops-app** (Bun + PostgreSQL + React/Buzola, Fabrika IAM behind the proxy).
|
|
109
|
+
|
|
110
|
+
- Routes: the contract's mounts and the SPA.
|
|
111
|
+
- Data layer: @fabrika/db over PostgreSQL + named SQL fixtures from skeleton metadata.
|
|
112
|
+
- Reasoning: the paved road the installation deploys.`,skeletons:"# Opice skeletons\n\nOne `*.test.ts` per flow, each a metadata-first `browserTest` with pending `step{intent,hint}` stubs and `invariant.todo` acceptances. Reviewed as a grid in the workspace.",issues:`# Issues (induced)
|
|
113
|
+
|
|
114
|
+
Deterministic compile step — issues induced from skeleton metadata.
|
|
115
|
+
|
|
116
|
+
- ISSUE-001 Foundation: routes + seed infra.
|
|
117
|
+
- ISSUE-004 Design checkpoint: theme the running app, reviewed at the design gate.
|
|
118
|
+
- ISSUE-101 Feature: cart + checkout vertical slice.`,build:`# Build
|
|
119
|
+
|
|
120
|
+
Per-issue assisted pipeline. The live-preview pane (right) will host the real running app (localhost:5173) once an issue is in flight.`};var Ju=hr.extend({generalNote:v(),annotations:ae(so.pick({id:!0,snippet:!0,note:!0,createdAt:!0}).passthrough()),responses:ae(wn([v(),mr.innerType().pick({id:!0,type:!0,label:!0}).extend({type:v()}).passthrough()])),feedbackEntries:ae(wn([v(),gr.pick({id:!0,markdown:!0}).passthrough()])).optional()});function ua(e){let t=Ju.safeParse(e);return t.success?Ut(t.data):null}class He extends Error{}function Yu(e=fetch){async function t(n,o,r,i){let s;try{s=await e(Zi(n,o),{method:r?"POST":"GET",headers:{accept:"application/json",...r?{"content-type":"application/json"}:{}},...r?{body:JSON.stringify(r)}:{},redirect:"error",cache:"no-store",signal:i?AbortSignal.any([i,AbortSignal.timeout(1e4)]):AbortSignal.timeout(1e4)})}catch{throw new He("Local builder unavailable. Check the daemon and refresh status.")}let l;try{l=await s.json()}catch{throw new He("Local builder returned an invalid response. Refresh status before continuing.")}if(!s.ok){let a=Hi.safeParse(l);if(a.success)throw new He(a.data.error.message);throw new He("Local builder rejected the request. Refresh status before continuing.")}try{let a=Qi(l);if(a.sessionId!==n)throw Error("Session mismatch");return a}catch{throw new He("Local builder returned an invalid status. Refresh status before continuing.")}}return{status:(n,o)=>t(n,"platform",void 0,o),register:(n,o)=>t(n,"register",{projectRoot:o}),act:(n,o,r)=>{let i={};try{if(o.kind==="connect")i={controlOrigin:tn(o.controlOrigin)};if(o.kind==="preview")i={url:o.url===null?null:$n(o.url)}}catch{throw new He("Enter a valid URL without credentials. Control origins require HTTPS except on localhost.")}return t(n,o.kind,i,r)}}}var jn=Yu();import{useEffect as da,useRef as Qu,useState as Fn}from"react";function pa(e,t){let[n,o]=Fn(e),[r,i]=Fn(null),[s,l]=Fn(null),[a,c]=Fn(!1),[u,d]=Fn(0),f=Qu(null);da(()=>(o(e),i(null),l(null),c(!1),d(0),()=>{f.current?.abort(),f.current=null}),[e]),da(()=>{if(n!==e||!t||a||s)return;let h=new AbortController,y,A=0,b=async()=>{try{if(++A>1200)throw new He("Automatic status refresh paused. Refresh status to continue.");let g=await jn.status(e,h.signal);if(h.signal.aborted)return;i(g),l(null),y=setTimeout(b,3000)}catch(g){if(!h.signal.aborted)l(g instanceof He?g.message:"Unable to read local deployment status.")}};return b(),()=>{h.abort(),clearTimeout(y)}},[e,n,t,a,u,s]);let p=n===e,m=p&&t&&r!==null&&s===null&&!a;return{data:p?r:null,error:p?s:null,busy:p&&a,enabled:m,refresh:()=>{i(null),l(null),d((h)=>h+1)},act:async(h)=>{if(!m||f.current)return;let y=new AbortController;f.current=y,c(!0);try{let A=await jn.act(e,h,y.signal);if(!y.signal.aborted)i(A)}catch(A){if(!y.signal.aborted)l(A instanceof He?A.message:"Local operation failed. Refresh status.")}finally{if(f.current===y){if(f.current=null,!y.signal.aborted)c(!1)}}}}}import{jsxDEV as Oe}from"react/jsx-dev-runtime";function Zu(e){return e==="build"}var ma={current:"intake",index:0,completed:[],reads:[],produces:[],gate:!1,satisfied:!1},ed="_Nový projekt — zatím žádný krok. Otevři první gate z agenta._";function ga(){let e=Mr()??aa,[t,n]=Tt("connecting"),o=pa(e,t==="live"),[r,i]=Tt(ma),[s,l]=Tt(null),[a,c]=Tt(!1),[u,d]=Tt(ma.current),[f,p]=Tt(!1),m=ls(!1),h=ls(null),y=ls(void 0);fa(()=>{let I=!1;return(async()=>{try{if(await Pe.health(),I)return;let N=new URLSearchParams(location.search).get("root");if(N?.endsWith("/.fabrika"))await jn.register(e,N.slice(0,-9));let K=await Pe.meta(e);if(I)return;if(K)l(K),y.current=K.projectRoot?`${K.projectRoot}/.fabrika`:void 0;let P=await Pe.phase(y.current);if(I)return;if(P){if(i(P),!m.current)d(P.current)}n("live")}catch{if(!I){if(Mr()){n("offline");return}if(l(la),i(is),!m.current)d(is.current);n("fixture")}}})(),()=>{I=!0}},[e]);let A=s!==null&&(t==="live"||t==="offline");fa(()=>{if(!A)return;let I=!1,N=null,K=()=>{Pe.meta(e).then((L)=>l(L)).catch(()=>{}),Pe.phase(y.current).then((L)=>{if(i(L),!m.current)d(L.current)}).catch(()=>{})},P=()=>{let L=Pe.openSocket(e,(w)=>{if(w.type==="plan-updated"||w.type==="revision-updated")p(!1),K();else if(w.type==="watcher-status")c(w.watching);else if(w.type==="phase-updated")p(!1),K();else if(w.type==="submit-ack")p(!1),K()});h.current=L,L.onopen=()=>n("live"),L.onclose=()=>{if(I)return;n("offline"),N=setTimeout(P,2000)}};return P(),()=>{if(I=!0,N)clearTimeout(N);h.current?.close(),h.current=null}},[A,e]);let[b,g]=Tt({type:"overview"}),B=(I)=>{m.current=!0,d(I)},D=(I,N)=>{let K=h.current;if(K&&Pe.submitGate(K,I,N))p(!0)},H=t==="live",T=as(()=>s?ia(s.revisions,u):null,[s,u]),U=r.gateName??s?.gate??null,M=H&&u===r.current&&!!U,q=as(()=>sa(T),[T]),oe=H&&!!T&&q.length>0,ne=T?.revision??s?.currentRevision??0,ie=s?.currentRevision??0,ke=M&&!!T?.hasFeedback&&!T?.feedbackConsumed,re=!M||M&&(f||ke),Z=t==="fixture"?ca[u]??"_No artifact for this phase yet._":ed,ue=as(()=>(s?.revisions??[]).map((I)=>({revision:I.revision,label:I.label??void 0,canvasFiles:I.canvasFiles.map((N)=>({filename:N.filename})),createdAt:I.createdAt??new Date().toISOString(),hasFeedback:!!I.hasFeedback,feedbackConsumed:!!I.feedbackConsumed})),[s]),ee=Zu(u),fe=Oe("div",{className:`grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)] ${ee?"grid-cols-[14rem_minmax(0,1fr)_22rem_auto]":"grid-cols-[14rem_minmax(0,1fr)_auto]"}`,children:[Oe(Oi,{state:r,focused:u,onFocus:B},void 0,!1,void 0,this),Oe(ra,{state:r,focused:u,canvas:oe?{revision:ne,files:q}:null,artifact:Z,isCurrentGate:M,sessionId:e,live:H},void 0,!1,void 0,this),ee&&Oe(Ni,{previewUrl:o.data?.previewUrl??null},void 0,!1,void 0,this),Oe(_i,{gateName:U,hasGate:oe,isCurrentGate:M,onSubmit:D},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return Oe("div",{className:"flex h-screen w-screen flex-col overflow-hidden bg-bg-base text-text-primary",children:[Oe(Ti,{sessionId:e,status:t,watching:a},void 0,!1,void 0,this),Oe(Ci,{platform:o,live:H},void 0,!1,void 0,this),t==="offline"&&Oe("p",{role:"alert",className:"px-6 py-2 text-body text-accent-amber",children:"Project unavailable. Check the local daemon, then reload this page."},void 0,!1,void 0,this),oe?Oe(Ko.Provider,{value:e,children:Oe(Gt.Provider,{value:{currentRevision:ie,selectedRevision:ne,revisions:ue,setSelectedRevision:()=>{},isReadOnly:re,compareRevision:null,setCompareRevision:()=>{},agentWatching:a},children:Oe(Vt.Provider,{value:{activeView:b,setActiveView:g,openFiles:[],closeFile:()=>{},canvasFiles:q.map((I)=>I.filename)},children:Oe(yr,{sessionId:e,revision:ne,isReadOnly:re,draftPhase:"current",loadState:(I,N)=>Pe.getResponses(I,N,ua),saveState:(I,N,K)=>{Pe.saveResponses(I,N,K)},children:fe},ne,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this):fe]},void 0,!0,void 0,this)}import{jsxDEV as nd}from"react/jsx-dev-runtime";var ha=document.getElementById("root");if(ha===null)throw Error("Builder dashboard root element is missing");td(ha).render(nd(ga,{},void 0,!1,void 0,this));
|