@ghostpaw/questlog 0.9.1 → 0.10.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.
@@ -0,0 +1,982 @@
1
+ #!/usr/bin/env node
2
+ import { randomBytes, createHmac } from 'node:crypto';
3
+ import { basename, extname } from 'node:path';
4
+
5
+ // src/tags/normalize_tag_name.ts
6
+ function normalizeTagName(name) {
7
+ return name.trim().toLowerCase().replace(/\s+/g, " ");
8
+ }
9
+
10
+ // src/hooks/types.ts
11
+ var hookEventTypes = [
12
+ "quest.due",
13
+ "quest.overdue",
14
+ "quest.unblocked",
15
+ "repeatable.spawned",
16
+ "rumor.captured"
17
+ ];
18
+
19
+ // src/hooks/add_hook.ts
20
+ function addHook(db, input) {
21
+ let url;
22
+ try {
23
+ url = new URL(input.url);
24
+ } catch {
25
+ throw new Error("Expected an HTTP or HTTPS URL");
26
+ }
27
+ if (!["http:", "https:"].includes(url.protocol)) throw new Error("Expected an HTTP or HTTPS URL");
28
+ const minGap = input.minGap ?? 60;
29
+ if (!Number.isSafeInteger(minGap) || minGap < 0)
30
+ throw new Error("Min gap must be a nonnegative integer");
31
+ const events = input.events ?? [...hookEventTypes];
32
+ if (!events.length || events.some((e) => !hookEventTypes.includes(e)))
33
+ throw new Error("Unknown event filter");
34
+ if (input.tag !== void 0 && !normalizeTagName(input.tag))
35
+ throw new Error("Expected a tag name");
36
+ const secret = input.secret ?? randomBytes(32).toString("hex");
37
+ if (!secret.trim()) throw new Error("Expected a nonempty signing secret");
38
+ const result = db.prepare(
39
+ "INSERT INTO hook_targets(url, secret, tag, events, min_gap, created_at) VALUES (?, ?, ?, ?, ?, ?)"
40
+ ).run(
41
+ url.href,
42
+ secret,
43
+ input.tag === void 0 ? null : normalizeTagName(input.tag),
44
+ JSON.stringify(events),
45
+ minGap,
46
+ input.now ?? Date.now()
47
+ );
48
+ return { id: Number(result.lastInsertRowid), secret };
49
+ }
50
+ function hookLabel(db, name) {
51
+ if (name !== void 0) {
52
+ if (!name.trim()) throw new Error("Expected a nonempty database label");
53
+ db.prepare(
54
+ "INSERT INTO hook_settings(id, label) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET label = excluded.label"
55
+ ).run(name);
56
+ }
57
+ const saved = db.prepare("SELECT label FROM hook_settings WHERE id = 1").get();
58
+ if (saved) return String(saved.label);
59
+ const path = String(
60
+ db.prepare("PRAGMA database_list").all().find((row) => row.name === "main")?.file ?? ""
61
+ );
62
+ return path ? basename(path, extname(path)) : "questlog";
63
+ }
64
+
65
+ // src/hooks/list_hooks.ts
66
+ function listHooks(db) {
67
+ return db.prepare(`SELECT id, url, tag, events, min_gap, created_at, last_wake,
68
+ (SELECT COUNT(*) FROM hook_assignments a LEFT JOIN hook_deliveries d ON d.id = a.delivery_id WHERE a.target_id = t.id AND (a.delivery_id IS NULL OR d.status = 'pending')) AS pending,
69
+ (SELECT COUNT(*) FROM hook_deliveries d WHERE d.target_id = t.id AND d.status = 'failed') AS failed
70
+ FROM hook_targets t ORDER BY id`).all().map((row) => {
71
+ const url = new URL(String(row.url));
72
+ url.username = "";
73
+ url.password = "";
74
+ url.search = "";
75
+ url.hash = "";
76
+ return {
77
+ id: Number(row.id),
78
+ scope: row.tag == null ? "database" : "tag",
79
+ url: url.href,
80
+ tag: row.tag == null ? null : String(row.tag),
81
+ events: JSON.parse(String(row.events)),
82
+ minGap: Number(row.min_gap),
83
+ createdAt: Number(row.created_at),
84
+ lastWake: row.last_wake == null ? null : Number(row.last_wake),
85
+ pending: Number(row.pending),
86
+ failed: Number(row.failed)
87
+ };
88
+ });
89
+ }
90
+
91
+ // src/with_transaction.ts
92
+ var transactionDepth = /* @__PURE__ */ new WeakMap();
93
+ function withTransaction(db, fn) {
94
+ const depth = transactionDepth.get(db) ?? 0;
95
+ const savepoint = `questlog_${depth}`;
96
+ if (depth === 0) {
97
+ db.exec("BEGIN IMMEDIATE");
98
+ } else {
99
+ db.exec(`SAVEPOINT ${savepoint}`);
100
+ }
101
+ transactionDepth.set(db, depth + 1);
102
+ try {
103
+ const result = fn();
104
+ if (depth === 0) {
105
+ db.exec("COMMIT");
106
+ } else {
107
+ db.exec(`RELEASE SAVEPOINT ${savepoint}`);
108
+ }
109
+ transactionDepth.set(db, depth);
110
+ return result;
111
+ } catch (error) {
112
+ try {
113
+ if (depth === 0) {
114
+ db.exec("ROLLBACK");
115
+ } else {
116
+ db.exec(`ROLLBACK TO SAVEPOINT ${savepoint}`);
117
+ db.exec(`RELEASE SAVEPOINT ${savepoint}`);
118
+ }
119
+ } catch {
120
+ }
121
+ transactionDepth.set(db, depth);
122
+ throw error;
123
+ }
124
+ }
125
+
126
+ // src/hooks/remove_hook.ts
127
+ function removeHook(db, id) {
128
+ withTransaction(db, () => {
129
+ db.prepare("DELETE FROM hook_assignments WHERE target_id = ?").run(id);
130
+ db.prepare("DELETE FROM hook_deliveries WHERE target_id = ?").run(id);
131
+ db.prepare("DELETE FROM hook_targets WHERE id = ?").run(id);
132
+ });
133
+ }
134
+
135
+ // src/version.ts
136
+ var questlogVersion = "0.10.1";
137
+
138
+ // src/hooks/send_hook_delivery.ts
139
+ async function sendHookDelivery(db, delivery, target, options) {
140
+ const now = options.now ?? options.clock?.() ?? Date.now();
141
+ const timestamp = String(Math.floor(now / 1e3));
142
+ const body = JSON.stringify({
143
+ type: "questlog.events",
144
+ db: hookLabel(db),
145
+ deliveryId: delivery.id,
146
+ sentAt: new Date(now).toISOString(),
147
+ events: delivery.events
148
+ });
149
+ const signature = createHmac("sha256", target.secret).update(`${timestamp}.${body}`).digest("hex");
150
+ let status = null;
151
+ let errorClass = null;
152
+ try {
153
+ const response = await (options.fetch ?? globalThis.fetch)(target.url, {
154
+ method: "POST",
155
+ redirect: "error",
156
+ headers: {
157
+ "content-type": "application/json",
158
+ "user-agent": `questlog/${questlogVersion}`,
159
+ "x-questlog-delivery": delivery.id,
160
+ "x-questlog-timestamp": timestamp,
161
+ "x-questlog-signature": `sha256=${signature}`
162
+ },
163
+ body,
164
+ signal: AbortSignal.timeout(Math.max(1, Math.min(options.timeoutMs ?? 5e3, 5e3)))
165
+ });
166
+ status = response.status;
167
+ await response.body?.cancel();
168
+ } catch (error) {
169
+ errorClass = error instanceof Error && ["TimeoutError", "AbortError"].includes(error.name) ? error.name : "NetworkError";
170
+ }
171
+ const delivered = status != null && status >= 200 && status < 300;
172
+ const completedAt = options.now ?? options.clock?.() ?? Date.now();
173
+ withTransaction(db, () => {
174
+ if (!db.prepare("SELECT id FROM hook_targets WHERE id = ? AND claim = ?").get(target.id, target.claim))
175
+ return;
176
+ const delay = Math.min(36e5, 3e4 * 2 ** (delivery.attempts - 1));
177
+ const jitter = Number.parseInt(randomBytes(2).toString("hex"), 16) % 1e3;
178
+ db.prepare(
179
+ "UPDATE hook_deliveries SET status = ?, http_status = ?, error_class = ?, next_attempt_at = ? WHERE id = ?"
180
+ ).run(
181
+ delivered ? "delivered" : delivery.attempts >= 8 ? "failed" : "pending",
182
+ status,
183
+ errorClass,
184
+ completedAt + delay + jitter,
185
+ delivery.id
186
+ );
187
+ db.prepare(
188
+ "UPDATE hook_targets SET claim = NULL, lease_until = NULL WHERE id = ? AND claim = ?"
189
+ ).run(target.id, target.claim);
190
+ db.prepare(
191
+ "DELETE FROM hook_deliveries WHERE target_id = ? AND status = 'delivered' AND id NOT IN (SELECT id FROM hook_deliveries WHERE target_id = ? AND status = 'delivered' ORDER BY last_attempt_at DESC, id DESC LIMIT 500)"
192
+ ).run(target.id, target.id);
193
+ });
194
+ return delivered;
195
+ }
196
+
197
+ // src/hooks/test_hook.ts
198
+ async function testHook(db, id, options = {}) {
199
+ const now = options.now ?? options.clock?.() ?? Date.now();
200
+ const claim = randomBytes(16).toString("hex");
201
+ const delivery = {
202
+ id: `d_${randomBytes(16).toString("hex")}`,
203
+ targetId: id,
204
+ events: [
205
+ {
206
+ id: `e_test_${randomBytes(16).toString("hex")}`,
207
+ type: "hook.test",
208
+ occurredAt: new Date(now).toISOString()
209
+ }
210
+ ],
211
+ status: "pending",
212
+ attempts: 1,
213
+ lastAttemptAt: now,
214
+ httpStatus: null,
215
+ errorClass: null,
216
+ nextAttemptAt: now
217
+ };
218
+ const target = withTransaction(db, () => {
219
+ const row = db.prepare("SELECT url, secret, lease_until FROM hook_targets WHERE id = ?").get(id);
220
+ if (!row) throw new Error("Hook not found");
221
+ if (row.lease_until != null && Number(row.lease_until) > now)
222
+ throw new Error("Hook delivery is in progress");
223
+ db.prepare(
224
+ "INSERT INTO hook_deliveries(id, target_id, events, status, attempts, last_attempt_at, next_attempt_at) VALUES (?, ?, ?, ?, ?, ?, ?)"
225
+ ).run(delivery.id, id, JSON.stringify(delivery.events), "pending", 1, now, now);
226
+ db.prepare(
227
+ "UPDATE hook_targets SET claim = ?, lease_until = ?, last_wake = ? WHERE id = ?"
228
+ ).run(claim, now + 12e4, now, id);
229
+ return { id, url: String(row.url), secret: String(row.secret), claim };
230
+ });
231
+ return { id: delivery.id, delivered: await sendHookDelivery(db, delivery, target, options) };
232
+ }
233
+
234
+ // src/quests/map_quest_row.ts
235
+ function asBoolean(value) {
236
+ return Number(value) === 1;
237
+ }
238
+ function mapQuestRow(row) {
239
+ return {
240
+ id: Number(row.id),
241
+ questlineId: row.questline_id == null ? null : Number(row.questline_id),
242
+ sourceRumorId: row.source_rumor_id == null ? null : Number(row.source_rumor_id),
243
+ spawnedByQuestId: row.spawned_by_quest_id == null ? null : Number(row.spawned_by_quest_id),
244
+ spawnedFromRepeatableId: row.spawned_from_repeatable_id == null ? null : Number(row.spawned_from_repeatable_id),
245
+ spawnedForAt: row.spawned_for_at == null ? null : Number(row.spawned_for_at),
246
+ title: String(row.title),
247
+ objective: String(row.objective),
248
+ outcome: row.outcome == null ? null : String(row.outcome),
249
+ createdAt: Number(row.created_at),
250
+ updatedAt: Number(row.updated_at),
251
+ startedAt: row.started_at == null ? null : Number(row.started_at),
252
+ resolvedAt: row.resolved_at == null ? null : Number(row.resolved_at),
253
+ success: row.success == null ? null : asBoolean(row.success),
254
+ effortSeconds: Number(row.effort_seconds),
255
+ estimateSeconds: row.estimate_seconds == null ? null : Number(row.estimate_seconds),
256
+ notBeforeAt: row.not_before_at == null ? null : Number(row.not_before_at),
257
+ dueAt: row.due_at == null ? null : Number(row.due_at),
258
+ scheduledStartAt: row.scheduled_start_at == null ? null : Number(row.scheduled_start_at),
259
+ scheduledEndAt: row.scheduled_end_at == null ? null : Number(row.scheduled_end_at),
260
+ allDay: asBoolean(row.all_day),
261
+ deletedAt: row.deleted_at == null ? null : Number(row.deleted_at)
262
+ };
263
+ }
264
+
265
+ // src/quests/get_quest_or_throw.ts
266
+ function getQuestOrThrow(db, questId) {
267
+ const row = db.prepare("SELECT * FROM quests WHERE id = ? AND deleted_at IS NULL").get(questId);
268
+ if (!row) {
269
+ throw new Error(`Quest ${questId} was not found.`);
270
+ }
271
+ return mapQuestRow(row);
272
+ }
273
+
274
+ // src/resolve_now.ts
275
+ function resolveNow(now) {
276
+ return now ?? Date.now();
277
+ }
278
+
279
+ // src/rewards/copy_repeatable_quest_rewards_to_quest.ts
280
+ function copyRepeatableQuestRewardsToQuest(db, repeatableQuestId, questId, now) {
281
+ const effectiveNow = resolveNow(now);
282
+ const rows = db.prepare(
283
+ `SELECT kind, name, description, quantity
284
+ FROM repeatable_quest_rewards
285
+ WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
286
+ ).all(repeatableQuestId);
287
+ for (const row of rows) {
288
+ db.prepare(
289
+ `INSERT INTO quest_rewards (quest_id, kind, name, description, quantity, created_at)
290
+ VALUES (?, ?, ?, ?, ?, ?)`
291
+ ).run(
292
+ questId,
293
+ String(row.kind),
294
+ String(row.name),
295
+ row.description == null ? null : String(row.description),
296
+ row.quantity == null ? null : Number(row.quantity),
297
+ effectiveNow
298
+ );
299
+ }
300
+ }
301
+
302
+ // src/tags/copy_repeatable_quest_tags_to_quest.ts
303
+ function copyRepeatableQuestTagsToQuest(db, repeatableQuestId, questId, now) {
304
+ const effectiveNow = resolveNow(now);
305
+ const rows = db.prepare(
306
+ `SELECT tag_id
307
+ FROM repeatable_quest_tags
308
+ WHERE repeatable_quest_id = ? AND deleted_at IS NULL`
309
+ ).all(repeatableQuestId);
310
+ for (const row of rows) {
311
+ db.prepare(
312
+ `INSERT INTO quest_tags (quest_id, tag_id, created_at)
313
+ VALUES (?, ?, ?)`
314
+ ).run(questId, Number(row.tag_id), effectiveNow);
315
+ }
316
+ }
317
+
318
+ // src/repeatable_quests/map_repeatable_quest_row.ts
319
+ function asBoolean2(value) {
320
+ return Number(value) === 1;
321
+ }
322
+ function mapRepeatableQuestRow(row) {
323
+ return {
324
+ id: Number(row.id),
325
+ questlineId: row.questline_id == null ? null : Number(row.questline_id),
326
+ title: String(row.title),
327
+ objective: String(row.objective),
328
+ rrule: String(row.rrule),
329
+ anchorAt: Number(row.anchor_at),
330
+ notBeforeOffsetSeconds: row.not_before_offset_seconds == null ? null : Number(row.not_before_offset_seconds),
331
+ dueOffsetSeconds: row.due_offset_seconds == null ? null : Number(row.due_offset_seconds),
332
+ scheduledStartOffsetSeconds: row.scheduled_start_offset_seconds == null ? null : Number(row.scheduled_start_offset_seconds),
333
+ scheduledEndOffsetSeconds: row.scheduled_end_offset_seconds == null ? null : Number(row.scheduled_end_offset_seconds),
334
+ allDay: asBoolean2(row.all_day),
335
+ estimateSeconds: row.estimate_seconds == null ? null : Number(row.estimate_seconds),
336
+ createdAt: Number(row.created_at),
337
+ updatedAt: Number(row.updated_at),
338
+ archivedAt: row.archived_at == null ? null : Number(row.archived_at),
339
+ deletedAt: row.deleted_at == null ? null : Number(row.deleted_at)
340
+ };
341
+ }
342
+
343
+ // src/repeatable_quests/get_repeatable_quest_or_throw.ts
344
+ function getRepeatableQuestOrThrow(db, repeatableQuestId) {
345
+ const row = db.prepare("SELECT * FROM repeatable_quests WHERE id = ? AND deleted_at IS NULL").get(repeatableQuestId);
346
+ if (!row) {
347
+ throw new Error(`Repeatable quest ${repeatableQuestId} was not found.`);
348
+ }
349
+ return mapRepeatableQuestRow(row);
350
+ }
351
+
352
+ // src/repeatable_quests/advance_anchor.ts
353
+ var WEEK_MS = 7 * 864e5;
354
+ function advanceAnchor(anchorAt, freq, interval) {
355
+ const date = new Date(anchorAt);
356
+ if (freq === "MONTHLY") {
357
+ date.setUTCMonth(date.getUTCMonth() + interval);
358
+ return date.getTime();
359
+ }
360
+ if (freq === "YEARLY") {
361
+ date.setUTCFullYear(date.getUTCFullYear() + interval);
362
+ return date.getTime();
363
+ }
364
+ return anchorAt + interval * WEEK_MS;
365
+ }
366
+
367
+ // src/repeatable_quests/parse_rrule.ts
368
+ var WEEKDAY = {
369
+ SU: 0,
370
+ MO: 1,
371
+ TU: 2,
372
+ WE: 3,
373
+ TH: 4,
374
+ FR: 5,
375
+ SA: 6
376
+ };
377
+ function parseRRule(rrule) {
378
+ const parts = Object.fromEntries(
379
+ rrule.split(";").map((part) => part.trim()).filter(Boolean).map((part) => {
380
+ const [key, value] = part.split("=");
381
+ return [key, value];
382
+ })
383
+ );
384
+ const freq = parts.FREQ;
385
+ if (freq !== "DAILY" && freq !== "WEEKLY" && freq !== "MONTHLY" && freq !== "YEARLY") {
386
+ throw new Error(`Unsupported RRULE FREQ: ${freq ?? "missing"}`);
387
+ }
388
+ const interval = parts.INTERVAL == null ? 1 : Number(parts.INTERVAL);
389
+ if (!Number.isFinite(interval) || interval < 1) {
390
+ throw new Error("RRULE INTERVAL must be a positive integer.");
391
+ }
392
+ const count = parts.COUNT == null ? null : Number(parts.COUNT);
393
+ if (count != null && (!Number.isFinite(count) || count < 1)) {
394
+ throw new Error("RRULE COUNT must be a positive integer.");
395
+ }
396
+ const until = parts.UNTIL == null ? null : Date.parse(parts.UNTIL);
397
+ if (parts.UNTIL != null && Number.isNaN(until)) {
398
+ throw new Error("RRULE UNTIL must be parseable as a date.");
399
+ }
400
+ const byDay = parts.BYDAY == null ? null : parts.BYDAY.split(",").map((token) => {
401
+ const value = WEEKDAY[token];
402
+ if (value == null) {
403
+ throw new Error(`Unsupported RRULE BYDAY token: ${token}`);
404
+ }
405
+ return value;
406
+ });
407
+ return { freq, interval, count, until, byDay };
408
+ }
409
+
410
+ // src/repeatable_quests/start_of_utc_day.ts
411
+ function startOfUtcDay(timestamp) {
412
+ const date = new Date(timestamp);
413
+ return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
414
+ }
415
+
416
+ // src/repeatable_quests/start_of_utc_week.ts
417
+ var DAY_MS = 864e5;
418
+ function startOfUtcWeek(dayStart) {
419
+ const date = new Date(dayStart);
420
+ return dayStart - date.getUTCDay() * DAY_MS;
421
+ }
422
+
423
+ // src/repeatable_quests/generate_anchors_until.ts
424
+ var DAY_MS2 = 864e5;
425
+ var WEEK_MS2 = 7 * DAY_MS2;
426
+ function generateAnchorsUntil(repeatable, now) {
427
+ const rule = parseRRule(repeatable.rrule);
428
+ const anchors = [];
429
+ const until = rule.until == null ? now : Math.min(now, rule.until);
430
+ if (repeatable.anchorAt > until) {
431
+ return anchors;
432
+ }
433
+ if (rule.freq === "DAILY") {
434
+ let occurrence2 = 0;
435
+ for (let current2 = repeatable.anchorAt; current2 <= until; current2 += rule.interval * DAY_MS2) {
436
+ occurrence2 += 1;
437
+ if (rule.count != null && occurrence2 > rule.count) {
438
+ break;
439
+ }
440
+ anchors.push(current2);
441
+ }
442
+ return anchors;
443
+ }
444
+ if (rule.freq === "WEEKLY" && rule.byDay && rule.byDay.length > 0) {
445
+ const anchorDayStart = startOfUtcDay(repeatable.anchorAt);
446
+ const anchorWeekStart = startOfUtcWeek(anchorDayStart);
447
+ const timeOffset = repeatable.anchorAt - anchorDayStart;
448
+ let occurrence2 = 0;
449
+ for (let day = anchorDayStart; day <= until; day += DAY_MS2) {
450
+ const weeksSince = Math.floor((startOfUtcWeek(day) - anchorWeekStart) / WEEK_MS2);
451
+ if (weeksSince < 0 || weeksSince % rule.interval !== 0) {
452
+ continue;
453
+ }
454
+ if (!rule.byDay.includes(new Date(day).getUTCDay())) {
455
+ continue;
456
+ }
457
+ const anchor = day + timeOffset;
458
+ if (anchor < repeatable.anchorAt || anchor > until) {
459
+ continue;
460
+ }
461
+ occurrence2 += 1;
462
+ if (rule.count != null && occurrence2 > rule.count) {
463
+ break;
464
+ }
465
+ anchors.push(anchor);
466
+ }
467
+ return anchors;
468
+ }
469
+ let occurrence = 0;
470
+ let current = repeatable.anchorAt;
471
+ while (current <= until) {
472
+ occurrence += 1;
473
+ if (rule.count != null && occurrence > rule.count) {
474
+ break;
475
+ }
476
+ anchors.push(current);
477
+ current = advanceAnchor(current, rule.freq, rule.interval);
478
+ }
479
+ return anchors;
480
+ }
481
+
482
+ // src/repeatable_quests/list_due_repeatable_quest_anchors.ts
483
+ function listDueRepeatableQuestAnchors(db, now) {
484
+ const repeatables = db.prepare(
485
+ `SELECT *
486
+ FROM repeatable_quests
487
+ WHERE deleted_at IS NULL
488
+ AND archived_at IS NULL`
489
+ ).all().map(mapRepeatableQuestRow);
490
+ const anchors = [];
491
+ if (repeatables.length === 0) {
492
+ return anchors;
493
+ }
494
+ const repeatableIds = repeatables.map((repeatable) => repeatable.id);
495
+ const maxAnchorAt = Math.max(
496
+ ...repeatables.map((repeatable) => Math.max(repeatable.anchorAt, now))
497
+ );
498
+ const existingRows = db.prepare(
499
+ `SELECT spawned_from_repeatable_id, spawned_for_at
500
+ FROM quests
501
+ WHERE spawned_from_repeatable_id IN (${repeatableIds.map(() => "?").join(", ")})
502
+ AND spawned_for_at IS NOT NULL
503
+ AND spawned_for_at <= ?`
504
+ ).all(...repeatableIds, maxAnchorAt);
505
+ const existingAnchors = new Set(
506
+ existingRows.map(
507
+ (row) => `${Number(row.spawned_from_repeatable_id)}:${Number(row.spawned_for_at)}`
508
+ )
509
+ );
510
+ for (const repeatable of repeatables) {
511
+ const dueAnchors = generateAnchorsUntil(repeatable, now);
512
+ for (const anchorAt of dueAnchors) {
513
+ if (!existingAnchors.has(`${repeatable.id}:${anchorAt}`)) {
514
+ anchors.push({
515
+ repeatableQuestId: repeatable.id,
516
+ anchorAt,
517
+ markerId: "attention.available.repeatable"
518
+ });
519
+ }
520
+ }
521
+ }
522
+ return anchors.sort(
523
+ (a, b) => a.anchorAt - b.anchorAt || a.repeatableQuestId - b.repeatableQuestId
524
+ );
525
+ }
526
+
527
+ // src/repeatable_quests/spawn_due_repeatable_quests.ts
528
+ function spawnDueRepeatableQuests(db, now) {
529
+ return withTransaction(db, () => {
530
+ const anchors = listDueRepeatableQuestAnchors(db, now);
531
+ const quests = [];
532
+ for (const anchor of anchors) {
533
+ const repeatable = getRepeatableQuestOrThrow(db, anchor.repeatableQuestId);
534
+ const created = db.prepare(
535
+ `INSERT INTO quests (
536
+ questline_id,
537
+ source_rumor_id,
538
+ spawned_by_quest_id,
539
+ spawned_from_repeatable_id,
540
+ spawned_for_at,
541
+ title,
542
+ objective,
543
+ created_at,
544
+ updated_at,
545
+ effort_seconds,
546
+ estimate_seconds,
547
+ not_before_at,
548
+ due_at,
549
+ scheduled_start_at,
550
+ scheduled_end_at,
551
+ all_day
552
+ ) VALUES (?, NULL, NULL, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?)`
553
+ ).run(
554
+ repeatable.questlineId ?? null,
555
+ repeatable.id,
556
+ anchor.anchorAt,
557
+ repeatable.title,
558
+ repeatable.objective,
559
+ now,
560
+ now,
561
+ repeatable.estimateSeconds ?? null,
562
+ repeatable.notBeforeOffsetSeconds == null ? null : anchor.anchorAt + repeatable.notBeforeOffsetSeconds * 1e3,
563
+ repeatable.dueOffsetSeconds == null ? null : anchor.anchorAt + repeatable.dueOffsetSeconds * 1e3,
564
+ repeatable.scheduledStartOffsetSeconds == null ? null : anchor.anchorAt + repeatable.scheduledStartOffsetSeconds * 1e3,
565
+ repeatable.scheduledEndOffsetSeconds == null ? null : anchor.anchorAt + repeatable.scheduledEndOffsetSeconds * 1e3,
566
+ repeatable.allDay ? 1 : 0
567
+ );
568
+ const questId = Number(created.lastInsertRowid);
569
+ copyRepeatableQuestTagsToQuest(db, repeatable.id, questId, now);
570
+ copyRepeatableQuestRewardsToQuest(db, repeatable.id, questId, now);
571
+ quests.push(getQuestOrThrow(db, questId));
572
+ }
573
+ return quests;
574
+ });
575
+ }
576
+
577
+ // src/markers/derive_quest_marker_id.ts
578
+ function deriveQuestMarkerId({
579
+ state,
580
+ available,
581
+ hasUnclaimedReward,
582
+ notBeforeAt,
583
+ blockerCount,
584
+ now
585
+ }) {
586
+ if (state === "done") {
587
+ return hasUnclaimedReward ? "progress.complete" : null;
588
+ }
589
+ if (state === "abandoned") {
590
+ return null;
591
+ }
592
+ if (state === "in_progress") {
593
+ return "progress.incomplete";
594
+ }
595
+ if (available) {
596
+ return "attention.available";
597
+ }
598
+ if (notBeforeAt != null && notBeforeAt > now) {
599
+ return "attention.available.future";
600
+ }
601
+ if (blockerCount > 0) {
602
+ return "progress.incomplete";
603
+ }
604
+ return null;
605
+ }
606
+
607
+ // src/rewards/map_quest_reward_row.ts
608
+ function mapQuestRewardRow(row) {
609
+ return {
610
+ id: Number(row.id),
611
+ questId: Number(row.quest_id),
612
+ kind: String(row.kind),
613
+ name: String(row.name),
614
+ description: row.description == null ? null : String(row.description),
615
+ quantity: row.quantity == null ? null : Number(row.quantity),
616
+ createdAt: Number(row.created_at),
617
+ claimedAt: row.claimed_at == null ? null : Number(row.claimed_at),
618
+ deletedAt: row.deleted_at == null ? null : Number(row.deleted_at)
619
+ };
620
+ }
621
+
622
+ // src/quests/derive_quest_state.ts
623
+ function deriveQuestState(quest) {
624
+ if (quest.resolvedAt != null && quest.success === true) {
625
+ return "done";
626
+ }
627
+ if (quest.resolvedAt != null && quest.success === false) {
628
+ return "abandoned";
629
+ }
630
+ if (quest.startedAt != null) {
631
+ return "in_progress";
632
+ }
633
+ return "open";
634
+ }
635
+
636
+ // src/quests/query_quest_detail_records.ts
637
+ function queryQuestDetailRecords(db, filters = {}, now = Date.now(), questIds) {
638
+ if (questIds && questIds.length === 0) {
639
+ return [];
640
+ }
641
+ const clauses = [];
642
+ const params = [];
643
+ if (!filters.includeDeleted) {
644
+ clauses.push("q.deleted_at IS NULL");
645
+ }
646
+ if (questIds && questIds.length > 0) {
647
+ clauses.push(`q.id IN (${questIds.map(() => "?").join(", ")})`);
648
+ params.push(...questIds);
649
+ }
650
+ if (filters.questlineId != null) {
651
+ clauses.push("q.questline_id = ?");
652
+ params.push(filters.questlineId);
653
+ }
654
+ if (filters.tagNames && filters.tagNames.length > 0) {
655
+ const normalized = [...new Set(filters.tagNames.map(normalizeTagName).filter(Boolean))];
656
+ for (const tag of normalized) {
657
+ clauses.push(
658
+ `EXISTS (
659
+ SELECT 1
660
+ FROM quest_tags qt
661
+ JOIN tags t ON t.id = qt.tag_id
662
+ WHERE qt.quest_id = q.id
663
+ AND qt.deleted_at IS NULL
664
+ AND t.deleted_at IS NULL
665
+ AND t.normalized_name = ?
666
+ )`
667
+ );
668
+ params.push(tag);
669
+ }
670
+ }
671
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
672
+ const rows = db.prepare(
673
+ `SELECT q.*,
674
+ COALESCE(q.due_at, ql.due_at) AS effective_due_at,
675
+ (
676
+ SELECT COUNT(*)
677
+ FROM quest_unlocks qu
678
+ JOIN quests blocker ON blocker.id = qu.from_quest_id
679
+ WHERE qu.to_quest_id = q.id
680
+ AND qu.deleted_at IS NULL
681
+ AND blocker.deleted_at IS NULL
682
+ AND NOT (blocker.resolved_at IS NOT NULL AND blocker.success = 1)
683
+ ) AS blocker_count
684
+ FROM quests q
685
+ LEFT JOIN questlines ql ON ql.id = q.questline_id AND ql.deleted_at IS NULL
686
+ ${where}
687
+ ORDER BY q.created_at DESC, q.id DESC`
688
+ ).all(...params);
689
+ if (rows.length === 0) {
690
+ return [];
691
+ }
692
+ const ids = rows.map((row) => Number(row.id));
693
+ const placeholders = ids.map(() => "?").join(", ");
694
+ const tagNamesByQuestId = /* @__PURE__ */ new Map();
695
+ const rewardsByQuestId = /* @__PURE__ */ new Map();
696
+ const unlocksByQuestId = /* @__PURE__ */ new Map();
697
+ const unlockedByQuestId = /* @__PURE__ */ new Map();
698
+ for (const row of db.prepare(
699
+ `SELECT qt.quest_id, t.name
700
+ FROM quest_tags qt
701
+ JOIN tags t ON t.id = qt.tag_id
702
+ WHERE qt.quest_id IN (${placeholders})
703
+ AND qt.deleted_at IS NULL
704
+ AND t.deleted_at IS NULL
705
+ ORDER BY qt.quest_id, t.name`
706
+ ).all(...ids)) {
707
+ const questId = Number(row.quest_id);
708
+ const tagNames = tagNamesByQuestId.get(questId) ?? [];
709
+ tagNames.push(String(row.name));
710
+ tagNamesByQuestId.set(questId, tagNames);
711
+ }
712
+ for (const row of db.prepare(
713
+ `SELECT *
714
+ FROM quest_rewards
715
+ WHERE quest_id IN (${placeholders})
716
+ AND deleted_at IS NULL
717
+ ORDER BY quest_id, created_at, id`
718
+ ).all(...ids)) {
719
+ const reward = mapQuestRewardRow(row);
720
+ const rewards = rewardsByQuestId.get(reward.questId) ?? [];
721
+ rewards.push(reward);
722
+ rewardsByQuestId.set(reward.questId, rewards);
723
+ }
724
+ for (const row of db.prepare(
725
+ `SELECT from_quest_id, to_quest_id
726
+ FROM quest_unlocks
727
+ WHERE from_quest_id IN (${placeholders})
728
+ AND deleted_at IS NULL
729
+ ORDER BY from_quest_id, to_quest_id`
730
+ ).all(...ids)) {
731
+ const questId = Number(row.from_quest_id);
732
+ const unlocks = unlocksByQuestId.get(questId) ?? [];
733
+ unlocks.push(Number(row.to_quest_id));
734
+ unlocksByQuestId.set(questId, unlocks);
735
+ }
736
+ for (const row of db.prepare(
737
+ `SELECT from_quest_id, to_quest_id
738
+ FROM quest_unlocks
739
+ WHERE to_quest_id IN (${placeholders})
740
+ AND deleted_at IS NULL
741
+ ORDER BY to_quest_id, from_quest_id`
742
+ ).all(...ids)) {
743
+ const questId = Number(row.to_quest_id);
744
+ const unlockedBy = unlockedByQuestId.get(questId) ?? [];
745
+ unlockedBy.push(Number(row.from_quest_id));
746
+ unlockedByQuestId.set(questId, unlockedBy);
747
+ }
748
+ return rows.map((row) => {
749
+ const quest = mapQuestRow(row);
750
+ const blockerCount = Number(row.blocker_count ?? 0);
751
+ const effectiveDueAt = row.effective_due_at == null ? null : Number(row.effective_due_at);
752
+ const rewards = rewardsByQuestId.get(quest.id) ?? [];
753
+ const state = deriveQuestState(quest);
754
+ const available = quest.deletedAt == null && quest.resolvedAt == null && (quest.notBeforeAt == null || quest.notBeforeAt <= now) && blockerCount === 0;
755
+ const markerId = deriveQuestMarkerId({
756
+ state,
757
+ available,
758
+ hasUnclaimedReward: rewards.some((reward) => reward.claimedAt == null),
759
+ notBeforeAt: quest.notBeforeAt,
760
+ blockerCount,
761
+ now
762
+ });
763
+ return {
764
+ detail: {
765
+ ...quest,
766
+ state,
767
+ markerId,
768
+ effectiveDueAt,
769
+ available,
770
+ tagNames: tagNamesByQuestId.get(quest.id) ?? [],
771
+ rewards,
772
+ unlocksQuestIds: unlocksByQuestId.get(quest.id) ?? [],
773
+ unlockedByQuestIds: unlockedByQuestId.get(quest.id) ?? []
774
+ },
775
+ blockerCount
776
+ };
777
+ });
778
+ }
779
+
780
+ // src/hooks/detect_hook_events.ts
781
+ function detectHookEvents(db, now) {
782
+ const events = [];
783
+ const add = (type, at, ids) => {
784
+ events.push({
785
+ id: `e_${type}_${ids.questId ?? ids.rumorId}_${ids.repeatableId ?? ""}_${at}`,
786
+ type,
787
+ ...ids,
788
+ occurredAt: new Date(at).toISOString()
789
+ });
790
+ };
791
+ for (const { detail: q } of queryQuestDetailRecords(db, {}, now)) {
792
+ if (q.resolvedAt == null && q.effectiveDueAt != null && q.effectiveDueAt <= now) {
793
+ add("quest.due", q.effectiveDueAt, { questId: q.id });
794
+ if (q.effectiveDueAt < now) add("quest.overdue", q.effectiveDueAt, { questId: q.id });
795
+ }
796
+ if (q.available) {
797
+ const prerequisites = db.prepare(
798
+ `SELECT p.id, p.resolved_at, u.created_at FROM quest_unlocks u JOIN quests p ON p.id = u.from_quest_id WHERE u.to_quest_id = ? AND u.deleted_at IS NULL AND p.deleted_at IS NULL AND p.success = 1 AND p.resolved_at IS NOT NULL`
799
+ ).all(q.id);
800
+ if (prerequisites.some((p) => Number(p.resolved_at) >= Number(p.created_at))) {
801
+ const at = Math.max(q.notBeforeAt ?? 0, ...prerequisites.map((p) => Number(p.resolved_at)));
802
+ if (at <= now) add("quest.unblocked", at, { questId: q.id });
803
+ }
804
+ }
805
+ if (q.spawnedFromRepeatableId != null && q.createdAt <= now)
806
+ add("repeatable.spawned", q.createdAt, {
807
+ questId: q.id,
808
+ repeatableId: q.spawnedFromRepeatableId
809
+ });
810
+ }
811
+ for (const row of db.prepare("SELECT id, created_at FROM rumors WHERE deleted_at IS NULL AND created_at <= ?").all(now))
812
+ add("rumor.captured", Number(row.created_at), { rumorId: Number(row.id) });
813
+ return events.sort(
814
+ (a, b) => a.occurredAt.localeCompare(b.occurredAt) || a.id.localeCompare(b.id)
815
+ );
816
+ }
817
+
818
+ // src/hooks/list_deliveries.ts
819
+ function listDeliveries(db, options = {}) {
820
+ return db.prepare(
821
+ `SELECT * FROM hook_deliveries ${options.includeDelivered ? "" : "WHERE status <> 'delivered'"} ORDER BY target_id, next_attempt_at, id`
822
+ ).all().map(
823
+ (row) => ({
824
+ id: String(row.id),
825
+ targetId: Number(row.target_id),
826
+ events: JSON.parse(String(row.events)),
827
+ status: row.status,
828
+ attempts: Number(row.attempts),
829
+ lastAttemptAt: row.last_attempt_at == null ? null : Number(row.last_attempt_at),
830
+ httpStatus: row.http_status == null ? null : Number(row.http_status),
831
+ errorClass: row.error_class == null ? null : String(row.error_class),
832
+ nextAttemptAt: Number(row.next_attempt_at)
833
+ })
834
+ ).filter(
835
+ (d) => options.questId === void 0 || d.events.some((e) => e.questId === options.questId)
836
+ );
837
+ }
838
+
839
+ // src/hooks/tick_questlog.ts
840
+ async function tickQuestlog(db, options = {}) {
841
+ const now = options.now ?? options.clock?.() ?? Date.now();
842
+ const result = {
843
+ events: [],
844
+ batches: [],
845
+ sent: 0,
846
+ queued: 0,
847
+ retrying: 0,
848
+ failed: 0
849
+ };
850
+ const claims = [];
851
+ const collect = () => {
852
+ spawnDueRepeatableQuests(db, now);
853
+ const detected = detectHookEvents(db, now);
854
+ result.events = detected.filter(
855
+ (e) => !db.prepare("SELECT id FROM hook_events WHERE id = ?").get(e.id)
856
+ );
857
+ for (const event of result.events)
858
+ db.prepare("INSERT INTO hook_events(id, occurred_at, event) VALUES (?, ?, ?)").run(
859
+ event.id,
860
+ Date.parse(event.occurredAt),
861
+ JSON.stringify(event)
862
+ );
863
+ for (const target of listHooks(db)) {
864
+ const events = db.prepare(
865
+ "SELECT e.event FROM hook_events e WHERE occurred_at >= ? AND NOT EXISTS (SELECT 1 FROM hook_assignments a WHERE a.target_id = ? AND a.event_id = e.id) ORDER BY occurred_at, id"
866
+ ).all(target.createdAt, target.id).map((row2) => JSON.parse(String(row2.event))).filter((event) => {
867
+ if (!target.events.includes(event.type)) return false;
868
+ if (target.tag == null) return true;
869
+ return event.questId !== void 0 && db.prepare(
870
+ "SELECT 1 FROM quest_tags qt JOIN tags t ON t.id = qt.tag_id WHERE qt.quest_id = ? AND qt.deleted_at IS NULL AND t.deleted_at IS NULL AND t.normalized_name = ?"
871
+ ).get(event.questId, normalizeTagName(target.tag)) !== void 0;
872
+ });
873
+ for (const event of events)
874
+ db.prepare("INSERT INTO hook_assignments(target_id, event_id) VALUES (?, ?)").run(
875
+ target.id,
876
+ event.id
877
+ );
878
+ const row = db.prepare("SELECT url, secret, lease_until FROM hook_targets WHERE id = ?").get(target.id);
879
+ if (!row || row.lease_until != null && Number(row.lease_until) > now) continue;
880
+ let pending = listDeliveries(db).find(
881
+ (d) => d.targetId === target.id && d.status === "pending"
882
+ );
883
+ const queued = db.prepare(
884
+ "SELECT e.event FROM hook_assignments a JOIN hook_events e ON e.id = a.event_id WHERE a.target_id = ? AND a.delivery_id IS NULL ORDER BY e.occurred_at, e.id"
885
+ ).all(target.id).map((r) => JSON.parse(String(r.event)));
886
+ if (!pending && queued.length) {
887
+ const id = `d_${randomBytes(16).toString("hex")}`;
888
+ db.prepare(
889
+ "INSERT INTO hook_deliveries(id, target_id, events, status, next_attempt_at) VALUES (?, ?, ?, 'pending', ?)"
890
+ ).run(
891
+ id,
892
+ target.id,
893
+ JSON.stringify(queued),
894
+ Math.max(now, (target.lastWake ?? -Infinity) + target.minGap * 1e3)
895
+ );
896
+ db.prepare(
897
+ "UPDATE hook_assignments SET delivery_id = ? WHERE target_id = ? AND delivery_id IS NULL"
898
+ ).run(id, target.id);
899
+ pending = listDeliveries(db).find((d) => d.id === id);
900
+ }
901
+ if (!pending) continue;
902
+ if (pending.attempts === 0 && queued.length && !queued.every((e) => pending?.events.some((p) => p.id === e.id))) {
903
+ pending.events.push(...queued);
904
+ db.prepare("UPDATE hook_deliveries SET events = ? WHERE id = ?").run(
905
+ JSON.stringify(pending.events),
906
+ pending.id
907
+ );
908
+ db.prepare(
909
+ "UPDATE hook_assignments SET delivery_id = ? WHERE target_id = ? AND delivery_id IS NULL"
910
+ ).run(pending.id, target.id);
911
+ }
912
+ if (pending.nextAttemptAt > now || target.lastWake != null && target.lastWake + target.minGap * 1e3 > now)
913
+ continue;
914
+ if (pending.attempts >= 8) {
915
+ db.prepare("UPDATE hook_deliveries SET status = 'failed' WHERE id = ?").run(pending.id);
916
+ continue;
917
+ }
918
+ const claim = randomBytes(16).toString("hex");
919
+ db.prepare(
920
+ "UPDATE hook_targets SET claim = ?, lease_until = ?, last_wake = ? WHERE id = ?"
921
+ ).run(claim, now + 12e4, now, target.id);
922
+ db.prepare(
923
+ "UPDATE hook_deliveries SET attempts = attempts + 1, last_attempt_at = ? WHERE id = ?"
924
+ ).run(now, pending.id);
925
+ pending.attempts++;
926
+ pending.lastAttemptAt = now;
927
+ result.batches.push({ targetId: target.id, events: pending.events });
928
+ claims.push({
929
+ delivery: pending,
930
+ target: { id: target.id, url: String(row.url), secret: String(row.secret), claim }
931
+ });
932
+ }
933
+ };
934
+ if (options.dryRun) {
935
+ const rollback = new Error("preview rollback");
936
+ try {
937
+ withTransaction(db, () => {
938
+ collect();
939
+ throw rollback;
940
+ });
941
+ } catch (error) {
942
+ if (error !== rollback) throw error;
943
+ }
944
+ } else withTransaction(db, collect);
945
+ if (!options.dryRun) {
946
+ const sent = await Promise.all(
947
+ claims.map((claim) => sendHookDelivery(db, claim.delivery, claim.target, options))
948
+ );
949
+ result.sent = sent.filter(Boolean).length;
950
+ }
951
+ const deliveries = listDeliveries(db);
952
+ result.queued = deliveries.filter((d) => d.status === "pending" && d.attempts === 0).length + Number(
953
+ db.prepare(
954
+ "SELECT COUNT(DISTINCT target_id) AS n FROM hook_assignments WHERE delivery_id IS NULL"
955
+ ).get()?.n ?? 0
956
+ );
957
+ result.retrying = deliveries.filter((d) => d.status === "pending" && d.attempts > 0).length;
958
+ result.failed = deliveries.filter((d) => d.status === "failed").length;
959
+ return result;
960
+ }
961
+
962
+ // src/hooks/watch_questlog.ts
963
+ async function watchQuestlog(db, options) {
964
+ const interval = options.interval ?? 60;
965
+ if (!Number.isFinite(interval) || interval < 5)
966
+ throw new Error("Interval must be at least 5 seconds");
967
+ while (!options.signal.aborted) {
968
+ options.onTick?.(await tickQuestlog(db, options));
969
+ if (options.signal.aborted) break;
970
+ await new Promise((resolve) => {
971
+ const finish = () => {
972
+ clearTimeout(timer);
973
+ options.signal.removeEventListener("abort", finish);
974
+ resolve();
975
+ };
976
+ const timer = setTimeout(finish, interval * 1e3);
977
+ options.signal.addEventListener("abort", finish, { once: true });
978
+ });
979
+ }
980
+ }
981
+
982
+ export { addHook, deriveQuestMarkerId, deriveQuestState, getQuestOrThrow, getRepeatableQuestOrThrow, hookLabel, listDeliveries, listDueRepeatableQuestAnchors, listHooks, mapQuestRewardRow, normalizeTagName, parseRRule, queryQuestDetailRecords, questlogVersion, removeHook, resolveNow, spawnDueRepeatableQuests, testHook, tickQuestlog, watchQuestlog, withTransaction };