@marktiderman/genesis-core 2.4.0 → 2.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 +42 -0
- package/dist/chunk-227N654S.js +497 -0
- package/dist/chunk-227N654S.js.map +1 -0
- package/dist/{chunk-ZIMQUFXD.js → chunk-37RWGNIO.js} +9 -4
- package/dist/chunk-37RWGNIO.js.map +1 -0
- package/dist/{chunk-5NEOX2N7.js → chunk-H2RGMX6L.js} +4 -4
- package/dist/{chunk-5NEOX2N7.js.map → chunk-H2RGMX6L.js.map} +1 -1
- package/dist/dates.d.ts +173 -1
- package/dist/dates.js +1 -1
- package/dist/errors.d.ts +8 -1
- package/dist/errors.js +1 -1
- package/dist/hooks/index.js +3 -3
- package/dist/index.js +3 -3
- package/dist/navigation.js.map +1 -1
- package/dist/resource-view/index.d.ts +34 -1
- package/dist/resource-view/index.js +28 -3
- package/dist/resource-view/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-3B4IFDMK.js +0 -117
- package/dist/chunk-3B4IFDMK.js.map +0 -1
- package/dist/chunk-ZIMQUFXD.js.map +0 -1
package/dist/chunk-3B4IFDMK.js
DELETED
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
// src/dates.ts
|
|
2
|
-
var DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
3
|
-
function isDay(value) {
|
|
4
|
-
if (typeof value !== "string") return false;
|
|
5
|
-
const m = DAY.exec(value);
|
|
6
|
-
if (!m) return false;
|
|
7
|
-
const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
|
|
8
|
-
return d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() === Number(m[2]) - 1 && d.getUTCDate() === Number(m[3]);
|
|
9
|
-
}
|
|
10
|
-
function assertDay(day, where) {
|
|
11
|
-
if (!isDay(day)) throw new RangeError(`${where}: "${String(day)}" is not a YYYY-MM-DD day`);
|
|
12
|
-
const m = DAY.exec(day);
|
|
13
|
-
return [Number(m[1]), Number(m[2]), Number(m[3])];
|
|
14
|
-
}
|
|
15
|
-
var formatters = /* @__PURE__ */ new Map();
|
|
16
|
-
function isTimeZone(zone) {
|
|
17
|
-
if (typeof zone !== "string" || !zone) return false;
|
|
18
|
-
if (formatters.has(zone)) return true;
|
|
19
|
-
try {
|
|
20
|
-
new Intl.DateTimeFormat("en-US", { timeZone: zone });
|
|
21
|
-
return true;
|
|
22
|
-
} catch {
|
|
23
|
-
return false;
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
function deviceTimeZone() {
|
|
27
|
-
try {
|
|
28
|
-
return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
29
|
-
} catch {
|
|
30
|
-
return "UTC";
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
function partsFormatter(zone) {
|
|
34
|
-
let f = formatters.get(zone);
|
|
35
|
-
if (!f) {
|
|
36
|
-
f = new Intl.DateTimeFormat("en-US", {
|
|
37
|
-
timeZone: zone,
|
|
38
|
-
hourCycle: "h23",
|
|
39
|
-
year: "numeric",
|
|
40
|
-
month: "2-digit",
|
|
41
|
-
day: "2-digit",
|
|
42
|
-
hour: "2-digit",
|
|
43
|
-
minute: "2-digit",
|
|
44
|
-
second: "2-digit",
|
|
45
|
-
weekday: "short"
|
|
46
|
-
});
|
|
47
|
-
formatters.set(zone, f);
|
|
48
|
-
}
|
|
49
|
-
return f;
|
|
50
|
-
}
|
|
51
|
-
var WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
52
|
-
function wallClock(zone, at = /* @__PURE__ */ new Date()) {
|
|
53
|
-
if (!isTimeZone(zone)) throw new RangeError(`wallClock: unknown time zone "${zone}"`);
|
|
54
|
-
const parts = {};
|
|
55
|
-
for (const p of partsFormatter(zone).formatToParts(at)) parts[p.type] = p.value;
|
|
56
|
-
return {
|
|
57
|
-
year: Number(parts["year"]),
|
|
58
|
-
month: Number(parts["month"]),
|
|
59
|
-
day: Number(parts["day"]),
|
|
60
|
-
hour: Number(parts["hour"]),
|
|
61
|
-
minute: Number(parts["minute"]),
|
|
62
|
-
second: Number(parts["second"]),
|
|
63
|
-
weekday: WEEKDAYS.indexOf(parts["weekday"] ?? "")
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
var pad = (n, width = 2) => String(n).padStart(width, "0");
|
|
67
|
-
var dayOf = (y, m, d) => `${pad(y, 4)}-${pad(m)}-${pad(d)}`;
|
|
68
|
-
function dayIn(zone, at = /* @__PURE__ */ new Date()) {
|
|
69
|
-
const c = wallClock(zone, at);
|
|
70
|
-
return dayOf(c.year, c.month, c.day);
|
|
71
|
-
}
|
|
72
|
-
function personTimeZone(person) {
|
|
73
|
-
const saved = person?.timeZone;
|
|
74
|
-
return saved && isTimeZone(saved) ? saved : deviceTimeZone();
|
|
75
|
-
}
|
|
76
|
-
function personDay(person, at = /* @__PURE__ */ new Date()) {
|
|
77
|
-
return dayIn(personTimeZone(person), at);
|
|
78
|
-
}
|
|
79
|
-
function addDays(day, days) {
|
|
80
|
-
const [y, m, d] = assertDay(day, "addDays");
|
|
81
|
-
if (!Number.isInteger(days)) throw new RangeError(`addDays: ${days} is not a whole number of days`);
|
|
82
|
-
const t = new Date(Date.UTC(y, m - 1, d + days));
|
|
83
|
-
return dayOf(t.getUTCFullYear(), t.getUTCMonth() + 1, t.getUTCDate());
|
|
84
|
-
}
|
|
85
|
-
function daysBetween(from, to) {
|
|
86
|
-
const [y1, m1, d1] = assertDay(from, "daysBetween");
|
|
87
|
-
const [y2, m2, d2] = assertDay(to, "daysBetween");
|
|
88
|
-
return Math.round((Date.UTC(y2, m2 - 1, d2) - Date.UTC(y1, m1 - 1, d1)) / 864e5);
|
|
89
|
-
}
|
|
90
|
-
function weekdayOf(day) {
|
|
91
|
-
const [y, m, d] = assertDay(day, "weekdayOf");
|
|
92
|
-
return new Date(Date.UTC(y, m - 1, d)).getUTCDay();
|
|
93
|
-
}
|
|
94
|
-
function startOfWeek(day, weekStartsOn = 1) {
|
|
95
|
-
if (!Number.isInteger(weekStartsOn) || weekStartsOn < 0 || weekStartsOn > 6) throw new RangeError("startOfWeek: weekStartsOn is 0 to 6");
|
|
96
|
-
return addDays(day, -((weekdayOf(day) - weekStartsOn + 7) % 7));
|
|
97
|
-
}
|
|
98
|
-
function startOfDayIn(day, zone) {
|
|
99
|
-
const [y, m, d] = assertDay(day, "startOfDayIn");
|
|
100
|
-
const target = Date.UTC(y, m - 1, d);
|
|
101
|
-
let at = target;
|
|
102
|
-
for (let i = 0; i < 2; i++) {
|
|
103
|
-
const c = wallClock(zone, new Date(at));
|
|
104
|
-
const shown = Date.UTC(c.year, c.month - 1, c.day, c.hour, c.minute, c.second);
|
|
105
|
-
at -= shown - target;
|
|
106
|
-
}
|
|
107
|
-
while (dayIn(zone, new Date(at)) < day) at += 15 * 6e4;
|
|
108
|
-
while (dayIn(zone, new Date(at - 1)) === day) at -= 15 * 6e4;
|
|
109
|
-
return new Date(at);
|
|
110
|
-
}
|
|
111
|
-
function dayRangeIn(day, zone) {
|
|
112
|
-
return { start: startOfDayIn(day, zone), end: startOfDayIn(addDays(day, 1), zone) };
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
export { addDays, dayIn, dayRangeIn, daysBetween, deviceTimeZone, isDay, isTimeZone, personDay, personTimeZone, startOfDayIn, startOfWeek, wallClock, weekdayOf };
|
|
116
|
-
//# sourceMappingURL=chunk-3B4IFDMK.js.map
|
|
117
|
-
//# sourceMappingURL=chunk-3B4IFDMK.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/dates.ts"],"names":[],"mappings":";AAoBA,IAAM,GAAA,GAAM,2BAAA;AAGL,SAAS,MAAM,KAAA,EAA8B;AAClD,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,KAAA;AACtC,EAAA,MAAM,CAAA,GAAI,GAAA,CAAI,IAAA,CAAK,KAAK,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,EAAQ,EAAE,MAAM,CAAA;AAC7E,IAAA,EAAA,IAAM,KAAA,GAAQ,MAAA;AAAA,EAChB;AAEA,EAAA,OAAO,KAAA,CAAM,MAAM,IAAI,IAAA,CAAK,EAAE,CAAC,CAAA,GAAI,GAAA,EAAK,EAAA,IAAM,EAAA,GAAK,GAAA;AACnD,EAAA,OAAO,KAAA,CAAM,IAAA,EAAM,IAAI,IAAA,CAAK,EAAA,GAAK,CAAC,CAAC,CAAA,KAAM,GAAA,EAAK,EAAA,IAAM,EAAA,GAAK,GAAA;AACzD,EAAA,OAAO,IAAI,KAAK,EAAE,CAAA;AACpB;AAGO,SAAS,UAAA,CAAW,KAAU,IAAA,EAA0C;AAC7E,EAAA,OAAO,EAAE,KAAA,EAAO,YAAA,CAAa,GAAA,EAAK,IAAI,CAAA,EAAG,GAAA,EAAK,YAAA,CAAa,OAAA,CAAQ,GAAA,EAAK,CAAC,CAAA,EAAG,IAAI,CAAA,EAAE;AACpF","file":"chunk-3B4IFDMK.js","sourcesContent":["/**\n * `@marktiderman/genesis-core/dates`: calendar days on a person's clock.\n *\n * A \"day\" here is a `YYYY-MM-DD` string: the date on some time zone's wall\n * clock. Which zone is the whole question. `new Date().toISOString().slice(0, 10)`\n * is the day in UTC, which is tomorrow for an evening in the Americas and\n * yesterday for a morning in Asia. The browser's zone is the device's, not\n * necessarily the person's, and a server's is usually UTC. So every function\n * here takes the zone, and `personDay` picks it in one order everywhere: the\n * person's saved zone, then the device's, then UTC.\n *\n * No dependencies: `Intl.DateTimeFormat` does the zone arithmetic, so daylight\n * saving is right wherever the runtime's time zone data is.\n *\n * @packageDocumentation\n */\n\n/** `YYYY-MM-DD`. */\nexport type Day = string;\n\nconst DAY = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** Whether `value` is a real `YYYY-MM-DD` day (not `2026-02-30`). @stability Beta */\nexport function isDay(value: unknown): value is Day {\n if (typeof value !== \"string\") return false;\n const m = DAY.exec(value);\n if (!m) return false;\n const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));\n return d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() === Number(m[2]) - 1 && d.getUTCDate() === Number(m[3]);\n}\n\nfunction assertDay(day: Day, where: string): [number, number, number] {\n if (!isDay(day)) throw new RangeError(`${where}: \"${String(day)}\" is not a YYYY-MM-DD day`);\n const m = DAY.exec(day)!;\n return [Number(m[1]), Number(m[2]), Number(m[3])];\n}\n\n// One formatter per zone, made once: building an Intl.DateTimeFormat is the slow part.\nconst formatters = new Map<string, Intl.DateTimeFormat>();\n\n/** Whether the runtime knows `zone` (`\"America/Denver\"`). @stability Beta */\nexport function isTimeZone(zone: unknown): zone is string {\n if (typeof zone !== \"string\" || !zone) return false;\n if (formatters.has(zone)) return true;\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: zone });\n return true;\n } catch {\n return false;\n }\n}\n\n/** The device's (or server's) zone, `\"UTC\"` when the runtime can't say. @stability Beta */\nexport function deviceTimeZone(): string {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n } catch {\n return \"UTC\";\n }\n}\n\nfunction partsFormatter(zone: string): Intl.DateTimeFormat {\n let f = formatters.get(zone);\n if (!f) {\n f = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: zone,\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n weekday: \"short\",\n });\n formatters.set(zone, f);\n }\n return f;\n}\n\nconst WEEKDAYS = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n\n/** The wall clock in a zone at one instant. `weekday` is 0 for Sunday. @stability Beta */\nexport interface WallClock {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n weekday: number;\n}\n\n/** What the clock on the wall in `zone` says at `at`. @stability Beta */\nexport function wallClock(zone: string, at: Date = new Date()): WallClock {\n if (!isTimeZone(zone)) throw new RangeError(`wallClock: unknown time zone \"${zone}\"`);\n const parts: Record<string, string> = {};\n for (const p of partsFormatter(zone).formatToParts(at)) parts[p.type] = p.value;\n return {\n year: Number(parts[\"year\"]),\n month: Number(parts[\"month\"]),\n day: Number(parts[\"day\"]),\n hour: Number(parts[\"hour\"]),\n minute: Number(parts[\"minute\"]),\n second: Number(parts[\"second\"]),\n weekday: WEEKDAYS.indexOf(parts[\"weekday\"] ?? \"\"),\n };\n}\n\nconst pad = (n: number, width = 2) => String(n).padStart(width, \"0\");\nconst dayOf = (y: number, m: number, d: number): Day => `${pad(y, 4)}-${pad(m)}-${pad(d)}`;\n\n/** The day on `zone`'s clock at `at` (default now). @stability Beta */\nexport function dayIn(zone: string, at: Date = new Date()): Day {\n const c = wallClock(zone, at);\n return dayOf(c.year, c.month, c.day);\n}\n\n/** Someone whose days are counted: their saved zone, when they have one. */\nexport interface PersonClock {\n timeZone?: string | null | undefined;\n}\n\n/**\n * The zone a person's days are counted in: their saved zone if the runtime\n * knows it, else the device's, else UTC. On a server, pass the person's zone:\n * the server's own is rarely theirs.\n *\n * @stability Beta\n */\nexport function personTimeZone(person?: PersonClock | null): string {\n const saved = person?.timeZone;\n return saved && isTimeZone(saved) ? saved : deviceTimeZone();\n}\n\n/**\n * Today (or the day at `at`) for this person: `dayIn(personTimeZone(person), at)`.\n *\n * ```ts\n * const today = personDay(profile); // \"2026-10-26\" on their clock\n * const dueToday = tasks.filter((t) => t.due_on === today);\n * ```\n *\n * @stability Beta\n */\nexport function personDay(person?: PersonClock | null, at: Date = new Date()): Day {\n return dayIn(personTimeZone(person), at);\n}\n\n/** `day` moved by `days` (negative goes back). Calendar arithmetic: no zone, no daylight saving. @stability Beta */\nexport function addDays(day: Day, days: number): Day {\n const [y, m, d] = assertDay(day, \"addDays\");\n if (!Number.isInteger(days)) throw new RangeError(`addDays: ${days} is not a whole number of days`);\n const t = new Date(Date.UTC(y, m - 1, d + days));\n return dayOf(t.getUTCFullYear(), t.getUTCMonth() + 1, t.getUTCDate());\n}\n\n/** Whole days from `from` to `to` (`to` − `from`; negative when `to` is earlier). @stability Beta */\nexport function daysBetween(from: Day, to: Day): number {\n const [y1, m1, d1] = assertDay(from, \"daysBetween\");\n const [y2, m2, d2] = assertDay(to, \"daysBetween\");\n return Math.round((Date.UTC(y2, m2 - 1, d2) - Date.UTC(y1, m1 - 1, d1)) / 86_400_000);\n}\n\n/** The weekday of a day, 0 for Sunday. @stability Beta */\nexport function weekdayOf(day: Day): number {\n const [y, m, d] = assertDay(day, \"weekdayOf\");\n return new Date(Date.UTC(y, m - 1, d)).getUTCDay();\n}\n\n/** The first day of `day`'s week, with weeks starting on `weekStartsOn` (0 Sunday … 6 Saturday; default 1, Monday). @stability Beta */\nexport function startOfWeek(day: Day, weekStartsOn = 1): Day {\n if (!Number.isInteger(weekStartsOn) || weekStartsOn < 0 || weekStartsOn > 6) throw new RangeError(\"startOfWeek: weekStartsOn is 0 to 6\");\n return addDays(day, -((weekdayOf(day) - weekStartsOn + 7) % 7));\n}\n\n/**\n * The instant `day` starts on `zone`'s clock: what to compare `created_at`\n * with for \"since midnight\". Where midnight doesn't exist (a daylight-saving\n * jump at 00:00), it's the first instant of the day that does.\n *\n * @stability Beta\n */\nexport function startOfDayIn(day: Day, zone: string): Date {\n const [y, m, d] = assertDay(day, \"startOfDayIn\");\n const target = Date.UTC(y, m - 1, d);\n // Guess the instant as if the zone were UTC, then correct by the zone's offset there, twice\n // (the second pass settles a guess that landed across a transition).\n let at = target;\n for (let i = 0; i < 2; i++) {\n const c = wallClock(zone, new Date(at));\n const shown = Date.UTC(c.year, c.month - 1, c.day, c.hour, c.minute, c.second);\n at -= shown - target;\n }\n // Midnight skipped by a transition: step forward to the first instant on that day.\n while (dayIn(zone, new Date(at)) < day) at += 15 * 60_000;\n while (dayIn(zone, new Date(at - 1)) === day) at -= 15 * 60_000;\n return new Date(at);\n}\n\n/** The `[start, end)` instants of `day` on `zone`'s clock (23 or 25 hours on daylight-saving days). @stability Beta */\nexport function dayRangeIn(day: Day, zone: string): { start: Date; end: Date } {\n return { start: startOfDayIn(day, zone), end: startOfDayIn(addDays(day, 1), zone) };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";;;;;AAwCA,SAAS,aAAA,GAAyB;AAChC,EAAA,IAAI,OAAO,OAAA,KAAY,WAAA,EAAa,OAAO,QAAQ,OAAO,CAAA;AAC1D,EAAA,MAAM,MAAM,OAAO,OAAA,KAAY,WAAA,GAAc,OAAA,CAAQ,KAAK,QAAA,GAAW,MAAA;AACrE,EAAA,OAAO,GAAA,KAAQ,YAAA;AACjB;AAGO,IAAM,oBAAA,GAAsC,CAAC,KAAA,EAAO,OAAA,KAAY;AACrE,EAAA,IAAI,CAAC,eAAc,EAAG;AAEtB,EAAA,OAAA,CAAQ,IAAA,CAAK,CAAA,UAAA,EAAa,OAAA,CAAQ,MAAM,KAAK,KAAK,CAAA;AACpD;AAGA,IAAM,GAAA,mBAAM,MAAA,CAAO,GAAA,CAAI,uBAAuB,CAAA;AAIvC,SAAS,gBAAA,GAAkC;AAChD,EAAA,OAAQ,UAAA,CAAsB,GAAG,CAAA,IAAK,oBAAA;AACxC;AAOO,SAAS,iBAAiB,QAAA,EAA4C;AAC3E,EAAA,MAAM,MAAA,GAAS,UAAA;AACf,EAAA,MAAM,QAAA,GAAW,OAAO,GAAG,CAAA;AAC3B,EAAA,IAAI,QAAA,EAAU,MAAA,CAAO,GAAG,CAAA,GAAI,QAAA;AAAA,OACvB,OAAO,OAAO,GAAG,CAAA;AACtB,EAAA,OAAO,MAAM;AACX,IAAA,IAAI,QAAA,EAAU,MAAA,CAAO,GAAG,CAAA,GAAI,QAAA;AAAA,SACvB,OAAO,OAAO,GAAG,CAAA;AAAA,EACxB,CAAA;AACF;AAOO,SAAS,WAAA,CAAY,OAAgB,OAAA,EAA4C;AACtF,EAAA,MAAM,OAA2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KAAA,EAAO,QAAQ,CAAA,IAAK,KAAA,CAAM,OAAO,YAAY,CAAA;AAClE,EAAA,MAAM,OAAA,GAAU,OAAO,MAAA,KAAW,QAAA,GAAW,MAAA,GAAS,OAAO,MAAA,KAAW,QAAA,GAAW,MAAA,CAAO,MAAM,CAAA,GAAI,GAAA;AACpG,EAAA,IAAI,MAAA,CAAO,SAAA,CAAU,OAAO,CAAA,EAAG;AAC7B,IAAA,MAAM,QAAA,GAAW,WAAW,OAAO,CAAA;AACnC,IAAA,IAAI,UAAU,OAAO,QAAA;AAAA,EACvB;AACA,EAAA,IAAI,OAAA,CAAQ,aAAY,EAAG,OAAO,EAAE,IAAA,EAAM,SAAA,EAAW,QAAQ,KAAA,EAAM;AACnE,EAAA,OAAO,EAAE,IAAA,EAAM,YAAA,EAAc,MAAA,EAAQ,IAAA,EAAK;AAC5C;AAWO,SAAS,aAAA,CAAc,KAAA,EAAgB,OAAA,GAAgC,EAAC,EAAoB;AACjG,EAAA,IAAI,IAAA;AACJ,EAAA,IAAI;AACF,IAAA,IAAA,GAAO,MAAA,CAAO,OAAO,OAAO,CAAA;AAAA,EAC9B,CAAA,CAAA,MAAQ;AAEN,IAAA,IAAA,GAAO,EAAE,IAAA,EAAM,YAAA,EAAc,MAAA,EAAQ,IAAA,EAAK;AAAA,EAC5C;AACA,EAAA,MAAM,OAAA,GAAU,QAAQ,QAAA,GAAW,IAAA,CAAK,IAAI,CAAA,IAAK,aAAA,CAAc,KAAK,IAAI,CAAA;AACxE,EAAA,OAAO,EAAE,GAAG,IAAA,EAAM,OAAA,EAAQ;AAC5B","file":"chunk-ZIMQUFXD.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Errors: one way for every Genesis package to report a caught error, and one\n// way to say what kind of error it is.\n//\n// `reportError(error, context)` is the seam a package calls when it catches\n// something it can't handle itself (a card's action that threw, a draft that\n// couldn't be saved). The host app decides where it goes: a native app's\n// observability block registers itself with `setErrorReporter` and sends it,\n// scrubbed, to Sentry; with nothing registered it is written with\n// `console.warn` in development and dropped in production.\n//\n// `classifyError(error)` sorts anything thrown into a few kinds a screen can\n// act on (offline, signed out, refused, gone, conflict, bad input, a bug),\n// with a sentence that is safe to show and whether it is worth reporting.\n// It is built on the provider's read and write outcomes.\n// ---------------------------------------------------------------------------\n\nimport { readOutcomeFromCode, writeOutcomeFromCode } from \"./provider/postgrest-errors\";\nimport { isDataReadError } from \"./schema/read-outcome\";\nimport { isDataWriteError } from \"./schema/write-outcome\";\n\n/** Where a reported error came from. */\nexport interface ErrorReportContext {\n /**\n * Which part caught it, as `package:part` (`chat:attachment-action`,\n * `forms-native:draft-save`). Low-cardinality: never an id or text.\n */\n source: string;\n /** True when the app could not go on. Default false: a package that reports has handled it. */\n fatal?: boolean;\n /** Low-cardinality labels (`query.key: \"tasks\"`), never ids, emails or text someone typed. */\n tags?: Readonly<Record<string, string>>;\n}\n\n/** Where `reportError` sends errors. A throw inside it is ignored. */\nexport type ErrorReporter = (error: unknown, context: ErrorReportContext) => void;\n\ndeclare const __DEV__: boolean | undefined;\n\n/** True in a development build (`__DEV__` on React Native, `NODE_ENV` elsewhere). */\nfunction isDevelopment(): boolean {\n if (typeof __DEV__ !== \"undefined\") return Boolean(__DEV__);\n const env = typeof process !== \"undefined\" ? process.env?.NODE_ENV : undefined;\n return env !== \"production\";\n}\n\n/** The reporter used when the app registered none: `console.warn` in development, nothing in production. */\nexport const defaultErrorReporter: ErrorReporter = (error, context) => {\n if (!isDevelopment()) return;\n // genesis-allow-console: the development fallback of the reporting seam itself.\n console.warn(`[genesis] ${context.source}:`, error);\n};\n\n// Kept on globalThis so two copies of this package (a bundling slip) still share one reporter.\nconst KEY = Symbol.for(\"genesis.errorReporter\");\ntype Holder = { [KEY]?: ErrorReporter };\n\n/** The reporter `reportError` uses now. */\nexport function getErrorReporter(): ErrorReporter {\n return (globalThis as Holder)[KEY] ?? defaultErrorReporter;\n}\n\n/**\n * Send every `reportError` to `reporter` (`null` puts the default back).\n * Returns a function that restores the reporter that was there before.\n * The native observability block calls it when it is created.\n */\nexport function setErrorReporter(reporter: ErrorReporter | null): () => void {\n const holder = globalThis as Holder;\n const previous = holder[KEY];\n if (reporter) holder[KEY] = reporter;\n else delete holder[KEY];\n return () => {\n if (previous) holder[KEY] = previous;\n else delete holder[KEY];\n };\n}\n\n/**\n * Report an error a package caught and handled. Never throws: a failing\n * reporter must not take the caller (an event handler, a render) down.\n * `context` may be just the source.\n */\nexport function reportError(error: unknown, context: ErrorReportContext | string): void {\n const full: ErrorReportContext = typeof context === \"string\" ? { source: context } : context;\n try {\n getErrorReporter()(error, full);\n } catch {\n // A failing reporter is ignored; reporting is never worth a second error.\n }\n}\n\n// ---------------------------------------------------------------------------\n// classifyError\n// ---------------------------------------------------------------------------\n\n/**\n * - `offline`: the request never reached the server (no network).\n * - `unauthenticated`: nobody is signed in, or the session ended.\n * - `forbidden`: the server refused this user.\n * - `not-found`: the record doesn't exist, or this user can't see it.\n * - `conflict`: someone else changed it first, or it already exists.\n * - `invalid`: the request or a value in it was rejected.\n * - `unexpected`: anything else (a bug, a server error).\n */\nexport type ErrorKind = \"offline\" | \"unauthenticated\" | \"forbidden\" | \"not-found\" | \"conflict\" | \"invalid\" | \"unexpected\";\n\n/** The sentence shown for each kind. Override any of them with `classifyError(e, { messages })`. */\nexport type ErrorMessages = Readonly<Record<ErrorKind, string>>;\n\n/** The English catalogue. Plain words, never the store's text. */\nexport const errorMessages: ErrorMessages = {\n offline: \"You're offline. Check your connection and try again.\",\n unauthenticated: \"Your session has ended. Sign in again to continue.\",\n forbidden: \"You don't have permission to do that.\",\n \"not-found\": \"This isn't here any more, or you can't see it.\",\n conflict: \"Someone else changed this first. Refresh and try again.\",\n invalid: \"Something in this couldn't be accepted. Check it and try again.\",\n unexpected: \"Something went wrong. Try again.\",\n};\n\nexport interface ClassifiedError {\n kind: ErrorKind;\n /** Safe to show: from the messages catalogue, never the error's own text. */\n message: string;\n /** Worth reporting to a crash tracker: a bug or a server failure, not something the user or the network caused. */\n report: boolean;\n}\n\nexport interface ClassifyErrorOptions {\n /** Reworded or translated sentences; what you leave out stays English. */\n messages?: Partial<ErrorMessages>;\n /** True when the device knows it is offline (TanStack's `onlineManager`, NetInfo). */\n isOffline?: () => boolean;\n}\n\n// The text each runtime's fetch throws when the request never left the device.\nconst NETWORK_MESSAGES = [\n /^network request failed$/i, // React Native\n /^failed to fetch$/i, // Chromium\n /^load failed$/i, // Safari\n /^networkerror when attempting to fetch resource\\.?$/i, // Firefox\n /^network error$/i,\n /^the internet connection appears to be offline\\.?$/i,\n];\n// Supabase's wrappers around a fetch that never reached the server.\nconst NETWORK_NAMES = new Set([\"AuthRetryableFetchError\", \"FunctionsFetchError\", \"StorageUnknownError\"]);\n\nfunction field(error: unknown, name: string): unknown {\n return typeof error === \"object\" && error !== null ? (error as Record<string, unknown>)[name] : undefined;\n}\n\nfunction isNetworkError(error: unknown): boolean {\n const name = field(error, \"name\");\n const message = field(error, \"message\");\n if (typeof name === \"string\" && NETWORK_NAMES.has(name)) {\n // StorageUnknownError covers other failures too; only its network form counts.\n return name !== \"StorageUnknownError\" || (typeof message === \"string\" && NETWORK_MESSAGES.some((re) => re.test(message)));\n }\n return typeof message === \"string\" && NETWORK_MESSAGES.some((re) => re.test(message.trim()));\n}\n\nfunction fromStatus(status: number): Omit<ClassifiedError, \"message\"> | null {\n if (status === 401) return { kind: \"unauthenticated\", report: false };\n if (status === 403) return { kind: \"forbidden\", report: false };\n if (status === 404 || status === 410) return { kind: \"not-found\", report: false };\n if (status === 409 || status === 412) return { kind: \"conflict\", report: false };\n if (status === 400 || status === 422) return { kind: \"invalid\", report: true };\n if (status === 429) return { kind: \"unexpected\", report: false };\n return null;\n}\n\nfunction kindOf(error: unknown, options: ClassifyErrorOptions): Omit<ClassifiedError, \"message\"> {\n if (isDataWriteError(error)) {\n switch (error.outcome) {\n case \"conflict\":\n case \"duplicate\":\n return { kind: \"conflict\", report: false };\n case \"gone\":\n return { kind: \"not-found\", report: false };\n case \"forbidden\":\n return { kind: \"forbidden\", report: false };\n case \"invalid\":\n return { kind: \"invalid\", report: false };\n case \"unauthenticated\":\n return { kind: \"unauthenticated\", report: false };\n default:\n // `error` and `audit_failed`: a network failure surfaces here as the write's cause.\n if (isNetworkError(error.cause ?? error) || options.isOffline?.()) return { kind: \"offline\", report: false };\n return { kind: \"unexpected\", report: true };\n }\n }\n if (isDataReadError(error)) {\n switch (error.outcome) {\n case \"unauthenticated\":\n return { kind: \"unauthenticated\", report: false };\n case \"forbidden\":\n return { kind: \"forbidden\", report: false };\n case \"gone\":\n return { kind: \"not-found\", report: false };\n case \"invalid\":\n // The request itself was wrong (an unknown column): a bug worth seeing.\n return { kind: \"invalid\", report: true };\n default:\n if (isNetworkError(error.cause ?? error) || options.isOffline?.()) return { kind: \"offline\", report: false };\n return { kind: \"unexpected\", report: true };\n }\n }\n if (isNetworkError(error)) return { kind: \"offline\", report: false };\n const code = field(error, \"code\");\n if (typeof code === \"string\" && code) {\n const read = readOutcomeFromCode(code);\n if (read === \"invalid\" && writeOutcomeFromCode(code) === \"error\") return { kind: \"invalid\", report: true };\n switch (writeOutcomeFromCode(code)) {\n case \"unauthenticated\":\n return { kind: \"unauthenticated\", report: false };\n case \"forbidden\":\n return { kind: \"forbidden\", report: false };\n case \"gone\":\n return { kind: \"not-found\", report: false };\n case \"duplicate\":\n return { kind: \"conflict\", report: false };\n case \"invalid\":\n return { kind: \"invalid\", report: false };\n default:\n break;\n }\n }\n const name = field(error, \"name\");\n if (name === \"AuthSessionMissingError\") return { kind: \"unauthenticated\", report: false };\n const status = field(error, \"status\") ?? field(error, \"statusCode\");\n const numeric = typeof status === \"number\" ? status : typeof status === \"string\" ? Number(status) : NaN;\n if (Number.isInteger(numeric)) {\n const byStatus = fromStatus(numeric);\n if (byStatus) return byStatus;\n }\n if (options.isOffline?.()) return { kind: \"offline\", report: false };\n return { kind: \"unexpected\", report: true };\n}\n\n/**\n * What kind of error this is, a sentence that is safe to show, and whether it\n * is worth reporting. Understands the provider's `DataWriteError` and\n * `DataReadError`, Postgres and PostgREST codes, HTTP statuses, Supabase's\n * auth and fetch errors, and each runtime's \"network request failed\".\n *\n * Use it for a toast (`toast.error(classifyError(e).message)`) and to decide\n * whether to report (`if (classifyError(e).report) reportError(e, …)`).\n */\nexport function classifyError(error: unknown, options: ClassifyErrorOptions = {}): ClassifiedError {\n let base: Omit<ClassifiedError, \"message\">;\n try {\n base = kindOf(error, options);\n } catch {\n // A getter that throws on an exotic value: still an answer, never a second error.\n base = { kind: \"unexpected\", report: true };\n }\n const message = options.messages?.[base.kind] ?? errorMessages[base.kind];\n return { ...base, message };\n}\n"]}
|