@rebasepro/server 0.23.0 → 0.24.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 (181) hide show
  1. package/README.md +1 -1
  2. package/bin/rebase-server.js +4 -2
  3. package/dist/{GCSStorageController-CjrA4PMo.js → GCSStorageController-BSiP1c-f.js} +22 -8
  4. package/dist/GCSStorageController-BSiP1c-f.js.map +1 -0
  5. package/dist/{S3StorageController-B6pKDNVj.js → S3StorageController-CAwFRgjV.js} +19 -7
  6. package/dist/S3StorageController-CAwFRgjV.js.map +1 -0
  7. package/dist/api/ast-schema-editor.d.ts +92 -1
  8. package/dist/api/errors.d.ts +9 -0
  9. package/dist/api/live-schema-routes.d.ts +38 -8
  10. package/dist/api/logs-routes.d.ts +39 -1
  11. package/dist/api/openapi-generator.d.ts +17 -0
  12. package/dist/api/rest/api-generator.d.ts +44 -10
  13. package/dist/api/rest/write-validation.d.ts +2 -2
  14. package/dist/api/types.d.ts +17 -1
  15. package/dist/{ast-schema-editor-Mvr50v_S.js → ast-schema-editor-CWqS_sLJ.js} +309 -11
  16. package/dist/ast-schema-editor-CWqS_sLJ.js.map +1 -0
  17. package/dist/auth/access.d.ts +105 -0
  18. package/dist/auth/adapter-middleware.d.ts +2 -1
  19. package/dist/auth/address-ownership.d.ts +16 -1
  20. package/dist/auth/admin-roles-route.d.ts +4 -2
  21. package/dist/auth/admin-roles.d.ts +17 -20
  22. package/dist/auth/admin-users-route.d.ts +1 -0
  23. package/dist/auth/api-keys/api-key-middleware.d.ts +56 -55
  24. package/dist/auth/api-keys/api-key-routes.d.ts +41 -11
  25. package/dist/auth/api-keys/api-key-store.d.ts +31 -8
  26. package/dist/auth/api-keys/api-key-types.d.ts +14 -16
  27. package/dist/auth/api-keys/http-operation.d.ts +19 -0
  28. package/dist/auth/api-keys/index.d.ts +11 -11
  29. package/dist/auth/api-keys/key-grant.d.ts +41 -0
  30. package/dist/auth/api-keys/legacy-permissions.d.ts +33 -0
  31. package/dist/auth/auth-hooks.d.ts +46 -7
  32. package/dist/auth/builtin-auth-adapter.d.ts +8 -0
  33. package/dist/auth/cookie-utils.d.ts +7 -0
  34. package/dist/auth/deliverable-address.d.ts +6 -0
  35. package/dist/auth/email-change-routes.d.ts +41 -0
  36. package/dist/auth/expired-token-sweep.d.ts +67 -0
  37. package/dist/auth/impersonation.d.ts +110 -0
  38. package/dist/auth/index.d.ts +4 -2
  39. package/dist/auth/interfaces.d.ts +110 -59
  40. package/dist/auth/jwt.d.ts +49 -3
  41. package/dist/auth/magic-link-routes.d.ts +2 -6
  42. package/dist/auth/mfa-routes.d.ts +2 -9
  43. package/dist/auth/middleware.d.ts +17 -5
  44. package/dist/auth/otp-routes.d.ts +2 -6
  45. package/dist/auth/passwordless-signup.d.ts +27 -0
  46. package/dist/auth/platform-token.d.ts +122 -0
  47. package/dist/auth/rate-limiter.d.ts +41 -0
  48. package/dist/auth/routes.d.ts +45 -0
  49. package/dist/auth/scope-routes.d.ts +22 -0
  50. package/dist/auth/session-routes.d.ts +11 -6
  51. package/dist/auth/token-revocation.d.ts +50 -1
  52. package/dist/auth/verify-credential.d.ts +28 -0
  53. package/dist/{auth-B-GIMpDG.js → auth-DMLngxn_.js} +2159 -569
  54. package/dist/auth-DMLngxn_.js.map +1 -0
  55. package/dist/backend-DTAOsLQc.js.map +1 -1
  56. package/dist/backup/backup-common.d.ts +10 -0
  57. package/dist/backup/backup-routes.d.ts +24 -4
  58. package/dist/backup/backup-schedule.d.ts +33 -0
  59. package/dist/backup/backup-storage.d.ts +14 -0
  60. package/dist/backup/index.d.ts +2 -0
  61. package/dist/backup-CN0s50D2.js +444 -0
  62. package/dist/backup-CN0s50D2.js.map +1 -0
  63. package/dist/boot/bundle.d.ts +19 -0
  64. package/dist/boot/env.d.ts +49 -4
  65. package/dist/boot/security-headers.d.ts +26 -0
  66. package/dist/boot/static-routing.d.ts +56 -0
  67. package/dist/collection_patch-BRu-BvDv.js +472 -0
  68. package/dist/collection_patch-BRu-BvDv.js.map +1 -0
  69. package/dist/{contract-routes-CbFjuBwa.js → contract-routes-fz8i4pxs.js} +17 -4
  70. package/dist/contract-routes-fz8i4pxs.js.map +1 -0
  71. package/dist/cron/cron-scheduler.d.ts +25 -20
  72. package/dist/cron/cron-store.d.ts +6 -2
  73. package/dist/{cron-loader-DfTj2Hbi.js → cron-loader-CwaANlOG.js} +4 -4
  74. package/dist/cron-loader-CwaANlOG.js.map +1 -0
  75. package/dist/{cron-routes-eE8nif_b.js → cron-routes-Bc-SB0Se.js} +10 -7
  76. package/dist/cron-routes-Bc-SB0Se.js.map +1 -0
  77. package/dist/{cron-scheduler-B0pLfAix.js → cron-scheduler-CYQgco86.js} +52 -34
  78. package/dist/cron-scheduler-CYQgco86.js.map +1 -0
  79. package/dist/{cron-store-TcoGz-xS.js → cron-store-D2Q9-Aco.js} +10 -15
  80. package/dist/cron-store-D2Q9-Aco.js.map +1 -0
  81. package/dist/{ddl-bootstrap-C6mo0Kmz.js → ddl-bootstrap-BaqMSa4Y.js} +2 -2
  82. package/dist/{ddl-bootstrap-C6mo0Kmz.js.map → ddl-bootstrap-BaqMSa4Y.js.map} +1 -1
  83. package/dist/email/index.d.ts +2 -2
  84. package/dist/email/templates.d.ts +22 -0
  85. package/dist/email/types.d.ts +26 -0
  86. package/dist/env.d.ts +1 -2
  87. package/dist/{errors-DWsX4yTd.js → errors-D6_y86c5.js} +102 -8
  88. package/dist/errors-D6_y86c5.js.map +1 -0
  89. package/dist/{function-loader-xnbDAPfa.js → function-loader-D7o5Epjj.js} +2 -2
  90. package/dist/{function-loader-xnbDAPfa.js.map → function-loader-D7o5Epjj.js.map} +1 -1
  91. package/dist/{function-routes-Chet4-lB.js → function-routes-CaNG4waN.js} +24 -12
  92. package/dist/function-routes-CaNG4waN.js.map +1 -0
  93. package/dist/functions/context.d.ts +17 -6
  94. package/dist/functions/guards.d.ts +22 -5
  95. package/dist/functions/index.d.ts +2 -2
  96. package/dist/functions/index.js +90 -36
  97. package/dist/functions/index.js.map +1 -1
  98. package/dist/{history-recorder-B4MpJfJK.js → history-recorder-Nr8zLvoU.js} +4 -4
  99. package/dist/{history-recorder-B4MpJfJK.js.map → history-recorder-Nr8zLvoU.js.map} +1 -1
  100. package/dist/{history-store-BhxWOuz9.js → history-store-rcAm_xFR.js} +2 -2
  101. package/dist/{history-store-BhxWOuz9.js.map → history-store-rcAm_xFR.js.map} +1 -1
  102. package/dist/index.d.ts +8 -2
  103. package/dist/index.es.js +3084 -753
  104. package/dist/index.es.js.map +1 -1
  105. package/dist/init/health.d.ts +17 -2
  106. package/dist/init/shutdown.d.ts +10 -0
  107. package/dist/init.d.ts +54 -0
  108. package/dist/{jobs-CazMYhyy.js → jobs-DqYNfquG.js} +5 -5
  109. package/dist/{jobs-CazMYhyy.js.map → jobs-DqYNfquG.js.map} +1 -1
  110. package/dist/{jwt-DnQHNFCl.js → jwt-R6bSPMjk.js} +39 -15
  111. package/dist/{jwt-DnQHNFCl.js.map → jwt-R6bSPMjk.js.map} +1 -1
  112. package/dist/{keys-CogCQpxG.js → keys-GAVZqbqx.js} +3 -17
  113. package/dist/{keys-CogCQpxG.js.map → keys-GAVZqbqx.js.map} +1 -1
  114. package/dist/{logger-DO2PZc4i.js → logger-D-S-hO5e.js} +26 -3
  115. package/dist/logger-D-S-hO5e.js.map +1 -0
  116. package/dist/{logs-routes-Bj4TYYUl.js → logs-routes-DAdv37GI.js} +48 -8
  117. package/dist/logs-routes-DAdv37GI.js.map +1 -0
  118. package/dist/mcp/consent-page.d.ts +1 -1
  119. package/dist/mcp/mcp-routes.d.ts +7 -0
  120. package/dist/mcp/mcp-tools.d.ts +15 -9
  121. package/dist/mcp/oauth-metadata.d.ts +21 -16
  122. package/dist/mcp/oauth-routes.d.ts +7 -1
  123. package/dist/{openapi-generator-O_O24MAT.js → openapi-generator-DAq_XVDu.js} +104 -13
  124. package/dist/openapi-generator-DAq_XVDu.js.map +1 -0
  125. package/dist/{proxy-Czngl3p9.js → proxy-qRlqeUmO.js} +2 -2
  126. package/dist/{proxy-Czngl3p9.js.map → proxy-qRlqeUmO.js.map} +1 -1
  127. package/dist/{query-parser-DGRVFNM3.js → query-parser-BgiKJKvc.js} +6 -56
  128. package/dist/query-parser-BgiKJKvc.js.map +1 -0
  129. package/dist/{request-timeout-C_4C2BeR.js → request-timeout-DgH7j8qO.js} +3 -3
  130. package/dist/{request-timeout-C_4C2BeR.js.map → request-timeout-DgH7j8qO.js.map} +1 -1
  131. package/dist/schema-edit/apply-schema-change.d.ts +63 -3
  132. package/dist/schema-edit/project-root.d.ts +3 -2
  133. package/dist/schema-edit/remote-source.d.ts +9 -4
  134. package/dist/{schema-editor-routes-C5-lh_jO.js → schema-editor-routes-oIyuWl3L.js} +12 -7
  135. package/dist/schema-editor-routes-oIyuWl3L.js.map +1 -0
  136. package/dist/serve-spa.d.ts +58 -0
  137. package/dist/services/routed-realtime-service.d.ts +11 -0
  138. package/dist/soft-delete-params-BWPilMPF.js +59 -0
  139. package/dist/soft-delete-params-BWPilMPF.js.map +1 -0
  140. package/dist/{src-vkcwKXbT.js → src-CatHFUym.js} +439 -20
  141. package/dist/src-CatHFUym.js.map +1 -0
  142. package/dist/{src-pmvW7BFx.js → src-I3aG1PcY.js} +252 -70
  143. package/dist/src-I3aG1PcY.js.map +1 -0
  144. package/dist/storage/GCSStorageController.d.ts +2 -0
  145. package/dist/storage/LocalStorageController.d.ts +2 -0
  146. package/dist/storage/S3StorageController.d.ts +2 -0
  147. package/dist/storage/index.d.ts +2 -2
  148. package/dist/storage/property-limits.d.ts +41 -6
  149. package/dist/storage/request-keys.d.ts +15 -0
  150. package/dist/storage/requested-object.d.ts +74 -0
  151. package/dist/storage/routes.d.ts +36 -18
  152. package/dist/storage/tus-handler.d.ts +30 -5
  153. package/dist/storage/types.d.ts +19 -0
  154. package/dist/types-BfKcm9do.js.map +1 -1
  155. package/dist/utils/logger.d.ts +12 -0
  156. package/package.json +5 -5
  157. package/dist/GCSStorageController-CjrA4PMo.js.map +0 -1
  158. package/dist/S3StorageController-B6pKDNVj.js.map +0 -1
  159. package/dist/admin-roles-vYdp_Pil.js +0 -36
  160. package/dist/admin-roles-vYdp_Pil.js.map +0 -1
  161. package/dist/admin_block-DxKLmdiv.js +0 -206
  162. package/dist/admin_block-DxKLmdiv.js.map +0 -1
  163. package/dist/ast-schema-editor-Mvr50v_S.js.map +0 -1
  164. package/dist/auth/api-keys/api-key-permission-guard.d.ts +0 -65
  165. package/dist/auth-B-GIMpDG.js.map +0 -1
  166. package/dist/backup-D7YR94N3.js +0 -253
  167. package/dist/backup-D7YR94N3.js.map +0 -1
  168. package/dist/contract-routes-CbFjuBwa.js.map +0 -1
  169. package/dist/cron-loader-DfTj2Hbi.js.map +0 -1
  170. package/dist/cron-routes-eE8nif_b.js.map +0 -1
  171. package/dist/cron-scheduler-B0pLfAix.js.map +0 -1
  172. package/dist/cron-store-TcoGz-xS.js.map +0 -1
  173. package/dist/errors-DWsX4yTd.js.map +0 -1
  174. package/dist/function-routes-Chet4-lB.js.map +0 -1
  175. package/dist/logger-DO2PZc4i.js.map +0 -1
  176. package/dist/logs-routes-Bj4TYYUl.js.map +0 -1
  177. package/dist/openapi-generator-O_O24MAT.js.map +0 -1
  178. package/dist/query-parser-DGRVFNM3.js.map +0 -1
  179. package/dist/schema-editor-routes-C5-lh_jO.js.map +0 -1
  180. package/dist/src-pmvW7BFx.js.map +0 -1
  181. package/dist/src-vkcwKXbT.js.map +0 -1
@@ -1,7 +1,32 @@
1
1
  import { Hono } from "hono";
2
2
  import { AuthAdapter, DataDriver, CollectionConfig } from "@rebasepro/types";
3
- import { HonoEnv } from "../types.js";
3
+ import { QueryOptions, HonoEnv } from "../types.js";
4
4
  import { type ListLimitOptions } from "./query-parser.js";
5
+ /**
6
+ * The row a single-row write addresses, as its route found it.
7
+ *
8
+ * `/comments/7` and `/posts/1/comments/7` address the same kind of row — a row
9
+ * of `comments` — two ways, and a write to it is one operation whichever way
10
+ * it arrived: the same body checks, the same `If-Match`, the same
11
+ * `Idempotency-Key`, the same answer. It was two pipelines, and the nested one
12
+ * re-listed two of the root's checks by hand and skipped the rest.
13
+ */
14
+ export interface RowAddress {
15
+ /** The collection the row belongs to: what a body is checked against and an `ETag` computed for. */
16
+ collection: CollectionConfig;
17
+ /**
18
+ * The path the driver reads and writes at: the collection's own, or a
19
+ * nested one, which the driver resolves and scopes to its parent row.
20
+ */
21
+ path: string;
22
+ /**
23
+ * Handed to the driver beside `path`. Unset for a nested path, whose
24
+ * collection the driver resolves from the path itself.
25
+ */
26
+ driverCollection?: CollectionConfig;
27
+ /** What a 404 calls the address. */
28
+ name: string;
29
+ }
5
30
  /**
6
31
  * Lightweight REST API generator that leverages existing Rebase DataDriver.
7
32
  * Supports `include` query parameter for eager-loading relations via Drizzle.
@@ -113,13 +138,16 @@ export declare class RestApiGenerator {
113
138
  */
114
139
  private createUnmatchedRoute;
115
140
  /**
116
- * Check API key permissions for a collection operation.
117
- * Throws 403 if the key doesn't have the required permission.
118
- * No-ops if the request is not authenticated via an API key.
141
+ * Check a narrowed credential's data scope for a collection operation:
142
+ * `data:<operation>` on the collection, or unqualified.
143
+ *
144
+ * Throws 403 when it is missing. A person's own session holds the whole
145
+ * data plane — their rows are RLS's to decide — so this only ever refuses
146
+ * an API key or a token.
119
147
  */
120
148
  private enforceApiKeyPermission;
121
149
  /**
122
- * API key permission check for nested paths.
150
+ * Data-scope check for nested paths.
123
151
  *
124
152
  * The operation lands on the collection the path addresses — the target
125
153
  * of its last relation — so that is the collection the key must hold the
@@ -260,7 +288,7 @@ export declare class RestApiGenerator {
260
288
  * and a tag compared against a read that hides it compares against
261
289
  * nothing.
262
290
  */
263
- private rowForETag;
291
+ static rowForETag(driver: DataDriver, address: RowAddress, id: string, alreadyRead: Record<string, unknown> | undefined, withDeleted?: QueryOptions["withDeleted"]): Promise<Record<string, unknown> | undefined>;
264
292
  /**
265
293
  * `GET /:id`, at a row's own address or through a parent: the row as the
266
294
  * query asked for it, and the `ETag` naming its version.
@@ -272,7 +300,10 @@ export declare class RestApiGenerator {
272
300
  * relation was a 412. A narrowed read therefore takes its tag from
273
301
  * {@link rowForETag}, the read the write routes make.
274
302
  */
275
- private readRow;
303
+ static readRow(driver: DataDriver, address: RowAddress, id: string, queryOptions: QueryOptions): Promise<{
304
+ row: Record<string, unknown>;
305
+ etag: string | undefined;
306
+ } | undefined>;
276
307
  /**
277
308
  * Answer a bulk write, honouring `Prefer: return=minimal`.
278
309
  *
@@ -344,13 +375,16 @@ export declare class RestApiGenerator {
344
375
  * @param collectionPath the path to read — a nested listing passes its own
345
376
  * `parent/:id/child` path, which the driver resolves.
346
377
  */
347
- private readPage;
378
+ static readPage(driver: DataDriver, collection: CollectionConfig, queryOptions: QueryOptions, searchString?: string, searchExplain?: boolean, collectionPath?: string): Promise<{
379
+ rows: Record<string, unknown>[];
380
+ meta: Record<string, unknown>;
381
+ }>;
348
382
  /**
349
383
  * Fetch raw collection data without Entity wrapper (fallback for non-Postgres)
350
384
  */
351
- private fetchRawCollection;
385
+ static fetchRawCollection(driver: DataDriver, collection: CollectionConfig, queryOptions: QueryOptions, searchString?: string, searchExplain?: boolean, collectionPath?: string, startAfter?: Record<string, unknown>): Promise<Record<string, unknown>[]>;
352
386
  /**
353
387
  * Count raw entities for a collection
354
388
  */
355
- private countRawEntities;
389
+ static countRawEntities(driver: DataDriver, collection: CollectionConfig, queryOptions: QueryOptions, searchString?: string, collectionPath?: string): Promise<number>;
356
390
  }
@@ -1,4 +1,4 @@
1
- import { CollectionConfig } from "@rebasepro/types";
1
+ import { CollectionConfig, type IncludeSpec } from "@rebasepro/types";
2
2
  import { type FieldViewer } from "@rebasepro/common";
3
3
  /**
4
4
  * Refuse a write naming a field this caller may not set.
@@ -151,7 +151,7 @@ export declare function assertWriteValuesValid(values: Record<string, unknown>,
151
151
  * assuming one.
152
152
  */
153
153
  export declare function projectResponseFields<T extends Record<string, unknown>>(rows: T[], fields: readonly string[] | undefined, collection: CollectionConfig, options?: {
154
- include?: readonly string[];
154
+ include?: IncludeSpec;
155
155
  }): T[];
156
156
  /**
157
157
  * Both write checks, as one call, for a transport that is not the REST router.
@@ -31,8 +31,24 @@ export type HonoEnv = {
31
31
  */
32
32
  recipientEmail?: string;
33
33
  driver?: DataDriver;
34
- /** Set when the request is authenticated via a Service API Key. */
34
+ /** Set when the request is authenticated with an API key (`rk_`). */
35
35
  apiKey?: ApiKeyMasked;
36
+ /**
37
+ * What the caller may do, when its credential is narrower than its
38
+ * person — an API key or an MCP token. Absent for a person's own
39
+ * session, who holds what their roles hold. Read it through
40
+ * `callerScopes` / `hasScope`, which fill in that second case.
41
+ */
42
+ scopes?: string[];
43
+ /**
44
+ * Who asked, when an administrator's request runs as another user
45
+ * (`x-rebase-impersonate`). `user` and `driver` are then the
46
+ * impersonated user's; this is the only place the administrator
47
+ * remains. See `auth/impersonation.ts`.
48
+ */
49
+ impersonator?: {
50
+ uid: string;
51
+ };
36
52
  /** Unique request correlation ID (generated or propagated from X-Request-ID header). */
37
53
  requestId?: string;
38
54
  /**
@@ -2,8 +2,8 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import "./src-vkcwKXbT.js";
6
- import { i as nestAdminPropertyKeys, r as nestAdminCollectionKeys } from "./admin_block-DxKLmdiv.js";
5
+ import "./src-CatHFUym.js";
6
+ import { a as nestCollectionPatchPaths, l as nestAdminCollectionKeys, n as collectionPatchProblems, o as runtimeOnlyKeyIn, u as nestAdminPropertyKeys } from "./collection_patch-BRu-BvDv.js";
7
7
  import * as fs$1 from "fs";
8
8
  import * as path$1 from "path";
9
9
  import { IndentationText, Node, Project, SyntaxKind } from "ts-morph";
@@ -130,6 +130,26 @@ var AstSchemaEditor = class AstSchemaEditor {
130
130
  if (!resolved.startsWith(this.collectionsDir + path$1.sep) && resolved !== this.collectionsDir) throw new Error("Path traversal detected: resolved path is outside the collections directory.");
131
131
  return resolved;
132
132
  }
133
+ /**
134
+ * Bring the in-memory project back in line with the disk.
135
+ *
136
+ * The source-only editor builds ONE of these at boot and serves every
137
+ * request with it, and ts-morph reads a file once and then trusts its
138
+ * copy. `project.save()` writes that copy back whole, so anything that
139
+ * reached the disk in between — the live editor's committed change (it
140
+ * builds a fresh editor per request), or the developer's own edit in the
141
+ * IDE — was overwritten by the boot-time copy plus this edit. In `rebase
142
+ * dev` the tsx-watch restart usually closed the window; outside watch mode
143
+ * the loss was permanent.
144
+ *
145
+ * Called at the top of every public method, so each edit applies to what
146
+ * is on disk now.
147
+ */
148
+ syncWithDisk() {
149
+ for (const file of this.project.getSourceFiles()) if (!fs$1.existsSync(file.getFilePath())) this.project.removeSourceFile(file);
150
+ else file.refreshFromFileSystemSync();
151
+ if (fs$1.existsSync(this.collectionsDir)) this.project.addSourceFilesAtPaths(`${this.collectionsDir}/**/*.ts`);
152
+ }
133
153
  getCollectionFile(collectionId) {
134
154
  const safeId = this.sanitizeCollectionId(collectionId);
135
155
  const filePath = this.safePath(`${safeId}.ts`);
@@ -212,6 +232,39 @@ var AstSchemaEditor = class AstSchemaEditor {
212
232
  static isPlainObject(value) {
213
233
  return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof RawExpression);
214
234
  }
235
+ /**
236
+ * The field that identifies each element of an array of objects, so an
237
+ * old element can be found again in the new array.
238
+ *
239
+ * Arrays travel whole (see `collection_patch.ts`), and an element's
240
+ * position is not its identity — adding an entity action at the front
241
+ * shifts every other one. `key`, `id`, `relationName`, `name`: the first
242
+ * one every new element carries, distinct, wins.
243
+ */
244
+ static identityField(items) {
245
+ for (const field of [
246
+ "key",
247
+ "id",
248
+ "relationName",
249
+ "name",
250
+ "slug"
251
+ ]) {
252
+ const values = items.map((item) => AstSchemaEditor.isPlainObject(item) ? item[field] : void 0);
253
+ if (values.every((value) => typeof value === "string" || typeof value === "number") && new Set(values).size === values.length) return field;
254
+ }
255
+ }
256
+ /** The old array's object elements, keyed by `field`'s literal value. */
257
+ oldElementsBy(oldArray, field) {
258
+ const byKey = /* @__PURE__ */ new Map();
259
+ const array = oldArray.asKind(SyntaxKind.ArrayLiteralExpression);
260
+ for (const element of array?.getElements() ?? []) {
261
+ const object = element.asKind(SyntaxKind.ObjectLiteralExpression);
262
+ const value = object ? this.initializerOf(object, field) : void 0;
263
+ const literal = value?.asKind(SyntaxKind.StringLiteral)?.getLiteralValue() ?? value?.asKind(SyntaxKind.NoSubstitutionTemplateLiteral)?.getLiteralValue() ?? value?.asKind(SyntaxKind.NumericLiteral)?.getText();
264
+ if (object && literal !== void 0) byKey.set(String(literal), object);
265
+ }
266
+ return byKey;
267
+ }
215
268
  convertJsonToAstString(obj, indentLevel = 0, oldAstNode) {
216
269
  const indentStr = " ";
217
270
  const indent = indentStr.repeat(indentLevel);
@@ -222,14 +275,17 @@ var AstSchemaEditor = class AstSchemaEditor {
222
275
  if (typeof obj === "number" || typeof obj === "boolean") return String(obj);
223
276
  if (Array.isArray(obj)) {
224
277
  if (obj.length === 0) return "[]";
225
- return `[\n${innerIndent}${obj.map((item) => this.convertJsonToAstString(item, indentLevel + 1)).join(`,\n${innerIndent}`)}\n${indent}]`;
278
+ const field = oldAstNode ? AstSchemaEditor.identityField(obj) : void 0;
279
+ const old = oldAstNode && field ? this.oldElementsBy(oldAstNode, field) : void 0;
280
+ return `[\n${innerIndent}${obj.map((item) => this.convertJsonToAstString(item, indentLevel + 1, old && field && AstSchemaEditor.isPlainObject(item) ? old.get(String(item[field])) : void 0)).join(`,\n${innerIndent}`)}\n${indent}]`;
226
281
  }
227
282
  if (typeof obj === "object") {
228
283
  const record = obj;
229
284
  const keys = Object.keys(record);
285
+ const oldObject = oldAstNode?.asKind(SyntaxKind.ObjectLiteralExpression);
230
286
  const preservedProps = [];
231
- if (oldAstNode) {
232
- const oldProps = oldAstNode.getProperties();
287
+ if (oldObject) {
288
+ const oldProps = oldObject.getProperties();
233
289
  for (const oldProp of oldProps) if (oldProp.isKind(SyntaxKind.PropertyAssignment)) {
234
290
  let name = oldProp.getNameNode().getText();
235
291
  if (name.startsWith("\"") && name.endsWith("\"")) name = name.slice(1, -1);
@@ -247,9 +303,9 @@ var AstSchemaEditor = class AstSchemaEditor {
247
303
  return `{\n${innerIndent}${[...keys.map((key) => {
248
304
  const keyStr = AstSchemaEditor.quoteKey(key);
249
305
  let childAstNode;
250
- if (oldAstNode && AstSchemaEditor.isPlainObject(record[key])) {
251
- const oldProp = this.findProperty(oldAstNode, key);
252
- if (oldProp && oldProp.isKind(SyntaxKind.PropertyAssignment)) childAstNode = oldProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
306
+ if (oldObject && (AstSchemaEditor.isPlainObject(record[key]) || Array.isArray(record[key]))) {
307
+ const oldProp = this.findProperty(oldObject, key);
308
+ if (oldProp && oldProp.isKind(SyntaxKind.PropertyAssignment)) childAstNode = oldProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression) ?? oldProp.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);
253
309
  }
254
310
  return `${keyStr}: ${this.convertJsonToAstString(record[key], indentLevel + 1, childAstNode)}`;
255
311
  }), ...preservedProps].join(`,\n${innerIndent}`)}\n${indent}}`;
@@ -296,6 +352,7 @@ var AstSchemaEditor = class AstSchemaEditor {
296
352
  else this.project.removeSourceFile(file);
297
353
  }
298
354
  async saveProperty(collectionId, propertyKey, propertyConfig) {
355
+ this.syncWithDisk();
299
356
  try {
300
357
  await this.writeProperty(collectionId, propertyKey, propertyConfig);
301
358
  } catch (err) {
@@ -330,6 +387,7 @@ var AstSchemaEditor = class AstSchemaEditor {
330
387
  }
331
388
  }
332
389
  async deleteProperty(collectionId, propertyKey) {
390
+ this.syncWithDisk();
333
391
  const propertiesProp = this.requireCollectionObject(collectionId).getProperty("properties");
334
392
  if (propertiesProp) {
335
393
  const propsObj = propertiesProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
@@ -356,6 +414,9 @@ var AstSchemaEditor = class AstSchemaEditor {
356
414
  * default, which in the scaffold is `access: "public"`.
357
415
  */
358
416
  async saveCollection(collectionId, collectionData, options = {}) {
417
+ this.syncWithDisk();
418
+ const runtimeOnly = runtimeOnlyKeyIn(collectionData);
419
+ if (runtimeOnly) throw new Error(`Refusing to write "${collectionId}": it holds "${runtimeOnly}", which the runtime adds to a collection it has loaded and a collection file must not hold. Save what changed instead.`);
359
420
  try {
360
421
  await this.writeCollection(collectionId, collectionData, options);
361
422
  } catch (err) {
@@ -363,6 +424,180 @@ var AstSchemaEditor = class AstSchemaEditor {
363
424
  throw err;
364
425
  }
365
426
  }
427
+ /**
428
+ * Write what changed about a collection, and nothing else.
429
+ *
430
+ * The patch is the difference between the collection the panel loaded and
431
+ * the one it is saving (`diffCollections` in `@rebasepro/types`), so it
432
+ * names only keys the person changed. Each is written where it is; every
433
+ * other byte of the file — imports, comments, formatting, handlers,
434
+ * properties shared from another module — is left as it was.
435
+ *
436
+ * A key whose value in the file is code — `status: statusProperty`,
437
+ * `enum: LOCALE_ENUM`, a spread — is not overwritten with the JSON the
438
+ * panel saw of it, which is what the whole-collection save did. The edit
439
+ * is refused, naming the code, so it can be made where that code lives.
440
+ *
441
+ * All or nothing: a refused operation leaves the file as it was, including
442
+ * the operations before it.
443
+ */
444
+ async applyPatch(collectionId, patch) {
445
+ this.syncWithDisk();
446
+ const problems = collectionPatchProblems(patch);
447
+ if (problems.length > 0) throw new Error(`Refusing to edit "${collectionId}": ${problems.join(" ")}`);
448
+ try {
449
+ await this.writePatch(collectionId, nestCollectionPatchPaths(patch));
450
+ } catch (err) {
451
+ this.forgetUnsaved(collectionId);
452
+ throw err;
453
+ }
454
+ }
455
+ async writePatch(collectionId, patch) {
456
+ this.requireCollectionObject(collectionId);
457
+ const file = this.getCollectionFile(collectionId);
458
+ for (const op of patch) this.applyPatchOp(collectionId, file, this.requireCollectionObject(collectionId), op);
459
+ await this.project.save();
460
+ }
461
+ applyPatchOp(collectionId, file, collectionObj, op) {
462
+ const { path: keys } = op;
463
+ const dotted = (end) => keys.slice(0, end).join(".");
464
+ let target = collectionObj;
465
+ for (let depth = 0; depth < keys.length - 1; depth++) {
466
+ const key = keys[depth];
467
+ const member = this.findMember(target, key);
468
+ if (!member) {
469
+ const spread = this.spreadIn(target);
470
+ if (spread) throw this.codeRefusal(collectionId, file, dotted(depth + 1), spread, "comes from");
471
+ if (op.op === "remove") return;
472
+ target = target.addPropertyAssignment({
473
+ name: AstSchemaEditor.quoteKey(key),
474
+ initializer: "{}"
475
+ }).getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);
476
+ continue;
477
+ }
478
+ const value = member.isKind(SyntaxKind.PropertyAssignment) ? AstSchemaEditor.unwrapExpression(member.getInitializer()) : void 0;
479
+ const next = value?.asKind(SyntaxKind.ObjectLiteralExpression);
480
+ if (!next) throw this.codeRefusal(collectionId, file, dotted(depth + 1), value ?? member, "is");
481
+ target = next;
482
+ }
483
+ const key = keys[keys.length - 1];
484
+ const member = this.findMember(target, key);
485
+ if (op.op === "remove") {
486
+ if (member) {
487
+ member.remove();
488
+ return;
489
+ }
490
+ const spread = this.spreadIn(target);
491
+ if (spread) throw this.codeRefusal(collectionId, file, dotted(keys.length), spread, "comes from");
492
+ return;
493
+ }
494
+ if (keys.length === 1 && key === "relations") {
495
+ this.writeRelations(collectionId, file, collectionObj, op.value);
496
+ this.findMember(collectionObj, "relations")?.formatText();
497
+ return;
498
+ }
499
+ const old = member?.isKind(SyntaxKind.PropertyAssignment) ? member.getInitializer() : void 0;
500
+ if (member && (!old || !AstSchemaEditor.isLiteralValue(old))) throw this.codeRefusal(collectionId, file, dotted(keys.length), old ?? member, "is");
501
+ if (old?.isKind(SyntaxKind.ArrayLiteralExpression)) {
502
+ const code = old.getElements().find((element) => !AstSchemaEditor.isLiteralValue(element));
503
+ if (code) throw this.codeRefusal(collectionId, file, dotted(keys.length), code, "holds");
504
+ }
505
+ const value = this.patchValueAsSource(collectionId, file, keys, op.value, old);
506
+ const text = this.convertJsonToAstString(value, 0, old);
507
+ (member?.isKind(SyntaxKind.PropertyAssignment) ? member.setInitializer(text) : target.addPropertyAssignment({
508
+ name: AstSchemaEditor.quoteKey(key),
509
+ initializer: text
510
+ })).formatText();
511
+ }
512
+ /**
513
+ * A patched value with every relation target it carries turned back into
514
+ * source — `() => xCollection` plus its import — according to where the
515
+ * path lands: a relation's `target`, a relation, a property, or a map of
516
+ * properties.
517
+ */
518
+ patchValueAsSource(collectionId, file, keys, value, old) {
519
+ let position = "collection";
520
+ for (const key of keys) switch (position) {
521
+ case "collection":
522
+ position = key === "properties" ? "properties" : "other";
523
+ break;
524
+ case "properties":
525
+ position = "property";
526
+ break;
527
+ case "property":
528
+ position = key === "properties" ? "properties" : key === "of" ? "property" : key === "oneOf" ? "oneOf" : key === "relation" ? "relation" : "other";
529
+ break;
530
+ case "oneOf":
531
+ position = key === "properties" ? "properties" : "other";
532
+ break;
533
+ case "relation":
534
+ if (key === "target" && typeof value === "string" && value.trim().length > 0) {
535
+ const trimmed = value.trim();
536
+ return new RawExpression(ARROW_TO_IDENTIFIER.test(trimmed) ? trimmed : this.targetThunk(file, trimmed));
537
+ }
538
+ position = "other";
539
+ break;
540
+ default: position = "other";
541
+ }
542
+ const oldObject = old?.asKind(SyntaxKind.ObjectLiteralExpression);
543
+ const where = keys.join(".");
544
+ if (position === "property") return this.propertyRelationTargetsAsSource(collectionId, file, value, oldObject, where);
545
+ if (position === "properties") return this.relationTargetsAsSource(collectionId, file, value, oldObject, where);
546
+ if (position === "relation" && AstSchemaEditor.isPlainObject(value)) {
547
+ const wrapped = this.propertyRelationTargetsAsSource(collectionId, file, {
548
+ type: "relation",
549
+ relation: value
550
+ }, oldObject ? void 0 : void 0, where);
551
+ const relation = AstSchemaEditor.isPlainObject(wrapped) ? wrapped.relation : value;
552
+ if (AstSchemaEditor.isPlainObject(relation) && !("target" in relation) && !(oldObject && this.findProperty(oldObject, "target"))) throw new Error(`Relation "${where}" on collection "${collectionId}" has no target collection. Pick one before saving.`);
553
+ return relation;
554
+ }
555
+ return value;
556
+ }
557
+ /** A member of an object literal by name: an assignment, a shorthand, a method. */
558
+ findMember(obj, name) {
559
+ return obj.getProperties().find((member) => {
560
+ if (member.isKind(SyntaxKind.SpreadAssignment)) return false;
561
+ const memberName = member.getName();
562
+ return memberName === name || memberName === JSON.stringify(name) || memberName === `'${name}'`;
563
+ });
564
+ }
565
+ spreadIn(obj) {
566
+ return obj.getProperties().find((member) => member.isKind(SyntaxKind.SpreadAssignment));
567
+ }
568
+ /** `x as const`, `x satisfies T`, `(x)` — the value inside. */
569
+ static unwrapExpression(node) {
570
+ if (!node) return void 0;
571
+ if (Node.isAsExpression(node) || Node.isSatisfiesExpression(node) || Node.isParenthesizedExpression(node)) return AstSchemaEditor.unwrapExpression(node.getExpression());
572
+ return node;
573
+ }
574
+ /**
575
+ * Whether a value in the file is data the panel's JSON fully describes —
576
+ * a literal — rather than code it saw only the result of.
577
+ */
578
+ static isLiteralValue(node) {
579
+ const value = AstSchemaEditor.unwrapExpression(node);
580
+ if (!value) return false;
581
+ switch (value.getKind()) {
582
+ case SyntaxKind.ObjectLiteralExpression:
583
+ case SyntaxKind.ArrayLiteralExpression:
584
+ case SyntaxKind.StringLiteral:
585
+ case SyntaxKind.NoSubstitutionTemplateLiteral:
586
+ case SyntaxKind.NumericLiteral:
587
+ case SyntaxKind.TrueKeyword:
588
+ case SyntaxKind.FalseKeyword:
589
+ case SyntaxKind.NullKeyword: return true;
590
+ case SyntaxKind.PrefixUnaryExpression: return value.asKindOrThrow(SyntaxKind.PrefixUnaryExpression).getOperand().isKind(SyntaxKind.NumericLiteral);
591
+ case SyntaxKind.Identifier: return value.getText() === "undefined";
592
+ default: return false;
593
+ }
594
+ }
595
+ /** "`properties.status` is `statusProperty` in posts.ts…" */
596
+ codeRefusal(collectionId, file, where, code, verb) {
597
+ const text = code.getText();
598
+ const shown = text.length > 60 ? `${text.slice(0, 57)}…` : text;
599
+ return /* @__PURE__ */ new Error(`\`${where}\` ${verb} \`${shown}\` in ${path$1.basename(file.getFilePath())}, which is code the editor cannot change without losing what it does. Change "${collectionId}" there instead.`);
600
+ }
366
601
  async writeCollection(collectionId, collectionData, options) {
367
602
  const partial = options.partial === true;
368
603
  let file = this.getCollectionFile(collectionId);
@@ -554,12 +789,75 @@ var AstSchemaEditor = class AstSchemaEditor {
554
789
  if (expr && expr.getKind() === SyntaxKind.Identifier) return expr.getText();
555
790
  for (const varDecl of file.getVariableDeclarations()) if (this.unwrapCollectionObject(varDecl.getInitializer())) return varDecl.getName();
556
791
  }
792
+ /**
793
+ * Delete a collection's file, and take it out of `index.ts`.
794
+ *
795
+ * This used to unlink `<slug>.ts` and stop. Every scaffold's `index.ts`
796
+ * imports every collection, so the next boot failed for the whole project
797
+ * ("Cannot find module …/tags"), and a collection another one linked to
798
+ * took that one down with it. Now:
799
+ *
800
+ * - a file any other module imports is refused, naming the importers — a
801
+ * relation to it has to go first, and that is a change the person makes;
802
+ * - `index.ts`'s import of it is removed, and so is each place it is listed
803
+ * in an array; any other use there is refused, naming the line;
804
+ * - the file is deleted.
805
+ *
806
+ * Only the source. The table and its rows are not touched.
807
+ *
808
+ * Returns what changed, as absolute paths, so the caller can commit it.
809
+ */
557
810
  async deleteCollection(collectionId) {
558
- const file = this.getCollectionFile(collectionId);
559
- if (file) file.deleteImmediatelySync();
811
+ this.syncWithDisk();
812
+ const target = this.getCollectionFile(collectionId);
813
+ if (!target) throw new Error(`Collection "${collectionId}" has no file at ${path$1.join(this.collectionsDir, `${collectionId}.ts`)}.`);
814
+ const targetPath = target.getFilePath();
815
+ const indexPath = path$1.join(this.collectionsDir, "index.ts");
816
+ const importers = this.project.getSourceFiles().filter((file) => file !== target && this.declarationsOf(file, targetPath).length > 0);
817
+ const others = importers.filter((file) => file.getFilePath() !== indexPath);
818
+ if (others.length > 0) throw new Error(`Cannot delete "${collectionId}": ${others.map((file) => path$1.basename(file.getFilePath())).join(", ")} ${others.length === 1 ? "imports" : "import"} it — a relation to it, most likely. Remove that first; deleting the file would stop every collection from loading.`);
819
+ const changed = [];
820
+ const index = importers.find((file) => file.getFilePath() === indexPath);
821
+ try {
822
+ if (index) {
823
+ for (const declaration of this.declarationsOf(index, targetPath)) {
824
+ const names = declaration.isKind(SyntaxKind.ImportDeclaration) ? [declaration.getDefaultImport()?.getText(), ...declaration.getNamedImports().map((named) => (named.getAliasNode() ?? named.getNameNode()).getText())].filter((name) => Boolean(name)) : [];
825
+ for (const name of names) {
826
+ const uses = index.getDescendantsOfKind(SyntaxKind.Identifier).filter((identifier) => identifier.getText() === name && !identifier.getFirstAncestorByKind(SyntaxKind.ImportDeclaration));
827
+ for (const use of uses) {
828
+ const array = use.getParentIfKind(SyntaxKind.ArrayLiteralExpression);
829
+ if (!array) throw new Error(`Cannot delete "${collectionId}": index.ts uses \`${name}\` at line ${use.getStartLineNumber()} in a way the editor cannot remove. Remove it there first.`);
830
+ array.removeElement(use);
831
+ }
832
+ }
833
+ declaration.remove();
834
+ }
835
+ changed.push(index.getFilePath());
836
+ }
837
+ target.delete();
838
+ await this.project.save();
839
+ } catch (err) {
840
+ if (index && !index.isSaved()) index.refreshFromFileSystemSync();
841
+ this.syncWithDisk();
842
+ throw err;
843
+ }
844
+ return {
845
+ deleted: targetPath,
846
+ changed
847
+ };
848
+ }
849
+ /** The import and export declarations in `file` whose relative specifier resolves to `targetPath`. */
850
+ declarationsOf(file, targetPath) {
851
+ const stem = (absolute) => absolute.replace(/\.(ts|tsx|js|mjs|cjs)$/, "");
852
+ const target = stem(targetPath);
853
+ return [...file.getImportDeclarations(), ...file.getExportDeclarations()].filter((declaration) => {
854
+ const specifier = declaration.getModuleSpecifierValue();
855
+ if (!specifier || !specifier.startsWith(".")) return false;
856
+ return stem(path$1.resolve(path$1.dirname(file.getFilePath()), specifier)) === target;
857
+ });
560
858
  }
561
859
  };
562
860
  //#endregion
563
861
  export { AstSchemaEditor };
564
862
 
565
- //# sourceMappingURL=ast-schema-editor-Mvr50v_S.js.map
863
+ //# sourceMappingURL=ast-schema-editor-CWqS_sLJ.js.map