json.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. /** Lossless-JSON validation and detached snapshots for durable session data. @module @deepseek-ai/dsh-session/json */
  2. /**
  3. * A value that round-trips losslessly through JSON: `null`, a boolean, a finite
  4. * number other than negative zero, a string, an array of such values, or a
  5. * plain object whose values are such values. Arrays may carry only their dense
  6. * indexed elements; extra own properties would be discarded by JSON. TypeScript
  7. * cannot distinguish `-0` from `number`, so {@link isJsonValue} and
  8. * {@link snapshotJsonValue} enforce these details at runtime. Use this type for
  9. * a payload that must survive session-log persistence and replay byte-identically
  10. * — e.g. a tool's private presentation `meta`.
  11. */
  12. export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
  13. /** Whether a realm-owned intrinsic prototype is backed by its native constructor. */
  14. function hasIntrinsicConstructor(prototype: object, name: 'Array' | 'Object'): boolean {
  15. const descriptor = Object.getOwnPropertyDescriptor(prototype, 'constructor')
  16. const constructor: unknown = descriptor?.value
  17. if (typeof constructor !== 'function') return false
  18. try {
  19. return constructor.name === name
  20. && constructor.prototype === prototype
  21. && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`
  22. } catch {
  23. return false
  24. }
  25. }
  26. /** Whether a candidate is one realm's intrinsic `Object.prototype`. */
  27. function isIntrinsicObjectPrototype(value: object): boolean {
  28. return Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, 'Object')
  29. }
  30. /** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */
  31. function hasPlainArrayPrototype(value: unknown[]): boolean {
  32. const prototype: unknown = Object.getPrototypeOf(value)
  33. if (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, 'Array')) return false
  34. const objectPrototype: unknown = Object.getPrototypeOf(prototype)
  35. return typeof objectPrototype === 'object'
  36. && objectPrototype !== null
  37. && isIntrinsicObjectPrototype(objectPrototype)
  38. }
  39. /** Whether an object is a plain or null-prototype record from any JavaScript realm. */
  40. function hasPlainObjectPrototype(value: object): boolean {
  41. const prototype: unknown = Object.getPrototypeOf(value)
  42. return prototype === null
  43. || typeof prototype === 'object' && isIntrinsicObjectPrototype(prototype)
  44. }
  45. /** Return every JSON-visible object key, or reject own data JSON would discard. */
  46. function enumerableStringKeys(value: object): string[] | undefined {
  47. const keys = Reflect.ownKeys(value)
  48. if (keys.some(key => typeof key !== 'string' || !Object.prototype.propertyIsEnumerable.call(value, key))) return undefined
  49. return keys as string[]
  50. }
  51. type SnapshotDestination =
  52. | { kind: 'root' }
  53. | { kind: 'array'; target: JsonValue[]; index: number }
  54. | { kind: 'object'; target: { [key: string]: JsonValue }; key: string }
  55. type JsonWalkTask =
  56. | { kind: 'visit'; value: unknown; destination?: SnapshotDestination }
  57. | { kind: 'array-item'; source: unknown[]; index: number; target?: JsonValue[] }
  58. | { kind: 'object-property'; source: Record<string, unknown>; key: string; target?: { [key: string]: JsonValue } }
  59. | { kind: 'leave'; source: object }
  60. /** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */
  61. function walkJsonValue(value: unknown, detach: boolean): JsonValue | true | undefined {
  62. const ancestors = new Set<object>()
  63. let root: JsonValue | undefined
  64. const assign = (destination: SnapshotDestination | undefined, item: JsonValue): void => {
  65. if (destination === undefined) return
  66. if (destination.kind === 'root') {
  67. root = item
  68. } else if (destination.kind === 'array') {
  69. destination.target[destination.index] = item
  70. } else {
  71. Object.defineProperty(destination.target, destination.key, {
  72. value: item,
  73. enumerable: true,
  74. configurable: true,
  75. writable: true,
  76. })
  77. }
  78. }
  79. const tasks: JsonWalkTask[] = [{
  80. kind: 'visit',
  81. value,
  82. ...(detach ? { destination: { kind: 'root' } as const } : {}),
  83. }]
  84. for (let task = tasks.pop(); task !== undefined; task = tasks.pop()) {
  85. if (task.kind === 'leave') {
  86. ancestors.delete(task.source)
  87. continue
  88. }
  89. if (task.kind === 'array-item') {
  90. if (!Object.prototype.hasOwnProperty.call(task.source, task.index)) return undefined
  91. tasks.push({
  92. kind: 'visit',
  93. value: task.source[task.index],
  94. ...(task.target === undefined ? {} : { destination: { kind: 'array', target: task.target, index: task.index } as const }),
  95. })
  96. continue
  97. }
  98. if (task.kind === 'object-property') {
  99. tasks.push({
  100. kind: 'visit',
  101. value: task.source[task.key],
  102. ...(task.target === undefined ? {} : { destination: { kind: 'object', target: task.target, key: task.key } as const }),
  103. })
  104. continue
  105. }
  106. const current = task.value
  107. if (current === null) {
  108. assign(task.destination, null)
  109. continue
  110. }
  111. if (typeof current === 'boolean' || typeof current === 'string') {
  112. assign(task.destination, current)
  113. continue
  114. }
  115. if (typeof current === 'number') {
  116. if (!Number.isFinite(current) || Object.is(current, -0)) return undefined
  117. assign(task.destination, current)
  118. continue
  119. }
  120. if (typeof current !== 'object') return undefined
  121. if (ancestors.has(current)) return undefined
  122. if (Array.isArray(current)) {
  123. if (!hasPlainArrayPrototype(current)) return undefined
  124. const length = current.length
  125. if (Reflect.ownKeys(current).length !== length + 1) return undefined
  126. const target = detach ? [] as JsonValue[] : undefined
  127. if (target !== undefined) assign(task.destination, target)
  128. ancestors.add(current)
  129. tasks.push({ kind: 'leave', source: current })
  130. for (let index = length - 1; index >= 0; index--) {
  131. tasks.push({ kind: 'array-item', source: current, index, ...(target === undefined ? {} : { target }) })
  132. }
  133. continue
  134. }
  135. if (!hasPlainObjectPrototype(current)) return undefined
  136. const keys = enumerableStringKeys(current)
  137. if (keys === undefined) return undefined
  138. const target = detach ? {} as { [key: string]: JsonValue } : undefined
  139. if (target !== undefined) assign(task.destination, target)
  140. ancestors.add(current)
  141. tasks.push({ kind: 'leave', source: current })
  142. for (let index = keys.length - 1; index >= 0; index--) {
  143. const key = keys[index]
  144. /* v8 ignore next -- the loop is bounded by the captured key count. */
  145. if (key === undefined) return undefined
  146. tasks.push({ kind: 'object-property', source: current as Record<string, unknown>, key, ...(target === undefined ? {} : { target }) })
  147. }
  148. }
  149. return detach ? root : true
  150. }
  151. /**
  152. * Validate and detach lossless JSON in one read per property, so a stateful
  153. * getter cannot change between validation and copying. Traversal is iterative,
  154. * so valid nesting is bounded by available memory rather than the JavaScript
  155. * call stack. Accepts ordinary arrays, plain or null-prototype objects, and JSON
  156. * scalars; rejects sparse, cyclic, exotic, negative-zero, and non-finite values.
  157. * Getter throws propagate.
  158. *
  159. * @param value - the candidate value to validate and detach.
  160. * @returns the detached snapshot, or `undefined` when the value is not
  161. * losslessly JSON-serializable.
  162. */
  163. export function snapshotJsonValue<T>(value: T): T | undefined {
  164. return walkJsonValue(value, true) as T | undefined
  165. }
  166. /**
  167. * Test the same lossless JSON boundary as {@link snapshotJsonValue} without
  168. * detaching it. Only own enumerable string properties participate; `toJSON`
  169. * is ignored and getters run, so persistence boundaries use the snapshotter.
  170. * @param value - the candidate event data to test.
  171. * @returns whether `value` survives JSON round-trip losslessly.
  172. */
  173. export function isJsonValue(value: unknown): boolean {
  174. return walkJsonValue(value, false) === true
  175. }