@warmhub/sdk-ts 0.162.0 → 0.163.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +5 -5
- package/changelog.json +10 -0
- package/dist/checkpoint.d.ts +101 -29
- package/dist/checkpoint.js +1 -1
- package/dist/checkpoint.js.map +1 -1
- package/dist/chunk-C2brwOhe.js +37 -0
- package/dist/chunk-C2brwOhe.js.map +1 -0
- package/dist/chunk-DvEqOqwB.js +2 -0
- package/dist/chunk-DvEqOqwB.js.map +1 -0
- package/dist/index.d.ts +10472 -10198
- package/dist/index.js +1 -2
- package/dist/react.d.ts +39 -35
- package/dist/react.js +1 -1
- package/dist/react.js.map +1 -1
- package/package.json +6 -7
- package/dist/chunk-BL6W7226.js +0 -34
- package/dist/chunk-BL6W7226.js.map +0 -1
- package/dist/chunk-XUGC6JZH.js +0 -10
- package/dist/chunk-XUGC6JZH.js.map +0 -1
- package/dist/index.js.map +0 -1
package/dist/chunk-XUGC6JZH.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import {A,_ as _$1,a,g as g$1,c,f as f$1,h,Aa,xa,sa,ta,ua,wa as wa$1,C as C$1,F as F$1,D as D$1,E as E$1,G as G$1,i,N as N$1,O,t,o,p as p$1,w,u,v,s,y as y$1,n,r,Z as Z$1,j as j$1,za,ya,va,qa,m,da,B,q,x,ea,d,e,ra,b}from'./chunk-BL6W7226.js';import {TRPCClientError,createTRPCProxyClient,splitLink,httpBatchLink,httpLink}from'@trpc/client';import {observable}from'@trpc/server/observable';import {z}from'zod';function Dt(n,e){let{childContext:t,onStringValue:r,onObjectKey:i}=e,o=[{value:n,context:e.rootContext}];for(;o.length>0;){let{value:s,context:a}=o.pop();if(typeof s=="string"){r(s,a);continue}if(Array.isArray(s)){for(let l=s.length-1;l>=0;l--)o.push({value:s[l],context:t(a,l)});continue}if(!j$1(s))continue;let u=Object.entries(s).map(([l,d])=>[l,t(a,l),d]);if(i)for(let[l,d]of u)i(l,d);for(let l=u.length-1;l>=0;l--){let d=u[l];d&&o.push({value:d[2],context:d[1]});}}}var g=class extends Error{code;status;hint;retryAfter;errorCode;backendCode;details;constructor(e,t,r,i,o,s,a){super(t),this.name="WarmHubError",this.code=e,this.status=r,this.hint=i,this.retryAfter=o,this.errorCode=s,this.backendCode=s,this.details=a;}get kind(){return this.code}};function Y(n){return n.keepShapes===true}var D=Symbol.for("warmhub.sdk.queuedOperations");function J(n){return typeof n=="object"&&n!==null&&typeof n[D]=="function"}function Gr(n){return g$1(n)}var y=class extends g{operationIndex;constructor(e,t,r="VALIDATION_ERROR"){super(r,e===void 0?t:`Invalid operation at index ${e}: ${t}`,r==="NOT_FOUND"?404:400),this.operationIndex=e;}},Kr="DEPENDENCY_FAILED",Me="`shapes` takes bare Shape names; writes always certify under the Shape's head version.",ge=["expectedVersion","leaseId"],Mt={add:new Set(["operation","name","shapes","data","affirmedTargets","skipExisting","file"]),revise:new Set(["operation","name","shapes","data","affirmedTargets","file",...ge,"keepShapes"]),retract:new Set(["operation","name","reason",...ge]),reaffirm:new Set(["operation","name","add","remove",...ge]),rename:new Set(["operation","name","newName"]),restore:new Set(["operation","name","newName",...ge])},jr=new Set(Object.keys(Mt)),zr=/@v\d+$/;function qe(n){return zr.test(n)}function qt(n){return typeof n=="string"&&n.length>0&&n.trim()===n&&!n.includes("/")&&!c(n)}function Lt(n,e,t){if(typeof n!="string"||n.length===0)throw new y(t,`'${e}' must be a non-empty name`);return n}function L(n,e,t=false){if(typeof n!="object"||n===null)throw new y(e,"an operation must be an object");if(Object.hasOwn(n,"shapeless"))throw new y(e,"shapeless is a builder option; a raw operation states a shapeless write as shapes: []");let r=n;if(typeof r.operation!="string"||!jr.has(r.operation))throw new y(e,"'operation' must be one of add, revise, retract, restore, reaffirm, rename");let i=Lt(r.name,"name",e);if(r.operation==="rename"){let a=Lt(r.newName,"newName",e);if(f$1(i)!==f$1(a))throw new y(e,`a Shape renames to a Shape: rename "${i}" to hub/shapes/<Name>, and a Thing to a Thing name`)}if((r.operation==="add"||r.operation==="revise")&&(Qr(r,i,e),r.data===void 0))throw new y(e,`${r.operation} requires 'data'`);if(r.operation==="add"&&r.expectedVersion!==void 0)throw new y(e,"expectedVersion is only valid on revise, retract, restore, or reaffirm operations");let o=Mt[r.operation],s=Object.keys(r).find(a=>r[a]!==void 0&&!o?.has(a));if(s!==void 0)throw new y(e,`unknown key "${s}" on a ${r.operation} operation`);return Jr(r,i,e),t&&r.operation==="add"?{...r,skipExisting:true}:r}function Qr(n,e,t){if(n.keepShapes!==void 0){if(n.operation!=="revise"||n.keepShapes!==true)throw new y(t,"keepShapes applies only to a revise: an add states its shapes, or shapeless");if(n.shapes!==void 0)throw new y(t,"state Shapes one way: shapes, shapeless, or keepShapes");return}let r=n.shapes;if(!Array.isArray(r))throw new y(t,`${String(n.operation)} "${e}" states no Shapes: pass shapes: ['Shape', ...], shapeless, or (revise only) keepShapes`);for(let i of r){if(typeof i=="string"&&qe(i))throw new y(t,Me);if(!qt(i))throw new y(t,`shapes holds bare Shape names ('Deal'); got ${JSON.stringify(i)}`)}if(f$1(e)&&r.length>0)throw new y(t,`"${e}" is a Shape: write it with shapes: []`);if(r.length===0&&n.affirmedTargets!==void 0)throw new y(t,"affirmedTargets needs a Shape that composes Assertion; a shapeless write has none")}var Yr=n=>`Name "${n}" contains reserved character "+". The "+" character is reserved for the historical collection auto-name namespace and is not allowed in user-supplied names.`;function Jr(n,e$1,t){let r=h(e$1);if(r!==void 0){let o=typeof n.newName=="string"?h(n.newName)??n.newName:void 0,s=ea({operation:n.operation,kind:"shape",name:r,...o!==void 0?{newName:o}:{}},t)[0];if(s)throw new y(t,s.message,s.code);return}if(n.operation==="restore"&&typeof n.newName=="string"&&f$1(n.newName)){let o=ea({operation:"restore",name:e$1,newName:n.newName},t)[0];if(o)throw new y(t,o.message,o.code);return}let i=n.operation==="add"?e$1:(n.operation==="rename"||n.operation==="restore")&&typeof n.newName=="string"?n.newName:void 0;if(i!==void 0){if(d(i))throw new y(t,e(i),"RESERVED_NAME");if(i.includes("+"))throw new y(t,Yr(i))}}function X(n,e=0){let t=new Set;n.forEach((r,i)=>{if(r.operation==="add"){if(t.has(r.name))throw new y(e+i,`Cannot add "${r.name}" twice in the same commit`,"ILLEGAL_OP_SEQUENCE");t.add(r.name);}});}var Ut=500;function U(n){let e=new Map,t=new Set;return async(r,i=0)=>{let o=new Set,s=new Set;for(let u of r){Y(u)&&!s.has(u.name)&&!t.has(u.name)&&!e.has(u.name)&&o.add(u.name);for(let l of Bt(u))s.add(l);}let a=await Xr([...o],n);return r.map((u,l)=>{if(!Y(u)){if(u.operation==="revise")e.set(u.name,u.shapes);else if(u.operation==="add"||u.operation==="rename")for(let S of Bt(u))t.add(S);return u}if(t.has(u.name))throw new y(i+l,`keepShapes revise "${u.name}": an earlier operation in this submission adds or renames it, so its Shapes are not known until that commits; submit it in a later request, or pass \`shapes\``);let{keepShapes:d,...m}=u,h=e.get(u.name);if(h!==void 0)return {...m,shapes:h};let b=a.get(u.name);if(b===void 0)throw new y(i+l,`keepShapes revise "${u.name}": no such Thing`,"NOT_FOUND");return e.set(u.name,b.shapes),{...m,shapes:b.shapes,expectedVersion:u.expectedVersion??b.version}})}}function Bt(n){return n.operation==="rename"?[n.name,n.newName]:n.operation==="add"||n.operation==="revise"?[n.name]:[]}async function Xr(n,e){let t=new Map;for(let r=0;r<n.length;r+=Ut){let i$1=n.slice(r,r+Ut),o=await e(i$1),s=new Set(o.missing),a=i$1.filter(u=>!s.has(u));if(a.length!==o.items.length)throw new Error(`keepShapes read returned ${o.items.length} items for ${a.length} found targets`);a.forEach((u,l)=>{let d=o.items[l];d!==void 0&&t.set(u,{shapes:d.declaredShapes.map(m=>i(m)),version:d.version});});}return t}var Zr=1e4,Ue=4*1024*1024,V=class extends Error{code="VALIDATION_ERROR";status=400;constructor(e,t){super(`Invalid operation at index ${e}: ${t}`),this.name="WarmHubError";}};function en(n,e){if(typeof n.name!="string"||n.name.length===0)throw new V(e,`${String(n.operation)} requires 'name'`);return n.name}function Vt(n,e,t){let r=n[t];if(typeof r!="number"||!Number.isInteger(r)||r<1)throw new V(e,`${String(n.operation)} requires a positive integer '${t}'`);return r}function tn(n,e){let t=en(n,e);if(n.operation==="remove")return {operation:"remove",name:t,expectedVersion:Vt(n,e,"expectedVersion")};let r=n.data;if(typeof r!="object"||r===null||Array.isArray(r))throw new V(e,"rewrite requires 'data', the complete replacement body as an object");let i=n.shapes;if(!Array.isArray(i)||i.some(o=>typeof o!="string"||o.length===0))throw new V(e,"rewrite requires 'shapes', the version's declared Shapes plus CorrectedThing");return {operation:"rewrite",name:t,version:Vt(n,e,"version"),shapes:i,data:r}}var Ht=n=>{let e=typeof n=="object"&&n!==null?n.operation:void 0;return e==="remove"||e==="rewrite"},Be=n=>!Ht(n);function Ft(n,e){let r=(J(n)?n[D]():n).map((i,o)=>Ht(i)?tn(i,o):L(i,o,e===true));return X(r.filter(Be)),r}async function rn(n,e){let t=(await n(e.filter(Be))).values();return e.map(r=>Be(r)?t.next().value:r)}async function Wt(n,e,t,r,i,o){let s=Ft(i,o?.skipExisting),a=U(e),u={...$t(t,r,[],o),operations:await rn(a,s)},l=Kt(u);if(l>Ue)throw new g("VALIDATION_ERROR",`Commit validation request exceeds the ${Ue}-byte encoded limit (${l} bytes).`,413,"Split the preview into smaller current-commit units.");return await n.mutate(u,{signal:o?.signal})}function $t(n,e,t,r){return {orgName:n,repoName:e,...r?.committer!==void 0?{committer:r.committer}:{},...r?.message!==void 0?{message:r.message}:{},...r?.componentRef!==void 0?{componentRef:r.componentRef}:{},operations:Ft(t,r?.skipExisting),...r?.includeWouldBeBody!==void 0?{includeWouldBeBody:r.includeWouldBeBody}:{}}}function Gt(n){return JSON.stringify(n)}function Kt(n){return new TextEncoder().encode(Gt(n)).byteLength}function ye(n){let e=new Set;return Dt(n,{rootContext:{key:null,parentKey:null,insideData:false},childContext:(t,r)=>({key:r,parentKey:t.key,insideData:t.insideData||r==="data"}),onStringValue:(t,r)=>{if(r.key==="durableId"&&r.parentKey==="metadata"&&!r.insideData)return;let i=b(t);i&&e.add(i.durableId);}}),e}async function jt(n,e){let t=[...n],r={};for(let i=0;i<t.length;i+=500){let{items:o}=await e(t.slice(i,i+500));for(let s of o)r[s.durableId]=s.canonicalWref;}return r}function Ve(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function an(n){if(!Ve(n))return;let e=n.decorations;return Ve(e)?e:void 0}function pn(n){let e=n instanceof Error?n:new Error(String(n));return Object.assign(e,{decorationFailure:true})}function zt(n){return ()=>({op:e,next:t})=>!n.enabled||e.type!=="query"||e.path==="thing.names"||e.path==="thing.headVersions"?t(e):observable(r=>{let i=false,o=false,s=false,a=()=>{!i&&o&&!s&&r.complete();},u=t(e).subscribe({next:l=>{let d=l.result?.data;if(!Ve(d)){r.next(l);return}let m=ye(d);if(m.size===0){r.next(l);return}s=true,jt(m,n.lookupNames).then(h=>{i||r.next({...l,result:{...l.result,data:{...d,decorations:h}}});}).catch(h=>{i||r.error(TRPCClientError.from(pn(h)));}).finally(()=>{s=false,a();});},error:l=>r.error(l),complete:()=>{o=true,a();}});return ()=>{i=true,u.unsubscribe();}})}function Qt(n,e){return {create:async(t,r,i)=>{try{return await n().grant.create.mutate({orgName:t,repoName:r,...i})}catch(o){throw e(o)}},get:async(t,r,i)=>{try{return await n().grant.get.query({orgName:t,repoName:r,grantId:i})}catch(o){throw e(o)}},list:async(t,r,i)=>{try{return await n().grant.list.query({orgName:t,repoName:r,limit:i?.limit,cursor:i?.cursor})}catch(o){throw e(o)}},revoke:async(t,r,i,o)=>{try{return await n().grant.revoke.mutate({orgName:t,repoName:r,grantId:i,reason:o?.reason})}catch(s){throw e(s)}}}}function Z(n,e,t){let r=za(e,t==="revise"?{allowUnsafeFieldNamePaths:ya(e)}:void 0);return r.valid?null:`Invalid shape definition for "${n}": ${r.errors.join("; ")}`}var H=class{receipts=[];operations=[];uploads=[];statusCounts={applied:0,noop:0,error:0};get allFailed(){return this.operations.length>0&&this.statusCounts.error===this.operations.length}addChunk(e){for(let t of e.receipt.operations)this.statusCounts[t.status]++,this.operations.push({...t,opIndex:e.chunkStart+t.opIndex});for(let t of e.uploads??[])this.uploads.push({...t,opIndex:e.chunkStart+t.opIndex});}addReceipt(e){this.receipts.push(e);}completedOperations(){return this.operations.filter(e=>e.status!=="error")}completedUploads(){return [...this.uploads]}toResult(e){let t=this.statusCounts.error>0;return {...e.committer!==void 0?{committer:e.committer}:{},...e.createdByEmail!==void 0?{createdByEmail:e.createdByEmail}:{},message:e.message,operationCount:this.operations.length,...e.repoSeq!==void 0?{repoSeq:e.repoSeq}:{},...t?{partial:t,statusCounts:{...this.statusCounts}}:{},operations:this.operations,receipts:this.receipts,...this.uploads.length>0?{uploads:this.uploads}:{}}}};function F(){let n=globalThis.crypto?.randomUUID?.();if(!n)throw new Error("This runtime cannot mint a cryptographically secure UUID");return n.toLowerCase()}var ln=F;var fe=1e3,Re=1e4,k=class extends Error{code="PARTIAL_STREAM_SUBMISSION";completedReceipts;completedOperations;uploads;submissionId;eventRequestId;chunkOrdinal;pendingOutcome;acknowledgedOperationCount;lastAcknowledgedRepoSeq;attemptedAppendOutcome;cause;constructor(e){super(e.pendingOutcome==="unknown"?`Stream submission outcome is unknown for event request ${e.eventRequestId}. Look up its immutable receipt before retrying.`:`Stream submission stopped at event request ${e.eventRequestId} after earlier chunks committed.`),this.name="WarmHubError",this.cause=e.cause,this.completedReceipts=e.completedReceipts,this.completedOperations=e.completedOperations??[],this.uploads=e.uploads??[],this.submissionId=e.submissionId,this.eventRequestId=e.eventRequestId,this.chunkOrdinal=e.chunkOrdinal,this.pendingOutcome=e.pendingOutcome,this.acknowledgedOperationCount=e.acknowledgedOperationCount??e.completedReceipts.length,this.attemptedAppendOutcome=e.attemptedAppendOutcome,e.lastAcknowledgedRepoSeq!==void 0&&(this.lastAcknowledgedRepoSeq=e.lastAcknowledgedRepoSeq);}},_=class extends Error{code;receipts;result;operations;statusCounts;cause;constructor(e){let t=e.operations.find(r=>r.status==="error")?.errors[0];super(t?`All ${e.operationCount} stream operations failed: ${t.message}`:`All ${e.operationCount} stream operations failed.`),this.name="WarmHubError",this.code=t&&e.operations.every(r=>r.status==="error"&&r.errors.length>0&&r.errors.every(i=>i.code===t.code))?t.code:"STREAM_ALL_OPERATIONS_FAILED",this.cause=t,this.result=e,this.receipts=e.receipts,this.operations=e.operations,this.statusCounts=e.statusCounts??{applied:0,noop:0,error:e.operationCount};}};function He(n){return n.status}function Xt(n){let e={applied:0,noop:0,error:0};for(let t of n)e[He(t)]++;return e}var dn={maxAttempts:3,baseDelayMs:250,maxDelayMs:8e3},mn=10,Yt=6e4;function Fe(n){if(n===false)return false;let e={};n!==void 0&&(Number.isFinite(n.maxAttempts)&&(e.maxAttempts=n.maxAttempts),Number.isFinite(n.baseDelayMs)&&(e.baseDelayMs=n.baseDelayMs),Number.isFinite(n.maxDelayMs)&&(e.maxDelayMs=n.maxDelayMs));let t={...dn,...e};return {maxAttempts:Math.min(mn,Math.max(1,Math.trunc(t.maxAttempts))),baseDelayMs:Math.min(Yt,Math.max(0,Math.trunc(t.baseDelayMs))),maxDelayMs:Math.min(Yt,Math.max(0,Math.trunc(t.maxDelayMs)))}}var hn=new Set(["BAD_REQUEST","METHOD_NOT_SUPPORTED","PARSE_ERROR","PAYLOAD_TOO_LARGE","PRECONDITION_FAILED","UNAUTHORIZED","UNPROCESSABLE_CONTENT","UNSUPPORTED_MEDIA_TYPE","UNAUTHENTICATED","FORBIDDEN","VALIDATION_ERROR","SHAPE_MISMATCH","RESERVED_NAME","ILLEGAL_OP_SEQUENCE","NOT_FOUND","KIND_MISMATCH","CONFLICT","NAME_TAKEN","TARGET_REMOVED","TARGET_REDACTED","ALREADY_RETRACTED","ARCHIVED","RATE_LIMITED","TOO_MANY_REQUESTS","UNRESOLVED_TOKEN"]),gn=new Set(["COMMIT_OUTCOME_UNKNOWN"]);function Zt(n){if(!n||typeof n!="object")return;let e=n.code;if(typeof e=="string")return e;let t=n.data,r=t?.warmhub?.code;if(typeof r=="string")return r;let i=t?.code;if(typeof i=="string")return i}function yn(n){if(!n||typeof n!="object")return;let e=n.data?.httpStatus;if(typeof e=="number")return e;let t=n.data?.warmhub?.status;if(typeof t=="number")return t;let r=n.status;return typeof r=="number"?r:void 0}function fn(n){return n!==void 0&&n>=400&&n<500&&n!==408}function er(n){let e=Zt(n);return e!==void 0&&gn.has(e)}function ee(n){if(er(n))return false;let e=Zt(n);return e!==void 0&&hn.has(e)||fn(yn(n))}function We(n){if(er(n)||ee(n))return false;if(Jt(n))return true;if(n instanceof TypeError||n instanceof SyntaxError)return false;let e=n?.cause;return Jt(e)?true:!(e instanceof TypeError||e instanceof SyntaxError)}function Jt(n){return n instanceof TypeError&&/fetch/i.test(n.message)}function $e(n,e){let t=e.baseDelayMs*2**Math.max(0,n-1),r=Math.random()*e.baseDelayMs;return Math.min(e.maxDelayMs,t+r)}function Ge(n){return new Promise(e=>setTimeout(e,n))}var be=class extends Error{code;status=400;constructor(e,t="VALIDATION_ERROR"){super(e),this.code=t,this.name="WarmHubError";}},Se=class extends Error{constructor(t){super("operation source failed");this.reason=t;}reason};async function W(n,e){let t=Ce(e.chunkSize),r=e.submissionId??F(),i=e.streamId??r,o=Fe(e.retry),s=new H,a,u,l=0,d,m=0,h=U(async R=>{if(!n.thing)throw new be("A keepShapes revise needs the client to read its Thing: this stream client has no thing.getMany");return await n.thing.getMany(e.orgName,e.repoName,R)}),b=R=>new k({cause:R.cause,completedReceipts:s.receipts,completedOperations:s.completedOperations(),uploads:s.completedUploads(),acknowledgedOperationCount:l,lastAcknowledgedRepoSeq:d,attemptedAppendOutcome:R.pendingOutcome==="absent"?"not_applied":"unknown",submissionId:r,eventRequestId:Z$1(r,m),chunkOrdinal:m,pendingOutcome:R.pendingOutcome});try{for await(let R of Rn(e.operations,t,e.skipExisting===!0,h)){let w=R.operations,v=1,x=!1;for(;;)try{let O=await n.stream.append({chunkOrdinal:m,orgName:e.orgName,repoName:e.repoName,streamId:i,submissionId:r,componentRef:e.componentRef,committer:e.committer,message:e.message,...e.returnRepoSeq!==void 0?{returnRepoSeq:e.returnRepoSeq}:{},operations:w});s.addReceipt(O.receipt),a=O.createdByEmail??a,u=O.repoSeq??u,s.addChunk({receipt:O.receipt,chunkStart:R.start,uploads:O.uploads}),l+=R.operations.length;let q=Cn(O.receipt);q!==void 0&&(d=q);break}catch(O){let q=ee(O);if(s.receipts.length===0&&!x&&q)throw O;if(o!==!1&&v<o.maxAttempts&&We(O)){await Ge($e(v,o)),v+=1,x=!0;continue}throw b({cause:O,pendingOutcome:x||!q?"unknown":"absent"})}m+=1;}}catch(R){throw R instanceof Se?s.receipts.length===0?R.reason:b({cause:R.reason,pendingOutcome:"absent"}):R}if(m===0)throw new be("At least one operation is required for stream submission.");let S=s.toResult({committer:e.committer,createdByEmail:a,message:e.message,repoSeq:u});if(s.allFailed)throw new _(S);return S}async function*Rn(n,e,t,r){try{let i=bn(n);if(i!==void 0){let u=i.map((d,m)=>L(d,m,t));X(u);let l=await r(u);for(let d=0;d<l.length;d+=e)yield {operations:l.slice(d,d+e),start:d};return}let o=0,s=[],a=async(u,l)=>await Sn(u,l,r);for await(let u of rr(n,t))s.push(u),o+=1,!(s.length<e)&&(yield await a(s,o),s=[]);s.length>0&&(yield await a(s,o));}catch(i){throw new Se(i)}}function bn(n){if(J(n))return n[D]();if(Array.isArray(n))return n}async function Sn(n,e,t){let r=e-n.length;return X(n,r),{operations:await t(n,r),start:r}}function tr(n){let e=U(n),t=0;return async r=>{let i=t;return t+=r.length,await e(r.map((o,s)=>L(o,i+s)),i)}}async function*rr(n,e){let t=we(n,e);try{for(;;){let r=await t.next();if(r.done)return;yield r.value;}}finally{let r=t.returnSourceOnce();r&&await r;}}function we(n,e){let t,r=0,i=false,o=false,s=()=>{if(t)return t;let a=J(n)?n[D]():n;return t=Symbol.asyncIterator in a?a[Symbol.asyncIterator]():a[Symbol.iterator](),t};return {async next(){let a=await s().next();if(a.done)return o=true,{done:true,value:void 0};let u=L(a.value,r,e);return r+=1,{done:false,value:u}},returnSourceOnce(){if(i||o){i=true;return}return i=true,t?.return?.()}}}function Ke(n){return wn.encode(`${JSON.stringify(n)}
|
|
2
|
-
`)}var wn=new TextEncoder;function Cn(n){let e=n.event?.repoSeq;if(e===void 0)return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0}function Ce(n){return Number.isFinite(n)?Math.max(1,Math.min(Re,Math.trunc(n))):fe}var $=class{ops=[];shapes;submitted=false;inFlight=false;constructor(e){this.shapes=e?.shapes;}add(e,t){this.assertCanModify();let r=this.ops.length,i=this.statedShapes(t,r,"add",e);return this.queue({operation:"add",name:e,shapes:i??[],data:t.data,...t.affirmedTargets!==void 0?{affirmedTargets:[...t.affirmedTargets]}:{},...t.skipExisting===true?{skipExisting:true}:{},...t.file!==void 0?{file:{...t.file}}:{}},t.data),this}revise(e,t){this.assertCanModify();let r=this.ops.length,i=this.statedShapes(t,r,"revise",e),o={data:t.data,...t.affirmedTargets!==void 0?{affirmedTargets:[...t.affirmedTargets]}:{},...t.file!==void 0?{file:{...t.file}}:{},...t.expectedVersion!==void 0?{expectedVersion:t.expectedVersion}:{},...t.leaseId!==void 0?{leaseId:t.leaseId}:{}};return this.queue(i===void 0?{operation:"revise",name:e,keepShapes:true,...o}:{operation:"revise",name:e,shapes:i,...o},t.data),this}retract(e,t={}){return this.assertCanModify(),this.queue({operation:"retract",name:e,...t.reason!==void 0?{reason:t.reason}:{},...t.expectedVersion!==void 0?{expectedVersion:t.expectedVersion}:{},...t.leaseId!==void 0?{leaseId:t.leaseId}:{}}),this}restore(e,t={}){return this.assertCanModify(),this.queue({operation:"restore",name:e,...t.newName!==void 0?{newName:t.newName}:{},...t.expectedVersion!==void 0?{expectedVersion:t.expectedVersion}:{},...t.leaseId!==void 0?{leaseId:t.leaseId}:{}}),this}rename(e,t){return this.assertCanModify(),this.queue({operation:"rename",name:e,newName:t}),this}reaffirm(e,t){return this.assertCanModify(),this.queue({operation:"reaffirm",name:e,...t.add!==void 0?{add:[...t.add]}:{},...t.remove!==void 0?{remove:[...t.remove]}:{},...t.expectedVersion!==void 0?{expectedVersion:t.expectedVersion}:{},...t.leaseId!==void 0?{leaseId:t.leaseId}:{}}),this}get operations(){return Object.freeze([...this.ops])}get size(){return this.ops.length}has(e){return this.ops.some(t=>t.operation==="add"&&t.name===e)}[D](){return this.ops}validate(){let e=[],t=[],r=new Set,i=new Set;return this.ops.forEach((o,s)=>{if(o.operation==="add")r.has(o.name)&&e.push({code:"DUPLICATE_NAME",operationIndex:s,message:`Duplicate name '${o.name}' at index ${s} (already added earlier in commit)`}),r.add(o.name);else if(o.operation==="revise")i.has(o.name)?e.push({code:"REVISE_AFTER_RETRACT",operationIndex:s,message:`Revise at index ${s} targets '${o.name}' which was already retracted in this commit`}):r.has(o.name)||t.push({code:"REVISE_UNKNOWN_WREF",operationIndex:s,message:`Revise at index ${s} references '${o.name}' which was not added in this commit (assuming it exists server-side)`});else if(o.operation==="retract"){if(i.has(o.name)){t.push({code:"RETRACT_AFTER_RETRACT",operationIndex:s,message:`Retract at index ${s} targets '${o.name}' which was already retracted in this commit`});return}r.has(o.name)||t.push({code:"RETRACT_UNKNOWN_WREF",operationIndex:s,message:`Retract at index ${s} references '${o.name}' which was not added in this commit (assuming it exists server-side)`}),i.add(o.name);}else o.operation==="restore"&&i.clear();}),this.ops.length===0&&e.push({code:"EMPTY_COMMIT",operationIndex:-1,message:"OperationBuilder has no operations"}),{valid:e.length===0,errors:e,warnings:t}}async commit(e){if(this.assertNotSubmitted(),this.inFlight)throw new y(void 0,"OperationBuilder: stream submission already in flight");let t=this.validate(),[r]=t.errors;if(r!==void 0){let i=t.errors.map(o=>o.message).join("; ");throw new y(r.operationIndex<0?void 0:r.operationIndex,`OperationBuilder validation failed: ${i}`)}this.inFlight=true;try{let i=await W(e.client,{orgName:e.orgName,repoName:e.repoName,committer:e.committer,message:e.message,chunkSize:e.chunkSize,streamId:e.streamId,submissionId:e.submissionId,returnRepoSeq:e.returnRepoSeq,retry:e.retry,operations:this});return this.submitted=!0,i}catch(i){throw i instanceof k&&(this.submitted=true),i}finally{this.inFlight=false;}}statedShapes(e,t,r,i){let o=[e.shapes!==void 0,e.shapeless!==void 0,e.keepShapes!==void 0].filter(Boolean).length;if(o!==1)throw new y(t,o===0?`${r} states no Shapes: pass shapes: ['Shape', ...], shapeless: true${r==="revise"?", or keepShapes: true":""}`:"state Shapes one way: shapes, shapeless, or keepShapes");if(e.keepShapes!==void 0){if(r==="add"||e.keepShapes!==true)throw new y(t,"keepShapes applies only to a revise: an add states its shapes, or shapeless");return}if(e.shapeless!==void 0){if(e.shapeless!==true)throw new y(t,"shapeless must be true");if(f$1(i))throw new y(t,`"${i}" is a Shape: write it with shapes: [], not shapeless`);return []}let s=[...e.shapes??[]];if(s.length===0&&!f$1(i))throw new y(t,`${r} "${i}" with shapes: [] is the raw spelling of a shapeless write; the builder takes shapeless: true`);return s}queue(e,t){let r=this.ops.length,i=L(e,r),o=h(i.name);if(o!==void 0&&(i.operation==="add"||i.operation==="revise")){let s=Z(o,i.data,i.operation);if(s)throw new y(r,s)}if(this.shapes&&t!==void 0&&(i.operation==="add"||i.operation==="revise")&&"shapes"in i&&i.shapes!==void 0)for(let s of i.shapes){let a=this.shapes[s];if(!a)continue;let u=Aa(t,a);if(!u.valid)throw new y(r,`Shape validation failed for '${i.name}' (shape: ${s}): ${u.errors.join("; ")}`)}this.ops.push(Object.freeze(i));}assertNotSubmitted(){if(this.submitted)throw new y(void 0,"OperationBuilder: already submitted, cannot modify")}assertCanModify(){if(this.assertNotSubmitted(),this.inFlight)throw new y(void 0,"OperationBuilder: stream submission already in flight, cannot modify")}};function nr(n){return {...n,createdAt:new Date(n.createdAt),updatedAt:new Date(n.updatedAt),runStartedAt:new Date(n.runStartedAt),...n.state==="complete"||n.state==="failed"?{completedAt:new Date(n.completedAt)}:{}}}function En(n){return {...n,expiresAt:new Date(n.expiresAt)}}function ir(n){if(typeof n.checkpointId=="string"&&typeof n.repoSeq!="number")return {by:"id",checkpointId:n.checkpointId};if(typeof n.repoSeq=="number"&&typeof n.checkpointId!="string")return {by:"repoSeq",repoSeq:n.repoSeq};throw new TypeError("Repository checkpoint selector must contain exactly one of checkpointId or repoSeq")}function or(n,e){return {status:async(t,r,i)=>{try{let o=await n().repo.checkpoint.status.query({orgName:t,repoName:r,selector:ir(i)});return nr(o)}catch(o){throw e(o)}},latest:async(t,r)=>{try{let i=await n().repo.checkpoint.latest.query({orgName:t,repoName:r});return i.checkpoint?nr(i.checkpoint):null}catch(i){throw e(i)}},getAccess:async(t,r,i)=>{try{let o=await n().repo.checkpoint.access.query({orgName:t,repoName:r,selector:i.checkpoint==="latest"?{by:"latest"}:ir(i.checkpoint),artifact:i.artifact==="archive"||i.artifact==="manifest"?{kind:i.artifact}:{kind:"chunk",path:i.artifact.chunkPath}});return En(o)}catch(o){throw e(o)}}}}var f=class extends Error{constructor(t,r){super(r??In[t]);this.reason=t;}reason;name="RepositoryExportError"},In={count_mismatch:"Repository export trailer record count does not match the rows read",digest_mismatch:"Repository export content digest does not match the trailer",fence_mismatch:"Repository export header and trailer disagree about atRepoSeq",format_mismatch:"Repository export delta and base use different format versions; take a fresh full export",header_invalid:"Repository export header is invalid",row_invalid:"Repository export row is invalid or not canonical",row_out_of_order:"Repository export rows are not strictly increasing by durableId (and by version within one Shape)",since_below_epoch_floor:"Repository export delta base is below the epoch floor",trailer_invalid:"Repository export trailer is invalid",truncated:"Repository export stream ended before its trailer"},te=class{#e=xa();#i=xa();#o=0;#t;#r;#a;#s=false;#p=false;#n;get header(){return this.#t}get lastDurableId(){return this.#r?.durableId}get lastShapeVersion(){let e=this.#r;return e?.kind==="shape"&&(this.#t?.formatVersion??0)>=6?e.version:void 0}get rowCount(){return this.#e.rowCount}get segmentRowCount(){return this.#o}get contentSha256(){return this.#n}finalizeContentSha256(){return this.#n===void 0&&(this.#n=this.#e.finalize(),this.#s=true),this.#n}beginSegment(){this.assertResumable(),this.#i=xa(),this.#o=0;}markUnverifiable(){this.#p=true;}finalizeSegment(){return this.#i.finalize()}get token(){return this.#a}set token(e){this.#a=e;}get complete(){return this.#s}markComplete(){this.finalizeContentSha256();}assertResumable(){if(this.#p)throw new f("digest_mismatch","Repository export session failed verification and cannot be resumed; start a new session");if(this.#s)throw new f("header_invalid","Repository export session is already complete; start a new session")}adoptHeader(e){this.assertResumable();let t=this.#t;if(t!==void 0&&(t.repo!==e.repo||t.mode!==e.mode||t.sinceRepoSeq!==e.sinceRepoSeq||t.atRepoSeq!==e.atRepoSeq))throw new f("header_invalid","Resumed repository export header does not match the opening header");if(t!==void 0&&t.formatVersion!==e.formatVersion)throw new f("header_invalid",`Resumed repository export is format ${e.formatVersion}, but it opened as format ${t.formatVersion}. Restart the export; a resume must use the format it started with.`);this.#t=e;}recordRow(e,t){let r=this.#t,i=this.#r;if(r?.mode==="heads"&&i!==void 0&&!sa(i,e,r.formatVersion))throw new f("row_out_of_order",`Repository export row '${e.durableId}' v${e.version} does not follow '${i.durableId}' v${i.version}`);this.#e.update(t),this.#i.update(t),this.#o+=1,this.#r={durableId:e.durableId,kind:e.kind,version:e.version};}};function G(){return new te}function On(n){return typeof n.get=="function"}function vn(n){return On(n)?n.values():n}function xn(n,e){return e>=6&&n.kind==="shape"?`${n.durableId}@v${n.version}`:n.durableId}function sr(n,e,t){if(t.base>=6!=t.delta>=6)throw new f("format_mismatch",`Repository export delta is format ${t.delta} but its base is format ${t.base}; take a fresh full export instead of folding across formats`);let r=new Map;for(let[i,o]of [[n,t.base],[e,t.delta]])for(let s of vn(i)){if(!s.active&&o>=6&&s.kind==="shape"){let u=`${s.durableId}@v`;for(let l of r.keys())l.startsWith(u)&&r.delete(l);continue}let a=xn(s,o);s.active?r.set(a,s):r.delete(a);}return r}var ar=10,An=new TextDecoder;function kn(n){let e=n.header;if(!e)throw new f("header_invalid","Repository export resumed without an opening header to inherit");return e}async function Tn(n,e,t){let r=await n.next();if(r.done)throw new f("truncated");let i;try{i=va(r.value);}catch(o){je("header_invalid",o);}if(!qa.includes(i.formatVersion)||t!==void 0&&(i.repo!==t.repo||i.mode!==t.mode||t.sinceRepoSeq!==void 0&&i.sinceRepoSeq!==t.sinceRepoSeq||t.atRepoSeq!==void 0&&i.atRepoSeq!==t.atRepoSeq))throw new f("header_invalid",t===void 0?`Repository export header declares format version ${i.formatVersion}; expected one of ${qa.join(", ")}`:`Repository export header describes ${i.repo} (${i.mode}, ${i.sinceRepoSeq}..${i.atRepoSeq}); expected ${t.repo} (${t.mode}${t.sinceRepoSeq!==void 0?`, since ${t.sinceRepoSeq}`:""}${t.atRepoSeq!==void 0?`, at ${t.atRepoSeq}`:""})`);return e.adoptHeader(i),i}async function*_n(n,e){let t=new Uint8Array(0);for await(let r of Nn(n)){let i=new Uint8Array(t.length+r.length);i.set(t),i.set(r,t.length),t=i;let o=t.indexOf(ar);for(;o!==-1;)yield t.subarray(0,o+1),t=t.subarray(o+1),o=t.indexOf(ar);}e.unterminated=t.length>0;}function Nn(n){if(Symbol.asyncIterator in n)return n;let e=n;return {async*[Symbol.asyncIterator](){let t=e.getReader();try{for(;;){let{done:r,value:i}=await t.read();if(r)return;i&&(yield i);}}finally{t.releaseLock();}}}}function Pn(n){try{let e=JSON.parse(An.decode(n));if(e!==null&&typeof e=="object"&&"kind"in e){let t=e.kind;if(typeof t=="string")return t}}catch{}return ""}function je(n,e){throw e instanceof f?e:new f(n,e instanceof Error?e.message:void 0)}async function*re(n,e,t,r={}){yield*cr(n,e,t,r);}async function pr(n,e={}){let t=G(),r=cr(n,t,void 0,e);for await(let i of r)e.onRow?.(i);return t}async function*cr(n,e,t,r){let i={unterminated:false},o=_n(n,i);try{yield*Dn(o,i,e,t,r);}finally{await o.return(void 0);}}async function*Dn(n,e,t,r,i){t.assertResumable();let o=i.resumed===true?kn(t):await Tn(n,t,r),s=ta(o);for(t.beginSegment();;){let a=await n.next();if(a.done){if(i.partial===true)return;throw new f("truncated")}let u=a.value;if(Pn(u)!=="trailer"){let d;try{d=ua(u);}catch(m){je("row_invalid",m);}if(!d.active&&!s)throw new f("row_invalid","Repository export tombstone is not legal in a full export");t.recordRow(d,u),yield d;continue}let l;try{if(l=wa$1(u),l.atRepoSeq!==o.atRepoSeq)throw new f("fence_mismatch");if(l.recordCount!==t.segmentRowCount)throw new f("count_mismatch");if(l.contentSha256!==t.finalizeSegment())throw new f("digest_mismatch")}catch(d){if(t.markUnverifiable(),d instanceof f)throw d;je("trailer_invalid",d);}if(!(await n.next()).done||e.unterminated)throw new f("trailer_invalid","Repository export stream continues past its trailer");t.markComplete();return}}var Ln="since-below-epoch-floor",Mn=1e3,qn=50,Un=3;function ze(n,e,t){let r=new URLSearchParams;for(let[o,s]of Object.entries(t))s!==void 0&&r.set(o,String(s));let i=r.toString();return `/api/repos/${encodeURIComponent(n)}/${encodeURIComponent(e)}/export${i?`?${i}`:""}`}function ur(n){let e=n?.reason;return e instanceof Error?e:new Error("Repository export was aborted")}function Bn(n){return n===void 0||!Number.isFinite(n)?Mn:Math.max(n,qn)}async function Vn(n,e){if(e?.aborted)throw ur(e);await new Promise((t,r)=>{let i=()=>{clearTimeout(o),r(ur(e));},o=setTimeout(()=>{e?.removeEventListener("abort",i),t();},n);e?.addEventListener("abort",i,{once:true});});}async function Hn(n,e){let t;try{t=await n.clone().json();}catch{}return (t?.code??t?.error?.code)===Ln?new f("since_below_epoch_floor",t?.message):t?.code!==void 0&&t.error===void 0?await e(new Response(JSON.stringify({error:t}),{status:n.status,headers:{"content-type":"application/json"}})):await e(n)}function Fn(n){let e=n;return typeof e?.url=="string"&&e.url!==""&&typeof e.expiresAt=="number"&&typeof e.atRepoSeq=="number"&&typeof e.recordCount=="number"&&typeof e.contentSha256=="string"}async function Wn(n){let e;try{e=await n.json();}catch{throw new f("header_invalid","Repository export redemption did not return a JSON download envelope")}if(!Fn(e))throw new f("header_invalid","Repository export download envelope must carry url, expiresAt, atRepoSeq, recordCount, and contentSha256");return e}function $n(n,e){let t=n.header?.atRepoSeq;if(t!==e.atRepoSeq)throw new f("fence_mismatch",`Repository export download is pinned to ${t}; the redemption named ${e.atRepoSeq}`);if(n.rowCount!==e.recordCount)throw new f("count_mismatch",`Repository export download carried ${n.rowCount} rows; the redemption named ${e.recordCount}`);if(n.contentSha256!==e.contentSha256)throw new f("digest_mismatch","Repository export download digest does not match the digest the redemption named")}function Qe(n,e,t=(r,i)=>globalThis.fetch(r,i)){let r=async(a,u)=>{let l=await n(a,{method:"GET",headers:{accept:ra},...u?{signal:u}:{}});if(!l.ok&&l.status!==202)throw await Hn(l,e);return l},i=async(a,u,l={})=>{let m=await(await r(ze(a,u,{mode:l.mode??"heads",sinceRepoSeq:l.sinceRepoSeq,atRepoSeq:l.atRepoSeq,prefer:"async"}),l.signal)).json();if(typeof m.exportToken!="string"||typeof m.atRepoSeq!="number")throw new f("header_invalid","Repository export async request did not return an exportToken and atRepoSeq");return {exportToken:m.exportToken,atRepoSeq:m.atRepoSeq}};return {prepare:i,stream:(a,u,l={})=>{let d=l.session?.lastDurableId??l.afterDurableId;if(d!==void 0&&(l.token!==void 0||l.session?.token!==void 0||l.prefer==="async"))throw new f("header_invalid",`Repository export token download cannot continue from '${d}': redemption returns the whole prepared object. Start a new session and redeem the token again.`);if(l.afterDurableId!==void 0&&l.session?.header===void 0)throw new f("header_invalid","Repository export afterDurableId needs a session carrying the opening header; reuse the session the broken stream wrote, or rebuild one with restoreRepositoryExportSession");return s(a,u,l)}};async function*s(a,u,l){let d=l.session??G(),m=d.header,h=l.signal,b=d.lastDurableId??l.afterDurableId,S={mode:m?.mode??l.mode??"heads",sinceRepoSeq:m?.sinceRepoSeq??l.sinceRepoSeq,atRepoSeq:m?.atRepoSeq??l.atRepoSeq,afterDurableId:b,afterVersion:d.lastDurableId===void 0?void 0:d.lastShapeVersion,formatVersion:b===void 0?void 0:m?.formatVersion},R={repo:`${a}/${u}`,mode:S.mode,...l.sinceRepoSeq===void 0?{}:{sinceRepoSeq:l.sinceRepoSeq},...l.atRepoSeq===void 0?{}:{atRepoSeq:l.atRepoSeq}};if(l.token!==void 0&&d.token!==void 0&&l.token!==d.token)throw new f("header_invalid",`Repository export session was redeeming token ${d.token}; resuming it with token ${l.token} would splice two exports`);let w=l.token??d.token;if(w!==void 0){d.token=w,yield*x(w);return}if(l.prefer==="async"){let T=await i(a,u,{mode:S.mode,...S.sinceRepoSeq===void 0?{}:{sinceRepoSeq:S.sinceRepoSeq},...S.atRepoSeq===void 0?{}:{atRepoSeq:S.atRepoSeq},...h?{signal:h}:{}});d.token=T.exportToken,yield*x(T.exportToken);return}let v=await r(ze(a,u,S),h);if(!v.body)throw new f("truncated");yield*re(v.body,d,R,{resumed:S.afterDurableId!==void 0});async function*x(T){for(let A=1;;A+=1){let ie=await q(T);try{yield*O(ie);return}catch(Ae){if(!(!(Ae instanceof f)||Ae.reason==="truncated")||d.rowCount>0||A>=Un||h?.aborted===true)throw Ae}}}async function*O(T){let A=await t(T.url,h?{signal:h}:{});if(!A.ok||!A.body)throw await A.body?.cancel(),new f("truncated",`Repository export download returned HTTP ${A.status}`);yield*re(A.body,d,R,{resumed:false}),$n(d,T);}async function q(T){let A=ze(a,u,{token:T});for(;;){let ie=await r(A,h);if(ie.status!==202)return await Wn(ie);await Vn(Bn(l.pollIntervalMs),h);}}}}var mr="warmhub/streaming-submission-manifest/v1",Gn=new TextEncoder,Je=z.string().regex(/^sha256:[0-9a-f]{64}$/),hr={type:z.literal("result"),chunkOrdinal:z.number().int().nonnegative(),opIndex:z.number().int().nonnegative(),submissionIndex:z.number().int().nonnegative(),name:z.string()},Kn=z.enum(A),jn=z.enum([...A,"noop"]),gr=z.object({path:z.string(),message:z.string()}),yr=_$1.loose().optional(),fr=z.object({added:z.array(z.string()),removed:z.array(z.string()),ignored:z.array(z.string())}),zn=z.discriminatedUnion("reason",[z.object({reason:z.literal("expected_version_mismatch"),expectedVersion:z.number().int().positive(),currentVersion:z.number().int().positive()}),z.object({reason:z.literal("lease_held"),leaseExpiresAt:z.iso.datetime()}),z.object({reason:z.literal("validation_failed"),issues:z.array(gr)}),z.object({reason:z.literal("rate_limit_reset"),retryAfterSeconds:z.number().int().positive(),resetAt:z.iso.datetime()}),z.object({reason:z.literal("cursor_fence_unavailable"),cause:z.enum(["not_ready","below_floor","above_head"]),retryFromStart:z.literal(true)})]),Qn=z.discriminatedUnion("reason",[z.object({reason:z.literal("expected_version_mismatch"),expectedVersion:z.number().int().nonnegative(),currentVersion:z.number().int().nonnegative()}).strict(),z.object({reason:z.literal("lease_held"),leaseExpiresAt:z.iso.datetime()}).strict(),z.object({reason:z.literal("validation_failed"),issues:z.array(gr.strict())}).strict(),z.object({reason:z.literal("rate_limit_reset"),retryAfterSeconds:z.number().nonnegative(),resetAt:z.iso.datetime()}).strict(),z.object({reason:z.literal("cursor_fence_unavailable"),cause:z.enum(["not_ready","below_floor","above_head"]),retryFromStart:z.literal(true)}).strict(),z.object({reason:z.literal("dependency_failed"),producerOpIndexes:z.array(z.number().int().nonnegative()).min(1)}).strict(),z.object({reason:z.literal("name_taken"),name:z.string().min(1),takenBy:z.object({durableId:z.string().min(1)}).loose().optional()}).loose(),z.object({reason:z.literal("target_removed"),targetDurableId:z.string().min(1),fieldPath:z.string().optional()}).loose(),z.object({reason:z.literal("target_redacted"),targetDurableId:z.string().min(1),fieldPath:z.string().optional()}).loose(),z.object({reason:z.literal(a)}).loose()]),lr={...hr,operation:Kn,submittedName:z.string().optional(),resolvedName:z.string().optional(),warnings:yr,affirmations:fr.optional()},Yn=z.union([z.looseObject({...hr,operation:jn.optional(),version:z.number().optional(),dataHash:z.string().optional(),status:z.enum(["success","noop","failed"]).optional(),error:z.object({code:z.string(),message:z.string(),details:zn.optional()}).optional(),resolvedName:z.string().optional(),retryable:z.boolean().optional(),warnings:yr,affirmations:fr.optional()}),z.looseObject({...lr,status:z.enum(["applied","noop"]),version:z.number().int().positive().optional(),dataHash:z.string().min(1).optional()}),z.looseObject({...lr,status:z.literal("error"),errors:z.array(z.object({code:z.string().min(1),message:z.string(),path:z.string().min(1).optional(),details:Qn.optional(),retryable:z.boolean().optional()}).strict()).min(1)})]),Rr=z.object({applied:z.number().int().nonnegative(),noop:z.number().int().nonnegative(),failed:z.number().int().nonnegative()}),Jn=z.looseObject({type:z.literal("group"),chunkOrdinal:z.number().int().nonnegative(),eventRequestId:z.uuid(),requestDigest:Je,outcome:z.enum(["event","no_event"]),repoSeq:z.number().int().nonnegative().optional(),operations:Rr,manifestDigest:Je}),Xn=z.looseObject({type:z.literal("summary"),submissionId:z.uuid(),streamId:z.string().min(1),groupSize:z.number().int().positive(),groups:z.number().int().nonnegative(),operations:Rr.extend({total:z.number().int().nonnegative()}),repoSeq:z.object({first:z.number().int().nonnegative().nullable(),last:z.number().int().nonnegative().nullable()}),verdict:z.string().min(1),durationMs:z.number().nonnegative(),truncatedAt:z.object({lineNumber:z.number().int().positive(),message:z.string()}).optional(),manifest:z.object({groups:z.number().int().nonnegative(),digest:Je})}),Zn=z.looseObject({type:z.literal("error"),code:z.string().min(1),message:z.string().optional()}),ei=z.union([Yn,Jn,Xn,Zn]),Ye=()=>({applied:0,noop:0,failed:0}),dr=(n,e)=>n.applied===e.applied&&n.noop===e.noop&&n.failed===e.failed,ti=new Set(["complete","operation-limit-reached","group-limit-reached"]),N=class extends Error{constructor(t,r){super(`Streaming submission protocol error at row ${r}: ${t}`);this.rowIndex=r;this.name="StreamingSubmissionProtocolError";}rowIndex};async function br(n){let e=Gn.encode(n),t=await globalThis.crypto.subtle.digest("SHA-256",e);return `sha256:${Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}`}async function ri(n,e,t){return br(`${mr}\0${n}\0${e}\0${t}`)}function ni(n){return n.status==="error"?"failed":n.status==="noop"?"noop":"applied"}var Xe=class{index=0;groupCount=0;resultCount=0;pendingCount=0;pendingCounts=Ye();totalCounts=Ye();firstRepoSeq=null;lastRepoSeq=null;manifestDigest=br(mr);terminalSeen=false;accept(e){let t=r=>{throw new N(r,this.index)};if(this.terminalSeen&&t("No row may follow the terminal row"),e.type==="result"){e.chunkOrdinal!==this.groupCount&&t(`Expected result chunkOrdinal ${this.groupCount}`),e.opIndex!==this.pendingCount&&t(`Expected result opIndex ${this.pendingCount}`),e.submissionIndex!==this.resultCount&&t(`Expected submissionIndex ${this.resultCount}`);let r=ni(e);this.pendingCounts[r]+=1,this.totalCounts[r]+=1,this.pendingCount+=1,this.resultCount+=1,this.index+=1;return}if(e.type==="group")return e.chunkOrdinal!==this.groupCount&&t(`Expected group chunkOrdinal ${this.groupCount}`),this.pendingCount===0&&t("A group must close result rows"),dr(this.pendingCounts,e.operations)||t("Group operation counters do not match its result rows"),this.acceptGroup(e,t);if(this.terminalSeen=true,this.pendingCount>0&&t("Terminal row cannot close a partial group"),e.type==="summary")return this.acceptSummary(e,t);this.index+=1;}async acceptGroup(e,t){this.manifestDigest=this.manifestDigest.then(r=>ri(r,e.chunkOrdinal,e.requestDigest)),e.manifestDigest!==await this.manifestDigest&&t("Group manifest digest does not match the receipt chain"),e.repoSeq!==void 0&&(this.firstRepoSeq??=e.repoSeq,this.lastRepoSeq=e.repoSeq),this.groupCount+=1,this.pendingCount=0,this.pendingCounts=Ye(),this.index+=1;}async acceptSummary(e,t){dr(this.totalCounts,e.operations)||t("Summary operation counters do not match result rows"),(e.groups!==this.groupCount||e.manifest.groups!==this.groupCount)&&t("Summary group counters do not match group rows"),e.manifest.digest!==await this.manifestDigest&&t("Summary manifest digest does not match the receipt chain"),(e.repoSeq.first!==this.firstRepoSeq||e.repoSeq.last!==this.lastRepoSeq)&&t("Summary repo sequence does not match group rows"),(ti.has(e.verdict)?e.operations.total!==this.resultCount:e.operations.total<this.resultCount)&&t("Summary total is incompatible with its verdict"),e.verdict==="truncated-by-parse-error"!=(e.truncatedAt!==void 0)&&t("truncatedAt must appear only for a parse-truncated verdict"),this.index+=1;}finish(){if(!this.terminalSeen)throw new N("Response must end with a summary or error row",this.index)}};function ii(n,e){let t;try{t=JSON.parse(n);}catch(i){throw new N(i instanceof Error?i.message:"Invalid JSON",e)}let r=ei.safeParse(t);if(!r.success)throw new N(r.error.issues[0]?.message??"Malformed row",e);return r.data}async function*Sr(n,e){let t=n.body?.getReader();if(!t)throw new N("Missing response body",0);let r=new Xe,i=new TextDecoder,o="",s=0,a=false,u,l=m=>{if(m.endsWith("\r")&&(m=m.slice(0,-1)),m.length===0)throw new N("Blank response row",s);let h=ii(m,s);return {pending:r.accept(h),row:h}},d=m=>{if(m.type==="summary"&&e!==void 0&&(m.submissionId!==e.submissionId||m.streamId!==e.streamId||m.groupSize!==e.groupSize))throw new N("Summary identity does not match the submission handle",s);s+=1;};try{for(;;){let{done:m,value:h}=await t.read();if(m)break;for(o+=i.decode(h,{stream:!0});;){let b=o.indexOf(`
|
|
3
|
-
`);if(b===-1)break;let S=o.slice(0,b);o=o.slice(b+1);let{pending:R,row:w}=l(S);R&&await R,d(w),w.type==="summary"||w.type==="error"?u=w:yield w;}}if(o+=i.decode(),o.length>0){let{pending:m,row:h}=l(o);m&&await m,d(h),h.type==="summary"||h.type==="error"?u=h:yield h;}r.finish(),a=!0,u&&(yield u);}finally{if(!a)try{await t.cancel();}catch{}t.releaseLock();}}var M=class extends Error{code="STREAMING_SUBMISSION_OUTCOME_UNKNOWN";outcome="unknown";retryable=false;retryIdentity;cause;constructor(e,t){super(`Streaming submission outcome is unknown for ${e.submissionId}. Reconstruct the original source and copy every retryIdentity field into the next applyStreaming call.`),this.name="StreamingSubmissionOutcomeUnknownError",this.retryIdentity=e,this.cause=t;}};function Ee(n){return n===void 0||n===""?void 0:n}function oi(){let n=globalThis;if(n.Bun!==void 0)return true;let e=n.process?.versions?.node;if(!e)return false;let[t=0,r=0]=e.split(".").map(Number);return t>22||t===22&&r>=2}function si(n){let e=new URLSearchParams({submissionId:n.submissionId,groupSize:String(n.groupSize)});return n.message!==void 0&&e.set("message",n.message),n.committer!==void 0&&e.set("committer",n.committer),`/api/repos/${encodeURIComponent(n.orgName)}/${encodeURIComponent(n.repoName)}/streams/${encodeURIComponent(n.streamId)}/submissions?${e}`}function ai(n,e,t){let r=we(n,false),i=U(t),o=0,s=false,a=async d=>{try{await d;}catch{}},u=()=>{if(!s){s=true;try{let d=r.returnSourceOnce();d&&a(d);}catch{}}};return {stream:new ReadableStream({async pull(d){try{let m=[],h=o,b=!1;for(;;){let S=await r.next();if(s)return;if(!(!S.done&&(m.push(S.value),o+=1,b||=Y(S.value),b&&o%e!==0))){for(let R of await i(m,h))d.enqueue(Ke(R));S.done&&d.close();return}}}catch(m){d.error(m),u();}},cancel(){u();}}),returnSourceOnce:u}}function pi(n,e){if(!n)return ()=>{};let t=()=>e.abort(n.reason);return n.aborted?t():n.addEventListener("abort",t,{once:true}),()=>n.removeEventListener("abort",t)}function ci(n){let e=n.options?.submissionId??F();return {orgName:n.orgName,repoName:n.repoName,streamId:n.options.streamId,submissionId:e,groupSize:Ce(n.options.groupSize),...Ee(n.message)!==void 0?{message:Ee(n.message)}:{},...Ee(n.options?.committer)!==void 0?{committer:Ee(n.options?.committer)}:{}}}function Cr(n,e){if(!n.options.streamId)throw e.localError("VALIDATION_ERROR","Streaming submissions require a non-empty streamId.");let t=ci(n),r=new AbortController,i=()=>{},o,s=false,a=async function*(){let u=false,l=false,d;try{if(!(e.runtimeSupported??oi)())throw e.localError("VALIDATION_ERROR","Streaming submissions require Bun or Node.js 22.2 or newer.");if(i=pi(n.options.signal,r),r.signal.aborted)throw e.localError("CANCELLED","Streaming submission was aborted.");let m=await e.prepare(si(t));if(r.signal.aborted)throw e.localError("CANCELLED","Streaming submission was aborted.");d=ai(n.operations,t.groupSize,e.readThings),u=!0;let h=await m.dispatch(d.stream,r.signal);if(!h.ok)throw l=!0,await m.httpError(h);for await(let b of Sr(h,t))yield b;}catch(m){throw m instanceof M?m:u&&!l?new M(t,m):e.normalizeLocalError(m)}finally{r.abort(),d?.returnSourceOnce(),i(),s=true;}};return {retryIdentity:t,[Symbol.asyncIterator](){return this},next(){return s?Promise.resolve({done:true,value:void 0}):(o??=a(),o.next())},async return(u){return r.abort(),o?o.return(u):(s=true,i(),{done:true,value:u})},async throw(u){if(r.abort(u),!o)throw s=true,i(),u;return o.throw(u)}}}var ui="0.0.0-development";function K(n){return n===ui}var Ze="0.162.0";var Er=3;function et(n){return n===w?"Run: wh update --yes":n===v?"Run: npm install @warmhub/sdk-ts@latest (or your package manager's equivalent).":n===x?"Run: pip install --upgrade warmhub":`Deploy a released ${n} build that satisfies the backend compatibility contract.`}function Ir(n,e){if(typeof n?.minSupportedClients!="object"||n.minSupportedClients===null||!Number.isSafeInteger(n.writeContractVersion)||n.writeContractVersion<1)return {message:"The backend does not advertise valid per-client write compatibility data.",hint:"Upgrade the WarmHub backend before retrying this write."};let t=n.minSupportedClients[e.name],r=typeof t=="string"?N$1(t):null;if(!r)return {message:`The backend does not advertise a valid compatibility floor for ${e.name}.`,hint:"Upgrade the WarmHub backend or register this first-party client family before writing."};if(!K(e.version)){let i=N$1(e.version);if(!i)return {message:`${e.name} reported malformed version "${e.version}".`,hint:"Use a released WarmHub client with a SemVer package version."};if(O(i,r)<0)return {message:`${e.name} ${e.version} is older than the backend's minimum supported version ${r}.`,hint:et(e.name)}}if(n.writeContractVersion<Er)return {message:`${e.name} requires write contract ${Er}, but the backend provides ${n.writeContractVersion}.`,hint:"Upgrade the WarmHub backend before retrying this write."}}function Or(n,e){try{return new URL(n).origin===new URL(e).origin}catch{return false}}var li=new Set(["GET","POST","PUT","PATCH","DELETE"]),I=class extends Error{reason;constructor(e,t){super(t),this.name="CliCallVerificationError",this.reason=e;}};async function di(n,e,t){let r=n.method.toUpperCase();if(!li.has(r))throw new I("unsupported-method",`Unsupported HTTP method "${n.method}" \u2014 component CLI dispatch only emits GET, POST, PUT, or PATCH`);let i=r,o=n.headers.get(C$1);if(!o)throw new I("missing-install-repo",`Missing ${C$1} header`);let s=j(e.CLI_SIGNING_SECRET),a=j(e.CLI_BEARER_TOKEN),u=j(e.CLI_API_KEY),l=j(e.CLI_BASIC_USERNAME)&&j(e.CLI_BASIC_PASSWORD);if(!s&&!a&&!u&&!l)throw new I("no-scheme-configured","no-scheme-configured: need at least one of CLI_SIGNING_SECRET, CLI_BEARER_TOKEN, CLI_API_KEY, or CLI_BASIC_USERNAME + CLI_BASIC_PASSWORD");if(a&&l)throw new I("no-scheme-configured","unsupported-scheme-combination: CLI_BEARER_TOKEN and CLI_BASIC_USERNAME + CLI_BASIC_PASSWORD both use the Authorization header and cannot be configured together");let d=new URL(n.url),m=d.pathname,h,b,S;if(F$1(i)?h={}:(h=Object.fromEntries(d.searchParams.entries()),b="",S={...h}),s){let R=n.headers.get(D$1);if(!R)throw new I("missing-signature",`Missing ${D$1} header`);let w=n.headers.get(E$1);if(!w)throw new I("missing-timestamp",`Missing ${E$1} header`);let v=Number(w);if(!Number.isFinite(v)||!Number.isInteger(v))throw new I("invalid-timestamp",`${E$1} must be an integer unix seconds value; got "${w}"`);b=await vr(n,i,b);let x=await G$1({secret:e.CLI_SIGNING_SECRET,method:i,path:m,query:h,installRepo:o,body:b,signature:R,timestamp:v,nowUnixSeconds:t?.nowUnixSeconds??Math.floor(Date.now()/1e3),toleranceSec:t?.toleranceSec});if(!x.ok)throw new I(x.reason,`HMAC verification failed: ${x.reason}`)}if(a){let R=`Bearer ${e.CLI_BEARER_TOKEN}`,w=n.headers.get("authorization")??"";if(!await tt(w,R))throw new I("invalid-bearer","invalid-bearer: bearer token mismatch")}if(u){let R=j(e.CLI_API_KEY_HEADER)?e.CLI_API_KEY_HEADER:"X-API-Key",w=n.headers.get(R)??"";if(!await tt(w,e.CLI_API_KEY))throw new I("invalid-api-key",`invalid-api-key: mismatch on header "${R}"`)}if(l){let R=`Basic ${btoa(`${e.CLI_BASIC_USERNAME}:${e.CLI_BASIC_PASSWORD}`)}`,w=n.headers.get("authorization")??"";if(!await tt(w,R))throw new I("invalid-basic","invalid-basic: basic auth mismatch")}return S===void 0&&(b=await vr(n,i,b),S=mi(b)),{method:i,installRepo:o,args:S}}async function vr(n,e,t){return F$1(e)?t!==void 0?t:n.text():""}function mi(n){let e;try{e=JSON.parse(n);}catch{throw new I("invalid-body","POST body is not valid JSON")}if(!hi(e))throw new I("invalid-body","POST body must be a JSON object of primitive args (string / number / boolean)");return e}function j(n){return typeof n=="string"&&n.length>0}function hi(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;for(let e of Object.values(n))if(e!==void 0&&typeof e!="string"&&typeof e!="number"&&typeof e!="boolean")return false;return true}async function tt(n,e){let[t,r]=await Promise.all([xr(n),xr(e)]),i=0;for(let o=0;o<t.length;o++)i|=t[o]^r[o];return i===0}async function xr(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)))}function ba(n){return i(n)}var bi={apiUrl:true,fetch:true,accessToken:true,auth:true,functionLogs:true,client:true,clientFlags:true,decorateResponses:true},Ur=Object.keys(bi),Si=new Set(Ur),wi=new Set(["token","apiKey","bearer"]);function Ci(n){if(n)for(let e of Object.keys(n)){if(Si.has(e))continue;let t=wi.has(e)?'; did you mean "accessToken"?':`. Valid options are: ${Ur.join(", ")}.`;throw new TypeError(`Unknown WarmHubClient option "${e}"${t}`)}}function Ei(n){if(!n||n.length===0)return [];for(let e of n)if(!q(e))throw new TypeError(`Invalid client flag "${e}": expected lowercase tokens matching [a-z0-9-]+.`);return [...new Set(n)].sort()}var kr="https://api.warmhub.ai",Ii=new Set(["commit.validate","repo.shapeInstanceCounts","thing.getMany","thing.headVersions","thing.names"]),Oi=500,vi=500,xi=1,Ai=8;function Oe(n){return {...n,actionContainer:void 0,actionContainerConfig:void 0}}function ki(n){return n.map(e=>Oe(e))}function Br(n,e,t){if(e===n||t.has(e))throw new g("VALIDATION_ERROR","Paginated result cursor did not advance")}function Tr(n){if(n===void 0)throw new g("VALIDATION_ERROR","sinceRepoSeq is required for an incremental read")}async function*Vr(n,e){let t=e,r=new Set;for(;;){t&&r.add(t);let i=await n(t);if(yield i,!i.nextCursor)return;Br(t,i.nextCursor,r),t=i.nextCursor;}}async function*C(n,e,t){for await(let r of Vr(n,t))yield*e(r);}async function E(n,e,t,r){if(t!==void 0&&(!Number.isFinite(t)||Math.trunc(t)!==t||t<0))throw new g("VALIDATION_ERROR","max must be a nonnegative integer");let i=[];for await(let o of Vr(n,r)){let s=e(o);if(t!==void 0&&i.length+s.length>t)throw new g("VALIDATION_ERROR",`Paginated result exceeded max=${t}`);i.push(...s);}return i}function _r(n){if(n?.slugs!==void 0)throw new g("VALIDATION_ERROR","repo.explore pagination helpers do not support slugs mode")}async function Nr(n){let e=[],t,r=new Set;for(;;){t&&r.add(t);let i=await n(t);if(e.push(...i.items),!i.nextCursor){if(i.repoSeq===void 0)throw new g("VALIDATION_ERROR","Incremental read completed without repoSeq");return {items:e,repoSeq:i.repoSeq}}Br(t,i.nextCursor,r),t=i.nextCursor;}}function Pr(n,e,t){return Number.isFinite(n)?Math.max(1,Math.min(t,Math.trunc(n))):e}function Ti(n,e){let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t}async function rt(n,e,t){if(n.length===0)return {requested:0,items:[],missing:[]};let r=Pr(e?.chunkSize,Oi,vi),i=Pr(e?.chunkConcurrency,xi,Ai);if(n.length<=r)return await t(n);let o=Ti(n,r),s=[];for(let a=0;a<o.length;a+=i){let u=o.slice(a,a+i),l=await Promise.all(u.map(t));s.push(...l);}return {requested:n.length,items:s.flatMap(a=>a.items),missing:s.flatMap(a=>a.missing)}}function Ie(n){return n!==void 0&&B.includes(n)?n:void 0}function ne(n){let[e,t,r]=n;return typeof e=="string"?{orgName:e,repoName:t,name:r}:e}function _i(n){let[e,t]=n;return typeof e=="string"?{orgName:e,repoName:t}:e}function Ni(n){let[e,t,r,i]=n;return typeof e=="string"?{orgName:e,repoName:t,subscriptionName:r,credentialSetName:i}:e}function Pi(n){let[e,t,r]=n;return typeof e=="string"?{orgName:e,repoName:t,subscriptionName:r}:e}function Di(n){let{actionContainer:e,actionContainerConfig:t,...r}=n;return r}function Li(n){let{actionContainer:e,actionContainerConfig:t,...r}=n;return r}function st(n){return !!n&&(!!n.shape||!!n.kind||!!n.about||!!n.match||!!n.componentRef||n.excludeComponents===true||(n.where?.length??0)>0)}function ve(n){return !!n&&(!!n.shape||!!n.about||!!n.match||!!n.componentRef||(n.where?.length??0)>0)}function Hr(n){let e=n.members;return Array.isArray(e)&&e.length>0}function Mi(n,e){if(n!=="set"&&n!=="list")throw new g("VALIDATION_ERROR",da(String(n)));if(st(e.query)&&!ve(e.query))throw new g("VALIDATION_ERROR","Selector-backed collection sources require shape, about, match, componentRef, or where; kind and excludeComponents only narrow an existing selector.");if(e.sourceRepo&&!ve(e.query))throw new g("VALIDATION_ERROR","sourceRepo requires a selector-backed collection query");if(e.sourceRepo&&Hr(e))throw new g("VALIDATION_ERROR","sourceRepo cannot be combined with explicit members; use canonical wh:org/repo/... member wrefs or omit sourceRepo.");if(st(e.query)&&n!=="set")throw new g("VALIDATION_ERROR","Selector-backed collection sources are only supported for set collections")}function Sa(n){return n??"off"}function qi(n){if(n!==void 0)switch(n){case "BAD_REQUEST":case "PARSE_ERROR":case "PAYLOAD_TOO_LARGE":case "UNPROCESSABLE_CONTENT":case "UNSUPPORTED_MEDIA_TYPE":return "VALIDATION_ERROR";case "METHOD_NOT_SUPPORTED":return "NOT_FOUND";case "UNAUTHORIZED":return "UNAUTHENTICATED";case "FORBIDDEN":return "FORBIDDEN";case "NOT_FOUND":return "NOT_FOUND";case "CONFLICT":return "CONFLICT";case "PRECONDITION_FAILED":return "PRECONDITION_FAILED";case "TOO_MANY_REQUESTS":return "RATE_LIMITED";default:return}}function Ui(n){if(n===void 0||n===408)return;if(n===405)return "NOT_FOUND";if(n===412)return "PRECONDITION_FAILED";if(n===422)return "VALIDATION_ERROR";let e=$r(n);return e!=="BACKEND"?e:n>=400&&n<500?"VALIDATION_ERROR":e}var Bi=[/\bselect\b.+?\bfrom\b/i,/\binsert\b.+?\binto\b/i,/\bupdate\b.+?\bset\b/i,/\bdelete\b.+?\bfrom\b/i,/\bparams:\s/i,/\.ts\(\d+,\d+\)/,/at\s+\S+\s+\(.*:\d+:\d+\)/,/node_modules\//,/drizzle/i];function nt(n){for(let e of Bi)if(e.test(n))return "An internal error occurred. Please try again or contact support.";return n}function Dr(n,e){if(typeof e!="string")return;let t=m(n,e);if(t)throw new g("VALIDATION_ERROR",t)}function p(n){if(n instanceof g)return n;if(n instanceof TRPCClientError){if(n.cause instanceof g)return n.cause;let e=n.data,t=e?.warmhub?.code,r=typeof e?.code=="string"?qi(e.code):void 0,i=Ui(e?.httpStatus),o=e?.warmhub?.message??nt(n.message);return new g(t??r??i??"BACKEND",o,e?.warmhub?.status??e?.httpStatus,e?.warmhub?.hint,e?.warmhub?.retryAfter??e?.retryAfter,t,e?.warmhub?.details)}if(n instanceof Error){let e=n;if(n.name==="WarmHubError"&&typeof e.code=="string"){let t=new g(e.code,nt(n.message),typeof e.status=="number"?e.status:void 0,typeof e.hint=="string"?e.hint:void 0,typeof e.retryAfter=="number"?e.retryAfter:void 0,typeof e.errorCode=="string"?e.errorCode:typeof e.backendCode=="string"?e.backendCode:void 0,e.details);return at(n)&&Object.defineProperty(t,Fr,{value:true}),t}return n.name==="AbortError"?new g("CANCELLED",n.message):n instanceof TypeError&&/fetch/i.test(n.message)?new g("NETWORK",n.message):new g("BACKEND",nt(n.message))}return new g("BACKEND","Unknown SDK error")}var Fr=Symbol.for("@warmhub/sdk-ts:allStreamOperationsFailed");function at(n){if(n instanceof _)return true;if(!(n instanceof Error))return false;let e=n;return e[Fr]===true||e.name==="WarmHubError"&&Array.isArray(e.receipts)&&Array.isArray(e.operations)}function wa(n){return at(n)}function Vi(n){return n instanceof g}function Hi(n){if(n instanceof M||at(n))return false;let e=p(n);return e.kind==="NETWORK"||e.kind==="CANCELLED"||e.kind==="BACKEND"||e.kind==="RATE_LIMITED"}var Fi=new Set(["ConnectionRefused","ECONNREFUSED","ENOTFOUND","ETIMEDOUT","EAI_AGAIN"]);function Wi(n){if(n instanceof TypeError&&/fetch/i.test(n.message))return true;if(n&&typeof n=="object"){let e=n.code;if(typeof e=="string"&&Fi.has(e))return true}return false}function $i(n){return `Unable to connect to ${n}. Is the computer able to access the url?`}function Ca(n,e){if(K(n))return false;let t=N$1(n),r=N$1(e);return !t||!r?false:O(t,r)<0}function Wr(n,e){return new g("CLIENT_INCOMPATIBLE",n,412,e)}function Gi(n,e){let t=Ir(n,e);if(t)throw Wr(t.message,t.hint)}function Ki(n,e){if(!(n!=="thing.rename"||typeof e?.eventRequestId=="string"))return new g("VALIDATION_ERROR","thing.rename takes (orgName, repoName, name, newName, { eventRequestId }): name and newName are full Thing names. The v1 order (orgName, repoName, shapeName, oldName, newName, opts) is gone.")}var Lr=class n$1{apiUrl;fetchImpl;accessToken;clientIdentity;#e;decorateResponses;functionLogMode;getToken;compatibilityCheck;overrideNoticePrinted=false;compatibilityNoticesPrinted=new Set;repositoryExport=Qe((e,t)=>this.fetchWithAuth(`${this.apiUrl.replace(/\/$/,"")}${e}`,t),e=>this.httpResponseError(e),(e,t)=>(this.fetchImpl??globalThis.fetch)(e,t));noteCompatibilityHeaders(e){let t$1=[],r=e.get(t);if(r){let{name:o,version:s}=this.clientIdentity;t$1.push(`${o} ${s} is older than the backend's minimum supported version ${r}. ${et(o)}`);}let i=e.get(o);if(i!==null){let o=new Set(i.split(","));for(let s of this.clientFlags)o.has(s)||t$1.push(`client flag "${s}" is not honored by this backend`);}for(let o of t$1)this.compatibilityNoticesPrinted.has(o)||(this.compatibilityNoticesPrinted.add(o),console.error(`warmhub: ${o}`));}noteCompatibilityOverride(){this.overrideNoticePrinted||(this.overrideNoticePrinted=true,console.error(`warmhub: compatibility checks overridden by client flag ${p$1}; the server remains authoritative.`));}assertWriteCompatible(){return this.clientFlags.includes(p$1)?(this.noteCompatibilityOverride(),Promise.resolve()):K(this.clientIdentity.version)&&Or(this.apiUrl,kr)?Promise.reject(Wr(`Development client ${this.clientIdentity.name}/${this.clientIdentity.version} cannot write to production.`,"Install a released WarmHub client artifact before writing to api.warmhub.ai.")):K(this.clientIdentity.version)&&this.clientIdentity.name!==w?Promise.resolve():this.diagnostics.assertCompatible()}pinnedShapeRefusal(e,t){if(e!=="stream.append")return;let r=t?.operations;if(!Array.isArray(r))return;let i=r.findIndex(o=>Array.isArray(o?.shapes)&&o.shapes.some(s=>typeof s=="string"&&qe(s)));return i<0?void 0:new y(i,Me)}createLocalRefusalLink(){return ()=>({op:e,next:t})=>{let r=Ki(e.path,e.input)??this.pinnedShapeRefusal(e.path,e.input);return r?observable(i=>{i.error(TRPCClientError.from(r));}):t(e)}}createCompatibilityLink(){return ()=>({op:e,next:t})=>e.type!=="mutation"||u.has(e.path)?t(e):observable(r=>{let i=false,o;return (async()=>{try{await this.assertWriteCompatible();}catch(s){if(i)return;r.error(TRPCClientError.from(s));return}i||(o=t(e).subscribe(r));})(),()=>{i=true,o?.unsubscribe();}})}auth={getClientId:async()=>{try{return await this.trpc.auth.getClientId.query()}catch(e){throw p(e)}},sync:async()=>{try{return await this.trpc.auth.sync.mutate()}catch(e){throw p(e)}},currentUser:async()=>{try{return await this.trpc.auth.currentUser.query()}catch(e){throw p(e)}},whoami:async()=>{try{return await this.trpc.auth.whoami.query()}catch(e){throw p(e)}}};homepage={featuredLists:async()=>{try{return await this.trpc.homepage.featuredLists.query()}catch(e){throw p(e)}}};access={resolve:async e=>{try{return await this.trpc.access.resolve.query(e)}catch(t){throw p(t)}}};diagnostics={ping:async()=>{let e=await this.fetchWithAuth(`${this.apiUrl.replace(/\/$/,"")}/health`);if(!e.ok)throw new g("BACKEND",`Health request failed with status ${e.status}`,e.status);return await e.json()},capabilities:async()=>{try{return await this.trpc.diagnostics.capabilities.query()}catch(e){throw p(e)}},assertCompatible:()=>{if(this.compatibilityCheck)return this.compatibilityCheck;let e=(async()=>{let t=await this.diagnostics.capabilities();Gi(t,this.clientIdentity);})();return this.compatibilityCheck=e,e.catch(t=>{Vi(t)&&t.code==="CLIENT_INCOMPATIBLE"||this.compatibilityCheck===e&&(this.compatibilityCheck=void 0);}),e}};component={list:async(e,t,r)=>{try{return await this.trpc.component.list.query({orgName:e,repoName:t,limit:r?.limit,cursor:r?.cursor})}catch(i){throw p(i)}},listIter:(e,t,r)=>C(i=>this.component.list(e,t,{...r,cursor:i}),i=>i.items,r?.cursor),listAll:async(e,t,r)=>{let{max:i,...o}=r??{};return await E(s=>this.component.list(e,t,{...o,cursor:s}),s=>s.items,i,o.cursor)},search:async(e,t)=>{try{return await this.trpc.component.search.query({query:e,limit:t?.limit,cursor:t?.cursor})}catch(r){throw p(r)}},searchIter:(e,t)=>C(r=>this.component.search(e,{...t,cursor:r}),r=>r.items,t?.cursor),searchAll:async(e,t)=>{let{max:r,...i}=t??{};return await E(o=>this.component.search(e,{...i,cursor:o}),o=>o.items,r,i.cursor)},get:async(e,t,r)=>{try{return await this.trpc.component.get.query({orgName:e,repoName:t,componentRef:r})}catch(i){throw p(i)}},history:async(e,t,r)=>{try{return await this.trpc.component.history.query({orgName:e,repoName:t,componentRef:r?.componentRef,limit:r?.limit})}catch(i){throw p(i)}},install:async(e,t,r,i)=>{try{return await this.trpc.component.install.mutate({orgName:e,repoName:t,componentRef:r,submissionId:i.submissionId})}catch(o){throw p(o)}},uninstall:async(e,t,r,i)=>{try{return await this.trpc.component.uninstall.mutate({orgName:e,repoName:t,componentRef:r,submissionId:i.submissionId})}catch(o){throw p(o)}},registry:{register:async(e,t,r)=>{try{return await this.trpc.component.registry.register.mutate({orgName:e,componentName:t,...r})}catch(i){throw p(i)}},unregister:async(e,t)=>{try{return await this.trpc.component.registry.unregister.mutate({orgName:e,componentName:t})}catch(r){throw p(r)}},list:async e=>{try{return await this.trpc.component.registry.list.query({orgName:e})}catch(t){throw p(t)}},view:async(e,t)=>{try{return await this.trpc.component.registry.view.query({orgName:e,componentName:t})}catch(r){throw p(r)}},update:async(e,t,r)=>{try{return await this.trpc.component.registry.update.mutate({orgName:e,componentName:t,...r})}catch(i){throw p(i)}},resolve:async(e,t,r)=>await this.requestJson(`/api/component-registry/${encodeURIComponent(e)}/${encodeURIComponent(t)}/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({installRepo:r})}),setupCall:async(e,t,r)=>(await this.assertWriteCompatible(),await this.requestJson(`/api/component-registry/${encodeURIComponent(e)}/${encodeURIComponent(t)}/setup-call`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}))},cli:{call:async(e,t,r,i)=>(await this.assertWriteCompatible(),await this.requestJson(`/api/component-registry/${encodeURIComponent(e)}/${encodeURIComponent(t)}/cli/${encodeURIComponent(r)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i)}))}};ops(e){return new $(e)}commit={validate:async(e,t,r,i)=>{try{return await Wt(this.trpc.commit.validate,this.thingShapesReader(e,t),e,t,r,i)}catch(o){throw p(o)}},apply:async(e,t,r,i,o)=>{try{return await W(this,{orgName:e,repoName:t,committer:o?.committer,message:r,componentRef:o?.componentRef,chunkSize:o?.chunkSize,skipExisting:o?.skipExisting,streamId:o?.streamId,submissionId:o?.submissionId,returnRepoSeq:o?.returnRepoSeq,retry:o?.retry,operations:i})}catch(s){throw s instanceof k||s instanceof _?s:p(s)}},applyStreaming:(e,t,r,i,o)=>Cr({orgName:e,repoName:t,message:r,operations:i,options:o},{prepare:async s=>await this.prepareStreamingSubmissionRequest(s),localError:(s,a)=>new g(s,a),normalizeLocalError:p,readThings:this.thingShapesReader(e,t)}),getReceipt:async(e,t,r)=>{try{return await this.trpc.commit.getReceipt.query({orgName:e,repoName:t,eventRequestId:r})}catch(i){throw p(i)}},getReceiptMetadata:async(e,t,r)=>{try{return await this.trpc.commit.getReceiptMetadata.query({orgName:e,repoName:t,eventRequestId:r})}catch(i){throw p(i)}}};org={get:async e=>{try{return await this.trpc.org.get.query({orgName:e})}catch(t){throw p(t)}},getCallerRole:async e=>{try{return await this.trpc.org.getCallerRole.query({orgName:e})}catch(t){throw p(t)}},list:async e=>{try{return {items:await this.trpc.org.list.query({includeArchived:e?.includeArchived})}}catch(t){throw p(t)}},create:async(e,t,r)=>{try{return await this.trpc.org.create.mutate({name:e,displayName:t,description:r})}catch(i){throw p(i)}},setDescription:async(e,t)=>{try{return await this.trpc.org.setDescription.mutate({orgName:e,description:t})}catch(r){throw p(r)}},setDisplayName:async(e,t)=>{try{return await this.trpc.org.setDisplayName.mutate({orgName:e,displayName:t})}catch(r){throw p(r)}},rename:async(e,t)=>{try{return await this.trpc.org.rename.mutate({orgName:e,newName:t})}catch(r){throw p(r)}},update:async e=>{try{return await this.trpc.org.update.mutate(e)}catch(t){throw p(t)}},addMember:async(e,t,r="editor")=>{try{return await this.trpc.org.addMember.mutate({orgName:e,email:t,role:r})}catch(i){throw p(i)}},removeMember:async(e,t)=>{try{await this.trpc.org.removeMember.mutate({orgName:e,email:t});}catch(r){throw p(r)}},leave:async e=>{try{await this.trpc.org.leave.mutate({orgName:e});}catch(t){throw p(t)}},changeMemberRole:async(e,t,r)=>{try{return await this.trpc.org.changeMemberRole.mutate({orgName:e,email:t,role:r})}catch(i){throw p(i)}},setMemberScopes:async(e,t,r)=>{try{await this.trpc.org.setMemberScopes.mutate({orgName:e,email:t,scopes:r});}catch(i){throw p(i)}},clearMemberScopes:async(e,t)=>{try{await this.trpc.org.clearMemberScopes.mutate({orgName:e,email:t});}catch(r){throw p(r)}},listMembers:async(e,t)=>{try{return await this.trpc.org.listMembers.query({orgName:e,pending:t?.pending})}catch(r){throw p(r)}},archive:async e=>{try{return await this.trpc.org.archive.mutate({orgName:e})}catch(t){throw p(t)}},unarchive:async e=>{try{return await this.trpc.org.unarchive.mutate({orgName:e})}catch(t){throw p(t)}},serviceAccounts:{create:async e=>{try{return await this.trpc.org.serviceAccount.create.mutate({orgName:e.orgName,name:e.name,role:e.role,description:e.description})}catch(t){throw p(t)}},list:async e=>{try{return await this.trpc.org.serviceAccount.list.query({orgName:e.orgName,includeDisabled:e.includeDisabled})}catch(t){throw p(t)}},get:async e=>{try{return await this.trpc.org.serviceAccount.get.query({orgName:e.orgName,name:e.name})}catch(t){throw p(t)}},setRole:async e=>{try{return await this.trpc.org.serviceAccount.setRole.mutate({orgName:e.orgName,name:e.name,role:e.role})}catch(t){throw p(t)}},disable:async e=>{try{return await this.trpc.org.serviceAccount.disable.mutate({orgName:e.orgName,name:e.name})}catch(t){throw p(t)}},enable:async e=>{try{return await this.trpc.org.serviceAccount.enable.mutate({orgName:e.orgName,name:e.name})}catch(t){throw p(t)}},delete:async e=>{try{await this.trpc.org.serviceAccount.delete.mutate({orgName:e.orgName,name:e.name});}catch(t){throw p(t)}}}};repo={checkpoint:or(()=>this.trpc,p),export:(e,t,r)=>this.repositoryExport.stream(e,t,r),exportPrepare:(e,t,r)=>this.repositoryExport.prepare(e,t,r),get:async(e,t)=>{try{return await this.trpc.repo.get.query({orgName:e,repoName:t})}catch(r){throw p(r)}},getStats:async(e,t)=>{try{return await this.trpc.repo.stats.query({orgName:e,repoName:t})}catch(r){throw p(r)}},getStatsBatch:async(e,t)=>{try{return await this.trpc.repo.statsBatch.query({orgName:e,repoNames:t})}catch(r){throw p(r)}},getConfigureStats:async(e,t)=>{try{return await this.trpc.repo.configureStats.query({orgName:e,repoName:t})}catch(r){throw p(r)}},getShapeInstanceCounts:async(e,t)=>{try{return await this.trpc.repo.shapeInstanceCounts.query({orgName:e,repoName:t})}catch(r){throw p(r)}},list:async(e,t)=>{try{return await this.trpc.repo.list.query({orgName:e,limit:t?.limit,cursor:t?.cursor,includeArchived:t?.includeArchived,search:t?.search,sort:t?.sort})}catch(r){throw p(r)}},listIter:(e,t)=>C(r=>this.repo.list(e,{...t,cursor:r}),r=>r.items,t?.cursor),listAll:async(e,t)=>{let{max:r,...i}=t??{};return await E(o=>this.repo.list(e,{...i,cursor:o}),o=>o.items,r,i.cursor)},search:async(e,t)=>{try{return await this.trpc.repo.search.query({query:e,limit:t?.limit,cursor:t?.cursor})}catch(r){throw p(r)}},searchIter:(e,t)=>C(r=>this.repo.search(e,{...t,cursor:r}),r=>r.items,t?.cursor),searchAll:async(e,t)=>{let{max:r,...i}=t??{};return await E(o=>this.repo.search(e,{...i,cursor:o}),o=>o.items,r,i.cursor)},create:async(e,t,r,i,o)=>{try{return await this.trpc.repo.create.mutate({orgName:e,repoName:t,description:r,visibility:i,displayName:o})}catch(s){throw p(s)}},setDescription:async(e,t,r)=>{try{return await this.trpc.repo.setDescription.mutate({orgName:e,repoName:t,description:r})}catch(i){throw p(i)}},setDisplayName:async(e,t,r)=>{try{return await this.trpc.repo.setDisplayName.mutate({orgName:e,repoName:t,displayName:r})}catch(i){throw p(i)}},setVisibility:async(e,t,r)=>{try{return await this.trpc.repo.setVisibility.mutate({orgName:e,repoName:t,visibility:r})}catch(i){throw p(i)}},rename:async(e,t,r)=>{try{return await this.trpc.repo.rename.mutate({orgName:e,repoName:t,newName:r})}catch(i){throw p(i)}},update:async e=>{try{return await this.trpc.repo.update.mutate(e)}catch(t){throw p(t)}},archive:async(e,t)=>{try{return await this.trpc.repo.archive.mutate({orgName:e,repoName:t})}catch(r){throw p(r)}},unarchive:async(e,t)=>{try{return await this.trpc.repo.unarchive.mutate({orgName:e,repoName:t})}catch(r){throw p(r)}},delete:async(e,t)=>{try{let r=await this.trpc.repo.delete.mutate({orgName:e,repoName:t});return {graceExpiresAt:new Date(r.graceExpiresAt)}}catch(r){throw p(r)}},listPage:async(e,t)=>{try{return await this.trpc.repo.listPage.query({orgName:e,limit:t?.limit,cursor:t?.cursor,includeArchived:t?.includeArchived,search:t?.search,sort:t?.sort})}catch(r){throw p(r)}},listPageIter:(e,t)=>C(r=>this.repo.listPage(e,{...t,cursor:r}),r=>r.items,t?.cursor),listPageAll:async(e,t)=>{let{max:r,...i}=t??{};return await E(o=>this.repo.listPage(e,{...i,cursor:o}),o=>o.items,r,i.cursor)},listForCaller:async e=>{try{return await this.trpc.repo.listForCaller.query({limit:e?.limit,sort:e?.sort})}catch(t){throw p(t)}},explore:async e=>{try{return await this.trpc.repo.explore.query({search:e?.search,org:e?.org,activity:e?.activity,hasSubscriptions:e?.hasSubscriptions,minThings:e?.minThings,sort:e?.sort,limit:e?.limit,cursor:e?.cursor,slugs:e?.slugs})}catch(t){throw p(t)}},exploreIter:e=>(_r(e),C(t=>this.repo.explore({...e,cursor:t}),t=>t.items,e?.cursor)),exploreAll:async e=>{_r(e);let{max:t,...r}=e??{};return await E(i=>this.repo.explore({...r,cursor:i}),i=>i.items,t,r.cursor)},getReadme:async(e,t)=>{try{return await this.trpc.repo.getReadme.query({orgName:e,repoName:t})}catch(r){throw p(r)}},getAgents:async(e,t)=>{try{return await this.trpc.repo.getAgents.query({orgName:e,repoName:t})}catch(r){throw p(r)}},getLicense:async(e,t)=>{try{return await this.trpc.repo.getLicense.query({orgName:e,repoName:t})}catch(r){throw p(r)}},describe:async(e,t,r={})=>{try{return await this.trpc.repo.describe.query({orgName:e,repoName:t,includeHead:r.includeHead})}catch(i){throw p(i)}},setReadme:async(e,t,r,i)=>{try{return Dr("Readme.content",r),await this.trpc.repo.setReadme.mutate({orgName:e,repoName:t,eventRequestId:i.eventRequestId,content:r})}catch(o){throw p(o)}},setAgents:async(e,t,r,i)=>{try{return Dr("Agents.content",r),await this.trpc.repo.setAgents.mutate({orgName:e,repoName:t,eventRequestId:i.eventRequestId,content:r})}catch(o){throw p(o)}},getLlmsTxt:async(e,t)=>{try{return await this.trpc.repo.getLlmsTxt.query({orgName:e,repoName:t})}catch(r){throw p(r)}},index:{describe:async(e,t)=>{try{return await this.trpc.repo.index.describe.query({orgName:e,repoName:t})}catch(r){throw p(r)}},pin:async(e,t,r,i)=>{try{return await this.trpc.repo.index.pin.mutate({orgName:e,repoName:t,shape:r,fieldPath:i})}catch(o){throw p(o)}},unpin:async(e,t,r,i)=>{try{return await this.trpc.repo.index.unpin.mutate({orgName:e,repoName:t,shape:r,fieldPath:i})}catch(o){throw p(o)}}}};shape={list:async(e,t,r)=>{try{return await this.trpc.shape.list.query({orgName:e,repoName:t,match:r?.match,componentRef:r?.componentRef,excludeComponents:r?.excludeComponents,includeRetracted:r?.includeRetracted})}catch(i){throw p(i)}},get:async(e,t,r,i)=>{try{return await this.trpc.shape.get.query({orgName:e,repoName:t,shapeName:r,includeRetracted:i?.includeRetracted})}catch(o){throw p(o)}},create:async(e,t,r,i,o)=>{let s=Z(r,{fields:i,...o.description!==void 0?{description:o.description}:{},...o.composes!==void 0?{composes:o.composes}:{}},"add");if(s)throw new g("VALIDATION_ERROR",s);try{return await this.trpc.shape.create.mutate({orgName:e,repoName:t,shapeName:r,fields:i,eventRequestId:o.eventRequestId,description:o.description,composes:o.composes})}catch(a){throw p(a)}},revise:async(...e)=>{let[t,r,i]=e,o=e.length===5?e[3]:void 0,s=e.length===5?e[4]:e[3],a=o?Z(i,{fields:o,...s.description!==void 0?{description:s.description}:{},...s.composes!==void 0?{composes:s.composes}:{}},"revise"):void 0;if(a)throw new g("VALIDATION_ERROR",a);try{return await this.trpc.shape.revise.mutate({orgName:t,repoName:r,shapeName:i,newFields:o,eventRequestId:s.eventRequestId,description:s.description,composes:s.composes})}catch(u){throw p(u)}},remove:async(e,t,r,i)=>{try{return await this.trpc.shape.remove.mutate({orgName:e,repoName:t,shapeName:r,eventRequestId:i.eventRequestId})}catch(o){throw p(o)}},rename:async(e,t,r,i,o)=>{try{return await this.trpc.shape.rename.mutate({orgName:e,repoName:t,oldName:r,newName:i,eventRequestId:o.eventRequestId})}catch(s){throw p(s)}},history:async(e,t,r,i={})=>{try{return await this.trpc.shape.history.query({orgName:e,repoName:t,name:r,includeRetracted:i.includeRetracted,limit:i.limit,cursor:i.cursor})}catch(o){throw p(o)}},historyIter:(e,t,r,i={})=>C(o=>this.shape.history(e,t,r,{...i,cursor:o}),o=>o.versions,i.cursor),historyAll:async(e,t,r,i)=>{let{max:o,...s}=i??{};return await E(a=>this.shape.history(e,t,r,{...s,cursor:a}),a=>a.versions,o,s.cursor)}};subscription={create:async e=>{try{let t=await this.trpc.subscription.create.mutate(Di(e));return Oe(t)}catch(t){throw p(t)}},get:async(...e)=>{try{let t=await this.trpc.subscription.get.query(ne(e));return Oe(t)}catch(t){throw p(t)}},reveal:async(...e)=>{try{return await this.trpc.subscription.reveal.query(ne(e))}catch(t){throw p(t)}},list:async(...e)=>{try{let t=await this.trpc.subscription.list.query(_i(e));return ki(t)}catch(t){throw p(t)}},update:async e=>{try{let t=await this.trpc.subscription.update.mutate(Li(e));return Oe(t)}catch(t){throw p(t)}},pause:async(...e)=>{try{return await this.trpc.subscription.pause.mutate(ne(e))}catch(t){throw p(t)}},resume:async(...e)=>{try{return await this.trpc.subscription.resume.mutate(ne(e))}catch(t){throw p(t)}},remove:async(...e)=>{try{return await this.trpc.subscription.remove.mutate(ne(e))}catch(t){throw p(t)}},bindCredentials:async(...e)=>{try{return await this.trpc.subscription.bindCredentials.mutate(Ni(e))}catch(t){throw p(t)}},unbindCredentials:async(...e)=>{try{return await this.trpc.subscription.unbindCredentials.mutate(Pi(e))}catch(t){throw p(t)}}};action={acquireLease:async(e,t,r,i,o,s)=>{try{return await this.trpc.action.acquireLease.mutate({orgName:e,repoName:t,subscriptionName:r,holderId:i,holderType:o,graceMs:s?.graceMs,ttlMs:s?.ttlMs})}catch(a){throw p(a)}},heartbeatLease:async(e,t,r,i,o)=>{try{return await this.trpc.action.heartbeatLease.mutate({orgName:e,repoName:t,subscriptionName:r,holderId:i,ttlMs:o})}catch(s){throw p(s)}},releaseLease:async(e,t,r,i)=>{try{return await this.trpc.action.releaseLease.mutate({orgName:e,repoName:t,subscriptionName:r,holderId:i})}catch(o){throw p(o)}},claimDelivery:async(e,t,r,i)=>{let o=typeof r=="string"?{runId:r}:r;try{return await this.trpc.action.claimDelivery.mutate({orgName:e,repoName:t,...o,holderId:i})}catch(s){throw p(s)}},completeDelivery:async(e,t,r,i)=>{let o=typeof r=="string"?{runId:r}:r;try{return await this.trpc.action.completeDelivery.mutate({orgName:e,repoName:t,...o,holderId:i})}catch(s){throw p(s)}},liveFeed:async(e,t,r,i)=>{try{return await this.trpc.action.liveFeed.query({orgName:e,repoName:t,subscriptionName:r,limit:i?.limit,cursor:i?.cursor})}catch(o){throw p(o)}},liveFeedIter:(e,t,r,i)=>C(o=>this.action.liveFeed(e,t,r,{...i,cursor:o}),o=>o.items,i?.cursor),liveFeedAll:async(e,t,r,i)=>{let{max:o,...s}=i??{};return await E(a=>this.action.liveFeed(e,t,r,{...s,cursor:a}),a=>a.items,o,s.cursor)},listRuns:async(e,t,r)=>{try{return await this.trpc.action.listRuns.query({orgName:e,repoName:t,runId:r?.runId,subscriptionName:r?.subscriptionName,status:r?.status,outcome:r?.outcome,since:r?.since,cursor:r?.cursor,limit:r?.limit})}catch(i){throw p(i)}},listRunsIter:(e,t,r)=>C(i=>this.action.listRuns(e,t,{...r,since:i===void 0?r?.since:void 0,cursor:i}),i=>i.items,r?.cursor),listRunsAll:async(e,t,r)=>{let{max:i,...o}=r??{};return await E(s=>this.action.listRuns(e,t,{...o,since:s===void 0?o.since:void 0,cursor:s}),s=>s.items,i,o.cursor)},latestRuns:async(e,t)=>{try{return await this.trpc.action.latestRuns.query({orgName:e,repoName:t})}catch(r){throw p(r)}},runStats:async(e,t,r)=>{try{return await this.trpc.action.runStats.query({orgName:e,repoName:t,subscriptionName:r?.subscriptionName,since:r?.since})}catch(i){throw p(i)}},getRunAttempts:async(e,t,r)=>{try{return await this.trpc.action.getRunAttempts.query({orgName:e,repoName:t,runId:r})}catch(i){throw p(i)}},listNotifications:async(e,t,r)=>{try{return await this.trpc.action.listNotifications.query({orgName:e,repoName:t,since:r?.since,limit:r?.limit})}catch(i){throw p(i)}}};collection={create:async(e,t,r)=>{try{return Mi(r.type,r),await this.trpc.collection.create.mutate({orgName:e,repoName:t,eventRequestId:r.eventRequestId,type:r.type,name:r.name,members:r.members,from:r.from,add:r.add,remove:r.remove,replaceMembers:r.replaceMembers,query:r.query,sourceOrgName:r.sourceRepo?.orgName,sourceRepoName:r.sourceRepo?.repoName,skipExisting:r.skipExisting,message:r.message,committer:r.committer})}catch(i){throw p(i)}},members:async(e,t,r,i)=>{try{return await this.trpc.collection.members.query({orgName:e,repoName:t,wref:r,version:i?.version,limit:i?.limit,cursor:i?.cursor,shape:i?.shape})}catch(o){throw p(o)}},membersIter:(e,t,r,i)=>{let o=i?.version;return C(async s=>{let a=await this.collection.members(e,t,r,{...i,version:o,cursor:s});return o??=a.version,a},s=>s.items,i?.cursor)},membersAll:async(e,t,r,i)=>{let{max:o,...s}=i??{},a=s.version;return await E(async u=>{let l=await this.collection.members(e,t,r,{...s,version:a,cursor:u});return a??=l.version,l},u=>u.items,o,s.cursor)},contains:async(e,t,r,i,o)=>{try{return await this.trpc.collection.contains.query({orgName:e,repoName:t,wref:r,version:o?.version,members:i,position:o?.position,shape:o?.shape})}catch(s){throw p(s)}},diff:async(e,t,r,i,o)=>{try{return await this.trpc.collection.diff.query({orgName:e,repoName:t,leftWref:r,rightWref:i,leftVersion:o?.leftVersion,rightVersion:o?.rightVersion,mode:o?.mode,shape:o?.shape})}catch(s){throw p(s)}},revise:async(e,t,r,i)=>{try{if(st(i.query)&&!ve(i.query))throw new g("VALIDATION_ERROR","Selector-backed collection sources require shape, about, match, componentRef, or where; kind and excludeComponents only narrow an existing selector.");if(i.sourceRepo&&!ve(i.query))throw new g("VALIDATION_ERROR","sourceRepo requires a selector-backed collection query");if(i.sourceRepo&&Hr(i))throw new g("VALIDATION_ERROR","sourceRepo cannot be combined with explicit members; use canonical wh:org/repo/... member wrefs or omit sourceRepo.");return await this.trpc.collection.revise.mutate({orgName:e,repoName:t,eventRequestId:i.eventRequestId,wref:r,members:i.members,add:i.add,remove:i.remove,query:i.query,sourceOrgName:i.sourceRepo?.orgName,sourceRepoName:i.sourceRepo?.repoName,message:i.message,committer:i.committer})}catch(o){throw p(o)}},stats:async(e,t,r,i)=>{try{return await this.trpc.collection.stats.query({orgName:e,repoName:t,wref:r,version:i?.version,shape:i?.shape})}catch(o){throw p(o)}}};view={evaluate:async(e,t,r,i)=>{try{return await this.trpc.view.evaluate.query({orgName:e,repoName:t,wref:r,limit:i?.limit,cursor:i?.cursor})}catch(o){throw p(o)}},evaluateIter:(e,t,r,i)=>C(o=>this.view.evaluate(e,t,r,{...i,cursor:o}),o=>o.items,i?.cursor),evaluateAll:async(e,t,r,i)=>{let{max:o,...s}=i??{};return await E(a=>this.view.evaluate(e,t,r,{...s,cursor:a}),a=>a.items,o,s.cursor)}};grant=Qt(()=>this.trpc,p);thing={head:async(e,t,r)=>{try{return await this.trpc.thing.head.query({orgName:e,repoName:t,shape:r?.shape,declaredShape:r?.declaredShape,shapeless:r?.shapeless,includeValidatedShapes:r?.includeValidatedShapes,kind:Ie(r?.kind),match:r?.match,dataMode:r?.dataMode,includeRetracted:r?.includeRetracted,limit:r?.limit,cursor:r?.cursor,componentRef:r?.componentRef,excludeComponents:r?.excludeComponents,excludeInfraShapes:r?.excludeInfraShapes,where:r?.where,sinceRepoSeq:r?.sinceRepoSeq})}catch(i){throw p(i)}},headIter:(e,t,r)=>C(i=>this.thing.head(e,t,{...r,cursor:i}),i=>i.items,r?.cursor),headAll:async(e,t,r)=>{let{max:i,...o}=r??{};return await E(s=>this.thing.head(e,t,{...o,cursor:s}),s=>s.items,i,o.cursor)},headChanges:async(e,t,r)=>(Tr(r?.sinceRepoSeq),await Nr(i=>this.thing.head(e,t,{...r,includeRetracted:true,cursor:i}))),get:async(e,t,r,i,o)=>{try{return await this.trpc.thing.get.query({orgName:e,repoName:t,wref:r,version:i,includeRetracted:o?.includeRetracted,dataMode:o?.dataMode})}catch(s){throw p(s)}},getWithLease:async(e,t,r,i)=>{try{return await this.trpc.thing.getWithLease.mutate({orgName:e,repoName:t,wref:r,ttlMs:i?.ttlMs})}catch(o){throw p(o)}},releaseLease:async(e,t,r,i)=>{try{await this.trpc.thing.releaseLease.mutate({orgName:e,repoName:t,wref:r,leaseId:i});}catch(o){throw p(o)}},graph:async(e,t,r,i)=>{try{return await this.trpc.thing.graph.query({orgName:e,repoName:t,wref:r,version:i?.version,depth:i?.depth,limit:i?.limit})}catch(o){throw p(o)}},getMany:async(e,t,r,i,o)=>{try{return await rt(r,o,s=>this.trpc.thing.getMany.query({orgName:e,repoName:t,wrefs:s,version:i,includeRetracted:o?.includeRetracted,dataMode:o?.dataMode}))}catch(s){throw p(s)}},headVersions:async(e,t,r,i)=>{try{return await rt(r,i,o=>this.trpc.thing.headVersions.query({orgName:e,repoName:t,wrefs:o}))}catch(o){throw p(o)}},names:async(e,t,r,i)=>{try{return await rt(r,i,o=>this.trpc.thing.names.query({orgName:e,repoName:t,durableIds:o}))}catch(o){throw p(o)}},history:async(e,t,r)=>{try{return await this.trpc.thing.history.query({orgName:e,repoName:t,wref:r.wref,shape:r.shape,declaredShape:r.declaredShape,about:r.about,includeRetracted:r.includeRetracted,resolveCollections:r.resolveCollections,match:r.match,limit:r.limit,cursor:r.cursor})}catch(i){throw p(i)}},historyIter:(e,t,r)=>C(i=>this.thing.history(e,t,{...r,cursor:i}),i=>i.versions,r.cursor),historyAll:async(e,t,r)=>{let{max:i,...o}=r;return await E(s=>this.thing.history(e,t,{...o,cursor:s}),s=>s.versions,i,o.cursor)},rename:async(e,t,r,i,o)=>{try{return await this.trpc.thing.rename.mutate({orgName:e,repoName:t,name:r,newName:i,eventRequestId:o.eventRequestId})}catch(s){throw p(s)}},remove:async(e,t,r,i)=>{try{return await this.trpc.thing.remove.mutate({orgName:e,repoName:t,wref:r,expectedVersion:i.expectedVersion,eventRequestId:i.eventRequestId})}catch(o){throw p(o)}},redact:async(e,t,r,i)=>{try{return await this.trpc.thing.redact.mutate({orgName:e,repoName:t,durableId:r,expectedVersion:i.expectedVersion,eventRequestId:i.eventRequestId})}catch(o){throw p(o)}},rewrite:async(e,t,r,i)=>{try{return await this.trpc.thing.rewrite.mutate({orgName:e,repoName:t,wref:r,version:i.version,shapes:i.shapes,data:i.data,eventRequestId:i.eventRequestId})}catch(o){throw p(o)}},resolve:async(e,t,r)=>{try{return await this.trpc.thing.resolve.query({orgName:e,repoName:t,wref:r})}catch(i){throw p(i)}},about:async(e,t,r,i)=>{try{return await this.trpc.thing.about.query({orgName:e,repoName:t,wref:r,shape:i?.shape,match:i?.match,includeRetracted:i?.includeRetracted,depth:i?.depth,resolveCollections:i?.resolveCollections,role:i?.role,limit:i?.limit,cursor:i?.cursor,where:i?.where})}catch(o){throw p(o)}},aboutIter:(e,t,r,i)=>C(o=>this.thing.about(e,t,r,{...i,cursor:o}),o=>o.assertions,i?.cursor),aboutAll:async(e,t,r,i)=>{let{max:o,...s}=i??{};return await E(a=>this.thing.about(e,t,r,{...s,cursor:a}),a=>a.assertions,o,s.cursor)},query:async(e,t,r)=>{try{return await this.trpc.thing.query.query({orgName:e,repoName:t,shape:r?.shape,declaredShape:r?.declaredShape,shapeless:r?.shapeless,includeValidatedShapes:r?.includeValidatedShapes,about:r?.about,affirmedAbout:r?.affirmedAbout,kind:Ie(r?.kind),match:r?.match,includeRetracted:r?.includeRetracted,resolveCollections:r?.resolveCollections,role:r?.role,limit:r?.limit,cursor:r?.cursor,componentRef:r?.componentRef,excludeComponents:r?.excludeComponents,excludeInfraShapes:r?.excludeInfraShapes,where:r?.where,sinceRepoSeq:r?.sinceRepoSeq})}catch(i){throw p(i)}},queryIter:(e,t,r)=>C(i=>this.thing.query(e,t,{...r,cursor:i}),i=>i.items,r?.cursor),queryAll:async(e,t,r)=>{let{max:i,...o}=r??{};return await E(s=>this.thing.query(e,t,{...o,cursor:s}),s=>s.items,i,o.cursor)},queryChanges:async(e,t,r)=>(Tr(r?.sinceRepoSeq),await Nr(i=>this.thing.query(e,t,{...r,includeRetracted:true,cursor:i}))),search:async(e,t,r,i)=>{try{return await this.trpc.thing.search.query({orgName:e,repoName:t,query:r,shape:i?.shape,about:i?.about,affirmedAbout:i?.affirmedAbout,kind:Ie(i?.kind),match:i?.match,includeRetracted:i?.includeRetracted,resolveCollections:i?.resolveCollections,limit:i?.limit,cursor:i?.cursor,componentRef:i?.componentRef,excludeComponents:i?.excludeComponents,excludeInfraShapes:i?.excludeInfraShapes,mode:i?.mode,nameMatch:i?.nameMatch})}catch(o){throw p(o)}},searchIter:(e,t,r,i)=>C(o=>this.thing.search(e,t,r,{...i,cursor:o}),o=>o.items,i?.cursor),searchAll:async(e,t,r,i)=>{let{max:o,...s}=i??{};return await E(a=>this.thing.search(e,t,r,{...s,cursor:a}),a=>a.items,o,s.cursor)},count:async(e,t,r)=>{try{return await this.trpc.thing.count.query({orgName:e,repoName:t,shape:r?.shape,declaredShape:r?.declaredShape,shapeless:r?.shapeless,about:r?.about,affirmedAbout:r?.affirmedAbout,kind:Ie(r?.kind),match:r?.match,includeRetracted:r?.includeRetracted,resolveCollections:r?.resolveCollections,componentRef:r?.componentRef,excludeComponents:r?.excludeComponents,excludeInfraShapes:r?.excludeInfraShapes,where:r?.where,sinceRepoSeq:r?.sinceRepoSeq})}catch(i){throw p(i)}},refs:async(e,t,r,i)=>{try{return await this.trpc.thing.refs.query({orgName:e,repoName:t,wref:r,direction:i?.direction,fieldPath:i?.fieldPath,binding:i?.binding,limit:i?.limit,cursor:i?.cursor})}catch(o){throw p(o)}},refsIter:(e,t,r,i)=>C(o=>this.thing.refs(e,t,r,{...i,cursor:o}),o=>o.items,i?.cursor),refsAll:async(e,t,r,i)=>{let{max:o,...s}=i??{};return await E(a=>this.thing.refs(e,t,r,{...s,cursor:a}),a=>a.items,o,s.cursor)}};live={thingHead:async(e,t,r,i)=>this.watchRepoQuery(e,t,r?.signal,()=>this.thing.head(e,t,{shape:r?.shape,declaredShape:r?.declaredShape,shapeless:r?.shapeless,includeValidatedShapes:r?.includeValidatedShapes,kind:r?.kind,match:r?.match,dataMode:r?.dataMode,limit:r?.limit,cursor:r?.cursor,includeRetracted:r?.includeRetracted,where:r?.where}),i),thingHistory:async(e,t,r,i)=>this.watchRepoQuery(e,t,r.signal,()=>this.thing.history(e,t,{wref:r.wref,shape:r.shape,declaredShape:r.declaredShape,about:r.about,resolveCollections:r.resolveCollections,match:r.match,limit:r.limit,cursor:r.cursor,includeRetracted:r.includeRetracted}),i),subscriptionLog:async(e,t,r,i,o)=>this.watchRepoQuery(e,t,i?.signal,()=>this.action.liveFeed(e,t,r,{limit:i?.limit,cursor:i?.cursor}),o),subscribe:async(e,t,r,i)=>{let o=new AbortController,s=Mr(r?.signal,o),a=0,u=this.runLiveLoop(()=>this.trpc.live.issueTicket.mutate({orgName:e,repoName:t}),s,async l=>{if(l.type!=="invalidate")return;let d=l.data;a++,await qr(()=>i({topic:d.topic,affectedShapes:d.affectedShapes,affectedThings:d.affectedThings,affectedTargets:d.affectedTargets,hasNewCommit:d.hasNewCommit}));}).then(()=>({updates:a}));return {close(){o.abort();},closed:u}}};token={create:async e=>{try{return await this.trpc.token.create.mutate(e)}catch(t){throw p(t)}},list:async e=>{try{return await this.trpc.token.list.query(e?.includeInactive?{includeInactive:!0}:void 0)}catch(t){throw p(t)}},listForServiceAccount:async(e,t)=>{try{return await this.trpc.token.list.query({serviceAccount:e,includeInactive:t?.includeInactive})}catch(r){throw p(r)}},get:async(e,t)=>{try{return await this.trpc.token.get.query({name:e,serviceAccount:t?.serviceAccount})}catch(r){throw p(r)}},revoke:async(e,t)=>{try{return await this.trpc.token.revoke.mutate({name:e,serviceAccount:t?.serviceAccount})}catch(r){throw p(r)}}};stream={append:async e=>{try{return await this.trpc.stream.append.mutate(e)}catch(t){throw p(t)}}};credential={createSet:async(e,t,r,i)=>{try{return await this.trpc.credential.createSet.mutate({orgName:e,repoName:t,name:r,scope:i?.scope??"repo",description:i?.description})}catch(o){throw p(o)}},listSets:async(e,t)=>{try{return await this.trpc.credential.listSets.query({orgName:e,repoName:t})}catch(r){throw p(r)}},getSet:async(e,t,r)=>{try{return await this.trpc.credential.getSet.query({orgName:e,repoName:t,name:r})}catch(i){throw p(i)}},setKey:async(e,t,r,i,o)=>{try{return await this.trpc.credential.setKey.mutate({orgName:e,repoName:t,setName:r,keyName:i,value:o})}catch(s){throw p(s)}},setKeys:async(e,t,r,i)=>{try{return await this.trpc.credential.setKeys.mutate({orgName:e,repoName:t,setName:r,secrets:i})}catch(o){throw p(o)}},unsetKey:async(e,t,r,i)=>{try{return await this.trpc.credential.unsetKey.mutate({orgName:e,repoName:t,setName:r,keyName:i})}catch(o){throw p(o)}},deleteSet:async(e,t,r)=>{try{return await this.trpc.credential.deleteSet.mutate({orgName:e,repoName:t,setName:r})}catch(i){throw p(i)}},listAuditLog:async(e,t,r,i)=>{try{return await this.trpc.credential.listAuditLog.query({orgName:e,repoName:t,setName:r,limit:i?.limit})}catch(o){throw p(o)}},revokeSet:async(e,t,r,i)=>{try{return await this.trpc.credential.revokeSet.mutate({orgName:e,repoName:t,setName:r,reason:i?.reason})}catch(o){throw p(o)}}};credentials=this.credential;constructor(e,t){let r=typeof e=="string"?t:e;Ci(r);let i=typeof e=="string"?e:e?.apiUrl??kr;if(this.apiUrl=i,this.fetchImpl=r?.fetch,this.accessToken=r?.accessToken??r?.auth?.getToken,this.functionLogMode=r?.functionLogs??"off",this.clientIdentity={name:r?.client?.name??v,version:r?.client?.version??Ze},this.#e=Object.freeze([...Ei(r?.clientFlags)]),this.decorateResponses=r?.decorateResponses??false,typeof this.accessToken=="function"){let a=this.accessToken;this.getToken=async()=>await a();}else if(this.accessToken){let a=this.accessToken;this.getToken=async()=>a;}let o=`${i.replace(/\/$/,"")}/trpc`,s=((a,u)=>this.fetchWithAuth(a,u));Object.defineProperty(this,"trpc",{value:createTRPCProxyClient({links:[this.createLocalRefusalLink(),this.createCompatibilityLink(),zt({enabled:this.decorateResponses,lookupNames:async a=>{try{return await this.trpc.thing.names.query({durableIds:a})}catch(u){throw p(u)}}}),splitLink({condition:a=>Ii.has(a.path),true:httpLink({url:o,fetch:s,methodOverride:"POST"}),false:httpBatchLink({url:o,fetch:s,methodOverride:"POST"})})]}),enumerable:false,writable:false,configurable:true});}get clientFlags(){return this.#e}withAccessToken(e){let t={apiUrl:this.apiUrl,fetch:this.fetchImpl,accessToken:e,client:this.clientIdentity,clientFlags:this.clientFlags,decorateResponses:this.decorateResponses};return new n$1(t)}actions=this.action;async runLiveLoop(e,t,r,i){for(;!t.aborted;){let o=new AbortController,s=()=>o.abort();t.addEventListener("abort",s,{once:true});let a;try{let u=await e(),l=await this.openSse(u.ticket,o.signal,r);if(a=l.closed,await l.ready,t.aborted)return;await i?.(),await l.closed;}catch(u){if(t.aborted)return;if(u instanceof xe)throw u.cause;if(!Hi(u))throw p(u)}finally{t.removeEventListener("abort",s),o.abort(),a?.catch(()=>{});}await zi(ji,t);}}async openSse(e,t,r){let i=await this.fetchWithAuth(`${this.apiUrl.replace(/\/$/,"")}/sse?ticket=${encodeURIComponent(e)}`,{headers:{accept:"text/event-stream"},signal:t});if(!i.ok)throw await this.httpResponseError(i);let o=i.body?.getReader();if(!o)throw new g("BACKEND","SSE response body is missing");let s=()=>{},a=new Promise(l=>{s=l;}),u=(async()=>{let l=new TextDecoder,d="";try{for(;;){let{done:m,value:h}=await o.read();if(m)break;for(d+=l.decode(h,{stream:!0}).replaceAll(`\r
|
|
4
|
-
`,`
|
|
5
|
-
`);;){let b=d.indexOf(`
|
|
6
|
-
|
|
7
|
-
`);if(b===-1)break;let S=d.slice(0,b);d=d.slice(b+2);let R=Qi(S);if(R){if(R.type==="ready"){s();continue}await r(R);}}}}catch(m){if(Yi(m)||t.aborted)return;throw m}finally{s(),o.releaseLock();}})();return {ready:a,closed:u}}applyClientHeader(e){e.has(s)||e.set(s,y$1(this.clientIdentity.name,this.clientIdentity.version)),this.clientFlags.length>0&&!e.has(n)&&e.set(n,r(this.clientFlags));}async fetchWithAuth(e,t){let r=this.fetchImpl??globalThis.fetch,i=new Headers(t?.headers),o=await it(this.accessToken);o&&i.set("authorization",`Bearer ${o}`),this.applyClientHeader(i);let s=async u=>{try{return await r(e,u)}catch(l){throw Wi(l)?new g("NETWORK",$i(this.apiUrl)):l}},a=await s({...t,headers:i});if(a.status===401&&typeof this.accessToken=="function"){let u=await it(this.accessToken);if(u&&u!==o){let l=new Headers(t?.headers);l.set("authorization",`Bearer ${u}`),this.applyClientHeader(l),a=await s({...t,headers:l});}}return this.noteCompatibilityHeaders(a.headers),a}async requestResponse(e,t){let r=await this.fetchWithAuth(`${this.apiUrl.replace(/\/$/,"")}${e}`,t);if(!r.ok)throw await this.httpResponseError(r);return r}thingShapesReader(e,t){return async r=>await this.thing.getMany(e,t,r)}async prepareStreamingSubmissionRequest(e){let t=this.fetchImpl??globalThis.fetch,r=new Headers({accept:"application/x-ndjson","content-type":"application/x-ndjson"}),i=await it(this.accessToken);i&&r.set("authorization",`Bearer ${i}`),this.applyClientHeader(r);let o=`${this.apiUrl.replace(/\/$/,"")}${e}`;return {dispatch:async(s,a)=>{let u=await t(o,{method:"POST",headers:r,body:s,signal:a,duplex:"half"});return this.noteCompatibilityHeaders(u.headers),u},httpError:async s=>await this.httpResponseError(s)}}async httpResponseError(e){let t=`Request failed with status ${e.status}`,r=$r(e.status),i,o,s;try{let a=await e.json();typeof a.error?.message=="string"&&(t=a.error.message),typeof a.error?.code=="string"&&(r=a.error.code,i=a.error.code),typeof a.error?.hint=="string"&&(o=a.error.hint),typeof a.error?.retryAfter=="number"&&(s=a.error.retryAfter);}catch{}return new g(r,t,e.status,o,s,i)}async requestJson(e,t){return await(await this.requestResponse(e,t)).json()}async watchRepoQuery(e,t,r,i,o){let s=new AbortController,a=Mr(r,s),u=0,l=async()=>{let m=await i();u+=1,await qr(()=>o(m));},d=this.runLiveLoop(()=>this.trpc.live.issueTicket.mutate({orgName:e,repoName:t}),a,async m=>{m.type==="invalidate"&&await l();},l).then(()=>({updates:u}));return {close(){s.abort();},closed:d}}};function $r(n){switch(n){case 400:return "VALIDATION_ERROR";case 401:return "UNAUTHENTICATED";case 403:return "FORBIDDEN";case 404:return "NOT_FOUND";case 409:return "CONFLICT";case 429:return "RATE_LIMITED";default:return "BACKEND"}}async function it(n){if(n)return typeof n=="string"?n:n()}function Mr(n,e){return n?n.aborted?(e.abort(),e.signal):(n.addEventListener("abort",()=>e.abort(),{once:true}),e.signal):e.signal}var ji=2e3,xe=class extends Error{constructor(e){super("Live consumer failed",{cause:e});}};async function qr(n){try{await n();}catch(e){throw new xe(e)}}function zi(n,e){return new Promise(t=>{if(e.aborted){t();return}let r=()=>{clearTimeout(i),t();},i=setTimeout(()=>{e.removeEventListener("abort",r),t();},n);e.addEventListener("abort",r,{once:true});})}function Qi(n){let e="message",t=[];for(let i of n.split(`
|
|
8
|
-
`))if(!(!i||i.startsWith(":"))){if(i.startsWith("event:")){e=i.slice(6).trim();continue}i.startsWith("data:")&&t.push(i.slice(5).trim());}if(t.length===0)return null;let r=t.join(`
|
|
9
|
-
`);return {type:e,data:JSON.parse(r)}}function Yi(n){return n instanceof Error&&n.name==="AbortError"}export{te as A,G as B,sr as C,re as D,pr as E,M as F,Ze as G,I as H,di as I,ba as J,kr as K,Sa as L,nt as M,p as N,wa as O,Vi as P,Hi as Q,Wi as R,$i as S,Ca as T,Lr as U,g as a,Gr as b,y as c,Kr as d,qt as e,Zr as f,Ue as g,$t as h,Gt as i,Kt as j,ye as k,an as l,H as m,F as n,ln as o,fe as p,Re as q,k as r,_ as s,He as t,Xt as u,ee as v,W as w,tr as x,$ as y,f as z};//# sourceMappingURL=chunk-XUGC6JZH.js.map
|
|
10
|
-
//# sourceMappingURL=chunk-XUGC6JZH.js.map
|