dsh-deepseek-pricing 0.1.0 → 0.2.1
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/README.md +84 -12
- package/client.js +1344 -42
- package/icon.svg +2 -9
- package/index.js +127 -5
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +6 -2
- package/src/data.js +220 -22
- package/src/options.js +55 -0
package/icon.svg
CHANGED
|
@@ -1,9 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
<path d="M32 13a19 19 0 0 1 0 38z" fill="#ffffff" opacity="0.18"/>
|
|
4
|
-
<circle cx="32" cy="32" r="17" fill="none" stroke="#ffffff" stroke-width="3.5" opacity="0.95"/>
|
|
5
|
-
<path d="M32 21.5v11.2l7.4 4.3" fill="none" stroke="#ffffff" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
|
|
6
|
-
<circle cx="32" cy="32" r="3.2" fill="#ffffff"/>
|
|
7
|
-
<path d="M17 32h4M43 32h4" stroke="#ffffff" stroke-width="3" stroke-linecap="round" opacity="0.75"/>
|
|
8
|
-
<path d="M32 12v4M32 48v4" stroke="#ffffff" stroke-width="3" stroke-linecap="round" opacity="0.75"/>
|
|
9
|
-
</svg>
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<svg version="1.1" width="64" height="64" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg"><g><rect x="3" y="3" width="58" height="58" rx="15" fill="#4d6bfe"/><path d="m13.3 32.2a18.8 18.8 0 0 1 18.8-18.8v18.8z" fill="#fff" fill-opacity=".629"/><path d="m41.3 15.8a18.8 18.8 0 0 1 8.74 21.1 18.8 18.8 0 0 1-18.1 13.9v-18.8z" fill="#fff" fill-opacity=".629"/><path transform="scale(1.08 .927)" d="m48.2 8.61-13.7 23.4h10.8v5.16h-12.6v7.11h12.6v5.23h-12.6v10.4h-6.48v-10.4h-13.1v-5.23h13.1v-7.11h-13.1v-5.16h11.1l-13.6-23.4h7.31c6.35 11.6 11.7 22 11.7 22l11.6-22z" fill="#00f" fill-opacity=".2" stroke-opacity="0" aria-label="¥"/><g><g><circle cx="32" cy="32" r="17" fill="none" stroke="#fff" stroke-opacity=".95" stroke-width="3.5"/><path d="m32 21.5v11.2l7.4 4.3" fill="none" stroke="#fff" stroke-linecap="round" stroke-linejoin="round" stroke-width="4"/><circle cx="32" cy="32" r="3.2" fill="#fff"/></g><g transform="translate(.23 .115)"><g transform="matrix(1.05 0 0 .945 -24.8 2.33)"><path d="m53.8 11.4-0.0151 4m-0.121 32-0.0151 4" opacity=".75" stroke="#fff" stroke-linecap="round" stroke-width="3"/></g><g transform="matrix(0 -1.05 .945 0 2.2 88.5)"><path d="m53.8 11.4-0.0151 4m-0.121 32-0.0151 4" opacity=".75" stroke="#fff" stroke-linecap="round" stroke-width="3"/></g></g></g></g></svg>
|
package/index.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Host half of dsh-deepseek-pricing.
|
|
3
3
|
*
|
|
4
|
-
* Registers two read-only HTTP routes
|
|
5
|
-
* enables it, an optional `deepseek_pricing` tool for
|
|
6
|
-
* access, caching and calculations live in
|
|
4
|
+
* Registers two read-only HTTP routes plus one write route for the browser
|
|
5
|
+
* half and, when the user enables it, an optional `deepseek_pricing` tool for
|
|
6
|
+
* the model. All network access, caching and calculations live in
|
|
7
|
+
* ./src/data.js.
|
|
7
8
|
*
|
|
8
9
|
* The config shape below is read by apply(); this bundle intentionally exports
|
|
9
10
|
* no Config schema: a workspace-linked bundle resolves bare `@deepseek-ai/*`
|
|
10
11
|
* imports from its real path (the workspace), not from the profile's
|
|
11
12
|
* node_modules, so importing schemastery here would fail to load the plugin.
|
|
12
|
-
* The row in cordis.patch.yml
|
|
13
|
+
* The row in cordis.patch.yml carries the values:
|
|
13
14
|
*
|
|
14
15
|
* - id: deepseek-pricing
|
|
15
16
|
* config:
|
|
@@ -17,11 +18,42 @@
|
|
|
17
18
|
* currency: CNY # CNY | USD
|
|
18
19
|
* refreshMinutes: 360 # 0 = manual refresh only
|
|
19
20
|
* holidayRefresh: true # sync Chinese statutory holidays
|
|
21
|
+
*
|
|
22
|
+
* The settings page edits the Host-owned subset through POST
|
|
23
|
+
* /api/deepseek-pricing/config, which persists through `configEditor` so the
|
|
24
|
+
* values live in the profile's cordis.patch.yml (one source of truth, removed
|
|
25
|
+
* with the row on uninstall) instead of a second store of our own.
|
|
20
26
|
*/
|
|
21
27
|
|
|
28
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
29
|
+
import { dirname, join } from 'node:path'
|
|
30
|
+
import { fileURLToPath } from 'node:url'
|
|
31
|
+
|
|
22
32
|
import { createDataLayer, describeError } from './src/data.js'
|
|
23
33
|
import { normalizeCurrency } from './src/pricing.js'
|
|
24
34
|
import { formatToolResult } from './src/format.js'
|
|
35
|
+
import { findOwnEntry, sanitizeConfigPatch } from './src/options.js'
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The holiday cache lives inside the installed package. Uninstalling the bundle
|
|
39
|
+
* deletes that directory, so the cache disappears with no leftover to document
|
|
40
|
+
* and no uninstall hook (DSH has none: `ctx.effect` teardown also runs on
|
|
41
|
+
* disable, reload, and restart, so it cannot mean "uninstall").
|
|
42
|
+
*/
|
|
43
|
+
const PACKAGE_DIR = dirname(fileURLToPath(import.meta.url))
|
|
44
|
+
const CACHE_DIR = join(PACKAGE_DIR, '.cache')
|
|
45
|
+
const HOLIDAY_CACHE_FILE = join(CACHE_DIR, 'holidays.json')
|
|
46
|
+
|
|
47
|
+
async function readHolidayCache() {
|
|
48
|
+
return JSON.parse(await readFile(HOLIDAY_CACHE_FILE, 'utf8'))
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function writeHolidayCache(payload) {
|
|
52
|
+
await mkdir(CACHE_DIR, { recursive: true })
|
|
53
|
+
const temporary = `${HOLIDAY_CACHE_FILE}.${process.pid}.tmp`
|
|
54
|
+
await writeFile(temporary, JSON.stringify(payload), 'utf8')
|
|
55
|
+
await rename(temporary, HOLIDAY_CACHE_FILE)
|
|
56
|
+
}
|
|
25
57
|
|
|
26
58
|
/**
|
|
27
59
|
* The browser-facing routes need the web server. Declaring it here makes the
|
|
@@ -80,6 +112,87 @@ function createRefreshHandler(data) {
|
|
|
80
112
|
}
|
|
81
113
|
}
|
|
82
114
|
|
|
115
|
+
/**
|
|
116
|
+
* Read a small JSON body without trusting its size. The browser half is the
|
|
117
|
+
* only caller, so a hard cap plus a rejected promise is enough.
|
|
118
|
+
*/
|
|
119
|
+
function readJsonBody(req, limit = 16 * 1024) {
|
|
120
|
+
return new Promise((resolve, reject) => {
|
|
121
|
+
let size = 0
|
|
122
|
+
const chunks = []
|
|
123
|
+
req.on('data', (chunk) => {
|
|
124
|
+
size += chunk.length
|
|
125
|
+
if (size > limit) {
|
|
126
|
+
reject(new Error('请求体过大'))
|
|
127
|
+
req.destroy()
|
|
128
|
+
return
|
|
129
|
+
}
|
|
130
|
+
chunks.push(chunk)
|
|
131
|
+
})
|
|
132
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
|
|
133
|
+
req.on('error', reject)
|
|
134
|
+
})
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Persist the config through the Loader. The response is sent first on
|
|
139
|
+
* purpose: `edit` reconciles this very row, which disposes the fiber that owns
|
|
140
|
+
* this handler, so an awaited write would abort the reply. The browser treats
|
|
141
|
+
* 202 as "saved, reloading" and re-reads /state afterwards.
|
|
142
|
+
*/
|
|
143
|
+
function createConfigHandler(ctx) {
|
|
144
|
+
return async (req, res) => {
|
|
145
|
+
const method = String(req.method || 'POST').toUpperCase()
|
|
146
|
+
if (method !== 'POST') {
|
|
147
|
+
sendJson(res, 405, { ok: false, error: '只支持 POST' })
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
let payload
|
|
151
|
+
try {
|
|
152
|
+
const text = await readJsonBody(req)
|
|
153
|
+
payload = text ? JSON.parse(text) : {}
|
|
154
|
+
} catch (error) {
|
|
155
|
+
sendJson(res, 400, { ok: false, error: describeError(error) })
|
|
156
|
+
return
|
|
157
|
+
}
|
|
158
|
+
const patch = sanitizeConfigPatch(payload)
|
|
159
|
+
if (Object.keys(patch).length === 0) {
|
|
160
|
+
sendJson(res, 400, { ok: false, error: '没有可写入的字段' })
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
const editor = typeof ctx.get === 'function' ? ctx.get('configEditor') : undefined
|
|
164
|
+
if (!editor || typeof editor.edit !== 'function') {
|
|
165
|
+
sendJson(res, 501, {
|
|
166
|
+
ok: false,
|
|
167
|
+
error: '当前 DSH 版本不支持自动写入配置,请手动编辑 profile 的 cordis.patch.yml',
|
|
168
|
+
})
|
|
169
|
+
return
|
|
170
|
+
}
|
|
171
|
+
let entry = null
|
|
172
|
+
try {
|
|
173
|
+
entry = findOwnEntry(editor)
|
|
174
|
+
} catch {
|
|
175
|
+
entry = null
|
|
176
|
+
}
|
|
177
|
+
if (!entry) {
|
|
178
|
+
sendJson(res, 404, {
|
|
179
|
+
ok: false,
|
|
180
|
+
error: '没有找到本插件的配置行,请手动编辑 profile 的 cordis.patch.yml',
|
|
181
|
+
})
|
|
182
|
+
return
|
|
183
|
+
}
|
|
184
|
+
sendJson(res, 202, { ok: true, patch, reload: true })
|
|
185
|
+
const timer = setTimeout(() => {
|
|
186
|
+
Promise.resolve()
|
|
187
|
+
.then(() => editor.edit(entry, (current) => ({ ...(current || {}), ...patch })))
|
|
188
|
+
.catch(() => {
|
|
189
|
+
// The page re-reads /state, which keeps reporting the old values.
|
|
190
|
+
})
|
|
191
|
+
}, 30)
|
|
192
|
+
if (timer && typeof timer.unref === 'function') timer.unref()
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
83
196
|
function createTool(data, config) {
|
|
84
197
|
return {
|
|
85
198
|
name: 'deepseek_pricing',
|
|
@@ -105,7 +218,7 @@ export function apply(ctx, rawConfig = {}) {
|
|
|
105
218
|
refreshMinutes: clampNumber(source.refreshMinutes, 0, 1440, 360),
|
|
106
219
|
holidayRefresh: source.holidayRefresh !== false,
|
|
107
220
|
}
|
|
108
|
-
const data = createDataLayer(config)
|
|
221
|
+
const data = createDataLayer(config, { readHolidayCache, writeHolidayCache })
|
|
109
222
|
|
|
110
223
|
// The web server publishes its service after the Host's plugin rows start,
|
|
111
224
|
// so a one-shot ctx.get('webServer') at apply time answers undefined on a
|
|
@@ -132,6 +245,15 @@ export function apply(ctx, rawConfig = {}) {
|
|
|
132
245
|
}),
|
|
133
246
|
'deepseek-pricing: refresh route',
|
|
134
247
|
)
|
|
248
|
+
scoped.effect(
|
|
249
|
+
() =>
|
|
250
|
+
server.register({
|
|
251
|
+
kind: 'exact',
|
|
252
|
+
path: '/api/deepseek-pricing/config',
|
|
253
|
+
handler: createConfigHandler(ctx),
|
|
254
|
+
}),
|
|
255
|
+
'deepseek-pricing: config route',
|
|
256
|
+
)
|
|
135
257
|
})
|
|
136
258
|
|
|
137
259
|
if (config.tool) {
|
package/locale/en.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "DeepSeek Peak & Pricing",
|
|
4
|
-
"description": "Shows whether DeepSeek calls are in peak or off-peak hours
|
|
4
|
+
"description": "Shows whether DeepSeek calls are in peak or off-peak hours, keeps official per-model prices in Settings, and can estimate each turn's cost."
|
|
5
5
|
}
|
|
6
|
-
}
|
|
6
|
+
}
|
package/locale/zh.json
CHANGED
package/package.json
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-deepseek-pricing",
|
|
3
|
-
"version": "0.1
|
|
4
|
-
"description": "DeepSeek 计费时段与模型价格:输入框状态徽章 +
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "DeepSeek 计费时段与模型价格:输入框状态徽章 + 设置页价格表 + 每轮花费估算,功能开关收在插件页面。",
|
|
5
5
|
"icon": "./icon.svg",
|
|
6
6
|
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/hai55555/dsh-deepseek-pricing.git"
|
|
10
|
+
},
|
|
7
11
|
"keywords": [
|
|
8
12
|
"dsh",
|
|
9
13
|
"deepseek",
|
package/src/data.js
CHANGED
|
@@ -18,11 +18,18 @@ import { normalizeCurrency, parsePricingMarkdown, pricingSource } from './pricin
|
|
|
18
18
|
import { holidayCnUrl, parseHolidayCn, parseTimor, timorUrl } from './holidays.js'
|
|
19
19
|
import { SNAPSHOT_CAPTURED_AT, snapshotFor, snapshotHolidays } from './snapshot.js'
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
// timor.tech is occasionally slow (measured 11 s for one year), so the old 8 s
|
|
22
|
+
// budget alone produced the "已同步 → 获取失败" flapping. The first state read
|
|
23
|
+
// no longer waits for holidays, which makes a generous timeout affordable.
|
|
24
|
+
const FETCH_TIMEOUT_MS = 20000
|
|
25
|
+
// A statutory calendar changes once a year (the next year is published around
|
|
26
|
+
// November), so a weekly check is plenty and a restart inside the window costs
|
|
27
|
+
// no network at all.
|
|
28
|
+
const HOLIDAY_TTL_MS = 7 * 24 * 3600 * 1000
|
|
29
|
+
const HOLIDAY_CACHE_VERSION = 1
|
|
23
30
|
const PRICE_RETRY_MS = 60 * 1000
|
|
24
|
-
const HOLIDAY_RETRY_MS =
|
|
25
|
-
const USER_AGENT = 'dsh-deepseek-pricing/0.
|
|
31
|
+
const HOLIDAY_RETRY_MS = 15 * 60 * 1000
|
|
32
|
+
const USER_AGENT = 'dsh-deepseek-pricing/0.2'
|
|
26
33
|
|
|
27
34
|
export function describeError(error) {
|
|
28
35
|
if (!error) return '未知错误'
|
|
@@ -65,6 +72,10 @@ function snapshotHolidayYear(year) {
|
|
|
65
72
|
export function createDataLayer(config, deps = {}) {
|
|
66
73
|
const nowFn = typeof deps.now === 'function' ? deps.now : () => Date.now()
|
|
67
74
|
const fetchText = typeof deps.fetchText === 'function' ? deps.fetchText : defaultFetchText
|
|
75
|
+
const readHolidayCache =
|
|
76
|
+
typeof deps.readHolidayCache === 'function' ? deps.readHolidayCache : null
|
|
77
|
+
const writeHolidayCache =
|
|
78
|
+
typeof deps.writeHolidayCache === 'function' ? deps.writeHolidayCache : null
|
|
68
79
|
|
|
69
80
|
const priceCache = new Map()
|
|
70
81
|
const priceError = new Map()
|
|
@@ -79,6 +90,131 @@ export function createDataLayer(config, deps = {}) {
|
|
|
79
90
|
error: null,
|
|
80
91
|
}
|
|
81
92
|
|
|
93
|
+
/**
|
|
94
|
+
* Last successful fetch per year. A transient network failure must not throw
|
|
95
|
+
* away a calendar we already have: the settings page used to flip between
|
|
96
|
+
* 已同步 and 获取失败 whenever a refresh hiccuped, and holiday pricing
|
|
97
|
+
* silently fell back to "no holidays" for a year that had just been fetched.
|
|
98
|
+
*/
|
|
99
|
+
const holidayLastGood = new Map()
|
|
100
|
+
// Consecutive refreshes that could not fetch a real calendar; the first few
|
|
101
|
+
// retry within a minute, then the gate widens to HOLIDAY_RETRY_MS.
|
|
102
|
+
let holidayFailures = 0
|
|
103
|
+
|
|
104
|
+
function rememberHolidayYear(year, entry) {
|
|
105
|
+
holidayLastGood.set(year, {
|
|
106
|
+
map: entry.map,
|
|
107
|
+
source: entry.source,
|
|
108
|
+
updatedAtMs: entry.updatedAtMs,
|
|
109
|
+
})
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function lastGoodHolidayYear(year, error) {
|
|
113
|
+
const previous = holidayLastGood.get(year)
|
|
114
|
+
if (!previous) return null
|
|
115
|
+
return {
|
|
116
|
+
year,
|
|
117
|
+
status: 'stale',
|
|
118
|
+
map: previous.map,
|
|
119
|
+
source: previous.source,
|
|
120
|
+
updatedAtMs: previous.updatedAtMs,
|
|
121
|
+
error,
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* The cache lives inside the installed package (`.cache/holidays.json`), so
|
|
127
|
+
* uninstalling the bundle — which deletes that directory — also removes it.
|
|
128
|
+
* Hydrating restores the calendars *and* the fetch clock, so a restart inside
|
|
129
|
+
* the TTL performs no request at all.
|
|
130
|
+
*/
|
|
131
|
+
let holidayCacheHydrated = false
|
|
132
|
+
|
|
133
|
+
async function hydrateHolidayCache() {
|
|
134
|
+
if (holidayCacheHydrated) return
|
|
135
|
+
holidayCacheHydrated = true
|
|
136
|
+
if (!readHolidayCache) return
|
|
137
|
+
let cached
|
|
138
|
+
try {
|
|
139
|
+
cached = await readHolidayCache()
|
|
140
|
+
} catch {
|
|
141
|
+
return
|
|
142
|
+
}
|
|
143
|
+
if (!cached || cached.version !== HOLIDAY_CACHE_VERSION || !Array.isArray(cached.years)) return
|
|
144
|
+
const currentYear = beijingParts(nowFn()).year
|
|
145
|
+
const years = []
|
|
146
|
+
for (const entry of cached.years) {
|
|
147
|
+
if (!entry || !Number.isInteger(entry.year)) continue
|
|
148
|
+
if (entry.year < currentYear || entry.year > currentYear + 1) continue
|
|
149
|
+
if (!entry.map || typeof entry.map !== 'object') continue
|
|
150
|
+
const good = {
|
|
151
|
+
map: entry.map,
|
|
152
|
+
source: typeof entry.source === 'string' ? entry.source : '磁盘缓存',
|
|
153
|
+
updatedAtMs: Number(entry.updatedAtMs) || 0,
|
|
154
|
+
}
|
|
155
|
+
holidayLastGood.set(entry.year, good)
|
|
156
|
+
years.push({
|
|
157
|
+
year: entry.year,
|
|
158
|
+
status: 'fresh',
|
|
159
|
+
map: good.map,
|
|
160
|
+
source: good.source,
|
|
161
|
+
updatedAtMs: good.updatedAtMs,
|
|
162
|
+
error: null,
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
if (years.length === 0) return
|
|
166
|
+
holidayState.years = years.sort((a, b) => a.year - b.year)
|
|
167
|
+
holidayState.merged = mergeHolidays(holidayState.years)
|
|
168
|
+
const savedAtMs = Number(cached.savedAtMs) || 0
|
|
169
|
+
if (savedAtMs > 0) {
|
|
170
|
+
holidayState.fetchedAtMs = savedAtMs
|
|
171
|
+
holidayState.attemptAtMs = savedAtMs
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Cold start with no cache: answer immediately from the built-in snapshot and
|
|
177
|
+
* let the fetch land behind the request. The old behaviour blocked the first
|
|
178
|
+
* state read for the whole fetch (up to 16 s with the old timeout).
|
|
179
|
+
*/
|
|
180
|
+
function seedPendingHolidayYears() {
|
|
181
|
+
const year = beijingParts(nowFn()).year
|
|
182
|
+
holidayState.years = [year, year + 1].map((entryYear) => {
|
|
183
|
+
const snapshot = snapshotHolidays(entryYear)
|
|
184
|
+
return {
|
|
185
|
+
year: entryYear,
|
|
186
|
+
status: 'pending',
|
|
187
|
+
map: snapshot || {},
|
|
188
|
+
source: snapshot ? '内置快照' : null,
|
|
189
|
+
updatedAtMs: snapshot ? Date.parse(SNAPSHOT_CAPTURED_AT) : null,
|
|
190
|
+
error: null,
|
|
191
|
+
}
|
|
192
|
+
})
|
|
193
|
+
holidayState.merged = mergeHolidays(holidayState.years)
|
|
194
|
+
holidayState.attemptAtMs = 0
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function persistHolidayCache() {
|
|
198
|
+
if (!writeHolidayCache) return
|
|
199
|
+
const currentYear = beijingParts(nowFn()).year
|
|
200
|
+
const years = Array.from(holidayLastGood.entries())
|
|
201
|
+
.filter(([year]) => year >= currentYear && year <= currentYear + 1)
|
|
202
|
+
.map(([year, good]) => ({
|
|
203
|
+
year,
|
|
204
|
+
map: good.map,
|
|
205
|
+
source: good.source,
|
|
206
|
+
updatedAtMs: good.updatedAtMs,
|
|
207
|
+
}))
|
|
208
|
+
.sort((a, b) => a.year - b.year)
|
|
209
|
+
if (years.length === 0) return
|
|
210
|
+
const payload = { version: HOLIDAY_CACHE_VERSION, savedAtMs: nowFn(), years }
|
|
211
|
+
Promise.resolve()
|
|
212
|
+
.then(() => writeHolidayCache(payload))
|
|
213
|
+
.catch(() => {
|
|
214
|
+
// A read-only package directory only costs the next cold start a fetch.
|
|
215
|
+
})
|
|
216
|
+
}
|
|
217
|
+
|
|
82
218
|
function single(key, task) {
|
|
83
219
|
if (inflight.has(key)) return inflight.get(key)
|
|
84
220
|
const promise = task().finally(() => {
|
|
@@ -101,7 +237,7 @@ export function createDataLayer(config, deps = {}) {
|
|
|
101
237
|
const text = await fetchText(attempt.url)
|
|
102
238
|
const parsed = attempt.parse(text, year)
|
|
103
239
|
if (parsed.status === 'ok') {
|
|
104
|
-
|
|
240
|
+
const entry = {
|
|
105
241
|
year,
|
|
106
242
|
status: 'fresh',
|
|
107
243
|
map: parsed.map,
|
|
@@ -109,12 +245,21 @@ export function createDataLayer(config, deps = {}) {
|
|
|
109
245
|
updatedAtMs: nowFn(),
|
|
110
246
|
error: null,
|
|
111
247
|
}
|
|
248
|
+
rememberHolidayYear(year, entry)
|
|
249
|
+
return entry
|
|
112
250
|
}
|
|
113
251
|
sawUnpublished = true
|
|
114
252
|
} catch (error) {
|
|
115
253
|
lastError = error
|
|
116
254
|
}
|
|
117
255
|
}
|
|
256
|
+
// Keep the last calendar we actually received rather than degrading to the
|
|
257
|
+
// snapshot (or to nothing) on a single failed refresh.
|
|
258
|
+
const previous = lastGoodHolidayYear(
|
|
259
|
+
year,
|
|
260
|
+
sawUnpublished && !lastError ? '本次未返回节假日数据' : describeError(lastError),
|
|
261
|
+
)
|
|
262
|
+
if (previous) return previous
|
|
118
263
|
const snapshot = snapshotHolidays(year)
|
|
119
264
|
if (snapshot) {
|
|
120
265
|
return {
|
|
@@ -139,20 +284,12 @@ export function createDataLayer(config, deps = {}) {
|
|
|
139
284
|
}
|
|
140
285
|
}
|
|
141
286
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
if (
|
|
149
|
-
!force &&
|
|
150
|
-
holidayState.attemptAtMs > 0 &&
|
|
151
|
-
nowMs - holidayState.attemptAtMs < HOLIDAY_RETRY_MS
|
|
152
|
-
) {
|
|
153
|
-
return holidayState
|
|
154
|
-
}
|
|
155
|
-
|
|
287
|
+
/**
|
|
288
|
+
* One refresh, deduplicated by `single`. The first call in a process waits for
|
|
289
|
+
* it (the page has a loading state); every later call serves the cached state
|
|
290
|
+
* and refreshes behind it, so an 8-second timeout never blocks the UI.
|
|
291
|
+
*/
|
|
292
|
+
function refreshHolidays() {
|
|
156
293
|
return single('holidays', async () => {
|
|
157
294
|
holidayState.attemptAtMs = nowFn()
|
|
158
295
|
const year = beijingParts(nowFn()).year
|
|
@@ -160,13 +297,54 @@ export function createDataLayer(config, deps = {}) {
|
|
|
160
297
|
holidayState.years = years
|
|
161
298
|
holidayState.merged = mergeHolidays(years)
|
|
162
299
|
holidayState.error = years.find((entry) => entry.error)?.error || null
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
300
|
+
// "Unpublished" is a definitive answer from the source, not a failure: it
|
|
301
|
+
// earns the full TTL instead of being retried every 15 minutes all year.
|
|
302
|
+
const settled = years.every(
|
|
303
|
+
(entry) => entry.status === 'fresh' || entry.status === 'unpublished',
|
|
304
|
+
)
|
|
305
|
+
holidayFailures = settled ? 0 : holidayFailures + 1
|
|
306
|
+
// Only a settled set earns the long TTL; anything else is retried after
|
|
307
|
+
// the shorter gate instead of being trusted for a week.
|
|
308
|
+
holidayState.fetchedAtMs = settled ? nowFn() : 0
|
|
309
|
+
if (years.some((entry) => entry.status === 'fresh')) persistHolidayCache()
|
|
166
310
|
return holidayState
|
|
167
311
|
})
|
|
168
312
|
}
|
|
169
313
|
|
|
314
|
+
function kickHolidayRefresh() {
|
|
315
|
+
refreshHolidays().catch(() => {
|
|
316
|
+
// The next build reports the failure through holidayWarnings().
|
|
317
|
+
})
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
async function loadHolidays(force) {
|
|
321
|
+
await hydrateHolidayCache()
|
|
322
|
+
if (!config.holidayRefresh) {
|
|
323
|
+
if (holidayState.years.length === 0) {
|
|
324
|
+
const year = beijingParts(nowFn()).year
|
|
325
|
+
holidayState.years = [year, year + 1].map(snapshotHolidayYear)
|
|
326
|
+
holidayState.merged = mergeHolidays(holidayState.years)
|
|
327
|
+
} else {
|
|
328
|
+
// Sync is off, but a calendar from an earlier sync is still real data —
|
|
329
|
+
// label it honestly instead of pretending it is a fresh fetch.
|
|
330
|
+
holidayState.years = holidayState.years.map((entry) => ({ ...entry, status: 'cached' }))
|
|
331
|
+
}
|
|
332
|
+
return holidayState
|
|
333
|
+
}
|
|
334
|
+
if (holidayState.years.length === 0) seedPendingHolidayYears()
|
|
335
|
+
const nowMs = nowFn()
|
|
336
|
+
const fresh =
|
|
337
|
+
holidayState.fetchedAtMs > 0 && nowMs - holidayState.fetchedAtMs < HOLIDAY_TTL_MS
|
|
338
|
+
if (!force && fresh) return holidayState
|
|
339
|
+
if (!force) {
|
|
340
|
+
const retryMs = holidayFailures > 0 && holidayFailures <= 3 ? 60 * 1000 : HOLIDAY_RETRY_MS
|
|
341
|
+
if (nowMs - holidayState.attemptAtMs >= retryMs) kickHolidayRefresh()
|
|
342
|
+
return holidayState
|
|
343
|
+
}
|
|
344
|
+
await refreshHolidays()
|
|
345
|
+
return holidayState
|
|
346
|
+
}
|
|
347
|
+
|
|
170
348
|
async function loadPrices(rawCurrency, force) {
|
|
171
349
|
const currency = normalizeCurrency(rawCurrency)
|
|
172
350
|
const ttl = config.refreshMinutes > 0 ? config.refreshMinutes * 60000 : 0
|
|
@@ -208,15 +386,29 @@ export function createDataLayer(config, deps = {}) {
|
|
|
208
386
|
})
|
|
209
387
|
}
|
|
210
388
|
|
|
389
|
+
function clockOf(ms) {
|
|
390
|
+
if (!Number.isFinite(ms)) return null
|
|
391
|
+
const parts = beijingParts(ms)
|
|
392
|
+
return `${String(parts.hour).padStart(2, '0')}:${String(parts.minute).padStart(2, '0')}`
|
|
393
|
+
}
|
|
394
|
+
|
|
211
395
|
function holidayWarnings() {
|
|
212
396
|
const warnings = []
|
|
213
397
|
for (const entry of holidayState.years) {
|
|
398
|
+
if (entry.status === 'pending') continue
|
|
214
399
|
if (entry.status === 'unpublished') {
|
|
215
400
|
warnings.push(`${entry.year} 年法定节假日数据尚未发布,节假日期间可能被误判为高峰`)
|
|
216
401
|
} else if (entry.status === 'unavailable') {
|
|
217
402
|
warnings.push(
|
|
218
403
|
`${entry.year} 年节假日数据获取失败${entry.error ? `(${entry.error})` : ''},按无节假日计算`,
|
|
219
404
|
)
|
|
405
|
+
} else if (entry.status === 'stale') {
|
|
406
|
+
const at = clockOf(entry.updatedAtMs)
|
|
407
|
+
warnings.push(
|
|
408
|
+
`${entry.year} 年节假日本次刷新失败${entry.error ? `(${entry.error})` : ''},沿用${
|
|
409
|
+
at ? ` ${at} ` : '上次'
|
|
410
|
+
}成功获取的数据;节假日判断仍然有效`,
|
|
411
|
+
)
|
|
220
412
|
}
|
|
221
413
|
}
|
|
222
414
|
if (
|
|
@@ -289,12 +481,18 @@ export function createDataLayer(config, deps = {}) {
|
|
|
289
481
|
source: entry.source,
|
|
290
482
|
updatedAtMs: entry.updatedAtMs,
|
|
291
483
|
})),
|
|
484
|
+
// Date -> holiday name, so the browser can price a past turn at the
|
|
485
|
+
// period that applied when it ended (weekend/holiday aware).
|
|
486
|
+
dates: holidays,
|
|
292
487
|
},
|
|
293
488
|
warnings,
|
|
294
489
|
config: {
|
|
295
490
|
tool: config.tool,
|
|
296
491
|
currency: config.currency,
|
|
297
492
|
refreshMinutes: config.refreshMinutes,
|
|
493
|
+
// The settings page mirrors every writable switch from here, so a
|
|
494
|
+
// written value must come back or the checkbox would snap back.
|
|
495
|
+
holidayRefresh: config.holidayRefresh,
|
|
298
496
|
},
|
|
299
497
|
}
|
|
300
498
|
}
|
package/src/options.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers behind the settings switches.
|
|
3
|
+
*
|
|
4
|
+
* The browser half and the Host half both need to agree on what a switch may
|
|
5
|
+
* write, but only the Host can persist it. Keeping the rule here (instead of
|
|
6
|
+
* inline in index.js) gives it one testable definition.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const ROW_ID = 'deepseek-pricing'
|
|
10
|
+
export const PACKAGE_NAME = 'dsh-deepseek-pricing'
|
|
11
|
+
export const REFRESH_MINUTES_MAX = 1440
|
|
12
|
+
|
|
13
|
+
function clampMinutes(value) {
|
|
14
|
+
const number = Number(value)
|
|
15
|
+
if (!Number.isFinite(number)) return null
|
|
16
|
+
return Math.min(REFRESH_MINUTES_MAX, Math.max(0, Math.round(number)))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The writable subset of the row config.
|
|
21
|
+
*
|
|
22
|
+
* `currency` is deliberately absent: the browser owns it as a display
|
|
23
|
+
* preference (localStorage plus `?currency=`), so writing it into the profile
|
|
24
|
+
* patch would let the price table and the model-facing tool disagree.
|
|
25
|
+
*/
|
|
26
|
+
export function sanitizeConfigPatch(raw) {
|
|
27
|
+
const source = raw && typeof raw === 'object' ? raw : {}
|
|
28
|
+
const patch = {}
|
|
29
|
+
if (typeof source.tool === 'boolean') patch.tool = source.tool
|
|
30
|
+
if (typeof source.holidayRefresh === 'boolean') patch.holidayRefresh = source.holidayRefresh
|
|
31
|
+
if (source.refreshMinutes !== undefined && source.refreshMinutes !== null) {
|
|
32
|
+
const minutes = clampMinutes(source.refreshMinutes)
|
|
33
|
+
if (minutes !== null) patch.refreshMinutes = minutes
|
|
34
|
+
}
|
|
35
|
+
return patch
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Find our own Loader entry. A row declared by a bundle patch can surface as
|
|
40
|
+
* `patchId`, `id`, or only `options.id`, depending on the Loader version, so
|
|
41
|
+
* every address we know is accepted and the package name is the fallback.
|
|
42
|
+
*/
|
|
43
|
+
export function findOwnEntry(editor) {
|
|
44
|
+
const entries = (editor && editor.entries && editor.entries()) || []
|
|
45
|
+
for (const entry of entries) {
|
|
46
|
+
if (!entry) continue
|
|
47
|
+
const options = entry.options || {}
|
|
48
|
+
const ids = [entry.patchId, entry.id, options.id]
|
|
49
|
+
const names = [entry.name, options.name]
|
|
50
|
+
if (ids.includes(ROW_ID) || names.includes(PACKAGE_NAME) || names.includes(ROW_ID)) {
|
|
51
|
+
return entry
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return null
|
|
55
|
+
}
|