@marktiderman/genesis-core 1.12.0 → 1.14.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 (92) hide show
  1. package/README.md +77 -0
  2. package/dist/chunk-3B4IFDMK.js +117 -0
  3. package/dist/chunk-3B4IFDMK.js.map +1 -0
  4. package/dist/{chunk-S2ZXUNXB.js → chunk-3LZAZ5KB.js} +3 -3
  5. package/dist/{chunk-S2ZXUNXB.js.map → chunk-3LZAZ5KB.js.map} +1 -1
  6. package/dist/chunk-7FVTGKTX.js +8 -0
  7. package/dist/chunk-7FVTGKTX.js.map +1 -0
  8. package/dist/{chunk-NMFABW4Y.js → chunk-7YHGNPPO.js} +5 -5
  9. package/dist/{chunk-NMFABW4Y.js.map → chunk-7YHGNPPO.js.map} +1 -1
  10. package/dist/chunk-AUVKRXRC.js +81 -0
  11. package/dist/chunk-AUVKRXRC.js.map +1 -0
  12. package/dist/{chunk-TOU2CMDH.js → chunk-K7K6NY3C.js} +168 -168
  13. package/dist/chunk-K7K6NY3C.js.map +1 -0
  14. package/dist/chunk-LFWSTJWI.js +108 -0
  15. package/dist/chunk-LFWSTJWI.js.map +1 -0
  16. package/dist/{chunk-RCAP3Q4T.js → chunk-OYIUIW7C.js} +3 -2
  17. package/dist/chunk-OYIUIW7C.js.map +1 -0
  18. package/dist/chunk-OZYF55E3.js +6 -0
  19. package/dist/chunk-OZYF55E3.js.map +1 -0
  20. package/dist/chunk-PA6WJE5E.js +115 -0
  21. package/dist/chunk-PA6WJE5E.js.map +1 -0
  22. package/dist/chunk-PP3XFFQM.js +85 -0
  23. package/dist/chunk-PP3XFFQM.js.map +1 -0
  24. package/dist/{chunk-BGTXN2E6.js → chunk-RF6YVWHX.js} +4 -4
  25. package/dist/{chunk-BGTXN2E6.js.map → chunk-RF6YVWHX.js.map} +1 -1
  26. package/dist/{chunk-NZPJI7FC.js → chunk-UGGMJUFQ.js} +45 -13
  27. package/dist/chunk-UGGMJUFQ.js.map +1 -0
  28. package/dist/{chunk-KXVHDK3Q.js → chunk-UV3ROHQA.js} +27 -5
  29. package/dist/chunk-UV3ROHQA.js.map +1 -0
  30. package/dist/chunk-YDDPFSQ6.js +35 -0
  31. package/dist/chunk-YDDPFSQ6.js.map +1 -0
  32. package/dist/{chunk-OSPLIKSH.js → chunk-YFTGLQDQ.js} +18 -8
  33. package/dist/chunk-YFTGLQDQ.js.map +1 -0
  34. package/dist/chunk-ZIMQUFXD.js +154 -0
  35. package/dist/chunk-ZIMQUFXD.js.map +1 -0
  36. package/dist/csv.d.ts +41 -0
  37. package/dist/csv.js +77 -0
  38. package/dist/csv.js.map +1 -0
  39. package/dist/dates.js +1 -115
  40. package/dist/dates.js.map +1 -1
  41. package/dist/errors.d.ts +69 -0
  42. package/dist/errors.js +7 -0
  43. package/dist/errors.js.map +1 -0
  44. package/dist/hooks/index.d.ts +7 -43
  45. package/dist/hooks/index.js +14 -11
  46. package/dist/hooks/live-cache.d.ts +15 -0
  47. package/dist/hooks/live-cache.js +3 -0
  48. package/dist/hooks/live-cache.js.map +1 -0
  49. package/dist/hooks/mutation-mode.d.ts +2 -2
  50. package/dist/hooks/mutation-mode.js +2 -2
  51. package/dist/hooks/related-keys.d.ts +2 -2
  52. package/dist/hooks/use-capabilities.d.ts +1 -1
  53. package/dist/hooks/use-infinite-resource.d.ts +18 -2
  54. package/dist/hooks/use-infinite-resource.js +4 -3
  55. package/dist/hooks/use-live.d.ts +15 -3
  56. package/dist/hooks/use-live.js +2 -1
  57. package/dist/hooks/use-one.d.ts +2 -2
  58. package/dist/hooks/use-one.js +4 -3
  59. package/dist/hooks/use-resource-form.d.ts +9 -2
  60. package/dist/hooks/use-resource-form.js +6 -5
  61. package/dist/hooks/use-resource.d.ts +2 -2
  62. package/dist/hooks/use-resource.js +5 -4
  63. package/dist/hooks/use-write.d.ts +2 -2
  64. package/dist/index.d.ts +14 -6
  65. package/dist/index.js +21 -14
  66. package/dist/provider/index.d.ts +11 -6
  67. package/dist/provider/index.js +3 -2
  68. package/dist/resource/index.d.ts +39 -0
  69. package/dist/resource/index.js +3 -0
  70. package/dist/resource/index.js.map +1 -0
  71. package/dist/resource-view/index.d.ts +468 -0
  72. package/dist/resource-view/index.js +542 -0
  73. package/dist/resource-view/index.js.map +1 -0
  74. package/dist/schema/index.d.ts +4 -4
  75. package/dist/schema/index.js +1 -0
  76. package/dist/status-BXRokZD9.d.ts +50 -0
  77. package/dist/testing/index.d.ts +3 -3
  78. package/dist/{types-B9DDfvWa.d.ts → types-CXhqXPN1.d.ts} +21 -4
  79. package/dist/{types-C7FJtFXV.d.ts → types-o8j7g6O6.d.ts} +38 -1
  80. package/dist/urls.d.ts +18 -0
  81. package/dist/urls.js +3 -0
  82. package/dist/urls.js.map +1 -0
  83. package/dist/viewer-scope-77MqxvmZ.d.ts +125 -0
  84. package/dist/{write-outcome-B2fE29yZ.d.ts → write-outcome-CFnpciUI.d.ts} +1 -1
  85. package/package.json +21 -1
  86. package/dist/chunk-5ORRAXIV.js +0 -30
  87. package/dist/chunk-5ORRAXIV.js.map +0 -1
  88. package/dist/chunk-KXVHDK3Q.js.map +0 -1
  89. package/dist/chunk-NZPJI7FC.js.map +0 -1
  90. package/dist/chunk-OSPLIKSH.js.map +0 -1
  91. package/dist/chunk-RCAP3Q4T.js.map +0 -1
  92. package/dist/chunk-TOU2CMDH.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schema/types.ts"],"names":[],"mappings":";AA+IO,SAAS,cAAA,GAAsC;AACpD,EAAA,OAAO,CACL,QAAA,KACiC,QAAA;AACrC","file":"chunk-7FVTGKTX.js","sourcesContent":["// ---------------------------------------------------------------------------\n// The one schema model (docs/DATA-STUDIO.md decisions 11, 12, 13, 30)\n//\n// Promoted from @marktiderman/genesis-switchboard, which keeps deprecated\n// aliases for one deprecation window. Everything here is a type or a pure\n// helper with no React, no runtime dependency and no I/O, so a server, an\n// edge function or the switchboard can import it without pulling in the\n// React half of this package.\n// ---------------------------------------------------------------------------\n\nimport type { FieldType as WidgetHint } from \"../form-types\";\n\nexport type { WidgetHint };\n\n/**\n * Portable storage type of a field — what kind of value the store holds,\n * independent of how a UI should edit it. The exact native type, when the\n * store reports one, is on {@link FieldSchema.dbType}.\n *\n * Exactly the six types the switchboard shipped as `FieldType`, so existing\n * exhaustive maps over it keep compiling. Finer distinctions (date versus\n * timestamp, enum, uuid) live in `dbType` and `widget`, not here.\n */\nexport type StorageType = \"string\" | \"number\" | \"boolean\" | \"datetime\" | \"json\" | \"relation\";\n\n/** A canonical, provider-agnostic row. Keys are field names from the schema. */\nexport type DataRow = Record<string, unknown>;\n\n/**\n * What the CURRENT user may do with one field. Reported by a provider's\n * `describe()`; never inferred in the browser.\n *\n * `read: false` means the value is never sent to this user, so the column\n * must not render at all (an answer key, a payout amount). `update: false`\n * with `read: true` renders the column read-only.\n */\nexport interface FieldPermissions {\n readonly read: boolean;\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n}\n\n/** A foreign-key style link from this field to another resource's field. */\nexport interface FieldReference {\n readonly resource: string;\n readonly field: string;\n}\n\nexport interface FieldSchema {\n /** Canonical field name in the resource's shape (provider-agnostic). */\n readonly name: string;\n /** Portable storage type. */\n readonly type: StorageType;\n /** True when a row may omit this field. */\n readonly optional?: boolean;\n /**\n * True when the field holds an ORDERED LIST of `type` values (e.g. a\n * multi-relation like `deps`/`serves`). Promotion emits a Postgres ARRAY\n * column (`<base>[]`) instead of a lossy scalar, so the cardinality survives\n * L1→L3 (CMT-1742-014).\n */\n readonly array?: boolean;\n /** Human note (surfaces in describe()/drift reports). */\n readonly description?: string;\n /** Human label, e.g. \"Date of birth\". Absent means a UI derives one from `name`. */\n readonly label?: string;\n /** The store's exact type, e.g. `timestamp with time zone` or `public.status`. */\n readonly dbType?: string;\n /** Which control fits this field. A hint: a UI may still choose another. */\n readonly widget?: WidgetHint;\n /** True when the store accepts null for this field. */\n readonly nullable?: boolean;\n /** True when the store fills the field itself on insert. */\n readonly hasDefault?: boolean;\n /** True when the store computes the field; it is never written. */\n readonly generated?: boolean;\n /** Allowed values, for enum-like fields. */\n readonly enumValues?: readonly string[];\n /** The resource and field this one points at, when it is a link. */\n readonly references?: FieldReference;\n /** The current user's rights on this field, when a provider reports them. */\n readonly permissions?: FieldPermissions;\n /**\n * The server owns this field (a status it derives, a total, an audit stamp): clients never write\n * it, so a UI shows it read-only. Declared once (`@genesis {\"readonly\": true}`); the database's\n * own guards still enforce it.\n */\n readonly readOnly?: boolean;\n /**\n * The value is sensitive (a note for staff, a health detail): a UI leaves it out of lists, exports\n * and previews unless a screen asks for it. Hiding it from a user is the database's job.\n */\n readonly sensitive?: boolean;\n}\n\n/**\n * One declaration of a resource: its fields and its identity.\n *\n * `key` names the identity field, or several for a composite key (a junction\n * table keyed on `(team_id, user_id)`). Use {@link keyFields} to read it as\n * a list without caring which form it took.\n */\nexport interface ResourceContract<Row extends DataRow = DataRow> {\n /** Resource name the app addresses, e.g. \"tickets\" or \"public.tickets\". */\n readonly name: string;\n /**\n * Identity field name, or names for a composite key, in key order.\n *\n * Typed `string` (not `keyof Row & string`) on purpose: `keyof Row` is a\n * dependent type that TypeScript checks contravariantly, which would make\n * `ResourceContract<WorkCycleRow>` non-assignable to the erased\n * `ResourceContract<DataRow>` that generic consumers accept. The key is\n * validated against the field schema at runtime instead.\n */\n readonly key: string | readonly string[];\n readonly fields: readonly FieldSchema[];\n /** Optional doc string. */\n readonly description?: string;\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** What one row is called in sentences (\"brand\"), and several (\"brands\") when not `noun` + \"s\". */\n readonly noun?: string;\n readonly nounPlural?: string;\n /** Phantom marker so `Row` is inferable from a contract. */\n readonly __row?: Row;\n}\n\n/** The row type a contract describes (its phantom `__row`), or `DataRow` when it carries none. */\nexport type RowOf<C> = C extends { readonly __row?: infer R } ? (unknown extends R ? DataRow : NonNullable<R>) : DataRow;\n\n/**\n * Declares a resource contract for a row type, keeping the literal contract (field names, key,\n * labelField) and attaching the row type so views can read it with `RowOf`. `labelField` must be\n * one of the row's fields.\n *\n * ```ts\n * export const publicBrands = defineResource<PublicBrandsRow>()({ name: \"public.brands\", key: \"id\", fields: [...] });\n * type Row = RowOf<typeof publicBrands>; // PublicBrandsRow\n * ```\n */\nexport function defineResource<Row extends DataRow>() {\n return <const C extends ResourceContract<Row> & { readonly labelField?: keyof Row & string }>(\n contract: C,\n ): C & { readonly __row?: Row } => contract;\n}\n\n/** What the current user may do with a whole resource. */\nexport interface ResourceAccess {\n readonly read: boolean;\n /** True when at least one field can be updated on rows this user can see. */\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n /** True when this user may add rows. Absent means the provider doesn't say. */\n readonly create?: boolean;\n /** True when this user may delete rows they can see. */\n readonly delete?: boolean;\n /** True when this user may read a row's audit history. */\n readonly history?: boolean;\n /** True when this user may read and add comments on rows they can see. */\n readonly comment?: boolean;\n /** Why `create`, `delete`, `history` or `comment` is false, in one human sentence each. */\n readonly reasons?: {\n readonly create?: string;\n readonly delete?: string;\n readonly history?: string;\n readonly comment?: string;\n };\n}\n\n/**\n * How another resource relates to this one, from the store's foreign keys.\n *\n * - `one`: a field on THIS resource points at one row of `resource`.\n * - `many`: rows of `resource` point at this row through their `field`.\n * - `through`: many rows of `resource`, linked by the junction resource in\n * `through` (a table whose key is two foreign keys).\n */\nexport interface ResourceRelation {\n readonly kind: \"one\" | \"many\" | \"through\";\n /** The related resource. */\n readonly resource: string;\n /**\n * `one`: the field on this resource. `many`: the field on `resource` that\n * holds this row's key. `through`: the junction's field holding this row's key.\n */\n readonly field: string;\n /** For `through`: the junction resource, and its field pointing at `resource`. */\n readonly through?: { readonly resource: string; readonly otherField: string };\n /** True when at most one related row can exist (a unique foreign key). */\n readonly unique?: boolean;\n}\n\n/**\n * The column a provider checks on every update so an edit never silently\n * overwrites someone else's. Only reported when the store itself advances it\n * on every successful update (a trigger such as `moddatetime`), because a\n * column nothing advances detects nothing.\n */\nexport interface VersionField {\n /**\n * The field holding the version. A provider with versioned writes returns\n * each row with its exact version token in this field, as a string, and\n * `expectedVersion` echoes `String(row[field])` back unchanged.\n */\n readonly field: string;\n /**\n * `row`: no column tracks versions, so the token is a fingerprint of the\n * row's values, and `field` is a name the provider adds to each record\n * (it is not one of the resource's fields).\n */\n readonly kind: \"integer\" | \"timestamp\" | \"row\";\n}\n\n/**\n * A resource as `describe()` reports it for the CURRENT user: the contract,\n * plus what this user may do. Fields the user may not read are left out\n * entirely, not marked hidden.\n */\nexport interface ResourceSchema<Row extends DataRow = DataRow> extends ResourceContract<Row> {\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n readonly access: ResourceAccess;\n /** Present only when writes can be version-checked. */\n readonly version?: VersionField;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** Resources this one links to or is linked from. Only ones this user may see. */\n readonly relations?: readonly ResourceRelation[];\n /** Fields the user may set when creating a row. Absent when creating isn't allowed. */\n readonly createFields?: readonly string[];\n /** Row actions this user may run: each calls the app's own function on one row. */\n readonly actions?: readonly RowAction[];\n}\n\n/** A named operation on one row, carried out by the app's own database function. */\nexport interface RowAction {\n readonly name: string;\n readonly label: string;\n /** Ask before running, with this question. */\n readonly confirm?: string;\n /** One sentence on what it does. */\n readonly description?: string;\n}\n\n/** A comment on a record. */\nexport interface RecordComment {\n readonly id: string;\n /** The signed-in user who wrote it (the token's `sub`). */\n readonly author: string;\n readonly body: string;\n /** ISO 8601, as the store recorded it. */\n readonly createdAt: string;\n}\n\n/** One entry of `listResources()`: enough to draw a sidebar. */\nexport interface ResourceSummary {\n readonly name: string;\n readonly label?: string;\n readonly description?: string;\n readonly access: ResourceAccess;\n}\n\n/** Filter operators a provider may support. Mirrors `FilterParam[\"operator\"]`. */\nexport type FilterOperator =\n | \"eq\"\n | \"neq\"\n | \"gt\"\n | \"lt\"\n | \"gte\"\n | \"lte\"\n | \"contains\"\n | \"in\"\n | \"between\"\n | \"is_null\"\n | \"is_not_null\";\n\n/**\n * What a provider can do. A UI hides any control the provider cannot serve,\n * instead of letting it error (DATA-STUDIO.md decision 9).\n */\nexport interface ProviderCapabilities {\n /** Server-side text search across fields. */\n readonly search: boolean;\n /** Server-side sort. */\n readonly sort: boolean;\n /** Server-side filter operators. Empty means no server filtering. */\n readonly filterOperators: readonly FilterOperator[];\n /** `updateMany` / `deleteMany` in one transaction. */\n readonly bulkWrites: boolean;\n /** Updates honour `expectedVersion` and reject stale writes. */\n readonly versionedWrites: boolean;\n /** Records may be keyed by more than one field. */\n readonly compositeKeys: boolean;\n /** Server-side sort by several fields at once (`ListParams.sorts`). */\n readonly multiSort?: boolean;\n /** `create` and `deleteOne` are served, subject to each resource's access. */\n readonly create?: boolean;\n readonly delete?: boolean;\n /** `history` is served, subject to each resource's access. */\n readonly history?: boolean;\n /** `importRows` is served, with a dry run. */\n readonly import?: boolean;\n /** `undo` is served. */\n readonly undo?: boolean;\n /** `runAction` is served. */\n readonly actions?: boolean;\n /** `comments` and `addComment` are served. */\n readonly comments?: boolean;\n /**\n * The most rows one `getList` page may ask for. A request for more is\n * refused (it is not cut short, which would shift later page boundaries),\n * so a client that wants every row must page at this size or less.\n */\n readonly maxPerPage?: number;\n /**\n * A delete moves the record to a recycle bin (it can be restored) instead\n * of removing it. Asked per resource: `capabilities(resource)`.\n */\n readonly softDelete?: boolean;\n /**\n * `create`, `update` and `deleteOne` honour `keepalive: true` in their\n * params (e.g. `fetch(url, { keepalive: true })`), so a write sent while\n * the page unloads still reaches the server. Without it, closing the tab\n * while an optimistic or undoable write is being sent shows the browser's\n * \"Leave site?\" prompt.\n */\n readonly keepaliveWrites?: boolean;\n /**\n * `getList` serves cursor (keyset) paging: `pagination.cursor` in,\n * `nextCursor` out. Pages stay correct while rows are added or removed,\n * and a deep page costs no more than the first.\n */\n readonly cursorPagination?: boolean;\n /**\n * `subscribe` reports changes to this resource (asked per resource:\n * `capabilities(resource)`), so `live` lists and records refresh when\n * someone else changes them.\n */\n readonly realtime?: boolean;\n}\n\n/** One audit record, as committed alongside the edit it describes. */\nexport interface AuditEntry {\n readonly id: string;\n /** ISO 8601 timestamp, as the store recorded it. */\n readonly occurredAt: string;\n /** The signed-in user who made the edit (the token's `sub`). */\n readonly actor: string | null;\n readonly resource: string;\n /** The record's key, field name → value. */\n readonly key: DataRow;\n /** `run` is a row action; `rowAction` names it. */\n readonly action: \"create\" | \"update\" | \"delete\" | \"run\";\n /** For `run`: which row action. */\n readonly rowAction?: string;\n /** Values of the changed fields before the edit. */\n readonly before: DataRow | null;\n /** Values of the changed fields after the edit. */\n readonly after: DataRow | null;\n}\n"]}
@@ -1,7 +1,7 @@
1
- import { invalidateResource, executeWrite, cachedRecord } from './chunk-S2ZXUNXB.js';
1
+ import { useLiveInvalidation } from './chunk-UV3ROHQA.js';
2
+ import { invalidateResource, executeWrite, cachedRecord } from './chunk-3LZAZ5KB.js';
3
+ import { resourceKeys } from './chunk-OYIUIW7C.js';
2
4
  import { relatedKeys } from './chunk-7NUL32W7.js';
3
- import { resourceKeys } from './chunk-RCAP3Q4T.js';
4
- import { useLiveInvalidation } from './chunk-KXVHDK3Q.js';
5
5
  import { useDataProvider } from './chunk-GGSXSI6Z.js';
6
6
  import { useState, useCallback, useMemo } from 'react';
7
7
  import { useQueryClient, useQuery, keepPreviousData, useMutation } from '@tanstack/react-query';
@@ -211,5 +211,5 @@ function useResource(resource, options = {}) {
211
211
  }
212
212
 
213
213
  export { useResource };
214
- //# sourceMappingURL=chunk-NMFABW4Y.js.map
215
- //# sourceMappingURL=chunk-NMFABW4Y.js.map
214
+ //# sourceMappingURL=chunk-7YHGNPPO.js.map
215
+ //# sourceMappingURL=chunk-7YHGNPPO.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-resource.ts"],"names":["keepPreviousData","keepPreviousPlaceholder"],"mappings":";;;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AmB,cAAA,CAAe,WAAA,CAAY,EAAE,CAAA;AAAA,IACjD,CAAC,cAAc;AAAA,GACjB;AAEA,EAAA,MAAM,UAAA,GACJ,cAAA,CAAe,SAAA,IACf,cAAA,CAAe,aACf,cAAA,CAAe,SAAA;AAEjB,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;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-NMFABW4Y.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\";\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// ---------------------------------------------------------------------------\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>) => 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> }>;\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 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> }\n >({\n mutationFn: async ({ id, data }) => {\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 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 });\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 }) => {\n const result = await provider.deleteOne(resource, { id, ...(keepalive ? { keepalive } : {}) });\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>) =>\n updateMutation.mutateAsync({ 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
+ {"version":3,"sources":["../src/hooks/use-resource.ts"],"names":["keepPreviousData","keepPreviousPlaceholder"],"mappings":";;;;;;;;AA2IA,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,eAAA;AAAA,IACA,eAAA;AAAA,IACA,eAAA;AAAA,IACA,OAAA;AAAA,IACA,YAAA,GAAe,aAAA;AAAA,IACf,WAAA;AAAA,IACA;AAAA,GACF,GAAI,OAAA;AAEJ,EAAA,MAAM,WAAW,eAAA,EAAgB;AACjC,EAAA,MAAM,cAAc,cAAA,EAAe;AAMnC,EAAA,MAAM,CAAC,IAAA,EAAM,UAAU,CAAA,GAAI,SAAgC,WAAW,CAAA;AACtE,EAAA,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KACf,cAAA,CAAe,YAAY,EAAE,EAAA,EAAI,MAAM,CAAA;AAAA,IACzC,CAAC,cAAc;AAAA,GACjB;AAEA,EAAA,MAAM,MAAA,GAAS,WAAA;AAAA,IACb,CAAC,EAAA,KAAmB,cAAA,CAAe,WAAA,CAAY,EAAE,CAAA;AAAA,IACjD,CAAC,cAAc;AAAA,GACjB;AAEA,EAAA,MAAM,UAAA,GACJ,cAAA,CAAe,SAAA,IACf,cAAA,CAAe,aACf,cAAA,CAAe,SAAA;AAEjB,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;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-7YHGNPPO.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\";\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// ---------------------------------------------------------------------------\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>) => 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> }>;\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 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> }\n >({\n mutationFn: async ({ id, data }) => {\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 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 });\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 }) => {\n const result = await provider.deleteOne(resource, { id, ...(keepalive ? { keepalive } : {}) });\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>) =>\n updateMutation.mutateAsync({ 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"]}
@@ -0,0 +1,81 @@
1
+ // src/hooks/live-cache.ts
2
+ function isListResult(value) {
3
+ return !!value && typeof value === "object" && Array.isArray(value.data);
4
+ }
5
+ function isInfinite(value) {
6
+ return !!value && typeof value === "object" && Array.isArray(value.pages);
7
+ }
8
+ var sameId = (a, b) => a != null && b != null && String(a) === String(b);
9
+ function merge(row, record) {
10
+ let next = null;
11
+ for (const key of Object.keys(row)) {
12
+ if (key in record && row[key] !== record[key]) (next ??= { ...row })[key] = record[key];
13
+ }
14
+ return next ?? row;
15
+ }
16
+ function patchList(list, record) {
17
+ let changed = false;
18
+ const data = list.data.map((row) => {
19
+ if (!sameId(row.id, record.id)) return row;
20
+ const next = merge(row, record);
21
+ if (next !== row) changed = true;
22
+ return next;
23
+ });
24
+ return changed ? { ...list, data } : list;
25
+ }
26
+ function patchCachedRow(queryClient, resource, record) {
27
+ if (record.id == null) return;
28
+ for (const query of queryClient.getQueryCache().findAll({ queryKey: [resource] })) {
29
+ const [, kind, idOrParams, select] = query.queryKey;
30
+ const data = query.state.data;
31
+ if (data === void 0) continue;
32
+ let next = data;
33
+ if (kind === "detail" && select === void 0 && sameId(idOrParams, record.id) && typeof data === "object" && data) {
34
+ next = merge(data, record);
35
+ } else if (kind === "list" && isListResult(data)) {
36
+ next = patchList(data, record);
37
+ } else if (kind === "infinite" && isInfinite(data)) {
38
+ let changed = false;
39
+ const pages = data.pages.map((page) => {
40
+ if (!isListResult(page)) return page;
41
+ const patched = patchList(page, record);
42
+ if (patched !== page) changed = true;
43
+ return patched;
44
+ });
45
+ if (changed) next = { ...data, pages };
46
+ }
47
+ if (next !== data) queryClient.setQueryData(query.queryKey, next);
48
+ }
49
+ }
50
+ function comparable(v) {
51
+ if (typeof v === "boolean") return true;
52
+ return typeof v === "string" && !/^\d{4}-\d{2}-\d{2}/.test(v) && !/^-?\d+(\.\d+)?$/.test(v);
53
+ }
54
+ function passes(record, filters) {
55
+ for (const f of filters ?? []) {
56
+ if (!(f.field in record)) continue;
57
+ const v = record[f.field];
58
+ if (f.operator === "is_null" && v !== null) return false;
59
+ if (f.operator === "is_not_null" && v === null) return false;
60
+ if (!comparable(v)) continue;
61
+ if (f.operator === "eq" && comparable(f.value) && v !== f.value) return false;
62
+ if (f.operator === "neq" && comparable(f.value) && v === f.value) return false;
63
+ if (f.operator === "in" && f.value.every(comparable) && !f.value.includes(v)) return false;
64
+ }
65
+ return true;
66
+ }
67
+ function holds(data, id) {
68
+ const rows = isListResult(data) ? data.data : isInfinite(data) ? data.pages.flatMap((p) => isListResult(p) ? p.data : []) : [];
69
+ return rows.some((row) => sameId(row.id, id));
70
+ }
71
+ function listCouldChange(query, records) {
72
+ const [, kind, params] = query.queryKey;
73
+ if (kind !== "list" && kind !== "infinite") return true;
74
+ const filters = params?.filters;
75
+ if (!filters?.length) return true;
76
+ return records.some((record) => passes(record, filters) || holds(query.state.data, record.id));
77
+ }
78
+
79
+ export { listCouldChange, patchCachedRow };
80
+ //# sourceMappingURL=chunk-AUVKRXRC.js.map
81
+ //# sourceMappingURL=chunk-AUVKRXRC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/live-cache.ts"],"names":[],"mappings":";AASA,SAAS,aAAa,KAAA,EAAiD;AACrE,EAAA,OAAO,CAAC,CAAC,KAAA,IAAS,OAAO,UAAU,QAAA,IAAY,KAAA,CAAM,OAAA,CAAS,KAAA,CAA6B,IAAI,CAAA;AACjG;AAEA,SAAS,WAAW,KAAA,EAA+C;AACjE,EAAA,OAAO,CAAC,CAAC,KAAA,IAAS,OAAO,UAAU,QAAA,IAAY,KAAA,CAAM,OAAA,CAAS,KAAA,C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,IAAA;AACT;AAEA,SAAS,KAAA,CAAM,MAAe,EAAA,EAAsB;AAClD,EAAA,MAAM,IAAA,GAAO,aAAa,IAAI,CAAA,GAAI,KAAK,IAAA,GAAO,UAAA,CAAW,IAAI,CAAA,GAAI,IAAA,CAAK,KAAA,CAAM,QAAQ,CAAC,CAAA,KAAO,aAAa,CAAC,CAAA,GAAI,EAAE,IAAA,GAAO,EAAG,CAAA,GAAI,EAAC;AAC/H,EAAA,OAAO,IAAA,CAAK,KAAK,CAAC,GAAA,KAAQ,OAAO,GAAA,CAAI,EAAA,EAAI,EAAE,CAAC,CAAA;AAC9C;AAMO,SAAS,eAAA,CAAgB,OAAc,OAAA,EAAkC;AAC9E,EAAA,MAAM,GAAG,IAAA,EAAM,MAAM,IAAI,KAAA,CAAM,QAAA;AAC/B,EAAA,IAAI,IAAA,KAAS,MAAA,IAAU,IAAA,KAAS,UAAA,EAAY,OAAO,IAAA;AACnD,EAAA,MAAM,UAAW,MAAA,EAAmC,OAAA;AACpD,EAAA,IAAI,CAAC,OAAA,EAAS,MAAA,EAAQ,OAAO,IAAA;AAC7B,EAAA,OAAO,OAAA,CAAQ,IAAA,CAAK,CAAC,MAAA,KAAW,OAAO,MAAA,EAAQ,OAAO,CAAA,IAAK,KAAA,CAAM,KAAA,CAAM,KAAA,CAAM,IAAA,EAAM,MAAA,CAAO,EAAE,CAAC,CAAA;AAC/F","file":"chunk-AUVKRXRC.js","sourcesContent":["// What a live event may do to cached reads before the refetch: patch a changed row in place, and\n// tell which lists the change can't have touched. Only the fields a cached row already has are\n// patched, so a list or record read with a narrower select never gains columns it didn't ask for.\n\nimport type { Query, QueryClient } from \"@tanstack/react-query\";\nimport type { BaseRecord, FilterParam, ListParams, ListResult } from \"../provider/types\";\n\ntype Row = Record<string, unknown>;\n\nfunction isListResult(value: unknown): value is ListResult<BaseRecord> {\n return !!value && typeof value === \"object\" && Array.isArray((value as { data?: unknown }).data);\n}\n\nfunction isInfinite(value: unknown): value is { pages: unknown[] } {\n return !!value && typeof value === \"object\" && Array.isArray((value as { pages?: unknown }).pages);\n}\n\nconst sameId = (a: unknown, b: unknown) => a != null && b != null && String(a) === String(b);\n\n/** `row` with the fields it already has taken from `record`; the same object when nothing changes. */\nfunction merge(row: Row, record: Row): Row {\n let next: Row | null = null;\n for (const key of Object.keys(row)) {\n if (key in record && row[key] !== record[key]) (next ??= { ...row })[key] = record[key];\n }\n return next ?? row;\n}\n\nfunction patchList(list: ListResult<BaseRecord>, record: Row): ListResult<BaseRecord> {\n let changed = false;\n const data = list.data.map((row) => {\n if (!sameId(row.id, record.id)) return row;\n const next = merge(row, record);\n if (next !== row) changed = true;\n return next as BaseRecord;\n });\n return changed ? { ...list, data } : list;\n}\n\n/**\n * Patches a changed row into every cached read of `resource`: records read whole (no `select`),\n * and the rows of lists and infinite lists. Fields a cached row lacks are left out.\n */\nexport function patchCachedRow(queryClient: QueryClient, resource: string, record: Row): void {\n if (record.id == null) return;\n for (const query of queryClient.getQueryCache().findAll({ queryKey: [resource] })) {\n const [, kind, idOrParams, select] = query.queryKey as readonly unknown[];\n const data = query.state.data;\n if (data === undefined) continue;\n let next: unknown = data;\n if (kind === \"detail\" && select === undefined && sameId(idOrParams, record.id) && typeof data === \"object\" && data) {\n next = merge(data as Row, record);\n } else if (kind === \"list\" && isListResult(data)) {\n next = patchList(data, record);\n } else if (kind === \"infinite\" && isInfinite(data)) {\n let changed = false;\n const pages = data.pages.map((page) => {\n if (!isListResult(page)) return page;\n const patched = patchList(page, record);\n if (patched !== page) changed = true;\n return patched;\n });\n if (changed) next = { ...data, pages };\n }\n if (next !== data) queryClient.setQueryData(query.queryKey, next);\n }\n}\n\n/**\n * A value this function can compare safely: text, a uuid or a boolean. Numbers, dates and\n * timestamps format differently in a realtime payload and in a PostgREST read, so they never narrow.\n */\nfunction comparable(v: unknown): v is string | boolean {\n if (typeof v === \"boolean\") return true;\n return typeof v === \"string\" && !/^\\d{4}-\\d{2}-\\d{2}/.test(v) && !/^-?\\d+(\\.\\d+)?$/.test(v);\n}\n\n/** Whether `record` passes the filters this function can read; any other filter counts as a pass. */\nfunction passes(record: Row, filters: readonly FilterParam[] | undefined): boolean {\n for (const f of filters ?? []) {\n if (!(f.field in record)) continue;\n const v = record[f.field];\n if (f.operator === \"is_null\" && v !== null) return false;\n if (f.operator === \"is_not_null\" && v === null) return false;\n if (!comparable(v)) continue;\n if (f.operator === \"eq\" && comparable(f.value) && v !== f.value) return false;\n if (f.operator === \"neq\" && comparable(f.value) && v === f.value) return false;\n if (f.operator === \"in\" && f.value.every(comparable) && !f.value.includes(v)) return false;\n }\n return true;\n}\n\nfunction holds(data: unknown, id: unknown): boolean {\n const rows = isListResult(data) ? data.data : isInfinite(data) ? data.pages.flatMap((p) => (isListResult(p) ? p.data : [])) : [];\n return rows.some((row) => sameId(row.id, id));\n}\n\n/**\n * Whether a cached list could be changed by these rows: one of them matches its filters, or is in\n * it now (it may have left). Any read that isn't a list could always change.\n */\nexport function listCouldChange(query: Query, records: readonly Row[]): boolean {\n const [, kind, params] = query.queryKey as readonly unknown[];\n if (kind !== \"list\" && kind !== \"infinite\") return true;\n const filters = (params as ListParams | undefined)?.filters;\n if (!filters?.length) return true;\n return records.some((record) => passes(record, filters) || holds(query.state.data, record.id));\n}\n"]}