dsh-session-guard 4.2.5 → 4.2.6

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.
@@ -1,202 +1,202 @@
1
- /**
2
- * BridgeDocHandle — 设置卡双轨数据源的桥轨(M4/T20-b)。
3
- *
4
- * ≤0.1.5(settingsScope fiber 永不解 / 0.1.0-0.1.1 无 client 服务)时,
5
- * 配置卡经本句柄走自家 webServer 桥(describe/mutate)读写宿主 settings 服务。
6
- * 与原生 SettingsScope(scope-face.ts)同构:getSnapshot/subscribe/set/unset。
7
- * 读 = POST /api/<ns>/settings/describe;写 = POST …/mutate(ops 转发宿主服务),
8
- * 成功即用回填描述符刷新快照并通知订阅者(无本地第二份状态——权威值始终在宿主)。
9
- *
10
- * 与 perm-gate src/client/bridge-scope.ts(T13b/T20-b 泛化模板)的差异:
11
- * ① 快照形状对齐本仓 SettingsScope(status: loading/ready/unavailable + mode);
12
- * ② describe 未就绪(settings-unavailable/ns-not-registered)时有限重试
13
- * (宿主 settings 服务解析晚于卡挂载的窗口),重试耗尽才落 'unavailable'。
14
- */
15
-
16
- /** 与 server 侧 settingsBridgeRoutesFor(src/settings-bridge.js)必须逐字符一致。 */
17
- function settingsBridgeRoutesFor(ns: string): { describe: string; mutate: string } {
18
- return { describe: `/api/${ns}/settings/describe`, mutate: `/api/${ns}/settings/mutate` }
19
- }
20
-
21
- interface Snapshot<T> {
22
- status: 'loading' | 'ready' | 'unavailable'
23
- value: T | undefined
24
- revision: number | undefined
25
- writable: boolean
26
- base: unknown
27
- user: unknown
28
- mode: 'bridge'
29
- }
30
-
31
- interface Descriptor {
32
- value?: unknown
33
- revision?: number
34
- [k: string]: unknown
35
- }
36
-
37
- interface BridgeBody {
38
- ok?: boolean
39
- code?: string
40
- message?: string
41
- value?: { descriptor?: Descriptor; writable?: boolean }
42
- }
43
-
44
- interface MutateOp {
45
- op: 'set' | 'unset'
46
- path: string[]
47
- value?: unknown
48
- }
49
-
50
- /**
51
- * ≤0.1.5 宿主 describe 的 descriptor.value 是「每字段 → {}」骨架(0.1.0/0.1.5
52
- * 实测:value={enabled:{},…,officialProviders:{}},真值拆在 base(合并默认层)
53
- * 与 user(用户层))——直接吞 value 会让卡拿到 officialProviders={},
54
- * `?? []` 不兜底({} 非 nullish)→ ListRow values.join 崩,整族 tab 槽殉葬。
55
- * 判特征:对象且每个自有值都是空 plain 对象(guard 字段是标量/数组,不会全空)。
56
- * 命中即以 {...base, ...user} 重组有效值(guard 配置全是顶层标量/数组,浅合并即语义)。
57
- */
58
- function isFieldSkeleton(v: unknown): v is Record<string, Record<string, never>> {
59
- if (v === null || typeof v !== 'object' || Array.isArray(v)) return false
60
- const values = Object.values(v as Record<string, unknown>)
61
- return values.length > 0
62
- && values.every((x) => x !== null && typeof x === 'object' && !Array.isArray(x) && Object.keys(x as object).length === 0)
63
- }
64
-
65
- function plainObject(v: unknown): Record<string, unknown> {
66
- return v !== null && typeof v === 'object' && !Array.isArray(v) ? { ...(v as Record<string, unknown>) } : {}
67
- }
68
-
69
- /** descriptor → 卡面可用 plain 值:正常代际用 value;骨架代际用 base+user 浅合并。 */
70
- function descriptorPlainValue(d: Descriptor): unknown {
71
- if (!isFieldSkeleton(d.value)) return d.value
72
- return { ...plainObject(d.base), ...plainObject(d.user) }
73
- }
74
-
75
- /** describe 不可就绪码:宿主 settings 未解析/未注册——值得重试的瞬态。 */
76
- const RETRYABLE_CODES = new Set(['settings-unavailable', 'ns-not-registered'])
77
- const RETRY_DELAY_MS = 1500
78
- const RETRY_MAX = 4
79
-
80
- export class BridgeDocHandle<T> {
81
- private snapshot: Snapshot<T>
82
- private listeners = new Set<() => void>()
83
- private revision: number | undefined
84
- private retriesLeft = RETRY_MAX
85
- private inflight: Promise<void> | undefined
86
- private readonly ns: string
87
- private readonly routes: { describe: string; mutate: string }
88
-
89
- constructor(ns: string) {
90
- this.ns = ns
91
- this.routes = settingsBridgeRoutesFor(ns)
92
- this.snapshot = {
93
- status: 'loading',
94
- value: undefined,
95
- revision: undefined,
96
- writable: true,
97
- base: undefined,
98
- user: undefined,
99
- mode: 'bridge',
100
- }
101
- void this.refresh()
102
- }
103
-
104
- getSnapshot(): Snapshot<T> {
105
- return this.snapshot
106
- }
107
-
108
- subscribe(listener: () => void): () => void {
109
- this.listeners.add(listener)
110
- return () => {
111
- this.listeners.delete(listener)
112
- }
113
- }
114
-
115
- async set(field: string, value: unknown): Promise<boolean> {
116
- return this.mutate([{ op: 'set', path: [field], value }])
117
- }
118
-
119
- async unset(field: string): Promise<boolean> {
120
- return this.mutate([{ op: 'unset', path: [field] }])
121
- }
122
-
123
- private notify(): void {
124
- for (const l of [...this.listeners]) l()
125
- }
126
-
127
- private applyDescriptor(d: Descriptor, writable: boolean): void {
128
- this.revision = typeof d.revision === 'number' ? d.revision : undefined
129
- this.snapshot = {
130
- status: 'ready',
131
- value: descriptorPlainValue(d) as T | undefined,
132
- revision: this.revision,
133
- writable,
134
- base: undefined,
135
- user: undefined,
136
- mode: 'bridge',
137
- }
138
- }
139
-
140
- private async request(path: string, body?: unknown): Promise<BridgeBody> {
141
- const response = await fetch(path, {
142
- method: 'POST',
143
- headers: { 'content-type': 'application/json' },
144
- body: JSON.stringify(body ?? {}),
145
- })
146
- if (!response.ok) throw new Error(`bridge ${path} HTTP ${response.status}`)
147
- return (await response.json()) as BridgeBody
148
- }
149
-
150
- /** describe 拉取;瞬态未就绪码在重试预算内延迟重拉,耗尽才落 unavailable。 */
151
- refresh(): Promise<void> {
152
- if (this.inflight !== undefined) return this.inflight
153
- this.inflight = (async () => {
154
- try {
155
- const body = await this.request(this.routes.describe)
156
- if (body.ok && body.value?.descriptor !== undefined) {
157
- this.retriesLeft = RETRY_MAX
158
- this.applyDescriptor(body.value.descriptor, body.value.writable !== false)
159
- } else if (body.code !== undefined && RETRYABLE_CODES.has(body.code) && this.retriesLeft > 0) {
160
- this.retriesLeft -= 1
161
- this.inflight = undefined
162
- setTimeout(() => {
163
- void this.refresh()
164
- }, RETRY_DELAY_MS)
165
- return
166
- } else {
167
- this.snapshot = { ...this.snapshot, status: 'unavailable', writable: false }
168
- }
169
- } catch {
170
- // 网络异常:按瞬态处理,预算内重试
171
- if (this.retriesLeft > 0) {
172
- this.retriesLeft -= 1
173
- this.inflight = undefined
174
- setTimeout(() => {
175
- void this.refresh()
176
- }, RETRY_DELAY_MS)
177
- return
178
- }
179
- this.snapshot = { ...this.snapshot, status: 'unavailable', writable: false }
180
- }
181
- // 重试路径已在上面清过 inflight(setTimeout 后由 refresh() 重建);
182
- // 终态路径在此清挂起标记并广播。重试等待期 notify 无害(快照未变)。
183
- this.inflight = undefined
184
- this.notify()
185
- })()
186
- return this.inflight
187
- }
188
-
189
- private async mutate(ops: MutateOp[]): Promise<boolean> {
190
- const body = await this.request(this.routes.mutate, { ops, expectedRevision: this.revision })
191
- if (body.ok && body.value?.descriptor !== undefined) {
192
- this.applyDescriptor(body.value.descriptor, this.snapshot.writable)
193
- this.notify()
194
- return true
195
- }
196
- if (body.code === 'settings-conflict') {
197
- await this.refresh() // 乐观并发失败:拉权威值,让下次写入带新 revision
198
- return false
199
- }
200
- throw new Error(`bridge mutate failed: ${body.code ?? 'unknown'} ${body.message ?? ''}`)
201
- }
202
- }
1
+ /**
2
+ * BridgeDocHandle — 设置卡双轨数据源的桥轨(M4/T20-b)。
3
+ *
4
+ * ≤0.1.5(settingsScope fiber 永不解 / 0.1.0-0.1.1 无 client 服务)时,
5
+ * 配置卡经本句柄走自家 webServer 桥(describe/mutate)读写宿主 settings 服务。
6
+ * 与原生 SettingsScope(scope-face.ts)同构:getSnapshot/subscribe/set/unset。
7
+ * 读 = POST /api/<ns>/settings/describe;写 = POST …/mutate(ops 转发宿主服务),
8
+ * 成功即用回填描述符刷新快照并通知订阅者(无本地第二份状态——权威值始终在宿主)。
9
+ *
10
+ * 与 perm-gate src/client/bridge-scope.ts(T13b/T20-b 泛化模板)的差异:
11
+ * ① 快照形状对齐本仓 SettingsScope(status: loading/ready/unavailable + mode);
12
+ * ② describe 未就绪(settings-unavailable/ns-not-registered)时有限重试
13
+ * (宿主 settings 服务解析晚于卡挂载的窗口),重试耗尽才落 'unavailable'。
14
+ */
15
+
16
+ /** 与 server 侧 settingsBridgeRoutesFor(src/settings-bridge.js)必须逐字符一致。 */
17
+ function settingsBridgeRoutesFor(ns: string): { describe: string; mutate: string } {
18
+ return { describe: `/api/${ns}/settings/describe`, mutate: `/api/${ns}/settings/mutate` }
19
+ }
20
+
21
+ interface Snapshot<T> {
22
+ status: 'loading' | 'ready' | 'unavailable'
23
+ value: T | undefined
24
+ revision: number | undefined
25
+ writable: boolean
26
+ base: unknown
27
+ user: unknown
28
+ mode: 'bridge'
29
+ }
30
+
31
+ interface Descriptor {
32
+ value?: unknown
33
+ revision?: number
34
+ [k: string]: unknown
35
+ }
36
+
37
+ interface BridgeBody {
38
+ ok?: boolean
39
+ code?: string
40
+ message?: string
41
+ value?: { descriptor?: Descriptor; writable?: boolean }
42
+ }
43
+
44
+ interface MutateOp {
45
+ op: 'set' | 'unset'
46
+ path: string[]
47
+ value?: unknown
48
+ }
49
+
50
+ /**
51
+ * ≤0.1.5 宿主 describe 的 descriptor.value 是「每字段 → {}」骨架(0.1.0/0.1.5
52
+ * 实测:value={enabled:{},…,officialProviders:{}},真值拆在 base(合并默认层)
53
+ * 与 user(用户层))——直接吞 value 会让卡拿到 officialProviders={},
54
+ * `?? []` 不兜底({} 非 nullish)→ ListRow values.join 崩,整族 tab 槽殉葬。
55
+ * 判特征:对象且每个自有值都是空 plain 对象(guard 字段是标量/数组,不会全空)。
56
+ * 命中即以 {...base, ...user} 重组有效值(guard 配置全是顶层标量/数组,浅合并即语义)。
57
+ */
58
+ function isFieldSkeleton(v: unknown): v is Record<string, Record<string, never>> {
59
+ if (v === null || typeof v !== 'object' || Array.isArray(v)) return false
60
+ const values = Object.values(v as Record<string, unknown>)
61
+ return values.length > 0
62
+ && values.every((x) => x !== null && typeof x === 'object' && !Array.isArray(x) && Object.keys(x as object).length === 0)
63
+ }
64
+
65
+ function plainObject(v: unknown): Record<string, unknown> {
66
+ return v !== null && typeof v === 'object' && !Array.isArray(v) ? { ...(v as Record<string, unknown>) } : {}
67
+ }
68
+
69
+ /** descriptor → 卡面可用 plain 值:正常代际用 value;骨架代际用 base+user 浅合并。 */
70
+ function descriptorPlainValue(d: Descriptor): unknown {
71
+ if (!isFieldSkeleton(d.value)) return d.value
72
+ return { ...plainObject(d.base), ...plainObject(d.user) }
73
+ }
74
+
75
+ /** describe 不可就绪码:宿主 settings 未解析/未注册——值得重试的瞬态。 */
76
+ const RETRYABLE_CODES = new Set(['settings-unavailable', 'ns-not-registered'])
77
+ const RETRY_DELAY_MS = 1500
78
+ const RETRY_MAX = 4
79
+
80
+ export class BridgeDocHandle<T> {
81
+ private snapshot: Snapshot<T>
82
+ private listeners = new Set<() => void>()
83
+ private revision: number | undefined
84
+ private retriesLeft = RETRY_MAX
85
+ private inflight: Promise<void> | undefined
86
+ private readonly ns: string
87
+ private readonly routes: { describe: string; mutate: string }
88
+
89
+ constructor(ns: string) {
90
+ this.ns = ns
91
+ this.routes = settingsBridgeRoutesFor(ns)
92
+ this.snapshot = {
93
+ status: 'loading',
94
+ value: undefined,
95
+ revision: undefined,
96
+ writable: true,
97
+ base: undefined,
98
+ user: undefined,
99
+ mode: 'bridge',
100
+ }
101
+ void this.refresh()
102
+ }
103
+
104
+ getSnapshot(): Snapshot<T> {
105
+ return this.snapshot
106
+ }
107
+
108
+ subscribe(listener: () => void): () => void {
109
+ this.listeners.add(listener)
110
+ return () => {
111
+ this.listeners.delete(listener)
112
+ }
113
+ }
114
+
115
+ async set(field: string, value: unknown): Promise<boolean> {
116
+ return this.mutate([{ op: 'set', path: [field], value }])
117
+ }
118
+
119
+ async unset(field: string): Promise<boolean> {
120
+ return this.mutate([{ op: 'unset', path: [field] }])
121
+ }
122
+
123
+ private notify(): void {
124
+ for (const l of [...this.listeners]) l()
125
+ }
126
+
127
+ private applyDescriptor(d: Descriptor, writable: boolean): void {
128
+ this.revision = typeof d.revision === 'number' ? d.revision : undefined
129
+ this.snapshot = {
130
+ status: 'ready',
131
+ value: descriptorPlainValue(d) as T | undefined,
132
+ revision: this.revision,
133
+ writable,
134
+ base: undefined,
135
+ user: undefined,
136
+ mode: 'bridge',
137
+ }
138
+ }
139
+
140
+ private async request(path: string, body?: unknown): Promise<BridgeBody> {
141
+ const response = await fetch(path, {
142
+ method: 'POST',
143
+ headers: { 'content-type': 'application/json' },
144
+ body: JSON.stringify(body ?? {}),
145
+ })
146
+ if (!response.ok) throw new Error(`bridge ${path} HTTP ${response.status}`)
147
+ return (await response.json()) as BridgeBody
148
+ }
149
+
150
+ /** describe 拉取;瞬态未就绪码在重试预算内延迟重拉,耗尽才落 unavailable。 */
151
+ refresh(): Promise<void> {
152
+ if (this.inflight !== undefined) return this.inflight
153
+ this.inflight = (async () => {
154
+ try {
155
+ const body = await this.request(this.routes.describe)
156
+ if (body.ok && body.value?.descriptor !== undefined) {
157
+ this.retriesLeft = RETRY_MAX
158
+ this.applyDescriptor(body.value.descriptor, body.value.writable !== false)
159
+ } else if (body.code !== undefined && RETRYABLE_CODES.has(body.code) && this.retriesLeft > 0) {
160
+ this.retriesLeft -= 1
161
+ this.inflight = undefined
162
+ setTimeout(() => {
163
+ void this.refresh()
164
+ }, RETRY_DELAY_MS)
165
+ return
166
+ } else {
167
+ this.snapshot = { ...this.snapshot, status: 'unavailable', writable: false }
168
+ }
169
+ } catch {
170
+ // 网络异常:按瞬态处理,预算内重试
171
+ if (this.retriesLeft > 0) {
172
+ this.retriesLeft -= 1
173
+ this.inflight = undefined
174
+ setTimeout(() => {
175
+ void this.refresh()
176
+ }, RETRY_DELAY_MS)
177
+ return
178
+ }
179
+ this.snapshot = { ...this.snapshot, status: 'unavailable', writable: false }
180
+ }
181
+ // 重试路径已在上面清过 inflight(setTimeout 后由 refresh() 重建);
182
+ // 终态路径在此清挂起标记并广播。重试等待期 notify 无害(快照未变)。
183
+ this.inflight = undefined
184
+ this.notify()
185
+ })()
186
+ return this.inflight
187
+ }
188
+
189
+ private async mutate(ops: MutateOp[]): Promise<boolean> {
190
+ const body = await this.request(this.routes.mutate, { ops, expectedRevision: this.revision })
191
+ if (body.ok && body.value?.descriptor !== undefined) {
192
+ this.applyDescriptor(body.value.descriptor, this.snapshot.writable)
193
+ this.notify()
194
+ return true
195
+ }
196
+ if (body.code === 'settings-conflict') {
197
+ await this.refresh() // 乐观并发失败:拉权威值,让下次写入带新 revision
198
+ return false
199
+ }
200
+ throw new Error(`bridge mutate failed: ${body.code ?? 'unknown'} ${body.message ?? ''}`)
201
+ }
202
+ }