@marktiderman/genesis-core 1.16.1 → 2.0.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 (36) hide show
  1. package/README.md +7 -4
  2. package/dist/{chunk-Y452U45I.js → chunk-2VVZ2KX3.js} +3 -3
  3. package/dist/{chunk-Y452U45I.js.map → chunk-2VVZ2KX3.js.map} +1 -1
  4. package/dist/{chunk-E4777JKI.js → chunk-3FFBW4XC.js} +21 -8
  5. package/dist/chunk-3FFBW4XC.js.map +1 -0
  6. package/dist/{chunk-OYIUIW7C.js → chunk-7PUFVNPB.js} +2 -2
  7. package/dist/chunk-7PUFVNPB.js.map +1 -0
  8. package/dist/{chunk-VMRLCTZR.js → chunk-CC37H7O2.js} +4 -4
  9. package/dist/{chunk-VMRLCTZR.js.map → chunk-CC37H7O2.js.map} +1 -1
  10. package/dist/{chunk-CZOFWG54.js → chunk-GWQHP3RC.js} +3 -3
  11. package/dist/{chunk-CZOFWG54.js.map → chunk-GWQHP3RC.js.map} +1 -1
  12. package/dist/{chunk-K7WEY5WR.js → chunk-OSFG3GFY.js} +3 -3
  13. package/dist/{chunk-K7WEY5WR.js.map → chunk-OSFG3GFY.js.map} +1 -1
  14. package/dist/{chunk-J2EIM7FC.js → chunk-QPD4FKPC.js} +4 -4
  15. package/dist/{chunk-J2EIM7FC.js.map → chunk-QPD4FKPC.js.map} +1 -1
  16. package/dist/chunk-XMC4EJUE.js +131 -0
  17. package/dist/chunk-XMC4EJUE.js.map +1 -0
  18. package/dist/hooks/index.d.ts +2 -1
  19. package/dist/hooks/index.js +9 -8
  20. package/dist/hooks/mutation-mode.js +2 -2
  21. package/dist/hooks/use-infinite-resource.js +2 -2
  22. package/dist/hooks/use-one.js +2 -2
  23. package/dist/hooks/use-relation-label.d.ts +25 -0
  24. package/dist/hooks/use-relation-label.js +5 -0
  25. package/dist/hooks/use-relation-label.js.map +1 -0
  26. package/dist/hooks/use-resource-form.js +4 -4
  27. package/dist/hooks/use-resource.js +3 -3
  28. package/dist/index.d.ts +5 -4
  29. package/dist/index.js +9 -8
  30. package/dist/resource-view/index.d.ts +128 -7
  31. package/dist/resource-view/index.js +148 -1
  32. package/dist/resource-view/index.js.map +1 -1
  33. package/dist/{viewer-scope-77MqxvmZ.d.ts → viewer-scope-bthEYSOB.d.ts} +24 -6
  34. package/package.json +1 -1
  35. package/dist/chunk-E4777JKI.js.map +0 -1
  36. package/dist/chunk-OYIUIW7C.js.map +0 -1
@@ -42,16 +42,17 @@ declare const NO_VIEWER: Viewer;
42
42
  */
43
43
  declare function clearViewerCache(queryClient: QueryClient): Promise<void>;
44
44
  /**
45
- * Where the viewer is working: the current practice, person or space, or a set
46
- * of people. Screens turn it into server filters and create defaults; it never
47
- * decides access (row-level security does).
45
+ * Where the viewer is working: the person, space or set of people Genesis knows by name, plus
46
+ * whatever the app scopes to under its own key (`{ orgId }`, `{ leagueId }`, `{ locationId }`).
47
+ * Screens turn it into server filters and create defaults (a view's `scope: ["league_id"]` reads
48
+ * `league_id`, then `leagueId`); it never decides access (row-level security does).
48
49
  */
49
50
  interface ResourceScope {
50
- practiceId?: string;
51
51
  personId?: string;
52
52
  spaceId?: string;
53
53
  /** Several people at once (a coach's client list, a group). */
54
54
  personIds?: readonly string[];
55
+ /** The app's own scope keys: `orgId`, `leagueId`, `locationId`, … */
55
56
  [key: string]: unknown;
56
57
  }
57
58
  interface ViewerContext {
@@ -61,6 +62,11 @@ interface ViewerContext {
61
62
  roles?: GenesisViewerRoles;
62
63
  /** The zone the viewer's days are counted in: theirs if known, else the device's. */
63
64
  timeZone: string;
65
+ /**
66
+ * The zone of whatever the viewer is scoped to (a location, a league), for columns with
67
+ * `timeZone: "scope"`: ViewerScope's `scopeTimeZone` when valid, else {@link timeZone}.
68
+ */
69
+ scopeTimeZone?: string;
64
70
  /**
65
71
  * Today on the viewer's clock (YYYY-MM-DD), kept current when the page comes back into view.
66
72
  * Use it for every "today" read and as query keys' `day`: `keys.for(useViewerScope())`.
@@ -102,10 +108,22 @@ interface ViewerScopeProps {
102
108
  * rendering on a server, whose own zone is rarely the viewer's.
103
109
  */
104
110
  timeZone?: string | null;
111
+ /**
112
+ * The IANA zone of whatever the viewer is scoped to (a location, a league), when it has one.
113
+ * Columns with `timeZone: "scope"` read on it; without it they read on the viewer's clock.
114
+ */
115
+ scopeTimeZone?: string | null;
105
116
  /** Shown while the session loads (and for the one render a change takes). */
106
117
  fallback?: ReactNode;
107
118
  children: ReactNode;
108
119
  }
120
+ /**
121
+ * The scope's clock: `scopeTimeZone` when the runtime knows it, else the viewer's. A zone it
122
+ * doesn't know is never a quiet fallback: it throws in development, and in production it is
123
+ * reported (`reportError`, once per zone) before the viewer's clock is used, so a misspelt zone can't show
124
+ * times on the wrong clock unnoticed.
125
+ */
126
+ declare function scopeClock(scopeTimeZone: string | null | undefined, viewerZone: string): string;
109
127
  /**
110
128
  * Keeps one viewer's cached data from ever showing to the next. Children
111
129
  * render only once the viewer is known, under a key of that viewer, so a
@@ -120,6 +138,6 @@ interface ViewerScopeProps {
120
138
  * </ViewerScope>
121
139
  * ```
122
140
  */
123
- declare function ViewerScope({ viewer, persistedViewer, scope, roles, timeZone, fallback, children }: ViewerScopeProps): react.JSX.Element;
141
+ declare function ViewerScope({ viewer, persistedViewer, scope, roles, timeZone, scopeTimeZone, fallback, children }: ViewerScopeProps): react.JSX.Element;
124
142
 
125
- export { type GenesisViewerRoles as G, NO_VIEWER as N, type ResourceScope as R, type Viewer as V, type ViewerContext as a, ViewerScope as b, type ViewerScopeProps as c, clearViewerCache as d, useViewer as e, useViewerScope as f, useOptionalViewerScope as u };
143
+ export { type GenesisViewerRoles as G, NO_VIEWER as N, type ResourceScope as R, type Viewer as V, type ViewerContext as a, ViewerScope as b, type ViewerScopeProps as c, clearViewerCache as d, useViewer as e, useViewerScope as f, scopeClock as s, useOptionalViewerScope as u };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-core",
3
- "version": "1.16.1",
3
+ "version": "2.0.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/viewer-scope.tsx"],"names":["Fragment"],"mappings":";;;;;;;;;AAUA,IAAI,cAAA,GAAiB,KAAA;AAOrB,SAAS,WAAW,KAAA,EAA+C;AACjE,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,MAAM,KAAA,GAAQ,CAAC,CAAA,KAAwB;AACrC,IAAA,IAAI,MAAM,OAAA,CAAQ,CAAC,GAAG,OAAO,CAAA,CAAE,IAAI,KAAK,CAAA,CAAE,GAAA,CAAI,CAAC,MAAM,CAAC,UAAA,CAAW,CAAC,CAAA,EAAG,CAAC,CAAU,CAAA,CAAE,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA,EAAG,CAAC,CAAC,CAAA,KAAO,CAAA,GAAI,IAAI,EAAA,GAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAE,EAAE,GAAA,CAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;AACnJ,IAAA,IAAI,CAAA,IAAK,OAAO,CAAA,KAAM,QAAA,EAAU;AAC9B,MAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,cAAA,CAAe,CAAC,CAAA;AACrC,MAAA,IAAI,KAAA,KAAU,MAAA,CAAO,SAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAChD,QAAA,IAAI,QAAQ,GAAA,CAAI,QAAA,KAAa,cAAc,MAAM,IAAI,UAAU,4EAA4E,CAAA;AAC3I,QAAA,QAAA,GAAW,IAAA;AACX,QAAA,OAAO,IAAA;AAAA,MACT;AACA,MAAA,OAAO,OAAO,WAAA,CAAY,MAAA,CAAO,QAAQ,CAA4B,CAAA,CAAE,IAAI,CAAC,CAAC,CAAA,EAAG,CAAC,MAAM,CAAC,CAAA,EAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;AAAA,IACvG;AACA,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AAA,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,EAAE,MAAA,EAAQ,KAAA,EAAA,CAAQ,SAAS,KAAA,IAAS,CAAA,IAAK,GAAG,CAAA;AACvD,IAAA,uBAAO,GAAA,CAAAA,QAAAA,EAAA,EAAG,QAAA,EAAA,QAAA,EAAS,CAAA;AAAA,EACrB;AACA,EAAA,uBACE,GAAA,CAAC,kBAAA,CAAmB,QAAA,EAAnB,EAA4B,OAC3B,QAAA,kBAAA,GAAA,CAACA,UAAA,EAAA,EAA6D,QAAA,EAAA,EAA/C,CAAA,EAAG,UAAU,YAAY,CAAA,CAAA,EAAI,OAAA,CAAQ,KAAK,EAAc,CAAA,EACzE,CAAA;AAEJ","file":"chunk-E4777JKI.js","sourcesContent":["import { useQueryClient, type QueryClient } from \"@tanstack/react-query\";\nimport { createContext, Fragment, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { dayIn, personTimeZone, type Day } from \"../dates\";\nimport { reportError } from \"../errors\";\nimport { stableJson } from \"./draft-controller\";\nimport { NO_VIEWER, type GenesisViewerRoles, type Viewer } from \"../viewer\";\nimport { dropPendingWrites, flushPendingWrites } from \"./mutation-mode\";\n\nexport { NO_VIEWER, type GenesisViewerRoles, type Viewer };\n\nlet warnedNotPlain = false;\n\n/**\n * Roles as a value: object keys and lists sorted, so `[\"editor\", \"owner\"]` equals\n * `[\"owner\", \"editor\"]`. A Set, Map or class would stringify as `{}` and hide a change: in\n * development that throws; in production it warns once and the roles count as unknown (undefined).\n */\nfunction rolesKeyOf(roles: GenesisViewerRoles): string | undefined {\n let notPlain = false;\n const plain = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(plain).map((x) => [stableJson(x), x] as const).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, x]) => x);\n if (v && typeof v === \"object\") {\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) {\n if (process.env.NODE_ENV !== \"production\") throw new TypeError(\"[genesis-core] ViewerScope roles must be plain JSON (no Set, Map or class)\");\n notPlain = true;\n return null;\n }\n return Object.fromEntries(Object.entries(v as Record<string, unknown>).map(([k, x]) => [k, plain(x)]));\n }\n return v;\n };\n const key = stableJson(plain(roles));\n if (!notPlain) return key;\n if (!warnedNotPlain) {\n warnedNotPlain = true;\n reportError(new TypeError(\"ViewerScope roles must be plain JSON (no Set, Map or class); treating them as unknown, so guards that need them refuse\"), \"core:viewer-scope\");\n }\n return undefined;\n}\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 viewer's roles (see `GenesisViewerRoles`), when ViewerScope was given them. */\n roles?: GenesisViewerRoles;\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\n/**\n * The viewer for guards: `{ id, scope, roles }` from the nearest ViewerScope, or\n * {@link NO_VIEWER} without one. The object is stable while those are equal by value, so it can\n * sit in a memo's dependencies.\n */\nexport function useViewer(): Viewer {\n const context = useContext(ViewerContextValue);\n return useMemo<Viewer>(\n () =>\n context\n ? Object.freeze({ id: context.viewer, scope: context.scope, ...(context.roles !== undefined ? { roles: context.roles } : {}) })\n : NO_VIEWER,\n [context],\n );\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 * What the viewer may do there (see `GenesisViewerRoles`), for view guards. Compared by value,\n * so a new object with the same roles changes nothing. Undefined while they load: guards that\n * need them refuse. Arriving (undefined → roles) or going back to undefined changes nothing;\n * different roles send the person's waiting writes, then reread every query, with nothing\n * remounted. Plain JSON values only (lists are compared as sets, in any order): a Set, Map or\n * class instance throws in development; in production it warns once and the roles count as\n * unknown (as if undefined), so guards that need them refuse.\n */\n roles?: GenesisViewerRoles;\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, roles, 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 // Roles by value too: undefined stays undefined, so \"not known yet\" never equals \"none\".\n // Roles that aren't plain JSON count as unknown in production (rolesKeyOf warns; development throws).\n const rolesKey = roles === undefined ? undefined : rolesKeyOf(roles);\n const value = useMemo<ViewerContext>(\n () => ({ viewer: viewer ?? null, scope: scope ?? {}, ...(rolesKey !== undefined ? { roles } : {}), timeZone: zone, day }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [viewer, scopeKey, rolesKey, zone, day],\n );\n // The last roles known for this viewer. Arriving (undefined → roles) or going back to undefined\n // changes nothing; different roles for the same person send their waiting writes, then reread\n // everything under the new roles. Nothing remounts: the person, their drafts and their\n // navigation are the same.\n const known = useRef<{ viewer: string | null | undefined; roles: string | undefined }>({ viewer, roles: undefined });\n useEffect(() => {\n if (known.current.viewer !== viewer) known.current = { viewer, roles: undefined };\n if (rolesKey === undefined) return;\n const previous = known.current.roles;\n known.current.roles = rolesKey;\n if (previous === undefined || previous === rolesKey) return;\n // The session is still theirs: their writes go out, and the database decides each one with the\n // roles as they are when it arrives (a refused one fails as any refused write does).\n void flushPendingWrites(queryClient).then(() => queryClient.invalidateQueries());\n }, [viewer, rolesKey, queryClient]);\n // Who the children were last mounted for, and how many times they were reset. Undefined before\n // the first mount.\n const [mounted, setMounted] = useState<{ viewer: string | null; epoch: number } | undefined>(undefined);\n if (viewer === undefined) return <>{fallback}</>;\n if (mounted === undefined || mounted.viewer !== viewer) {\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, epoch: (mounted?.epoch ?? 0) + 1 });\n return <>{fallback}</>;\n }\n return (\n <ViewerContextValue.Provider value={value}>\n <Fragment key={`${viewer ?? \"signed-out\"}#${mounted.epoch}`}>{children}</Fragment>\n </ViewerContextValue.Provider>\n );\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/query-keys.ts"],"names":[],"mappings":";AAyDA,SAAS,YAAY,KAAA,EAAyB;AAC5C,EAAA,MAAM,GAAA,GAAc,EAAE,MAAA,EAAQ,KAAA,CAAM,MAAA,EAAO;AAC3C,EAAA,IAAI,KAAA,CAAM,KAAA,KAAU,MAAA,EAAW,GAAA,CAAI,QAAQ,KAAA,CAAM,KAAA;AACjD,EAAA,IAAI,KAAA,CAAM,GAAA,KAAQ,MAAA,EAAW,GAAA,CAAI,MAAM,KAAA,CAAM,GAAA;AAE7C,EAAA,IAAI,KAAA,CAAM,KAAA,IAAS,MAAA,CAAO,IAAA,CAAK,MAAM,KAAK,CAAA,CAAE,MAAA,GAAS,CAAA,EAAG,GAAA,CAAI,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AW,CAAC,EAAA,KAAsC,CAAC,QAAA,EAAU,UAAU,EAAE,CAAA;AAAA,IACzE,MAAA,EAAQ,CAAC,EAAA,EAAmC,MAAA,KAAoB,CAAC,QAAA,EAAU,QAAA,EAAU,IAAI,MAAM,CAAA;AAAA,IAC/F,UAAU,CAAC,MAAA,KAAoB,CAAC,QAAA,EAAU,YAAY,MAAM;AAAA,GAC9D;AACF","file":"chunk-OYIUIW7C.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Query keys (README \"Query keys\")\n//\n// One place that builds every cache key, so a write invalidates what it made\n// stale and nothing shows across people. Keys are `[domain, kind, fields]`:\n// TanStack matches keys by prefix and matches objects by their fields, so\n// `[domain]` and `[domain, kind]` invalidate everything under them, and\n// `where({...})` reaches keys by any field, including one person inside a\n// multi-person key.\n//\n// App keys are scoped to the signed-in viewer by default: `for({ viewer })`\n// is the only way to build one, and the scope (viewer, group, day) is part of\n// the fields. Resource keys carry no viewer: `ViewerScope` (or\n// `clearViewerCache` in the sign-in/out action) keeps those apart.\n// ---------------------------------------------------------------------------\n\nimport type { Query } from \"@tanstack/react-query\";\nimport type { Identifier, ListParams } from \"./provider/types\";\n\n/** Who and when a key is for. `viewer` is required; null means signed out. */\nexport interface KeyScope {\n viewer: string | null;\n /** The group, practice or space the screen is filtered to. */\n group?: string | null;\n /** The person-day (YYYY-MM-DD) a \"today\" read is for. */\n day?: string | null;\n /**\n * Where the viewer is working (ViewerScope's `scope`: practice, person, space…). Part of every\n * key, so the same query for two practices never shares a cache entry.\n */\n scope?: Readonly<Record<string, unknown>>;\n}\n\ntype Fields = Record<string, unknown>;\ntype QueryDefs = Record<string, (...args: never[]) => Fields>;\n\nexport type ScopedKey<D extends string, K> = readonly [D, K, Fields];\n\n/** A filter for `invalidateQueries` / `removeQueries` / `getQueriesData`. */\nexport interface KeyFilter {\n predicate: (query: Query) => boolean;\n}\n\nexport type QueryKeys<D extends string, Q extends QueryDefs> = {\n /** Every key in the domain: `[domain]`. */\n readonly all: readonly [D];\n /** Builds keys for one scope. */\n for(scope: KeyScope): { [K in keyof Q]: (...args: Parameters<Q[K]>) => ScopedKey<D, K> };\n /**\n * Keys whose fields match `fields`: an equal value (`1` matches `\"1\"`,\n * objects whatever their key order), an array field containing the value,\n * or, for an array value, an array field containing every item. `kind`\n * narrows it to one query.\n */\n where(fields: Fields, kind?: keyof Q): KeyFilter;\n} & { readonly [K in keyof Q]: { readonly all: readonly [D, K] } };\n\nfunction scopeFields(scope: KeyScope): Fields {\n const out: Fields = { viewer: scope.viewer };\n if (scope.group !== undefined) out.group = scope.group;\n if (scope.day !== undefined) out.day = scope.day;\n // Key order doesn't matter: TanStack hashes keys with object keys sorted.\n if (scope.scope && Object.keys(scope.scope).length > 0) out.scope = { ...scope.scope };\n return out;\n}\n\nconst stableText = (value: unknown) =>\n JSON.stringify(value, (_key, v: unknown) =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? Object.fromEntries(Object.entries(v as Fields).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))\n : v,\n );\n\n/** Equal, with numbers and their text equal, and objects equal whatever their key order. */\nfunction same(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n const scalar = (v: unknown) => typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\";\n if (scalar(a) && scalar(b)) return String(a) === String(b);\n return stableText(a) === stableText(b);\n}\n\nfunction fieldMatches(have: unknown, want: unknown): boolean {\n if (same(have, want)) return true;\n if (!Array.isArray(have)) return false;\n // An empty list asks for an empty list, not \"any list\".\n if (Array.isArray(want)) return want.length > 0 && want.every((w) => have.some((h) => same(h, w)));\n return have.some((h) => same(h, want));\n}\n\n/**\n * The keys of one domain. Each query maps its arguments to the fields that\n * make it distinct (sort arrays so order never makes two keys):\n *\n * ```ts\n * export const worksheetKeys = defineQueryKeys(\"worksheet-items\", {\n * lessonParts: (people: string[]) => ({ people: [...people].sort() }),\n * byEntry: (entryId: string) => ({ entryId }),\n * });\n * useQuery({ queryKey: worksheetKeys.for({ viewer }).lessonParts(people), … });\n * queryClient.invalidateQueries(worksheetKeys.where({ people: personId }));\n * queryClient.invalidateQueries(worksheetKeys.where({ entryId }, \"byEntry\"));\n * queryClient.invalidateQueries({ queryKey: worksheetKeys.lessonParts.all });\n * ```\n */\nexport function defineQueryKeys<const D extends string, Q extends QueryDefs>(domain: D, queries: Q): QueryKeys<D, Q> {\n const keys: Record<string, unknown> = {\n all: [domain] as const,\n for(scope: KeyScope) {\n if (!scope || !(\"viewer\" in scope)) throw new Error(`[genesis-core] ${domain} keys need a scope with a viewer`);\n const scoped = scopeFields(scope);\n return Object.fromEntries(\n Object.entries(queries).map(([kind, fields]) => [\n kind,\n (...args: never[]) => {\n const own = fields(...args);\n for (const name of Object.keys(scoped)) {\n if (name in own) throw new Error(`[genesis-core] ${domain}.${kind} can't name a field \"${name}\": it's the scope's`);\n }\n return [domain, kind, { ...own, ...scoped }] as const;\n },\n ]),\n );\n },\n where(fields: Fields, kind?: string): KeyFilter {\n return {\n predicate: (query) => {\n const [d, k, f] = query.queryKey as readonly unknown[];\n if (d !== domain || (kind !== undefined && k !== kind)) return false;\n if (!f || typeof f !== \"object\") return Object.keys(fields).length === 0;\n // A key without the field never matches it, even when the value asked for is undefined.\n return Object.entries(fields).every(([name, want]) => name in f && fieldMatches((f as Fields)[name], want));\n },\n };\n },\n };\n for (const kind of Object.keys(queries)) {\n if (kind in keys) throw new Error(`[genesis-core] ${domain} can't have a query named \"${kind}\"`);\n keys[kind] = { all: [domain, kind] as const };\n }\n return keys as QueryKeys<D, Q>;\n}\n\n/**\n * The keys Genesis's own hooks cache a resource under, for writing into or\n * invalidating them by hand: `[resource]` covers them all.\n */\nexport function resourceKeys(resource: string) {\n return {\n all: [resource] as const,\n lists: [resource, \"list\"] as const,\n list: (params: ListParams) => [resource, \"list\", params] as const,\n details: [resource, \"detail\"] as const,\n /** Every projection of one record: `detail(id, select)` for any `select`. */\n detailsOf: (id: Identifier | null | undefined) => [resource, \"detail\", id] as const,\n detail: (id: Identifier | null | undefined, select?: string) => [resource, \"detail\", id, select] as const,\n infinite: (params: unknown) => [resource, \"infinite\", params] as const,\n };\n}\n\n"]}