worker-json.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /** Lossless-JSON snapshots for the dependency-free source worker closure. @module @deepseek-ai/dsh-code-runtime-worker/worker-json */
  2. import type { CodeJsonValue } from '@deepseek-ai/dsh-code-runtime'
  3. /* jscpd:ignore-start -- the source worker mirrors session JSON helpers without workspace runtime imports */
  4. /** Whether a realm-owned intrinsic prototype names and points back to its constructor. */
  5. function hasIntrinsicConstructor(prototype: object, name: 'Array' | 'Object'): boolean {
  6. const descriptor = Object.getOwnPropertyDescriptor(prototype, 'constructor')
  7. const constructor: unknown = descriptor?.value
  8. return typeof constructor === 'function'
  9. && constructor.name === name
  10. && constructor.prototype === prototype
  11. }
  12. /** Whether a candidate is one realm's intrinsic `Object.prototype`. */
  13. function isIntrinsicObjectPrototype(value: object): boolean {
  14. return Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, 'Object')
  15. }
  16. /** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */
  17. function hasPlainArrayPrototype(value: unknown[]): boolean {
  18. const prototype: unknown = Object.getPrototypeOf(value)
  19. if (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, 'Array')) return false
  20. const objectPrototype: unknown = Object.getPrototypeOf(prototype)
  21. return typeof objectPrototype === 'object'
  22. && objectPrototype !== null
  23. && isIntrinsicObjectPrototype(objectPrototype)
  24. }
  25. /** Whether an object is a plain or null-prototype record from any JavaScript realm. */
  26. function hasPlainObjectPrototype(value: object): boolean {
  27. const prototype: unknown = Object.getPrototypeOf(value)
  28. return prototype === null
  29. || typeof prototype === 'object' && isIntrinsicObjectPrototype(prototype)
  30. }
  31. /** Return every JSON-visible object key, or reject own data JSON would discard. */
  32. function enumerableStringKeys(value: object): string[] | undefined {
  33. const keys = Reflect.ownKeys(value)
  34. if (keys.some(key => typeof key !== 'string' || !Object.prototype.propertyIsEnumerable.call(value, key))) return undefined
  35. return keys as string[]
  36. }
  37. type SnapshotDestination =
  38. | { kind: 'root' }
  39. | { kind: 'array'; target: CodeJsonValue[]; index: number }
  40. | { kind: 'object'; target: Record<string, CodeJsonValue>; key: string }
  41. type SnapshotTask =
  42. | { kind: 'visit'; value: unknown; destination: SnapshotDestination }
  43. | { kind: 'array-item'; source: unknown[]; index: number; target: CodeJsonValue[] }
  44. | { kind: 'object-property'; source: Record<string, unknown>; key: string; target: Record<string, CodeJsonValue> }
  45. | { kind: 'leave'; source: object }
  46. /**
  47. * Validate and detach one worker-boundary value without loading another
  48. * workspace package at runtime. This mirrors the session-owned canonical
  49. * JSON boundary while remaining safe to import from the unbuilt worker.
  50. * Its iterative traversal adds no JavaScript call-stack depth limit.
  51. *
  52. * @param value - the candidate completion value.
  53. * @returns a detached lossless-JSON snapshot, or `undefined` when invalid.
  54. */
  55. export function snapshotCodeJsonValue(value: unknown): CodeJsonValue | undefined {
  56. const active = new Set<object>()
  57. let root: CodeJsonValue | undefined
  58. const assign = (destination: SnapshotDestination, item: CodeJsonValue): void => {
  59. if (destination.kind === 'root') {
  60. root = item
  61. } else if (destination.kind === 'array') {
  62. destination.target[destination.index] = item
  63. } else {
  64. Object.defineProperty(destination.target, destination.key, {
  65. value: item,
  66. enumerable: true,
  67. configurable: true,
  68. writable: true,
  69. })
  70. }
  71. }
  72. const tasks: SnapshotTask[] = [{ kind: 'visit', value, destination: { kind: 'root' } }]
  73. for (let task = tasks.pop(); task !== undefined; task = tasks.pop()) {
  74. if (task.kind === 'leave') {
  75. active.delete(task.source)
  76. continue
  77. }
  78. if (task.kind === 'array-item') {
  79. if (!Object.hasOwn(task.source, task.index)) return undefined
  80. tasks.push({
  81. kind: 'visit',
  82. value: task.source[task.index],
  83. destination: { kind: 'array', target: task.target, index: task.index },
  84. })
  85. continue
  86. }
  87. if (task.kind === 'object-property') {
  88. tasks.push({
  89. kind: 'visit',
  90. value: task.source[task.key],
  91. destination: { kind: 'object', target: task.target, key: task.key },
  92. })
  93. continue
  94. }
  95. const candidate = task.value
  96. if (candidate === null) {
  97. assign(task.destination, null)
  98. continue
  99. }
  100. if (typeof candidate === 'boolean' || typeof candidate === 'string') {
  101. assign(task.destination, candidate)
  102. continue
  103. }
  104. if (typeof candidate === 'number') {
  105. if (!Number.isFinite(candidate) || Object.is(candidate, -0)) return undefined
  106. assign(task.destination, candidate)
  107. continue
  108. }
  109. if (typeof candidate !== 'object') return undefined
  110. if (active.has(candidate)) return undefined
  111. if (Array.isArray(candidate)) {
  112. if (!hasPlainArrayPrototype(candidate)) return undefined
  113. const length = candidate.length
  114. if (Reflect.ownKeys(candidate).length !== length + 1) return undefined
  115. const target: CodeJsonValue[] = []
  116. assign(task.destination, target)
  117. active.add(candidate)
  118. tasks.push({ kind: 'leave', source: candidate })
  119. for (let index = length - 1; index >= 0; index--) {
  120. tasks.push({ kind: 'array-item', source: candidate, index, target })
  121. }
  122. continue
  123. }
  124. if (!hasPlainObjectPrototype(candidate)) return undefined
  125. const keys = enumerableStringKeys(candidate)
  126. if (keys === undefined) return undefined
  127. const target: Record<string, CodeJsonValue> = {}
  128. assign(task.destination, target)
  129. active.add(candidate)
  130. tasks.push({ kind: 'leave', source: candidate })
  131. for (let index = keys.length - 1; index >= 0; index--) {
  132. const key = keys[index]
  133. /* v8 ignore next -- the loop is bounded by the captured key count. */
  134. if (key === undefined) return undefined
  135. tasks.push({ kind: 'object-property', source: candidate as Record<string, unknown>, key, target })
  136. }
  137. }
  138. return root
  139. }
  140. interface ArrayWireToken {
  141. kind: 'array'
  142. length: number
  143. }
  144. interface ObjectWireToken {
  145. kind: 'object'
  146. keys: string[]
  147. }
  148. type WorkerJsonToken = null | boolean | number | string | ArrayWireToken | ObjectWireToken
  149. /**
  150. * A pre-order, bounded-depth transport for one lossless JSON value. Container
  151. * markers and scalar leaves share one flat token array, so `worker_threads`
  152. * never has to structured-clone the value's application nesting.
  153. */
  154. export type WorkerJsonWire = WorkerJsonToken[]
  155. /**
  156. * Flatten one validated JSON value for the worker-thread message port.
  157. * @param value - the lossless JSON value to transport.
  158. * @returns a pre-order token stream whose own nesting is bounded.
  159. */
  160. export function encodeWorkerJson(value: CodeJsonValue): WorkerJsonWire {
  161. const wire: WorkerJsonWire = []
  162. const pending: CodeJsonValue[] = [value]
  163. for (let current = pending.pop(); current !== undefined; current = pending.pop()) {
  164. if (current === null || typeof current === 'boolean' || typeof current === 'number' || typeof current === 'string') {
  165. wire.push(current)
  166. continue
  167. }
  168. if (Array.isArray(current)) {
  169. wire.push({ kind: 'array', length: current.length })
  170. for (let index = current.length - 1; index >= 0; index--) {
  171. const item = current[index]
  172. if (item === undefined) throw new Error('cannot encode a sparse JSON array')
  173. pending.push(item)
  174. }
  175. continue
  176. }
  177. const keys = Object.keys(current)
  178. wire.push({ kind: 'object', keys })
  179. for (let index = keys.length - 1; index >= 0; index--) {
  180. const key = keys[index]
  181. /* v8 ignore next -- the loop is bounded by the captured key count. */
  182. if (key === undefined) throw new Error('cannot encode a missing JSON object key')
  183. const item = current[key]
  184. if (item === undefined) throw new Error('cannot encode an undefined JSON object property')
  185. pending.push(item)
  186. }
  187. }
  188. return wire
  189. }
  190. type DecodeFrame =
  191. | { kind: 'array'; target: CodeJsonValue[]; length: number; index: number }
  192. | { kind: 'object'; target: Record<string, CodeJsonValue>; keys: string[]; index: number }
  193. /** Whether an array contains exactly its dense indexed slots and `length`. */
  194. function isDenseArray(value: unknown[]): boolean {
  195. if (!hasPlainArrayPrototype(value) || Reflect.ownKeys(value).length !== value.length + 1) return false
  196. for (let index = 0; index < value.length; index++) {
  197. if (!Object.hasOwn(value, index)) return false
  198. }
  199. return true
  200. }
  201. /** Return one exact container marker, or reject any extra/missing fields. */
  202. function containerToken(value: object): ArrayWireToken | ObjectWireToken | undefined {
  203. if (Array.isArray(value) || !hasPlainObjectPrototype(value)) return undefined
  204. const keys = enumerableStringKeys(value)
  205. if (keys === undefined) return undefined
  206. const token = value as Record<string, unknown>
  207. if (token.kind === 'array') {
  208. if (keys.length !== 2 || !keys.includes('kind') || !keys.includes('length')) return undefined
  209. const length = token.length
  210. return typeof length === 'number' && Number.isSafeInteger(length) && length >= 0
  211. ? { kind: 'array', length }
  212. : undefined
  213. }
  214. if (token.kind === 'object') {
  215. if (keys.length !== 2 || !keys.includes('kind') || !keys.includes('keys')) return undefined
  216. const objectKeys = token.keys
  217. if (!Array.isArray(objectKeys) || !isDenseArray(objectKeys)) return undefined
  218. const unique = new Set<string>()
  219. const normalizedKeys: string[] = []
  220. for (const key of objectKeys as unknown[]) {
  221. if (typeof key !== 'string' || unique.has(key)) return undefined
  222. unique.add(key)
  223. normalizedKeys.push(key)
  224. }
  225. return { kind: 'object', keys: normalizedKeys }
  226. }
  227. return undefined
  228. }
  229. /**
  230. * Rebuild one lossless JSON value from the flat worker-thread wire format.
  231. * Malformed or incomplete traffic returns `undefined`; traversal is iterative
  232. * and therefore independent of the transported value's application depth.
  233. * @param input - untrusted message-port payload.
  234. * @returns the detached JSON value, or `undefined` when the wire is invalid.
  235. */
  236. export function decodeWorkerJson(input: unknown): CodeJsonValue | undefined {
  237. try {
  238. if (!Array.isArray(input) || !isDenseArray(input) || input.length === 0) return undefined
  239. const wire = input as unknown[]
  240. const frames: DecodeFrame[] = []
  241. let root: CodeJsonValue | undefined
  242. let rootAssigned = false
  243. const attach = (value: CodeJsonValue): boolean => {
  244. const parent = frames.at(-1)
  245. if (!parent) {
  246. if (rootAssigned) return false
  247. root = value
  248. rootAssigned = true
  249. return true
  250. }
  251. /* v8 ignore next -- completed frames are popped before another token can attach. */
  252. if (parent.index >= (parent.kind === 'array' ? parent.length : parent.keys.length)) return false
  253. if (parent.kind === 'array') {
  254. parent.target.push(value)
  255. } else {
  256. const key = parent.keys[parent.index]
  257. /* v8 ignore next -- object frames are built from validated keys and their exact length. */
  258. if (key === undefined) return false
  259. Object.defineProperty(parent.target, key, {
  260. value,
  261. enumerable: true,
  262. configurable: true,
  263. writable: true,
  264. })
  265. }
  266. parent.index += 1
  267. return true
  268. }
  269. for (let tokenIndex = 0; tokenIndex < wire.length; tokenIndex++) {
  270. const token = wire[tokenIndex]
  271. let value: CodeJsonValue
  272. let frame: DecodeFrame | undefined
  273. if (token === null || typeof token === 'boolean' || typeof token === 'string') {
  274. value = token
  275. } else if (typeof token === 'number') {
  276. if (!Number.isFinite(token) || Object.is(token, -0)) return undefined
  277. value = token
  278. } else {
  279. if (typeof token !== 'object') return undefined
  280. const marker = containerToken(token)
  281. if (!marker) return undefined
  282. const remainingTokens = wire.length - tokenIndex - 1
  283. if (marker.kind === 'array') {
  284. if (marker.length > remainingTokens) return undefined
  285. const target: CodeJsonValue[] = []
  286. value = target
  287. if (marker.length > 0) frame = { kind: 'array', target, length: marker.length, index: 0 }
  288. } else {
  289. if (marker.keys.length > remainingTokens) return undefined
  290. const target: Record<string, CodeJsonValue> = {}
  291. value = target
  292. if (marker.keys.length > 0) frame = { kind: 'object', target, keys: marker.keys, index: 0 }
  293. }
  294. }
  295. if (!attach(value)) return undefined
  296. if (frame) frames.push(frame)
  297. while (frames.length > 0) {
  298. const current = frames.at(-1)
  299. /* v8 ignore next -- the loop condition guarantees a final frame. */
  300. if (current === undefined) break
  301. if (current.index < (current.kind === 'array' ? current.length : current.keys.length)) break
  302. frames.pop()
  303. }
  304. }
  305. return frames.length === 0 ? root : undefined
  306. } catch {
  307. return undefined
  308. }
  309. }
  310. /* jscpd:ignore-end */