@cogniformai/instructor-stream
Version:
Streaming-first structured data extraction from LLMs with real-time updates
2 lines • 24.5 kB
JavaScript
var P=i=>typeof i=="object"&&i!==null,U=i=>Array.isArray(i)?i:[],q=i=>{if(i.type==="text")return typeof i.text=="string"?i.text:void 0;if(i.type==="tool_call_chunk")return typeof i.args=="string"?i.args:void 0},Y=i=>{if(typeof i=="number"&&Number.isFinite(i))return i;if(typeof i=="string"){let e=i.match(/(-?\d+)(?!.*\d)/);if(e){let n=Number.parseInt(e[1],10);return Number.isNaN(n)?void 0:n}}},Q=i=>{if(!(!P(i)||typeof i.type!="string")&&(i.type==="text"||i.type==="tool_call_chunk"))return i},W=i=>{let e=U(i.data);for(let n of e){if(!P(n))continue;let r=n.langgraph_node;if(typeof r=="string"&&r.length>0)return r}},$=i=>{let e=[],n=0;for(let r of U(i.data)){if(!P(r))continue;let t=U(r.content);for(let o of t){let s=Q(o);if(!s)continue;let u=q(s);typeof u!="string"||u.length===0||e.push({text:u,index:Y(s.index),order:n++})}}return e.sort((r,t)=>{let o=typeof r.index=="number",s=typeof t.index=="number";if(o&&s){let u=r.index-t.index;return u!==0?u:r.order-t.order}return o?-1:s?1:r.order-t.order}),e.map(r=>r.text).join("")};function v(){return new TransformStream({transform(i,e){if(!P(i))return;let n=i,r=W(n);if(!r)return;let t=$(n);t.length!==0&&e.enqueue({node:r,chunk:t})}})}function X(i){let e=typeof i=="string"?JSON.parse(i):i;return e.choices?.[0]?.delta?.function_call?.arguments??e.choices?.[0]?.message?.function_call?.arguments??""}function ee(i){let e=typeof i=="string"?JSON.parse(i):i;return e.choices?.[0]?.delta?.tool_calls?.[0]?.function?.arguments??e.choices?.[0]?.message?.tool_calls?.[0]?.function?.arguments??""}function te(i){let e=typeof i=="string"?JSON.parse(i):i,n=e.choices?.[0]?.delta?.content??e?.choices?.[0]?.message?.content??"",r=/```json\n([\s\S]*?)\n```/,t=n.match(r);return t?t[1]:n}function B(i){let e=typeof i=="string"?JSON.parse(i):i,n=e.choices?.[0]?.delta?.function_call?.arguments||e.choices?.[0]?.message?.function_call?.arguments||!1,r=e.choices?.[0]?.delta?.tool_calls?.[0]?.function?.arguments??e.choices?.[0]?.message?.tool_calls?.[0]?.function?.arguments??!1;return n?X(i):r?ee(i):te(i)}function ne(i){return i.replace(/[\x00-\x1F\x7F-\x9F]/g,"")}function le({res:i}){let e,n=new TextEncoder;async function*r(o){let s=!1;e=()=>{s=!0};for await(let u of o){if(s)break;B(u)&&(yield B(u))}}let t=r(i);return new ReadableStream({async start(o){for await(let s of t)o.enqueue(n.encode(ne(s)));o.close()},cancel(){e&&e()}})}async function*G(i){let e=i.getReader();try{for(;;){let{done:n,value:r}=await e.read();if(n)break;yield r}}finally{e.releaseLock()}}function F(i,e,n){let r=i;for(let o=0;o<e.length-1;o++){let s=e[o],u=e[o+1];r[s]==null&&(r[s]=typeof u=="number"?[]:{}),r=r[s]}let t=e[e.length-1];r[t]=n}import{z as _}from"zod";var z=(T=>(T[T.LEFT_BRACE=0]="LEFT_BRACE",T[T.RIGHT_BRACE=1]="RIGHT_BRACE",T[T.LEFT_BRACKET=2]="LEFT_BRACKET",T[T.RIGHT_BRACKET=3]="RIGHT_BRACKET",T[T.COLON=4]="COLON",T[T.COMMA=5]="COMMA",T[T.TRUE=6]="TRUE",T[T.FALSE=7]="FALSE",T[T.NULL=8]="NULL",T[T.STRING=9]="STRING",T[T.NUMBER=10]="NUMBER",T[T.SEPARATOR=11]="SEPARATOR",T))(z||{}),a=z;function K(i){return["VALUE","KEY","COLON","COMMA","ENDED","ERROR","SEPARATOR"][i]}var re={paths:void 0,keepStack:!0,separator:void 0,strictRootObject:!1},L=class extends Error{constructor(n){super(n);this.name="TokenParserError"}},R=class{constructor(e){this.state=0;this.mode=void 0;this.key=void 0;this.value=void 0;this.stack=[];this.rootSeen=!1;e={...re,...e},e.paths&&(this.paths=e.paths.map(n=>{if(n===void 0||n==="$*")return;if(!n.startsWith("$"))throw new L(`Invalid selector "${n}". Should start with "$".`);let r=n.split(".").slice(1);if(r.includes(""))throw new L(`Invalid selector "${n}". ".." syntax not supported.`);return r})),this.keepStack=!0,this.separator=e.separator,this.strictRootObject=!!e.strictRootObject}shouldEmit(){return this.paths?this.paths.some(e=>{if(e===void 0)return!0;if(e.length!==this.stack.length)return!1;for(let r=0;r<e.length-1;r++){let t=e[r],{key:o}=this.stack[r+1];if(t!=="*"&&t!==o)return!1}let n=e[e.length-1];return n==="*"?!0:n===this.key?.toString()}):!0}push(){this.stack.push({key:this.key,value:this.value,mode:this.mode,emit:this.shouldEmit()})}pop(){let e=this.value,n,r=this.stack.pop();this.key=r.key,this.value=r.value,this.mode=r.mode,n=r.emit,this.state=this.mode!==void 0?3:0,this.emit(e,n)}emit(e,n){!this.keepStack&&this.value&&this.stack.every(r=>!r.emit)&&delete this.value[this.key],n&&this.onValue({value:e,key:this.key,parent:this.value,stack:this.stack}),this.stack.length===0&&(this.separator?this.state=6:this.separator===void 0&&this.end(),this.rootSeen=!1)}get isEnded(){return this.state===4}write({token:e,value:n,partial:r}){if(!r){if(!this.rootSeen&&this.strictRootObject&&this.state===0&&this.stack.length===0){if(e!==a.LEFT_BRACE){this.rootSeen=!0,this.error(new L("Root must be an object"));return}this.rootSeen=!0}if(this.state===0){if(e===a.STRING||e===a.NUMBER||e===a.TRUE||e===a.FALSE||e===a.NULL){this.mode===0?(this.value[this.key]=n,this.state=3):this.mode===1&&(this.value.push(n),this.state=3),this.emit(n,this.shouldEmit());return}if(e===a.LEFT_BRACE){if(this.push(),this.mode===0)this.value=this.value[this.key]={};else if(this.mode===1){let t={};this.value.push(t),this.value=t}else this.value={};this.mode=0,this.state=1,this.key=void 0;return}if(e===a.LEFT_BRACKET){if(this.push(),this.mode===0)this.value=this.value[this.key]=[];else if(this.mode===1){let t=[];this.value.push(t),this.value=t}else this.value=[];this.mode=1,this.state=0,this.key=0;return}if(this.mode===1&&e===a.RIGHT_BRACKET&&this.value.length===0){this.pop();return}}if(this.state===1){if(e===a.STRING){this.key=n,this.state=2;return}if(e===a.RIGHT_BRACE&&Object.keys(this.value).length===0){this.pop();return}}if(this.state===2&&e===a.COLON){this.state=0;return}if(this.state===3){if(e===a.COMMA){if(this.mode===1){this.state=0,this.key++;return}if(this.mode===0){this.state=1;return}}if(e===a.RIGHT_BRACE&&this.mode===0||e===a.RIGHT_BRACKET&&this.mode===1){this.pop();return}}if(this.state===6&&e===a.SEPARATOR&&n===this.separator){this.state=0;return}this.error(new L(`Unexpected ${a[e]} (${JSON.stringify(n)}) in state ${K(this.state)}`))}}error(e){this.state!==4&&(this.state=5),this.onError(e)}end(){this.state!==0&&this.state!==6||this.stack.length>0?this.error(new Error(`Parser ended in mid-parsing (state: ${K(this.state)}). Either not all the data was received or the data was invalid.`)):(this.state=4,this.onEnd())}onValue(e){throw new L(`Can't emit data before the "onValue" callback has been set up.`)}onError(e){throw e}onEnd(){}};var N=class{constructor({onIncrementalString:e}){this.decoder=new TextDecoder("utf-8");this.assembled="";this.byteLength=0;this.onIncrementalString=e??void 0}appendChar(e){this.assembled+=String.fromCharCode(e),this.byteLength++,this.update()}appendBuf(e,n=0,r=e.length){let t=this.decoder.decode(e.subarray(n,r));this.assembled+=t,this.byteLength+=r-n,this.update()}update(){this.onIncrementalString&&this.onIncrementalString(this.assembled)}reset(){this.assembled="",this.byteLength=0}toString(){return this.assembled}},b=class{constructor(e,n){this.decoder=new TextDecoder("utf-8");this.bufferOffset=0;this.string="";this.byteLength=0;this.buffer=new Uint8Array(e),this.onIncrementalString=n??void 0}appendChar(e){this.bufferOffset>=this.buffer.length&&this.flushStringBuffer(),this.buffer[this.bufferOffset++]=e,this.byteLength++}appendBuf(e,n=0,r=e.length){let t=r-n;this.bufferOffset+t>this.buffer.length&&this.flushStringBuffer(),this.buffer.set(e.subarray(n,r),this.bufferOffset),this.bufferOffset+=t,this.byteLength+=t}flushStringBuffer(){this.string+=this.decoder.decode(this.buffer.subarray(0,this.bufferOffset)),this.bufferOffset=0,this.update()}update(){this.onIncrementalString&&this.onIncrementalString(this.string)}reset(){this.string="",this.bufferOffset=0,this.byteLength=0}toString(){return this.string+=this.decoder.decode(this.buffer.subarray(0,this.bufferOffset)),this.bufferOffset=0,this.string}};var w={34:34,92:92,47:47,98:8,102:12,110:10,114:13,116:9};function Le(i){let e=typeof i=="string"?i:"choices"in i&&i.choices?.[0]?i.choices[0].message?.content??"":"",n=/<think(?:ing)?>([\s\S]*?)(?:<\/think(?:ing)?>|\Z)/i,r=e.match(n),t=r?r[1].trim():"",o=e.replace(n,"").trim();if(o.trim().startsWith("{")||o.trim().startsWith("["))return{json:o.trim(),thinking:t};let s=/```(?:json)?\s*([\s\S]*?)```/,u=o.match(s);if(u)return{json:u[1].trim(),thinking:t};let l=o.match(/```(?:json)?\s*([\s\S]*)/i);if(l){let d=l[1].trim();if(d.startsWith("{")||d.startsWith("["))return{json:d,thinking:t}}return{json:"",thinking:t}}function J(i){return["START","ENDED","ERROR","TRUE1","TRUE2","TRUE3","FALSE1","FALSE2","FALSE3","FALSE4","NULL1","NULL2","NULL3","STRING_DEFAULT","STRING_AFTER_BACKSLASH","STRING_UNICODE_DIGIT_1","STRING_UNICODE_DIGIT_2","STRING_UNICODE_DIGIT_3","STRING_UNICODE_DIGIT_4","STRING_INCOMPLETE_CHAR","NUMBER_AFTER_INITIAL_MINUS","NUMBER_AFTER_INITIAL_ZERO","NUMBER_AFTER_INITIAL_NON_ZERO","NUMBER_AFTER_FULL_STOP","NUMBER_AFTER_DECIMAL","NUMBER_AFTER_E","NUMBER_AFTER_E_AND_SIGN","NUMBER_AFTER_E_AND_DIGIT","SEPARATOR"][i]}var oe={stringBufferSize:0,numberBufferSize:0,separator:void 0,handleUnescapedNewLines:!1},g=class extends Error{constructor(n){super(n);this.name="TokenizerError"}},y=class{constructor(e){this.state=0;this.separatorIndex=0;this.bytes_remaining=0;this.bytes_in_sequence=0;this.char_split_buffer=new Uint8Array(4);this.encoder=new TextEncoder;this.offset=-1;e={...oe,...e};let n=r=>{this.onToken({token:a.STRING,value:r,partial:!0})};this.bufferedString=e?.stringBufferSize&&e.stringBufferSize>0?new b(e.stringBufferSize):new N({onIncrementalString:n}),this.bufferedNumber=e?.numberBufferSize&&e.numberBufferSize>0?new b(e.numberBufferSize,n):new N({}),this.handleUnescapedNewLines=e?.handleUnescapedNewLines??!1,this.separator=e?.separator,this.separatorBytes=e?.separator?this.encoder.encode(e.separator):void 0}get isEnded(){return this.state===1}write(e){let n;if(e instanceof Uint8Array)n=e;else if(typeof e=="string")n=this.encoder.encode(e);else if(typeof e=="object"&&"buffer"in e||Array.isArray(e))n=Uint8Array.from(e);else{this.error(new TypeError("Unexpected type. The `write` function only accepts Arrays, TypedArrays and Strings."));return}for(let r=0;r<n.length;r++){let t=n[r];switch(this.state){case 0:if(this.offset++,this.separatorBytes&&t===this.separatorBytes[0]){if(this.separatorBytes.length===1){this.state=0,this.onToken({token:a.SEPARATOR,value:this.separator,offset:this.offset+this.separatorBytes.length-1});continue}this.state=28;continue}if(t===32||t===10||t===13||t===9)continue;if(t===123){this.onToken({token:a.LEFT_BRACE,value:"{",offset:this.offset});continue}if(t===125){this.onToken({token:a.RIGHT_BRACE,value:"}",offset:this.offset});continue}if(t===91){this.onToken({token:a.LEFT_BRACKET,value:"[",offset:this.offset});continue}if(t===93){this.onToken({token:a.RIGHT_BRACKET,value:"]",offset:this.offset});continue}if(t===58){this.onToken({token:a.COLON,value:":",offset:this.offset});continue}if(t===44){this.onToken({token:a.COMMA,value:",",offset:this.offset});continue}if(t===116){this.state=3;continue}if(t===102){this.state=6;continue}if(t===110){this.state=10;continue}if(t===34){this.bufferedString.reset(),this.state=13;continue}if(t>=49&&t<=57){this.bufferedNumber.reset(),this.bufferedNumber.appendChar(t),this.state=22;continue}if(t===48){this.bufferedNumber.reset(),this.bufferedNumber.appendChar(t),this.state=21;continue}if(t===45){this.bufferedNumber.reset(),this.bufferedNumber.appendChar(t),this.state=20;continue}break;case 13:if(this.handleUnescapedNewLines&&t===10){this.bufferedString.appendChar(92),this.bufferedString.appendChar(110);continue}if(t===34){let o=this.bufferedString.toString();this.state=0,this.onToken({token:a.STRING,value:o,offset:this.offset}),this.offset+=this.bufferedString.byteLength+1;continue}if(t===92){this.state=14;continue}if(t>=128){if(t>=194&&t<=223?this.bytes_in_sequence=2:t<=239?this.bytes_in_sequence=3:this.bytes_in_sequence=4,this.bytes_in_sequence<=n.length-r){this.bufferedString.appendBuf(n,r,r+this.bytes_in_sequence),r+=this.bytes_in_sequence-1;continue}this.bytes_remaining=r+this.bytes_in_sequence-n.length,this.char_split_buffer.set(n.subarray(r)),r=n.length-1,this.state=19;continue}if(t>=32){this.bufferedString.appendChar(t);continue}break;case 19:this.char_split_buffer.set(n.subarray(r,r+this.bytes_remaining),this.bytes_in_sequence-this.bytes_remaining),this.bufferedString.appendBuf(this.char_split_buffer,0,this.bytes_in_sequence),r=this.bytes_remaining-1,this.state=13;continue;case 14:if(w?.[t]){this.bufferedString.appendChar(w[t]),this.state=13;continue}if(t===117){this.unicode="",this.state=15;continue}break;case 15:case 16:case 17:if(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102){this.unicode+=String.fromCharCode(t),this.state+=1;continue}break;case 18:if(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102){let o=parseInt(this.unicode+String.fromCharCode(t),16);this.highSurrogate===void 0?o>=55296&&o<=56319?this.highSurrogate=o:this.bufferedString.appendBuf(this.encoder.encode(String.fromCharCode(o))):(o>=56320&&o<=57343?this.bufferedString.appendBuf(this.encoder.encode(String.fromCharCode(this.highSurrogate,o))):this.bufferedString.appendBuf(this.encoder.encode(String.fromCharCode(this.highSurrogate))),this.highSurrogate=void 0),this.state=13;continue}break;case 20:if(t===48){this.bufferedNumber.appendChar(t),this.state=21;continue}if(t>=49&&t<=57){this.bufferedNumber.appendChar(t),this.state=22;continue}break;case 21:if(t===46){this.bufferedNumber.appendChar(t),this.state=23;continue}if(t===101||t===69){this.bufferedNumber.appendChar(t),this.state=25;continue}r--,this.state=0,this.emitNumber();continue;case 22:if(t>=48&&t<=57){this.bufferedNumber.appendChar(t);continue}if(t===46){this.bufferedNumber.appendChar(t),this.state=23;continue}if(t===101||t===69){this.bufferedNumber.appendChar(t),this.state=25;continue}r--,this.state=0,this.emitNumber();continue;case 23:if(t>=48&&t<=57){this.bufferedNumber.appendChar(t),this.state=24;continue}break;case 24:if(t>=48&&t<=57){this.bufferedNumber.appendChar(t);continue}if(t===101||t===69){this.bufferedNumber.appendChar(t),this.state=25;continue}r--,this.state=0,this.emitNumber();continue;case 25:if(t===43||t===45){this.bufferedNumber.appendChar(t),this.state=26;continue}case 26:if(t>=48&&t<=57){this.bufferedNumber.appendChar(t),this.state=27;continue}break;case 27:if(t>=48&&t<=57){this.bufferedNumber.appendChar(t);continue}r--,this.state=0,this.emitNumber();continue;case 3:if(t===114){this.state=4;continue}break;case 4:if(t===117){this.state=5;continue}break;case 5:if(t===101){this.state=0,this.onToken({token:a.TRUE,value:!0,offset:this.offset}),this.offset+=3;continue}break;case 6:if(t===97){this.state=7;continue}break;case 7:if(t===108){this.state=8;continue}break;case 8:if(t===115){this.state=9;continue}break;case 9:if(t===101){this.state=0,this.onToken({token:a.FALSE,value:!1,offset:this.offset}),this.offset+=4;continue}break;case 10:if(t===117){this.state=11;continue}break;case 11:if(t===108){this.state=12;continue}break;case 12:if(t===108){this.state=0,this.onToken({token:a.NULL,value:null,offset:this.offset}),this.offset+=3;continue}break;case 28:if(this.separatorIndex++,!this.separatorBytes||t!==this.separatorBytes[this.separatorIndex])break;this.separatorIndex===this.separatorBytes.length-1&&(this.state=0,this.onToken({token:a.SEPARATOR,value:this.separator,offset:this.offset+this.separatorIndex}),this.separatorIndex=0);continue;case 1:if(t===32||t===10||t===13||t===9)continue}this.error(new g(`Unexpected "${String.fromCharCode(t)}" at position "${r}" in state ${J(this.state)}`));return}}emitNumber(){this.onToken({token:a.NUMBER,value:this.parseNumber(this.bufferedNumber.toString()),offset:this.offset}),this.offset+=this.bufferedNumber.byteLength-1}parseNumber(e){return Number(e)}error(e){this.state!==1&&(this.state=2),this.onError(e)}end(){switch(this.state){case 21:case 22:case 24:case 27:this.state=1,this.emitNumber(),this.onEnd();break;case 0:case 2:case 28:this.state=1,this.onEnd();break;default:this.error(new g(`Tokenizer ended in the middle of a token (state: ${J(this.state)}). Either not all the data was received or the data was invalid.`))}}onToken(e){throw new g(`Can't emit tokens before the "onToken" callback has been set up.`)}onError(e){throw e}onEnd(){}};var C=class{constructor(e={}){this.tokenizer=new y(e),this.tokenParser=new R(e),this.tokenizer.onToken=this.tokenParser.write.bind(this.tokenParser),this.tokenizer.onEnd=()=>{this.tokenParser.isEnded||this.tokenParser.end()},this.tokenParser.onError=this.tokenizer.error.bind(this.tokenizer),this.tokenParser.onEnd=()=>{this.tokenizer.isEnded||this.tokenizer.end()}}get isEnded(){return this.tokenizer.isEnded&&this.tokenParser.isEnded}write(e){this.tokenizer.write(e)}end(){this.tokenizer.end()}set onToken(e){this.tokenizer.onToken=n=>{let r=[a.STRING,a.NUMBER,a.TRUE,a.FALSE,a.NULL];this.tokenParser.state===0&&r.includes(n.token)&&e({parser:{state:this.tokenParser.state,key:this.tokenParser.key,mode:this.tokenParser.mode,stack:this.tokenParser.stack},tokenizer:n}),this.tokenParser.write(n)}}set onValue(e){this.tokenParser.onValue=e}set onError(e){this.tokenizer.onError=e}set onEnd(e){this.tokenParser.onEnd=()=>{this.tokenizer.isEnded||this.tokenizer.end(),e.call(this.tokenParser)}}};var k=class{constructor(e,n={}){this.activePath=[];this.completedPaths=[];let{defaultData:r,onKeyComplete:t,typeDefaults:o,autoJSONMode:s="object-or-array",maxUnstringifyDepth:u=2,snapshotMode:l="object"}=n;this.schemaInstance=this.createBlankObject(e,r,o),this.onKeyComplete=t,this.autoJSONMode=s,this.maxUnstringifyDepth=u,this.snapshotMode=l}getDefaultValue(e,n){try{let r=e.safeParse(void 0);if(r.success&&r.data!==void 0)return r.data}catch{}if(e instanceof _.ZodString)return Object.prototype.hasOwnProperty.call(n??{},"string")?n?.string:null;if(e instanceof _.ZodNumber)return Object.prototype.hasOwnProperty.call(n??{},"number")?n?.number:null;if(e instanceof _.ZodBoolean)return Object.prototype.hasOwnProperty.call(n??{},"boolean")?n?.boolean:null;if(e instanceof _.ZodArray)return[];if(e instanceof _.ZodObject)return this.createBlankObject(e,void 0,n);if(e instanceof _.ZodRecord)return{};if(e instanceof _.ZodOptional||e instanceof _.ZodNullable||"unwrap"in e&&typeof e.unwrap=="function")try{let r=e.unwrap();return this.getDefaultValue(r,n)}catch{return null}return null}createBlankObject(e,n,r){if(e instanceof _.ZodObject){let o={},{shape:s}=e;for(let u in s)o[u]=n&&Object.prototype.hasOwnProperty.call(n,u)?n[u]:this.getDefaultValue(s[u],r);return o}let t=this.getDefaultValue(e,r);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}getPathFromStack(e=[],n){let r=e.length,t=r>0?r-1:0,o=new Array(t+1);for(let s=1;s<r;s++)o[s-1]=e[s].key;return o[t]=n,o}handleToken({parser:{key:e,stack:n},tokenizer:{value:r,partial:t}}){let o=this.getPathFromStack(n,e),s=this.activePath.length===0||!this.arePathsEqual(this.activePath,o);s&&(this.activePath=o),t||this.completedPaths.push(o),(s||!t)&&this.onKeyComplete&&this.onKeyComplete({activePath:this.activePath,completedPaths:this.completedPaths});let u=r;!t&&typeof r=="string"&&this.autoJSONMode!=="off"&&(u=this.unstringifyIfJSON(r)),F(this.schemaInstance,o,u)}arePathsEqual(e,n){if(e.length!==n.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==n[r])return!1;return!0}unstringifyIfJSON(e){let n=this.maxUnstringifyDepth,r=e;for(;n>0&&typeof r=="string";){let t=r.trim();if(t.length<2)break;let o=t.charCodeAt(0),s=t.charCodeAt(t.length-1),u=o===123&&s===125,l=o===91&&s===93,d=u||l;if(!d&&o===34&&s===34){let f=t.slice(1,-1).trim();if(f.length>=2){let E=f.charCodeAt(0),T=f.charCodeAt(f.length-1),c=E===123&&T===125,M=E===91&&T===93;(c||M)&&(d=!0)}}if(!d)break;try{let f=JSON.parse(t);if(Array.isArray(f)||f!==null&&typeof f=="object")return f;if(typeof f=="string"){r=f,n-=1;continue}return e}catch{return e}}return typeof r=="string"?r:e}getSchemaStub(e,n,r){return this.createBlankObject(e,n,r)}parse(e={stringBufferSize:0,handleUnescapedNewLines:!0}){let n=new C({stringBufferSize:e.stringBufferSize??0,handleUnescapedNewLines:e.handleUnescapedNewLines??!0,strictRootObject:!0});n.onToken=this.handleToken.bind(this),n.onValue=()=>{},n.onError=t=>{console.error("Error in the json parser transform stream: parsing chunk",t)};let r=this.snapshotMode==="string"?new TextEncoder:void 0;return new TransformStream({transform:async(t,o)=>{try{n.write(t),this.snapshotMode==="object"?o.enqueue(this.schemaInstance):o.enqueue(r.encode(JSON.stringify(this.schemaInstance)))}catch(s){typeof n.onError=="function"?n.onError(s):o.error(s)}},flush:()=>{this.onKeyComplete&&this.onKeyComplete({completedPaths:this.completedPaths,activePath:[]}),this.activePath=[]}})}};function x(i){return{async start(e){return{stream:await i(e)}}}}var O=class{constructor({debug:e=!1}={}){this.debug=!1;this.debug=e}log(e,...n){if(!this.debug&&e==="debug")return;let r=new Date().toISOString();switch(e){case"debug":console.debug(`[ZodStream-CLIENT:DEBUG] ${r}:`,...n);break;case"info":console.info(`[ZodStream-CLIENT:INFO] ${r}:`,...n);break;case"warn":console.warn(`[ZodStream-CLIENT:WARN] ${r}:`,...n);break;case"error":console.error(`[ZodStream-CLIENT:ERROR] ${r}:`,...n);break}}async chatCompletionStream({adapter:e,channelType:n="default",completionPromise:r,data:t,response_model:o,validationMode:s="none",signal:u}){let l=[],d=[],f=0,E=!1,T=null,c=!0;this.log("debug","Starting completion stream");let M=new k(o.schema,{onKeyComplete:({activePath:h,completedPaths:A})=>{this.log("debug","Key complete",h,A),l=[...h],d=A.map(S=>Array.isArray(S)?[...S]:[]),A.length>f&&(E=!0,f=A.length)},typeDefaults:{string:null,number:null,boolean:null},snapshotMode:"object"});try{let h=e??(r?x(async({data:m,signal:I})=>r(m,I)):void 0);if(!h)throw new Error("No streaming provider adapter or completionPromise was supplied.");let A=await h.start({schema:o.schema,data:t,signal:u});if(!A?.stream)throw this.log("error","Adapter returned no stream"),new Error("Adapter returned no stream");let S=A.meta??{},j=M.parse({handleUnescapedNewLines:!0}),V=A.stream.pipeThrough(j),Z=new TransformStream({transform:async(m,I)=>{T=m;try{if(s==="on-complete"&&E){let D=await o.schema.safeParseAsync(m);c=D.success,E=!1,this.log("debug","Validation (on-complete) result",D.success)}else s==="none"&&(c=!0);let p={...S,_isValid:s==="none"?!0:c,_activePath:l,_completedPaths:d,_type:n};I.enqueue({data:[m],_meta:p})}catch(p){this.log("error","Error validating snapshot",p),I.error(p)}},flush:async m=>{if(T&&s==="final"){try{let p=await o.schema.safeParseAsync(T);c=p.success,this.log("debug","Validation (final) result",p.success)}catch(p){this.log("error","Error validating final snapshot",p),c=!1}let I={...S,_isValid:c,_activePath:l,_completedPaths:d,_type:n};m.enqueue({data:[T],_meta:I})}}}),H=V.pipeThrough(Z);return G(H)}catch(h){throw this.log("error","Error making completion call"),h}}getSchemaStub({schema:e,defaultData:n={}}){return new k(e,{defaultData:n,typeDefaults:{string:null,number:null,boolean:null}}).getSchemaStub(e,n)}async create(e){return this.chatCompletionStream(e)}};var se=new TextEncoder,ae=(i,e,n,r,t)=>{let o=new TransformStream({transform(f,E){E.enqueue(se.encode(f))}}),s=o.writable.getWriter(),u=x(async()=>o.readable),l=new O,d=(async()=>{let f=await l.create({adapter:u,response_model:{schema:e},channelType:i,validationMode:r});for await(let E of f){let T=E.data[0];await n(i,T,E._meta)}})();return d.catch(f=>{t.push(f)}),{writer:s,close:async()=>{try{await s.close()}catch{}await d}}};async function ue(i){let e=i.validationMode??"none",n=new Map,r=[],t=i.upstream.pipeThrough(v()).getReader();try{for(;;){let{value:o,done:s}=await t.read();if(s)break;if(!o)continue;let{node:u,chunk:l}=o,d=i.schemas[u]??i.defaultSchema;if(!d)continue;let f=n.get(u);f||(f=ae(u,d,i.onSnapshot,e,r),n.set(u,f)),await f.writer.write(l)}}finally{t.releaseLock(),await Promise.all([...n.values()].map(o=>o.close()))}if(r.length>0)throw r[0]}function ut(i){let e=Symbol.asyncIterator in i?i[Symbol.asyncIterator]():(async function*(){for(let n of i)yield n})();return new ReadableStream({async pull(n){let{value:r,done:t}=await e.next();t?n.close():n.enqueue(r)},async cancel(){typeof e.return=="function"&&await e.return()}})}export{B as a,le as b,Le as c,x as d,O as e,v as f,ue as g,ut as h};
//# sourceMappingURL=chunk-MPEVFTMN.js.map