index.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /** Duplicate-install-safe JSON and immutable-value helpers. @module @deepseek-ai/dsh-util-values */
  2. /** A value that round-trips through JSON without loss. */
  3. export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
  4. /**
  5. * Mark an unreachable closed-union branch.
  6. * @param value - impossible value; an unhandled typed variant fails at the call site.
  7. * @param context - optional switch-site label included in the failure message.
  8. * @returns never; a runtime value that escaped its type always throws.
  9. */
  10. export function assertNever(value: never, context?: string): never {
  11. const rendered = (JSON.stringify(value) as string | undefined) ?? String(value)
  12. throw new Error(`unreachable variant${context ? ` in ${context}` : ''}: ${rendered}`)
  13. }
  14. /** Whether a realm-owned intrinsic prototype is backed by its native constructor. */
  15. function hasIntrinsicConstructor(prototype: object, name: 'Array' | 'Object'): boolean {
  16. const descriptor = Object.getOwnPropertyDescriptor(prototype, 'constructor')
  17. const constructor: unknown = descriptor?.value
  18. if (typeof constructor !== 'function') return false
  19. try {
  20. return constructor.name === name
  21. && constructor.prototype === prototype
  22. && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`
  23. } catch {
  24. return false
  25. }
  26. }
  27. /** Whether a candidate is one realm's intrinsic `Object.prototype`. */
  28. function isIntrinsicObjectPrototype(value: object): boolean {
  29. return Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, 'Object')
  30. }
  31. /** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */
  32. function hasPlainArrayPrototype(value: unknown[]): boolean {
  33. const prototype: unknown = Object.getPrototypeOf(value)
  34. if (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, 'Array')) return false
  35. const objectPrototype: unknown = Object.getPrototypeOf(prototype)
  36. return typeof objectPrototype === 'object'
  37. && objectPrototype !== null
  38. && isIntrinsicObjectPrototype(objectPrototype)
  39. }
  40. /** Whether an object is a plain or null-prototype record from any JavaScript realm. */
  41. function hasPlainObjectPrototype(value: object): boolean {
  42. const prototype: unknown = Object.getPrototypeOf(value)
  43. return prototype === null
  44. || typeof prototype === 'object' && isIntrinsicObjectPrototype(prototype)
  45. }
  46. /** Return every JSON-visible object key, or reject own data JSON would discard. */
  47. function enumerableStringKeys(value: object): string[] | undefined {
  48. const keys = Reflect.ownKeys(value)
  49. if (keys.some(key => typeof key !== 'string' || !Object.prototype.propertyIsEnumerable.call(value, key))) return undefined
  50. return keys as string[]
  51. }
  52. type SnapshotDestination =
  53. | { kind: 'root' }
  54. | { kind: 'array'; target: JsonValue[]; index: number }
  55. | { kind: 'object'; target: { [key: string]: JsonValue }; key: string }
  56. type JsonWalkTask =
  57. | { kind: 'visit'; value: unknown; destination?: SnapshotDestination }
  58. | { kind: 'array-item'; source: unknown[]; index: number; target?: JsonValue[] }
  59. | { kind: 'object-property'; source: Record<string, unknown>; key: string; target?: { [key: string]: JsonValue } }
  60. | { kind: 'leave'; source: object }
  61. /** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */
  62. function walkJsonValue(value: unknown, detach: boolean): JsonValue | true | undefined {
  63. const ancestors = new Set<object>()
  64. let root: JsonValue | undefined
  65. const assign = (destination: SnapshotDestination | undefined, item: JsonValue): void => {
  66. if (destination === undefined) return
  67. if (destination.kind === 'root') {
  68. root = item
  69. } else if (destination.kind === 'array') {
  70. destination.target[destination.index] = item
  71. } else {
  72. Object.defineProperty(destination.target, destination.key, {
  73. value: item,
  74. enumerable: true,
  75. configurable: true,
  76. writable: true,
  77. })
  78. }
  79. }
  80. const tasks: JsonWalkTask[] = [{
  81. kind: 'visit',
  82. value,
  83. ...(detach ? { destination: { kind: 'root' } as const } : {}),
  84. }]
  85. for (let task = tasks.pop(); task !== undefined; task = tasks.pop()) {
  86. if (task.kind === 'leave') {
  87. ancestors.delete(task.source)
  88. continue
  89. }
  90. if (task.kind === 'array-item') {
  91. if (!Object.prototype.hasOwnProperty.call(task.source, task.index)) return undefined
  92. tasks.push({
  93. kind: 'visit',
  94. value: task.source[task.index],
  95. ...(task.target === undefined ? {} : { destination: { kind: 'array', target: task.target, index: task.index } as const }),
  96. })
  97. continue
  98. }
  99. if (task.kind === 'object-property') {
  100. tasks.push({
  101. kind: 'visit',
  102. value: task.source[task.key],
  103. ...(task.target === undefined ? {} : { destination: { kind: 'object', target: task.target, key: task.key } as const }),
  104. })
  105. continue
  106. }
  107. const current = task.value
  108. if (current === null) {
  109. assign(task.destination, null)
  110. continue
  111. }
  112. if (typeof current === 'boolean' || typeof current === 'string') {
  113. assign(task.destination, current)
  114. continue
  115. }
  116. if (typeof current === 'number') {
  117. if (!Number.isFinite(current) || Object.is(current, -0)) return undefined
  118. assign(task.destination, current)
  119. continue
  120. }
  121. if (typeof current !== 'object') return undefined
  122. if (ancestors.has(current)) return undefined
  123. if (Array.isArray(current)) {
  124. if (!hasPlainArrayPrototype(current)) return undefined
  125. const length = current.length
  126. if (Reflect.ownKeys(current).length !== length + 1) return undefined
  127. const target = detach ? [] as JsonValue[] : undefined
  128. if (target !== undefined) assign(task.destination, target)
  129. ancestors.add(current)
  130. tasks.push({ kind: 'leave', source: current })
  131. for (let index = length - 1; index >= 0; index--) {
  132. tasks.push({ kind: 'array-item', source: current, index, ...(target === undefined ? {} : { target }) })
  133. }
  134. continue
  135. }
  136. if (!hasPlainObjectPrototype(current)) return undefined
  137. const keys = enumerableStringKeys(current)
  138. if (keys === undefined) return undefined
  139. const target = detach ? {} as { [key: string]: JsonValue } : undefined
  140. if (target !== undefined) assign(task.destination, target)
  141. ancestors.add(current)
  142. tasks.push({ kind: 'leave', source: current })
  143. for (let index = keys.length - 1; index >= 0; index--) {
  144. const key = keys[index]
  145. /* v8 ignore next -- the loop is bounded by the captured key count. */
  146. if (key === undefined) return undefined
  147. tasks.push({ kind: 'object-property', source: current as Record<string, unknown>, key, ...(target === undefined ? {} : { target }) })
  148. }
  149. }
  150. return detach ? root : true
  151. }
  152. /**
  153. * Validate and detach lossless JSON in one read per property.
  154. * @param value - candidate value to validate and detach.
  155. * @returns the detached snapshot, or `undefined` when the value is not losslessly JSON-serializable.
  156. */
  157. export function snapshotJsonValue<T>(value: T): T | undefined {
  158. return walkJsonValue(value, true) as T | undefined
  159. }
  160. /**
  161. * Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.
  162. * @param value - candidate value to test.
  163. * @returns whether the value survives a JSON round trip without loss.
  164. */
  165. export function isJsonValue(value: unknown): boolean {
  166. return walkJsonValue(value, false) === true
  167. }
  168. /**
  169. * Compare JSON-compatible values structurally.
  170. * @param a - one JSON-compatible value.
  171. * @param b - the other JSON-compatible value.
  172. * @returns whether both values contain the same JSON data.
  173. */
  174. export function deepEqualJson(a: unknown, b: unknown): boolean {
  175. if (a === b) return true
  176. if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false
  177. if (Array.isArray(a) || Array.isArray(b)) {
  178. if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false
  179. return a.every((entry, index) => deepEqualJson(entry, b[index]))
  180. }
  181. const left = a as Record<string, unknown>
  182. const right = b as Record<string, unknown>
  183. const keys = Object.keys(left)
  184. if (keys.length !== Object.keys(right).length) return false
  185. return keys.every(key => key in right && deepEqualJson(left[key], right[key]))
  186. }
  187. /**
  188. * Deep-freeze an object graph in place while leaving live AbortSignal objects mutable.
  189. * @param value - value to freeze.
  190. * @returns the same value after every reachable enumerable child is frozen.
  191. */
  192. export function deepFreeze<T>(value: T): T {
  193. const seen = new WeakSet<object>()
  194. const pending: (
  195. | { kind: 'visit'; node: unknown }
  196. | { kind: 'property'; source: Record<string, unknown>; key: string }
  197. )[] = [{ kind: 'visit', node: value }]
  198. while (pending.length > 0) {
  199. const task = pending.pop()
  200. /* v8 ignore next -- the loop condition guarantees one pending task. */
  201. if (task === undefined) continue
  202. if (task.kind === 'property') {
  203. pending.push({ kind: 'visit', node: task.source[task.key] })
  204. continue
  205. }
  206. const node = task.node
  207. if (node === null || typeof node !== 'object') continue
  208. if (node instanceof AbortSignal) continue
  209. if (seen.has(node)) continue
  210. seen.add(node)
  211. Object.freeze(node)
  212. const keys = Object.keys(node)
  213. for (let index = keys.length - 1; index >= 0; index--) {
  214. const key = keys[index]
  215. /* v8 ignore next -- the loop is bounded by the captured key count. */
  216. if (key === undefined) continue
  217. pending.push({ kind: 'property', source: node as Record<string, unknown>, key })
  218. }
  219. }
  220. return value
  221. }