worker-json.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. /**
  4. * Validate and detach one worker-boundary value without loading another
  5. * workspace package at runtime. This mirrors the session-owned canonical
  6. * JSON boundary while remaining safe to import from the unbuilt worker.
  7. *
  8. * @param value - the candidate completion value.
  9. * @returns a detached lossless-JSON snapshot, or `undefined` when invalid.
  10. */
  11. export function snapshotCodeJsonValue(value: unknown): CodeJsonValue | undefined {
  12. const active = new Set<object>()
  13. const within = <T extends CodeJsonValue>(source: object, build: () => T | undefined): T | undefined => {
  14. if (active.has(source)) return undefined
  15. active.add(source)
  16. try {
  17. return build()
  18. } finally {
  19. active.delete(source)
  20. }
  21. }
  22. const copy = (candidate: unknown): CodeJsonValue | undefined => {
  23. if (candidate === null) return null
  24. if (typeof candidate === 'boolean' || typeof candidate === 'string') return candidate
  25. if (typeof candidate === 'number') {
  26. return Number.isFinite(candidate) && !Object.is(candidate, -0) ? candidate : undefined
  27. }
  28. if (typeof candidate !== 'object') return undefined
  29. if (Array.isArray(candidate)) {
  30. if (Object.getPrototypeOf(candidate) !== Array.prototype) return undefined
  31. if (Reflect.ownKeys(candidate).length !== candidate.length + 1) return undefined
  32. return within(candidate, () => {
  33. const result: CodeJsonValue[] = []
  34. for (let index = 0; index < candidate.length; index++) {
  35. if (!Object.hasOwn(candidate, index)) return undefined
  36. const item = copy(candidate[index])
  37. if (item === undefined) return undefined
  38. result.push(item)
  39. }
  40. return result
  41. })
  42. }
  43. const prototype = Object.getPrototypeOf(candidate) as unknown
  44. if (prototype !== Object.prototype && prototype !== null) return undefined
  45. return within(candidate, () => {
  46. const result: Record<string, CodeJsonValue> = {}
  47. for (const key of Object.keys(candidate)) {
  48. const item = copy((candidate as Record<string, unknown>)[key])
  49. if (item === undefined) return undefined
  50. Object.defineProperty(result, key, {
  51. value: item,
  52. enumerable: true,
  53. configurable: true,
  54. writable: true,
  55. })
  56. }
  57. return result
  58. })
  59. }
  60. return copy(value)
  61. }