@witbitz/sdk 4.3.0 → 4.5.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/README.md +2 -2
- package/a2aCore.js +41 -5
- package/accountErase.js +15 -4
- package/accountIndexDoc.js +24 -7
- package/accountRecord.js +6 -2
- package/accountStores.js +21 -5
- package/acctV2App.js +111 -12
- package/acctV2Client.js +11 -1
- package/acctV2UiCore.js +27 -7
- package/agentDoorTools.js +28 -0
- package/awsKey.js +3 -1
- package/backupRecord.js +3 -0
- package/chatLock.js +16 -0
- package/cloudDevicePins.js +2 -2
- package/codeAttachments.js +101 -0
- package/codeCache.js +173 -0
- package/codeCloud.js +2 -2
- package/codeComputers.js +9 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeModes.js +2 -0
- package/codeProgress.js +54 -0
- package/codeSent.js +109 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +46 -5
- package/connections.js +37 -20
- package/decrypt.html +69 -9
- package/deviceAttest.js +9 -3
- package/eraseFile.js +15 -0
- package/idb.js +19 -3
- package/idbSeal.js +5 -2
- package/inviteReceive.js +44 -0
- package/inviteSend.js +8 -2
- package/jobAgents.js +2 -2
- package/keptMerge.js +9 -2
- package/l1-worker-src.js +1 -1
- package/l1-worker.js +122 -43
- package/laneAssociation.js +78 -0
- package/laneConfig.js +4 -3
- package/laneLinkCore.js +9 -0
- package/ledgerView.js +30 -4
- package/manifest.json +112 -87
- package/memberChange.js +4 -2
- package/mirrorBatch.js +47 -0
- package/offlineBundle.js +21 -0
- package/opRouting.js +10 -0
- package/package.json +27 -2
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/protectedLocal.js +52 -13
- package/reactionHolders.js +86 -0
- package/removedMessage.js +1 -1
- package/roomEmbed.js +111 -0
- package/roomIntake.js +324 -0
- package/roomName.js +1 -1
- package/roomRoster.js +30 -7
- package/rosterCount.js +6 -3
- package/scheduleNext.js +60 -0
- package/sdkA2A.js +200 -42
- package/sdkAccount.js +88 -18
- package/sdkAccountDoc.js +13 -5
- package/sdkAccountSections.js +172 -23
- package/sdkAgui.js +33 -6
- package/sdkBackup.js +53 -11
- package/sdkBackupV2.js +15 -3
- package/sdkCloudDevice.js +20 -5
- package/sdkComputers.js +695 -65
- package/sdkDictation.js +115 -25
- package/sdkErase.js +12 -5
- package/sdkExports.js +19 -8
- package/sdkInvitations.js +4 -2
- package/sdkKeptAgent.js +19 -3
- package/sdkKeptIntake.js +100 -0
- package/sdkLaneLink.js +8 -9
- package/sdkPlan.js +4 -2
- package/sdkRekey.js +122 -22
- package/sdkReport.js +1 -1
- package/sdkSafeMedia.js +1 -1
- package/sdkSchedules.js +8 -1
- package/sdkSpeech.js +32 -2
- package/sdkTemporaryRooms.js +124 -0
- package/sdkTurn.js +12 -4
- package/sdkVault.js +66 -10
- package/sentinelRelease.js +1 -0
- package/sharedViews.js +34 -4
- package/siri.js +140 -9
- package/spaceClient.js +112 -17
- package/spaceEmailGate.js +2 -2
- package/spaceExport.js +50 -5
- package/spaceFork.js +15 -7
- package/spaceTemplates.js +99 -0
- package/speechOut.js +21 -5
- package/store.js +134 -27
- package/sw-notif-core.js +11 -8
- package/tapTrail.js +58 -0
- package/turnVerdict.js +1 -0
- package/usageReceipts.js +12 -5
- package/vault-core.js +568 -126
- package/vault-kit.mjs +3 -3
- package/vault-screens.js +30 -18
- package/vaultAtRest.js +38 -6
- package/vaultCoreLock.js +3 -1
- package/vaultCorePush.js +58 -7
- package/vaultKeep.js +9 -3
- package/vaultWorkerHost.js +32 -7
- package/witbitz-admin.d.ts +3 -0
- package/witbitz-admin.mjs +12 -11
- package/witbitz-sdk.d.ts +170 -43
- package/witbitz-sdk.js +833 -203
package/roomIntake.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
// roomIntake.js — THE MESSAGE INTAKE, the account's side (docs/message-intake.md). Producers that do not hold the
|
|
2
|
+
// message room's key (the Sentinel's Siri and A2A doors, a cloud bot, a webhook's result) WRITE to it and never read it:
|
|
3
|
+
// each holds a drop address (a random token minted here) and the intake's PUBLIC key, seals a box and drops it
|
|
4
|
+
// (op 'intakedrop', keyless). A device of the account reads the waiting boxes, opens them with the intake's private key,
|
|
5
|
+
// and turns each into an ordinary room message (roomMail) — so handlers, claims, retries and purge are roomMail's.
|
|
6
|
+
//
|
|
7
|
+
// THE INTAKE KEY is generated once and kept IN the message room, as its state doc `intakekey` — only holders of the
|
|
8
|
+
// room's key read it (the account's devices; in the hosted app, through the vault's worker). Nothing new travels with the
|
|
9
|
+
// account: the message room's pointer already does. (The design first said "derived from the room key"; a key pair kept
|
|
10
|
+
// in the room gives the same property and needs no curve arithmetic in the page.)
|
|
11
|
+
//
|
|
12
|
+
// THE REGISTRY: the server keeps only token HASHES (op 'intakereg'); the labels, kinds and allowed targets live in the
|
|
13
|
+
// message room's state doc `intake`, which the server checks nothing against and devices check everything against.
|
|
14
|
+
//
|
|
15
|
+
// A BOX BECOMES A MESSAGE ONCE: its row id is `in.<hash 10>.<n>`; one atomic write puts the message AND a mark
|
|
16
|
+
// (collection `inmark`, same id), both ifVersion null — a second device gets 409, and the mark outlives the message
|
|
17
|
+
// (handled and deleted) until the box has left the intake, so a stale read never converts it again. A small box is copied into the row and acknowledged at once; a big one (body over
|
|
18
|
+
// INLINE_MAX — a row holds 16 KB) rides BY REFERENCE ({ box: { drop, n } }; the handler calls body(msg)) and is
|
|
19
|
+
// acknowledged once its message has been handled and left the room. Box contents are UNTRUSTED data, never instructions.
|
|
20
|
+
import { genRecipientKey, openBox } from './e2ee.js'
|
|
21
|
+
|
|
22
|
+
export const INLINE_MAX = 12_000
|
|
23
|
+
export const INTAKE_PAGES_MAX = 8 // pages one collect reads past boxes that must stay (a 10 MB mail is ≤ 6 boxes)
|
|
24
|
+
const KEY_DOC = 'intakekey'
|
|
25
|
+
const REG_DOC = 'intake'
|
|
26
|
+
const KIND_RE = /^[a-z][a-z0-9:_-]{0,39}$/
|
|
27
|
+
// Kinds a producer's boxes may be besides its own (and `<kind>:…`): a mail address's attachment parts come as `mailfile`
|
|
28
|
+
// (infra/cloud-computer/sentinel/mail.mjs inbound, in the live Sentinel image) — refused before, so no attachment ever arrived
|
|
29
|
+
// (docs/state-machines.md I44, found with W#2).
|
|
30
|
+
const RELATED_KINDS = Object.freeze({ mail: Object.freeze(['mailfile']) })
|
|
31
|
+
const MSG = 'msg' // roomMail's collection
|
|
32
|
+
export const SEALED = 'sealed:' // roomMail's sealed-message kind prefix (held equal by spaces/test/roomMailSealed.test.mjs)
|
|
33
|
+
export const MARK = 'inmark' // one row per converted box, same id as its message
|
|
34
|
+
export const MARK_KEEP_MS = 60 * 60_000 // a mark outlives any device's stale read of the intake
|
|
35
|
+
const b64u = (u8) => btoa(String.fromCharCode(...u8)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
36
|
+
export async function dropHash(token) { return b64u(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(String(token))))) }
|
|
37
|
+
const unb64u = (s) => Uint8Array.from(atob(String(s).replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (String(s).length % 4)) % 4)), (c) => c.charCodeAt(0))
|
|
38
|
+
/** A producer's drop token, DERIVED from the intake's private key and the producer's id (HMAC-SHA256) — so any device of
|
|
39
|
+
* the account recomputes the same address for 'siri' or one A2A peer, and nothing new has to be stored or synced. */
|
|
40
|
+
export async function deriveDropToken(priv, id) {
|
|
41
|
+
const k = await crypto.subtle.importKey('raw', unb64u(priv.d), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
|
|
42
|
+
return b64u(new Uint8Array(await crypto.subtle.sign('HMAC', k, new TextEncoder().encode('witbitz intake drop v1|' + String(id)))))
|
|
43
|
+
}
|
|
44
|
+
/** The producer a converted message came from, by its row id (`in.<hash 10>.<n>`) → the hash prefix, or ''. */
|
|
45
|
+
export const dropPrefixOf = (msg) => { const m = /^in\.([A-Za-z0-9_-]{10})\.\d+$/.exec(String((msg && msg.id) || '')); return m ? m[1] : '' }
|
|
46
|
+
export const LEAVE_FOR_MS = 5 * 60_000 // a box a cloud device should take (io.leaveFor) waits this long for it
|
|
47
|
+
export const intakeRowId = (hash, n) => `in.${String(hash).slice(0, 10).replace(/[^A-Za-z0-9_-]/g, '_')}.${n}`
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param io {{
|
|
51
|
+
* room: () => Promise<string|null>, ensureRoom: () => Promise<string>,
|
|
52
|
+
* state: (room, name, patch?, ifV?) => Promise<{ status, v, state }>, // the message room's state docs
|
|
53
|
+
* intakeReg: (room, ops) => Promise<object>, intake: (room, from?: { drop, n }) => Promise<{ status, boxes, more }>,
|
|
54
|
+
* intakeAck: (room, items) => Promise<object>,
|
|
55
|
+
* data: (room, ops) => Promise<{ status }>, // the room's data op (atomic; 409 = a condition failed)
|
|
56
|
+
* rowsOf: (collection) => Map<id, { row, v }>, // roomMail's fold (roomMail.rowsOf)
|
|
57
|
+
* broadcast?: (kind) => boolean, // a kind every device runs (no claim): see collect
|
|
58
|
+
* now?: () => number,
|
|
59
|
+
* onError?: (where, err) => void,
|
|
60
|
+
* }}
|
|
61
|
+
*/
|
|
62
|
+
export function makeRoomIntake(io) {
|
|
63
|
+
const say = (w, e) => { try { io.onError && io.onError(w, e) } catch { /* */ } }
|
|
64
|
+
const now = io.now || Date.now
|
|
65
|
+
let keyCache = null, regCache = null
|
|
66
|
+
let lastTo = null // the room the newest box this device opened was for — a tapped "New message for your assistant" opens it (space.js openIntakeTap)
|
|
67
|
+
let emptyUntil = 0 // no producer registered: the registry is read again only after this (a mint here resets it)
|
|
68
|
+
const EMPTY_RECHECK_MS = 5 * 60_000
|
|
69
|
+
|
|
70
|
+
// strict: a read that FAILED throws — "no intake" and "could not read it" are different answers (side sweep: an account erase
|
|
71
|
+
// took an unread key for no mail addresses and listed them as removed)
|
|
72
|
+
async function intakeKey({ create = false, strict = false } = {}) {
|
|
73
|
+
if (keyCache) return keyCache
|
|
74
|
+
const room = create ? await io.ensureRoom() : await io.room()
|
|
75
|
+
if (!room) return null
|
|
76
|
+
for (let i = 0; i < 4; i++) {
|
|
77
|
+
const r = await io.state(room, KEY_DOC)
|
|
78
|
+
if (strict && (!r || (r.status !== 200 && r.status !== 404))) throw new Error('intake: the key could not be read')
|
|
79
|
+
if (!r || r.status !== 200) return null
|
|
80
|
+
const st = r.state
|
|
81
|
+
if (st && st.pub && st.priv) { keyCache = { room, pub: st.pub, priv: st.priv }; return keyCache }
|
|
82
|
+
if (!create) return null
|
|
83
|
+
const k = await genRecipientKey()
|
|
84
|
+
const w = await io.state(room, KEY_DOC, { pub: k.publicJwk, priv: k.privateJwk }, Number(r.v) || 0) // another device made one first → 409, read theirs
|
|
85
|
+
if (w && w.status === 200) { keyCache = { room, pub: k.publicJwk, priv: k.privateJwk }; return keyCache }
|
|
86
|
+
}
|
|
87
|
+
return null
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function registry(room) {
|
|
91
|
+
const r = await io.state(room, REG_DOC)
|
|
92
|
+
if (!r || r.status !== 200) return null
|
|
93
|
+
regCache = { v: Number(r.v) || 0, drops: (r.state && r.state.drops) || {} }
|
|
94
|
+
return regCache
|
|
95
|
+
}
|
|
96
|
+
async function editRegistry(room, change) {
|
|
97
|
+
for (let i = 0; i < 6; i++) {
|
|
98
|
+
const cur = await registry(room); if (!cur) throw new Error('intake: the registry could not be read')
|
|
99
|
+
const drops = change({ ...cur.drops })
|
|
100
|
+
const w = await io.state(room, REG_DOC, { drops }, cur.v)
|
|
101
|
+
if (w && w.status === 200) { regCache = { v: cur.v + 1, drops }; return drops }
|
|
102
|
+
}
|
|
103
|
+
throw new Error('intake: the registry is busy')
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A drop address for one producer. `kind` = what its boxes are (their messages' kind, or a prefix of it); `target` =
|
|
107
|
+
* the one room its boxes may address, or 'any'. → { token, hash, pub, room } — hand `token` + `pub` + `room` to the
|
|
108
|
+
* producer; nothing here can read back the token. */
|
|
109
|
+
async function mint({ label, kind, target = 'any' }) {
|
|
110
|
+
if (typeof kind !== 'string' || !KIND_RE.test(kind)) throw new Error('intake: a producer needs a kind')
|
|
111
|
+
const key = await intakeKey({ create: true }); if (!key) throw new Error('intake: no intake key')
|
|
112
|
+
const tok = new Uint8Array(32); crypto.getRandomValues(tok)
|
|
113
|
+
const token = b64u(tok), hash = await dropHash(token)
|
|
114
|
+
await editRegistry(key.room, (d) => ({ ...d, [hash]: { label: String(label || kind).slice(0, 80), kind, target: String(target || 'any').slice(0, 64), created: Date.now() } }))
|
|
115
|
+
const r = await io.intakeReg(key.room, [{ op: 'add', drop: hash }])
|
|
116
|
+
if (!r || r.status !== 200) throw new Error('intake: the drop address was not registered' + (r && r.error ? ` (${r.error})` : ''))
|
|
117
|
+
emptyUntil = 0
|
|
118
|
+
return { token, hash, pub: key.pub, room: key.room }
|
|
119
|
+
}
|
|
120
|
+
/** The drop address of a STABLE producer id ('siri', 'a2a:<lane>:<peer>'): derived from the intake key, registered once
|
|
121
|
+
* (with its kind and target in the sealed registry), the same on every device. → { token, hash, pub, room } */
|
|
122
|
+
async function address({ id, label, kind, target = 'any' }) {
|
|
123
|
+
if (typeof id !== 'string' || !id) throw new Error('intake: an address needs an id')
|
|
124
|
+
if (typeof kind !== 'string' || !KIND_RE.test(kind)) throw new Error('intake: a producer needs a kind')
|
|
125
|
+
const key = await intakeKey({ create: true }); if (!key) throw new Error('intake: no intake key')
|
|
126
|
+
const token = await deriveDropToken(key.priv, id), hash = await dropHash(token)
|
|
127
|
+
const want = { label: String(label || kind).slice(0, 80), kind, target: String(target || 'any').slice(0, 64), id }
|
|
128
|
+
const cur = await registry(key.room)
|
|
129
|
+
const have = cur && cur.drops[hash]
|
|
130
|
+
if (!(have && have.kind === want.kind && have.target === want.target && have.label === want.label && have.id === id)) {
|
|
131
|
+
await editRegistry(key.room, (d) => ({ ...d, [hash]: { ...want, created: (have && have.created) || Date.now() } }))
|
|
132
|
+
}
|
|
133
|
+
const r = await io.intakeReg(key.room, [{ op: 'add', drop: hash }]) // idempotent on the server
|
|
134
|
+
if (!r || r.status !== 200) throw new Error('intake: the drop address was not registered' + (r && r.error ? ` (${r.error})` : ''))
|
|
135
|
+
emptyUntil = 0
|
|
136
|
+
return { token, hash, pub: { x: key.pub.x, y: key.pub.y }, room: key.room }
|
|
137
|
+
}
|
|
138
|
+
/** The drop address a stable producer id ALREADY has — LOOKUP ONLY: no intake key is made, nothing is registered (a Space
|
|
139
|
+
* deleted without ever having had mail gets no address on its way out — I44 / W#3). → { token, hash, pub, room } | null */
|
|
140
|
+
async function lookup({ id }) {
|
|
141
|
+
if (typeof id !== 'string' || !id) return null
|
|
142
|
+
const key = await intakeKey(); if (!key) return null
|
|
143
|
+
const token = await deriveDropToken(key.priv, id), hash = await dropHash(token)
|
|
144
|
+
const cur = await registry(key.room)
|
|
145
|
+
if (!cur) throw new Error('intake: the registry could not be read')
|
|
146
|
+
return cur.drops[hash] ? { token, hash, pub: { x: key.pub.x, y: key.pub.y }, room: key.room } : null
|
|
147
|
+
}
|
|
148
|
+
/** Every stable producer registered in the CURRENT message room's intake, with its drop address → [{ id, kind, target,
|
|
149
|
+
* label, token, hash, pub, room }] (I44 / W#6: what a message-room switch must carry to the new intake). */
|
|
150
|
+
async function addresses() {
|
|
151
|
+
const key = await intakeKey({ strict: true }); if (!key) return []
|
|
152
|
+
const cur = await registry(key.room); if (!cur) throw new Error('intake: the registry could not be read')
|
|
153
|
+
const out = []
|
|
154
|
+
for (const [hash, e] of Object.entries(cur.drops)) {
|
|
155
|
+
if (!e || typeof e.id !== 'string' || !e.id) continue
|
|
156
|
+
const token = await deriveDropToken(key.priv, e.id)
|
|
157
|
+
if (await dropHash(token) !== hash) continue
|
|
158
|
+
out.push({ id: e.id, kind: e.kind, target: e.target, label: e.label, token, hash, pub: { x: key.pub.x, y: key.pub.y }, room: key.room })
|
|
159
|
+
}
|
|
160
|
+
return out
|
|
161
|
+
}
|
|
162
|
+
/** Cut a stable producer off by its id. */
|
|
163
|
+
async function revokeAddress(id) {
|
|
164
|
+
const key = await intakeKey(); if (!key) return false
|
|
165
|
+
return revoke(await dropHash(await deriveDropToken(key.priv, id)))
|
|
166
|
+
}
|
|
167
|
+
/** The registry entry of the producer a converted message came from (its label, kind, target, id) — or null. */
|
|
168
|
+
async function producerOf(msg) {
|
|
169
|
+
const pre = dropPrefixOf(msg); if (!pre) return null
|
|
170
|
+
const room = await io.room(); if (!room) return null
|
|
171
|
+
const find = (reg) => Object.entries(reg.drops).find(([h]) => h.slice(0, 10) === pre)
|
|
172
|
+
let hit = (regCache && regCache.drops) ? find(regCache) : null
|
|
173
|
+
if (!hit) { // not in the cached list (or none yet): read it now. Unreadable → THROW, so the message waits — null means a definite miss,
|
|
174
|
+
// and a handler drops on null (side sweep 2026-11-28: a fresh page's failed read dropped waiting mail)
|
|
175
|
+
const reg = await registry(room); if (!reg) throw new Error('intake: the registry could not be read')
|
|
176
|
+
hit = find(reg)
|
|
177
|
+
}
|
|
178
|
+
return hit ? { hash: hit[0], ...hit[1] } : null
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Cut a producer off: its address stops working and its waiting boxes go. */
|
|
182
|
+
async function revoke(hash) {
|
|
183
|
+
const room = await io.room(); if (!room) return false
|
|
184
|
+
const r = await io.intakeReg(room, [{ op: 'remove', drop: hash }])
|
|
185
|
+
await editRegistry(room, (d) => { delete d[hash]; return d })
|
|
186
|
+
return !!(r && r.status === 200)
|
|
187
|
+
}
|
|
188
|
+
async function producers() { const room = await io.room(); if (!room) return {}; const r = await registry(room); return r ? r.drops : {} }
|
|
189
|
+
|
|
190
|
+
const opened = new Map() // `drop:n` → the opened body of a big box this page read (body(msg) answers from here first)
|
|
191
|
+
async function openOne(key, b) {
|
|
192
|
+
let txt = null
|
|
193
|
+
try { txt = await openBox(b.box, key.priv) } catch { txt = null }
|
|
194
|
+
if (txt == null) return null
|
|
195
|
+
try { const o = JSON.parse(txt); return o && typeof o === 'object' ? o : null } catch { return null }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Read the waiting boxes and turn them into messages. Safe to run on several devices at once. → how many converted.
|
|
199
|
+
* Call it right after roomMail's pass, so the marks and messages it reads are fresh. */
|
|
200
|
+
// what happened to each waiting box (io.trace, optional) — said once per box and outcome, never its contents
|
|
201
|
+
const _traced = new Set()
|
|
202
|
+
const tr = (id, what) => { if (typeof io.trace !== 'function') return; const k = id + '|' + what; if (_traced.has(k)) return; _traced.add(k); try { io.trace('intake ' + String(id).slice(-14) + ': ' + what) } catch { /* */ } }
|
|
203
|
+
async function collect() {
|
|
204
|
+
const room = await io.room(); if (!room) return 0
|
|
205
|
+
if (now() < emptyUntil) return 0
|
|
206
|
+
const reg = await registry(room); if (!reg) return 0
|
|
207
|
+
if (!Object.keys(reg.drops).length) { emptyUntil = now() + EMPTY_RECHECK_MS; return 0 }
|
|
208
|
+
const key = await intakeKey(); if (!key) return 0
|
|
209
|
+
let r = await io.intake(room)
|
|
210
|
+
if (!r || r.status !== 200 || !Array.isArray(r.boxes)) return 0
|
|
211
|
+
const marks = io.rowsOf(MARK), msgs = io.rowsOf(MSG)
|
|
212
|
+
const t = now()
|
|
213
|
+
let converted = 0
|
|
214
|
+
const ackable = new Set() // `drop:n` that may go
|
|
215
|
+
// EVERY PAGE THAT A STAYING BOX HOLDS BACK (side sweep: mail-attachment-blocks-next-intake-page): a read carries ~5 M characters,
|
|
216
|
+
// a mail's attachment part ~3.6 M — and a converted part STAYS (its broadcast message lives 24 h, every device reads it by
|
|
217
|
+
// reference). The read always starts at the first box not acknowledged, so the next part was not read for 24 h, and its message
|
|
218
|
+
// was then born older than its lifetime: dropped, the mail waiting for ever. While the page holds a box that must stay, read on
|
|
219
|
+
// from after it (`from`, an older server ignores it and answers the same page: stop), up to INTAKE_PAGES_MAX pages.
|
|
220
|
+
const all = [], seenAt = new Set()
|
|
221
|
+
for (let page = 0; ; page++) {
|
|
222
|
+
const fresh = r.boxes.filter((b) => !seenAt.has(b.drop + ':' + b.n))
|
|
223
|
+
if (page && fresh.length !== r.boxes.length) break // `from` was not honoured: this page was read already
|
|
224
|
+
for (const b of fresh) { seenAt.add(b.drop + ':' + b.n); all.push(b) }
|
|
225
|
+
for (const b of fresh) {
|
|
226
|
+
const id = intakeRowId(b.drop, b.n), at = b.drop + ':' + b.n
|
|
227
|
+
if (marks.has(id)) { // converted already (here or on another device)
|
|
228
|
+
const mr = marks.get(id).row || {}
|
|
229
|
+
// ⛔ 10·D#1 (pass 10): THE CLOUD DEVICE'S CLAIM IS A LEASE. It marks a box before it delivers it; a worker killed in between
|
|
230
|
+
// (its 15-minute limit, an enclave restart) never delivers — and this device acked the box on the mark alone: the message
|
|
231
|
+
// was lost. A device mark with `until` and no `done` is a delivery in progress: the box stays; once the lease has passed
|
|
232
|
+
// the device is taken to have died and the mark goes, so a later pass delivers the box here (a rare repeat over a loss).
|
|
233
|
+
// A device mark with no `until` is an older device's: as before.
|
|
234
|
+
if (mr.by === 'cloud-device' && Number(mr.until) > 0 && !mr.done) {
|
|
235
|
+
if (t < Number(mr.until)) { tr(id, 'the cloud device is delivering it'); continue }
|
|
236
|
+
tr(id, 'the cloud device\'s claim ran out undelivered — taken back here')
|
|
237
|
+
try { await io.data(room, [{ op: 'del', collection: MARK, id }]) } catch (err) { say('intake:lease', err) }
|
|
238
|
+
continue
|
|
239
|
+
}
|
|
240
|
+
tr(id, 'converted already (mark there)')
|
|
241
|
+
const big = mr.big
|
|
242
|
+
if (!big || !msgs.has(id)) ackable.add(at) // small: copied into its message; big: its message was handled
|
|
243
|
+
continue
|
|
244
|
+
}
|
|
245
|
+
const prod = reg.drops[b.drop]
|
|
246
|
+
const o = prod ? await openOne(key, b) : null
|
|
247
|
+
const kindOk = o && typeof o.kind === 'string' && KIND_RE.test(o.kind) && (o.kind === prod.kind || o.kind.startsWith(prod.kind + ':') || (RELATED_KINDS[prod.kind] || []).includes(o.kind))
|
|
248
|
+
const to = o && typeof o.to === 'string' ? o.to.slice(0, 64) : ''
|
|
249
|
+
const targetOk = o && to && (prod.target === 'any' || prod.target === to)
|
|
250
|
+
if (!(o && kindOk && targetOk)) { tr(id, !prod ? 'no producer registered for its drop' : !o ? 'did not open with the intake key' : !kindOk ? 'kind ' + String(o.kind).slice(0, 20) + ' is not its producer\'s' : 'addressed to another room'); say('intake:refused', new Error(`a box from ${prod ? prod.label : 'an unknown producer'} was refused`)); ackable.add(at); continue }
|
|
251
|
+
// LEFT FOR THE CLOUD DEVICE (docs/always-on-agent-plan.md: an always-on Space answers its outside agents itself, no draft):
|
|
252
|
+
// io.leaveFor(kind, to) — a box for a Space the device keeps is left to it for LEAVE_FOR_MS (it is woken at once and takes it in
|
|
253
|
+
// seconds); after that the device is taken to be away, and this device delivers it as before.
|
|
254
|
+
let leave = false; try { leave = typeof io.leaveFor === 'function' && !!io.leaveFor(o.kind, to) && t - (Number(b.at) || Number(o.at) || t) < LEAVE_FOR_MS } catch { leave = false }
|
|
255
|
+
if (leave) { tr(id, 'left for the cloud device that keeps ' + to.slice(0, 12)); continue }
|
|
256
|
+
const body = o.body ?? null
|
|
257
|
+
const big = JSON.stringify(body).length > INLINE_MAX
|
|
258
|
+
const rowBody = big ? { box: { drop: b.drop, n: b.n } } : body
|
|
259
|
+
// ⛔ SEALED UNDER THE ACCOUNT KEY, like every room message (roomMail.js send): the message room is a standard room.
|
|
260
|
+
let sealedBody = null
|
|
261
|
+
if (typeof io.seal === 'function') { try { sealedBody = await io.seal(rowBody) } catch { sealedBody = null } }
|
|
262
|
+
// ⛔ NEVER READABLE FOR A CONFIDENTIAL ROOM (sync sweep 11-06 P1/P6, still open 11-09): a seal that failed (no account key here just
|
|
263
|
+
// now) wrote the body in the clear into the message room. As roomMail.send: a message for a CONFIDENTIAL room waits — the box
|
|
264
|
+
// stays in the intake, not acknowledged, and becomes a sealed message on a later pass once the key is here. An ordinary room's
|
|
265
|
+
// message goes as before (a device with no account key yet still delivers its Siri drops).
|
|
266
|
+
if (rowBody != null && !sealedBody && typeof io.confidential === 'function' && io.confidential(to)) { say('intake:waits', new Error(`a box from ${prod.label} for a confidential room waits — no account key here to seal it`)); continue }
|
|
267
|
+
lastTo = { to, kind: prod.kind, at: Date.now() } // opened and valid: whoever converts it, this is where it goes
|
|
268
|
+
// A BROADCAST kind (io.broadcast — a mail's attachment parts, I44 / W#2) is run by EVERY device that holds the target's key,
|
|
269
|
+
// not claimed by one: each keeps its copy, so whichever device later claims the mail has every part.
|
|
270
|
+
let fan = false; try { fan = typeof io.broadcast === 'function' && !!io.broadcast(o.kind) } catch { fan = false }
|
|
271
|
+
const row = { from: 'intake:' + prod.kind, to, kind: sealedBody ? SEALED + o.kind : o.kind, once: !fan, at: Number(o.at) || Number(b.at) || t, device: 'intake', via: { producer: prod.label }, ...(sealedBody ? { sbody: sealedBody } : { body: rowBody }) }
|
|
272
|
+
// ONE atomic write: the mark and the message, both "must not exist" — a box becomes a message once, even after its
|
|
273
|
+
// message was handled and deleted (the mark stays until the box has left the intake).
|
|
274
|
+
const w = await io.data(room, [
|
|
275
|
+
{ op: 'put', collection: MARK, id, row: { at: t, big }, ifVersion: null },
|
|
276
|
+
{ op: 'put', collection: MSG, id, row, ifVersion: null },
|
|
277
|
+
])
|
|
278
|
+
tr(id, (w && w.status === 200 ? 'converted into a ' + (sealedBody ? 'sealed ' : '') + 'message for ' : 'not converted (' + (w && w.status) + ') for ') + String(to).slice(0, 10) + ' · ' + o.kind)
|
|
279
|
+
if (w && w.status === 200) { converted++; if (big) opened.set(at, body); else ackable.add(at) }
|
|
280
|
+
// 409: another device converted it first — the next pass sees its mark
|
|
281
|
+
}
|
|
282
|
+
if (!r.more || page + 1 >= INTAKE_PAGES_MAX || !r.boxes.length || r.boxes.every((b) => ackable.has(b.drop + ':' + b.n))) break // nothing holds the head: the ack moves it
|
|
283
|
+
const last = r.boxes[r.boxes.length - 1]
|
|
284
|
+
const nx = await io.intake(room, { drop: last.drop, n: last.n + 1 })
|
|
285
|
+
if (!nx || nx.status !== 200 || !Array.isArray(nx.boxes)) break
|
|
286
|
+
r = nx
|
|
287
|
+
}
|
|
288
|
+
// acknowledge a CONTIGUOUS prefix per producer: positions are a count, so a box goes only with everything before it
|
|
289
|
+
const items = []
|
|
290
|
+
const byDrop = new Map(); for (const b of all) (byDrop.get(b.drop) || byDrop.set(b.drop, []).get(b.drop)).push(b.n)
|
|
291
|
+
for (const [drop, ns] of byDrop) {
|
|
292
|
+
let upTo = null
|
|
293
|
+
for (const n of ns.sort((a, c) => a - c)) { if (!ackable.has(drop + ':' + n)) break; upTo = n + 1 }
|
|
294
|
+
if (upTo != null) items.push({ drop, upTo })
|
|
295
|
+
}
|
|
296
|
+
if (items.length) { try { await io.intakeAck(room, items) } catch (err) { say('intake:ack', err) } }
|
|
297
|
+
// a mark goes once its box has left the intake for good: not in a COMPLETE read, and older than any stale read
|
|
298
|
+
if (!r.more) {
|
|
299
|
+
const waiting = new Set(all.map((b) => intakeRowId(b.drop, b.n)))
|
|
300
|
+
const done = [...marks].filter(([id, m]) => !waiting.has(id) && !msgs.has(id) && t - (Number(m.row && m.row.at) || 0) > MARK_KEEP_MS).map(([id]) => id).slice(0, 50)
|
|
301
|
+
if (done.length) { try { await io.data(room, done.map((id) => ({ op: 'del', collection: MARK, id }))) } catch (err) { say('intake:marks', err) } }
|
|
302
|
+
}
|
|
303
|
+
return converted
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** A message's body: inline, or — a big box carried by reference — read and opened from the intake. */
|
|
307
|
+
async function body(msg) {
|
|
308
|
+
const b = msg && msg.body
|
|
309
|
+
if (!(b && b.box && typeof b.box.drop === 'string' && Number.isInteger(b.box.n))) return b ?? null
|
|
310
|
+
const at = b.box.drop + ':' + b.box.n
|
|
311
|
+
if (opened.has(at)) return opened.get(at)
|
|
312
|
+
const room = await io.room(); const key = await intakeKey(); if (!room || !key) return null
|
|
313
|
+
const r = await io.intake(room, { drop: b.box.drop, n: b.box.n }) // read from THAT box: a later page is not behind the head (an older server: the head page, as before)
|
|
314
|
+
const hit = r && Array.isArray(r.boxes) ? r.boxes.find((x) => x.drop === b.box.drop && x.n === b.box.n) : null
|
|
315
|
+
const o = hit ? await openOne(key, hit) : null
|
|
316
|
+
const out = o ? (o.body ?? null) : null
|
|
317
|
+
if (o) opened.set(at, out)
|
|
318
|
+
return out
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** The message room moved (two devices made one): its intake key is another, so every address is too. */
|
|
322
|
+
const forget = () => { keyCache = null; regCache = null; emptyUntil = 0 }
|
|
323
|
+
return { mint, address, lookup, addresses, revoke, revokeAddress, producerOf, forget, producers, publicKey: async () => (await intakeKey({ create: true }) || {}).pub || null, collect, body, lastConverted: () => lastTo }
|
|
324
|
+
}
|
package/roomName.js
CHANGED
|
@@ -105,7 +105,7 @@ export function peopleIn(entries) {
|
|
|
105
105
|
const list = Array.isArray(entries) ? entries : []
|
|
106
106
|
const personKey = personKeyer(list)
|
|
107
107
|
for (const e of list) {
|
|
108
|
-
if (!e || e.self || e.sys || isLaneCopy(e) || e.kind === 'fork') continue
|
|
108
|
+
if (!e || e.self || e.sys || e.kind === 'safe' || isLaneCopy(e) || e.kind === 'fork') continue
|
|
109
109
|
if (e.kind === TITLE_KIND && !e.manual) continue
|
|
110
110
|
const id = personKey(e)
|
|
111
111
|
if (id) who.add(id)
|
package/roomRoster.js
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
import { memberHash } from './rosterHash.js'
|
|
2
2
|
|
|
3
3
|
/** Resolve a verified post against the server's signing-key directory. A chosen name alone proves no address. */
|
|
4
|
-
export function
|
|
4
|
+
export function verifiedSigningIds(entries) {
|
|
5
|
+
const ids = new Set()
|
|
6
|
+
for (const e of entries || []) {
|
|
7
|
+
const key = e?.spk || e?.vspk
|
|
8
|
+
if (e?.verified === true && !e.keyOnly && !e.self && e.kind !== 'agent' && key?.x && key?.y) ids.add(key.x + '.' + key.y)
|
|
9
|
+
}
|
|
10
|
+
return ids
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function verifiedPosters(entries, seen, { withId = false } = {}) {
|
|
5
14
|
const posters = []
|
|
6
15
|
for (const e of entries || []) {
|
|
7
16
|
const point = e?.spk || e?.vspk
|
|
@@ -10,9 +19,10 @@ export function verifiedPosters(entries, seen) {
|
|
|
10
19
|
const person = Object.prototype.hasOwnProperty.call(seen, id) ? seen[id] : null
|
|
11
20
|
if (person?.left) continue
|
|
12
21
|
const owner = person?.swapped ? null : person
|
|
13
|
-
const
|
|
22
|
+
const stampedEmail = (e.kind === 'data' || e.kind === 'title') && typeof e.email === 'string' ? e.email.trim().toLowerCase() : ''
|
|
23
|
+
const email = owner?.email || stampedEmail || (e.emailNameVerified === true ? String(e.name || '').trim().toLowerCase() : '')
|
|
14
24
|
const user = owner?.user || e.user || ''
|
|
15
|
-
if (email || user) posters.push({ email, user })
|
|
25
|
+
if (email || user) posters.push({ email, user, ...(withId && !person?.swapped ? { id } : {}) })
|
|
16
26
|
}
|
|
17
27
|
return posters
|
|
18
28
|
}
|
|
@@ -64,6 +74,7 @@ function clean (e) {
|
|
|
64
74
|
return out
|
|
65
75
|
}
|
|
66
76
|
|
|
77
|
+
export const hasVerifiedClaim = roster => rows(roster).some(e => e.verified === true)
|
|
67
78
|
const rows = (roster) => (Array.isArray(roster) ? roster : Array.isArray(roster?.people) ? roster.people : []).map(clean).filter(Boolean)
|
|
68
79
|
// Join order, with the id as a tiebreak: two devices can stamp the same millisecond, and without this two viewers
|
|
69
80
|
// could number them oppositely — which would quietly break the one promise a label makes.
|
|
@@ -123,8 +134,9 @@ export function membersView ({ allow = {}, rows = [], seenIdentity = () => '', s
|
|
|
123
134
|
if (had) { had.email ||= p.email; had.user ||= p.user; had.me ||= p.me; return }
|
|
124
135
|
people.set(key, { ...p })
|
|
125
136
|
}
|
|
137
|
+
const postedById = new Map((posters || []).filter(p => p?.id && (p.email || p.user)).map(p => [p.id, p]))
|
|
126
138
|
for (const r of rows) {
|
|
127
|
-
const p = personOf(r.id)
|
|
139
|
+
const p = personOf(r.id) || postedById.get(r.id)
|
|
128
140
|
const isMe = r.id === mineId || (!!me && !!p && p.email === me)
|
|
129
141
|
// A verified room lists MEMBERS: a row nobody vouched for (a typed name — a reader with the link, or a device that
|
|
130
142
|
// announced before it had its key) is not a member and is not shown. The owner read "Tomer · unverified" beside a
|
|
@@ -143,7 +155,7 @@ export function membersView ({ allow = {}, rows = [], seenIdentity = () => '', s
|
|
|
143
155
|
const key = email || '@' + norm(user)
|
|
144
156
|
const byUser = !email && [...people.values()].find((x) => user && norm(x.user) === norm(user))
|
|
145
157
|
if (byUser) continue
|
|
146
|
-
add(key, { email, user, me: !!me && email === me, label: '' })
|
|
158
|
+
add(key, { email, user, me: !!me && email === me, label: '', ...(a.id ? { id: a.id } : {}) })
|
|
147
159
|
}
|
|
148
160
|
// You are a member the moment you are reading as your verified self, whether or not this device has announced.
|
|
149
161
|
if (me && ![...people.values()].some((x) => x.me)) { if (people.has(me)) people.get(me).me = true; else add(me, { email: me, user: '', me: true, label: '' }) }
|
|
@@ -160,7 +172,7 @@ export function membersView ({ allow = {}, rows = [], seenIdentity = () => '', s
|
|
|
160
172
|
const emails = Array.isArray(allow.emails) ? allow.emails.filter(Boolean) : []
|
|
161
173
|
// an older room's @username entry: { handle, username } — the username it had THEN. A signed-in member whose handle it is
|
|
162
174
|
// (seenHandles: the caller resolved the signed-in usernames) is that member under their new name, not a second person.
|
|
163
|
-
const users = Array.isArray(allow.users) ? allow.users.filter((u) => !(u && typeof u === 'object' && u.handle && seenHandles.has(String(u.handle)))).map((u) => (u && typeof u === 'object' ? u.username : u)).filter(Boolean) : []
|
|
175
|
+
const users = Array.isArray(allow.users) ? allow.users.filter((u) => !(u && typeof u === 'object' && u.handle && (seenHandles.has(String(u.handle)) || seenHandles.has(String(u.handle).toLowerCase().trim())))).map((u) => (u && typeof u === 'object' ? u.username : u)).filter(Boolean) : []
|
|
164
176
|
for (const e of emails) if (!covered.has(norm(e))) items.push({ label: e, tag: 'not yet opened', address: e })
|
|
165
177
|
for (const u of users) if (!covered.has(norm('@' + u))) items.push({ label: '@' + u, tag: 'not yet opened', address: '@' + u, user: u })
|
|
166
178
|
const domains = Array.isArray(allow.domains) ? allow.domains.filter(Boolean) : []
|
|
@@ -178,7 +190,11 @@ export function membersView ({ allow = {}, rows = [], seenIdentity = () => '', s
|
|
|
178
190
|
/** A verified room's guest book does not yet SHOW this row as signed in (`seen`, the server's record of who the email gate
|
|
179
191
|
* verified): announce again even with nothing changed — a lost write (two members announcing at once) would otherwise leave the
|
|
180
192
|
* member nameless for ever, and a member change in place cannot reach a hidden member it cannot name. */
|
|
181
|
-
|
|
193
|
+
// ⚑ A RECORD MARKED `left` IS NOT A SIGHTING (the owner, 2026-11-27: removed from a Space and added back, he opened it and the owner's
|
|
194
|
+
// list said "Not yet opened" for good). A removal — or leaving — marks the member's record `left` (roomLeave.markLeft) and every
|
|
195
|
+
// reader skips such a record; it still holds the email, so this said "seen", the device never announced again, and the mark never
|
|
196
|
+
// cleared. The server writes a fresh record over a `left` one (spaceService roster_seen `mine`).
|
|
197
|
+
export const unseenIn = (seen, id) => !!id && !(seen && typeof seen === 'object' && seen[id] && seen[id].email && !seen[id].left)
|
|
182
198
|
/** Seen, but before the record kept WHICH list entries this person is (2026-10-23, rosterCount samePeople): announced ONCE more
|
|
183
199
|
* per room and key on this page (never retried — a server that does not keep them yet answers the same) so one person on the list by email and by
|
|
184
200
|
* @username counts once. */
|
|
@@ -256,6 +272,9 @@ export function listRoster (roster, { attested = null } = {}) {
|
|
|
256
272
|
verified,
|
|
257
273
|
named: verified && !!e.name, // a name someone ATTESTED — the only kind that may be shown plain
|
|
258
274
|
claimed: !verified && !!e.name, // a name its owner typed — shown, and the UI must mark it
|
|
275
|
+
// announced under a BROWSER PROFILE's id, not a key (selfRow's deviceId): one person on two browsers is two rows — counted
|
|
276
|
+
// per device, labelled "visitor" (the owner's rule, side sweep: open-room-device-rows-labelled-people)
|
|
277
|
+
visitor: !verified && !String(e.id || '').includes('.'),
|
|
259
278
|
label: standalone[i] ? e.name : (e.name ? `${e.name} (${ordinal})` : ordinal),
|
|
260
279
|
}
|
|
261
280
|
})
|
|
@@ -273,6 +292,10 @@ export async function privateInvitationMatches(cfg, room, seen, { resolveUsers,
|
|
|
273
292
|
let resolvedSeen = null
|
|
274
293
|
const resolveSeen = async () => { if (resolvedSeen) return resolvedSeen; try { resolvedSeen = ((await within(resolveUsers(seenUsers))) || { resolved: [] }).resolved || [] } catch { resolvedSeen = [] } return resolvedSeen }
|
|
275
294
|
if (seenUsers.length && legacyUsers.length) for (const r of await resolveSeen()) if (r && r.handle) seenHandles.add(String(r.handle))
|
|
295
|
+
// …and the handles the GATE recorded at their sign-in (roster_seen `entries`, 'u:<handle>' — agent/spaceOidc.mjs allowEntriesFor):
|
|
296
|
+
// a renamed member whose email door is closed resolves with no handle, and the old name was listed "not yet opened" beside them
|
|
297
|
+
// (side sweep 2026-11-28)
|
|
298
|
+
if (legacyUsers.length) for (const p of Object.values(seen)) for (const k of (p && Array.isArray(p.entries) ? p.entries : [])) if (typeof k === 'string' && k.startsWith('u:') && k.length > 2) seenHandles.add(k.slice(2))
|
|
276
299
|
try {
|
|
277
300
|
const mh = Array.isArray(cfg.allow && cfg.allow.mh) ? cfg.allow.mh : []
|
|
278
301
|
if (mh.length) { const got = new Set(); for (const p of Object.values(seen)) { if (p && p.email) { const h = await memberHash(p.email, room); if (h) got.add(h) } }
|
package/rosterCount.js
CHANGED
|
@@ -12,11 +12,14 @@ const list = (v) => (Array.isArray(v) ? v.map(norm).filter(Boolean) : [])
|
|
|
12
12
|
/** Exactly one admitted identity, and it is the signed-in person; no usernames or domains. */
|
|
13
13
|
export async function isSoloVerified(cfg, room, me, { hash = memberHash } = {}) {
|
|
14
14
|
const email = norm(me), allow = cfg?.allow
|
|
15
|
-
if (!email || cfg?.admission !== 'email' || !allow || allow.users?.length || allow.domains?.length) return false
|
|
15
|
+
if (!email || cfg?.admission !== 'email' || !allow || allow.users?.length || allow.domains?.length || allow.tags?.length) return false
|
|
16
16
|
const shown = Array.isArray(allow.emails) ? allow.emails.map(norm) : []
|
|
17
17
|
const hidden = Array.isArray(allow.mh) ? allow.mh : []
|
|
18
|
-
if (shown.length
|
|
19
|
-
|
|
18
|
+
if (!shown.length && !hidden.length) return false
|
|
19
|
+
if (shown.some(address => address !== email)) return false
|
|
20
|
+
if (!hidden.length) return true
|
|
21
|
+
const expected = await hash(email, room)
|
|
22
|
+
return hidden.every(h => h === expected)
|
|
20
23
|
}
|
|
21
24
|
|
|
22
25
|
export async function rosterParticipants (space, roomSalt, { seen = null } = {}) {
|
package/scheduleNext.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// scheduleNext.js — WHEN A DAILY SCHEDULE RUNS NEXT, for the always-on card and the SDK's schedules.list() (side sweep
|
|
2
|
+
// daily-schedule-display-omits-spring-gap-run-time). The cloud device runs a daily job at the first tick of a local day whose clock
|
|
3
|
+
// reads its time or later (schedulesDoc.js isDue): on the night the clocks skip that time, it becomes due the moment they jump.
|
|
4
|
+
// Computed from the time zone rules Intl holds on THIS device — display only. The turn enclave and the cloud device never read it.
|
|
5
|
+
|
|
6
|
+
const MIN = 60_000, DAY = 86_400_000, WINDOW = 48 * 3_600_000
|
|
7
|
+
const fmts = new Map()
|
|
8
|
+
const fmt = (tz) => {
|
|
9
|
+
let f = fmts.get(tz)
|
|
10
|
+
if (!f) { f = new Intl.DateTimeFormat('en-CA', { timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); fmts.set(tz, f) }
|
|
11
|
+
return f
|
|
12
|
+
}
|
|
13
|
+
function wall (ms, tz) {
|
|
14
|
+
const p = Object.fromEntries(fmt(tz).formatToParts(new Date(ms)).map((x) => [x.type, x.value]))
|
|
15
|
+
return { y: +p.year, mo: +p.month, d: +p.day, day: `${p.year}-${p.month}-${p.day}`, hm: `${p.hour}:${p.minute}`, h: +p.hour, mi: +p.minute }
|
|
16
|
+
}
|
|
17
|
+
/** The zone's offset at `ms` (wall clock − UTC, ms). */
|
|
18
|
+
const offset = (ms, tz) => { const w = wall(ms, tz), m = Math.floor(ms / MIN) * MIN; return Date.UTC(w.y, w.mo - 1, w.d, w.h, w.mi) - m }
|
|
19
|
+
|
|
20
|
+
/** The day's run: the first instant the local clock on that day reads `at` or later → { at (ms), skipped (the clocks jump past it),
|
|
21
|
+
* runsAt ('HH:MM' on the clock then) }, or null. */
|
|
22
|
+
function occurrence (y, mo, d, at, tz) {
|
|
23
|
+
const [h, mi] = at.split(':').map(Number), t0 = Date.UTC(y, mo - 1, d, h, mi), w0 = new Date(t0)
|
|
24
|
+
const day = `${w0.getUTCFullYear()}-${String(w0.getUTCMonth() + 1).padStart(2, '0')}-${String(w0.getUTCDate()).padStart(2, '0')}`
|
|
25
|
+
const cands = [...new Set([t0 - offset(t0 - DAY, tz), t0 - offset(t0 + DAY, tz)])].sort((a, b) => a - b)
|
|
26
|
+
const exact = cands.find((c) => { const w = wall(c, tz); return w.day === day && w.hm === at }) // the first, when the autumn clock repeats it
|
|
27
|
+
if (exact !== undefined) return { at: exact, skipped: false, runsAt: at }
|
|
28
|
+
const reached = (t) => { const w = wall(t, tz); return w.day > day || (w.day === day && w.hm >= at) }
|
|
29
|
+
let lo = cands[0], hi = cands[cands.length - 1]
|
|
30
|
+
if (lo === hi || reached(lo) || !reached(hi)) return null
|
|
31
|
+
while (hi - lo > MIN) { const mid = lo + Math.floor((hi - lo) / MIN / 2) * MIN; if (reached(mid)) hi = mid; else lo = mid } // the minute the clocks jump
|
|
32
|
+
return { at: hi, skipped: true, runsAt: wall(hi, tz).hm }
|
|
33
|
+
}
|
|
34
|
+
/** The runs of the next three local days still ahead of `now`, in order. */
|
|
35
|
+
function upcoming (when, now) {
|
|
36
|
+
if (!when || typeof when.at !== 'string' || !/^\d\d:\d\d$/.test(when.at) || !when.tz) return []
|
|
37
|
+
let today; try { today = wall(now, when.tz) } catch { return [] }
|
|
38
|
+
const out = []
|
|
39
|
+
for (let i = 0; i < 3; i++) {
|
|
40
|
+
const o = occurrence(today.y, today.mo, today.d + i, when.at, when.tz)
|
|
41
|
+
if (o && o.at > now) out.push({ ...o, i })
|
|
42
|
+
}
|
|
43
|
+
return out
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** When a daily job (`{ at, tz }`) runs next (ms), or null (not a daily job). */
|
|
47
|
+
export const nextDailyRun = (when, now = Date.now()) => { const u = upcoming(when, now); return u.length ? u[0].at : null }
|
|
48
|
+
|
|
49
|
+
/** The card's line when the clocks skip a daily job's time within the next 48 hours, else ''. */
|
|
50
|
+
export function skipNote (when, now = Date.now()) {
|
|
51
|
+
const o = upcoming(when, now).find((x) => x.skipped && x.at - now <= WINDOW)
|
|
52
|
+
if (!o) return ''
|
|
53
|
+
const label = o.i === 0 ? 'Today' : o.i === 1 ? 'Tomorrow' : 'On ' + new Intl.DateTimeFormat('en-US', { timeZone: when.tz, weekday: 'long' }).format(new Date(o.at))
|
|
54
|
+
return `${label} the clocks skip ${when.at} — it runs at ${o.runsAt}`
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The SDK's list: each active daily job with its next run (`next`, ms) — new objects; anything else as it came. */
|
|
58
|
+
export const withNextRuns = (jobs, now = Date.now()) => (Array.isArray(jobs)
|
|
59
|
+
? jobs.map((j) => { if (!j || j.paused || !j.when) return j; const next = nextDailyRun(j.when, now); return next === null ? j : { ...j, next } })
|
|
60
|
+
: jobs)
|