dsh-remote-plugin 0.8.0-rc.3 → 0.8.0-rc.4

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.
@@ -0,0 +1,47 @@
1
+ // Only public peak-pricing settings are projected; account configuration stays on the host.
2
+ export function peakReminderSchedule(config, now = Date.now()) {
3
+ const base = { ok: true, schema: 1, source: 'dsh-cost-meter', generatedAt: now, validUntil: now + 7 * 86400000 }
4
+ if (config?.peakEnabled === false || config?.peakAlertEnabled === false) return { ...base, available: true, enabled: false, events: [] }
5
+ const windows = config?.peakWindows, holidays = config?.peakHolidays
6
+ const effectiveAt = Date.parse(config?.peakEffectiveAt || '')
7
+ const validDate = d => typeof d === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(d) && Number.isFinite(Date.parse(d + 'T00:00:00Z')) && new Date(d + 'T00:00:00Z').toISOString().slice(0,10) === d
8
+ const ahead = config?.peakAlertAhead ?? 2, target = config?.peakAlertTarget ?? 'both'
9
+ if (config?.peakEnabled !== true || !Array.isArray(windows) || windows.length > 24 || !Array.isArray(holidays) || holidays.length > 366
10
+ || !Number.isFinite(effectiveAt) || !Number.isInteger(ahead) || ahead < 1 || ahead > 30 || !['peak','offpeak','both'].includes(target)
11
+ || windows.some(w => !Number.isInteger(w?.start) || w.start < 0 || w.start > 23 || !Number.isInteger(w?.end) || w.end < 0 || w.end > 24)
12
+ || holidays.some(d => !validDate(d))) {
13
+ return { ...base, available: false, code: 'unsupported-policy', events: [] }
14
+ }
15
+ const excluded = new Set(holidays)
16
+ const isPeak = at => {
17
+ if (at < effectiveAt) return false
18
+ const beijing = new Date(at + 8 * 3600000), day = beijing.getUTCDay()
19
+ if (day === 0 || day === 6 || excluded.has(beijing.toISOString().slice(0,10))) return false
20
+ const hour = new Date(at).getUTCHours()
21
+ return windows.some(w => w.start < w.end ? hour >= w.start && hour < w.end : hour >= w.start || hour < w.end)
22
+ }
23
+ const candidates = new Set([effectiveAt]), midnight = Math.floor(now / 86400000) * 86400000
24
+ for (let day = -1; day <= 8; day++) {
25
+ const start = midnight + day * 86400000
26
+ candidates.add(start + 16 * 3600000)
27
+ for (const w of windows) { candidates.add(start + w.start * 3600000); candidates.add(start + w.end * 3600000) }
28
+ }
29
+ const events = [...candidates].sort((a,b) => a-b).flatMap(at => {
30
+ const intoPeak = isPeak(at)
31
+ if (at < now - 30 * 60000 || at > base.validUntil || isPeak(at - 1) === intoPeak || target !== 'both' && (target === 'peak') !== intoPeak) return []
32
+ return [{ id: at + ':' + (intoPeak ? 'peak' : 'offpeak'), at, notifyAt: at - ahead * 60000, intoPeak }]
33
+ }).slice(0,64)
34
+ return { ...base, available: true, enabled: true, aheadMinutes: ahead, target, timezone: 'Asia/Shanghai', events }
35
+ }
36
+
37
+ export async function readPeakReminders(ctx) {
38
+ let service
39
+ try { service = ctx.get?.('costMeter') } catch {}
40
+ if (!service || typeof service.getState !== 'function') return { status: 200, body: { ok: true, schema: 1, available: false, code: 'not-installed' } }
41
+ let timer
42
+ try {
43
+ const state = await Promise.race([Promise.resolve().then(() => service.getState()), new Promise((_, reject) => { timer = setTimeout(() => reject(Error('timeout')), 20000) })])
44
+ return { status: 200, body: peakReminderSchedule(state?.config) }
45
+ } catch { return { status: 502, body: { ok: false, code: 'peak-policy-unavailable' } } }
46
+ finally { clearTimeout(timer) }
47
+ }
@@ -0,0 +1,89 @@
1
+ /* Shared bounded announcement schema. Embedded into the single-file gateway. */
2
+ 'use strict';
3
+ function createAnnouncementForms() {
4
+ const string = (value, max) => typeof value === 'string' && value.trim().length <= max ? value.trim() : ''
5
+ const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))
6
+ function normalize(value, announcementId) {
7
+ if (!value || typeof value !== 'object') return null
8
+ const id = string(value.id || announcementId, 120)
9
+ const legacy = !Array.isArray(value.questions) && !value.type || value.legacy === true
10
+ const rows = Array.isArray(value.questions) ? value.questions : [{ ...value, id: 'answer' }]
11
+ if (!id || !rows.length || rows.length > 8) return null
12
+ const ids = new Set(), questions = []
13
+ for (const row of rows) {
14
+ const questionId = string(row?.id, 120), question = string(row?.question || row?.label, 300), type = row?.type || 'single'
15
+ if (!questionId || ids.has(questionId) || !question || !['single','multiple','text'].includes(type)) return null
16
+ ids.add(questionId)
17
+ const required = row.required !== false, options = [], seen = new Set()
18
+ if (type !== 'text') {
19
+ if (!Array.isArray(row.options) || row.options.length < 2 || row.options.length > 12) return null
20
+ for (const option of row.options) {
21
+ const optionId = string(option?.id, 120), label = string(option?.label, 200)
22
+ if (!optionId || !label || seen.has(optionId)) return null
23
+ seen.add(optionId); options.push({ id: optionId, label, description: string(option.description || '', 500) })
24
+ }
25
+ }
26
+ const min = type === 'text' ? (required ? 1 : 0) : row.minSelections ?? row.min ?? (required ? 1 : 0)
27
+ const max = type === 'text' ? row.maxLength ?? row.max ?? 600 : type === 'single' ? 1 : row.maxSelections ?? row.max ?? options.length
28
+ if (!Number.isInteger(min) || !Number.isInteger(max) || min < 0 || max < Math.max(1, min) || max > (type === 'text' ? 1200 : options.length)) return null
29
+ questions.push({ id: questionId, question, type, required, options, min, max, placeholder: string(row.placeholder || '', 200) })
30
+ }
31
+ return { id, legacy: !!legacy, question: string(value.question || value.title, 300) || questions[0].question,
32
+ options: questions.length === 1 ? questions[0].options : [], questions }
33
+ }
34
+ function validate(poll, payload) {
35
+ if (!poll) return { error: 'poll not found' }
36
+ const rows = poll.legacy && typeof payload.optionId === 'string' ? [{ questionId: poll.questions[0].id, optionIds: [payload.optionId] }] : payload.answers
37
+ if (!Array.isArray(rows) || rows.length > poll.questions.length) return { error: 'invalid answers' }
38
+ const byId = new Map()
39
+ for (const row of rows) {
40
+ if (!row || typeof row.questionId !== 'string' || byId.has(row.questionId) || !poll.questions.some(q => q.id === row.questionId)) return { error: 'invalid question' }
41
+ byId.set(row.questionId, row)
42
+ }
43
+ const answers = []
44
+ for (const q of poll.questions) {
45
+ const row = byId.get(q.id)
46
+ if (q.type === 'text') {
47
+ const value = row?.text ?? ''
48
+ if (typeof value !== 'string' || value.trim().length < q.min || value.trim().length > q.max || /[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(value)) return { error: 'invalid text', questionId: q.id }
49
+ if (value.trim()) answers.push({ questionId: q.id, text: value.trim() })
50
+ } else {
51
+ const values = row?.optionIds ?? []
52
+ if (!Array.isArray(values) || values.length < q.min || values.length > q.max || new Set(values).size !== values.length) return { error: 'invalid selection count', questionId: q.id }
53
+ if (values.some(id => typeof id !== 'string' || !q.options.some(option => option.id === id))) return { error: 'poll option not found', questionId: q.id }
54
+ if (values.length) answers.push({ questionId: q.id, optionIds: q.options.filter(option => values.includes(option.id)).map(option => option.id) })
55
+ }
56
+ }
57
+ if (!answers.length) return { error: 'answer required' }
58
+ return poll.legacy ? { optionId: answers[0].optionIds[0] } : { answers }
59
+ }
60
+ function encode(announcementId, pollId, answer) {
61
+ const message = 'POLL ' + JSON.stringify({ announcementId, pollId, ...answer })
62
+ return message.length <= 2000 ? message : null
63
+ }
64
+ function render(poll, answers = [], disabled = false, english = false) {
65
+ return poll.questions.map((q, index) => {
66
+ const answer = answers.find(row => row.questionId === q.id), off = disabled ? ' disabled' : ''
67
+ const label = q.question + (q.required ? ' *' : '')
68
+ const body = q.type === 'text'
69
+ ? `<textarea aria-label="${esc(label)}" id="announcement-field-${index}" maxlength="${q.max}" rows="2" placeholder="${esc(q.placeholder)}"${q.required ? ' required' : ''}${off}>${esc(answer?.text || '')}</textarea>`
70
+ : q.options.map(option => `<label class="announcement-poll-option"><input type="${q.type === 'multiple' ? 'checkbox' : 'radio'}" name="announcement-q-${index}" value="${esc(option.id)}"${answer?.optionIds?.includes(option.id) ? ' checked' : ''}${off}><span><strong>${esc(option.label)}</strong>${option.description ? `<small>${esc(option.description)}</small>` : ''}</span></label>`).join('')
71
+ const hint = q.type === 'multiple' ? (english ? `Choose ${q.min}–${q.max}` : `选择 ${q.min}–${q.max} 项`) : q.type === 'text' ? (english ? `Up to ${q.max} characters` : `最多 ${q.max} 字`) : ''
72
+ return `<fieldset class="announcement-form-field" data-form-question="${esc(q.id)}"><legend>${esc(label)}</legend>${hint ? `<p class="announcement-form-hint">${esc(hint)}</p>` : ''}${body}</fieldset>`
73
+ }).join('')
74
+ }
75
+ function read(panel, poll) {
76
+ const fields = [...panel.querySelectorAll('[data-form-question]')]
77
+ return poll.questions.map(q => {
78
+ const field = fields.find(el => el.dataset.formQuestion === q.id)
79
+ return q.type === 'text' ? { questionId: q.id, text: field?.querySelector('textarea')?.value || '' }
80
+ : { questionId: q.id, optionIds: [...(field?.querySelectorAll('input:checked') || [])].map(el => el.value) }
81
+ })
82
+ }
83
+ return { normalize, validate, encode, render, read }
84
+ }
85
+ ;(function(root) {
86
+ const api = createAnnouncementForms()
87
+ if (typeof module !== 'undefined' && module.exports) module.exports = api
88
+ else root.DshAnnouncementForms = api
89
+ })(typeof window === 'undefined' ? globalThis : window)