@marktiderman/genesis-core 2.10.0 → 2.11.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 (91) hide show
  1. package/README.md +164 -1
  2. package/dist/{chunk-LGTXQTHA.js → chunk-2VJQVAJD.js} +3 -3
  3. package/dist/{chunk-LGTXQTHA.js.map → chunk-2VJQVAJD.js.map} +1 -1
  4. package/dist/chunk-2WS4LGYU.js +47 -0
  5. package/dist/chunk-2WS4LGYU.js.map +1 -0
  6. package/dist/{chunk-KXVDDDJY.js → chunk-3B5O36DU.js} +105 -13
  7. package/dist/chunk-3B5O36DU.js.map +1 -0
  8. package/dist/{chunk-EHFYSJJA.js → chunk-42QPCDQF.js} +3 -3
  9. package/dist/{chunk-EHFYSJJA.js.map → chunk-42QPCDQF.js.map} +1 -1
  10. package/dist/{chunk-RK365SO2.js → chunk-AKF2RAGX.js} +8 -5
  11. package/dist/chunk-AKF2RAGX.js.map +1 -0
  12. package/dist/{chunk-4ZR7472O.js → chunk-LOJGHR5O.js} +4 -4
  13. package/dist/{chunk-4ZR7472O.js.map → chunk-LOJGHR5O.js.map} +1 -1
  14. package/dist/{chunk-ON2V4RXX.js → chunk-OC4OGB2K.js} +19 -11
  15. package/dist/chunk-OC4OGB2K.js.map +1 -0
  16. package/dist/{chunk-HQAVDVIH.js → chunk-POMTRNAL.js} +4 -4
  17. package/dist/{chunk-HQAVDVIH.js.map → chunk-POMTRNAL.js.map} +1 -1
  18. package/dist/{chunk-VDEW4AOS.js → chunk-PSFKIG27.js} +55 -6
  19. package/dist/chunk-PSFKIG27.js.map +1 -0
  20. package/dist/{chunk-37RWGNIO.js → chunk-VFT6QKZW.js} +114 -5
  21. package/dist/chunk-VFT6QKZW.js.map +1 -0
  22. package/dist/{chunk-VDS6REM3.js → chunk-VJGU6E4U.js} +5 -5
  23. package/dist/{chunk-VDS6REM3.js.map → chunk-VJGU6E4U.js.map} +1 -1
  24. package/dist/{chunk-ZCE3CHPX.js → chunk-XVRIWP7B.js} +3 -3
  25. package/dist/{chunk-ZCE3CHPX.js.map → chunk-XVRIWP7B.js.map} +1 -1
  26. package/dist/{chunk-7FVTGKTX.js → chunk-YDMKMNDS.js} +2 -2
  27. package/dist/{chunk-7FVTGKTX.js.map → chunk-YDMKMNDS.js.map} +1 -1
  28. package/dist/{chunk-6WV6ST67.js → chunk-YNXLPOAB.js} +97 -10
  29. package/dist/chunk-YNXLPOAB.js.map +1 -0
  30. package/dist/{chunk-7GW3QR63.js → chunk-ZHC3MDCS.js} +101 -18
  31. package/dist/chunk-ZHC3MDCS.js.map +1 -0
  32. package/dist/conversation/index.d.ts +195 -0
  33. package/dist/conversation/index.js +110 -0
  34. package/dist/conversation/index.js.map +1 -0
  35. package/dist/csv.d.ts +1 -1
  36. package/dist/errors.js +1 -2
  37. package/dist/form-types.d.ts +1 -1
  38. package/dist/gallery/index.d.ts +79 -0
  39. package/dist/gallery/index.js +64 -0
  40. package/dist/gallery/index.js.map +1 -0
  41. package/dist/hooks/index.d.ts +5 -4
  42. package/dist/hooks/index.js +18 -18
  43. package/dist/hooks/mutation-mode.d.ts +29 -2
  44. package/dist/hooks/mutation-mode.js +9 -4
  45. package/dist/hooks/related-keys.d.ts +1 -1
  46. package/dist/hooks/use-capabilities.d.ts +1 -1
  47. package/dist/hooks/use-capabilities.js +2 -2
  48. package/dist/hooks/use-infinite-resource.d.ts +1 -1
  49. package/dist/hooks/use-infinite-resource.js +4 -4
  50. package/dist/hooks/use-link-options.d.ts +1 -1
  51. package/dist/hooks/use-link-options.js +6 -6
  52. package/dist/hooks/use-live.d.ts +1 -1
  53. package/dist/hooks/use-live.js +3 -3
  54. package/dist/hooks/use-one.d.ts +1 -1
  55. package/dist/hooks/use-one.js +4 -4
  56. package/dist/hooks/use-relation-label.d.ts +1 -1
  57. package/dist/hooks/use-relation-label.js +2 -2
  58. package/dist/hooks/use-resource-form.d.ts +14 -1
  59. package/dist/hooks/use-resource-form.js +12 -9
  60. package/dist/hooks/use-resource.d.ts +17 -3
  61. package/dist/hooks/use-resource.js +12 -8
  62. package/dist/hooks/use-write.d.ts +1 -1
  63. package/dist/index.d.ts +8 -6
  64. package/dist/index.js +21 -21
  65. package/dist/offline/index.d.ts +84 -0
  66. package/dist/offline/index.js +413 -0
  67. package/dist/offline/index.js.map +1 -0
  68. package/dist/provider/index.d.ts +60 -7
  69. package/dist/provider/index.js +3 -3
  70. package/dist/resource-view/index.d.ts +79 -4
  71. package/dist/resource-view/index.js +141 -19
  72. package/dist/resource-view/index.js.map +1 -1
  73. package/dist/schema/index.d.ts +4 -3
  74. package/dist/schema/index.js +2 -1
  75. package/dist/testing/index.d.ts +2 -2
  76. package/dist/{types-9WnGxZhj.d.ts → types-BzLv8yOm.d.ts} +8 -0
  77. package/dist/types-CsKSAKqs.d.ts +143 -0
  78. package/dist/{viewer-scope-bthEYSOB.d.ts → viewer-scope-Dx0N9AYk.d.ts} +3 -2
  79. package/dist/workspaces.d.ts +1 -1
  80. package/dist/{write-outcome-ZWlhhzRW.d.ts → write-outcome-DC5hORz-.d.ts} +1 -1
  81. package/dist/write-state-DVC4Yq9T.d.ts +58 -0
  82. package/package.json +15 -2
  83. package/dist/chunk-37RWGNIO.js.map +0 -1
  84. package/dist/chunk-6WV6ST67.js.map +0 -1
  85. package/dist/chunk-7GW3QR63.js.map +0 -1
  86. package/dist/chunk-KXVDDDJY.js.map +0 -1
  87. package/dist/chunk-ON2V4RXX.js.map +0 -1
  88. package/dist/chunk-PA6WJE5E.js +0 -115
  89. package/dist/chunk-PA6WJE5E.js.map +0 -1
  90. package/dist/chunk-RK365SO2.js.map +0 -1
  91. package/dist/chunk-VDEW4AOS.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-resource-form.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAwBA,SAAS,oBAAuB,KAAA,EAAa;AAC3C,EAAA,IAAI;AACF,IAAA,OAAO,OAAO,eAAA,KAAoB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QAAA;AAAA,IACA,SAAA;AAAA,IACA,OAAA;AAAA,IACA,YAAA;AAAA,IACA,QAAA,EAAU,eAAe,QAAA,IAAY,IAAA;AAAA,IACrC,QAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-3B5O36DU.js","sourcesContent":["import { useMemo, useCallback, useEffect, useRef, useState } from \"react\";\nimport { useForm, type UseFormReturn, type Resolver } from \"react-hook-form\";\nimport { zodResolver } from \"@hookform/resolvers/zod\";\nimport { z } from \"zod\";\nimport { useOne } from \"./use-one\";\nimport { useDataProvider, useStorage } from \"../provider/context\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { titleCase } from \"../utils\";\nimport type { ResourceFormFieldDef, FieldType } from \"../form-types\";\nimport type { BaseRecord, InvalidationKey } from \"../provider/types\";\nimport { relatedKeys } from \"./related-keys\";\nimport { isDataWriteError } from \"../schema/write-outcome\";\nimport { writeConflict, type WriteConflict } from \"../schema/write-state\";\nimport { patchCachedRow } from \"./live-cache\";\nimport {\n cachedRecord,\n executeWrite,\n invalidateResource,\n sameValue,\n type MutationModeOptions,\n} from \"./mutation-mode\";\nimport { useUnsavedChangesGuard } from \"./use-unsaved-changes-guard\";\n\n/** A deep copy where the platform allows one (form values are plain data). */\nfunction structuredCloneSafe<T>(value: T): T {\n try {\n return typeof structuredClone === \"function\" ? structuredClone(value) : value;\n } catch {\n return value;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface UseResourceFormOptions extends MutationModeOptions {\n resource: string;\n action: \"create\" | \"edit\";\n id?: string;\n initialData?: Record<string, unknown>;\n fields?: ResourceFormFieldDef[];\n /**\n * Infer fields from the row's keys when `fields` is empty (or unset). Default true, as before.\n * False: `fields` is the whole form even when empty, so a description that leaves nothing\n * writable (a view) never turns into one input per column of the row being edited.\n */\n inferFields?: boolean;\n /** Full dataset used to auto-detect select fields from unique values. */\n listData?: Record<string, unknown>[];\n /**\n * The form is done. After the save in `pessimistic` mode (with the stored\n * row); at once in `optimistic` and `undoable` modes (with the submitted\n * values over the record, and no `id` for a create).\n */\n onSuccess?: (data: Record<string, unknown>) => void;\n /**\n * The save failed. In `optimistic` and `undoable` modes the form may be\n * gone by then, so show the error from here (genesis-ui's ResourceForm\n * toasts it when no `onError` is given).\n */\n onError?: (error: Error) => void;\n /**\n * Warn before unsaved changes are lost. Default false. While the form is\n * dirty, closing or reloading the tab shows the browser's prompt, and\n * `confirmLeave()` asks before in-app navigation (wire it to a router\n * blocker; see SKILL.md \"Unsaved changes\").\n */\n warnWhenUnsaved?: boolean | { message?: string };\n /**\n * Whether the form is on screen. Default true. Pass false while it is\n * hidden but still mounted (a closed dialog). An optimistic or undoable\n * save that fails later is put back on the form (field errors, unsaved\n * again) only while the form is mounted, visible and still holds the\n * values it saved; otherwise the failure only reaches `onError`.\n */\n visible?: boolean;\n /**\n * Pre-fill create form defaults from URL query params: a param named like a\n * field (`?status=draft`) becomes that field's starting value. Default true.\n * Pass false for a form that should not read the page's URL, e.g. one\n * opened from a list whose own filters live in the query string.\n */\n prefillFromUrl?: boolean;\n /**\n * Generate a placeholder (\"Enter name\", \"name@example.com\") for a field\n * whose `placeholder` is unset. Default true. A placeholder that only\n * repeats the label adds noise without information, so `ResourceForm`\n * turns this off unless asked.\n */\n autoPlaceholder?: boolean;\n /** Validation trigger mode. Default \"onBlur\". */\n validationMode?: \"onBlur\" | \"onChange\" | \"onSubmit\";\n /** Enable autosave drafts to localStorage for create mode. */\n autosave?: boolean | { debounceMs?: number };\n /**\n * Other query keys to invalidate after a save, on top of `[resource]` and\n * the provider's own `invalidates`.\n */\n invalidates?: InvalidationKey[];\n /**\n * What an edit sends. `\"loaded\"` (default): every field of the record the form opened with,\n * plus any field the person changed, but never a field the record didn't carry and nobody\n * touched. So a list that didn't load a column (or a value the server left out) can't be\n * overwritten with an empty one. `\"all\"`: every form field, as before.\n */\n updates?: \"loaded\" | \"all\";\n}\n\nexport interface UseResourceFormReturn {\n form: UseFormReturn<Record<string, unknown>>;\n resolvedFields: ResourceFormFieldDef[];\n onSubmit: (e?: { preventDefault?: () => void }) => Promise<void>;\n /** Raw save handler — use with form.handleSubmit(handleSave, onInvalid). */\n handleSave: (data: Record<string, unknown>) => Promise<void>;\n isSaving: boolean;\n isLoading: boolean;\n /**\n * The form has changes that have not been saved. False again once a save\n * succeeds (or, in optimistic / undoable modes, is handed off).\n */\n isDirty: boolean;\n /**\n * For in-app navigation: true when it is fine to leave (nothing unsaved,\n * `warnWhenUnsaved` off, or the user confirmed). Asks with\n * `window.confirm` otherwise.\n */\n confirmLeave: () => boolean;\n /**\n * Set when a save met someone else's change (a versioned resource's\n * `conflict`): their row beside what this form tried to save. Show it with\n * ConflictSheet; null otherwise.\n */\n conflict: WriteConflict | null;\n /** Save this form's values over theirs, at the version the conflict reported. */\n keepMine: () => Promise<void>;\n /** Drop this form's changes and show their row. */\n takeTheirs: () => void;\n /** Close the conflict without choosing: the form keeps its unsaved values. */\n dismissConflict: () => void;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Infer a field type from a value */\nfunction inferFieldType(value: unknown): FieldType {\n if (typeof value === \"boolean\") return \"switch\";\n if (typeof value === \"number\") return \"number\";\n if (typeof value === \"string\") {\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(value)) return \"date\";\n if (value.includes(\"@\") && value.includes(\".\")) return \"email\";\n if (/^https?:\\/\\//.test(value)) return \"url\";\n if (value.length > 100) return \"textarea\";\n }\n return \"text\";\n}\n\n/** Try to infer a select field from unique values across the full dataset */\nfunction inferSelectFromData(\n key: string,\n allData: Record<string, unknown>[] | undefined,\n): { type: \"select\"; options: { value: string; label: string }[] } | null {\n if (!allData || allData.length === 0) return null;\n const uniqueValues = new Set<string>();\n for (const row of allData) {\n const v = row[key];\n if (typeof v === \"string\" && v.length > 0) uniqueValues.add(v);\n }\n if (uniqueValues.size > 0 && uniqueValues.size <= 10) {\n return {\n type: \"select\" as const,\n options: Array.from(uniqueValues)\n .sort()\n .map((v) => ({ value: v, label: v })),\n };\n }\n return null;\n}\n\n/** Generate a sensible placeholder for an auto-inferred field */\nfunction defaultPlaceholder(key: string, type: FieldType): string {\n switch (type) {\n case \"email\": return \"name@example.com\";\n case \"url\": return \"https://...\";\n case \"number\": return \"0\";\n case \"date\": return \"YYYY-MM-DD\";\n case \"textarea\": return `Enter ${titleCase(key).toLowerCase()}...`;\n default: return `Enter ${titleCase(key).toLowerCase()}`;\n }\n}\n\n/** Resolve fields from data keys when none provided */\nfunction resolveFields(\n fields: ResourceFormFieldDef[] | undefined,\n data: Record<string, unknown> | undefined,\n allData?: Record<string, unknown>[],\n autoPlaceholder = true,\n infer = true,\n): ResourceFormFieldDef[] {\n const placeholderFor = (key: string, type: FieldType): string | undefined =>\n autoPlaceholder ? defaultPlaceholder(key, type) : undefined;\n if ((fields && fields.length > 0) || (fields && !infer)) {\n return fields.map((f) => {\n const inferred = f.type ?? (data ? inferFieldType(data[f.key]) : \"text\");\n return {\n ...f,\n label: f.label ?? titleCase(f.key),\n type: inferred,\n placeholder: f.placeholder ?? placeholderFor(f.key, inferred),\n required: f.required ?? (inferred !== \"switch\" && inferred !== \"checkbox\" && inferred !== \"hidden\"),\n };\n });\n }\n\n if (!data || !infer) return [];\n\n return Object.keys(data)\n .filter((key) => key !== \"id\" && key !== \"created_at\" && key !== \"updated_at\")\n .map((key) => {\n // Check for select-like field first (string with few unique values)\n if (typeof data[key] === \"string\") {\n const selectInfo = inferSelectFromData(key, allData);\n if (selectInfo) {\n return {\n key,\n label: titleCase(key),\n type: selectInfo.type,\n options: selectInfo.options,\n placeholder: autoPlaceholder\n ? `Select ${titleCase(key).toLowerCase()}...`\n : undefined,\n required: true,\n };\n }\n }\n\n const inferred = inferFieldType(data[key]);\n return {\n key,\n label: titleCase(key),\n type: inferred,\n placeholder: placeholderFor(key, inferred),\n required: inferred !== \"switch\" && inferred !== \"checkbox\" && inferred !== \"hidden\",\n };\n });\n}\n\n/** Build a zod schema from resolved fields */\nfunction buildSchema(fields: ResourceFormFieldDef[], action: \"create\" | \"edit\" = \"create\") {\n const shape: Record<string, z.ZodTypeAny> = {};\n\n for (const field of fields) {\n const fieldType = field.type ?? \"text\";\n\n if (field.hidden || fieldType === \"hidden\") continue;\n // An edit never sends a field read-only on edit, so it isn't checked either: a row loaded\n // without it would otherwise fail \"required\" on a field the person can't fill.\n if (action === \"edit\" && field.readOnlyOnEdit) continue;\n\n // File/image fields store File objects — z.any() is intentional here because\n // the File API shape varies by platform (browser File, React Native asset, etc.)\n // and form libraries may wrap files differently.\n if (fieldType === \"file\" || fieldType === \"image\") {\n shape[field.key] = field.required !== false ? z.unknown().refine((v) => v != null, { message: `${field.label ?? titleCase(field.key)} is required` }) : z.unknown().optional();\n continue;\n }\n\n switch (fieldType) {\n case \"number\": {\n let schema = z.coerce.number({ message: \"Must be a number\" });\n if (field.min != null) schema = schema.min(field.min);\n if (field.max != null) schema = schema.max(field.max);\n // An optional field may start at null (a screen's `filter` of null): accept it as is,\n // before coercion would turn it into 0.\n shape[field.key] = field.required !== false\n ? schema\n : z.null().or(schema).optional();\n break;\n }\n case \"relation\": {\n // A linked row's key, as the row holds it: text (a uuid) or a number. Cleared, it is null.\n const message = `${field.label ?? titleCase(field.key)} is required`;\n shape[field.key] = field.required !== false\n ? z.unknown().refine((v) => (typeof v === \"string\" && v !== \"\") || (typeof v === \"number\" && Number.isFinite(v)), { message })\n : z.union([z.string(), z.number()]).nullable().optional();\n break;\n }\n case \"array\": {\n if (field.arrayFields) {\n const itemShape: Record<string, z.ZodTypeAny> = {};\n for (const sub of field.arrayFields) {\n const subType = sub.type ?? \"text\";\n if (subType === \"number\") {\n let s = z.coerce.number({ message: \"Must be a number\" });\n if (sub.min != null) s = s.min(sub.min);\n if (sub.max != null) s = s.max(sub.max);\n itemShape[sub.key] = sub.required !== false ? s : s.optional();\n } else if (subType === \"switch\" || subType === \"checkbox\") {\n itemShape[sub.key] = z.boolean().optional();\n } else {\n let s = z.string();\n if (sub.required !== false) {\n s = s.min(1, `${sub.label ?? titleCase(sub.key)} is required`);\n }\n if (subType === \"email\") s = s.email(\"Invalid email address\");\n if (subType === \"url\") s = s.url(\"Invalid URL\");\n if (sub.maxLength != null) {\n s = s.max(\n sub.maxLength,\n `${sub.label ?? titleCase(sub.key)} must be ${sub.maxLength} characters or fewer`,\n );\n }\n itemShape[sub.key] = sub.required === false ? s.optional().or(z.literal(\"\")) : s;\n }\n }\n let arraySchema: z.ZodTypeAny = z.array(z.object(itemShape));\n if (field.arrayMin != null) arraySchema = (arraySchema as z.ZodArray<z.ZodTypeAny>).min(field.arrayMin, `Minimum ${field.arrayMin} items required`);\n if (field.arrayMax != null) arraySchema = (arraySchema as z.ZodArray<z.ZodTypeAny>).max(field.arrayMax, `Maximum ${field.arrayMax} items allowed`);\n shape[field.key] = arraySchema;\n }\n break;\n }\n case \"switch\":\n case \"checkbox\": {\n shape[field.key] = z.boolean().optional();\n break;\n }\n default: {\n // text, email, url, textarea, date, select\n let schema = z.string();\n if (field.required !== false) {\n schema = schema.min(1, `${field.label ?? titleCase(field.key)} is required`);\n }\n if (fieldType === \"email\") {\n schema = schema.email(\"Invalid email address\");\n }\n if (fieldType === \"url\") {\n schema = schema.url(\"Invalid URL\");\n }\n if (field.maxLength != null) {\n schema = schema.max(\n field.maxLength,\n `${field.label ?? titleCase(field.key)} must be ${field.maxLength} characters or fewer`,\n );\n }\n // An optional field may start at null (a screen's `filter` of null); \"\" is an empty input.\n shape[field.key] = field.required === false\n ? schema.optional().nullable().or(z.literal(\"\"))\n : schema;\n break;\n }\n }\n }\n\n return z.object(shape).passthrough();\n}\n\n/** Build default values for a single array item from its sub-field definitions */\nexport function buildArrayItemDefaults(\n arrayFields: ResourceFormFieldDef[],\n): Record<string, unknown> {\n const defaults: Record<string, unknown> = {};\n for (const sub of arrayFields) {\n const subType = sub.type ?? \"text\";\n if (subType === \"number\") defaults[sub.key] = undefined;\n else if (subType === \"switch\" || subType === \"checkbox\") defaults[sub.key] = false;\n else defaults[sub.key] = sub.defaultValue ?? \"\";\n }\n return defaults;\n}\n\n// Input types whose empty value (\"\") can be a real value of the column.\nconst TEXT_TYPES: ReadonlySet<string> = new Set([\"text\", \"textarea\", \"email\", \"tel\", \"url\", \"hidden\"]);\n\n/**\n * What a save sends for an input left empty: `\"\"`, or `undefined` (a cleared number input). Only a field whose column the form knows\n * about (`nullable` set, as ResourceView sets it from a generated contract) is changed:\n * a create leaves it out, so the column's default (or null) applies, and an edit the person\n * made clears it to null. Everything else goes as before, `\"\"` included: a field without\n * `nullable`, an edit of a field nobody touched (`changed` doesn't list it), a value the\n * screen started the field at (its `defaultValue`), and a text column that can't be null\n * (on a create, only when it has no default to fall back on).\n */\nexport function blankValues(\n values: Record<string, unknown>,\n fields: readonly ResourceFormFieldDef[],\n action: \"create\" | \"edit\",\n changed?: ReadonlySet<string>,\n): Record<string, unknown> {\n const byKey = new Map(fields.map((f) => [f.key, f]));\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(values)) {\n const field = byKey.get(key);\n const asBefore =\n (value !== \"\" && value !== undefined) ||\n field?.nullable === undefined ||\n field.defaultValue === \"\" ||\n (action === \"edit\" && changed !== undefined && !changed.has(key)) ||\n (TEXT_TYPES.has(field.type ?? \"text\") && !field.nullable && !(action === \"create\" && field.hasDefault));\n if (asBefore) out[key] = value;\n else if (action === \"edit\") out[key] = null;\n }\n return out;\n}\n\n/** Build default values from fields and existing data */\nfunction buildDefaults(\n fields: ResourceFormFieldDef[],\n data: Record<string, unknown> | undefined,\n action: \"create\" | \"edit\",\n prefillFromUrl: boolean,\n): Record<string, unknown> {\n const defaults: Record<string, unknown> = {};\n for (const field of fields) {\n // A create's blank template (every column as \"\") never hides a field's own default.\n const blankOnCreate = action === \"create\" && data?.[field.key] === \"\" && field.defaultValue !== undefined;\n if (data && field.key in data && !blankOnCreate) {\n defaults[field.key] = data[field.key];\n } else if (field.defaultValue !== undefined) {\n defaults[field.key] = field.defaultValue;\n } else {\n const fieldType = field.type ?? \"text\";\n switch (fieldType) {\n case \"array\":\n defaults[field.key] = field.arrayMin\n ? Array.from({ length: field.arrayMin }, () =>\n buildArrayItemDefaults(field.arrayFields ?? []),\n )\n : [];\n break;\n case \"number\":\n defaults[field.key] = undefined;\n break;\n case \"switch\":\n case \"checkbox\":\n defaults[field.key] = false;\n break;\n default:\n defaults[field.key] = \"\";\n break;\n }\n }\n }\n\n // URL pre-fill for create mode\n if (typeof window !== \"undefined\" && typeof window.location !== \"undefined\" && typeof window.location.search === \"string\" && action === \"create\" && prefillFromUrl !== false) {\n const params = new URLSearchParams(window.location.search);\n for (const field of fields) {\n // A hidden field is the screen's (its filter or defaults), never the URL's; so is one\n // that says so (a value the screen's filter fixes).\n if (field.hidden || field.type === \"hidden\" || field.fromUrl === false) continue;\n const val = params.get(field.key);\n if (val != null) {\n defaults[field.key] = field.type === \"number\" ? Number(val) : val;\n }\n }\n }\n\n return defaults;\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useResourceForm(options: UseResourceFormOptions): UseResourceFormReturn {\n const {\n resource,\n action,\n id,\n initialData,\n fields: fieldsProp,\n inferFields = true,\n listData,\n onSuccess,\n onError,\n prefillFromUrl = true,\n autoPlaceholder = true,\n validationMode,\n autosave,\n invalidates,\n warnWhenUnsaved = false,\n mutationMode = \"pessimistic\",\n undoDelayMs,\n onUndoable,\n visible = true,\n updates = \"loaded\",\n } = options;\n\n const autosaveEnabled = !!autosave;\n const debounceMs = typeof autosave === \"object\" ? autosave.debounceMs ?? 1000 : 1000;\n\n const provider = useDataProvider();\n const storage = useStorage();\n const queryClient = useQueryClient();\n\n // Fetch record for edit mode when no initialData\n const needsFetch = action === \"edit\" && !initialData && !!id;\n const fetchResult = useOne(\n resource,\n needsFetch ? id : undefined,\n { enabled: needsFetch },\n );\n\n const fetchedData = fetchResult.data ?? undefined;\n const effectiveData = initialData ?? fetchedData;\n const isLoading = needsFetch && fetchResult.isLoading;\n\n // In edit mode the form starts from the provider's form shape of the row\n // (`DataProvider.toFormValues`), for a resource whose form differs from\n // its table. The record id still comes from the row itself.\n const formSource = useMemo(\n () =>\n action === \"edit\" && effectiveData && provider.toFormValues\n ? provider.toFormValues(resource, effectiveData)\n : effectiveData,\n [action, effectiveData, provider, resource],\n );\n\n // Resolve fields\n const resolvedFields = useMemo(\n () => resolveFields(fieldsProp, formSource, listData, autoPlaceholder, inferFields),\n [fieldsProp, formSource, listData, autoPlaceholder, inferFields],\n );\n\n // Build schema\n const schema = useMemo(\n () => buildSchema(resolvedFields, action),\n [resolvedFields, action],\n );\n\n // Build defaults (with optional draft restoration)\n const defaultValues = useMemo(() => {\n const defaults = buildDefaults(resolvedFields, formSource, action, prefillFromUrl);\n if (autosaveEnabled && action === \"create\") {\n const key = `genesis-draft:${resource}:new`;\n const saved = storage.getItem(key);\n if (saved) {\n try {\n const draft = JSON.parse(saved);\n if (draft && typeof draft === \"object\" && !Array.isArray(draft)) {\n // Only restore keys that exist in the field definitions\n const validKeys = new Set(resolvedFields.map((f) => f.key));\n for (const k of Object.keys(draft)) {\n if (validKeys.has(k)) {\n defaults[k] = draft[k];\n }\n }\n } else {\n console.warn(`[useResourceForm] Draft for \"${resource}\" has unexpected shape, removing`);\n storage.removeItem(key);\n }\n } catch {\n console.warn(`[useResourceForm] Corrupt draft for \"${resource}\", removing`);\n storage.removeItem(key);\n }\n }\n }\n return defaults;\n }, [resolvedFields, formSource, action, prefillFromUrl, autosaveEnabled, resource, storage]);\n\n // Form\n // Cast the resolver because zod v4's passthrough() produces `unknown` for input,\n // but react-hook-form expects FieldValues (Record<string, any>).\n const resolver = useMemo(\n () => zodResolver(schema) as unknown as Resolver<Record<string, unknown>>,\n [schema],\n );\n\n const form = useForm<Record<string, unknown>>({\n resolver,\n defaultValues,\n values: action === \"edit\" ? defaultValues : undefined,\n mode: validationMode ?? \"onBlur\",\n reValidateMode: \"onChange\",\n shouldUnregister: true,\n });\n\n // A create form that stays mounted follows its defaults: the screen's hidden values (a new\n // filter or defaults) always, the rest only while the person hasn't typed anything.\n const firstDefaults = useRef(defaultValues);\n useEffect(() => {\n // By value: a screen may hand a new but equal object every render.\n if (action !== \"create\" || sameValue(firstDefaults.current, defaultValues)) return;\n firstDefaults.current = defaultValues;\n if (!form.formState.isDirty) {\n form.reset(defaultValues);\n return;\n }\n for (const field of resolvedFields) {\n if (field.hidden || field.type === \"hidden\") form.setValue(field.key, defaultValues[field.key]);\n }\n }, [action, defaultValues, form, resolvedFields]);\n\n // Autosave effect — persist form values to storage for create mode\n useEffect(() => {\n if (!autosaveEnabled || action !== \"create\") return;\n const key = `genesis-draft:${resource}:new`;\n let timer: ReturnType<typeof setTimeout>;\n\n const subscription = form.watch((values) => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n try {\n storage.setItem(key, JSON.stringify(values));\n } catch (err) {\n console.warn(`[useResourceForm] Autosave failed for \"${resource}\":`, err instanceof Error ? err.message : String(err));\n }\n }, debounceMs);\n });\n\n return () => {\n clearTimeout(timer);\n subscription.unsubscribe();\n };\n }, [autosaveEnabled, resource, action, form, debounceMs, storage]);\n\n // Unsaved changes: RHF's isDirty, cleared by a successful save until the\n // next edit (a create form keeps its values after saving, so RHF alone\n // would still call it dirty).\n const rhfDirty = form.formState.isDirty;\n const [savedClean, setSavedClean] = useState(false);\n const savedCleanRef = useRef(false);\n useEffect(() => {\n const subscription = form.watch((_values, info) => {\n // `watch` also reports resets (no field name); only an edit dirties.\n if (!info.name) return;\n savedCleanRef.current = false;\n setSavedClean(false);\n });\n return () => subscription.unsubscribe();\n }, [form]);\n const isDirty = rhfDirty && !savedClean;\n const warn = !!warnWhenUnsaved;\n const { confirmLeave: guardConfirm } = useUnsavedChangesGuard({\n when: warn && isDirty,\n message: typeof warnWhenUnsaved === \"object\" ? warnWhenUnsaved.message : undefined,\n });\n const confirmLeave = useCallback(\n // The ref, not state: a router blocker may ask in the same tick as the\n // save's onSuccess navigates, before a re-render.\n () => (!warn || savedCleanRef.current ? true : guardConfirm()),\n [warn, guardConfirm],\n );\n const markSaved = useCallback(() => {\n savedCleanRef.current = true;\n setSavedClean(true);\n }, []);\n\n // A save that fails after it was handed off only comes back to the form\n // while the user can still see it.\n const mountedRef = useRef(true);\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n const visibleRef = useRef(visible);\n visibleRef.current = visible;\n\n /** A failed save, on the form: per-field messages and a root summary. */\n const showError = useCallback(\n (error: Error) => {\n const fieldErrors = isDataWriteError(error) ? error.fields : undefined;\n const known = new Set(resolvedFields.map((f) => f.key));\n let first: string | undefined;\n if (fieldErrors) {\n for (const [field, message] of Object.entries(fieldErrors)) {\n if (!known.has(field)) continue;\n form.setError(field, { type: \"server\", message });\n first ??= field;\n }\n }\n form.setError(\"root\", { type: \"server\", message: error.message });\n if (first) {\n try {\n form.setFocus(first);\n } catch {\n // Not rendered (hidden or custom renderForm): the summary still says it.\n }\n }\n },\n [form, resolvedFields],\n );\n\n const reportError = useCallback(\n (error: Error, handedOff?: Record<string, unknown>) => {\n // A save handed off optimistically and then refused is unsaved again,\n // if the form still shows what it saved; a closed, hidden or reset\n // form is left alone.\n const onForm =\n !handedOff ||\n (mountedRef.current && visibleRef.current && sameValue(form.getValues(), handedOff));\n if (onForm) {\n savedCleanRef.current = false;\n setSavedClean(false);\n showError(error);\n }\n if (onError) {\n onError(error);\n } else {\n console.error(`[useResourceForm] ${action} failed for \"${resource}\":`, error);\n }\n },\n [form, showError, onError, action, resource],\n );\n\n // A save that met someone else's change: the values it tried to save, the fields the person\n // changed, and their row as it is now.\n const [conflictState, setConflictState] = useState<{\n conflict: WriteConflict;\n submitted: Record<string, unknown>;\n changed: readonly string[];\n row: Record<string, unknown>;\n } | null>(null);\n // After \"take theirs\": their row, as the record the next save is checked against, until the\n // form's own record changes.\n const [rebased, setRebased] = useState<BaseRecord | null>(null);\n // Counts conflicts found, so \"keep mine\" can tell a new conflict from a plain failure.\n const conflictsFound = useRef(0);\n // Cleared when the form's record really changes, not when a screen hands an equal object again.\n const rebasedFor = useRef(effectiveData);\n useEffect(() => {\n if (sameValue(rebasedFor.current, effectiveData)) return;\n rebasedFor.current = effectiveData;\n setRebased(null);\n }, [effectiveData]);\n // What this person typed that a conflict hasn't settled: kept on the form across the refetch a\n // rolled-back optimistic save starts (which resets the form to their row), until they save or\n // take theirs, so neither a second conflict nor closing the sheet loses it.\n const [unsettled, setUnsettled] = useState<{ changed: readonly string[]; values: Record<string, unknown> } | null>(null);\n useEffect(() => {\n if (!unsettled) return;\n for (const key of unsettled.changed) {\n if (!sameValue(form.getValues(key), unsettled.values[key])) form.setValue(key, unsettled.values[key], { shouldDirty: true });\n }\n }, [unsettled, defaultValues, form]);\n\n // Submit handler. Resolves true when the save went through (or had nothing to send).\n const save = useCallback(\n async (\n submitted: Record<string, unknown>,\n expectedVersion?: string,\n /** \"Keep mine\": the fields this person changed, as the conflict recorded them. */\n keep?: readonly string[],\n ): Promise<boolean> => {\n // \"Keep mine\" leaves the conflict up until this save settles.\n if (expectedVersion === undefined) setConflictState(null);\n // What the form shows as this save goes out (raw input values, before\n // any resolver coercion), to tell later whether it still does.\n const shown = structuredCloneSafe(form.getValues());\n // A field the opened record didn't carry goes only when the person changed it (compared by\n // value: RHF's dirtyFields updates only when read during render).\n const opened = formSource as Record<string, unknown> | undefined;\n // A field read-only when editing is never written by an edit: sending even its unchanged\n // value would fail on a column the person may not update.\n const lockedOnEdit = new Set(action === \"edit\" ? resolvedFields.filter((f) => f.readOnlyOnEdit).map((f) => f.key) : []);\n const writable = lockedOnEdit.size\n ? Object.fromEntries(Object.entries(submitted).filter(([k]) => !lockedOnEdit.has(k)))\n : submitted;\n const changed =\n action === \"edit\" && updates === \"loaded\" && opened\n ? Object.fromEntries(\n Object.entries(writable).filter(\n // Changed: what an input shows differs from where it started, or, for a value saved\n // without an input (a direct handleSave), the value itself does.\n ([k, v]) =>\n k in opened ||\n !sameValue(k in (shown as object) ? (shown as Record<string, unknown>)[k] : v, defaultValues[k]),\n ),\n )\n : writable;\n // An empty input the person left or made empty is no value (see `blankValues`).\n const touched = new Set(\n keep ??\n Object.entries(changed)\n .filter(([k, v]) => !sameValue(k in (shown as object) ? (shown as Record<string, unknown>)[k] : v, defaultValues[k]))\n .map(([k]) => k),\n );\n const formData = blankValues(changed, resolvedFields, action, touched);\n // A conflict offers only what this person changed, compared in the form's shape.\n const conflictOf = (error: unknown) => {\n const found = writeConflict(error, formData, {\n changed: touched,\n ...(provider.toFormValues && formSource !== effectiveData\n ? { view: (row: Record<string, unknown>) => provider.toFormValues!(resource, row as BaseRecord) as Record<string, unknown> }\n : {}),\n });\n if (found && isDataWriteError(error) && error.current) {\n conflictsFound.current += 1;\n setUnsettled({ changed: [...touched], values: { ...submitted } });\n setConflictState({ conflict: found, submitted, changed: [...touched], row: error.current as Record<string, unknown> });\n }\n return found;\n };\n // An edit with nothing left to write (only read-only fields) has nothing to send.\n if (action === \"edit\" && Object.keys(formData).length === 0) {\n setConflictState(null);\n markSaved();\n onSuccess?.({ ...(effectiveData ?? {}), ...(id != null && id !== \"\" ? { id } : {}) });\n return true;\n }\n try {\n let recordId: string | number | undefined;\n if (action === \"edit\") {\n recordId = id ?? String((effectiveData as Record<string, unknown>)?.id ?? \"\");\n if (!recordId) {\n throw new Error(\"Cannot update record: no ID available. Provide an id prop or ensure the record has an id field.\");\n }\n }\n const before = recordId != null ? cachedRecord(queryClient, resource, recordId) : undefined;\n const outcome = await executeWrite<BaseRecord>({\n queryClient,\n provider,\n resource,\n kind: action === \"create\" ? \"create\" : \"update\",\n id: recordId,\n // The cache holds rows; patch it only when the form's values are\n // row-shaped (no provider.toFormValues reshaping this record).\n data: formSource === effectiveData ? formData : undefined,\n // The record the form shows: its version is the one this edit is checked against, even\n // when the cache has since refetched a newer one.\n ...(action === \"edit\" && (rebased ?? effectiveData) ? { base: (rebased ?? effectiveData) as BaseRecord } : {}),\n ...(expectedVersion !== undefined ? { expectedVersion } : {}),\n mode: mutationMode,\n undoDelayMs,\n onUndoable,\n send: async (ctx) => {\n const keepalive = ctx.keepalive ? { keepalive: true } : {};\n const res =\n action === \"create\"\n ? await provider.create(resource, { data: formData, ...keepalive })\n : await provider.update(resource, {\n id: recordId!,\n data: ctx.data ?? formData,\n ...keepalive,\n ...(ctx.expectedVersion !== undefined ? { expectedVersion: ctx.expectedVersion } : {}),\n });\n return { record: res.data, audit: res.audit };\n },\n committed: async (result) => {\n // The next save from this form is checked against the version this one left, not the\n // record it opened with (a form that stays open after a save, such as a native sheet).\n if (action === \"edit\" && mountedRef.current && result && typeof result === \"object\") {\n const saved = result as BaseRecord;\n setRebased((prev) => ({ ...((prev ?? effectiveData ?? {}) as BaseRecord), ...saved }));\n }\n // Clear draft on successful save\n if (autosaveEnabled && action === \"create\") {\n try {\n storage.removeItem(`genesis-draft:${resource}:new`);\n } catch (err) {\n console.warn(`[useResourceForm] Draft cleanup failed for \"${resource}\":`, err instanceof Error ? err.message : String(err));\n }\n }\n // Invalidate queries to refresh data: the resource's own, then any\n // related keys the provider or the caller named.\n await invalidateResource(queryClient, resource);\n const related = relatedKeys(\n provider,\n {\n resource,\n kind: action === \"create\" ? \"create\" : \"update\",\n id: (recordId ?? result.id) as string | number,\n record: result,\n },\n invalidates,\n );\n await Promise.all(related.map((queryKey) => queryClient.invalidateQueries({ queryKey: [...queryKey] })));\n },\n failedLater: (error) => {\n if (mountedRef.current) conflictOf(error);\n reportError(error, shown);\n },\n });\n setConflictState(null);\n setUnsettled(null);\n markSaved();\n if (outcome.status === \"committed\") {\n onSuccess?.(outcome.record);\n } else {\n onSuccess?.(\n action === \"edit\"\n ? { ...(before ?? effectiveData ?? {}), ...formData, id: recordId }\n : { ...formData },\n );\n }\n return true;\n } catch (err) {\n conflictOf(err);\n reportError(err instanceof Error ? err : new Error(String(err)));\n return false;\n }\n },\n [form, action, provider, resource, id, effectiveData, rebased, formSource, queryClient, onSuccess, autosaveEnabled, storage, invalidates, mutationMode, undoDelayMs, onUndoable, reportError, markSaved, updates, defaultValues, resolvedFields],\n );\n\n const handleSubmit = useCallback(async (submitted: Record<string, unknown>) => {\n await save(submitted);\n }, [save]);\n\n const keepMine = useCallback(async () => {\n if (!conflictState) return;\n const { conflict, submitted, changed } = conflictState;\n // Only what this person changed is theirs to keep: every other field the form sends takes\n // their value, so \"keep mine\" never puts back a stale copy of a field nobody touched here.\n const values = { ...submitted };\n for (const key of Object.keys(values)) {\n if (!changed.includes(key) && key in conflict.theirs) values[key] = conflict.theirs[key];\n }\n form.clearErrors(\"root\");\n const found = conflictsFound.current;\n const ok = await save(values, conflict.currentVersion ?? undefined, changed);\n // Failed without a new conflict (which replaces this one): say why, on the sheet.\n if (!ok && conflictsFound.current === found) throw new Error(form.getFieldState(\"root\").error?.message ?? \"Not saved.\");\n }, [conflictState, form, save]);\n\n const dismissConflict = useCallback(() => setConflictState(null), []);\n\n const takeTheirs = useCallback(() => {\n if (!conflictState) return;\n const { row: theirs } = conflictState;\n setConflictState(null);\n setUnsettled(null);\n // The next save is checked against their row's version, not the one the form opened at.\n setRebased({ ...((effectiveData ?? {}) as BaseRecord), ...(theirs as BaseRecord) });\n form.clearErrors();\n const recordId = id ?? (effectiveData as Record<string, unknown> | undefined)?.id;\n if (recordId != null && recordId !== \"\") {\n // Every cached copy shows their row now; the refetch confirms it.\n patchCachedRow(queryClient, resource, { ...theirs, id: recordId as string | number });\n void invalidateResource(queryClient, resource);\n }\n const shown = action === \"edit\" && provider.toFormValues ? provider.toFormValues(resource, theirs as BaseRecord) : theirs;\n // Every field the form shows, from their row; anything else the form holds stays.\n const next = { ...form.getValues() };\n for (const key of new Set([...resolvedFields.map((f) => f.key), ...Object.keys(next)])) {\n if (key in shown) next[key] = (shown as Record<string, unknown>)[key];\n }\n form.reset(next);\n }, [conflictState, form, id, effectiveData, queryClient, resource, action, provider, resolvedFields]);\n\n const onSubmit = useCallback(\n (e?: { preventDefault?: () => void }) => form.handleSubmit(handleSubmit)(e as React.BaseSyntheticEvent),\n [form, handleSubmit],\n );\n\n const isSaving = form.formState.isSubmitting;\n\n return {\n form,\n resolvedFields,\n onSubmit,\n handleSave: handleSubmit,\n isSaving,\n isLoading,\n isDirty,\n confirmLeave,\n conflict: conflictState?.conflict ?? null,\n keepMine,\n takeTheirs,\n dismissConflict,\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { useDataProvider } from './chunk-VDEW4AOS.js';
1
+ import { useDataProvider } from './chunk-PSFKIG27.js';
2
2
  import { useQuery } from '@tanstack/react-query';
3
3
 
4
4
  var CHUNK = 100;
@@ -130,5 +130,5 @@ function useRelationLabel(reference, id, options = {}) {
130
130
  }
131
131
 
132
132
  export { loadRelationLabel, relationNamingField, useRelationLabel };
133
- //# sourceMappingURL=chunk-EHFYSJJA.js.map
134
- //# sourceMappingURL=chunk-EHFYSJJA.js.map
133
+ //# sourceMappingURL=chunk-42QPCDQF.js.map
134
+ //# sourceMappingURL=chunk-42QPCDQF.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-relation-label.ts"],"names":[],"mappings":";;;AAiBA,IAAM,KAAA,GAAQ,GAAA;AAEd,IAAM,UAAA,GAAa,0BAAA;AAEnB,IAAM,MAAA,GAAS,6CAAA;AAUf,IAAM,OAAA,uBAAc,OAAA,EAA0C;AAC9D,IAAM,MAAA,uBAAa,OAAA,EAAgE;AAEnF,IAAM,SAAA,GAAY,GAAA;AAGlB,SAAS,MAAA,CAAU,MAAwB,QAAA,EAAyB;AAClE,EAAA,OAAO,IAAI,OAAA,CAAW,CAAC,OAAA,KAAY;AACjC,IAAA,MAAM,QAAQ,UAAA,CAAW,MAAM,OAAA,CAAQ,QAAQ,GAAG,SAAS,CAAA;AAC3D,IAAA,MAAM,IAAA,GAAO,CAAC,KAAA,KAAa;AACzB,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,OAAA,CAAQ,KAAK,CAAA;AAAA,IACf,CAAA;AACA,IAAA,IAAI;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AA,GAAK,EAAA,GAAK,IAAA;AACnH,EAAA,MAAM,GAAA,GAAM,MAAA,KAAW,IAAA,GAAO,IAAA,GAAO,CAAA,EAAG,OAAO,MAAM,CAAA,CAAA,EAAI,MAAA,CAAO,MAAM,CAAC,CAAA,CAAA;AACvE,EAAA,MAAM,QAAQ,QAAA,CAAS;AAAA,IACrB,QAAA,EAAU,CAAC,SAAA,EAAW,QAAA,EAAU,kBAAkB,EAAE,KAAA,EAAO,SAAA,EAAW,KAAA,EAAO,UAAA,EAAY,UAAA,IAAc,IAAA,EAAM,EAAA,EAAI,KAAK,CAAA;AAAA,IACtH,OAAA,EAAS,OAAA,IAAW,OAAA,CAAQ,SAAA,IAAa,GAAG,CAAA;AAAA,IAC5C,SAAA,EAAW,GAAA;AAAA,IACX,KAAA,EAAO,KAAA;AAAA,IACP,SAAS,MAAM,iBAAA,CAAkB,QAAA,EAAU,SAAA,EAAY,QAAS,UAAU;AAAA,GAC3E,CAAA;AACD,EAAA,IAAI,KAAA,CAAM,SAAS,OAAO,IAAA;AAC1B,EAAA,OAAO,KAAA,CAAM,IAAA;AACf","file":"chunk-EHFYSJJA.js","sourcesContent":["// A link's words: the linked row's name in place of its id (docs/RESOURCE-VIEW.md, \"Relation\n// labels\"). Every cell asks for its own id, and the ids asked for in the same moment go out as\n// one `in` query per linked resource, so a page of 50 rows costs one request, never 50.\n\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { DataProvider, Identifier } from \"../provider/types\";\nimport type { FieldReference } from \"../schema/types\";\n\nexport interface UseRelationLabelOptions {\n /** The linked row's field that names it. Default: the linked resource's `labelField` (`describe`). */\n labelField?: string;\n /** Default `true`. */\n enabled?: boolean;\n}\n\n// Ids per request: an `in` list stays well inside a URL.\nconst CHUNK = 100;\n// Field names only go into `select`, so nothing else rides along in the request.\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n// What names a row when nothing says (as `defineView` guesses a contract's labelField).\nconst NAMING = /^(name|title|label|full_name|display_name)$/;\n\ntype Waiter = { resolve: (label: string | null) => void; reject: (error: unknown) => void };\n// Keyed by the id's type and text, so 1 and \"1\" are both sent as given: a provider that compares\n// strictly (the mock's `in`) must get a number as a number. Rows match by text either way, since\n// a database may hand back 1 for \"1\".\ntype Asked = { id: Identifier; waiters: Waiter[] };\ntype Batch = { reference: FieldReference; labelField: string | undefined; ids: Map<string, Asked> };\n\n// Per provider, so two providers (two apps, a test each) never share a batch or a guess.\nconst batches = new WeakMap<DataProvider, Map<string, Batch>>();\nconst namers = new WeakMap<DataProvider, Map<string, Promise<string | undefined>>>();\n// How long a label waits on `describe` or `capabilities` before going on without them.\nconst SETTLE_MS = 10_000;\n\n/** A promise's value, or `fallback` when it fails, throws or takes longer than SETTLE_MS. */\nfunction within<T>(work: () => Promise<T>, fallback: T): Promise<T> {\n return new Promise<T>((resolve) => {\n const timer = setTimeout(() => resolve(fallback), SETTLE_MS);\n const done = (value: T) => {\n clearTimeout(timer);\n resolve(value);\n };\n try {\n work().then(done, () => done(fallback));\n } catch {\n done(fallback);\n }\n });\n}\n\n/**\n * The linked resource's naming field, from `describe` once per resource; undefined when it can't\n * say. A failed `describe` isn't remembered, so the next page asks again.\n */\nfunction namingField(provider: DataProvider, resource: string): Promise<string | undefined> {\n let known = namers.get(provider);\n if (!known) namers.set(provider, (known = new Map()));\n let found = known.get(resource);\n if (!found) {\n const describe = provider.describe?.bind(provider);\n const table = known;\n found = describe\n ? within(\n () =>\n describe(resource).then((schema) => schema.labelField ?? schema.fields.find((f) => NAMING.test(f.name))?.name ?? null),\n undefined as string | null | undefined,\n ).then((field) => {\n // undefined: describe failed. null: it answered, with no naming field.\n if (field === undefined) table.delete(resource);\n return field ?? undefined;\n })\n : Promise.resolve(undefined);\n known.set(resource, found);\n }\n return found;\n}\n\n/**\n * The linked resource's naming field, as a link's words find it: its `labelField` from\n * `describe`, else a `name`/`title`-like field. Undefined when it can't say. Asked once per\n * resource and provider; a picker uses it to search and sort the rows it lists.\n */\nexport function relationNamingField(provider: DataProvider, resource: string): Promise<string | undefined> {\n return namingField(provider, resource);\n}\n\n/** Ids per request: the provider's page limit, at most CHUNK. */\nasync function chunkSize(provider: DataProvider, resource: string): Promise<number> {\n const capabilities = provider.capabilities?.bind(provider);\n const max = capabilities ? await within(() => capabilities(resource).then((c) => c.maxPerPage), undefined) : undefined;\n return typeof max === \"number\" && max >= 1 ? Math.min(CHUNK, Math.floor(max)) : CHUNK;\n}\n\n/** A value as words, or null when it has none. */\nfunction words(value: unknown): string | null {\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n if (typeof value !== \"string\") return null;\n return value.trim() || null;\n}\n\nasync function flush(provider: DataProvider, batch: Batch): Promise<void> {\n const { reference, ids } = batch;\n const fail = (keys: readonly string[], error: unknown) => keys.forEach((k) => ids.get(k)?.waiters.forEach((w) => w.reject(error)));\n const all = [...ids.keys()];\n let labelField: string | undefined;\n let size: number;\n try {\n labelField = batch.labelField ?? (await namingField(provider, reference.resource));\n if (labelField !== undefined && !IDENTIFIER.test(labelField)) labelField = undefined;\n size = await chunkSize(provider, reference.resource);\n } catch (error) {\n // Every waiter settles, whatever went wrong.\n fail(all, error);\n return;\n }\n const select = labelField && IDENTIFIER.test(reference.field) ? `${reference.field},${labelField}` : undefined;\n for (let i = 0; i < all.length; i += size) {\n const chunk = all.slice(i, i + size);\n try {\n const { data } = await provider.getList(reference.resource, {\n // The whole page: a link to a field that isn't unique can match more rows than ids.\n pagination: { page: 1, perPage: size },\n filters: [{ field: reference.field, operator: \"in\", value: chunk.map((k) => ids.get(k)!.id) as string[] | number[] }],\n count: \"none\",\n ...(select ? { select } : {}),\n });\n const found = new Map<string, string | null>();\n for (const row of data as Record<string, unknown>[]) {\n const key = String(row[reference.field]);\n if (found.get(key)) continue;\n const name = labelField ? row[labelField] : row[Object.keys(row).find((k) => NAMING.test(k)) ?? \"\"];\n found.set(key, words(name));\n }\n // An id the viewer can't see, or one that's gone, has no words.\n for (const k of chunk) {\n const asked = ids.get(k);\n asked?.waiters.forEach((w) => w.resolve(found.get(String(asked.id)) ?? null));\n }\n } catch (error) {\n fail(chunk, error);\n }\n }\n}\n\n/**\n * The words for one linked id, batched with every other id asked for in the same tick: one\n * `getList(resource, { filters: [{ field, operator: \"in\" }] })` per linked resource and naming\n * field. Resolves null when the row has no words or isn't visible to this viewer.\n */\nexport function loadRelationLabel(\n provider: DataProvider,\n reference: FieldReference,\n id: Identifier,\n labelField?: string,\n): Promise<string | null> {\n let pending = batches.get(provider);\n if (!pending) batches.set(provider, (pending = new Map()));\n const key = `${reference.resource}\\u0000${reference.field}\\u0000${labelField ?? \"\"}`;\n let batch = pending.get(key);\n if (!batch) {\n const created: Batch = { reference, labelField, ids: new Map() };\n pending.set(key, (batch = created));\n // A macrotask, not a microtask: every cell's effect in a commit has asked by then.\n setTimeout(() => {\n pending!.delete(key);\n void flush(provider, created);\n }, 0);\n }\n return new Promise((resolve, reject) => {\n const idKey = `${typeof id}:${String(id)}`;\n const asked = batch!.ids.get(idKey) ?? { id, waiters: [] };\n asked.waiters.push({ resolve, reject });\n batch!.ids.set(idKey, asked);\n });\n}\n\n/**\n * A linked row's words for a `relation` cell: `undefined` while they load, `null` when there are\n * none (the row is hidden from this viewer, gone, unnamed, or the read failed), so a screen shows\n * its own words then, never the raw id. Cached per id for a minute and refreshed when the linked\n * resource changes (its writes invalidate `[resource]`).\n */\nexport function useRelationLabel(\n reference: FieldReference | undefined,\n id: unknown,\n options: UseRelationLabelOptions = {},\n): string | null | undefined {\n const provider = useDataProvider();\n const { labelField, enabled = true } = options;\n const linked: Identifier | null = typeof id === \"string\" || (typeof id === \"number\" && Number.isFinite(id)) ? id : null;\n const key = linked === null ? null : `${typeof linked}:${String(linked)}`;\n const query = useQuery({\n queryKey: [reference?.resource, \"relation-label\", { field: reference?.field, labelField: labelField ?? null, id: key }],\n enabled: enabled && Boolean(reference && key),\n staleTime: 60_000,\n retry: false,\n queryFn: () => loadRelationLabel(provider, reference!, linked!, labelField),\n });\n if (query.isError) return null;\n return query.data;\n}\n"]}
1
+ {"version":3,"sources":["../src/hooks/use-relation-label.ts"],"names":[],"mappings":";;;AAiBA,IAAM,KAAA,GAAQ,GAAA;AAEd,IAAM,UAAA,GAAa,0BAAA;AAEnB,IAAM,MAAA,GAAS,6CAAA;AAUf,IAAM,OAAA,uBAAc,OAAA,EAA0C;AAC9D,IAAM,MAAA,uBAAa,OAAA,EAAgE;AAEnF,IAAM,SAAA,GAAY,GAAA;AAGlB,SAAS,MAAA,CAAU,MAAwB,QAAA,EAAyB;AAClE,EAAA,OAAO,IAAI,OAAA,CAAW,CAAC,OAAA,KAAY;AACjC,IAAA,MAAM,QAAQ,UAAA,CAAW,MAAM,OAAA,CAAQ,QAAQ,GAAG,SAAS,CAAA;AAC3D,IAAA,MAAM,IAAA,GAAO,CAAC,KAAA,KAAa;AACzB,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,OAAA,CAAQ,KAAK,CAAA;AAAA,IACf,CAAA;AACA,IAAA,IAAI;AACF,MAAA,IAAA,GAAO,IAAA,CAAK,IAAA,EAAM,MAAM,IAAA,CAAK,QAAQ,CAAC,CAAA;AAAA,IACxC,CAAA,CAAA,MAAQ;AACN,MAAA,IAAA,CAAK,QAAQ,CAAA;AAAA,IACf;AAAA,EACF,CAAC,CAAA;AACH;AAMA,SAAS,WAAA,CAAY,UAAwB,QAAA,EAA+C;AAC1F,EAAA,IAAI,KAAA,GAAQ,MAAA,CAAO,GAAA,CAAI,QAAQ,CAAA;AAC/B,EAAA,IAAI,CAAC,OAAO,MAAA,CAAO,GAAA,CAAI,UAAW,KAAA,mBAAQ,IAAI,KAAM,CAAA;AACpD,EAAA,IAAI,KAAA,GAAQ,KAAA,CAAM,GAAA,CAAI,QAAQ,CAAA;AAC9B,EAAA,IAAI,CAAC,KAAA,EAAO;AACV,IAAA,MAAM,QAAA,GAAW,QAAA,CAAS,QAAA,EAAU,IAAA,CAAK,QAAQ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UAAU;AAAA,GAC3E,CAAA;AACD,EAAA,IAAI,KAAA,CAAM,SAAS,OAAO,IAAA;AAC1B,EAAA,OAAO,KAAA,CAAM,IAAA;AACf","file":"chunk-42QPCDQF.js","sourcesContent":["// A link's words: the linked row's name in place of its id (docs/RESOURCE-VIEW.md, \"Relation\n// labels\"). Every cell asks for its own id, and the ids asked for in the same moment go out as\n// one `in` query per linked resource, so a page of 50 rows costs one request, never 50.\n\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { DataProvider, Identifier } from \"../provider/types\";\nimport type { FieldReference } from \"../schema/types\";\n\nexport interface UseRelationLabelOptions {\n /** The linked row's field that names it. Default: the linked resource's `labelField` (`describe`). */\n labelField?: string;\n /** Default `true`. */\n enabled?: boolean;\n}\n\n// Ids per request: an `in` list stays well inside a URL.\nconst CHUNK = 100;\n// Field names only go into `select`, so nothing else rides along in the request.\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n// What names a row when nothing says (as `defineView` guesses a contract's labelField).\nconst NAMING = /^(name|title|label|full_name|display_name)$/;\n\ntype Waiter = { resolve: (label: string | null) => void; reject: (error: unknown) => void };\n// Keyed by the id's type and text, so 1 and \"1\" are both sent as given: a provider that compares\n// strictly (the mock's `in`) must get a number as a number. Rows match by text either way, since\n// a database may hand back 1 for \"1\".\ntype Asked = { id: Identifier; waiters: Waiter[] };\ntype Batch = { reference: FieldReference; labelField: string | undefined; ids: Map<string, Asked> };\n\n// Per provider, so two providers (two apps, a test each) never share a batch or a guess.\nconst batches = new WeakMap<DataProvider, Map<string, Batch>>();\nconst namers = new WeakMap<DataProvider, Map<string, Promise<string | undefined>>>();\n// How long a label waits on `describe` or `capabilities` before going on without them.\nconst SETTLE_MS = 10_000;\n\n/** A promise's value, or `fallback` when it fails, throws or takes longer than SETTLE_MS. */\nfunction within<T>(work: () => Promise<T>, fallback: T): Promise<T> {\n return new Promise<T>((resolve) => {\n const timer = setTimeout(() => resolve(fallback), SETTLE_MS);\n const done = (value: T) => {\n clearTimeout(timer);\n resolve(value);\n };\n try {\n work().then(done, () => done(fallback));\n } catch {\n done(fallback);\n }\n });\n}\n\n/**\n * The linked resource's naming field, from `describe` once per resource; undefined when it can't\n * say. A failed `describe` isn't remembered, so the next page asks again.\n */\nfunction namingField(provider: DataProvider, resource: string): Promise<string | undefined> {\n let known = namers.get(provider);\n if (!known) namers.set(provider, (known = new Map()));\n let found = known.get(resource);\n if (!found) {\n const describe = provider.describe?.bind(provider);\n const table = known;\n found = describe\n ? within(\n () =>\n describe(resource).then((schema) => schema.labelField ?? schema.fields.find((f) => NAMING.test(f.name))?.name ?? null),\n undefined as string | null | undefined,\n ).then((field) => {\n // undefined: describe failed. null: it answered, with no naming field.\n if (field === undefined) table.delete(resource);\n return field ?? undefined;\n })\n : Promise.resolve(undefined);\n known.set(resource, found);\n }\n return found;\n}\n\n/**\n * The linked resource's naming field, as a link's words find it: its `labelField` from\n * `describe`, else a `name`/`title`-like field. Undefined when it can't say. Asked once per\n * resource and provider; a picker uses it to search and sort the rows it lists.\n */\nexport function relationNamingField(provider: DataProvider, resource: string): Promise<string | undefined> {\n return namingField(provider, resource);\n}\n\n/** Ids per request: the provider's page limit, at most CHUNK. */\nasync function chunkSize(provider: DataProvider, resource: string): Promise<number> {\n const capabilities = provider.capabilities?.bind(provider);\n const max = capabilities ? await within(() => capabilities(resource).then((c) => c.maxPerPage), undefined) : undefined;\n return typeof max === \"number\" && max >= 1 ? Math.min(CHUNK, Math.floor(max)) : CHUNK;\n}\n\n/** A value as words, or null when it has none. */\nfunction words(value: unknown): string | null {\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n if (typeof value !== \"string\") return null;\n return value.trim() || null;\n}\n\nasync function flush(provider: DataProvider, batch: Batch): Promise<void> {\n const { reference, ids } = batch;\n const fail = (keys: readonly string[], error: unknown) => keys.forEach((k) => ids.get(k)?.waiters.forEach((w) => w.reject(error)));\n const all = [...ids.keys()];\n let labelField: string | undefined;\n let size: number;\n try {\n labelField = batch.labelField ?? (await namingField(provider, reference.resource));\n if (labelField !== undefined && !IDENTIFIER.test(labelField)) labelField = undefined;\n size = await chunkSize(provider, reference.resource);\n } catch (error) {\n // Every waiter settles, whatever went wrong.\n fail(all, error);\n return;\n }\n const select = labelField && IDENTIFIER.test(reference.field) ? `${reference.field},${labelField}` : undefined;\n for (let i = 0; i < all.length; i += size) {\n const chunk = all.slice(i, i + size);\n try {\n const { data } = await provider.getList(reference.resource, {\n // The whole page: a link to a field that isn't unique can match more rows than ids.\n pagination: { page: 1, perPage: size },\n filters: [{ field: reference.field, operator: \"in\", value: chunk.map((k) => ids.get(k)!.id) as string[] | number[] }],\n count: \"none\",\n ...(select ? { select } : {}),\n });\n const found = new Map<string, string | null>();\n for (const row of data as Record<string, unknown>[]) {\n const key = String(row[reference.field]);\n if (found.get(key)) continue;\n const name = labelField ? row[labelField] : row[Object.keys(row).find((k) => NAMING.test(k)) ?? \"\"];\n found.set(key, words(name));\n }\n // An id the viewer can't see, or one that's gone, has no words.\n for (const k of chunk) {\n const asked = ids.get(k);\n asked?.waiters.forEach((w) => w.resolve(found.get(String(asked.id)) ?? null));\n }\n } catch (error) {\n fail(chunk, error);\n }\n }\n}\n\n/**\n * The words for one linked id, batched with every other id asked for in the same tick: one\n * `getList(resource, { filters: [{ field, operator: \"in\" }] })` per linked resource and naming\n * field. Resolves null when the row has no words or isn't visible to this viewer.\n */\nexport function loadRelationLabel(\n provider: DataProvider,\n reference: FieldReference,\n id: Identifier,\n labelField?: string,\n): Promise<string | null> {\n let pending = batches.get(provider);\n if (!pending) batches.set(provider, (pending = new Map()));\n const key = `${reference.resource}\\u0000${reference.field}\\u0000${labelField ?? \"\"}`;\n let batch = pending.get(key);\n if (!batch) {\n const created: Batch = { reference, labelField, ids: new Map() };\n pending.set(key, (batch = created));\n // A macrotask, not a microtask: every cell's effect in a commit has asked by then.\n setTimeout(() => {\n pending!.delete(key);\n void flush(provider, created);\n }, 0);\n }\n return new Promise((resolve, reject) => {\n const idKey = `${typeof id}:${String(id)}`;\n const asked = batch!.ids.get(idKey) ?? { id, waiters: [] };\n asked.waiters.push({ resolve, reject });\n batch!.ids.set(idKey, asked);\n });\n}\n\n/**\n * A linked row's words for a `relation` cell: `undefined` while they load, `null` when there are\n * none (the row is hidden from this viewer, gone, unnamed, or the read failed), so a screen shows\n * its own words then, never the raw id. Cached per id for a minute and refreshed when the linked\n * resource changes (its writes invalidate `[resource]`).\n */\nexport function useRelationLabel(\n reference: FieldReference | undefined,\n id: unknown,\n options: UseRelationLabelOptions = {},\n): string | null | undefined {\n const provider = useDataProvider();\n const { labelField, enabled = true } = options;\n const linked: Identifier | null = typeof id === \"string\" || (typeof id === \"number\" && Number.isFinite(id)) ? id : null;\n const key = linked === null ? null : `${typeof linked}:${String(linked)}`;\n const query = useQuery({\n queryKey: [reference?.resource, \"relation-label\", { field: reference?.field, labelField: labelField ?? null, id: key }],\n enabled: enabled && Boolean(reference && key),\n staleTime: 60_000,\n retry: false,\n queryFn: () => loadRelationLabel(provider, reference!, linked!, labelField),\n });\n if (query.isError) return null;\n return query.data;\n}\n"]}
@@ -1,9 +1,10 @@
1
1
  import { NO_VIEWER } from './chunk-OZYF55E3.js';
2
2
  import { workspaceAt, workspaceHref } from './chunk-UHOMTFBD.js';
3
3
  import { stableJson } from './chunk-HBAPYA5K.js';
4
- import { flushPendingWrites, dropPendingWrites } from './chunk-6WV6ST67.js';
4
+ import { flushPendingWrites, dropPendingWrites } from './chunk-YNXLPOAB.js';
5
+ import { PersistedViewerContext } from './chunk-PSFKIG27.js';
5
6
  import { isTimeZone, personTimeZone, dayIn } from './chunk-WXENWPWP.js';
6
- import { reportError } from './chunk-37RWGNIO.js';
7
+ import { reportError } from './chunk-VFT6QKZW.js';
7
8
  import { useQueryClient } from '@tanstack/react-query';
8
9
  import { createContext, useContext, useMemo, useRef, useEffect, useState, Fragment as Fragment$1 } from 'react';
9
10
  import { jsx, Fragment } from 'react/jsx-runtime';
@@ -82,8 +83,10 @@ function scopeClock(scopeTimeZone, viewerZone) {
82
83
  return viewerZone;
83
84
  }
84
85
  var reportedScopeZones = /* @__PURE__ */ new Set();
85
- function ViewerScope({ viewer, persistedViewer, scope, roles, timeZone, scopeTimeZone, fallback = null, children }) {
86
+ function ViewerScope({ viewer, persistedViewer: persistedViewerProp, scope, roles, timeZone, scopeTimeZone, fallback = null, children }) {
86
87
  const queryClient = useQueryClient();
88
+ const restoredFor = useContext(PersistedViewerContext);
89
+ const persistedViewer = persistedViewerProp !== void 0 ? persistedViewerProp : restoredFor;
87
90
  const zone = personTimeZone({ timeZone });
88
91
  const scopeZone = useMemo(() => scopeClock(scopeTimeZone, zone), [scopeTimeZone, zone]);
89
92
  const day = useToday(zone);
@@ -163,5 +166,5 @@ function WorkspaceScope({ workspaces, pathname, scope, keep, children, ...viewer
163
166
  }
164
167
 
165
168
  export { ViewerScope, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace };
166
- //# sourceMappingURL=chunk-RK365SO2.js.map
167
- //# sourceMappingURL=chunk-RK365SO2.js.map
169
+ //# sourceMappingURL=chunk-AKF2RAGX.js.map
170
+ //# sourceMappingURL=chunk-AKF2RAGX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/viewer-scope.tsx","../src/hooks/workspace-scope.tsx"],"names":["Fragment","createContext","useContext","useMemo","useEffect","jsx"],"mappings":";;;;;;;;;;;AAWA,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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AAA,IAAC,WAAA;AAAA,IAAA;AAAA,MACE,GAAG,WAAA;AAAA,MACJ,OAAO,EAAE,GAAG,KAAA,EAAO,GAAG,SAAS,KAAA,EAAM;AAAA,MACpC,GAAI,SAAS,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI,EAAC;AAAA,MAC/D,GAAI,SAAS,QAAA,KAAa,MAAA,GAAY,EAAE,aAAA,EAAe,OAAA,CAAQ,QAAA,EAAS,GAAI,EAAC;AAAA,MAE7E;AAAA;AAAA,GACH,EACF,CAAA;AAEJ","file":"chunk-AKF2RAGX.js","sourcesContent":["import { useQueryClient, type QueryClient } from \"@tanstack/react-query\";\nimport { createContext, Fragment, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { dayIn, isTimeZone, 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\";\nimport { PersistedViewerContext } from \"../provider/context\";\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 person, space or set of people Genesis knows by name, plus\n * whatever the app scopes to under its own key (`{ orgId }`, `{ leagueId }`, `{ locationId }`).\n * Screens turn it into server filters and create defaults (a view's `scope: [\"league_id\"]` reads\n * `league_id`, then `leagueId`); it never decides access (row-level security does).\n */\nexport interface ResourceScope {\n personId?: string;\n spaceId?: string;\n /** Several people at once (a coach's client list, a group). */\n personIds?: readonly string[];\n /** The app's own scope keys: `orgId`, `leagueId`, `locationId`, … */\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 * The zone of whatever the viewer is scoped to (a location, a league), for columns with\n * `timeZone: \"scope\"`: ViewerScope's `scopeTimeZone` when valid, else {@link timeZone}.\n */\n scopeTimeZone?: 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. Inside a\n * `GenesisProvider` with `persist`, it defaults to its `persistScope`'s user.\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 /**\n * The IANA zone of whatever the viewer is scoped to (a location, a league), when it has one.\n * Columns with `timeZone: \"scope\"` read on it; without it they read on the viewer's clock.\n */\n scopeTimeZone?: 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 * The scope's clock: `scopeTimeZone` when the runtime knows it, else the viewer's. A zone it\n * doesn't know is never a quiet fallback: it throws in development, and in production it is\n * reported (`reportError`, once per zone) before the viewer's clock is used, so a misspelt zone can't show\n * times on the wrong clock unnoticed.\n */\nexport function scopeClock(scopeTimeZone: string | null | undefined, viewerZone: string): string {\n if (scopeTimeZone === undefined || scopeTimeZone === null || scopeTimeZone === \"\") return viewerZone;\n if (isTimeZone(scopeTimeZone)) return scopeTimeZone;\n const error = new RangeError(`[genesis-core] scopeTimeZone \"${scopeTimeZone}\" isn't a time zone this runtime knows (an IANA name such as \"Europe/Berlin\")`);\n if (process.env.NODE_ENV !== \"production\") throw error;\n // Once per zone: a bad zone in a long-lived screen must not flood the error reporter.\n if (!reportedScopeZones.has(scopeTimeZone)) {\n reportedScopeZones.add(scopeTimeZone);\n reportError(error, \"core:viewer-scope\");\n }\n return viewerZone;\n}\n\n/** The unknown scope zones already reported, so each is reported once per page load. */\nconst reportedScopeZones = new Set<string>();\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: persistedViewerProp, scope, roles, timeZone, scopeTimeZone, fallback = null, children }: ViewerScopeProps) {\n const queryClient = useQueryClient();\n const restoredFor = useContext(PersistedViewerContext);\n const persistedViewer = persistedViewerProp !== undefined ? persistedViewerProp : restoredFor;\n const zone = personTimeZone({ timeZone });\n // Memoised, and scopeClock reports a zone once, so a bad zone isn't reported on every render.\n const scopeZone = useMemo(() => scopeClock(scopeTimeZone, zone), [scopeTimeZone, zone]);\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, scopeTimeZone: scopeZone, day }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [viewer, scopeKey, rolesKey, zone, scopeZone, 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","import { createContext, useContext, useEffect, useMemo } from \"react\";\nimport { ViewerScope, type ViewerScopeProps } from \"./viewer-scope\";\nimport { workspaceAt, workspaceHref, type Workspace, type WorkspaceHrefOptions } from \"../workspaces\";\n\n/**\n * The workspace the viewer is in, and where each of their others is from here.\n *\n * @stability Beta\n */\nexport interface WorkspaceContext<W extends Workspace = Workspace> {\n /** Undefined when the URL is in no workspace (the app's front door, a sign-in page). */\n current: W | undefined;\n workspaces: readonly W[];\n /** Where switching to `to` goes from the current URL, keeping the viewer's place when it can. */\n hrefFor: (to: W) => string;\n}\n\nconst WorkspaceContextValue = createContext<WorkspaceContext | null>(null);\n\n/**\n * The nearest `WorkspaceScope`'s workspaces, or null outside one.\n *\n * @stability Beta\n */\nexport function useWorkspace<W extends Workspace = Workspace>(): WorkspaceContext<W> | null {\n return useContext(WorkspaceContextValue) as WorkspaceContext<W> | null;\n}\n\nconst STORAGE_PREFIX = \"genesis:workspace:\";\n\n/**\n * The workspace this viewer was last in on this device, for the app's front door\n * (`defaultWorkspace(workspaces, rememberedWorkspaceId(viewer))`). Null when unknown.\n *\n * @stability Beta\n */\nexport function rememberedWorkspaceId(viewer: string | null | undefined): string | null {\n if (!viewer || typeof window === \"undefined\") return null;\n try {\n return window.localStorage.getItem(STORAGE_PREFIX + viewer);\n } catch {\n return null;\n }\n}\n\nfunction remember(viewer: string, id: string) {\n try {\n window.localStorage.setItem(STORAGE_PREFIX + viewer, id);\n } catch {\n // private mode or full: the front door falls back to the first tenant.\n }\n}\n\n/** @stability Beta */\nexport interface WorkspaceScopeProps<W extends Workspace = Workspace> extends Omit<ViewerScopeProps, \"scope\" | \"roles\" | \"scopeTimeZone\"> {\n /** Every workspace this viewer has. */\n workspaces: readonly W[];\n /** The current URL's path (`useLocation().pathname`): the workspace is read from it. */\n pathname: string;\n /** Scope keys every workspace adds to its own (rarely needed). */\n scope?: ViewerScopeProps[\"scope\"];\n /** How switching keeps the viewer's place (see `workspaceHref`). */\n keep?: WorkspaceHrefOptions[\"keep\"];\n}\n\n/**\n * `ViewerScope` for an app with workspaces: use it in place of `ViewerScope`. It reads the current\n * workspace from the URL and scopes everything under it to that workspace (its `scope`, `roles` and\n * `timeZone`), so every view with `scope: [\"org_id\"]` follows the switcher with no screen code. It\n * remembers the workspace per viewer on this device, and gives `WorkspaceSwitcher` its list.\n *\n * ```tsx\n * <WorkspaceScope viewer={userId} workspaces={workspaces} pathname={location.pathname}>\n * <AppShell headerSlot={<WorkspaceSwitcher linkComponent={Link} />} …>\n * </WorkspaceScope>\n * ```\n *\n * @stability Beta\n */\nexport function WorkspaceScope<W extends Workspace>({ workspaces, pathname, scope, keep, children, ...viewerProps }: WorkspaceScopeProps<W>) {\n const current = workspaceAt(workspaces, pathname);\n const value = useMemo<WorkspaceContext<W>>(\n () => ({\n current,\n workspaces,\n hrefFor: (to) => workspaceHref(workspaces, to, pathname, keep ? { keep } : {}),\n }),\n [current, workspaces, pathname, keep],\n );\n const viewer = viewerProps.viewer;\n useEffect(() => {\n if (viewer && current) remember(viewer, current.id);\n }, [viewer, current]);\n return (\n <WorkspaceContextValue.Provider value={value as unknown as WorkspaceContext}>\n <ViewerScope\n {...viewerProps}\n scope={{ ...scope, ...current?.scope }}\n {...(current?.roles !== undefined ? { roles: current.roles } : {})}\n {...(current?.timeZone !== undefined ? { scopeTimeZone: current.timeZone } : {})}\n >\n {children}\n </ViewerScope>\n </WorkspaceContextValue.Provider>\n );\n}\n\n"]}
@@ -1,6 +1,6 @@
1
- import { useLiveInvalidation } from './chunk-ZCE3CHPX.js';
1
+ import { useLiveInvalidation } from './chunk-XVRIWP7B.js';
2
2
  import { resourceKeys } from './chunk-7PUFVNPB.js';
3
- import { useDataProvider } from './chunk-VDEW4AOS.js';
3
+ import { useDataProvider } from './chunk-PSFKIG27.js';
4
4
  import { useQuery } from '@tanstack/react-query';
5
5
 
6
6
  function useOne(resource, id, options = {}) {
@@ -35,5 +35,5 @@ function useOne(resource, id, options = {}) {
35
35
  }
36
36
 
37
37
  export { useOne };
38
- //# sourceMappingURL=chunk-4ZR7472O.js.map
39
- //# sourceMappingURL=chunk-4ZR7472O.js.map
38
+ //# sourceMappingURL=chunk-LOJGHR5O.js.map
39
+ //# sourceMappingURL=chunk-LOJGHR5O.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-one.ts"],"names":[],"mappings":";;;;;AAiCO,SAAS,MAAA,CACd,QAAA,EACA,EAAA,EACA,OAAA,GAAyB,EAAC,EACP;AACnB,EAAA,MAAM,WAAW,eAAA,EAAgB;AAEjC,EAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAK,GAAI,OAAA;AAClC,EAAA,MAAM,SAAA,GAAY,OAAA,IAAW,CAAC,CAAC,EAAA;AAG/B,EAAA,mBAAA;AAAA,IACE,QAAA;AAAA,IACA,IAAA;AAAA,IACA,aAAa,EAAA,IAAM,IAAA;AAAA,IACnB,EAAA,IAAM,IAAA,GAAO,EAAE,EAAA,KAAO,EAAC;AAAA,IACvB,YAAA,CAAa,QAAQ,CAAA,CAAE,SAAA,CAAU,EAAE,CAAA;AAAA,IACnC,CAAC,KAAA,KAAU,KAAA,CAAM,IAAA,KAAS,SAAA,IAAa,EAAE,IAAA,IAAQ,KAAA,CAAA,IAAU,KAAA,CAAM,EAAA,IAAM,QAAQ,MAAA,CAAO,KAAA,CAAM,EAAE,CAAA,KAAM,OAAO,EAAE;AAAA,GAC/G;AAEA,EAAA,OAAO,QAAA,CAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASjB,UAAU,YAAA,CAAa,QAAQ,CAAA,CAAE,MAAA,CAAO,IAAI,MAAM,CAAA;AAAA,IAClD,SAAS,YAAY;AACnB,MAAA,IAAI,EAAA,IAAM,IAAA,EAAM,MAAM,IAAI,MAAM,YAAY,CAAA;AAC5C,MAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,MAAA,CAAU,UAAU,EAAE,EAAA,EAAI,QAAQ,CAAA;AAChE,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB,CAAA;AAAA,IACA,OAAA,EAAS;AAAA,GACV,CAAA;AACH","file":"chunk-4ZR7472O.js","sourcesContent":["import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { BaseRecord, Identifier } from \"../provider/types\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface UseOneOptions {\n /** Supabase select/join syntax, e.g. \"*, author:profiles(name)\". */\n select?: string;\n /** Defaults to `!!id` — won't fetch when id is falsy. */\n enabled?: boolean;\n /**\n * Keep the record current while mounted: refetch it when the provider\n * reports a change to it (`DataProvider.subscribe`). See\n * `UseResourceOptions.live`. Off by default.\n */\n live?: boolean | LiveOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch a single record by id, powered by TanStack Query.\n *\n * Returns the full `UseQueryResult<T>` with the data unwrapped from the\n * provider's `GetOneResult` wrapper.\n */\nexport function useOne<T extends BaseRecord = BaseRecord>(\n resource: string,\n id: Identifier | undefined | null,\n options: UseOneOptions = {},\n): UseQueryResult<T> {\n const provider = useDataProvider();\n\n const { select, enabled, live } = options;\n const isEnabled = enabled ?? !!id;\n\n // Only this record's events; `changed` (events may have been missed) too.\n useLiveInvalidation(\n resource,\n live,\n isEnabled && id != null,\n id != null ? { id } : {},\n resourceKeys(resource).detailsOf(id),\n (event) => event.type === \"changed\" || !(\"id\" in event) || event.id == null || String(event.id) === String(id),\n );\n\n return useQuery<T>({\n // `select` is part of the key because it is part of the REQUEST: two pages\n // asking for the same record with different projections get different\n // rows back, and keying only on the id makes them share one cache entry.\n // Whichever mounted first wins for the whole staleTime window, and the\n // other silently renders a record missing the joined fields it asked for\n // — no error, no refetch, just absent data. `useResource`'s list key has\n // always included `select` (it keys on the whole `params` object); this\n // was the one place it did not.\n queryKey: resourceKeys(resource).detail(id, select),\n queryFn: async () => {\n if (id == null) throw new Error(\"Missing id\");\n const result = await provider.getOne<T>(resource, { id, select });\n return result.data;\n },\n enabled: isEnabled,\n });\n}\n"]}
1
+ {"version":3,"sources":["../src/hooks/use-one.ts"],"names":[],"mappings":";;;;;AAiCO,SAAS,MAAA,CACd,QAAA,EACA,EAAA,EACA,OAAA,GAAyB,EAAC,EACP;AACnB,EAAA,MAAM,WAAW,eAAA,EAAgB;AAEjC,EAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAK,GAAI,OAAA;AAClC,EAAA,MAAM,SAAA,GAAY,OAAA,IAAW,CAAC,CAAC,EAAA;AAG/B,EAAA,mBAAA;AAAA,IACE,QAAA;AAAA,IACA,IAAA;AAAA,IACA,aAAa,EAAA,IAAM,IAAA;AAAA,IACnB,EAAA,IAAM,IAAA,GAAO,EAAE,EAAA,KAAO,EAAC;AAAA,IACvB,YAAA,CAAa,QAAQ,CAAA,CAAE,SAAA,CAAU,EAAE,CAAA;AAAA,IACnC,CAAC,KAAA,KAAU,KAAA,CAAM,IAAA,KAAS,SAAA,IAAa,EAAE,IAAA,IAAQ,KAAA,CAAA,IAAU,KAAA,CAAM,EAAA,IAAM,QAAQ,MAAA,CAAO,KAAA,CAAM,EAAE,CAAA,KAAM,OAAO,EAAE;AAAA,GAC/G;AAEA,EAAA,OAAO,QAAA,CAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASjB,UAAU,YAAA,CAAa,QAAQ,CAAA,CAAE,MAAA,CAAO,IAAI,MAAM,CAAA;AAAA,IAClD,SAAS,YAAY;AACnB,MAAA,IAAI,EAAA,IAAM,IAAA,EAAM,MAAM,IAAI,MAAM,YAAY,CAAA;AAC5C,MAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,MAAA,CAAU,UAAU,EAAE,EAAA,EAAI,QAAQ,CAAA;AAChE,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB,CAAA;AAAA,IACA,OAAA,EAAS;AAAA,GACV,CAAA;AACH","file":"chunk-LOJGHR5O.js","sourcesContent":["import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { BaseRecord, Identifier } from \"../provider/types\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface UseOneOptions {\n /** Supabase select/join syntax, e.g. \"*, author:profiles(name)\". */\n select?: string;\n /** Defaults to `!!id` — won't fetch when id is falsy. */\n enabled?: boolean;\n /**\n * Keep the record current while mounted: refetch it when the provider\n * reports a change to it (`DataProvider.subscribe`). See\n * `UseResourceOptions.live`. Off by default.\n */\n live?: boolean | LiveOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch a single record by id, powered by TanStack Query.\n *\n * Returns the full `UseQueryResult<T>` with the data unwrapped from the\n * provider's `GetOneResult` wrapper.\n */\nexport function useOne<T extends BaseRecord = BaseRecord>(\n resource: string,\n id: Identifier | undefined | null,\n options: UseOneOptions = {},\n): UseQueryResult<T> {\n const provider = useDataProvider();\n\n const { select, enabled, live } = options;\n const isEnabled = enabled ?? !!id;\n\n // Only this record's events; `changed` (events may have been missed) too.\n useLiveInvalidation(\n resource,\n live,\n isEnabled && id != null,\n id != null ? { id } : {},\n resourceKeys(resource).detailsOf(id),\n (event) => event.type === \"changed\" || !(\"id\" in event) || event.id == null || String(event.id) === String(id),\n );\n\n return useQuery<T>({\n // `select` is part of the key because it is part of the REQUEST: two pages\n // asking for the same record with different projections get different\n // rows back, and keying only on the id makes them share one cache entry.\n // Whichever mounted first wins for the whole staleTime window, and the\n // other silently renders a record missing the joined fields it asked for\n // — no error, no refetch, just absent data. `useResource`'s list key has\n // always included `select` (it keys on the whole `params` object); this\n // was the one place it did not.\n queryKey: resourceKeys(resource).detail(id, select),\n queryFn: async () => {\n if (id == null) throw new Error(\"Missing id\");\n const result = await provider.getOne<T>(resource, { id, select });\n return result.data;\n },\n enabled: isEnabled,\n });\n}\n"]}
@@ -1,8 +1,9 @@
1
- import { useLiveInvalidation } from './chunk-ZCE3CHPX.js';
2
- import { invalidateResource, executeWrite, cachedRecord } from './chunk-6WV6ST67.js';
3
- import { resourceKeys } from './chunk-7PUFVNPB.js';
4
- import { useDataProvider } from './chunk-VDEW4AOS.js';
5
1
  import { relatedKeys } from './chunk-7NUL32W7.js';
2
+ import { useLiveInvalidation } from './chunk-XVRIWP7B.js';
3
+ import { invalidateResource, executeWrite, cachedRecord } from './chunk-YNXLPOAB.js';
4
+ import { resourceKeys } from './chunk-7PUFVNPB.js';
5
+ import { useDataProvider } from './chunk-PSFKIG27.js';
6
+ import { isDataWriteError } from './chunk-LG6TUBVM.js';
6
7
  import { useState, useCallback, useMemo } from 'react';
7
8
  import { useQueryClient, useQuery, keepPreviousData, useMutation } from '@tanstack/react-query';
8
9
 
@@ -103,6 +104,7 @@ function useResource(resource, options = {}) {
103
104
  );
104
105
  const defaultOnError = useCallback(
105
106
  (error) => {
107
+ if (isDataWriteError(error) && error.outcome === "conflict" && error.current) return;
106
108
  console.error(`[useResource] ${resource} mutation failed:`, error.message);
107
109
  },
108
110
  [resource]
@@ -137,18 +139,20 @@ function useResource(resource, options = {}) {
137
139
  onError: reportError
138
140
  });
139
141
  const updateMutation = useMutation({
140
- mutationFn: async ({ id, data }) => {
142
+ mutationFn: async ({ id, data, options: options2 }) => {
141
143
  const before = cachedRecord(queryClient, resource, id);
142
144
  const outcome = await executeWrite({
143
145
  ...modeArgs,
144
146
  kind: "update",
145
147
  id,
146
148
  data,
149
+ ...options2?.expectedVersion !== void 0 ? { expectedVersion: options2.expectedVersion } : {},
147
150
  send: async (ctx) => {
148
151
  const result = await provider.update(resource, {
149
152
  id,
150
153
  data: ctx.data ?? data,
151
- ...ctx.keepalive ? { keepalive: true } : {}
154
+ ...ctx.keepalive ? { keepalive: true } : {},
155
+ ...ctx.expectedVersion !== void 0 ? { expectedVersion: ctx.expectedVersion } : {}
152
156
  });
153
157
  return { record: result.data, audit: result.audit };
154
158
  },
@@ -167,8 +171,12 @@ function useResource(resource, options = {}) {
167
171
  ...modeArgs,
168
172
  kind: "delete",
169
173
  id,
170
- send: async ({ keepalive }) => {
171
- const result = await provider.deleteOne(resource, { id, ...keepalive ? { keepalive } : {} });
174
+ send: async ({ keepalive, expectedVersion }) => {
175
+ const result = await provider.deleteOne(resource, {
176
+ id,
177
+ ...keepalive ? { keepalive } : {},
178
+ ...expectedVersion !== void 0 ? { expectedVersion } : {}
179
+ });
172
180
  return { record: void 0, audit: result?.audit };
173
181
  },
174
182
  committed: () => {
@@ -184,7 +192,7 @@ function useResource(resource, options = {}) {
184
192
  [createMutation]
185
193
  );
186
194
  const update = useCallback(
187
- (id, data) => updateMutation.mutateAsync({ id, data }),
195
+ (id, data, options2) => updateMutation.mutateAsync(options2 ? { id, data, options: options2 } : { id, data }),
188
196
  [updateMutation]
189
197
  );
190
198
  const remove = useCallback(
@@ -211,5 +219,5 @@ function useResource(resource, options = {}) {
211
219
  }
212
220
 
213
221
  export { useResource };
214
- //# sourceMappingURL=chunk-ON2V4RXX.js.map
215
- //# sourceMappingURL=chunk-ON2V4RXX.js.map
222
+ //# sourceMappingURL=chunk-OC4OGB2K.js.map
223
+ //# sourceMappingURL=chunk-OC4OGB2K.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-resource.ts"],"names":["keepPreviousData","keepPreviousPlaceholder","options"],"mappings":";;;;;;;;;AA0JA,SAAS,gBAAgB,OAAA,EAAwD;AAC/E,EAAA,IAAI,CAAC,SAAS,OAAO,MAAA;AACrB,EAAA,OAAO,IAAA,CAAK,SAAA;AAAA,IACV,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM;AACjB,MAAA,MAAM,SAAkC,EAAC;AACzC,MAAA,KAAA,MAAW,OAAO,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,CAAE,MAAK,EAAG;AACvC,QAAA,MAAA,CAAO,GAAG,CAAA,GAAK,CAAA,CAAyC,GAAG,CAAA;AAAA,MAC7D;AACA,MAAA,OAAO,MAAA;AAAA,IACT,CAAC;AAAA,GACH;AACF;AAMO,SAAS,WAAA,CACd,QAAA,EACA,OAAA,GAAiC,EAAC,EACZ;AACtB,EAAA,MAAM;AAAA,IACJ,WAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA,GAAiB,EAAA;AAAA,IACjB,WAAA,GAAc,CAAA;AAAA,IACd,aAAA,GAAgB,EAAA;AAAA,IAChB,MAAA;AAAA,IACA,YAAA,EAAc,kBAAA;AAAA,IACd,OAAA,GAAU,IAAA;AAAA,IACV,WAAA;AAAA,sBACAA,kBAAA,GAAmB,KAAA;AAAA,IACnB,IAAA;AAAA,IACA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A;AAAA,IACA,UAAA;AAAA,IACA,SAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,UAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-OC4OGB2K.js","sourcesContent":["import { useState, useCallback, useMemo } from \"react\";\nimport {\n keepPreviousData as keepPreviousPlaceholder,\n useQuery,\n useMutation,\n useQueryClient,\n type UseQueryResult,\n type UseMutationResult,\n} from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type {\n BaseRecord,\n Identifier,\n SortParam,\n FilterParam,\n ListParams,\n ListResult,\n InvalidationKey,\n WriteEvent,\n} from \"../provider/types\";\nimport { relatedKeys } from \"./related-keys\";\nimport {\n cachedRecord,\n executeWrite,\n invalidateResource,\n type MutationModeOptions,\n} from \"./mutation-mode\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\nimport { isDataWriteError } from \"../schema/write-outcome\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface UseResourceOptions<T> extends MutationModeOptions {\n defaultSort?: SortParam;\n /**\n * Re-synced whenever its value changes (deep-equal, order-independent),\n * not just its identity — safe to pass a scope/audience-derived array that\n * changes across renders. This only covers CHANGES on an already-mounted\n * hook, though: if this starts `undefined` while the real value resolves\n * asynchronously, gate `enabled` on that same readiness signal too — the\n * hook cannot tell \"no defaultFilters intended\" apart from \"not resolved\n * yet,\" so an ungated hook's very first fetch can still run unscoped.\n */\n defaultFilters?: FilterParam[];\n defaultPerPage?: number;\n /** The page to start on (from 1), e.g. restored from the URL. Default 1. */\n defaultPage?: number;\n /** The search to start with, e.g. restored from the URL. Default \"\". */\n defaultSearch?: string;\n /** Supabase select/join syntax, e.g. \"*, author:profiles(name)\". */\n select?: string;\n /** Fields to search across when setSearch is called. Required for server-side search. */\n searchFields?: string[];\n /** Disable auto-fetching. */\n enabled?: boolean;\n /**\n * Other query keys to invalidate after a create, update or delete, on top\n * of `[resource]` and the provider's own `invalidates` (e.g. `[[\"me\"]]`\n * when a write changes the signed-in user's roles).\n */\n invalidates?: InvalidationKey[];\n /**\n * While the next page / sort / search is loading, keep returning the\n * previous result (`list.isPlaceholderData` is true meanwhile) instead of\n * dropping to `undefined`. A paged list then stays on screen between pages\n * rather than flashing a skeleton. Default false.\n */\n keepPreviousData?: boolean;\n /**\n * Keep the list current while mounted: subscribe to the provider's change\n * events (`DataProvider.subscribe`) and refetch this resource's cached\n * reads (lists and records) when it reports one, once per burst of\n * events. Events are hints: rows always come from the provider's normal\n * read. Pending optimistic and undoable writes stay applied over the\n * refetch. Needs a provider that serves `subscribe` for the resource\n * (`capabilities(resource).realtime`); otherwise it does nothing. Off by\n * default.\n */\n live?: boolean | LiveOptions;\n /**\n * After the write commits, with the provider's row. In `optimistic` and\n * `undoable` modes that is after `create` / `update` / `remove` have\n * already resolved.\n */\n onCreateSuccess?: (data: T) => void;\n onUpdateSuccess?: (data: T) => void;\n onDeleteSuccess?: () => void;\n /**\n * A write failed. In `optimistic` and `undoable` modes this is the only\n * place a failure is reported (the cache has already been put back), so\n * show it to the user here.\n */\n onError?: (error: Error) => void;\n}\n\n/** What `update` can take beside the change. */\nexport interface UpdateOptions {\n /**\n * Check the write against this version instead of the cached row's: \"keep mine\" after a\n * conflict, at the version the conflict reported (`WriteConflict.currentVersion`). A version\n * already chained for the row wins over it: a write sent while an earlier write of the same row\n * is still in flight is checked against the version that one commits (as\n * `ExecuteWriteArgs.expectedVersion`). The write\n * still goes through the resource's write path (queued behind any other write of the row, its\n * committed version recorded), so a move made right after it is checked against it.\n */\n expectedVersion?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Return type\n// ---------------------------------------------------------------------------\n\nexport interface UseResourceReturn<T> {\n /** TanStack Query result for the list query. */\n list: UseQueryResult<ListResult<T>>;\n /** Current list params (pagination, sort, filters, search). */\n params: ListParams;\n setSort: (sort: SortParam | undefined) => void;\n setFilters: (filters: FilterParam[]) => void;\n setPage: (page: number) => void;\n setPerPage: (perPage: number) => void;\n setSearch: (query: string) => void;\n /**\n * Create a new record. Returns the created item. In `optimistic` and\n * `undoable` modes it resolves at once with the values given (no `id` yet;\n * `onCreateSuccess` gets the stored row).\n */\n create: (data: Partial<T>) => Promise<T>;\n /**\n * Update an existing record by id. Returns the updated item. In\n * `optimistic` and `undoable` modes it resolves at once with the cached\n * row merged with `data`.\n */\n update: (id: Identifier, data: Partial<T>, options?: UpdateOptions) => Promise<T>;\n /** Delete a record by id. Resolves at once in `optimistic` / `undoable` modes. */\n remove: (id: Identifier) => Promise<void>;\n /** True when any mutation is in-flight. */\n isMutating: boolean;\n createMutation: UseMutationResult<T, Error, Partial<T>>;\n updateMutation: UseMutationResult<T, Error, { id: Identifier; data: Partial<T>; options?: UpdateOptions }>;\n deleteMutation: UseMutationResult<void, Error, Identifier>;\n}\n\n// ---------------------------------------------------------------------------\n// Filter identity — a deep-equality key independent of object-key order, so\n// a caller that rebuilds the same logical filters via a differently-ordered\n// spread (e.g. `{...base, operator: \"eq\"}` vs `{operator: \"eq\", ...base}`)\n// doesn't trip a spurious resync + pagination reset on an unrelated rerender.\n// ---------------------------------------------------------------------------\n\nfunction stableFilterKey(filters: FilterParam[] | undefined): string | undefined {\n if (!filters) return undefined;\n return JSON.stringify(\n filters.map((f) => {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(f).sort()) {\n sorted[key] = (f as unknown as Record<string, unknown>)[key];\n }\n return sorted;\n }),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useResource<T extends BaseRecord = BaseRecord>(\n resource: string,\n options: UseResourceOptions<T> = {},\n): UseResourceReturn<T> {\n const {\n defaultSort,\n defaultFilters,\n defaultPerPage = 25,\n defaultPage = 1,\n defaultSearch = \"\",\n select,\n searchFields: searchFieldsOption,\n enabled = true,\n invalidates,\n keepPreviousData = false,\n live,\n onCreateSuccess,\n onUpdateSuccess,\n onDeleteSuccess,\n onError,\n mutationMode = \"pessimistic\",\n undoDelayMs,\n onUndoable,\n } = options;\n\n const provider = useDataProvider();\n const queryClient = useQueryClient();\n\n // -------------------------------------------------------------------------\n // State\n // -------------------------------------------------------------------------\n\n const [sort, setSortRaw] = useState<SortParam | undefined>(defaultSort);\n const [filters, setFiltersRaw] = useState<FilterParam[]>(defaultFilters ?? []);\n const [page, setPage] = useState(Math.max(1, Math.floor(defaultPage)));\n const [perPage, setPerPageRaw] = useState(defaultPerPage);\n const [searchQuery, setSearchQuery] = useState(defaultSearch);\n\n // `defaultFilters` often resolves asynchronously — a caller's scope/audience\n // (team, project, ...) can still be loading on first render, so the array\n // it passes in changes value (not just identity) after mount, and may later\n // clear back to undefined (e.g. the scope itself is cleared). Re-syncing\n // here, during render rather than in an effect, means `filters` is already\n // correct by the time `params`/`list` below compute for this pass — no\n // stray unscoped fetch on the frame before an effect would have caught up.\n //\n // This only closes the gap for `defaultFilters` CHANGING across renders on\n // an already-mounted, already-enabled hook (e.g. a scope switch). It cannot\n // help the very first render: `filters` still seeds from whatever\n // `defaultFilters` is on mount, and `undefined` here is genuinely ambiguous\n // between \"this caller never uses defaultFilters\" (in which case forcing a\n // fetch to wait would break it forever) and \"the real value hasn't resolved\n // yet.\" A caller in the second case MUST also gate `enabled` on that same\n // readiness signal for its very first fetch to be correctly scoped — this\n // hook has no way to tell the two cases apart on its own.\n const defaultFiltersKey = stableFilterKey(defaultFilters);\n const [syncedFiltersKey, setSyncedFiltersKey] = useState(defaultFiltersKey);\n if (defaultFiltersKey !== syncedFiltersKey) {\n setSyncedFiltersKey(defaultFiltersKey);\n setFiltersRaw(defaultFilters ?? []);\n setPage(1);\n }\n\n const setSort = useCallback((s: SortParam | undefined) => {\n setSortRaw(s);\n setPage(1);\n }, []);\n\n const setFilters = useCallback((f: FilterParam[]) => {\n setFiltersRaw(f);\n setPage(1);\n }, []);\n\n const setPerPage = useCallback((value: number) => {\n setPerPageRaw(value);\n setPage(1);\n }, []);\n\n const setSearch = useCallback((query: string) => {\n setSearchQuery(query);\n setPage(1);\n }, []);\n\n // -------------------------------------------------------------------------\n // Params\n // -------------------------------------------------------------------------\n\n const params = useMemo<ListParams>(() => {\n const p: ListParams = {\n pagination: { page, perPage },\n sort,\n filters: filters.length > 0 ? filters : undefined,\n select,\n };\n if (searchQuery && searchFieldsOption && searchFieldsOption.length > 0) {\n p.search = { query: searchQuery, fields: searchFieldsOption };\n }\n return p;\n }, [page, perPage, sort, filters, select, searchQuery, searchFieldsOption]);\n\n // -------------------------------------------------------------------------\n // List query\n // -------------------------------------------------------------------------\n\n const listQueryKey = useMemo(\n () => resourceKeys(resource).list(params),\n [resource, params],\n );\n\n const list = useQuery<ListResult<T>>({\n queryKey: listQueryKey,\n queryFn: () => provider.getList<T>(resource, params),\n enabled,\n placeholderData: keepPreviousData ? keepPreviousPlaceholder : undefined,\n });\n\n // Every cached read of the resource: its lists, and the records a peek or\n // detail page shows from it.\n useLiveInvalidation(resource, live, enabled, { filters: params.filters }, [resource]);\n\n // -------------------------------------------------------------------------\n // Mutations\n // -------------------------------------------------------------------------\n\n const invalidateAfter = useCallback(\n (event: WriteEvent) => {\n // Pending optimistic/undoable patches are re-applied to the refetch.\n void invalidateResource(queryClient, resource);\n for (const queryKey of relatedKeys(provider, event, invalidates)) {\n void queryClient.invalidateQueries({ queryKey: [...queryKey] });\n }\n },\n [queryClient, resource, provider, invalidates],\n );\n\n const defaultOnError = useCallback(\n (error: Error) => {\n // A conflict is an outcome the caller shows (a conflict sheet), not a failure to log.\n if (isDataWriteError(error) && error.outcome === \"conflict\" && error.current) return;\n console.error(`[useResource] ${resource} mutation failed:`, error.message);\n },\n [resource],\n );\n const reportError = onError ?? defaultOnError;\n\n const modeArgs = {\n queryClient,\n provider,\n resource,\n mode: mutationMode,\n undoDelayMs,\n onUndoable,\n failedLater: reportError,\n };\n\n const createMutation = useMutation<T, Error, Partial<T>>({\n mutationFn: async (data) => {\n const outcome = await executeWrite<T>({\n ...modeArgs,\n kind: \"create\",\n data: data as Record<string, unknown>,\n send: async ({ keepalive }) => {\n const result = await provider.create<T>(resource, { data, ...(keepalive ? { keepalive } : {}) });\n return { record: result.data, audit: result.audit };\n },\n committed: (record) => {\n invalidateAfter({ resource, kind: \"create\", id: record.id, record });\n onCreateSuccess?.(record);\n },\n });\n return outcome.status === \"committed\" ? outcome.record : (data as T);\n },\n onError: reportError,\n });\n\n const updateMutation = useMutation<\n T,\n Error,\n { id: Identifier; data: Partial<T>; options?: UpdateOptions }\n >({\n mutationFn: async ({ id, data, options }) => {\n const before = cachedRecord(queryClient, resource, id);\n const outcome = await executeWrite<T>({\n ...modeArgs,\n kind: \"update\",\n id,\n data: data as Record<string, unknown>,\n ...(options?.expectedVersion !== undefined ? { expectedVersion: options.expectedVersion } : {}),\n send: async (ctx) => {\n const result = await provider.update<T>(resource, {\n id,\n data: (ctx.data ?? data) as Partial<T>,\n ...(ctx.keepalive ? { keepalive: true } : {}),\n ...(ctx.expectedVersion !== undefined ? { expectedVersion: ctx.expectedVersion } : {}),\n });\n return { record: result.data, audit: result.audit };\n },\n committed: (record) => {\n invalidateAfter({ resource, kind: \"update\", id, record });\n onUpdateSuccess?.(record);\n },\n });\n return outcome.status === \"committed\"\n ? outcome.record\n : ({ ...(before ?? {}), ...data, id: before?.id ?? id } as T);\n },\n onError: reportError,\n });\n\n const deleteMutation = useMutation<void, Error, Identifier>({\n mutationFn: async (id) => {\n await executeWrite<void>({\n ...modeArgs,\n kind: \"delete\",\n id,\n send: async ({ keepalive, expectedVersion }) => {\n const result = await provider.deleteOne(resource, {\n id,\n ...(keepalive ? { keepalive } : {}),\n ...(expectedVersion !== undefined ? { expectedVersion } : {}),\n });\n return { record: undefined, audit: result?.audit };\n },\n committed: () => {\n invalidateAfter({ resource, kind: \"delete\", id });\n onDeleteSuccess?.();\n },\n });\n },\n onError: reportError,\n });\n\n // -------------------------------------------------------------------------\n // Convenience wrappers\n // -------------------------------------------------------------------------\n\n const create = useCallback(\n (data: Partial<T>) => createMutation.mutateAsync(data),\n [createMutation],\n );\n\n const update = useCallback(\n (id: Identifier, data: Partial<T>, options?: UpdateOptions) =>\n updateMutation.mutateAsync(options ? { id, data, options } : { id, data }),\n [updateMutation],\n );\n\n const remove = useCallback(\n (id: Identifier) => deleteMutation.mutateAsync(id),\n [deleteMutation],\n );\n\n const isMutating =\n createMutation.isPending ||\n updateMutation.isPending ||\n deleteMutation.isPending;\n\n return {\n list,\n params,\n setSort,\n setFilters,\n setPage,\n setPerPage,\n setSearch,\n create,\n update,\n remove,\n isMutating,\n createMutation,\n updateMutation,\n deleteMutation,\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { useLiveInvalidation } from './chunk-ZCE3CHPX.js';
1
+ import { useLiveInvalidation } from './chunk-XVRIWP7B.js';
2
2
  import { resourceKeys } from './chunk-7PUFVNPB.js';
3
- import { useDataProvider } from './chunk-VDEW4AOS.js';
3
+ import { useDataProvider } from './chunk-PSFKIG27.js';
4
4
  import { useState, useCallback, useMemo, useRef } from 'react';
5
5
  import { useInfiniteQuery, keepPreviousData } from '@tanstack/react-query';
6
6
 
@@ -145,5 +145,5 @@ function useInfiniteResource(resource, options = {}) {
145
145
  }
146
146
 
147
147
  export { useInfiniteResource };
148
- //# sourceMappingURL=chunk-HQAVDVIH.js.map
149
- //# sourceMappingURL=chunk-HQAVDVIH.js.map
148
+ //# sourceMappingURL=chunk-POMTRNAL.js.map
149
+ //# sourceMappingURL=chunk-POMTRNAL.js.map