MCPcopy Index your code
hub / github.com/easydiffusion/easydiffusion / readStreamAsJSON

Method readStreamAsJSON

ui/media/js/engine.js:129–179  ·  view source on GitHub ↗
(jsonStr, throwOnError)

Source from the content-addressed store, hash-verified

127 } while (!done && (this.#response.ok || this.#response.status === 425))
128 }
129 *readStreamAsJSON(jsonStr, throwOnError) {
130 if (typeof jsonStr !== "string") {
131 throw new Error("jsonStr is not a string.")
132 }
133 do {
134 if (this.#bufferedString.length > 0) {
135 // Append new data when required
136 if (jsonStr.length > 0) {
137 jsonStr = this.#bufferedString + jsonStr
138 } else {
139 jsonStr = this.#bufferedString
140 }
141 this.#bufferedString = ""
142 }
143 if (!jsonStr) {
144 return
145 }
146 // Find next delimiter
147 let lastChunkIdx = jsonStr.indexOf("}{")
148 if (lastChunkIdx >= 0) {
149 this.#bufferedString = jsonStr.substring(0, lastChunkIdx + 1)
150 jsonStr = jsonStr.substring(lastChunkIdx + 1)
151 } else {
152 this.#bufferedString = jsonStr
153 jsonStr = ""
154 }
155 if (this.#bufferedString.length <= 0) {
156 return
157 }
158 // hack for a middleman buffering all the streaming updates, and unleashing them on the poor browser in one shot.
159 // this results in having to parse JSON like {"step": 1}{"step": 2}{"step": 3}{"ste...
160 // which is obviously invalid and can happen at any point while rendering.
161 // So we need to extract only the next {} section
162 try {
163 // Try to parse
164 const jsonObj = JSON.parse(this.#bufferedString)
165 this.#bufferedString = jsonStr
166 jsonStr = ""
167 yield jsonObj
168 } catch (e) {
169 if (throwOnError) {
170 console.error(`Parsing: "${this.#bufferedString}", Buffer: "${jsonStr}"`)
171 }
172 this.#bufferedString += jsonStr
173 if (e instanceof SyntaxError && !throwOnError) {
174 return
175 }
176 throw e
177 }
178 } while (this.#bufferedString.length > 0 && this.#bufferedString.indexOf("}") >= 0)
179 }
180 }
181
182 const EVENT_IDLE = "idle"

Callers 2

getReaderMethod · 0.95
jasmineSpec.jsFile · 0.80

Calls 1

parseMethod · 0.80

Tested by

no test coverage detected