@linxin666/dsh-remote-bridge 0.4.8 → 0.4.10

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 (72) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +75 -18
  3. package/README.zh.md +74 -18
  4. package/lib/client.js +783 -260
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +15849 -2913
  7. package/lib/types/client/PairEntry.d.ts +2 -2
  8. package/lib/types/client/PairPanel.d.ts +10 -2
  9. package/lib/types/client/UiPresentRow.d.ts +13 -0
  10. package/lib/types/client/icons.d.ts +5 -13
  11. package/lib/types/client/index.d.ts +4 -0
  12. package/lib/types/client/locales.d.ts +24 -15
  13. package/lib/types/client/semantic.d.ts +9 -5
  14. package/lib/types/client/toolview-slot.d.ts +68 -0
  15. package/lib/types/client/ui-card.d.ts +160 -0
  16. package/lib/types/core/commands.d.ts +59 -0
  17. package/lib/types/core/connection.d.ts +106 -0
  18. package/lib/types/core/devices.d.ts +102 -2
  19. package/lib/types/core/extension.d.ts +13 -0
  20. package/lib/types/core/hub.d.ts +129 -15
  21. package/lib/types/core/liveactivity.d.ts +324 -0
  22. package/lib/types/core/protocol.d.ts +328 -5
  23. package/lib/types/core/push.d.ts +186 -0
  24. package/lib/types/core/questions.d.ts +61 -9
  25. package/lib/types/core/session-meta.d.ts +55 -1
  26. package/lib/types/core/squads.d.ts +130 -0
  27. package/lib/types/core/turn-end-quiet.d.ts +135 -0
  28. package/lib/types/core/ui.d.ts +238 -0
  29. package/lib/types/core/usage-stats.d.ts +160 -0
  30. package/lib/types/core/usage.d.ts +294 -0
  31. package/lib/types/host/apns.d.ts +151 -0
  32. package/lib/types/host/squads-ledger.d.ts +39 -0
  33. package/lib/types/host/squads.d.ts +77 -0
  34. package/lib/types/host/ui-tools.d.ts +80 -0
  35. package/lib/types/host/usage-stats.d.ts +75 -0
  36. package/lib/types/host/watchers.d.ts +95 -0
  37. package/lib/types/index.d.ts +47 -3
  38. package/package.json +15 -14
  39. package/src/client/PairEntry.tsx +58 -31
  40. package/src/client/PairPanel.tsx +181 -97
  41. package/src/client/UiPresentRow.tsx +149 -0
  42. package/src/client/icons.tsx +17 -60
  43. package/src/client/index.ts +11 -0
  44. package/src/client/locales.ts +36 -24
  45. package/src/client/panel.module.css +239 -186
  46. package/src/client/semantic.ts +10 -6
  47. package/src/client/toolview-slot.ts +84 -0
  48. package/src/client/ui-card.ts +368 -0
  49. package/src/client/ui-present.module.css +87 -0
  50. package/src/core/commands.ts +95 -0
  51. package/src/core/connection.ts +811 -12
  52. package/src/core/devices.ts +337 -5
  53. package/src/core/extension.ts +20 -0
  54. package/src/core/hub.ts +518 -43
  55. package/src/core/liveactivity.ts +833 -0
  56. package/src/core/protocol.ts +370 -5
  57. package/src/core/push.ts +385 -0
  58. package/src/core/questions.ts +81 -10
  59. package/src/core/session-meta.ts +73 -1
  60. package/src/core/squads.ts +345 -0
  61. package/src/core/turn-end-quiet.ts +388 -0
  62. package/src/core/ui.ts +398 -0
  63. package/src/core/usage-stats.ts +424 -0
  64. package/src/core/usage.ts +937 -0
  65. package/src/core/wire.ts +8 -0
  66. package/src/host/apns.ts +320 -0
  67. package/src/host/squads-ledger.ts +105 -0
  68. package/src/host/squads.ts +206 -0
  69. package/src/host/ui-tools.ts +233 -0
  70. package/src/host/usage-stats.ts +155 -0
  71. package/src/host/watchers.ts +296 -0
  72. package/src/index.ts +327 -10
@@ -0,0 +1,424 @@
1
+ /**
2
+ * `usage.stats` 的应答:宿主自己那份按天记的 token 台账的聚合。
3
+ *
4
+ * 这一半与 `usage.ts` 的两半有一个根本区别:那两半读的是本进程自己的事实,这一半
5
+ * 读的是另一个插件(`dsh-usage`)挂在这个宿主上的 HTTP 路由。所以它的缺席方式也
6
+ * 不同——宿主根本没挂那个插件是一件关于这台 Mac 的事实(`no-usage-plugin`),
7
+ * 不是错误;而路由取不到、形状不符、超时才是 `probe-failed`。
8
+ *
9
+ * 两条铁律贯穿本模块:
10
+ *
11
+ * - 永不编 0。五个桶在一行里恒在,但那说的是「这一行读到过」:一次没读到的聚合
12
+ * 回 `probe-failed` 并带上短原因,绝不拿上一轮的值冒充这一轮。日历上某一天宿主
13
+ * 台账里没有条目,是那一天确实没有用量——宿主自己的 `/day` 路由对这种日子答的
14
+ * 也是全 0,所以按 0 收是转述,不是编造。
15
+ * - 宿主侧 30 秒一次。同一份聚合数据在一个窗口内最多读一次,并发调用合并成一次:
16
+ * 台账是这台 Mac 的事实,一部手机重复问不该让宿主多读一遍。
17
+ *
18
+ * 读的是两条路由(都在那个插件的 `/api/dsh-usage` 前缀下):`GET /overview` 一次
19
+ * 给出今天、最近 30 个有记录的日子的台账、以及观测花费;`GET /day?date=YYYY-MM-DD`
20
+ * 补一天。所以一次聚合是 1 + K 次本机回环读,K 只在请求的窗口比 `/overview` 自带的
21
+ * 那一截更深、或本月台账被那一截截断时才不为 0。
22
+ * @module dsh-remote-bridge/core/usage-stats
23
+ */
24
+
25
+ import { failureText } from './gateway-errors.ts'
26
+
27
+ /** 省略 `days` 时回多少天。 */
28
+ export const STATS_DAYS_DEFAULT = 14
29
+
30
+ /** 一次最多回多少天:再往上按这个数收。 */
31
+ export const STATS_DAYS_MAX = 60
32
+
33
+ /** 同一份聚合数据在这个窗口内最多读一次(本桥这一侧)。 */
34
+ export const STATS_CACHE_TTL_MS = 30_000
35
+
36
+ /** 最多记住几个不同窗口的聚合;一次开屏通常只问一个。 */
37
+ export const STATS_CACHE_LIMIT = 8
38
+
39
+ /** 一天有多少毫秒;日期加减一律走 UTC,免得夏令时把一天算成 23 或 25 小时。 */
40
+ const DAY_MS = 86_400_000
41
+
42
+ /** 一次读数里的一行:五个互不重叠的 token 桶,未用即真实的 0。 */
43
+ export interface UsageBuckets {
44
+ /** 未命中缓存的输入 token。 */
45
+ readonly input: number
46
+ /** 输出 token(含推理)。 */
47
+ readonly output: number
48
+ /** 命中缓存的输入 token。 */
49
+ readonly cacheRead: number
50
+ /** 写入缓存的 token。 */
51
+ readonly cacheWrite: number
52
+ /** 推理 token,provider 报过才有。 */
53
+ readonly reasoning: number
54
+ }
55
+
56
+ /** 按天的一行:日期键 `YYYY-MM-DD` 加上五个桶。 */
57
+ export interface UsageDayBucket extends UsageBuckets {
58
+ /** 本地日期键 `YYYY-MM-DD`。 */
59
+ readonly day: string
60
+ }
61
+
62
+ /** 观测到的真实花费:官方账户余额的下降累计,CNY 口径。 */
63
+ export interface UsageObservedSpend {
64
+ /** 累计花费,元。 */
65
+ readonly cny: number
66
+ /** 这次累计起点的那次余额观测时刻(epoch ms)。 */
67
+ readonly since: number
68
+ }
69
+
70
+ /** `usage.stats` 读得到时回的那一份。 */
71
+ export interface UsageStatsView {
72
+ /** 宿主拼这份聚合的时刻(epoch ms),不是本桥答话的时刻。 */
73
+ readonly updatedAt: number
74
+ /** 宿主本地的今天。 */
75
+ readonly today: UsageBuckets
76
+ /** 宿主本地的本月,从 1 号到今天的累计。 */
77
+ readonly month: UsageBuckets
78
+ /** 请求的窗口内按日期升序的一天一行,最多 `days` 条。 */
79
+ readonly days: UsageDayBucket[]
80
+ /** 宿主有观测花费时才有这个键。 */
81
+ readonly observedSpend?: UsageObservedSpend
82
+ }
83
+
84
+ /** 读不到时回的那一份:为什么读不到,不是错误码。 */
85
+ export interface UsageStatsUnsupported {
86
+ /**
87
+ * `no-usage-plugin` —— 这台宿主没挂 `dsh-usage`(关于这台 Mac 的事实);
88
+ * `probe-failed` —— 路由取不到、形状不符或超时。
89
+ */
90
+ readonly unsupported: 'no-usage-plugin' | 'probe-failed'
91
+ /** 短原因,只给 `probe-failed`。 */
92
+ readonly reason?: string
93
+ }
94
+
95
+ /** `usage.stats` 的应答体。 */
96
+ export type UsageStatsAnswer = UsageStatsView | UsageStatsUnsupported
97
+
98
+ /**
99
+ * 一次宿主路由读数的结果。
100
+ *
101
+ * `missing` 单独一格,是因为「路由不存在」与「路由答了错」在协议里是两个答案:
102
+ * 前者说明那台宿主没挂插件,后者说明这次没读到。
103
+ */
104
+ export type UsageStatsOutcome =
105
+ | { readonly kind: 'answer'; readonly body: unknown }
106
+ | { readonly kind: 'missing' }
107
+ | { readonly kind: 'failed'; readonly reason: string }
108
+
109
+ /** 宿主那两条路由,按本模块需要的那一格给出来。 */
110
+ export interface UsageStatsTransport {
111
+ /** `GET /api/dsh-usage/overview`。 */
112
+ overview(): Promise<UsageStatsOutcome>
113
+ /**
114
+ * `GET /api/dsh-usage/day?date=<day>`。
115
+ * @param day - 本地日期键 `YYYY-MM-DD`。
116
+ */
117
+ day(day: string): Promise<UsageStatsOutcome>
118
+ }
119
+
120
+ /** 构造 {@link UsageStatsReader} 的全部输入。 */
121
+ export interface UsageStatsReaderOptions {
122
+ /** 每次读数都重新解析一次;晚挂载的宿主路由因此也能被读到。 */
123
+ readonly transport: () => UsageStatsTransport | undefined
124
+ /** 缓存窗口读的时钟。 */
125
+ readonly now: () => number
126
+ /** 读不到时的落点。 */
127
+ readonly log: (message: string) => void
128
+ /** 缓存窗口;默认 {@link STATS_CACHE_TTL_MS}。 */
129
+ readonly ttlMs?: number
130
+ }
131
+
132
+ /** 一次聚合里本模块用到的几格,读过形状之后。 */
133
+ interface OverviewFacts {
134
+ readonly updatedAt: number
135
+ readonly todayKey: string
136
+ readonly today: UsageBuckets
137
+ readonly rows: Map<string, UsageBuckets>
138
+ readonly availableDays: readonly string[]
139
+ readonly observedSpend?: UsageObservedSpend
140
+ }
141
+
142
+ /**
143
+ * `usage.stats` 背后的读服务,一个宿主一份、所有连接共享。
144
+ *
145
+ * 缓存与合并都按窗口值分开放:两个客户端问 14 天和问 30 天是两份不同的聚合,但
146
+ * 它们各自的窗口内都不会让宿主多读一遍。
147
+ */
148
+ export class UsageStatsReader {
149
+ readonly #options: UsageStatsReaderOptions
150
+ readonly #cache = new Map<number, { readonly at: number; readonly answer: UsageStatsAnswer }>()
151
+ readonly #inFlight = new Map<number, Promise<UsageStatsAnswer>>()
152
+
153
+ /**
154
+ * @param options - 宿主路由的解析函数、时钟与日志。
155
+ */
156
+ constructor(options: UsageStatsReaderOptions) {
157
+ this.#options = options
158
+ }
159
+
160
+ /**
161
+ * 一个窗口的用量聚合。
162
+ *
163
+ * 窗口值先收进 `[1, 60]`:省下的天数与超出的天数都不是客户端能定的,而「问 1000
164
+ * 天」不该让本桥去翻 1000 个日历。
165
+ * @param days - 要多少天。
166
+ * @returns 读到的那一份,或者为什么读不到。
167
+ */
168
+ async stats(days: number): Promise<UsageStatsAnswer> {
169
+ const window = clampStatsDays(days)
170
+ const cached = this.#cache.get(window)
171
+ if (cached !== undefined && this.#options.now() - cached.at < this.#ttl()) return cached.answer
172
+ const running = this.#inFlight.get(window)
173
+ if (running !== undefined) return await running
174
+ const settle = (answer: UsageStatsAnswer): UsageStatsAnswer => {
175
+ this.#remember(window, answer)
176
+ this.#inFlight.delete(window)
177
+ return answer
178
+ }
179
+ const read = this.#read(window)
180
+ .then(settle, (error: unknown) => settle({ unsupported: 'probe-failed', reason: failureText(error) }))
181
+ this.#inFlight.set(window, read)
182
+ return await read
183
+ }
184
+
185
+ /**
186
+ * 读一次聚合。
187
+ *
188
+ * 先一条 `/overview`:它一次给出今天、最近 30 个有记录的日子的台账与观测花费。
189
+ * 请求的窗口比那一截更深、或者本月的台账被那一截截断(30 天里挤了 31 个日子只
190
+ * 可能发生在某月的最后一天)时,才按 `availableDays` 补读缺的那几天——只有确实
191
+ * 有记录的日子才补,剩下的日历日子按真实的 0 收。
192
+ * @param window - 已经收进合法区间的天数。
193
+ * @returns 读到的那一份,或者为什么读不到。
194
+ */
195
+ async #read(window: number): Promise<UsageStatsAnswer> {
196
+ const transport = this.#transport()
197
+ if (transport === undefined) return { unsupported: 'probe-failed', reason: 'no host usage route' }
198
+ const overview = await transport.overview()
199
+ if (overview.kind === 'missing') return { unsupported: 'no-usage-plugin' }
200
+ if (overview.kind === 'failed') return { unsupported: 'probe-failed', reason: overview.reason }
201
+ const facts = overviewFactsOf(overview.body)
202
+ if (facts === undefined) return { unsupported: 'probe-failed', reason: 'unrecognized overview shape' }
203
+ const filled = await this.#fill(transport, facts, window)
204
+ if (typeof filled === 'string') return { unsupported: 'probe-failed', reason: filled }
205
+ return {
206
+ updatedAt: facts.updatedAt,
207
+ today: facts.today,
208
+ month: monthBucketsOf(filled, facts.todayKey),
209
+ days: windowDaysOf(filled, facts.todayKey, window),
210
+ ...(facts.observedSpend === undefined ? {} : { observedSpend: facts.observedSpend }),
211
+ }
212
+ }
213
+
214
+ /**
215
+ * 把请求的窗口与本月还缺的有记录日子从 `/day` 补上。
216
+ *
217
+ * 补的只有两处交集:确实有记录(`availableDays` 里点过名)、且落在这次要看的
218
+ * 两段日期里(请求的窗口,或本月)。两段都短的缘故,K 有上界:窗口内至多比那一截
219
+ * 多出 `window - 30` 天,本月至多 31 天。一天都补不到是常态。
220
+ * @param transport - 宿主路由。
221
+ * @param facts - 已经读过形状的 `/overview`。
222
+ * @param window - 请求的天数。
223
+ * @returns 补齐后的行,或者一句短原因(补齐失败就不答这份聚合)。
224
+ */
225
+ async #fill(transport: UsageStatsTransport, facts: OverviewFacts, window: number): Promise<Map<string, UsageBuckets> | string> {
226
+ const rows = new Map(facts.rows)
227
+ const oldest = shiftDay(facts.todayKey, -(window - 1))
228
+ const month = facts.todayKey.slice(0, 7)
229
+ const wanted = facts.availableDays.filter(day => !rows.has(day)
230
+ && ((day >= oldest && day <= facts.todayKey) || day.startsWith(month)))
231
+ if (wanted.length === 0) return rows
232
+ const answers = await Promise.all(wanted.map(async day => ({ day, outcome: await transport.day(day) })))
233
+ for (const { day, outcome } of answers) {
234
+ if (outcome.kind === 'failed') return outcome.reason
235
+ if (outcome.kind === 'missing') return `the day route is missing ${day}`
236
+ const buckets = dayBucketsOf(outcome.body)
237
+ if (buckets === undefined) return `unrecognized day shape for ${day}`
238
+ rows.set(day, buckets)
239
+ }
240
+ return rows
241
+ }
242
+
243
+ /** 宿主路由的一次解析;解析本身抛错按「没有路由」处理。 */
244
+ #transport(): UsageStatsTransport | undefined {
245
+ try {
246
+ return this.#options.transport()
247
+ } catch (error) {
248
+ this.#options.log(`the host usage routes could not be resolved: ${failureText(error)}`)
249
+ return undefined
250
+ }
251
+ }
252
+
253
+ /** 记一份聚合(读到与没读到都记)并维持容量上界。 */
254
+ #remember(window: number, answer: UsageStatsAnswer): void {
255
+ this.#cache.delete(window)
256
+ this.#cache.set(window, { at: this.#options.now(), answer })
257
+ while (this.#cache.size > STATS_CACHE_LIMIT) {
258
+ const oldest = this.#cache.keys().next()
259
+ if (oldest.done === true) return
260
+ this.#cache.delete(oldest.value)
261
+ }
262
+ }
263
+
264
+ /** 缓存窗口。 */
265
+ #ttl(): number {
266
+ return this.#options.ttlMs ?? STATS_CACHE_TTL_MS
267
+ }
268
+ }
269
+
270
+ /**
271
+ * 把客户端给的天数收成合法的窗口。
272
+ * @param days - 客户端给的天数。
273
+ * @returns 一个 `[1, 60]` 间的整数;不是有限数时回默认的 14 天。
274
+ */
275
+ export function clampStatsDays(days: number): number {
276
+ if (!Number.isFinite(days)) return STATS_DAYS_DEFAULT
277
+ return Math.min(STATS_DAYS_MAX, Math.max(1, Math.floor(days)))
278
+ }
279
+
280
+ /** 五个桶全 0:一天没用量时的真实读数。 */
281
+ function emptyBuckets(): UsageBuckets {
282
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 }
283
+ }
284
+
285
+ /** 两个桶相加。 */
286
+ function addBuckets(left: UsageBuckets, right: UsageBuckets): UsageBuckets {
287
+ return {
288
+ input: left.input + right.input,
289
+ output: left.output + right.output,
290
+ cacheRead: left.cacheRead + right.cacheRead,
291
+ cacheWrite: left.cacheWrite + right.cacheWrite,
292
+ reasoning: left.reasoning + right.reasoning,
293
+ }
294
+ }
295
+
296
+ /**
297
+ * 宿主台账的一格折成五个桶。
298
+ *
299
+ * 五个数缺一个就整行不认:只读到输入、把没读到的推理编成 0,等于把「不知道」说成
300
+ * 「没有」。
301
+ * @param value - 宿主 `UsageTokenTotals` 的一格。
302
+ * @returns 五个桶,形状不符时 undefined。
303
+ */
304
+ function bucketsOfTotals(value: unknown): UsageBuckets | undefined {
305
+ if (!isRecord(value)) return undefined
306
+ const input = countOf(value.inputTokens)
307
+ const output = countOf(value.outputTokens)
308
+ const cacheRead = countOf(value.cacheReadTokens)
309
+ const cacheWrite = countOf(value.cacheWriteTokens)
310
+ const reasoning = countOf(value.reasoningTokens)
311
+ if (input === undefined || output === undefined || cacheRead === undefined || cacheWrite === undefined || reasoning === undefined) return undefined
312
+ return { input, output, cacheRead, cacheWrite, reasoning }
313
+ }
314
+
315
+ /** 一天的一行:`/day` 把它包在 `{ok:true, day:{...}}` 里。 */
316
+ function dayBucketsOf(body: unknown): UsageBuckets | undefined {
317
+ if (!isRecord(body)) return undefined
318
+ return bucketsOfTotals(isRecord(body.day) ? body.day.totals : undefined)
319
+ }
320
+
321
+ /** 一个非负的有限数;宿主把 token 数写成整数。 */
322
+ function countOf(value: unknown): number | undefined {
323
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined
324
+ }
325
+
326
+ /** `/overview` 里本模块要的一格;形状不符时 undefined。 */
327
+ function overviewFactsOf(body: unknown): OverviewFacts | undefined {
328
+ if (!isRecord(body)) return undefined
329
+ const updatedAt = countOf(body.updatedAt)
330
+ const usage = isRecord(body.usage) ? body.usage : undefined
331
+ if (updatedAt === undefined || usage === undefined) return undefined
332
+ const today = isRecord(usage.today) ? usage.today : undefined
333
+ const todayKey = typeof today?.date === 'string' ? today.date : undefined
334
+ const todayBuckets = bucketsOfTotals(today?.totals)
335
+ if (todayKey === undefined || !isDayKey(todayKey) || todayBuckets === undefined) return undefined
336
+ const rows = new Map<string, UsageBuckets>()
337
+ const listed = usage.days
338
+ if (!Array.isArray(listed)) return undefined
339
+ for (const row of listed) {
340
+ if (!isRecord(row) || typeof row.date !== 'string' || !isDayKey(row.date)) return undefined
341
+ const buckets = bucketsOfTotals(row.totals)
342
+ if (buckets === undefined) return undefined
343
+ rows.set(row.date, buckets)
344
+ }
345
+ const availableDays: string[] = []
346
+ if (Array.isArray(usage.availableDays)) {
347
+ for (const day of usage.availableDays) if (typeof day === 'string' && isDayKey(day)) availableDays.push(day)
348
+ }
349
+ const spend = isRecord(usage.observedSpend) ? usage.observedSpend : undefined
350
+ const cny = countOf(spend?.cny)
351
+ const since = countOf(spend?.since)
352
+ const observedSpend = cny === undefined || since === undefined ? undefined : { cny, since }
353
+ return {
354
+ updatedAt,
355
+ todayKey,
356
+ today: todayBuckets,
357
+ rows,
358
+ availableDays,
359
+ ...(observedSpend === undefined ? {} : { observedSpend }),
360
+ }
361
+ }
362
+
363
+ /** 窗口内按日期升序的一天一行;台账里没有的日子是真实的 0。 */
364
+ function windowDaysOf(rows: Map<string, UsageBuckets>, todayKey: string, window: number): UsageDayBucket[] {
365
+ const oldest = shiftDay(todayKey, -(window - 1))
366
+ const days: UsageDayBucket[] = []
367
+ for (let index = 0; index < window; index += 1) {
368
+ const day = shiftDay(oldest, index)
369
+ days.push({ day, ...(rows.get(day) ?? emptyBuckets()) })
370
+ }
371
+ return days
372
+ }
373
+
374
+ /** 本月的累计:只有本月的行,其余日子是真 0。 */
375
+ function monthBucketsOf(rows: Map<string, UsageBuckets>, todayKey: string): UsageBuckets {
376
+ const month = todayKey.slice(0, 7)
377
+ let total = emptyBuckets()
378
+ for (const [day, buckets] of rows) if (day.startsWith(month)) total = addBuckets(total, buckets)
379
+ return total
380
+ }
381
+
382
+ /**
383
+ * 一个日期键加减天数。
384
+ *
385
+ * 走 UTC 是为了不让夏令时把「加一天」算成 23 或 25 小时:这里加的是日历天。
386
+ * @param day - 日期键 `YYYY-MM-DD`。
387
+ * @param delta - 加减多少天,负数向前。
388
+ * @returns 新的日期键。
389
+ */
390
+ export function shiftDay(day: string, delta: number): string {
391
+ const number = dayNumberOf(day)
392
+ if (number === undefined) return day
393
+ const shifted = new Date(number + delta * DAY_MS)
394
+ const year = shifted.getUTCFullYear()
395
+ const month = `${shifted.getUTCMonth() + 1}`.padStart(2, '0')
396
+ const date = `${shifted.getUTCDate()}`.padStart(2, '0')
397
+ return `${year}-${month}-${date}`
398
+ }
399
+
400
+ /**
401
+ * `YYYY-MM-DD` 是不是一个真实存在的日子。
402
+ * @param value - 待判定的文本。
403
+ * @returns 格式对且日子存在时为 true。
404
+ */
405
+ export function isDayKey(value: string): boolean {
406
+ return dayNumberOf(value) !== undefined
407
+ }
408
+
409
+ /** 日期键折成 UTC 的日序号;格式不对或日子不存在时 undefined。 */
410
+ function dayNumberOf(value: string): number | undefined {
411
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return undefined
412
+ const year = Number(value.slice(0, 4))
413
+ const month = Number(value.slice(5, 7))
414
+ const date = Number(value.slice(8, 10))
415
+ const ms = Date.UTC(year, month - 1, date)
416
+ const parsed = new Date(ms)
417
+ if (parsed.getUTCFullYear() !== year || parsed.getUTCMonth() !== month - 1 || parsed.getUTCDate() !== date) return undefined
418
+ return ms
419
+ }
420
+
421
+ /** 一个可按下标读取的普通对象。 */
422
+ function isRecord(value: unknown): value is Record<string, unknown> {
423
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
424
+ }