@marktiderman/genesis-core 1.12.0 → 1.13.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.
Files changed (80) hide show
  1. package/README.md +32 -0
  2. package/dist/chunk-3B4IFDMK.js +117 -0
  3. package/dist/chunk-3B4IFDMK.js.map +1 -0
  4. package/dist/chunk-7FVTGKTX.js +8 -0
  5. package/dist/chunk-7FVTGKTX.js.map +1 -0
  6. package/dist/chunk-AUVKRXRC.js +81 -0
  7. package/dist/chunk-AUVKRXRC.js.map +1 -0
  8. package/dist/chunk-FARKPY6R.js +66 -0
  9. package/dist/chunk-FARKPY6R.js.map +1 -0
  10. package/dist/{chunk-OSPLIKSH.js → chunk-GEF5W2LO.js} +19 -9
  11. package/dist/chunk-GEF5W2LO.js.map +1 -0
  12. package/dist/{chunk-NMFABW4Y.js → chunk-JKZ2FVWK.js} +5 -5
  13. package/dist/{chunk-NMFABW4Y.js.map → chunk-JKZ2FVWK.js.map} +1 -1
  14. package/dist/{chunk-RCAP3Q4T.js → chunk-OYIUIW7C.js} +3 -2
  15. package/dist/chunk-OYIUIW7C.js.map +1 -0
  16. package/dist/{chunk-S2ZXUNXB.js → chunk-REYTMXAA.js} +3 -3
  17. package/dist/{chunk-S2ZXUNXB.js.map → chunk-REYTMXAA.js.map} +1 -1
  18. package/dist/{chunk-BGTXN2E6.js → chunk-RF6YVWHX.js} +4 -4
  19. package/dist/{chunk-BGTXN2E6.js.map → chunk-RF6YVWHX.js.map} +1 -1
  20. package/dist/{chunk-TOU2CMDH.js → chunk-TCL27Q5W.js} +167 -58
  21. package/dist/chunk-TCL27Q5W.js.map +1 -0
  22. package/dist/{chunk-NZPJI7FC.js → chunk-UGGMJUFQ.js} +45 -13
  23. package/dist/chunk-UGGMJUFQ.js.map +1 -0
  24. package/dist/{chunk-KXVHDK3Q.js → chunk-UV3ROHQA.js} +27 -5
  25. package/dist/chunk-UV3ROHQA.js.map +1 -0
  26. package/dist/chunk-YDDPFSQ6.js +35 -0
  27. package/dist/chunk-YDDPFSQ6.js.map +1 -0
  28. package/dist/csv.d.ts +41 -0
  29. package/dist/csv.js +77 -0
  30. package/dist/csv.js.map +1 -0
  31. package/dist/dates.js +1 -115
  32. package/dist/dates.js.map +1 -1
  33. package/dist/hooks/index.d.ts +7 -43
  34. package/dist/hooks/index.js +14 -12
  35. package/dist/hooks/live-cache.d.ts +15 -0
  36. package/dist/hooks/live-cache.js +3 -0
  37. package/dist/hooks/live-cache.js.map +1 -0
  38. package/dist/hooks/mutation-mode.d.ts +2 -2
  39. package/dist/hooks/mutation-mode.js +2 -2
  40. package/dist/hooks/related-keys.d.ts +2 -2
  41. package/dist/hooks/use-capabilities.d.ts +1 -1
  42. package/dist/hooks/use-infinite-resource.d.ts +18 -2
  43. package/dist/hooks/use-infinite-resource.js +4 -3
  44. package/dist/hooks/use-live.d.ts +15 -3
  45. package/dist/hooks/use-live.js +2 -1
  46. package/dist/hooks/use-one.d.ts +2 -2
  47. package/dist/hooks/use-one.js +4 -3
  48. package/dist/hooks/use-resource-form.d.ts +9 -2
  49. package/dist/hooks/use-resource-form.js +7 -6
  50. package/dist/hooks/use-resource.d.ts +2 -2
  51. package/dist/hooks/use-resource.js +5 -4
  52. package/dist/hooks/use-write.d.ts +2 -2
  53. package/dist/index.d.ts +13 -6
  54. package/dist/index.js +19 -15
  55. package/dist/provider/index.d.ts +11 -6
  56. package/dist/provider/index.js +2 -2
  57. package/dist/resource/index.d.ts +86 -0
  58. package/dist/resource/index.js +85 -0
  59. package/dist/resource/index.js.map +1 -0
  60. package/dist/resource-view/index.d.ts +285 -0
  61. package/dist/resource-view/index.js +320 -0
  62. package/dist/resource-view/index.js.map +1 -0
  63. package/dist/schema/index.d.ts +4 -4
  64. package/dist/schema/index.js +1 -0
  65. package/dist/testing/index.d.ts +3 -3
  66. package/dist/{types-B9DDfvWa.d.ts → types-CXhqXPN1.d.ts} +21 -4
  67. package/dist/{types-C7FJtFXV.d.ts → types-o8j7g6O6.d.ts} +38 -1
  68. package/dist/urls.d.ts +18 -0
  69. package/dist/urls.js +3 -0
  70. package/dist/urls.js.map +1 -0
  71. package/dist/viewer-scope-0dR-_o0f.d.ts +76 -0
  72. package/dist/{write-outcome-B2fE29yZ.d.ts → write-outcome-CFnpciUI.d.ts} +1 -1
  73. package/package.json +17 -1
  74. package/dist/chunk-5ORRAXIV.js +0 -30
  75. package/dist/chunk-5ORRAXIV.js.map +0 -1
  76. package/dist/chunk-KXVHDK3Q.js.map +0 -1
  77. package/dist/chunk-NZPJI7FC.js.map +0 -1
  78. package/dist/chunk-OSPLIKSH.js.map +0 -1
  79. package/dist/chunk-RCAP3Q4T.js.map +0 -1
  80. package/dist/chunk-TOU2CMDH.js.map +0 -1
package/README.md CHANGED
@@ -139,6 +139,13 @@ create view public.tasks_with_people with (security_invoker = true) as
139
139
  Writes send only the table's own columns: list them as `writeColumns`, or an update keeps just the
140
140
  columns the table's row has, so a form built from the view row never sends `person_name` back.
141
141
 
142
+ ### Counting totals
143
+
144
+ `total` is exact by default, which scans every matching row. For a large table, set
145
+ `resources.<name>.count` to `"estimated"` (or `"planned"`): the database's statistics answer
146
+ instantly and `totalIsEstimate` is true, so a screen can say "about 90,000". `"none"` skips the
147
+ count (`total` is -1). A caller can override per request with `getList(resource, { count })`.
148
+
142
149
  ### Handling failures
143
150
 
144
151
  ```ts
@@ -531,6 +538,13 @@ Keys are `[domain, kind, { ...fields, viewer, group?, day? }]`. `where(fields, k
531
538
  field that is equal (`1` matches `"1"`; objects in any key order), an array field containing the
532
539
  value, or for an array value an array field containing every item. Never a substring.
533
540
 
541
+ `ViewerScope` also carries **where** the viewer is working: `scope={{ practiceId }}` (or
542
+ `personId`, `spaceId`, a `personIds` set). Read it with `useViewerScope()`; screens turn it into
543
+ server filters and create defaults. It never decides access, and changing it remounts nothing.
544
+ Pass the viewer's saved `timeZone` too: `useViewerScope().day` is today on their clock (kept current
545
+ when the page comes back into view, and across midnight), and `keys.for(useViewerScope())` uses it
546
+ as the key's `day`, so no screen works out "today" itself.
547
+
534
548
  With a persisted cache (a native app's saved query cache), pass the viewer it was saved for as
535
549
  `persistedViewer`, or the first known viewer empties it on every cold start. Without `ViewerScope`, call `clearViewerCache(queryClient)` in the sign-in and
536
550
  sign-out actions, before the session changes: it also sends the old viewer's waiting undoable
@@ -569,6 +583,24 @@ const release = useWrite((itemId: string) => callRpc(supabase, "release_step", {
569
583
  `run(args)` rejects on failure; `fire(args)` never does (the error shows in `error`). One write runs at a
570
584
  time: a second click while it runs gets the same promise, not a second write.
571
585
 
586
+ ## Resource page rules (`/resource`)
587
+
588
+ The pure rules behind a resource page (a form, a course, a lesson, a worksheet), with no React,
589
+ so a server or a phone app can use them: `readinessOf(findings, { emptyCode, pending })` and
590
+ `readinessChip(readiness, labels)` (the readiness chip's words and tone), `SAVE_STATE_LABEL`,
591
+ `dayLabel` ("Today", "Yesterday", "Oct 21"), `prefilledUrl` and `embedSnippet` (the Share
592
+ dialog's links), and the types `ChipTone`, `SaveState`, `Readiness`, `ReadinessFinding`,
593
+ `ReadinessOptions`, `ReadinessLabels`, `PrefillChoice`, `HeadlineNumber` (a headline number as
594
+ data) and `HeadlineTone`. genesis-ui's `/resource` components draw them, and
595
+ `@marktiderman/genesis-ui/resource/rules` re-exports the same functions.
596
+
597
+ ```ts
598
+ import { readinessChip, readinessOf } from "@marktiderman/genesis-core/resource";
599
+
600
+ readinessChip(readinessOf(findings, { emptyCode: "no-lessons" }), { empty: "Add a lesson" });
601
+ // → { label: "Add a lesson", tone: "muted" }
602
+ ```
603
+
572
604
  ## Days and time zones (`/dates`)
573
605
 
574
606
  A day is a `YYYY-MM-DD` string: the date on one time zone's clock. `new Date().toISOString().slice(0, 10)`
@@ -0,0 +1,117 @@
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
@@ -0,0 +1 @@
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,CAAA;AACxB,EAAA,IAAI,CAAC,GAAG,OAAO,KAAA;AACf,EAAA,MAAM,CAAA,GAAI,IAAI,IAAA,CAAK,IAAA,CAAK,IAAI,MAAA,CAAO,CAAA,CAAE,CAAC,CAAC,CAAA,EAAG,OAAO,CAAA,CAAE,CAAC,CAAC,CAAA,GAAI,CAAA,EAAG,OAAO,CAAA,CAAE,CAAC,CAAC,CAAC,CAAC,CAAA;AACzE,EAAA,OAAO,CAAA,CAAE,gBAAe,KAAM,MAAA,CAAO,EAAE,CAAC,CAAC,CAAA,IAAK,CAAA,CAAE,WAAA,EAAY,KAAM,OAAO,CAAA,CAAE,CAAC,CAAC,CAAA,GAAI,CAAA,IAAK,CAAA,CAAE,YAAW,KAAM,MAAA,CAAO,CAAA,CAAE,CAAC,CAAC,CAAA;AACtH;AAEA,SAAS,SAAA,CAAU,KAAU,K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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"]}
@@ -0,0 +1,8 @@
1
+ // src/schema/types.ts
2
+ function defineResource() {
3
+ return (contract) => contract;
4
+ }
5
+
6
+ export { defineResource };
7
+ //# sourceMappingURL=chunk-7FVTGKTX.js.map
8
+ //# sourceMappingURL=chunk-7FVTGKTX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schema/types.ts"],"names":[],"mappings":";AA+IO,SAAS,cAAA,GAAsC;AACpD,EAAA,OAAO,CACL,QAAA,KACiC,QAAA;AACrC","file":"chunk-7FVTGKTX.js","sourcesContent":["// ---------------------------------------------------------------------------\n// The one schema model (docs/DATA-STUDIO.md decisions 11, 12, 13, 30)\n//\n// Promoted from @marktiderman/genesis-switchboard, which keeps deprecated\n// aliases for one deprecation window. Everything here is a type or a pure\n// helper with no React, no runtime dependency and no I/O, so a server, an\n// edge function or the switchboard can import it without pulling in the\n// React half of this package.\n// ---------------------------------------------------------------------------\n\nimport type { FieldType as WidgetHint } from \"../form-types\";\n\nexport type { WidgetHint };\n\n/**\n * Portable storage type of a field — what kind of value the store holds,\n * independent of how a UI should edit it. The exact native type, when the\n * store reports one, is on {@link FieldSchema.dbType}.\n *\n * Exactly the six types the switchboard shipped as `FieldType`, so existing\n * exhaustive maps over it keep compiling. Finer distinctions (date versus\n * timestamp, enum, uuid) live in `dbType` and `widget`, not here.\n */\nexport type StorageType = \"string\" | \"number\" | \"boolean\" | \"datetime\" | \"json\" | \"relation\";\n\n/** A canonical, provider-agnostic row. Keys are field names from the schema. */\nexport type DataRow = Record<string, unknown>;\n\n/**\n * What the CURRENT user may do with one field. Reported by a provider's\n * `describe()`; never inferred in the browser.\n *\n * `read: false` means the value is never sent to this user, so the column\n * must not render at all (an answer key, a payout amount). `update: false`\n * with `read: true` renders the column read-only.\n */\nexport interface FieldPermissions {\n readonly read: boolean;\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n}\n\n/** A foreign-key style link from this field to another resource's field. */\nexport interface FieldReference {\n readonly resource: string;\n readonly field: string;\n}\n\nexport interface FieldSchema {\n /** Canonical field name in the resource's shape (provider-agnostic). */\n readonly name: string;\n /** Portable storage type. */\n readonly type: StorageType;\n /** True when a row may omit this field. */\n readonly optional?: boolean;\n /**\n * True when the field holds an ORDERED LIST of `type` values (e.g. a\n * multi-relation like `deps`/`serves`). Promotion emits a Postgres ARRAY\n * column (`<base>[]`) instead of a lossy scalar, so the cardinality survives\n * L1→L3 (CMT-1742-014).\n */\n readonly array?: boolean;\n /** Human note (surfaces in describe()/drift reports). */\n readonly description?: string;\n /** Human label, e.g. \"Date of birth\". Absent means a UI derives one from `name`. */\n readonly label?: string;\n /** The store's exact type, e.g. `timestamp with time zone` or `public.status`. */\n readonly dbType?: string;\n /** Which control fits this field. A hint: a UI may still choose another. */\n readonly widget?: WidgetHint;\n /** True when the store accepts null for this field. */\n readonly nullable?: boolean;\n /** True when the store fills the field itself on insert. */\n readonly hasDefault?: boolean;\n /** True when the store computes the field; it is never written. */\n readonly generated?: boolean;\n /** Allowed values, for enum-like fields. */\n readonly enumValues?: readonly string[];\n /** The resource and field this one points at, when it is a link. */\n readonly references?: FieldReference;\n /** The current user's rights on this field, when a provider reports them. */\n readonly permissions?: FieldPermissions;\n /**\n * The server owns this field (a status it derives, a total, an audit stamp): clients never write\n * it, so a UI shows it read-only. Declared once (`@genesis {\"readonly\": true}`); the database's\n * own guards still enforce it.\n */\n readonly readOnly?: boolean;\n /**\n * The value is sensitive (a note for staff, a health detail): a UI leaves it out of lists, exports\n * and previews unless a screen asks for it. Hiding it from a user is the database's job.\n */\n readonly sensitive?: boolean;\n}\n\n/**\n * One declaration of a resource: its fields and its identity.\n *\n * `key` names the identity field, or several for a composite key (a junction\n * table keyed on `(team_id, user_id)`). Use {@link keyFields} to read it as\n * a list without caring which form it took.\n */\nexport interface ResourceContract<Row extends DataRow = DataRow> {\n /** Resource name the app addresses, e.g. \"tickets\" or \"public.tickets\". */\n readonly name: string;\n /**\n * Identity field name, or names for a composite key, in key order.\n *\n * Typed `string` (not `keyof Row & string`) on purpose: `keyof Row` is a\n * dependent type that TypeScript checks contravariantly, which would make\n * `ResourceContract<WorkCycleRow>` non-assignable to the erased\n * `ResourceContract<DataRow>` that generic consumers accept. The key is\n * validated against the field schema at runtime instead.\n */\n readonly key: string | readonly string[];\n readonly fields: readonly FieldSchema[];\n /** Optional doc string. */\n readonly description?: string;\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** What one row is called in sentences (\"brand\"), and several (\"brands\") when not `noun` + \"s\". */\n readonly noun?: string;\n readonly nounPlural?: string;\n /** Phantom marker so `Row` is inferable from a contract. */\n readonly __row?: Row;\n}\n\n/** The row type a contract describes (its phantom `__row`), or `DataRow` when it carries none. */\nexport type RowOf<C> = C extends { readonly __row?: infer R } ? (unknown extends R ? DataRow : NonNullable<R>) : DataRow;\n\n/**\n * Declares a resource contract for a row type, keeping the literal contract (field names, key,\n * labelField) and attaching the row type so views can read it with `RowOf`. `labelField` must be\n * one of the row's fields.\n *\n * ```ts\n * export const publicBrands = defineResource<PublicBrandsRow>()({ name: \"public.brands\", key: \"id\", fields: [...] });\n * type Row = RowOf<typeof publicBrands>; // PublicBrandsRow\n * ```\n */\nexport function defineResource<Row extends DataRow>() {\n return <const C extends ResourceContract<Row> & { readonly labelField?: keyof Row & string }>(\n contract: C,\n ): C & { readonly __row?: Row } => contract;\n}\n\n/** What the current user may do with a whole resource. */\nexport interface ResourceAccess {\n readonly read: boolean;\n /** True when at least one field can be updated on rows this user can see. */\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n /** True when this user may add rows. Absent means the provider doesn't say. */\n readonly create?: boolean;\n /** True when this user may delete rows they can see. */\n readonly delete?: boolean;\n /** True when this user may read a row's audit history. */\n readonly history?: boolean;\n /** True when this user may read and add comments on rows they can see. */\n readonly comment?: boolean;\n /** Why `create`, `delete`, `history` or `comment` is false, in one human sentence each. */\n readonly reasons?: {\n readonly create?: string;\n readonly delete?: string;\n readonly history?: string;\n readonly comment?: string;\n };\n}\n\n/**\n * How another resource relates to this one, from the store's foreign keys.\n *\n * - `one`: a field on THIS resource points at one row of `resource`.\n * - `many`: rows of `resource` point at this row through their `field`.\n * - `through`: many rows of `resource`, linked by the junction resource in\n * `through` (a table whose key is two foreign keys).\n */\nexport interface ResourceRelation {\n readonly kind: \"one\" | \"many\" | \"through\";\n /** The related resource. */\n readonly resource: string;\n /**\n * `one`: the field on this resource. `many`: the field on `resource` that\n * holds this row's key. `through`: the junction's field holding this row's key.\n */\n readonly field: string;\n /** For `through`: the junction resource, and its field pointing at `resource`. */\n readonly through?: { readonly resource: string; readonly otherField: string };\n /** True when at most one related row can exist (a unique foreign key). */\n readonly unique?: boolean;\n}\n\n/**\n * The column a provider checks on every update so an edit never silently\n * overwrites someone else's. Only reported when the store itself advances it\n * on every successful update (a trigger such as `moddatetime`), because a\n * column nothing advances detects nothing.\n */\nexport interface VersionField {\n /**\n * The field holding the version. A provider with versioned writes returns\n * each row with its exact version token in this field, as a string, and\n * `expectedVersion` echoes `String(row[field])` back unchanged.\n */\n readonly field: string;\n /**\n * `row`: no column tracks versions, so the token is a fingerprint of the\n * row's values, and `field` is a name the provider adds to each record\n * (it is not one of the resource's fields).\n */\n readonly kind: \"integer\" | \"timestamp\" | \"row\";\n}\n\n/**\n * A resource as `describe()` reports it for the CURRENT user: the contract,\n * plus what this user may do. Fields the user may not read are left out\n * entirely, not marked hidden.\n */\nexport interface ResourceSchema<Row extends DataRow = DataRow> extends ResourceContract<Row> {\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n readonly access: ResourceAccess;\n /** Present only when writes can be version-checked. */\n readonly version?: VersionField;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** Resources this one links to or is linked from. Only ones this user may see. */\n readonly relations?: readonly ResourceRelation[];\n /** Fields the user may set when creating a row. Absent when creating isn't allowed. */\n readonly createFields?: readonly string[];\n /** Row actions this user may run: each calls the app's own function on one row. */\n readonly actions?: readonly RowAction[];\n}\n\n/** A named operation on one row, carried out by the app's own database function. */\nexport interface RowAction {\n readonly name: string;\n readonly label: string;\n /** Ask before running, with this question. */\n readonly confirm?: string;\n /** One sentence on what it does. */\n readonly description?: string;\n}\n\n/** A comment on a record. */\nexport interface RecordComment {\n readonly id: string;\n /** The signed-in user who wrote it (the token's `sub`). */\n readonly author: string;\n readonly body: string;\n /** ISO 8601, as the store recorded it. */\n readonly createdAt: string;\n}\n\n/** One entry of `listResources()`: enough to draw a sidebar. */\nexport interface ResourceSummary {\n readonly name: string;\n readonly label?: string;\n readonly description?: string;\n readonly access: ResourceAccess;\n}\n\n/** Filter operators a provider may support. Mirrors `FilterParam[\"operator\"]`. */\nexport type FilterOperator =\n | \"eq\"\n | \"neq\"\n | \"gt\"\n | \"lt\"\n | \"gte\"\n | \"lte\"\n | \"contains\"\n | \"in\"\n | \"between\"\n | \"is_null\"\n | \"is_not_null\";\n\n/**\n * What a provider can do. A UI hides any control the provider cannot serve,\n * instead of letting it error (DATA-STUDIO.md decision 9).\n */\nexport interface ProviderCapabilities {\n /** Server-side text search across fields. */\n readonly search: boolean;\n /** Server-side sort. */\n readonly sort: boolean;\n /** Server-side filter operators. Empty means no server filtering. */\n readonly filterOperators: readonly FilterOperator[];\n /** `updateMany` / `deleteMany` in one transaction. */\n readonly bulkWrites: boolean;\n /** Updates honour `expectedVersion` and reject stale writes. */\n readonly versionedWrites: boolean;\n /** Records may be keyed by more than one field. */\n readonly compositeKeys: boolean;\n /** Server-side sort by several fields at once (`ListParams.sorts`). */\n readonly multiSort?: boolean;\n /** `create` and `deleteOne` are served, subject to each resource's access. */\n readonly create?: boolean;\n readonly delete?: boolean;\n /** `history` is served, subject to each resource's access. */\n readonly history?: boolean;\n /** `importRows` is served, with a dry run. */\n readonly import?: boolean;\n /** `undo` is served. */\n readonly undo?: boolean;\n /** `runAction` is served. */\n readonly actions?: boolean;\n /** `comments` and `addComment` are served. */\n readonly comments?: boolean;\n /**\n * The most rows one `getList` page may ask for. A request for more is\n * refused (it is not cut short, which would shift later page boundaries),\n * so a client that wants every row must page at this size or less.\n */\n readonly maxPerPage?: number;\n /**\n * A delete moves the record to a recycle bin (it can be restored) instead\n * of removing it. Asked per resource: `capabilities(resource)`.\n */\n readonly softDelete?: boolean;\n /**\n * `create`, `update` and `deleteOne` honour `keepalive: true` in their\n * params (e.g. `fetch(url, { keepalive: true })`), so a write sent while\n * the page unloads still reaches the server. Without it, closing the tab\n * while an optimistic or undoable write is being sent shows the browser's\n * \"Leave site?\" prompt.\n */\n readonly keepaliveWrites?: boolean;\n /**\n * `getList` serves cursor (keyset) paging: `pagination.cursor` in,\n * `nextCursor` out. Pages stay correct while rows are added or removed,\n * and a deep page costs no more than the first.\n */\n readonly cursorPagination?: boolean;\n /**\n * `subscribe` reports changes to this resource (asked per resource:\n * `capabilities(resource)`), so `live` lists and records refresh when\n * someone else changes them.\n */\n readonly realtime?: boolean;\n}\n\n/** One audit record, as committed alongside the edit it describes. */\nexport interface AuditEntry {\n readonly id: string;\n /** ISO 8601 timestamp, as the store recorded it. */\n readonly occurredAt: string;\n /** The signed-in user who made the edit (the token's `sub`). */\n readonly actor: string | null;\n readonly resource: string;\n /** The record's key, field name → value. */\n readonly key: DataRow;\n /** `run` is a row action; `rowAction` names it. */\n readonly action: \"create\" | \"update\" | \"delete\" | \"run\";\n /** For `run`: which row action. */\n readonly rowAction?: string;\n /** Values of the changed fields before the edit. */\n readonly before: DataRow | null;\n /** Values of the changed fields after the edit. */\n readonly after: DataRow | null;\n}\n"]}
@@ -0,0 +1,81 @@
1
+ // src/hooks/live-cache.ts
2
+ function isListResult(value) {
3
+ return !!value && typeof value === "object" && Array.isArray(value.data);
4
+ }
5
+ function isInfinite(value) {
6
+ return !!value && typeof value === "object" && Array.isArray(value.pages);
7
+ }
8
+ var sameId = (a, b) => a != null && b != null && String(a) === String(b);
9
+ function merge(row, record) {
10
+ let next = null;
11
+ for (const key of Object.keys(row)) {
12
+ if (key in record && row[key] !== record[key]) (next ??= { ...row })[key] = record[key];
13
+ }
14
+ return next ?? row;
15
+ }
16
+ function patchList(list, record) {
17
+ let changed = false;
18
+ const data = list.data.map((row) => {
19
+ if (!sameId(row.id, record.id)) return row;
20
+ const next = merge(row, record);
21
+ if (next !== row) changed = true;
22
+ return next;
23
+ });
24
+ return changed ? { ...list, data } : list;
25
+ }
26
+ function patchCachedRow(queryClient, resource, record) {
27
+ if (record.id == null) return;
28
+ for (const query of queryClient.getQueryCache().findAll({ queryKey: [resource] })) {
29
+ const [, kind, idOrParams, select] = query.queryKey;
30
+ const data = query.state.data;
31
+ if (data === void 0) continue;
32
+ let next = data;
33
+ if (kind === "detail" && select === void 0 && sameId(idOrParams, record.id) && typeof data === "object" && data) {
34
+ next = merge(data, record);
35
+ } else if (kind === "list" && isListResult(data)) {
36
+ next = patchList(data, record);
37
+ } else if (kind === "infinite" && isInfinite(data)) {
38
+ let changed = false;
39
+ const pages = data.pages.map((page) => {
40
+ if (!isListResult(page)) return page;
41
+ const patched = patchList(page, record);
42
+ if (patched !== page) changed = true;
43
+ return patched;
44
+ });
45
+ if (changed) next = { ...data, pages };
46
+ }
47
+ if (next !== data) queryClient.setQueryData(query.queryKey, next);
48
+ }
49
+ }
50
+ function comparable(v) {
51
+ if (typeof v === "boolean") return true;
52
+ return typeof v === "string" && !/^\d{4}-\d{2}-\d{2}/.test(v) && !/^-?\d+(\.\d+)?$/.test(v);
53
+ }
54
+ function passes(record, filters) {
55
+ for (const f of filters ?? []) {
56
+ if (!(f.field in record)) continue;
57
+ const v = record[f.field];
58
+ if (f.operator === "is_null" && v !== null) return false;
59
+ if (f.operator === "is_not_null" && v === null) return false;
60
+ if (!comparable(v)) continue;
61
+ if (f.operator === "eq" && comparable(f.value) && v !== f.value) return false;
62
+ if (f.operator === "neq" && comparable(f.value) && v === f.value) return false;
63
+ if (f.operator === "in" && f.value.every(comparable) && !f.value.includes(v)) return false;
64
+ }
65
+ return true;
66
+ }
67
+ function holds(data, id) {
68
+ const rows = isListResult(data) ? data.data : isInfinite(data) ? data.pages.flatMap((p) => isListResult(p) ? p.data : []) : [];
69
+ return rows.some((row) => sameId(row.id, id));
70
+ }
71
+ function listCouldChange(query, records) {
72
+ const [, kind, params] = query.queryKey;
73
+ if (kind !== "list" && kind !== "infinite") return true;
74
+ const filters = params?.filters;
75
+ if (!filters?.length) return true;
76
+ return records.some((record) => passes(record, filters) || holds(query.state.data, record.id));
77
+ }
78
+
79
+ export { listCouldChange, patchCachedRow };
80
+ //# sourceMappingURL=chunk-AUVKRXRC.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EAAE,CAAC,CAAA;AAC/F","file":"chunk-AUVKRXRC.js","sourcesContent":["// What a live event may do to cached reads before the refetch: patch a changed row in place, and\n// tell which lists the change can't have touched. Only the fields a cached row already has are\n// patched, so a list or record read with a narrower select never gains columns it didn't ask for.\n\nimport type { Query, QueryClient } from \"@tanstack/react-query\";\nimport type { BaseRecord, FilterParam, ListParams, ListResult } from \"../provider/types\";\n\ntype Row = Record<string, unknown>;\n\nfunction isListResult(value: unknown): value is ListResult<BaseRecord> {\n return !!value && typeof value === \"object\" && Array.isArray((value as { data?: unknown }).data);\n}\n\nfunction isInfinite(value: unknown): value is { pages: unknown[] } {\n return !!value && typeof value === \"object\" && Array.isArray((value as { pages?: unknown }).pages);\n}\n\nconst sameId = (a: unknown, b: unknown) => a != null && b != null && String(a) === String(b);\n\n/** `row` with the fields it already has taken from `record`; the same object when nothing changes. */\nfunction merge(row: Row, record: Row): Row {\n let next: Row | null = null;\n for (const key of Object.keys(row)) {\n if (key in record && row[key] !== record[key]) (next ??= { ...row })[key] = record[key];\n }\n return next ?? row;\n}\n\nfunction patchList(list: ListResult<BaseRecord>, record: Row): ListResult<BaseRecord> {\n let changed = false;\n const data = list.data.map((row) => {\n if (!sameId(row.id, record.id)) return row;\n const next = merge(row, record);\n if (next !== row) changed = true;\n return next as BaseRecord;\n });\n return changed ? { ...list, data } : list;\n}\n\n/**\n * Patches a changed row into every cached read of `resource`: records read whole (no `select`),\n * and the rows of lists and infinite lists. Fields a cached row lacks are left out.\n */\nexport function patchCachedRow(queryClient: QueryClient, resource: string, record: Row): void {\n if (record.id == null) return;\n for (const query of queryClient.getQueryCache().findAll({ queryKey: [resource] })) {\n const [, kind, idOrParams, select] = query.queryKey as readonly unknown[];\n const data = query.state.data;\n if (data === undefined) continue;\n let next: unknown = data;\n if (kind === \"detail\" && select === undefined && sameId(idOrParams, record.id) && typeof data === \"object\" && data) {\n next = merge(data as Row, record);\n } else if (kind === \"list\" && isListResult(data)) {\n next = patchList(data, record);\n } else if (kind === \"infinite\" && isInfinite(data)) {\n let changed = false;\n const pages = data.pages.map((page) => {\n if (!isListResult(page)) return page;\n const patched = patchList(page, record);\n if (patched !== page) changed = true;\n return patched;\n });\n if (changed) next = { ...data, pages };\n }\n if (next !== data) queryClient.setQueryData(query.queryKey, next);\n }\n}\n\n/**\n * A value this function can compare safely: text, a uuid or a boolean. Numbers, dates and\n * timestamps format differently in a realtime payload and in a PostgREST read, so they never narrow.\n */\nfunction comparable(v: unknown): v is string | boolean {\n if (typeof v === \"boolean\") return true;\n return typeof v === \"string\" && !/^\\d{4}-\\d{2}-\\d{2}/.test(v) && !/^-?\\d+(\\.\\d+)?$/.test(v);\n}\n\n/** Whether `record` passes the filters this function can read; any other filter counts as a pass. */\nfunction passes(record: Row, filters: readonly FilterParam[] | undefined): boolean {\n for (const f of filters ?? []) {\n if (!(f.field in record)) continue;\n const v = record[f.field];\n if (f.operator === \"is_null\" && v !== null) return false;\n if (f.operator === \"is_not_null\" && v === null) return false;\n if (!comparable(v)) continue;\n if (f.operator === \"eq\" && comparable(f.value) && v !== f.value) return false;\n if (f.operator === \"neq\" && comparable(f.value) && v === f.value) return false;\n if (f.operator === \"in\" && f.value.every(comparable) && !f.value.includes(v)) return false;\n }\n return true;\n}\n\nfunction holds(data: unknown, id: unknown): boolean {\n const rows = isListResult(data) ? data.data : isInfinite(data) ? data.pages.flatMap((p) => (isListResult(p) ? p.data : [])) : [];\n return rows.some((row) => sameId(row.id, id));\n}\n\n/**\n * Whether a cached list could be changed by these rows: one of them matches its filters, or is in\n * it now (it may have left). Any read that isn't a list could always change.\n */\nexport function listCouldChange(query: Query, records: readonly Row[]): boolean {\n const [, kind, params] = query.queryKey as readonly unknown[];\n if (kind !== \"list\" && kind !== \"infinite\") return true;\n const filters = (params as ListParams | undefined)?.filters;\n if (!filters?.length) return true;\n return records.some((record) => passes(record, filters) || holds(query.state.data, record.id));\n}\n"]}
@@ -0,0 +1,66 @@
1
+ import { flushPendingWrites, dropPendingWrites } from './chunk-REYTMXAA.js';
2
+ import { stableJson } from './chunk-HBAPYA5K.js';
3
+ import { personTimeZone, dayIn } from './chunk-3B4IFDMK.js';
4
+ import { useQueryClient } from '@tanstack/react-query';
5
+ import { createContext, useContext, useMemo, useState, Fragment as Fragment$1, useEffect } from 'react';
6
+ import { jsx, Fragment } from 'react/jsx-runtime';
7
+
8
+ function useToday(zone) {
9
+ const [day, setDay] = useState(() => dayIn(zone));
10
+ useEffect(() => {
11
+ const check = () => setDay(dayIn(zone));
12
+ check();
13
+ const onVisible = () => {
14
+ if (typeof document === "undefined" || document.visibilityState === "visible") check();
15
+ };
16
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", onVisible);
17
+ const timer = setInterval(check, 6e4);
18
+ return () => {
19
+ if (typeof document !== "undefined") document.removeEventListener("visibilitychange", onVisible);
20
+ clearInterval(timer);
21
+ };
22
+ }, [zone]);
23
+ return day;
24
+ }
25
+ async function clearViewerCache(queryClient) {
26
+ await flushPendingWrites(queryClient);
27
+ await queryClient.cancelQueries();
28
+ queryClient.clear();
29
+ }
30
+ var ViewerContextValue = createContext(null);
31
+ function useViewerScope() {
32
+ const value = useContext(ViewerContextValue);
33
+ if (!value) throw new Error("[genesis-core] useViewerScope needs a <ViewerScope> above it");
34
+ return value;
35
+ }
36
+ function useOptionalViewerScope() {
37
+ return useContext(ViewerContextValue);
38
+ }
39
+ function ViewerScope({ viewer, persistedViewer, scope, timeZone, fallback = null, children }) {
40
+ const queryClient = useQueryClient();
41
+ const zone = personTimeZone({ timeZone });
42
+ const day = useToday(zone);
43
+ const scopeKey = stableJson(scope ?? {});
44
+ const value = useMemo(
45
+ () => ({ viewer: viewer ?? null, scope: scope ?? {}, timeZone: zone, day }),
46
+ // eslint-disable-next-line react-hooks/exhaustive-deps
47
+ [viewer, scopeKey, zone, day]
48
+ );
49
+ const [mounted, setMounted] = useState(void 0);
50
+ if (viewer === void 0) return /* @__PURE__ */ jsx(Fragment, { children: fallback });
51
+ if (viewer !== mounted) {
52
+ const keep = mounted === void 0 && persistedViewer !== void 0 && persistedViewer === viewer;
53
+ if (!keep) {
54
+ dropPendingWrites(queryClient);
55
+ void queryClient.cancelQueries();
56
+ queryClient.clear();
57
+ }
58
+ setMounted(viewer);
59
+ return /* @__PURE__ */ jsx(Fragment, { children: fallback });
60
+ }
61
+ return /* @__PURE__ */ jsx(ViewerContextValue.Provider, { value, children: /* @__PURE__ */ jsx(Fragment$1, { children }, viewer ?? "signed-out") });
62
+ }
63
+
64
+ export { ViewerScope, clearViewerCache, useOptionalViewerScope, useViewerScope };
65
+ //# sourceMappingURL=chunk-FARKPY6R.js.map
66
+ //# sourceMappingURL=chunk-FARKPY6R.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/viewer-scope.tsx"],"names":["Fragment"],"mappings":";;;;;;;AAOA,SAAS,SAAS,IAAA,EAAmB;AACnC,EAAA,MAAM,CAAC,KAAK,MAAM,CAAA,GAAI,SAAS,MAAM,KAAA,CAAM,IAAI,CAAC,CAAA;AAChD,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,MAAM,KAAA,GAAQ,MAAM,MAAA,CAAO,KAAA,CAAM,IAAI,CAAC,CAAA;AACtC,IAAA,KAAA,EAAM;AACN,IAAA,MAAM,YAAY,MAAM;AACtB,MAAA,IAAI,OAAO,QAAA,KAAa,WAAA,IAAe,QAAA,CAAS,eAAA,KAAoB,WAAW,KAAA,EAAM;AAAA,IACvF,CAAA;AACA,IAAA,IAAI,OAAO,QAAA,KAAa,WAAA,EAAa,QAAA,CAAS,gBAAA,CAAiB,oBAAoB,SAAS,CAAA;AAE5F,IAAA,MAAM,KAAA,GAAQ,WAAA,CAAY,KAAA,EAAO,GAAM,CAAA;AACvC,IAAA,OAAO,MAAM;AACX,MAAA,IAAI,OAAO,QAAA,KAAa,WAAA,EAAa,QAAA,CAAS,mBAAA,CAAoB,oBAAoB,SAAS,CAAA;AAC/F,MAAA,aAAA,CAAc,KAAK,CAAA;AAAA,IACr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A,EAAW,uBAAO,GAAA,CAAAA,QAAAA,EAAA,EAAG,QAAA,EAAA,QAAA,EAAS,CAAA;AAC7C,EAAA,IAAI,WAAW,OAAA,EAAS;AACtB,IAAA,MAAM,IAAA,GAAO,OAAA,KAAY,MAAA,IAAa,eAAA,KAAoB,UAAa,eAAA,KAAoB,MAAA;AAG3F,IAAA,IAAI,CAAC,IAAA,EAAM;AAIT,MAAA,iBAAA,CAAkB,WAAW,CAAA;AAC7B,MAAA,KAAK,YAAY,aAAA,EAAc;AAC/B,MAAA,WAAA,CAAY,KAAA,EAAM;AAAA,IACpB;AACA,IAAA,UAAA,CAAW,MAAM,CAAA;AACjB,IAAA,uBAAO,GAAA,CAAAA,QAAAA,EAAA,EAAG,QAAA,EAAA,QAAA,EAAS,CAAA;AAAA,EACrB;AACA,EAAA,uBACE,GAAA,CAAC,kBAAA,CAAmB,QAAA,EAAnB,EAA4B,KAAA,EAC3B,8BAACA,UAAA,EAAA,EAAuC,QAAA,EAAA,EAAzB,MAAA,IAAU,YAAwB,CAAA,EACnD,CAAA;AAEJ","file":"chunk-FARKPY6R.js","sourcesContent":["import { useQueryClient, type QueryClient } from \"@tanstack/react-query\";\nimport { createContext, Fragment, useContext, useEffect, useMemo, useState, type ReactNode } from \"react\";\nimport { dayIn, personTimeZone, type Day } from \"../dates\";\nimport { stableJson } from \"./draft-controller\";\nimport { dropPendingWrites, flushPendingWrites } from \"./mutation-mode\";\n\n/** Today in `zone`, rechecked when the page comes back into view and at the next minute boundary while it's open. */\nfunction useToday(zone: string): Day {\n const [day, setDay] = useState(() => dayIn(zone));\n useEffect(() => {\n const check = () => setDay(dayIn(zone));\n check();\n const onVisible = () => {\n if (typeof document === \"undefined\" || document.visibilityState === \"visible\") check();\n };\n if (typeof document !== \"undefined\") document.addEventListener(\"visibilitychange\", onVisible);\n // A page left open over midnight rolls over within a minute.\n const timer = setInterval(check, 60_000);\n return () => {\n if (typeof document !== \"undefined\") document.removeEventListener(\"visibilitychange\", onVisible);\n clearInterval(timer);\n };\n }, [zone]);\n return day;\n}\n\n/**\n * Empties the query cache for a new viewer: sends the old viewer's waiting\n * undoable writes (the session is still theirs), cancels reads in flight,\n * then removes every query. Call it in the sign-in and sign-out actions,\n * before the session changes.\n */\nexport async function clearViewerCache(queryClient: QueryClient): Promise<void> {\n await flushPendingWrites(queryClient);\n await queryClient.cancelQueries();\n queryClient.clear();\n}\n\n/**\n * Where the viewer is working: the current practice, person or space, or a set\n * of people. Screens turn it into server filters and create defaults; it never\n * decides access (row-level security does).\n */\nexport interface ResourceScope {\n practiceId?: string;\n personId?: string;\n spaceId?: string;\n /** Several people at once (a coach's client list, a group). */\n personIds?: readonly string[];\n [key: string]: unknown;\n}\n\nexport interface ViewerContext {\n viewer: string | null;\n scope: ResourceScope;\n /** The zone the viewer's days are counted in: theirs if known, else the device's. */\n timeZone: string;\n /**\n * Today on the viewer's clock (YYYY-MM-DD), kept current when the page comes back into view.\n * Use it for every \"today\" read and as query keys' `day`: `keys.for(useViewerScope())`.\n */\n day: Day;\n}\n\nconst ViewerContextValue = createContext<ViewerContext | null>(null);\n\n/** The viewer and scope from the nearest `ViewerScope`. Throws without one: screens that cache per viewer need it. */\nexport function useViewerScope(): ViewerContext {\n const value = useContext(ViewerContextValue);\n if (!value) throw new Error(\"[genesis-core] useViewerScope needs a <ViewerScope> above it\");\n return value;\n}\n\n/** Like useViewerScope, or null outside a ViewerScope. */\nexport function useOptionalViewerScope(): ViewerContext | null {\n return useContext(ViewerContextValue);\n}\n\nexport interface ViewerScopeProps {\n /** The signed-in viewer's id, null when signed out, undefined while the session loads. */\n viewer: string | null | undefined;\n /**\n * The viewer a persisted cache was saved for. When the first known viewer\n * is this one, the restored cache is kept; otherwise it's emptied.\n */\n persistedViewer?: string | null;\n /** Where the viewer is working (see `ResourceScope`). Changing it doesn't remount or clear anything. */\n scope?: ResourceScope;\n /**\n * The viewer's saved time zone (IANA), when known; else the device's is used. Pass it when\n * rendering on a server, whose own zone is rarely the viewer's.\n */\n timeZone?: string | null;\n /** Shown while the session loads (and for the one render a change takes). */\n fallback?: ReactNode;\n children: ReactNode;\n}\n\n/**\n * Keeps one viewer's cached data from ever showing to the next. Children\n * render only once the viewer is known, under a key of that viewer, so a\n * sign-out or a new person signing in unmounts every screen and its queries\n * before the cache is emptied and the new viewer's screens mount fresh. The\n * first known viewer empties a restored cache too, unless it's the\n * `persistedViewer` it was saved for.\n *\n * ```tsx\n * <ViewerScope viewer={session === undefined ? undefined : (session?.user.id ?? null)}>\n * <App />\n * </ViewerScope>\n * ```\n */\nexport function ViewerScope({ viewer, persistedViewer, scope, timeZone, fallback = null, children }: ViewerScopeProps) {\n const queryClient = useQueryClient();\n const zone = personTimeZone({ timeZone });\n const day = useToday(zone);\n // A new scope object each render shouldn't re-render every reader: compare by value.\n const scopeKey = stableJson(scope ?? {});\n const value = useMemo<ViewerContext>(\n () => ({ viewer: viewer ?? null, scope: scope ?? {}, timeZone: zone, day }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [viewer, scopeKey, zone, day],\n );\n // The viewer the children were last mounted for; undefined before the first.\n const [mounted, setMounted] = useState<string | null | undefined>(undefined);\n if (viewer === undefined) return <>{fallback}</>;\n if (viewer !== mounted) {\n const keep = mounted === undefined && persistedViewer !== undefined && persistedViewer === viewer;\n // Nothing for the new viewer is mounted yet, so emptying now can't strand\n // a fetch; the old viewer's screens unmount with this render.\n if (!keep) {\n // The session already belongs to the new viewer: the old one's unsent\n // writes must never go out under it. (clearViewerCache, run before the\n // session changes, sends them instead.)\n dropPendingWrites(queryClient);\n void queryClient.cancelQueries();\n queryClient.clear();\n }\n setMounted(viewer);\n return <>{fallback}</>;\n }\n return (\n <ViewerContextValue.Provider value={value}>\n <Fragment key={viewer ?? \"signed-out\"}>{children}</Fragment>\n </ViewerContextValue.Provider>\n );\n}\n"]}
@@ -1,10 +1,10 @@
1
+ import { useOne } from './chunk-RF6YVWHX.js';
1
2
  import { useUnsavedChangesGuard } from './chunk-XQO4OH2N.js';
2
- import { sameValue, cachedRecord, executeWrite, invalidateResource } from './chunk-S2ZXUNXB.js';
3
+ import { sameValue, cachedRecord, executeWrite, invalidateResource } from './chunk-REYTMXAA.js';
3
4
  import { relatedKeys } from './chunk-7NUL32W7.js';
4
- import { useOne } from './chunk-BGTXN2E6.js';
5
+ import { isDataWriteError } from './chunk-LG6TUBVM.js';
5
6
  import { useDataProvider, useStorage } from './chunk-GGSXSI6Z.js';
6
7
  import { titleCase } from './chunk-RYEXWQFD.js';
7
- import { isDataWriteError } from './chunk-LG6TUBVM.js';
8
8
  import { useMemo, useEffect, useState, useRef, useCallback } from 'react';
9
9
  import { useForm } from 'react-hook-form';
10
10
  import { zodResolver } from '@hookform/resolvers/zod';
@@ -193,7 +193,8 @@ function buildArrayItemDefaults(arrayFields) {
193
193
  function buildDefaults(fields, data, action, prefillFromUrl) {
194
194
  const defaults = {};
195
195
  for (const field of fields) {
196
- if (data && field.key in data) {
196
+ const blankOnCreate = action === "create" && data?.[field.key] === "" && field.defaultValue !== void 0;
197
+ if (data && field.key in data && !blankOnCreate) {
197
198
  defaults[field.key] = data[field.key];
198
199
  } else if (field.defaultValue !== void 0) {
199
200
  defaults[field.key] = field.defaultValue;
@@ -249,7 +250,8 @@ function useResourceForm(options) {
249
250
  mutationMode = "pessimistic",
250
251
  undoDelayMs,
251
252
  onUndoable,
252
- visible = true
253
+ visible = true,
254
+ updates = "loaded"
253
255
  } = options;
254
256
  const autosaveEnabled = !!autosave;
255
257
  const debounceMs = typeof autosave === "object" ? autosave.debounceMs ?? 1e3 : 1e3;
@@ -410,8 +412,16 @@ function useResourceForm(options) {
410
412
  [form, showError, onError, action, resource]
411
413
  );
412
414
  const handleSubmit = useCallback(
413
- async (formData) => {
415
+ async (submitted) => {
414
416
  const shown = structuredCloneSafe(form.getValues());
417
+ const opened = formSource;
418
+ const formData = action === "edit" && updates === "loaded" && opened ? Object.fromEntries(
419
+ Object.entries(submitted).filter(
420
+ // Changed: what an input shows differs from where it started, or, for a value saved
421
+ // without an input (a direct handleSave), the value itself does.
422
+ ([k, v]) => k in opened || !sameValue(k in shown ? shown[k] : v, defaultValues[k])
423
+ )
424
+ ) : submitted;
415
425
  try {
416
426
  let recordId;
417
427
  if (action === "edit") {
@@ -473,7 +483,7 @@ function useResourceForm(options) {
473
483
  reportError(err instanceof Error ? err : new Error(String(err)));
474
484
  }
475
485
  },
476
- [form, action, provider, resource, id, effectiveData, formSource, queryClient, onSuccess, autosaveEnabled, storage, invalidates, mutationMode, undoDelayMs, onUndoable, reportError, markSaved]
486
+ [form, action, provider, resource, id, effectiveData, formSource, queryClient, onSuccess, autosaveEnabled, storage, invalidates, mutationMode, undoDelayMs, onUndoable, reportError, markSaved, updates, defaultValues]
477
487
  );
478
488
  const onSubmit = useCallback(
479
489
  (e) => form.handleSubmit(handleSubmit)(e),
@@ -493,5 +503,5 @@ function useResourceForm(options) {
493
503
  }
494
504
 
495
505
  export { buildArrayItemDefaults, useResourceForm };
496
- //# sourceMappingURL=chunk-OSPLIKSH.js.map
497
- //# sourceMappingURL=chunk-OSPLIKSH.js.map
506
+ //# sourceMappingURL=chunk-GEF5W2LO.js.map
507
+ //# sourceMappingURL=chunk-GEF5W2LO.js.map