dsh-subagent-dispatch-control 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +183 -2
  3. package/client.js +9781 -0
  4. package/cordis.patch.yml +13 -0
  5. package/docs/BOOST-EVIDENCE.md +259 -0
  6. package/docs/CONFORMANCE.md +236 -0
  7. package/docs/FACTS-CONTRACT.md +368 -0
  8. package/docs/FLOW-COVERAGE.md +215 -0
  9. package/docs/PACKAGE-README.md +858 -0
  10. package/docs/RANGE-PLAN.md +357 -0
  11. package/docs/SECURITY-NOTES.md +110 -0
  12. package/docs/SPLIT-PLAN.md +604 -0
  13. package/docs/STAGE3-CONTRACT.md +287 -0
  14. package/docs/TIER-ROUTING.md +275 -0
  15. package/docs/badge/CONFORMANCE.md +246 -0
  16. package/docs/badge/DETAIL.md +319 -0
  17. package/docs/badge/PROJECTIONS.md +264 -0
  18. package/docs/badge/TEST-PLAN.md +252 -0
  19. package/docs/images/badge-menu.png +0 -0
  20. package/docs/images/dispatch.png +0 -0
  21. package/docs/images/header.png +0 -0
  22. package/docs/images/pair-header.png +0 -0
  23. package/docs/images/pair-panel.png +0 -0
  24. package/docs/images/panel.png +0 -0
  25. package/docs/wiki/Home.md +43 -0
  26. package/docs/wiki//344/275/277/347/224/250/346/214/207/345/215/227.md +97 -0
  27. package/docs/wiki//345/256/211/350/243/205/344/270/216/345/215/207/347/272/247.md +87 -0
  28. package/docs/wiki//346/225/205/351/232/234/346/216/222/346/237/245.md +94 -0
  29. package/icon.svg +12 -0
  30. package/lib/badge-policy.mjs +502 -0
  31. package/lib/badge-sync.mjs +385 -0
  32. package/lib/command.mjs +490 -0
  33. package/lib/completion.mjs +288 -0
  34. package/lib/concurrency.mjs +2555 -0
  35. package/lib/dispatch-command.mjs +181 -0
  36. package/lib/dispatch-gate.mjs +924 -0
  37. package/lib/facts-store.mjs +183 -0
  38. package/lib/gate-state.mjs +465 -0
  39. package/lib/gate.mjs +886 -0
  40. package/lib/index.js +309 -0
  41. package/lib/inject.mjs +195 -0
  42. package/lib/interrupt.mjs +376 -0
  43. package/lib/ledger.mjs +948 -0
  44. package/lib/lifecycle.mjs +274 -0
  45. package/lib/messages.mjs +532 -0
  46. package/lib/notice.mjs +769 -0
  47. package/lib/plan-gate.mjs +385 -0
  48. package/lib/projection.mjs +978 -0
  49. package/lib/report.mjs +290 -0
  50. package/lib/route.mjs +346 -0
  51. package/lib/run-registry.mjs +402 -0
  52. package/lib/services.mjs +293 -0
  53. package/lib/stuck.mjs +567 -0
  54. package/lib/tier-config.mjs +212 -0
  55. package/lib/tier-policy.mjs +167 -0
  56. package/lib/tier-state.mjs +137 -0
  57. package/lib/todo-gate.mjs +1672 -0
  58. package/lib/tools.mjs +2912 -0
  59. package/locale/en.json +9 -0
  60. package/locale/zh.json +9 -0
  61. package/package.json +83 -4
  62. package/vendor/node_modules/@deepseek-ai/cosmokit/LICENSE +21 -0
  63. package/vendor/node_modules/@deepseek-ai/cosmokit/README.md +30 -0
  64. package/vendor/node_modules/@deepseek-ai/cosmokit/lib/index.js +418 -0
  65. package/vendor/node_modules/@deepseek-ai/cosmokit/package.json +32 -0
  66. package/vendor/node_modules/@deepseek-ai/cosmokit/src/array.ts +42 -0
  67. package/vendor/node_modules/@deepseek-ai/cosmokit/src/index.ts +12 -0
  68. package/vendor/node_modules/@deepseek-ai/cosmokit/src/misc.ts +78 -0
  69. package/vendor/node_modules/@deepseek-ai/cosmokit/src/string.ts +113 -0
  70. package/vendor/node_modules/@deepseek-ai/cosmokit/src/time.ts +92 -0
  71. package/vendor/node_modules/@deepseek-ai/cosmokit/src/types.ts +168 -0
  72. package/vendor/node_modules/@deepseek-ai/cosmokit/src/volatile.ts +86 -0
  73. package/vendor/node_modules/@deepseek-ai/schemastery/LICENSE +21 -0
  74. package/vendor/node_modules/@deepseek-ai/schemastery/README.md +393 -0
  75. package/vendor/node_modules/@deepseek-ai/schemastery/lib/index.cjs +635 -0
  76. package/vendor/node_modules/@deepseek-ai/schemastery/lib/index.mjs +635 -0
  77. package/vendor/node_modules/@deepseek-ai/schemastery/package.json +39 -0
  78. package/vendor/node_modules/@deepseek-ai/schemastery/src/index.ts +962 -0
  79. package/vendor/node_modules/@standard-schema/spec/LICENSE +21 -0
  80. package/vendor/node_modules/@standard-schema/spec/README.md +198 -0
  81. package/vendor/node_modules/@standard-schema/spec/dist/index.cjs +18 -0
  82. package/vendor/node_modules/@standard-schema/spec/dist/index.js +0 -0
  83. package/vendor/node_modules/@standard-schema/spec/package.json +39 -0
@@ -0,0 +1,78 @@
1
+ /** String/symbol keyed dictionary type. */
2
+ export type Dict<T = any, K extends string | symbol = string> = { [key in K]: T }
3
+ /** Safely read `T[K]`, returning `never` when `K` is not a key of `T`. */
4
+ export type Get<T extends {}, K> = K extends keyof T ? T[K] : never
5
+ /** Conditional extraction helper with a configurable return type. */
6
+ export type Extract<S, T, U = S> = S extends T ? U : never
7
+ /** Accept a value or an array, unless the value is already an array type. */
8
+ export type MaybeArray<T> = [T] extends [unknown[]] ? T : T | T[]
9
+ /** Wrap a value in `Promise`, preserving the resolved type of existing promises. */
10
+ export type Promisify<T> = Promise<T extends Promise<infer S> ? S : T>
11
+ /** Accept a value or promise unless the value type is already promise-like. */
12
+ export type Awaitable<T> = [T] extends [Promise<unknown>] ? T : T | Promise<T>
13
+ /** Convert a union type to an intersection type. */
14
+ export type Intersect<U> = (U extends any ? (arg: U) => void : never) extends ((arg: infer I) => void) ? I : never
15
+
16
+ /** No-op callback returning `undefined` at runtime and `any` at type level. */
17
+ export function noop(): any {}
18
+
19
+ /** Return true when a value is `null` or `undefined`. */
20
+ export function isNullable(value: any): value is null | undefined | void {
21
+ return value === null || value === undefined
22
+ }
23
+
24
+ /** Return true when a value is neither `null` nor `undefined`. */
25
+ export function isNonNullable<T>(value: T): value is NonNullable<T> {
26
+ return !isNullable(value)
27
+ }
28
+
29
+ /** Return true for non-array object values. */
30
+ export function isPlainObject(data: any) {
31
+ return data && typeof data === 'object' && !Array.isArray(data)
32
+ }
33
+
34
+ /** Filter object entries with a key type guard. */
35
+ export function filterKeys<T, K extends string, U extends K>(object: Dict<T, K>, filter: (key: K, value: T) => key is U): Dict<T, U>
36
+ /** Filter object entries with a boolean predicate. */
37
+ export function filterKeys<T, K extends string>(object: Dict<T, K>, filter: (key: K, value: T) => boolean): Dict<T, K>
38
+ /** Filter object entries and return a new object. */
39
+ export function filterKeys(object: {}, filter: (key: string, value: any) => boolean) {
40
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)))
41
+ }
42
+
43
+ /** Map object values while preserving the original key set. */
44
+ export function mapValues<U, T, K extends string>(object: Dict<T, K>, transform: (value: T, key: K) => U) {
45
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, (transform as any)(value, key)])) as Dict<U, K>
46
+ }
47
+
48
+ /** Alias for `mapValues`. */
49
+ export { mapValues as valueMap }
50
+
51
+ /** Pick selected keys from an object, optionally including `undefined` values. */
52
+ export function pick<T extends object, K extends keyof T>(source: T, keys?: Iterable<K>, forced?: boolean) {
53
+ if (!keys) return { ...source }
54
+ const result = {} as Pick<T, K>
55
+ for (const key of keys) {
56
+ if (forced || source[key] !== undefined) result[key] = source[key]
57
+ }
58
+ return result
59
+ }
60
+
61
+ /** Omit selected keys from a shallow object copy. */
62
+ export function omit<T, K extends keyof T>(source: T, keys?: Iterable<K>) {
63
+ if (!keys) return { ...source }
64
+ const result = { ...source } as Omit<T, K>
65
+ for (const key of keys) {
66
+ Reflect.deleteProperty(result, key)
67
+ }
68
+ return result
69
+ }
70
+
71
+ /** Define a non-enumerable writable property with a typed key. */
72
+ export function defineProperty<T, K extends keyof T>(object: T, key: K, value: T[K]): T
73
+ /** Define a non-enumerable writable property with an arbitrary key. */
74
+ export function defineProperty<T, K extends keyof any>(object: T, key: K, value: any): T
75
+ /** Define a non-enumerable writable property and return the object. */
76
+ export function defineProperty<T, K extends keyof any>(object: T, key: K, value: any) {
77
+ return Object.defineProperty(object, key, { writable: true, value, enumerable: false })
78
+ }
@@ -0,0 +1,113 @@
1
+ /** Uppercase the first character of a string. */
2
+ export function capitalize(source: string) {
3
+ return source.charAt(0).toUpperCase() + source.slice(1)
4
+ }
5
+
6
+ /** Lowercase the first character of a string. */
7
+ export function uncapitalize(source: string) {
8
+ return source.charAt(0).toLowerCase() + source.slice(1)
9
+ }
10
+
11
+ /** Convert dash or underscore delimited text to camelCase. */
12
+ export function camelCase(source: string) {
13
+ return source.replace(/[_-][a-z]/g, str => str.slice(1).toUpperCase())
14
+ }
15
+
16
+ const enum State {
17
+ DELIM,
18
+ UPPER,
19
+ LOWER,
20
+ }
21
+
22
+ function tokenize(source: string, delimiters: number[], delimiter: number) {
23
+ const output: number[] = []
24
+ let state = State.DELIM
25
+ for (let i = 0; i < source.length; i++) {
26
+ const code = source.charCodeAt(i)
27
+ if (code >= 65 && code <= 90) {
28
+ if (state === State.UPPER) {
29
+ const next = source.charCodeAt(i + 1)
30
+ if (next >= 97 && next <= 122) {
31
+ output.push(delimiter)
32
+ }
33
+ output.push(code + 32)
34
+ } else {
35
+ if (state !== State.DELIM) {
36
+ output.push(delimiter)
37
+ }
38
+ output.push(code + 32)
39
+ }
40
+ state = State.UPPER
41
+ } else if (code >= 97 && code <= 122) {
42
+ output.push(code)
43
+ state = State.LOWER
44
+ } else if (delimiters.includes(code)) {
45
+ if (state !== State.DELIM) {
46
+ output.push(delimiter)
47
+ }
48
+ state = State.DELIM
49
+ } else {
50
+ output.push(code)
51
+ }
52
+ }
53
+ return String.fromCharCode(...output)
54
+ }
55
+
56
+ /** Convert text to dash-delimited parameter case. */
57
+ export function paramCase(source: string) {
58
+ return tokenize(source, [45, 95], 45)
59
+ }
60
+
61
+ /** Convert text to underscore-delimited snake case. */
62
+ export function snakeCase(source: string) {
63
+ return tokenize(source, [45, 95], 95)
64
+ }
65
+
66
+ /** Runtime alias for `camelCase`. */
67
+ export const camelize = camelCase
68
+ /** Runtime alias for `paramCase`. */
69
+ export const hyphenate = paramCase
70
+
71
+ namespace Letter {
72
+ /* eslint-disable @typescript-eslint/member-delimiter-style */
73
+ interface LowerToUpper {
74
+ a: 'A', b: 'B', c: 'C', d: 'D', e: 'E', f: 'F', g: 'G', h: 'H', i: 'I', j: 'J', k: 'K', l: 'L', m: 'M',
75
+ n: 'N', o: 'O', p: 'P', q: 'Q', r: 'R', s: 'S', t: 'T', u: 'U', v: 'V', w: 'W', x: 'X', y: 'Y', z: 'Z',
76
+ }
77
+
78
+ interface UpperToLower {
79
+ A: 'a', B: 'b', C: 'c', D: 'd', E: 'e', F: 'f', G: 'g', H: 'h', I: 'i', J: 'j', K: 'k', L: 'l', M: 'm',
80
+ N: 'n', O: 'o', P: 'p', Q: 'q', R: 'r', S: 's', T: 't', U: 'u', V: 'v', W: 'w', X: 'x', Y: 'y', Z: 'z',
81
+ }
82
+ /* eslint-enable @typescript-eslint/member-delimiter-style */
83
+
84
+ export type Upper = keyof UpperToLower
85
+ export type Lower = keyof LowerToUpper
86
+
87
+ export type ToUpper<S extends string> = S extends Lower ? LowerToUpper[S] : S
88
+ export type ToLower<S extends string, P extends string = ''> = S extends Upper ? `${P}${UpperToLower[S]}` : S
89
+ }
90
+
91
+ /* eslint-disable @typescript-eslint/naming-convention */
92
+ /** Type-level conversion from dash-delimited text to camelCase. */
93
+ export type camelize<S extends string> = S extends `${infer L}-${infer M}${infer R}` ? `${L}${Letter.ToUpper<M>}${camelize<R>}` : S
94
+ /** Type-level conversion from camelCase text to dash-delimited text. */
95
+ export type hyphenate<S extends string> = S extends `${infer L}${infer R}` ? `${Letter.ToLower<L, '-'>}${hyphenate<R>}` : S
96
+ /* eslint-enable @typescript-eslint/naming-convention */
97
+
98
+ /** Format a property key as a JavaScript member access suffix. */
99
+ export function formatProperty(key: keyof any) {
100
+ if (typeof key !== 'string') return `[${key.toString()}]`
101
+ return /^[a-z_$][\w$]*$/i.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`
102
+ }
103
+
104
+ /** Remove one trailing slash from a path string. */
105
+ export function trimSlash(source: string) {
106
+ return source.replace(/\/$/, '')
107
+ }
108
+
109
+ /** Ensure a path starts with `/` and has no trailing slash. */
110
+ export function sanitize(source: string) {
111
+ if (!source.startsWith('/')) source = '/' + source
112
+ return trimSlash(source)
113
+ }
@@ -0,0 +1,92 @@
1
+ /** Time constants plus parsing and formatting helpers. */
2
+ export namespace Time {
3
+ export const millisecond = 1
4
+ export const second = 1000
5
+ export const minute = second * 60
6
+ export const hour = minute * 60
7
+ export const day = hour * 24
8
+ export const week = day * 7
9
+
10
+ let timezoneOffset = new Date().getTimezoneOffset()
11
+
12
+ export function setTimezoneOffset(offset: number) {
13
+ timezoneOffset = offset
14
+ }
15
+
16
+ export function getTimezoneOffset() {
17
+ return timezoneOffset
18
+ }
19
+
20
+ export function getDateNumber(date: number | Date = new Date(), offset?: number) {
21
+ if (typeof date === 'number') date = new Date(date)
22
+ if (offset === undefined) offset = timezoneOffset
23
+ return Math.floor((date.valueOf() / minute - offset) / 1440)
24
+ }
25
+
26
+ export function fromDateNumber(value: number, offset?: number) {
27
+ const date = new Date(value * day)
28
+ if (offset === undefined) offset = timezoneOffset
29
+ return new Date(+date + offset * minute)
30
+ }
31
+
32
+ const numeric = /\d+(?:\.\d+)?/.source
33
+ const timeRegExp = new RegExp(`^${[
34
+ 'w(?:eek(?:s)?)?',
35
+ 'd(?:ay(?:s)?)?',
36
+ 'h(?:our(?:s)?)?',
37
+ 'm(?:in(?:ute)?(?:s)?)?',
38
+ 's(?:ec(?:ond)?(?:s)?)?',
39
+ ].map(unit => `(${numeric}${unit})?`).join('')}$`)
40
+
41
+ export function parseTime(source: string) {
42
+ const capture = timeRegExp.exec(source)
43
+ if (!capture) return 0
44
+ return (parseFloat(capture[1]) * week || 0)
45
+ + (parseFloat(capture[2]) * day || 0)
46
+ + (parseFloat(capture[3]) * hour || 0)
47
+ + (parseFloat(capture[4]) * minute || 0)
48
+ + (parseFloat(capture[5]) * second || 0)
49
+ }
50
+
51
+ export function parseDate(date: string) {
52
+ const parsed = parseTime(date)
53
+ if (parsed) {
54
+ date = Date.now() + parsed as any
55
+ } else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) {
56
+ date = `${new Date().toLocaleDateString()}-${date}`
57
+ } else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) {
58
+ date = `${new Date().getFullYear()}-${date}`
59
+ }
60
+ return date ? new Date(date) : new Date()
61
+ }
62
+
63
+ export function format(ms: number) {
64
+ const abs = Math.abs(ms)
65
+ if (abs >= day - hour / 2) {
66
+ return Math.round(ms / day) + 'd'
67
+ } else if (abs >= hour - minute / 2) {
68
+ return Math.round(ms / hour) + 'h'
69
+ } else if (abs >= minute - second / 2) {
70
+ return Math.round(ms / minute) + 'm'
71
+ } else if (abs >= second) {
72
+ return Math.round(ms / second) + 's'
73
+ }
74
+ return ms + 'ms'
75
+ }
76
+
77
+ export function toDigits(source: number, length = 2) {
78
+ return source.toString().padStart(length, '0')
79
+ }
80
+
81
+ export function template(template: string, time = new Date()) {
82
+ return template
83
+ .replace('yyyy', time.getFullYear().toString())
84
+ .replace('yy', time.getFullYear().toString().slice(2))
85
+ .replace('MM', toDigits(time.getMonth() + 1))
86
+ .replace('dd', toDigits(time.getDate()))
87
+ .replace('hh', toDigits(time.getHours()))
88
+ .replace('mm', toDigits(time.getMinutes()))
89
+ .replace('ss', toDigits(time.getSeconds()))
90
+ .replace('SSS', toDigits(time.getMilliseconds(), 3))
91
+ }
92
+ }
@@ -0,0 +1,168 @@
1
+ import { isNullable } from './misc.ts'
2
+ import { isVolatile } from './volatile.ts'
3
+
4
+ type GlobalConstructorNames = keyof {
5
+ [K in keyof typeof globalThis as typeof globalThis[K] extends abstract new (...args: any) => any ? K : never]: K
6
+ }
7
+
8
+ /** Create a predicate for a global constructor name. */
9
+ export function is<K extends GlobalConstructorNames>(type: K): (value: any) => value is InstanceType<typeof globalThis[K]>
10
+ /** Test whether a value matches a global constructor name. */
11
+ export function is<K extends GlobalConstructorNames>(type: K, value: any): value is InstanceType<typeof globalThis[K]>
12
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
13
+ export function is<K extends GlobalConstructorNames>(type: K, value?: any): any {
14
+ if (arguments.length === 1) return (value: any) => is(type, value)
15
+ return type in globalThis && value instanceof (globalThis[type] as any)
16
+ || Object.prototype.toString.call(value).slice(8, -1) === type
17
+ }
18
+
19
+ function isArrayBufferLike(value: any): value is ArrayBufferLike {
20
+ return is('ArrayBuffer', value) || is('SharedArrayBuffer', value)
21
+ }
22
+
23
+ function isArrayBufferSource(value: any): value is Binary.Source {
24
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value)
25
+ }
26
+
27
+ /** Binary source detection and base64/hex conversion helpers. */
28
+ export namespace Binary {
29
+ export type Source<T extends ArrayBufferLike = ArrayBufferLike> = T | ArrayBufferView<T>
30
+
31
+ export const is = isArrayBufferLike
32
+ export const isSource = isArrayBufferSource
33
+
34
+ export function fromSource<T extends ArrayBufferLike>(source: Source<T>): T {
35
+ if (ArrayBuffer.isView(source)) {
36
+ // https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer#answer-31394257
37
+ return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength) as T
38
+ } else {
39
+ return source
40
+ }
41
+ }
42
+
43
+ export function toBase64(source: Source) {
44
+ source = fromSource(source)
45
+ if (typeof Buffer !== 'undefined') {
46
+ return Buffer.from(source).toString('base64')
47
+ }
48
+ let binary = ''
49
+ const bytes = new Uint8Array(source)
50
+ for (let i = 0; i < bytes.byteLength; i++) {
51
+ binary += String.fromCharCode(bytes[i])
52
+ }
53
+ return btoa(binary)
54
+ }
55
+
56
+ export function fromBase64(source: string) {
57
+ if (typeof Buffer !== 'undefined') return fromSource(Buffer.from(source, 'base64'))
58
+ return Uint8Array.from(atob(source), c => c.charCodeAt(0))
59
+ }
60
+
61
+ export function toHex(source: Source) {
62
+ source = fromSource(source)
63
+ if (typeof Buffer !== 'undefined') return Buffer.from(source).toString('hex')
64
+ return Array.from(new Uint8Array(source), byte => byte.toString(16).padStart(2, '0')).join('')
65
+ }
66
+
67
+ export function fromHex(source: string) {
68
+ if (typeof Buffer !== 'undefined') return fromSource(Buffer.from(source, 'hex'))
69
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1)
70
+ const buffer: number[] = []
71
+ for (let i = 0; i < hex.length; i += 2) {
72
+ buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16))
73
+ }
74
+ return Uint8Array.from(buffer).buffer
75
+ }
76
+ }
77
+
78
+ /** Decode a base64 string into binary data. */
79
+ export const base64ToArrayBuffer = Binary.fromBase64
80
+ /** Encode binary data as base64. */
81
+ export const arrayBufferToBase64 = Binary.toBase64
82
+ /** Decode a hex string into binary data. */
83
+ export const hexToArrayBuffer = Binary.fromHex
84
+ /** Encode binary data as hex. */
85
+ export const arrayBufferToHex = Binary.toHex
86
+
87
+ /** Deep-clone common JavaScript values while preserving prototypes. */
88
+ export function clone<T>(source: T): T
89
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
90
+ export function clone(source: any, refs = new Map<any, any>()) {
91
+ if (!source || typeof source !== 'object') return source
92
+ if (is('Date', source)) return new Date(source.valueOf())
93
+ if (is('RegExp', source)) return new RegExp(source.source, source.flags)
94
+ if (isArrayBufferLike(source)) return source.slice(0)
95
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength)
96
+ const cached = refs.get(source)
97
+ if (cached) return cached
98
+ if (Array.isArray(source)) {
99
+ const result: any[] = []
100
+ refs.set(source, result)
101
+ source.forEach((value, index) => {
102
+ result[index] = Reflect.apply(clone, null, [value, refs])
103
+ })
104
+ return result
105
+ }
106
+ const result = Object.create(Object.getPrototypeOf(source))
107
+ refs.set(source, result)
108
+ for (const key of Reflect.ownKeys(source)) {
109
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) }
110
+ if ('value' in descriptor) {
111
+ descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs])
112
+ }
113
+ Reflect.defineProperty(result, key, descriptor)
114
+ }
115
+ return result
116
+ }
117
+
118
+ /**
119
+ * Compare values recursively, treating two volatile references as equal regardless of value.
120
+ * Strict comparison distinguishes null/undefined, treats opaque objects by identity,
121
+ * compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.
122
+ * @param a - first value.
123
+ * @param b - second value.
124
+ * @param strict - whether to require strict data equality outside volatile references.
125
+ * @returns whether the values compare equal.
126
+ */
127
+ export function deepEqual(a: any, b: any, strict?: boolean): boolean {
128
+ const ancestors = new Set<object>()
129
+ function compare(a: any, b: any): boolean {
130
+ if (a === b) return true
131
+ if (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b)
132
+ if (!strict && isNullable(a) && isNullable(b)) return true
133
+ if (typeof a !== typeof b || typeof a !== 'object' || !a || !b) return false
134
+ if (ancestors.has(a)) return false
135
+
136
+ function check<T>(test: (x: any) => x is T, then: (a: T, b: T) => boolean) {
137
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : undefined
138
+ }
139
+
140
+ ancestors.add(a)
141
+ try {
142
+ return check(Array.isArray, (a, b) => {
143
+ if (a.length !== b.length) return false
144
+ for (let index = 0; index < a.length; index++) {
145
+ if (!compare(a[index], b[index])) return false
146
+ }
147
+ return true
148
+ })
149
+ ?? check(is('Date'), (a, b) => a.valueOf() === b.valueOf())
150
+ ?? check(is('URL'), (a, b) => a.href === b.href)
151
+ ?? check(is('RegExp'), (a, b) => a.source === b.source && a.flags === b.flags)
152
+ ?? check(isArrayBufferLike, (a, b) => {
153
+ if (a.byteLength !== b.byteLength) return false
154
+ const viewA = new Uint8Array(a)
155
+ const viewB = new Uint8Array(b)
156
+ for (let i = 0; i < viewA.length; i++) {
157
+ if (viewA[i] !== viewB[i]) return false
158
+ }
159
+ return true
160
+ })
161
+ ?? ((!strict || [a, b].every(value => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null))
162
+ && Object.keys({ ...a, ...b }).every(key => compare(a[key], b[key])))
163
+ } finally {
164
+ ancestors.delete(a)
165
+ }
166
+ }
167
+ return compare(a, b)
168
+ }
@@ -0,0 +1,86 @@
1
+ /** Shared config references used by schema validators and plugin runtimes. */
2
+
3
+ const write = Symbol.for('cosmokit.volatile.write')
4
+
5
+ /** Recursively readonly data returned by a volatile config reference. */
6
+ export type VolatileSnapshot<T> = T extends object ? { readonly [K in keyof T]: VolatileSnapshot<T[K]> } : T
7
+
8
+ /** A stable reference; keep the reference, or capture its value for one operation only. */
9
+ export interface Volatile<T> {
10
+ /** @returns the current immutable snapshot, including undefined for an absent value. */
11
+ get(): VolatileSnapshot<T>
12
+ }
13
+
14
+ interface WritableVolatile extends Volatile<unknown> {
15
+ [write](value: unknown): void
16
+ }
17
+
18
+ function snapshot(value: unknown, ancestors = new Set<object>()): unknown {
19
+ if (typeof value === 'function') throw new TypeError('volatile config cannot contain functions')
20
+ if (value === null || typeof value !== 'object') return value
21
+ if (ancestors.has(value)) throw new TypeError('volatile config cannot contain cycles')
22
+ ancestors.add(value)
23
+ try {
24
+ if (Array.isArray(value)) return Object.freeze(value.map(item => snapshot(item, ancestors)))
25
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
26
+ throw new TypeError('volatile config objects must be plain objects or arrays')
27
+ }
28
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])))
29
+ } finally {
30
+ ancestors.delete(value)
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Create a detached reference containing an immutable copy of the supplied data.
36
+ * @param value - validated config data; class instances and functions are unsupported.
37
+ * @returns a reference whose value is updated only by its owning runtime.
38
+ */
39
+ export function createVolatile<T>(value: T): Volatile<T> {
40
+ let current = snapshot(value)
41
+ return Object.freeze({
42
+ get: () => current,
43
+ [write]: (value: unknown) => { current = value },
44
+ }) as Volatile<T>
45
+ }
46
+
47
+ /**
48
+ * Identify references across ESM/CJS copies of the shared library.
49
+ * @param value - a parsed config value.
50
+ * @returns whether the value implements the shared reference protocol.
51
+ */
52
+ export function isVolatile(value: unknown): value is Volatile<unknown> {
53
+ return typeof value === 'object' && value !== null && write in value
54
+ }
55
+
56
+ /**
57
+ * Collect config references without descending into their snapshots or opaque objects.
58
+ * @internal
59
+ * @param value - parsed config; cyclic ordinary fields are visited once per path.
60
+ * @returns references and their object-key paths, including an empty path for a root reference.
61
+ */
62
+ export function volatileEntries(value: unknown): { path: string[]; ref: Volatile<unknown> }[] {
63
+ const ancestors = new Set<object>()
64
+ function visit(value: unknown, path: string[]): { path: string[]; ref: Volatile<unknown> }[] {
65
+ if (isVolatile(value)) return [{ path, ref: value }]
66
+ if (!value || typeof value !== 'object' || ancestors.has(value)) return []
67
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return []
68
+ ancestors.add(value)
69
+ try {
70
+ return Object.entries(value).flatMap(([key, child]) => visit(child, [...path, key]))
71
+ } finally {
72
+ ancestors.delete(value)
73
+ }
74
+ }
75
+ return visit(value, [])
76
+ }
77
+
78
+ /**
79
+ * Commit an already validated immutable snapshot from another reference.
80
+ * @internal
81
+ * @param target - the owning plugin's stable reference.
82
+ * @param source - a newly parsed candidate reference.
83
+ */
84
+ export function updateVolatile(target: Volatile<unknown>, source: Volatile<unknown>): void {
85
+ ;(target as WritableVolatile)[write](source.get())
86
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021-present Shigma
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.