dsh-token-receipt 1.0.0 → 1.1.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.
package/index.js CHANGED
@@ -11,8 +11,22 @@ import { createPricingCatalog, createPricingAccumulator } from './pricing.js'
11
11
 
12
12
  const ROUTE = '/api/token-receipt'
13
13
  const DAY_MS = 24 * 60 * 60 * 1000
14
+ const MAX_TS = 8_640_000_000_000_000
14
15
  const CACHE_TTL_MS = 10_000
15
16
  const RECENT_DAYS = 3
17
+ const VALID_PERIODS = new Set(['day', 'week', 'month', 'days30', 'days90', 'all'])
18
+ const PERIOD_CODES = new Map([
19
+ ['day', 'D'],
20
+ ['week', 'W'],
21
+ ['month', 'M'],
22
+ ['days30', '30D'],
23
+ ['days90', '90D'],
24
+ ['all', 'ALL'],
25
+ ])
26
+ const PERIOD_LOOKBACK_DAYS = new Map([
27
+ ['days30', 29],
28
+ ['days90', 89],
29
+ ])
16
30
 
17
31
  export const name = 'token-receipt'
18
32
  export const inject = ['webServer']
@@ -28,9 +42,44 @@ function sendJson(res, status, body, headOnly = false) {
28
42
  res.end(payload)
29
43
  }
30
44
 
45
+ function nextLocalDay(timestamp) {
46
+ const d = new Date(timestamp)
47
+ d.setDate(d.getDate() + 1)
48
+ return d.getTime()
49
+ }
50
+
31
51
  function localDayBounds(now = new Date()) {
32
- const start = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
33
- return { from: start, to: start + DAY_MS }
52
+ const from = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
53
+ const to = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).getTime()
54
+ return { from, to }
55
+ }
56
+
57
+ /** Compute default [from, to) local-time bounds for a validated receipt period. */
58
+ function defaultPeriodBounds(period, nowDate) {
59
+ const dayBounds = localDayBounds(nowDate)
60
+ const lookback = PERIOD_LOOKBACK_DAYS.get(period)
61
+ if (lookback !== undefined) {
62
+ return {
63
+ from: new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() - lookback).getTime(),
64
+ to: dayBounds.to,
65
+ }
66
+ }
67
+ if (period === 'all') return { from: 1, to: dayBounds.to }
68
+ return dayBounds
69
+ }
70
+
71
+ /** Resolve the fallback YYYY-MM-DD label using the inclusive end date for rolling/all-time windows. */
72
+ function defaultDateLabel(period, from, to) {
73
+ if (period === 'days30' || period === 'days90' || period === 'all') {
74
+ return compactDate(to - 1)
75
+ }
76
+ return compactDate(from)
77
+ }
78
+
79
+ function parseTs(raw) {
80
+ if (raw === null || raw.trim() === '') return NaN
81
+ const ts = Number(raw)
82
+ return Number.isFinite(ts) && ts > 0 && ts <= MAX_TS ? ts : NaN
34
83
  }
35
84
 
36
85
  function compactDate(timestamp) {
@@ -57,8 +106,11 @@ function hashSuffix(input) {
57
106
  function messageText(message) {
58
107
  const content = message && Array.isArray(message.content) ? message.content : []
59
108
  for (const block of content) {
60
- if (block && block.type === 'text' && typeof block.text === 'string' && block.text.trim() !== '') {
61
- return block.text.trim().replace(/\s+/g, ' ')
109
+ if (block && block.type === 'text' && typeof block.text === 'string') {
110
+ const trimmed = block.text.trim()
111
+ if (trimmed !== '' && !trimmed.startsWith('<')) {
112
+ return trimmed.replace(/\s+/g, ' ')
113
+ }
62
114
  }
63
115
  }
64
116
  return ''
@@ -66,7 +118,8 @@ function messageText(message) {
66
118
 
67
119
  function shortTitle(text) {
68
120
  if (!text) return 'Untitled session'
69
- return text.length > 46 ? `${text.slice(0, 45)}…` : text
121
+ const chars = Array.from(text)
122
+ return chars.length > 46 ? `${chars.slice(0, 45).join('')}…` : text
70
123
  }
71
124
 
72
125
  async function mapLimit(items, limit, worker) {
@@ -98,14 +151,14 @@ async function loadSessionUsage(query, record) {
98
151
  return null
99
152
  }
100
153
  if (!snapshot || !Array.isArray(snapshot.events)) return null
101
- const inherited = Number(snapshot.inheritedEventCount) || 0
154
+ const inherited = finite(snapshot.inheritedEventCount)
102
155
  let title = ''
103
156
 
104
157
  for (const candidate of snapshot.events) {
105
158
  if (candidate && candidate.type === 'user/message') {
106
159
  const body = candidate.data && candidate.data.message ? candidate.data.message : candidate.data
107
160
  const text = messageText(body)
108
- if (text !== '' && !text.startsWith('<')) {
161
+ if (text !== '') {
109
162
  title = text
110
163
  break
111
164
  }
@@ -115,8 +168,8 @@ async function loadSessionUsage(query, record) {
115
168
  const messages = []
116
169
  for (const event of snapshot.events) {
117
170
  if (!event || event.type !== 'assistant/message') continue
118
- if (typeof event.seq === 'number' && event.seq < inherited) continue
119
- if (typeof event.time !== 'number') continue
171
+ if (Number.isFinite(event.seq) && event.seq < inherited) continue
172
+ if (!Number.isFinite(event.time)) continue
120
173
  const usage = event.data && event.data.usage
121
174
  if (!usage) continue
122
175
  const message = event.data.message || {}
@@ -148,9 +201,14 @@ async function cachedSessionUsage(query, record, revision, sessionUsageCache) {
148
201
  const id = record.header.id
149
202
  const hit = sessionUsageCache.get(id)
150
203
  const key = revision == null ? null : String(revision)
151
- if (hit && key !== null && hit.revision === key) return hit.value
204
+ if (hit && key !== null && hit.revision === key) {
205
+ sessionUsageCache.delete(id)
206
+ sessionUsageCache.set(id, hit)
207
+ return hit.value
208
+ }
152
209
  const value = await loadSessionUsage(query, record)
153
210
  if (key !== null) {
211
+ sessionUsageCache.delete(id)
154
212
  sessionUsageCache.set(id, { revision: key, value })
155
213
  if (sessionUsageCache.size > 512) {
156
214
  const oldest = sessionUsageCache.keys().next().value
@@ -165,14 +223,20 @@ async function cachedSessionUsage(query, record, revision, sessionUsageCache) {
165
223
  * long ago can still be used today, so recency uses the persisted log's
166
224
  * modification time and the live-session set rather than creation time alone.
167
225
  */
168
- async function candidateRecords(ctx, query, from, to) {
169
- const records = await query.listSessions()
226
+ async function candidateRecords(ctx, query, from, to, sessionUsageCache) {
227
+ const rawRecords = await query.listSessions()
228
+ const records = Array.isArray(rawRecords) ? rawRecords : []
170
229
  const persistence = ctx.get('sessionPersistence')
171
230
  const live = ctx.get('sessions')
172
231
  const liveIds = new Set()
173
232
  if (live && typeof live.list === 'function') {
174
233
  try {
175
- for (const session of live.list()) liveIds.add(session.id)
234
+ const liveList = live.list()
235
+ if (liveList) {
236
+ for (const session of liveList) {
237
+ if (session && typeof session.id === 'string') liveIds.add(session.id)
238
+ }
239
+ }
176
240
  } catch {
177
241
  /* the live set is an optimization only */
178
242
  }
@@ -182,11 +246,13 @@ async function candidateRecords(ctx, query, from, to) {
182
246
  if (persistence && typeof persistence.list === 'function') {
183
247
  try {
184
248
  const snapshots = await persistence.list()
185
- for (const snapshot of snapshots) {
186
- if (!snapshot || !snapshot.header) continue
187
- revisions.set(snapshot.header.id, snapshot.revision)
188
- const path = snapshot.location && snapshot.location.path
189
- if (typeof path === 'string') paths.set(snapshot.header.id, path)
249
+ if (Array.isArray(snapshots)) {
250
+ for (const snapshot of snapshots) {
251
+ if (!snapshot || !snapshot.header || typeof snapshot.header.id !== 'string') continue
252
+ revisions.set(snapshot.header.id, snapshot.revision)
253
+ const path = snapshot.location && snapshot.location.path
254
+ if (typeof path === 'string') paths.set(snapshot.header.id, path)
255
+ }
190
256
  }
191
257
  } catch {
192
258
  /* fall back to reading whatever the query returns */
@@ -200,6 +266,8 @@ async function candidateRecords(ctx, query, from, to) {
200
266
  if (header.createdAt && header.createdAt >= to) return false
201
267
  if (liveIds.has(header.id)) return true
202
268
  if (!header.createdAt || header.createdAt >= recentFloor) return true
269
+ const rev = revisions.get(header.id)
270
+ if (rev != null && sessionUsageCache?.get(header.id)?.revision === String(rev)) return true
203
271
  const path = paths.get(header.id)
204
272
  if (path !== undefined) {
205
273
  try {
@@ -221,7 +289,7 @@ async function computeBill(ctx, from, to, dateLabel, period, state, snapshot) {
221
289
  throw error
222
290
  }
223
291
 
224
- const candidates = await candidateRecords(ctx, query, from, to)
292
+ const candidates = await candidateRecords(ctx, query, from, to, state.sessionUsageCache)
225
293
  const loaded = await mapLimit(candidates, 6, ({ record, revision }) => cachedSessionUsage(query, record, revision, state.sessionUsageCache))
226
294
  const rows = loaded.filter((row) => row && row.messages.length > 0)
227
295
 
@@ -239,6 +307,8 @@ async function computeBill(ctx, from, to, dateLabel, period, state, snapshot) {
239
307
  const modelMap = new Map()
240
308
  const pricing = createPricingAccumulator(snapshot)
241
309
  const sessionRows = []
310
+ let billFirstAt = 0
311
+ let billLastAt = 0
242
312
 
243
313
  for (const row of rows) {
244
314
  let requests = 0
@@ -261,6 +331,8 @@ async function computeBill(ctx, from, to, dateLabel, period, state, snapshot) {
261
331
  reasoning += message.reasoning
262
332
  firstAt = firstAt === 0 || message.time < firstAt ? message.time : firstAt
263
333
  lastAt = message.time > lastAt ? message.time : lastAt
334
+ billFirstAt = billFirstAt === 0 || message.time < billFirstAt ? message.time : billFirstAt
335
+ billLastAt = message.time > billLastAt ? message.time : billLastAt
264
336
  const key = `${message.provider}\u0000${message.model}`
265
337
  const existing = modelMap.get(key) || {
266
338
  provider: message.provider, model: message.model, total: 0, input: 0, output: 0,
@@ -301,8 +373,8 @@ async function computeBill(ctx, from, to, dateLabel, period, state, snapshot) {
301
373
 
302
374
  }
303
375
 
304
- const date = dateLabel || compactDate(from)
305
- const periodCode = period === 'week' ? 'W' : period === 'month' ? 'M' : 'D'
376
+ const date = dateLabel || defaultDateLabel(period, from, to)
377
+ const periodCode = PERIOD_CODES.get(period) || 'D'
306
378
  const billNo = `TR-${periodCode}-${date.replaceAll('-', '')}-${hashSuffix(`${period}:${date}:${totals.totalTokens}:${totals.requests}`)}`
307
379
 
308
380
  return {
@@ -311,6 +383,8 @@ async function computeBill(ctx, from, to, dateLabel, period, state, snapshot) {
311
383
  period,
312
384
  from,
313
385
  to,
386
+ firstAt: billFirstAt > 0 ? billFirstAt : null,
387
+ lastAt: billLastAt > 0 ? billLastAt : null,
314
388
  generatedAt: state.now(),
315
389
  billNo,
316
390
  totals,
@@ -336,7 +410,7 @@ async function cachedBill(ctx, state, key, from, to, dateLabel, period, snapshot
336
410
  const bill = await promise
337
411
  entry.pending = false
338
412
  entry.at = state.now()
339
- if (bill.pricing.status === 'unavailable' && billCache.get(key) === entry) billCache.delete(key)
413
+ if (snapshot.book === null && billCache.get(key) === entry) billCache.delete(key)
340
414
  return bill
341
415
  } catch (error) {
342
416
  if (billCache.get(key) === entry) billCache.delete(key)
@@ -350,8 +424,8 @@ export function createReceiptService(ctx, options = {}) {
350
424
  const catalog = options.catalog || createPricingCatalog({ fetchImpl: options.fetchImpl, now })
351
425
  const state = { now, billCache: new Map(), sessionUsageCache: new Map() }
352
426
 
353
- async function getBill({ from, to, date, period = 'day' }) {
354
- const snapshot = await catalog.read()
427
+ async function getBill({ from, to, date, period = 'day', force = false }) {
428
+ const snapshot = await catalog.read({ force: Boolean(force) })
355
429
  // Include labels and price state: a previously unavailable price can recover
356
430
  // without waiting for a session revision or an unrelated date to change.
357
431
  const key = JSON.stringify([from, to, date, period, snapshot.version, snapshot.stale])
@@ -370,18 +444,24 @@ export function createReceiptService(ctx, options = {}) {
370
444
  } catch {
371
445
  return sendJson(res, 400, { ok: false, error: 'Invalid request.' }, headOnly)
372
446
  }
373
- const defaultBounds = localDayBounds(new Date(now()))
374
- const fromParam = url.searchParams.get('from')
375
- const toParam = url.searchParams.get('to')
376
- const from = fromParam === null ? NaN : Number(fromParam)
377
- const to = toParam === null ? NaN : Number(toParam)
378
- const safeFrom = Number.isFinite(from) ? from : defaultBounds.from
379
- const safeTo = Number.isFinite(to) && to > safeFrom ? to : safeFrom + DAY_MS
380
- const dateLabel = url.searchParams.get('date') || compactDate(safeFrom)
381
447
  const requestedPeriod = url.searchParams.get('period')
382
- const period = requestedPeriod === 'week' || requestedPeriod === 'month' ? requestedPeriod : 'day'
448
+ const period = VALID_PERIODS.has(requestedPeriod) ? requestedPeriod : 'day'
449
+ const defaultBounds = defaultPeriodBounds(period, new Date(now()))
450
+ const from = parseTs(url.searchParams.get('from'))
451
+ const to = parseTs(url.searchParams.get('to'))
452
+ let safeFrom = Number.isFinite(from) ? from : defaultBounds.from
453
+ let safeTo = Number.isFinite(to) && to > safeFrom
454
+ ? to
455
+ : safeFrom === defaultBounds.from ? defaultBounds.to : nextLocalDay(safeFrom)
456
+ if (!Number.isFinite(safeTo) || safeTo <= safeFrom) {
457
+ safeFrom = defaultBounds.from
458
+ safeTo = defaultBounds.to
459
+ }
460
+ const rawDate = url.searchParams.get('date')?.trim() ?? ''
461
+ const dateLabel = /^[A-Za-z0-9-]{1,32}$/.test(rawDate) ? rawDate : defaultDateLabel(period, safeFrom, safeTo)
462
+ const refresh = url.searchParams.get('refresh')
383
463
  try {
384
- const bill = await getBill({ from: safeFrom, to: safeTo, date: dateLabel, period })
464
+ const bill = await getBill({ from: safeFrom, to: safeTo, date: dateLabel, period, force: refresh === '1' })
385
465
  return sendJson(res, 200, bill, headOnly)
386
466
  } catch (error) {
387
467
  const statusCode = error && Number.isInteger(error.statusCode) ? error.statusCode : 500
package/locale/en.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Token receipt",
4
- "description": "Print daily, weekly, or monthly token usage and estimated costs as a receipt. Currency follows the language, with manual USD/CNY/JPY selection. Replay printing and save a PNG. Usage stays local; only public model prices are fetched from models.dev.",
5
- "detail": "docs/DETAIL.md"
4
+ "description": "Print daily, weekly, monthly, 30-day, 90-day, or all-time token usage and estimated costs as a receipt. Currency follows the language, with manual USD/CNY/JPY selection. Replay printing, and copy the image or save a PNG. Usage stays local; only public model prices are fetched from models.dev.",
5
+ "detail": "assets/detail/DETAIL.md"
6
6
  }
7
7
  }
package/locale/ja.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "トークン明細",
4
- "description": "日・週・月ごとのトークン使用量と推定料金をレシートとして印刷できます。通貨は言語に連動し、USD/CNY/JPY に手動で切り替えることもできます。印刷アニメーションと PNG 保存に対応。使用量は端末内に保管し、models.dev の公開料金のみを取得します。会話データは送信しません。",
5
- "detail": "docs/DETAIL.ja.md"
4
+ "description": "日・週・月・直近30日・直近90日・全期間のトークン使用量と推定料金をレシートとして印刷できます。通貨は言語に連動し、USD/CNY/JPY に手動で切り替えることもできます。印刷アニメーションに加え、画像のコピーと PNG 保存に対応。使用量は端末内に保管し、models.dev の公開料金のみを取得します。会話データは送信しません。",
5
+ "detail": "assets/detail/DETAIL.ja.md"
6
6
  }
7
7
  }
package/locale/zh.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Token 账单",
4
- "description": "把日、周、月的 token 用量与预估费用打印成小票,币种跟随语言,支持 USD/CNY/JPY 手动切换、打印动画和 PNG 保存。用量从本机 DSH 会话读取,仅联网获取 models.dev 公开价格,不上传会话数据。",
5
- "detail": "docs/DETAIL.zh.md"
4
+ "description": "把日、周、月、近 30 天、近 90 天与全部的 token 用量及预估费用打印成小票,币种跟随语言,支持 USD/CNY/JPY 手动切换、打印动画,以及复制图片或保存 PNG。用量从本机 DSH 会话读取,仅联网获取 models.dev 公开价格,不上传会话数据。",
5
+ "detail": "assets/detail/DETAIL.zh.md"
6
6
  }
7
7
  }
package/package.json CHANGED
@@ -1,30 +1,30 @@
1
1
  {
2
2
  "name": "dsh-token-receipt",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "private": false,
5
- "description": "Print daily, weekly, or monthly token usage and estimated model costs as a tactile receipt, with PNG export.",
5
+ "description": "Print daily, weekly, monthly, 30-day, 90-day, or all-time token usage and estimated model costs as a tactile receipt, with clipboard copy and PNG export.",
6
6
  "type": "module",
7
7
  "main": "index.js",
8
8
  "exports": {
9
9
  ".": "./index.js",
10
10
  "./client": "./client.js",
11
11
  "./locale/*.json": "./locale/*.json",
12
- "./icon": "./icon.svg"
12
+ "./icon": "./icon.svg",
13
+ "./package.json": "./package.json"
13
14
  },
14
15
  "files": [
15
16
  "index.js",
17
+ "pricing.js",
16
18
  "client.js",
17
19
  "cordis.patch.yml",
18
20
  "locale/*.json",
19
- "docs",
20
- "assets",
21
+ "assets/detail",
21
22
  "icon.svg",
22
23
  "README.md",
24
+ "README.zh.md",
25
+ "README.ja.md",
23
26
  "LICENSE",
24
27
  "CHANGELOG.md",
25
- "README.zh.md",
26
- "RELEASING.md",
27
- "pricing.js",
28
28
  "THIRD_PARTY_NOTICES.md",
29
29
  "licenses"
30
30
  ],
@@ -74,6 +74,6 @@
74
74
  "scripts": {
75
75
  "check": "node --check index.js && node --check pricing.js && node --check client.js",
76
76
  "prepublishOnly": "npm run check && npm test",
77
- "test": "node --test tests/*.test.js"
77
+ "test": "node --test \"tests/*.test.js\""
78
78
  }
79
79
  }
package/pricing.js CHANGED
@@ -64,11 +64,6 @@ function orgOf(id) {
64
64
  return slash > 0 ? id.slice(0, slash).toLowerCase() : undefined
65
65
  }
66
66
 
67
- function labOf(canonical) {
68
- const slash = canonical.indexOf('/')
69
- return slash > 0 ? canonical.slice(0, slash).toLowerCase() : undefined
70
- }
71
-
72
67
  function stripPrefixes(input, prefixes) {
73
68
  let out = input
74
69
  let changed = true
@@ -123,7 +118,7 @@ function familyVendorOf(model) {
123
118
  return FAMILY_VENDORS.find(([prefix]) => bare.startsWith(prefix))?.[1]
124
119
  }
125
120
 
126
- const MODELS_DEV_PROVIDER_IDS = {
121
+ const MODELS_DEV_PROVIDER_IDS = Object.assign(Object.create(null), {
127
122
  'deepseek-official': 'deepseek',
128
123
  'deepseek-account': 'deepseek',
129
124
  'kimi-coding': 'moonshotai',
@@ -143,10 +138,12 @@ const MODELS_DEV_PROVIDER_IDS = {
143
138
  'xiaomi-token-plan-sgp': 'xiaomi',
144
139
  'minimax-coding-plan': 'minimax',
145
140
  'minimax-cn-coding-plan': 'minimax-cn',
146
- }
141
+ })
147
142
 
148
143
  function modelsDevProviderOf(dshProviderId) {
149
- return MODELS_DEV_PROVIDER_IDS[dshProviderId] ?? dshProviderId
144
+ return Object.hasOwn(MODELS_DEV_PROVIDER_IDS, dshProviderId)
145
+ ? MODELS_DEV_PROVIDER_IDS[dshProviderId]
146
+ : dshProviderId
150
147
  }
151
148
 
152
149
  function isDeepSeekProvider(dshProviderId) {
@@ -154,14 +151,13 @@ function isDeepSeekProvider(dshProviderId) {
154
151
  }
155
152
 
156
153
  function sameRate(a, b) {
157
- const close = (x, y) => Math.abs(x - y) <= 1e-9 * Math.max(1, Math.abs(x))
154
+ const close = (x, y) => Math.abs(x - y) <= 1e-9 * Math.max(1, Math.abs(x), Math.abs(y))
158
155
  return close(a.hit, b.hit) && close(a.miss, b.miss) && close(a.write, b.write) && close(a.out, b.out)
159
156
  }
160
157
 
161
158
  function rateOfEntry(value) {
162
- const v = value
163
- if (v === null || typeof v !== 'object') return null
164
- const r = v
159
+ const r = asRecord(value)
160
+ if (r === null) return null
165
161
  const num = (x) => typeof x === 'number' && Number.isFinite(x)
166
162
  return num(r.hit) && num(r.miss) && num(r.write) && num(r.out)
167
163
  ? { hit: r.hit, miss: r.miss, write: r.write, out: r.out }
@@ -180,30 +176,38 @@ function pushForms(map, forms, candidate) {
180
176
 
181
177
  export function priceIndexOf(
182
178
  prices,
183
- canonicalOf = {},
179
+ canonicalOf = Object.create(null),
184
180
  ) {
185
181
  const byModel = new Map()
186
182
  const byNormalized = new Map()
187
183
  const branches = new Map()
184
+ if (!prices || typeof prices !== 'object') return { byModel, byNormalized, branches }
188
185
  for (const pid of Object.keys(prices)) {
189
186
  if (isSubscriptionPlanProvider(pid)) continue
190
187
  const branchPrices = branchOf(prices, pid)
191
188
  if (branchPrices === null) continue
189
+ const canonicalBranch = canonicalOf && typeof canonicalOf === 'object' && Object.hasOwn(canonicalOf, pid)
190
+ ? asRecord(canonicalOf[pid])
191
+ : null
192
192
  const exact = new Map()
193
193
  const suffix = new Map()
194
194
  const normalized = new Map()
195
195
  const normalizedSuffix = new Map()
196
196
  const labs = new Set()
197
197
  for (const mid of Object.keys(branchPrices)) {
198
- const rate = branchPrices[mid]
199
- if (rateOfEntry(rate) === null) continue
200
- const canonical = canonicalOf[pid]?.[mid]
201
- const lab = canonical === undefined || canonical.length === 0 ? undefined : labOf(canonical)
198
+ if (!Object.hasOwn(branchPrices, mid)) continue
199
+ const rate = rateOfEntry(branchPrices[mid])
200
+ if (rate === null) continue
201
+ const rawCanonical = canonicalBranch !== null && Object.hasOwn(canonicalBranch, mid)
202
+ ? canonicalBranch[mid]
203
+ : undefined
204
+ const canonical = typeof rawCanonical === 'string' && rawCanonical.length > 0 ? rawCanonical : undefined
205
+ const lab = canonical === undefined ? undefined : orgOf(canonical)
202
206
  const candidate = {
203
207
  pid,
204
208
  mid,
205
209
  rate,
206
- ...canonical === undefined || canonical.length === 0 ? {} : { canonical },
210
+ ...canonical === undefined ? {} : { canonical },
207
211
  ...lab === undefined ? {} : { lab },
208
212
  }
209
213
  const lower = lowerModelId(mid)
@@ -259,9 +263,7 @@ function faceOf(candidate, via, confidence) {
259
263
  function lookupBranch(branch, model) {
260
264
  const exact = lowerModelId(model)
261
265
  const normalized = normalizeModelId(model)
262
- const stages
263
-
264
- = [
266
+ const stages = [
265
267
  { map: branch.byExact, keys: [exact], via: 'direct', confidence: 'high' },
266
268
  { map: branch.bySuffix, keys: [exact], via: 'branch-suffix', confidence: 'high' },
267
269
  { map: branch.byNormalized, keys: [normalized], via: 'branch-normalized', confidence: 'medium' },
@@ -402,32 +404,23 @@ function resolvePriceOf(book, provider, model) {
402
404
  return unpriced('no-entry')
403
405
  }
404
406
 
405
- function priceFaceOf(book, provider, model) {
406
- const resolution = priceResolutionOf(book, provider, model)
407
- return resolution.kind === 'priced' ? resolution.face : null
408
- }
409
-
410
- function priceOf(book, provider, model) {
411
- return priceFaceOf(book, provider, model)?.rate ?? null
412
- }
413
-
414
407
  function branchOf(book, id) {
415
- const value = book[id]
416
- return value !== null && typeof value === 'object' ? value : null
408
+ if (!book || typeof book !== 'object' || !Object.hasOwn(book, id)) return null
409
+ return asRecord(book[id])
417
410
  }
418
411
 
419
412
  export function pricesBookOf(value) {
420
413
  const data = asRecord(value)
421
- if (data === null || Array.isArray(data)) return null
422
- const book = {}
423
- const canonicalOf = {}
414
+ if (data === null) return null
415
+ const book = Object.create(null)
416
+ const canonicalOf = Object.create(null)
424
417
  for (const providerId of Object.keys(data)) {
425
418
  if (providerId === '__proto__' || providerId === 'constructor' || providerId === 'prototype') continue
426
419
  const provider = asRecord(data[providerId])
427
420
  if (provider === null) continue
428
421
  const modelList = asRecord(provider.models)
429
422
  if (modelList === null) continue
430
- const models = {}
423
+ const models = Object.create(null)
431
424
  for (const id of Object.keys(modelList)) {
432
425
  if (id === '__proto__' || id === 'constructor' || id === 'prototype') continue
433
426
  const model = asRecord(modelList[id])
@@ -442,9 +435,11 @@ export function pricesBookOf(value) {
442
435
  write: rateNum(cost.cache_write) ?? miss,
443
436
  out,
444
437
  }
445
- const canonical = model?.['canonical_model_id']
438
+ const canonical = model.canonical_model_id
446
439
  if (typeof canonical === 'string' && canonical.length > 0) {
447
- const branch = canonicalOf[providerId] ?? (canonicalOf[providerId] = {})
440
+ const branch = Object.hasOwn(canonicalOf, providerId)
441
+ ? canonicalOf[providerId]
442
+ : (canonicalOf[providerId] = Object.create(null))
448
443
  branch[id] = canonical
449
444
  }
450
445
  }
@@ -460,6 +455,7 @@ function rateNum(value) {
460
455
  export const PRICE_SOURCE = 'https://models.dev/api.json'
461
456
  export const PRICE_TTL_MS = 60 * 60 * 1000
462
457
  export const PRICE_FAILURE_BACKOFF_MS = 30_000
458
+ export const PRICE_FORCE_COOLDOWN_MS = 1_000
463
459
  export const PRICE_TIMEOUT_MS = 8_000
464
460
 
465
461
  /** The provider prefix is stripped only when it is the supplied source provider. */
@@ -494,12 +490,14 @@ export function createPricingCatalog(options = {}) {
494
490
  const now = options.now || Date.now
495
491
  const ttlMs = options.ttlMs ?? PRICE_TTL_MS
496
492
  const failureBackoffMs = options.failureBackoffMs ?? PRICE_FAILURE_BACKOFF_MS
493
+ const forceCooldownMs = Math.min(failureBackoffMs, options.forceCooldownMs ?? PRICE_FORCE_COOLDOWN_MS)
497
494
  const timeoutMs = options.timeoutMs ?? PRICE_TIMEOUT_MS
498
495
  let book = null
499
496
  let fetchedAt = null
500
497
  let version = 0
501
498
  let failed = false
502
499
  let retryAt = 0
500
+ let forceRetryAt = 0
503
501
  let inflight = null
504
502
  let controller = null
505
503
  let disposed = false
@@ -514,21 +512,33 @@ export function createPricingCatalog(options = {}) {
514
512
  })
515
513
 
516
514
  async function refresh() {
517
- controller = new AbortController()
515
+ const requestController = new AbortController()
516
+ controller = requestController
517
+ const { signal } = requestController
518
518
  let timer
519
+ let onAbort
519
520
  try {
520
521
  // Race explicitly: a custom fetcher might not implement AbortSignal.
521
522
  const next = await Promise.race([
522
523
  Promise.resolve().then(async () => {
523
524
  const response = await fetchImpl(PRICE_SOURCE, {
524
525
  headers: { accept: 'application/json', 'user-agent': 'Mozilla/5.0 TokenReceipt/1.0 (+https://github.com/maxlee/dsh-token-receipt)' },
525
- signal: controller.signal,
526
+ signal,
526
527
  })
527
528
  if (!response || !response.ok) throw new Error(`Model price request failed (${response?.status ?? 'no response'})`)
528
529
  return pricesBookOf(await response.json())
529
530
  }),
530
531
  new Promise((_, reject) => {
531
- timer = setTimeout(() => { controller?.abort(); reject(new Error('Model price request timed out')) }, timeoutMs)
532
+ if (signal.aborted) {
533
+ reject(new Error('Model price request aborted'))
534
+ return
535
+ }
536
+ onAbort = () => reject(new Error('Model price request aborted'))
537
+ signal.addEventListener('abort', onAbort, { once: true })
538
+ timer = setTimeout(() => {
539
+ reject(new Error('Model price request timed out'))
540
+ requestController.abort()
541
+ }, timeoutMs)
532
542
  }),
533
543
  ])
534
544
  if (next === null || next.index.branches.size === 0) throw new Error('Model price catalog contains no usable rates')
@@ -538,22 +548,29 @@ export function createPricingCatalog(options = {}) {
538
548
  version += 1
539
549
  failed = false
540
550
  retryAt = 0
551
+ forceRetryAt = 0
541
552
  } catch {
542
553
  if (disposed) return
554
+ const failedAt = now()
543
555
  failed = true
544
- retryAt = now() + failureBackoffMs
556
+ retryAt = failedAt + failureBackoffMs
557
+ forceRetryAt = failedAt + forceCooldownMs
545
558
  } finally {
546
559
  clearTimeout(timer)
547
- controller = null
560
+ if (onAbort) signal.removeEventListener('abort', onAbort)
561
+ if (controller === requestController) controller = null
548
562
  }
549
563
  }
550
564
 
551
565
  return {
552
- async read() {
566
+ async read(options = {}) {
553
567
  if (disposed) return snapshot()
554
568
  if (inflight !== null) { await inflight; return snapshot() }
555
- const fresh = book !== null && fetchedAt !== null && now() - fetchedAt < ttlMs
556
- if ((!fresh || failed) && now() >= retryAt) {
569
+ const currentNow = now()
570
+ const force = Boolean(options?.force)
571
+ const stale = book !== null && (failed || fetchedAt === null || currentNow - fetchedAt >= ttlMs)
572
+ const needsRefresh = book === null || stale
573
+ if (needsRefresh && currentNow >= (force ? forceRetryAt : retryAt)) {
557
574
  inflight = refresh()
558
575
  try { await inflight } finally { inflight = null }
559
576
  }
package/RELEASING.md DELETED
@@ -1,31 +0,0 @@
1
- # Releasing
2
-
3
- This repository is set up for a public npm package and a GitHub repository.
4
-
5
- ## Before the first publish
6
-
7
- 1. Confirm the package name in `package.json` is still available:
8
- `npm view dsh-token-receipt version`.
9
- 2. Log in to npm with the account that owns `@maxlee`:
10
- `npm login`.
11
- 3. Run the local checks:
12
- `npm run check && npm pack --dry-run`.
13
-
14
- ## Publish a version
15
-
16
- ```bash
17
- npm version patch # or minor / major
18
- git push origin main --tags
19
- npm publish --access public
20
- ```
21
-
22
- For a trusted-publishing release from GitHub Actions, create an
23
- `NPM_TOKEN` repository secret (or configure npm trusted publishing) and push a
24
- `v*` tag. The `release.yml` workflow publishes with provenance.
25
-
26
- ## Push the repository
27
-
28
- ```bash
29
- git remote add origin git@github.com:maxlee/dsh-token-receipt.git
30
- git push -u origin main --tags
31
- ```
@@ -1,10 +0,0 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" width="360" height="520" viewBox="0 0 360 520">
2
- <filter id="paper-grain" x="-10%" y="-10%" width="120%" height="120%" color-interpolation-filters="sRGB">
3
- <feTurbulence type="fractalNoise" baseFrequency="0.012 0.02" numOctaves="3" seed="42" stitchTiles="stitch" />
4
- <feColorMatrix type="saturate" values="0" />
5
- <feComponentTransfer>
6
- <feFuncA type="table" tableValues="0 0.22" />
7
- </feComponentTransfer>
8
- </filter>
9
- <rect width="100%" height="100%" filter="url(#paper-grain)" opacity="0.35" />
10
- </svg>