better-supabase 0.0.0 → 0.2.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 (157) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +88 -1
  3. package/bin/better-supabase.js +4 -0
  4. package/dist/casing-da0uRTqt.js +14 -0
  5. package/dist/claims-CoTobNC-.js +25 -0
  6. package/dist/cli/bin.d.ts +1 -0
  7. package/dist/cli/bin.js +15 -0
  8. package/dist/cli/index.d.ts +226 -0
  9. package/dist/cli/index.js +3 -0
  10. package/dist/cli-DrSgDOQC.js +6646 -0
  11. package/dist/client/index.d.ts +2 -0
  12. package/dist/client/index.js +112 -0
  13. package/dist/compiler-CZ9nIuqy.d.ts +14 -0
  14. package/dist/config/index.d.ts +3 -0
  15. package/dist/config/index.js +3 -0
  16. package/dist/config-ClDXmVtY.js +277 -0
  17. package/dist/define-BXMYD9AY.js +1071 -0
  18. package/dist/define-e3zI4_4g.d.ts +679 -0
  19. package/dist/edge/index.d.ts +43 -0
  20. package/dist/edge/index.js +103 -0
  21. package/dist/entitlements-CTEBm7IB.js +20 -0
  22. package/dist/entitlements-Dng-ctuT.d.ts +42 -0
  23. package/dist/env/index.d.ts +2 -0
  24. package/dist/env/index.js +2 -0
  25. package/dist/env-BEToab0I.js +204 -0
  26. package/dist/errors-Bl3rkOzo.js +196 -0
  27. package/dist/events/index.d.ts +2 -0
  28. package/dist/events/index.js +2 -0
  29. package/dist/events-BuzTgn2D.js +135 -0
  30. package/dist/events-DOt3nSO-.d.ts +84 -0
  31. package/dist/executor-BYXQ9AGn.d.ts +25 -0
  32. package/dist/executor-CGdNQ27g.d.ts +195 -0
  33. package/dist/executor-DeppvirK.js +89 -0
  34. package/dist/guards-BnzDvFrz.js +10 -0
  35. package/dist/hono/index.d.ts +45 -0
  36. package/dist/hono/index.js +70 -0
  37. package/dist/index-Bw1bwtC0.d.ts +144 -0
  38. package/dist/index-CBDufH1M.d.ts +120 -0
  39. package/dist/index-CG69s15v.d.ts +38 -0
  40. package/dist/index-Ciu5Xlml.d.ts +74 -0
  41. package/dist/index-D4v7sncu.d.ts +62 -0
  42. package/dist/index-DOsjFvMf.d.ts +618 -0
  43. package/dist/index-DbxFr7XG.d.ts +76 -0
  44. package/dist/index-DuP14VHo.d.ts +216 -0
  45. package/dist/index-Dy6kuF0P.d.ts +71 -0
  46. package/dist/index-K-3WM2Hp.d.ts +117 -0
  47. package/dist/index.d.ts +110 -0
  48. package/dist/index.js +43 -0
  49. package/dist/invalidate-DbxuL2jL.js +18 -0
  50. package/dist/jobs/index.d.ts +173 -0
  51. package/dist/jobs/index.js +478 -0
  52. package/dist/json-schema-BpYqkCKf.js +182 -0
  53. package/dist/lint/index.d.ts +75 -0
  54. package/dist/lint/index.js +167 -0
  55. package/dist/list/index.d.ts +2 -0
  56. package/dist/list/index.js +410 -0
  57. package/dist/live-D8rV1Ldw.js +168 -0
  58. package/dist/live-DJyZMD6w.d.ts +191 -0
  59. package/dist/logger-glM28NVN.js +21 -0
  60. package/dist/mcp/index.d.ts +142 -0
  61. package/dist/mcp/index.js +463 -0
  62. package/dist/mfa-CpLfJSde.js +541 -0
  63. package/dist/mfa-TVia554c.d.ts +44 -0
  64. package/dist/next/image/index.d.ts +34 -0
  65. package/dist/next/image/index.js +40 -0
  66. package/dist/next/index.d.ts +210 -0
  67. package/dist/next/index.js +427 -0
  68. package/dist/openapi/index.d.ts +2 -0
  69. package/dist/openapi/index.js +332 -0
  70. package/dist/orpc/index.d.ts +46 -0
  71. package/dist/orpc/index.js +50 -0
  72. package/dist/otel/index.d.ts +40 -0
  73. package/dist/otel/index.js +168 -0
  74. package/dist/path-Cv__-OTj.d.ts +17 -0
  75. package/dist/permdock-sql-CghlHPuH.js +117 -0
  76. package/dist/plugin-BqR6wKMB.js +23 -0
  77. package/dist/plugin-C4TR9J0Z.d.ts +118 -0
  78. package/dist/plugins/actor/index.d.ts +13 -0
  79. package/dist/plugins/actor/index.js +43 -0
  80. package/dist/plugins/rules/index.d.ts +89 -0
  81. package/dist/plugins/rules/index.js +167 -0
  82. package/dist/plugins/soft-delete/index.d.ts +38 -0
  83. package/dist/plugins/soft-delete/index.js +69 -0
  84. package/dist/plugins/tenant/index.d.ts +49 -0
  85. package/dist/plugins/tenant/index.js +75 -0
  86. package/dist/plugins/timestamps/index.d.ts +9 -0
  87. package/dist/plugins/timestamps/index.js +37 -0
  88. package/dist/plugins/validation/index.d.ts +24 -0
  89. package/dist/plugins/validation/index.js +59 -0
  90. package/dist/pool-R2m_DkXi.d.ts +37 -0
  91. package/dist/postgres/index.d.ts +28 -0
  92. package/dist/postgres/index.js +79 -0
  93. package/dist/postgrest-cAEQ_IQN.d.ts +43 -0
  94. package/dist/problem-BTkTtRV9.js +97 -0
  95. package/dist/problem-DlgB0lYl.d.ts +47 -0
  96. package/dist/query/index.d.ts +2 -0
  97. package/dist/query/index.js +3 -0
  98. package/dist/query-ChvDbsDE.js +186 -0
  99. package/dist/react/index.d.ts +7 -0
  100. package/dist/react/index.js +5 -0
  101. package/dist/react/server.d.ts +13 -0
  102. package/dist/react/server.js +25 -0
  103. package/dist/react/session.d.ts +2 -0
  104. package/dist/react/session.js +3 -0
  105. package/dist/react-C83BdBGt.js +242 -0
  106. package/dist/read-set-4lI3W_gZ.js +216 -0
  107. package/dist/realtime/index.d.ts +4 -0
  108. package/dist/realtime/index.js +268 -0
  109. package/dist/resolve-CjHILk2w.d.ts +170 -0
  110. package/dist/resource-BHEWmQJK.js +175 -0
  111. package/dist/resource-CgZa3YG_.d.ts +65 -0
  112. package/dist/respond-DMcbQwfN.js +383 -0
  113. package/dist/respond-Dne1ARSa.d.ts +169 -0
  114. package/dist/result-CTkCZ6JA.d.ts +198 -0
  115. package/dist/result-DWXatkd6.js +103 -0
  116. package/dist/scope-CDHcS7dE.js +90 -0
  117. package/dist/seed-CzecODcJ.js +101 -0
  118. package/dist/server/index.d.ts +42 -0
  119. package/dist/server/index.js +68 -0
  120. package/dist/session-C3LxnQ0e.d.ts +22 -0
  121. package/dist/session-CqEwzVup.js +20 -0
  122. package/dist/shared-_6-uPL7E.js +57 -0
  123. package/dist/simplify-bwJpLnaS.js +665 -0
  124. package/dist/spec-pins-C3oc-Tdp.js +20 -0
  125. package/dist/spec-pins-CqorWDnO.d.ts +20 -0
  126. package/dist/sql-DTjA1LPj.js +260 -0
  127. package/dist/ssr/index.d.ts +5 -0
  128. package/dist/ssr/index.js +4 -0
  129. package/dist/standard-CyhRzctb.d.ts +7 -0
  130. package/dist/standard-FUi3Z3-7.js +21 -0
  131. package/dist/stats-C5W-rBfR.js +566 -0
  132. package/dist/storage/index.d.ts +5 -0
  133. package/dist/storage/index.js +2 -0
  134. package/dist/storage-DuGn38fr.js +527 -0
  135. package/dist/tables-rZxRxNPW.js +59 -0
  136. package/dist/template-mbvlysOo.d.ts +6 -0
  137. package/dist/testing/index.d.ts +325 -0
  138. package/dist/testing/index.js +819 -0
  139. package/dist/types-6cYK9pbJ.js +29 -0
  140. package/dist/types-C83v5SQz.d.ts +248 -0
  141. package/dist/version-Cqq1m3UY.js +4 -0
  142. package/dist/view-D1s0wa0T.d.ts +49 -0
  143. package/dist/view-aOYizTeE.js +36 -0
  144. package/dist/webhooks/index.d.ts +152 -0
  145. package/dist/webhooks/index.js +2 -0
  146. package/dist/webhooks-DMipjhSP.js +139 -0
  147. package/package.json +250 -17
  148. package/schemas/config-v1.json +373 -0
  149. package/schemas/doctor-report-v1.json +106 -0
  150. package/schemas/snapshot-v2.json +1006 -0
  151. package/skills/better-supabase/SKILL.md +84 -0
  152. package/skills/better-supabase/references/plugins.md +65 -0
  153. package/skills/better-supabase/references/troubleshooting.md +39 -0
  154. package/skills/better-supabase-api/SKILL.md +67 -0
  155. package/skills/better-supabase-api/references/adapters.md +108 -0
  156. package/skills/better-supabase-testing/SKILL.md +66 -0
  157. package/index.js +0 -1
@@ -0,0 +1,216 @@
1
+ import { b as PermdockBucketPolicy, i as BucketPolicyName } from "./types-C83v5SQz.js";
2
+ import { p as DbError, t as AsyncResult } from "./result-CTkCZ6JA.js";
3
+ import { n as StoragePath, t as PathIn } from "./path-Cv__-OTj.js";
4
+ import { n as TemplateValues, t as TemplateParams } from "./template-mbvlysOo.js";
5
+ import { SupabaseClient } from "@supabase/supabase-js";
6
+ //#region src/storage/index.d.ts
7
+ type BucketPolicy = BucketPolicyName | PermdockBucketPolicy;
8
+ interface BucketConfig<P extends string = string, Id extends string = string> {
9
+ /** Bucket id, e.g. `customer-logos`. */
10
+ readonly id: Id;
11
+ /** Object path template, e.g. `{orgId}/{customerId}/logo/{version}.webp`. */
12
+ readonly path: P;
13
+ readonly public?: boolean;
14
+ /**
15
+ * Generated `storage.objects` policies. `tenant` and `owner` match a path
16
+ * segment against the JWT; `public` allows reads; `none` leaves access to
17
+ * the secret key; `{ permdock, scope }` calls PermDock's SQL helpers.
18
+ * Defaults to `none`.
19
+ *
20
+ * The helpers check role and scope only. Use `permdock` just for
21
+ * permissions whose grants have no row conditions beyond the scope: for a
22
+ * permission with row conditions (e.g. `ownerId = principal.id`) the bucket
23
+ * grants every object in the scope. Leave those to the policies
24
+ * `permdock rls generate` writes.
25
+ */
26
+ readonly policy?: BucketPolicy;
27
+ /** `'5MiB'`, `'500KB'` or bytes. */
28
+ readonly fileSizeLimit?: string | number;
29
+ /** `['image/png', 'image/*']`. */
30
+ readonly allowedMimeTypes?: readonly string[];
31
+ readonly tenant?: {
32
+ /** Placeholder holding the tenant id. Defaults to `orgId`. */
33
+ readonly param?: string;
34
+ /** JWT claim paths, first match wins. Defaults to `tenant_id`, then `app_metadata.tenant_id`. */
35
+ readonly claim?: string | readonly string[];
36
+ /** SQL expression for the tenant id, instead of `claim`. */
37
+ readonly sql?: string;
38
+ };
39
+ readonly owner?: {
40
+ /** Placeholder holding the user id. Defaults to `userId`. */
41
+ readonly param?: string;
42
+ };
43
+ }
44
+ /**
45
+ * A path from the template's values, or an existing path string (checked
46
+ * against the template). `StoragePath`s of other buckets are rejected.
47
+ */
48
+ type ObjectTarget<P extends string, Id extends string = string> = TemplateValues<P> | PathIn<Id>;
49
+ declare const TTL: {
50
+ readonly minute: 60;
51
+ readonly hour: 3600;
52
+ readonly day: 86_400;
53
+ readonly week: 604_800;
54
+ };
55
+ type TtlPreset = keyof typeof TTL;
56
+ interface TransformOptions {
57
+ readonly width?: number;
58
+ readonly height?: number;
59
+ readonly resize?: "cover" | "contain" | "fill";
60
+ readonly quality?: number;
61
+ readonly format?: "origin";
62
+ }
63
+ type UploadBody = Blob | ArrayBuffer | ArrayBufferView | ReadableStream<Uint8Array> | FormData | string;
64
+ interface UploadOptions {
65
+ readonly contentType?: string;
66
+ readonly cacheControl?: string;
67
+ readonly upsert?: boolean;
68
+ readonly metadata?: Readonly<Record<string, unknown>>;
69
+ readonly signal?: AbortSignal;
70
+ }
71
+ interface UrlOptions {
72
+ /** Seconds or a preset. Defaults to `hour`. */
73
+ readonly ttl?: number | TtlPreset;
74
+ readonly transform?: TransformOptions;
75
+ /** Serve as an attachment, optionally with a file name. */
76
+ readonly download?: boolean | string;
77
+ }
78
+ interface StoredObject {
79
+ readonly path: string;
80
+ readonly size?: number;
81
+ readonly contentType?: string;
82
+ readonly createdAt: string | null;
83
+ readonly updatedAt: string | null;
84
+ }
85
+ interface Reservation {
86
+ readonly path: string;
87
+ readonly token: string;
88
+ readonly signedUrl: string;
89
+ }
90
+ interface ReplaceOptions<Id extends string = string> extends UploadOptions {
91
+ /** Path the object replaces. Removed after `commit` succeeds. */
92
+ readonly previous?: string | null;
93
+ /**
94
+ * Store the new path, e.g. update the row. Throwing or returning an error
95
+ * `Result` removes the new object and keeps the previous one.
96
+ */
97
+ readonly commit?: (path: StoragePath<Id>) => unknown;
98
+ }
99
+ interface ReplaceResult<Id extends string = string> {
100
+ readonly path: StoragePath<Id>;
101
+ readonly removed: string | null;
102
+ /** Set when the previous object could not be removed. */
103
+ readonly cleanup?: DbError;
104
+ }
105
+ interface SweepOptions<P extends string> {
106
+ /** Only look under the path prefix these values fill. */
107
+ readonly within?: Partial<TemplateValues<P>>;
108
+ /** Minimum age in milliseconds, or a cutoff date. */
109
+ readonly olderThan: number | Date;
110
+ /** Returns which of `paths` are still referenced. */
111
+ readonly referenced: (paths: readonly string[]) => PromiseLike<Iterable<string>> | Iterable<string>;
112
+ readonly dryRun?: boolean;
113
+ readonly batchSize?: number;
114
+ readonly signal?: AbortSignal;
115
+ readonly now?: () => number;
116
+ }
117
+ interface SweepResult {
118
+ readonly scanned: number;
119
+ readonly orphans: readonly string[];
120
+ readonly removed: readonly string[];
121
+ }
122
+ interface BucketDrift {
123
+ readonly field: "missing" | "public" | "fileSizeLimit" | "allowedMimeTypes";
124
+ readonly expected: unknown;
125
+ readonly actual: unknown;
126
+ readonly message: string;
127
+ }
128
+ /** Bucket state as stored in `storage.buckets` (or `better-supabase` introspection). */
129
+ interface ActualBucket {
130
+ readonly public: boolean;
131
+ readonly fileSizeLimit?: number | null;
132
+ readonly allowedMimeTypes?: readonly string[] | null;
133
+ }
134
+ type StorageClient = Pick<SupabaseClient, "storage">;
135
+ interface BucketClient<P extends string, Id extends string = string> {
136
+ readonly bucket: Bucket<P, Id>;
137
+ upload(target: ObjectTarget<P, Id>, body: UploadBody, options?: UploadOptions): AsyncResult<{
138
+ path: StoragePath<Id>;
139
+ }>;
140
+ download(target: ObjectTarget<P, Id>, options?: {
141
+ signal?: AbortSignal;
142
+ }): AsyncResult<Blob>;
143
+ exists(target: ObjectTarget<P, Id>): AsyncResult<boolean>;
144
+ remove(targets: readonly ObjectTarget<P, Id>[]): AsyncResult<readonly string[]>;
145
+ list(within?: Partial<TemplateValues<P>>, options?: {
146
+ signal?: AbortSignal;
147
+ }): AsyncResult<readonly StoredObject[]>;
148
+ signedUrl(target: ObjectTarget<P, Id>, options?: UrlOptions): AsyncResult<string>;
149
+ signedUrls(targets: readonly ObjectTarget<P, Id>[], options?: Omit<UrlOptions, "transform">): AsyncResult<readonly string[]>;
150
+ /** URL for public buckets. No request is made. */
151
+ publicUrl(target: ObjectTarget<P, Id>, options?: Omit<UrlOptions, "ttl">): string;
152
+ /** Image transform URL: public for public buckets, signed otherwise. */
153
+ renderUrl(target: ObjectTarget<P, Id>, transform: TransformOptions, options?: Omit<UrlOptions, "transform">): AsyncResult<string>;
154
+ /** Upload the new object, run `commit`, then remove the previous object. */
155
+ replace(target: ObjectTarget<P, Id>, body: UploadBody, options?: ReplaceOptions<Id>): AsyncResult<ReplaceResult<Id>>;
156
+ /** A signed upload URL for a browser or another service. */
157
+ reserve(target: ObjectTarget<P, Id>, options?: {
158
+ upsert?: boolean;
159
+ }): AsyncResult<Reservation>;
160
+ uploadReserved(reservation: Pick<Reservation, "path" | "token">, body: UploadBody, options?: UploadOptions): AsyncResult<{
161
+ path: StoragePath<Id>;
162
+ }>;
163
+ /** Removes objects that match the template, are old enough and are not referenced. */
164
+ sweep(options: SweepOptions<P>): AsyncResult<SweepResult>;
165
+ }
166
+ interface Bucket<P extends string, Id extends string = string> {
167
+ readonly id: Id;
168
+ readonly template: P;
169
+ readonly params: readonly TemplateParams<P>[];
170
+ readonly public: boolean;
171
+ readonly policy: BucketPolicy;
172
+ /**
173
+ * Placeholder holding the owning user's id: `owner.param` for `owner`
174
+ * buckets, otherwise `userId` when the template has it. Account deletion
175
+ * removes the objects it fills.
176
+ */
177
+ readonly owner: string | undefined;
178
+ readonly fileSizeLimit: number | undefined;
179
+ readonly allowedMimeTypes: readonly string[] | undefined;
180
+ path(values: TemplateValues<P>): StoragePath<Id>;
181
+ match(path: string): TemplateValues<P> | null;
182
+ /** Folder prefix filled by `values`, for listing. */
183
+ prefix(values?: Partial<TemplateValues<P>>): string;
184
+ /** Checks a size and content type against the bucket limits. */
185
+ check(file: {
186
+ size?: number;
187
+ type?: string;
188
+ }): DbError | undefined;
189
+ /** `insert into storage.buckets` plus `storage.objects` policies. Idempotent. */
190
+ sql(): string;
191
+ /** A `[storage.buckets.<id>]` section for `supabase/config.toml`. */
192
+ toml(): string;
193
+ drift(actual: ActualBucket | undefined): readonly BucketDrift[];
194
+ connect(client: StorageClient): BucketClient<P, Id>;
195
+ }
196
+ declare function parseSize(value: string | number): number;
197
+ /** Maps a Storage error (`StorageApiError`, fetch failures) to a `DbError`. */
198
+ declare function fromStorageError(raw: unknown, table?: string): DbError;
199
+ /**
200
+ * A typed Storage bucket: path builders from a template, limits, generated
201
+ * SQL policies and `config.toml`, and helpers for the multi-step work apps
202
+ * repeat (replace, signed uploads, orphan cleanup).
203
+ *
204
+ * ```ts
205
+ * export const logos = defineBucket({
206
+ * id: 'customer-logos',
207
+ * path: '{orgId}/{customerId}/logo/{version}.webp',
208
+ * policy: 'tenant',
209
+ * fileSizeLimit: '5MiB',
210
+ * allowedMimeTypes: ['image/webp'],
211
+ * });
212
+ * ```
213
+ */
214
+ declare function defineBucket<const P extends string, const Id extends string = string>(config: BucketConfig<P, Id>): Bucket<P, Id>;
215
+ //#endregion
216
+ export { parseSize as C, fromStorageError as S, TtlPreset as _, BucketDrift as a, UrlOptions as b, ReplaceOptions as c, StorageClient as d, StoredObject as f, TransformOptions as g, TTL as h, BucketConfig as i, ReplaceResult as l, SweepResult as m, Bucket as n, BucketPolicy as o, SweepOptions as p, BucketClient as r, ObjectTarget as s, ActualBucket as t, Reservation as u, UploadBody as v, defineBucket as x, UploadOptions as y };
@@ -0,0 +1,71 @@
1
+ import { StandardSchemaV1 } from "@standard-schema/spec";
2
+ import { SupabaseEnv } from "@supabase/server";
3
+ //#region src/env/index.d.ts
4
+ /** Validated Supabase settings. Only `publicEnv()` of it is safe to ship to a browser. */
5
+ interface BetterSupabaseEnv {
6
+ readonly url: string;
7
+ readonly publishableKey: string;
8
+ readonly secretKey?: string;
9
+ /** Named secret keys from `SUPABASE_SECRET_KEYS`, including `default` when `secretKey` is set. */
10
+ readonly secretKeys?: Readonly<Record<string, string>>;
11
+ /** `SUPABASE_JWKS_URL`, or `<url>/auth/v1/.well-known/jwks.json`. */
12
+ readonly jwksUrl: URL;
13
+ /** Direct Postgres connection string (`SUPABASE_DB_URL` / `DATABASE_URL`). */
14
+ readonly dbUrl?: string;
15
+ /** Project ref for hosted projects (`<ref>.supabase.co`). */
16
+ readonly projectRef?: string;
17
+ /** `SUPABASE_READ_URL`: a read replica or the `<ref>-all` load balancer, for reads. */
18
+ readonly readUrl?: string;
19
+ }
20
+ interface PublicEnv {
21
+ readonly url: string;
22
+ readonly publishableKey: string;
23
+ }
24
+ type EnvSource = Readonly<Record<string, string | undefined>>;
25
+ interface EnvIssue {
26
+ /** The variable names that were checked, first one preferred. */
27
+ readonly variables: readonly string[];
28
+ readonly message: string;
29
+ }
30
+ interface EnvOptions {
31
+ /** Settings that must be present. `url` and `publishableKey` always are. */
32
+ readonly require?: readonly ("secretKey" | "dbUrl")[];
33
+ }
34
+ type EnvResult = {
35
+ readonly ok: true;
36
+ readonly env: BetterSupabaseEnv;
37
+ readonly issues?: undefined;
38
+ } | {
39
+ readonly ok: false;
40
+ readonly env?: undefined;
41
+ readonly issues: readonly EnvIssue[];
42
+ };
43
+ declare const ENV_VARIABLES: {
44
+ readonly url: readonly string[];
45
+ readonly publishableKey: readonly string[];
46
+ readonly secretKey: readonly string[];
47
+ readonly dbUrl: readonly string[];
48
+ readonly jwksUrl: readonly string[];
49
+ readonly readUrl: readonly string[];
50
+ };
51
+ declare class EnvValidationError extends Error {
52
+ override readonly name = "EnvValidationError";
53
+ readonly issues: readonly EnvIssue[];
54
+ constructor(issues: readonly EnvIssue[]);
55
+ }
56
+ /**
57
+ * Reads and validates Supabase settings. Accepts the `SUPABASE_`,
58
+ * `NEXT_PUBLIC_`, `VITE_`, `PUBLIC_`, `EXPO_PUBLIC_` and `NUXT_PUBLIC_`
59
+ * spellings. Issues name variables, never values.
60
+ */
61
+ declare function parseEnv(source: EnvSource, options?: EnvOptions): EnvResult;
62
+ /** Like `parseEnv`, but throws `EnvValidationError`. Reads `process.env` by default. */
63
+ declare function loadEnv(source?: EnvSource, options?: EnvOptions): BetterSupabaseEnv;
64
+ /** The env validator as a Standard Schema, for t3-env, framework config or any validator slot. */
65
+ declare function envSchema(options?: EnvOptions): StandardSchemaV1<EnvSource, BetterSupabaseEnv>;
66
+ /** The parts that are safe in client bundles. */
67
+ declare function publicEnv(env: BetterSupabaseEnv): PublicEnv;
68
+ /** Converts to `@supabase/server`'s `SupabaseEnv` (the `env` option of `withSupabase`). */
69
+ declare function toServerEnv(env: BetterSupabaseEnv): SupabaseEnv;
70
+ //#endregion
71
+ export { EnvResult as a, PublicEnv as c, parseEnv as d, publicEnv as f, EnvOptions as i, envSchema as l, ENV_VARIABLES as n, EnvSource as o, toServerEnv as p, EnvIssue as r, EnvValidationError as s, BetterSupabaseEnv as t, loadEnv as u };
@@ -0,0 +1,117 @@
1
+ import { C as PrimaryKeyValue, L as UniqueWhere, N as TableKey, R as Update, _ as Insert, n as AnyModels, t as AnyFunctions } from "./types-C83v5SQz.js";
2
+ import { _ as DbException } from "./result-CTkCZ6JA.js";
3
+ import { C as FindExt, Ct as WhereInput, M as UpsertArgs, N as WriteArgs, S as DeleteExt, T as OffsetPageArgs, X as InferResult, Z as QuerySpec, _ as CursorPage, it as AggregateResult, j as UpdateArgs, k as Returned, l as CacheAdapter, lt as FindFirstArgs, rt as AggregateArgs, st as CountArgs, t as BetterSupabase, ut as FindManyArgs, v as CursorPageArgs, vt as Payload, w as OffsetPage, x as DeleteArgs, y as Db, yt as ReadArgs } from "./define-e3zI4_4g.js";
4
+ import { DataTag, InfiniteData, QueryClient, SkipToken } from "@tanstack/query-core";
5
+ //#region src/query/invalidate.d.ts
6
+ /** Carried by every better-supabase query: the tables whose changes make it stale. */
7
+ interface BetterQueryMeta {
8
+ readonly bsTables: readonly string[];
9
+ readonly [key: string]: unknown;
10
+ }
11
+ /**
12
+ * Invalidates every query that read one of `tables`: better-supabase queries
13
+ * by their `meta.bsTables`, and other `['bs', table, ...]` keys by prefix.
14
+ */
15
+ declare function invalidateTables(client: QueryClient, tables: readonly string[]): Promise<void>;
16
+ //#endregion
17
+ //#region src/query/index.d.ts
18
+ type QueryKeyOf<T> = DataTag<readonly unknown[], T, DbException>;
19
+ type QueryFnOf<T> = ((context: {
20
+ readonly signal: AbortSignal;
21
+ }) => Promise<T>) | SkipToken;
22
+ /** Options for `useQuery`, `createQuery`, `injectQuery`, `queryClient.fetchQuery` and `prefetchQuery`. */
23
+ interface QueryOptionsOf<T> {
24
+ readonly queryKey: QueryKeyOf<T>;
25
+ readonly queryFn: QueryFnOf<T>;
26
+ readonly meta: BetterQueryMeta;
27
+ readonly staleTime?: number;
28
+ }
29
+ /** Options for infinite queries over cursor (`string | null`) or offset (`number`) pages. */
30
+ interface InfiniteOptionsOf<P, Param> {
31
+ readonly queryKey: DataTag<readonly unknown[], InfiniteData<P>, DbException>;
32
+ readonly queryFn: (context: {
33
+ readonly signal: AbortSignal;
34
+ readonly pageParam: Param;
35
+ }) => Promise<P>;
36
+ readonly initialPageParam: Param;
37
+ readonly getNextPageParam: (last: P) => Param | undefined;
38
+ readonly meta: BetterQueryMeta;
39
+ readonly staleTime?: number;
40
+ }
41
+ /** Options for `useMutation`. Invalidates every query that read a changed table. */
42
+ interface MutationOptionsOf<V, R> {
43
+ readonly mutationKey: readonly unknown[];
44
+ readonly mutationFn: (variables: V) => Promise<R>;
45
+ readonly onSuccess: (data: R, variables: V, onMutateResult: unknown, context: {
46
+ readonly client: QueryClient;
47
+ }) => Promise<void>;
48
+ }
49
+ interface TableQueries<M extends AnyModels, T extends TableKey<M>, E> {
50
+ /** Prefix of every key for this table's own queries. */
51
+ readonly key: readonly ["bs", T];
52
+ findMany<const A extends FindManyArgs<M, T> & FindExt<E, M, T>>(args?: A | SkipToken): QueryOptionsOf<Payload<M, T, A>[]>;
53
+ findFirst<const A extends FindFirstArgs<M, T> & FindExt<E, M, T>>(args?: A | SkipToken): QueryOptionsOf<Payload<M, T, A> | null>;
54
+ findUnique<const A extends ReadArgs<M, T> & {
55
+ readonly where: UniqueWhere<M, T>;
56
+ } & FindExt<E, M, T>>(args: A | SkipToken): QueryOptionsOf<Payload<M, T, A> | null>;
57
+ findById<const A extends ReadArgs<M, T> & FindExt<E, M, T>>(id: PrimaryKeyValue<M, T> | SkipToken, args?: A): QueryOptionsOf<Payload<M, T, A>>;
58
+ count(args?: (CountArgs<M, T> & FindExt<E, M, T>) | SkipToken): QueryOptionsOf<number>;
59
+ aggregate<const A extends AggregateArgs<M, T> & FindExt<E, M, T>>(args: A | SkipToken): QueryOptionsOf<AggregateResult<M, T, A>>;
60
+ exists(args?: ({
61
+ readonly where?: WhereInput<M, T>;
62
+ } & FindExt<E, M, T>) | SkipToken): QueryOptionsOf<boolean>;
63
+ paginate<const A extends OffsetPageArgs<M, T> & FindExt<E, M, T>>(args: A | SkipToken): QueryOptionsOf<OffsetPage<Payload<M, T, A>>>;
64
+ /** Cursor pages for `useInfiniteQuery`. */
65
+ infinite<const A extends Omit<CursorPageArgs<M, T>, "after"> & FindExt<E, M, T>>(args: A): InfiniteOptionsOf<CursorPage<Payload<M, T, A>>, string | null>;
66
+ /** Numbered pages for `useInfiniteQuery`, starting at `args.page` (default 1). */
67
+ infinitePages<const A extends OffsetPageArgs<M, T> & FindExt<E, M, T>>(args: A): InfiniteOptionsOf<OffsetPage<Payload<M, T, A>>, number>;
68
+ create<const A extends WriteArgs<M, T> = {}>(args?: A): MutationOptionsOf<Insert<M, T>, Returned<M, T, A>>;
69
+ update<const A extends UpdateArgs<M, T> = {}>(args?: A): MutationOptionsOf<{
70
+ readonly id: PrimaryKeyValue<M, T>;
71
+ readonly patch: Update<M, T>;
72
+ }, Returned<M, T, A>>;
73
+ upsert<const A extends UpsertArgs<M, T> = {}>(args?: A): MutationOptionsOf<Insert<M, T>, Returned<M, T, A>>;
74
+ delete(args?: DeleteArgs & DeleteExt<E, M, T>): MutationOptionsOf<PrimaryKeyValue<M, T>, void>;
75
+ }
76
+ type RpcArgsOf<F extends AnyFunctions, N extends keyof F> = F[N]["Args"];
77
+ interface QueryHelpers<M extends AnyModels, F extends AnyFunctions> {
78
+ /** Prefix of every better-supabase key. */
79
+ readonly key: readonly ["bs"];
80
+ /** Query options for a `QuerySpec`, for example one sent from a Server Component. */
81
+ $spec<S extends QuerySpec<TableKey<M>>>(spec: S | SkipToken): QueryOptionsOf<InferResult<S>>;
82
+ /** Fetches a spec into `queryClient` for server rendering and hydration. */
83
+ $prefetch(queryClient: QueryClient, spec: QuerySpec<TableKey<M>>): Promise<void>;
84
+ /** Query options for a database function. `tables` lists what it reads, for invalidation. */
85
+ $rpc<N extends Extract<keyof F, string>>(name: N, args?: RpcArgsOf<F, N> | SkipToken, options?: {
86
+ readonly tables?: readonly TableKey<M>[];
87
+ }): QueryOptionsOf<F[N]["Returns"]>;
88
+ /** Mutation options for a database function; invalidates what `sb.defineRpc` declared. */
89
+ $rpcMutation<N extends Extract<keyof F, string>>(name: N): MutationOptionsOf<RpcArgsOf<F, N>, F[N]["Returns"]>;
90
+ }
91
+ type Queries<M extends AnyModels, E, F extends AnyFunctions = AnyFunctions> = { readonly [T in TableKey<M>]: TableQueries<M, T, E>; } & QueryHelpers<M, F>;
92
+ interface CreateQueriesOptions {
93
+ /**
94
+ * `staleTime` for every query option. Set it above zero when rendering on
95
+ * the server so hydrated data isn't refetched on mount.
96
+ */
97
+ readonly staleTime?: number;
98
+ }
99
+ /**
100
+ * TanStack Query option factories for every table, framework-neutral: pass
101
+ * them to `useQuery` (React), `createQuery` (Svelte, Solid), `useQuery`
102
+ * (Vue) or `injectQuery` (Angular). Payload types flow into the cache, errors
103
+ * are `DbException`s, and mutations invalidate every query that read a
104
+ * changed table.
105
+ *
106
+ * ```ts
107
+ * const q = createQueries(sb, () => browser.db);
108
+ * const { data } = useQuery(q.customers.findMany({ select: ['id', 'name'] }));
109
+ * ```
110
+ */
111
+ declare function createQueries<M extends AnyModels, D, F extends AnyFunctions, E>(sb: BetterSupabase<M, D, F, E>, db: Db<M, F, E, unknown> | (() => Db<M, F, E, unknown>), options?: CreateQueriesOptions): Queries<M, E, F>;
112
+ /** Invalidates every query that read a table in the target. */
113
+ declare function queryCache(client: QueryClient): CacheAdapter;
114
+ /** Invalidates affected queries for every mutation and declared RPC `sb` performs in this runtime. */
115
+ declare function invalidateOnMutation<M extends AnyModels, D, F extends AnyFunctions, E>(sb: BetterSupabase<M, D, F, E>, client: QueryClient): () => void;
116
+ //#endregion
117
+ export { QueryHelpers as a, TableQueries as c, queryCache as d, BetterQueryMeta as f, Queries as i, createQueries as l, InfiniteOptionsOf as n, QueryKeyOf as o, invalidateTables as p, MutationOptionsOf as r, QueryOptionsOf as s, CreateQueriesOptions as t, invalidateOnMutation as u };
@@ -0,0 +1,110 @@
1
+ import { A as SchemaMeta, C as PrimaryKeyValue, D as Relations, E as RelationShape, F as UniqueConstraint, I as UniqueKeyName, L as UniqueWhere, M as TableFlags, N as TableKey, O as Row, P as TableMeta, R as Update, S as PrimaryKeyColumn, T as RelationMeta, _ as Insert, a as Casing, b as PermdockBucketPolicy, c as Codec, d as Flags, f as FlagsShape, g as FunctionsOf, h as FunctionShape, i as BucketPolicyName, j as Simplify, k as Schema, l as ColumnMeta, m as FunctionMeta, n as AnyModels, o as CheckConstraint, p as ForeignKeyConstraint, r as BucketMeta, s as ClaimsMeta, t as AnyFunctions, u as DatabaseOf, v as ModelShape, w as RealtimeTableMeta, x as PermdockTopicPolicy, y as ModelsOf } from "./types-C83v5SQz.js";
2
+ import { C as and, E as or, S as UpdateOp, T as not, _ as OrderTerm, a as AggregateFn, b as SelectOp, c as Condition, d as FunctionSource, f as Include, g as Operation, h as MutationOp, i as RpcContext, l as CountMode, m as Measure, n as ExecuteResult, o as Aggregation, p as InsertOp, r as Executor, s as ColumnOp, t as ExecuteContext, u as DeleteOp, v as Quantifier, w as column, x as Selection, y as SelectColumn } from "./executor-CGdNQ27g.js";
3
+ import { C as isConflict, D as statusOf, E as mapDbError, S as isCheck, T as isForeignKey, _ as DbException, a as Ok, b as ValidationIssue, c as err, d as toBetterResult, f as toDbError, g as DbErrorOf, h as DbErrorKinds, i as Err, l as fromBetterResult, m as DbErrorKind, n as BetterResultApi, o as Result, p as DbError, r as BetterResultShape, t as AsyncResult, u as ok, v as ErrorMapper, w as isDbError, x as dbError, y as RawDbError } from "./result-CTkCZ6JA.js";
4
+ import { a as EventHub, c as QueryEvent, d as LogFields, f as Logger, i as EventHandler, l as RefreshEvent, m as silentLogger, n as BetterSupabaseEvents, o as EventName, p as consoleLogger, r as ErrorEvent, s as MutationNotice, t as AuthEvent, u as RpcNotice } from "./events-DOt3nSO-.js";
5
+ import { $ as Specs, A as RpcOptions, B as ReadSet, C as FindExt, Ct as WhereInput, D as Repository, E as PageOf, F as EMPTY_STATS, G as ReadSetParams, H as ReadSetParamType, I as StatsRecorder, J as isReadSet, K as ReadSetResult, L as recordStats, M as UpsertArgs, N as WriteArgs, O as RepositoryOf, P as DbStats, Q as ReadMethod, R as SearchArgs, S as DeleteExt, St as SortDirection, T as OffsetPageArgs, U as ReadSetParamTypes, V as ReadSetOptions, W as ReadSetParamValue, X as InferResult, Y as readSetTables, Z as QuerySpec, _ as CursorPage, _t as OrderByInput, a as defineSupabase, at as AggregateRow, b as DbHelpers, bt as RelationMeasureArg, c as postgrestExecutor, ct as FieldFilter, d as MemoryCache, dt as IncludeArg, et as TableSpecs, f as cacheTargetOf, ft as IncludeArgs, g as ConflictTarget, gt as OrderByArg, h as rpcCacheTargets, ht as NumericMeasureArg, i as RpcDefinition, it as AggregateResult, j as UpdateArgs, k as Returned, l as CacheAdapter, lt as FindFirstArgs, m as rowKey, mt as MeasureKey, n as ConnectOptions, nt as specTables, o as PostgrestClientLike, ot as CountArg, p as memoryCache, pt as MeasureArg, q as defineReadSet, r as DefineSupabaseOptions, rt as AggregateArgs, s as explainPostgrest, st as CountArgs, t as BetterSupabase, tt as isQuerySpec, u as CacheTarget, ut as FindManyArgs, v as CursorPageArgs, vt as Payload, w as OffsetPage, x as DeleteArgs, xt as SelectArg, y as Db, yt as ReadArgs, z as InferReadSetParams } from "./define-e3zI4_4g.js";
6
+ import { _ as definePlugin, a as ExtensionOf, c as MutationEvent, d as PLUGIN_API_VERSION, f as Plugin, g as WithExtension, h as RequestContext, i as CallOptions, l as MutationKind, m as RepositoryExtension, n as AnyPlugin, o as HasFlag, p as RepositoryApi, r as ApplyExtension, s as HookArgs, t as Actor, u as NoExtension } from "./plugin-C4TR9J0Z.js";
7
+ import { n as validate, t as StandardSchemaV1 } from "./standard-CyhRzctb.js";
8
+ import { a as compilePostgrest, i as PostgrestPlan, n as PlanLimit, r as PlanOrder, t as PlanFilter } from "./postgrest-cAEQ_IQN.js";
9
+ import { n as StoragePath } from "./path-Cv__-OTj.js";
10
+ import { n as postgrestCompiler, t as Compiler } from "./compiler-CZ9nIuqy.js";
11
+ import { a as ProblemResponseOptions, c as problemResponse, i as ProblemOptions, l as toProblem, n as PROBLEM_TYPE_BASE, o as fromProblem, r as ProblemDetails, s as isProblem, t as PROBLEM_CONTENT_TYPE } from "./problem-DlgB0lYl.js";
12
+ import { t as SPEC_PINS } from "./spec-pins-CqorWDnO.js";
13
+ //#region src/core/define-repository.d.ts
14
+ /** Adds `Methods` to the repository of `Table` only. */
15
+ interface TableRepositoryExtension<Table extends string, Methods> extends RepositoryExtension {
16
+ readonly methods: this["T"] extends Table ? Methods : unknown;
17
+ }
18
+ /**
19
+ * Domain methods for one table, installed with `use()`. `base` is the
20
+ * repository at call time, with every other plugin's methods.
21
+ *
22
+ * ```ts
23
+ * const customers = defineRepository(sb, 'customers', (base) => ({
24
+ * active: () => base.findMany({ where: { status: 'active' } }),
25
+ * }));
26
+ * export const app = sb.use(customers);
27
+ * await app.connect(client).customers.active();
28
+ * ```
29
+ */
30
+ export declare function defineRepository<M extends AnyModels, D, F extends AnyFunctions, E, const Table extends TableKey<M>, Methods extends object>(sb: BetterSupabase<M, D, F, E>, table: Table, build: (base: RepositoryOf<M, Table, E>) => Methods): Plugin<`repository:${Table}`, TableRepositoryExtension<Table, Methods>>;
31
+ //#endregion
32
+ //#region src/ir/tables.d.ts
33
+ /**
34
+ * App keys of every table an operation reads or writes: its own table, each
35
+ * included relation and each relation used in a filter. Cached reads of these
36
+ * tables go stale when any of them changes.
37
+ */
38
+ export declare function touchedTables(op: Operation): string[];
39
+ /**
40
+ * Tables whose rows can change when rows of `table` change: the table itself
41
+ * plus every table whose foreign key cascades or sets a value on delete,
42
+ * followed through chains of cascades.
43
+ */
44
+ export declare function invalidationTargets(meta: SchemaMeta, table: string): string[];
45
+ //#endregion
46
+ //#region src/core/cursor.d.ts
47
+ /** Opaque, URL-safe keyset cursor. */
48
+ export declare function encodeCursor(values: readonly unknown[]): string;
49
+ export declare function decodeCursor(cursor: string): unknown[] | undefined;
50
+ //#endregion
51
+ //#region src/schema/define.d.ts
52
+ /**
53
+ * Binds generated model types to runtime metadata. Called from the generated
54
+ * module; apps import the returned `schema`, never call this themselves.
55
+ */
56
+ export declare function defineSchema<M extends AnyModels, D = unknown, F extends AnyFunctions = AnyFunctions>(meta: SchemaMeta): Schema<M, D, F>;
57
+ export declare function tableMeta(meta: SchemaMeta, table: string): TableMeta;
58
+ //#endregion
59
+ //#region src/schema/enrich.d.ts
60
+ type Override<R, O> = { [K in keyof R]: K extends keyof O ? null extends R[K] ? O[K] | null : O[K] : R[K]; };
61
+ type EnrichTables<Tables, O> = { [T in keyof Tables]: T extends keyof O ? { [P in keyof Tables[T]]: P extends "Row" | "Insert" | "Update" ? Override<Tables[T][P], O[T]> : Tables[T][P]; } : Tables[T]; };
62
+ type EnrichSchema<S, O> = { [P in keyof S]: P extends "Tables" | "Views" ? EnrichTables<S[P], O> : S[P]; };
63
+ /**
64
+ * Narrows column types of a `supabase gen types` `Database`: CHECK-constraint
65
+ * unions and typed jsonb. Overrides are keyed `{ schema: { table: { column } } }`.
66
+ */
67
+ type EnrichDatabase<D, O> = { [S in keyof D]: S extends keyof O ? EnrichSchema<D[S], O[S]> : D[S]; };
68
+ //#endregion
69
+ //#region src/ir/build.d.ts
70
+ /** Escapes LIKE wildcards so user input matches literally. */
71
+ export declare function escapeLike(value: string): string;
72
+ //#endregion
73
+ //#region src/ir/codec.d.ts
74
+ /** Wire form of an app value: `Date` to ISO text, `bigint` to decimal text. */
75
+ export declare function encodeValue(value: unknown): unknown;
76
+ /** Applies column codecs to returned rows, including embedded relations. */
77
+ export declare function decodeRows(selection: Selection | undefined, rows: readonly Record<string, unknown>[]): Record<string, unknown>[];
78
+ //#endregion
79
+ //#region src/ir/scope.d.ts
80
+ /** Returns the filter that always applies to rows of `table`, if any. */
81
+ type ScopeFor = (table: TableMeta) => Condition | undefined;
82
+ /**
83
+ * Applies `scopeFor` to every relation filter in a condition. `every(W)`
84
+ * becomes `none(S and not W)` so out-of-scope rows (soft-deleted, other
85
+ * tenants) neither satisfy nor fail it.
86
+ */
87
+ export declare function scopeCondition(condition: Condition | undefined, scopeFor: ScopeFor): Condition | undefined;
88
+ /** Applies `scopeFor` to every include and to filters inside includes. */
89
+ export declare function scopeSelection(selection: Selection, scopeFor: ScopeFor): Selection;
90
+ /**
91
+ * Scopes a whole operation: the root table's rows (reads, updates, deletes),
92
+ * relation filters, includes and returned embeds. Inserts only get their
93
+ * returning selection scoped.
94
+ */
95
+ export declare function scopeOperation(op: Operation, scopeFor: ScopeFor, root?: boolean): Operation;
96
+ //#endregion
97
+ //#region src/ir/simplify.d.ts
98
+ /**
99
+ * Folds constant conditions. `true` means "no filter", `false` means "matches
100
+ * nothing", so executors can skip the request entirely.
101
+ */
102
+ export declare function simplify(condition: Condition | undefined): Condition | boolean;
103
+ //#endregion
104
+ //#region src/casing/index.d.ts
105
+ /** `first_name` to `firstName`. Leaves already camel-cased names untouched. */
106
+ export declare function toCamel(name: string): string;
107
+ /** `firstName` to `first_name`. */
108
+ export declare function toSnake(name: string): string;
109
+ //#endregion
110
+ export { type Actor, type AggregateArgs, type AggregateFn, type AggregateResult, type AggregateRow, type Aggregation, type AnyFunctions, type AnyModels, type AnyPlugin, type ApplyExtension, AsyncResult, type AuthEvent, type BetterResultApi, type BetterResultShape, BetterSupabase, type BetterSupabaseEvents, type BucketMeta, type BucketPolicyName, type CacheAdapter, type CacheTarget, type CallOptions, type Casing, type CheckConstraint, type ClaimsMeta, type Codec, type ColumnMeta, type ColumnOp, type Compiler, type Condition, type ConflictTarget, type ConnectOptions, type CountArg, type CountArgs, type CountMode, type CursorPage, type CursorPageArgs, type DatabaseOf, type Db, type DbError, type DbErrorKind, type DbErrorKinds, type DbErrorOf, DbException, type DbHelpers, type DbStats, type DefineSupabaseOptions, type DeleteArgs, type DeleteExt, type DeleteOp, EMPTY_STATS, type EnrichDatabase, type Err, type ErrorEvent, type ErrorMapper, type EventHandler, EventHub, type EventName, type ExecuteContext, type ExecuteResult, type Executor, type ExtensionOf, type FieldFilter, type FindExt, type FindFirstArgs, type FindManyArgs, type Flags, type FlagsShape, type ForeignKeyConstraint, type FunctionMeta, type FunctionShape, type FunctionSource, type FunctionsOf, type HasFlag, type HookArgs, type Include, type IncludeArg, type IncludeArgs, type InferReadSetParams, type InferResult, type Insert, type InsertOp, type LogFields, type Logger, type Measure, type MeasureArg, type MeasureKey, type MemoryCache, type ModelShape, type ModelsOf, type MutationEvent, type MutationKind, type MutationNotice, type MutationOp, type NoExtension, type NumericMeasureArg, type OffsetPage, type OffsetPageArgs, type Ok, type Operation, type OrderByArg, type OrderByInput, type OrderTerm, PLUGIN_API_VERSION, PROBLEM_CONTENT_TYPE, PROBLEM_TYPE_BASE, type PageOf, type Payload, type PermdockBucketPolicy, type PermdockTopicPolicy, type PlanFilter, type PlanLimit, type PlanOrder, type Plugin, type PostgrestClientLike, type PostgrestPlan, type PrimaryKeyColumn, type PrimaryKeyValue, type ProblemDetails, type ProblemOptions, type ProblemResponseOptions, type Quantifier, type QueryEvent, type QuerySpec, type RawDbError, type ReadArgs, type ReadMethod, type ReadSet, type ReadSetOptions, type ReadSetParamType, type ReadSetParamTypes, type ReadSetParamValue, type ReadSetParams, type ReadSetResult, type RealtimeTableMeta, type RefreshEvent, type RelationMeasureArg, type RelationMeta, type RelationShape, type Relations, type Repository, type RepositoryApi, type RepositoryExtension, type RepositoryOf, type RequestContext, type Result, type Returned, type Row, type RpcContext, type RpcDefinition, type RpcNotice, type RpcOptions, SPEC_PINS, type Schema, type SchemaMeta, type ScopeFor, type SearchArgs, type SelectArg, type SelectColumn, type SelectOp, type Selection, type Simplify, type SortDirection, type Specs, type StandardSchemaV1, StatsRecorder, type StoragePath, type TableFlags, type TableKey, type TableMeta, type TableRepositoryExtension, type TableSpecs, type UniqueConstraint, type UniqueKeyName, type UniqueWhere, type Update, type UpdateArgs, type UpdateOp, type UpsertArgs, type ValidationIssue, type WhereInput, type WithExtension, type WriteArgs, and, cacheTargetOf, column, compilePostgrest, consoleLogger, dbError, definePlugin, defineReadSet, defineSupabase, err, explainPostgrest, fromBetterResult, fromProblem, isCheck, isConflict, isDbError, isForeignKey, isProblem, isQuerySpec, isReadSet, mapDbError, memoryCache, not, ok, or, postgrestCompiler, postgrestExecutor, problemResponse, readSetTables, recordStats, rowKey, rpcCacheTargets, silentLogger, specTables, statusOf, toBetterResult, toDbError, toProblem, validate };
package/dist/index.js ADDED
@@ -0,0 +1,43 @@
1
+ import { a as isConflict, c as mapDbError, i as isCheck, l as statusOf, n as dbError, o as isDbError, s as isForeignKey, t as DbException } from "./errors-Bl3rkOzo.js";
2
+ import { i as escapeLike, l as defineSchema, o as decodeRows, s as encodeValue, t as simplify, u as tableMeta } from "./simplify-bwJpLnaS.js";
3
+ import { i as or, n as column, r as not, t as and } from "./types-6cYK9pbJ.js";
4
+ import { a as toBetterResult, i as ok, n as err, o as toDbError, r as fromBetterResult, t as AsyncResult } from "./result-DWXatkd6.js";
5
+ import { a as EventHub, c as rowKey, i as encodeCursor, l as rpcCacheTargets, n as defineSupabase, o as cacheTargetOf, r as decodeCursor, s as memoryCache, t as BetterSupabase } from "./define-BXMYD9AY.js";
6
+ import { n as touchedTables, t as invalidationTargets } from "./tables-rZxRxNPW.js";
7
+ import { n as silentLogger, t as consoleLogger } from "./logger-glM28NVN.js";
8
+ import { n as definePlugin, t as PLUGIN_API_VERSION } from "./plugin-BqR6wKMB.js";
9
+ import { a as postgrestExecutor, i as explainPostgrest, n as StatsRecorder, o as compilePostgrest, r as recordStats, t as EMPTY_STATS } from "./stats-C5W-rBfR.js";
10
+ import { c as readSetTables, d as isQuerySpec, f as specTables, i as defineReadSet, o as isReadSet } from "./read-set-4lI3W_gZ.js";
11
+ import { t as validate } from "./standard-FUi3Z3-7.js";
12
+ import { a as problemResponse, i as isProblem, n as PROBLEM_TYPE_BASE, o as toProblem, r as fromProblem, t as PROBLEM_CONTENT_TYPE } from "./problem-BTkTtRV9.js";
13
+ import { t as SPEC_PINS } from "./spec-pins-C3oc-Tdp.js";
14
+ import { n as scopeOperation, r as scopeSelection, t as scopeCondition } from "./scope-CDHcS7dE.js";
15
+ import { n as toCamel, r as toSnake } from "./casing-da0uRTqt.js";
16
+ //#region src/core/define-repository.ts
17
+ /**
18
+ * Domain methods for one table, installed with `use()`. `base` is the
19
+ * repository at call time, with every other plugin's methods.
20
+ *
21
+ * ```ts
22
+ * const customers = defineRepository(sb, 'customers', (base) => ({
23
+ * active: () => base.findMany({ where: { status: 'active' } }),
24
+ * }));
25
+ * export const app = sb.use(customers);
26
+ * await app.connect(client).customers.active();
27
+ * ```
28
+ */
29
+ function defineRepository(sb, table, build) {
30
+ if (!(table in sb.meta.tables)) throw new TypeError(`better-supabase: defineRepository: unknown table "${table}"`);
31
+ return definePlugin({
32
+ name: `repository:${table}`,
33
+ repository: ({ table: meta, base }) => meta.key === table ? build(base) : void 0
34
+ });
35
+ }
36
+ //#endregion
37
+ //#region src/core/compiler.ts
38
+ const postgrestCompiler = {
39
+ target: "postgrest",
40
+ compile: compilePostgrest
41
+ };
42
+ //#endregion
43
+ export { AsyncResult, BetterSupabase, DbException, EMPTY_STATS, EventHub, PLUGIN_API_VERSION, PROBLEM_CONTENT_TYPE, PROBLEM_TYPE_BASE, SPEC_PINS, StatsRecorder, and, cacheTargetOf, column, compilePostgrest, consoleLogger, dbError, decodeCursor, decodeRows, definePlugin, defineReadSet, defineRepository, defineSchema, defineSupabase, encodeCursor, encodeValue, err, escapeLike, explainPostgrest, fromBetterResult, fromProblem, invalidationTargets, isCheck, isConflict, isDbError, isForeignKey, isProblem, isQuerySpec, isReadSet, mapDbError, memoryCache, not, ok, or, postgrestCompiler, postgrestExecutor, problemResponse, readSetTables, recordStats, rowKey, rpcCacheTargets, scopeCondition, scopeOperation, scopeSelection, silentLogger, simplify, specTables, statusOf, tableMeta, toBetterResult, toCamel, toDbError, toProblem, toSnake, touchedTables, validate };
@@ -0,0 +1,18 @@
1
+ //#region src/query/invalidate.ts
2
+ function queryTables(query) {
3
+ const tables = query.meta?.["bsTables"];
4
+ if (Array.isArray(tables)) return tables.filter((t) => typeof t === "string");
5
+ const [prefix, table] = query.queryKey;
6
+ return prefix === "bs" && typeof table === "string" ? [table] : void 0;
7
+ }
8
+ /**
9
+ * Invalidates every query that read one of `tables`: better-supabase queries
10
+ * by their `meta.bsTables`, and other `['bs', table, ...]` keys by prefix.
11
+ */
12
+ function invalidateTables(client, tables) {
13
+ if (tables.length === 0) return Promise.resolve();
14
+ const changed = new Set(tables);
15
+ return client.invalidateQueries({ predicate: (query) => queryTables(query)?.some((table) => changed.has(table)) ?? false });
16
+ }
17
+ //#endregion
18
+ export { invalidateTables as t };