@rebasepro/codegen 0.12.1-canary.gf5f1d39 → 0.13.1-canary.g06dbe5b

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.
package/README.md CHANGED
@@ -8,10 +8,10 @@ Generates typed TypeScript definitions from Rebase collection definitions — pr
8
8
  pnpm add @rebasepro/codegen
9
9
  ```
10
10
 
11
- ### Peer Dependencies
11
+ ### Dependencies
12
12
 
13
- - `@rebasepro/common`
14
- - `@rebasepro/types`
13
+ - `@rebasepro/common` — a runtime dependency (`resolveCollectionRelations`)
14
+ - `@rebasepro/types` — a peer dependency (types only)
15
15
 
16
16
  ## What This Package Does
17
17
 
@@ -29,20 +29,55 @@ This is typically invoked via the CLI (`npx rebase generate-sdk`) rather than ca
29
29
  | `GenerateSDKOptions` | Interface | `{ includeReadme?: boolean }` (default: `true`) |
30
30
  | `toPascalCase` | Function | `"my_collection"` → `"MyCollection"` |
31
31
  | `toCamelCase` | Function | `"my_collection"` → `"myCollection"` |
32
- | `toSafeIdentifier` | Function | Converts slugs to valid JS identifiers |
32
+ | `toSafeIdentifier` | Function | Converts a **slug** to a valid JS identifier (collection accessors only — never column names) |
33
33
  | `indent` | Function | Indent text by N spaces |
34
+ | `CodegenError` | Class | Thrown for a schema that cannot be expressed as valid TypeScript |
34
35
 
35
36
  ## Generated Output
36
37
 
37
38
  `generateSDK()` produces:
38
39
 
39
- 1. **`database.types.ts`** — A `Database` interface where each collection slug is a key containing:
40
- - `Row` Full snapshot type (read operations)
41
- - `Insert` Type for creating snapshots (auto-ID fields are optional)
42
- - `Update` All-optional partial type for updates
40
+ 1. **`database.types.ts`** — A `Database` interface keyed by each collection's
41
+ *accessor* (`my-notes` `myNotes`, the property name on `client.data`),
42
+ alongside a `collectionsDictionary` const mapping each accessor back to the
43
+ slug the wire uses. Each entry contains:
44
+ - `Row` — what a read serves. Column names are the **real** ones, unchanged:
45
+ a `created_at` column is `row.created_at`. Nullable columns are `T | null`,
46
+ the primary key is always present, relations appear only when `include`
47
+ names them, and `excludeFromApi` columns are absent.
48
+ - `Insert` — what `create()` accepts. Server-assigned ids are optional; a
49
+ `belongsTo` target may be named either way (`{ author: 5 }` or
50
+ `{ author_id: 5 }`); `excludeFromApi` columns are absent here too.
51
+ - `Update` — what `update()` accepts. Everything optional, primary key
52
+ omitted, `excludeFromApi` columns absent.
53
+
54
+ `excludeFromApi` means one thing in all three: the API surface does not mention
55
+ the property, in either direction. The server still accepts such a field on a
56
+ write — this is what the generated types describe, not a new enforcement point —
57
+ but nothing generated names it, so a generated client cannot offer a password
58
+ hash as something to read, filter or send.
43
59
 
44
60
  2. **`README.md`** — Usage instructions (opt out with `includeReadme: false`)
45
61
 
62
+ ### Names
63
+
64
+ Only the collection accessor is transformed. Column names are emitted verbatim,
65
+ quoted when they are not valid identifiers (`"user id"?: string | null`), because
66
+ `where` and `orderBy` are keyed off `Row` — a renamed column makes the correct
67
+ filter fail to compile and the wrong one fail at runtime.
68
+
69
+ Generation **fails** rather than emitting a broken file when two slugs would
70
+ produce the same accessor: the interface would not compile, and
71
+ `collectionsDictionary` would silently keep only one, routing a collection's
72
+ reads to another's table.
73
+
74
+ ### Untrusted schemas
75
+
76
+ `rebase generate-sdk --from <url>` generates from a remote contract, so slugs,
77
+ column names and enum values come from that server. Every one of them is emitted
78
+ as an escaped literal — untrusted input cannot add a declaration to the generated
79
+ file. There is a test that asserts exactly this.
80
+
46
81
  ### Property Type Mapping
47
82
 
48
83
  | Rebase Type | TypeScript Type |
@@ -53,8 +88,8 @@ This is typically invoked via the CLI (`npx rebase generate-sdk`) rather than ca
53
88
  | `date` | `string` (ISO 8601) |
54
89
  | `geopoint` | `{ latitude: number; longitude: number }` |
55
90
  | `reference` | `string \| number` |
56
- | `relation` | Relation object type |
57
- | `map` | Inline object type or `Record<string, any>` |
91
+ | `relation` | The target's own `Row`, inlined (what `include` serves) |
92
+ | `map` | Inline object type or `Record<string, unknown>` |
58
93
  | `array` | `Array<T>` with inferred inner type |
59
94
  | `vector` | `number[]` |
60
95
  | `binary` | `string` |
@@ -1,2 +1,13 @@
1
1
  import { CollectionConfig } from "@rebasepro/types";
2
- export declare function generateTypedefs(collections: CollectionConfig[]): string;
2
+ /**
3
+ * A schema that cannot be expressed as a valid TypeScript file.
4
+ *
5
+ * Thrown rather than emitted. The generator used to concatenate whatever it was
6
+ * given, so a slug that collided with another one, or that was not an
7
+ * identifier, produced a file that either failed to compile or — worse —
8
+ * compiled while quietly routing one collection to another's slug.
9
+ */
10
+ export declare class CodegenError extends Error {
11
+ constructor(message: string);
12
+ }
13
+ export declare function generateTypedefs(input: CollectionConfig[]): string;
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * Generates a purely typed Typescript database definition.
5
5
  */
6
6
  import { CollectionConfig } from "@rebasepro/types";
7
- export { generateTypedefs } from "./generate-types";
7
+ export { generateTypedefs, CodegenError } from "./generate-types";
8
8
  export { toPascalCase, toCamelCase, toSafeIdentifier, indent } from "./utils";
9
9
  export interface GeneratedFile {
10
10
  /** Relative file path within the output directory */
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import { resolveCollectionRelations } from "@rebasepro/common";
1
+ import { findRelation, resolveCollectionRelations, sortCollectionsBySlug } from "@rebasepro/common";
2
2
  //#region src/utils.ts
3
3
  /**
4
4
  * Utility functions for the SDK generator
@@ -6,9 +6,17 @@ import { resolveCollectionRelations } from "@rebasepro/common";
6
6
  /**
7
7
  * Convert a slug/snake_case string to PascalCase
8
8
  * e.g. "private_notes" → "PrivateNotes"
9
+ *
10
+ * Capitals already inside a word are meaningful and are kept: lowercasing the
11
+ * tail of every chunk turned "TestEntities" into "Testentities", which is what
12
+ * ended up in the generated type names. SHOUTING_CASE is the one shape where
13
+ * the tail is not meaningful, so it is folded down.
9
14
  */
10
15
  function toPascalCase(str) {
11
- return str.split(/[_\-\s]+/).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
16
+ return str.split(/[_\-\s]+/).filter(Boolean).map((word) => {
17
+ const rest = /^[A-Z0-9]+$/.test(word) ? word.slice(1).toLowerCase() : word.slice(1);
18
+ return word.charAt(0).toUpperCase() + rest;
19
+ }).join("");
12
20
  }
13
21
  /**
14
22
  * Convert a slug/snake_case string to camelCase
@@ -35,16 +43,70 @@ function indent(text, spaces) {
35
43
  }
36
44
  //#endregion
37
45
  //#region src/generate-types.ts
46
+ /**
47
+ * A schema that cannot be expressed as a valid TypeScript file.
48
+ *
49
+ * Thrown rather than emitted. The generator used to concatenate whatever it was
50
+ * given, so a slug that collided with another one, or that was not an
51
+ * identifier, produced a file that either failed to compile or — worse —
52
+ * compiled while quietly routing one collection to another's slug.
53
+ */
54
+ var CodegenError = class extends Error {
55
+ constructor(message) {
56
+ super(message);
57
+ this.name = "CodegenError";
58
+ }
59
+ };
60
+ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
61
+ /**
62
+ * A property name for the emitted TypeScript: verbatim when it is a valid
63
+ * identifier, quoted otherwise.
64
+ *
65
+ * Every key that reaches the output goes through here. Column names are not
66
+ * required to be identifiers — `"order"`, `"user id"`, a quoted Postgres
67
+ * identifier — and the previous behaviour of camel-casing them into shape
68
+ * renamed the column in the type while the wire kept the original, so the
69
+ * generated `Row` described fields that did not exist.
70
+ */
71
+ function emitKey(key) {
72
+ return IDENTIFIER.test(key) ? key : JSON.stringify(key);
73
+ }
74
+ /**
75
+ * A string literal, escaped.
76
+ *
77
+ * `"${value}"` was the previous form. A value containing a quote closed the
78
+ * literal early, which at best broke the file and at worst let a slug from a
79
+ * remote contract inject top-level statements into a file the developer
80
+ * compiles and bundles.
81
+ */
82
+ function emitString(value) {
83
+ return JSON.stringify(value);
84
+ }
85
+ /** The `id`s of an enum declared as an array, an array of `{ id }`, or an object map. */
86
+ function enumIds(raw) {
87
+ if (Array.isArray(raw)) return raw.map((entry) => entry && typeof entry === "object" ? entry.id : entry);
88
+ if (raw && typeof raw === "object") return Object.keys(raw);
89
+ return [];
90
+ }
38
91
  function propertyToTypeScriptType(prop) {
39
92
  switch (prop.type) {
40
93
  case "string": {
41
94
  const sp = prop;
42
- if (sp.enum) return (Array.isArray(sp.enum) ? sp.enum.map((e) => typeof e === "object" ? String(e.id) : String(e)) : Object.keys(sp.enum)).map((v) => `"${v}"`).join(" | ");
95
+ if (sp.enum) {
96
+ const ids = enumIds(sp.enum);
97
+ if (ids.length === 0) return "string";
98
+ return ids.map((v) => emitString(String(v))).join(" | ");
99
+ }
43
100
  return "string";
44
101
  }
45
102
  case "number": {
46
103
  const np = prop;
47
- if (np.enum) return (Array.isArray(np.enum) ? np.enum.map((e) => typeof e === "object" ? String(e.id) : String(e)) : Object.keys(np.enum)).join(" | ");
104
+ if (np.enum) {
105
+ const ids = enumIds(np.enum);
106
+ const numbers = ids.map(Number);
107
+ if (ids.length === 0 || numbers.some((n) => !Number.isFinite(n))) return "number";
108
+ return numbers.map((n) => String(n)).join(" | ");
109
+ }
48
110
  return "number";
49
111
  }
50
112
  case "boolean": return "boolean";
@@ -54,7 +116,12 @@ function propertyToTypeScriptType(prop) {
54
116
  case "relation": return "string | number";
55
117
  case "map": {
56
118
  const mapProp = prop;
57
- if (mapProp.properties) return `{ ${Object.entries(mapProp.properties).map(([k, v]) => `${toSafeIdentifier(k)}: ${propertyToTypeScriptType(v)};`).join(" ")} }`;
119
+ if (mapProp.properties) return `{ ${Object.entries(mapProp.properties).map(([k, v]) => {
120
+ const child = v;
121
+ const optional = !child.validation?.required;
122
+ const type = propertyToTypeScriptType(child);
123
+ return `${emitKey(k)}${optional ? "?" : ""}: ${optional ? `${type} | null` : type};`;
124
+ }).join(" ")} }`;
58
125
  return "Record<string, unknown>";
59
126
  }
60
127
  case "array": {
@@ -88,6 +155,18 @@ function foreignKeyType(relation) {
88
155
  if (!idProp) return "string | number";
89
156
  return idProp[1].type === "number" ? "number" : "string";
90
157
  }
158
+ /** Whether a property is the collection's primary key. */
159
+ function isPrimaryKey(prop) {
160
+ return Boolean(prop.isId);
161
+ }
162
+ /**
163
+ * Whether the server assigns this primary key, so a write does not have to.
164
+ * `true` and `"manual"` both mean the caller supplies it.
165
+ */
166
+ function isAutoAssignedId(prop) {
167
+ const isId = prop.isId;
168
+ return Boolean(isId) && isId !== "manual" && isId !== true;
169
+ }
91
170
  /**
92
171
  * The type an *included* relation arrives as: the target's own row, inlined.
93
172
  *
@@ -100,13 +179,69 @@ function foreignKeyType(relation) {
100
179
  * Falls back to an open record when the target is not part of this generation
101
180
  * run, since there is no `Row` to point at.
102
181
  */
103
- function includedRelationType(relation, knownSlugs) {
182
+ function includedRelationType(relation, accessors) {
104
183
  const slug = resolveTargetCollection(relation)?.slug ?? relation.targetSlug;
105
- const rowType = slug && knownSlugs.has(slug) ? `Database[${JSON.stringify(toSafeIdentifier(slug))}]["Row"]` : "Record<string, unknown>";
184
+ const accessor = slug ? accessors.get(slug) : void 0;
185
+ const rowType = accessor ? `Database[${emitString(accessor)}]["Row"]` : "Record<string, unknown>";
106
186
  return relation.cardinality === "many" ? `Array<${rowType}>` : rowType;
107
187
  }
108
- function generateTypedefs(collections) {
109
- const knownSlugs = new Set(collections.map((c) => c.slug).filter(Boolean));
188
+ /**
189
+ * Map every slug to the property name it is reachable under on `client.data`.
190
+ *
191
+ * The accessor is a safe identifier because `client.data.myNotes` is the point
192
+ * of generating this at all, and `collectionsDictionary` maps it back to the
193
+ * slug the wire uses. Two slugs that safe down to the same identifier cannot
194
+ * both have it: the interface would not compile, and the dictionary — an object
195
+ * literal — would silently keep only the last, routing one collection's reads
196
+ * to the other's table. There is no defensible way to pick, so this refuses.
197
+ */
198
+ function buildAccessors(collections) {
199
+ const accessors = /* @__PURE__ */ new Map();
200
+ const bySafeName = /* @__PURE__ */ new Map();
201
+ for (const collection of collections) {
202
+ const slug = collection.slug;
203
+ if (typeof slug !== "string" || slug.length === 0) throw new CodegenError("A collection has no slug, so it has no name to generate a type for. Every collection needs a unique `slug`.");
204
+ const safe = toSafeIdentifier(slug);
205
+ if (safe.length === 0) throw new CodegenError(`The slug ${emitString(slug)} has no characters that can form a property name, so it cannot be reached as \`client.data.<name>\`. Use a slug containing letters, digits, underscores or dashes.`);
206
+ const existing = bySafeName.get(safe);
207
+ if (existing !== void 0) throw new CodegenError(`The collections ${emitString(existing)} and ${emitString(slug)} both generate the accessor "${safe}", so only one of them could be reached from the generated client and the other's reads would silently go to the wrong table. Rename one of the slugs.`);
208
+ bySafeName.set(safe, slug);
209
+ accessors.set(slug, safe);
210
+ }
211
+ return accessors;
212
+ }
213
+ /** One emitted `key: type;` line, already indented. */
214
+ function line(key, type, optional) {
215
+ return ` ${emitKey(key)}${optional ? "?" : ""}: ${type};`;
216
+ }
217
+ /**
218
+ * The keys `excludeFromApi` takes off the API surface — in *both* directions.
219
+ *
220
+ * `excludeFromApi` means one thing: the API surface does not mention this
221
+ * property. `Row` already honoured that; `Insert` and `Update` deliberately did
222
+ * not, on the reading that the column is stripped from responses rather than
223
+ * from writes. That left the generated types as the one place a password hash
224
+ * was still named, and it invited a client to send one. The server still
225
+ * *accepts* such a field on a write — this describes the surface, it does not
226
+ * add an enforcement point — but nothing generated advertises it.
227
+ *
228
+ * Keyed by the property name *and* by its column name, the same pair the
229
+ * server's `stripExcluded` deletes, so a foreign key or a relation addressed
230
+ * under the column name cannot put the property back.
231
+ */
232
+ function excludedApiKeys(properties) {
233
+ const excluded = /* @__PURE__ */ new Set();
234
+ for (const [key, rawProp] of Object.entries(properties)) {
235
+ const prop = rawProp;
236
+ if (!prop?.excludeFromApi) continue;
237
+ excluded.add(key);
238
+ if (prop.columnName) excluded.add(prop.columnName);
239
+ }
240
+ return excluded;
241
+ }
242
+ function generateTypedefs(input) {
243
+ const collections = sortCollectionsBySlug(input);
244
+ const accessors = buildAccessors(collections);
110
245
  const lines = [
111
246
  "/**",
112
247
  " * This file was auto-generated by Rebase.",
@@ -116,21 +251,27 @@ function generateTypedefs(collections) {
116
251
  "export interface Database {"
117
252
  ];
118
253
  for (const collection of collections) {
119
- toPascalCase(collection.slug);
120
254
  const properties = collection.properties ?? {};
121
255
  let resolvedRelations = {};
122
256
  try {
123
257
  resolvedRelations = resolveCollectionRelations(collection);
124
- } catch {}
125
- lines.push(` ${toSafeIdentifier(collection.slug)}: {`);
258
+ } catch (e) {
259
+ console.warn(`[rebase] Could not resolve the relations of "${collection.slug}", so its generated type has no relation fields and none of their foreign-key columns. This is usually a circular import in the collection files — make sure the target is \`() => otherCollection\` and not evaluated at module load.\n ${e instanceof Error ? e.message : String(e)}`);
260
+ }
261
+ const subcollections = collection.subcollections;
262
+ if (Array.isArray(subcollections) && subcollections.length > 0) console.warn(`[rebase] "${collection.slug}" declares ${subcollections.length} subcollection(s), which are not part of the generated Database: they are reached over a nested path (\`data/${collection.slug}/<id>/<relation>\`), not as a top-level accessor. Register a subcollection as a collection of its own if you want a typed accessor for it.`);
263
+ lines.push(` ${emitKey(accessors.get(collection.slug))}: {`);
126
264
  lines.push(" Row: {");
127
265
  const emittedKeys = /* @__PURE__ */ new Set();
266
+ const excluded = excludedApiKeys(properties);
267
+ for (const key of excluded) emittedKeys.add(key);
128
268
  for (const [key, rawProp] of Object.entries(properties)) {
129
269
  const prop = rawProp;
130
270
  if (prop.type === "relation") continue;
271
+ if (excluded.has(key)) continue;
131
272
  const tsType = propertyToTypeScriptType(prop);
132
- const isRequired = prop.validation?.required;
133
- lines.push(` ${toSafeIdentifier(key)}${isRequired ? "" : "?"}: ${tsType};`);
273
+ const isRequired = Boolean(prop.validation?.required) || isPrimaryKey(prop);
274
+ lines.push(line(key, isRequired ? tsType : `${tsType} | null`, !isRequired));
134
275
  emittedKeys.add(key);
135
276
  }
136
277
  for (const [relKey, relation] of Object.entries(resolvedRelations)) if (relation.kind === "belongsTo" && relation.localKey) {
@@ -138,74 +279,94 @@ function generateTypedefs(collections) {
138
279
  if (emittedKeys.has(fkKey)) continue;
139
280
  const fkType = foreignKeyType(relation);
140
281
  const shadowedByInclude = relKey === fkKey;
141
- const tsType = shadowedByInclude ? `${fkType} | ${includedRelationType(relation, knownSlugs)}` : fkType;
142
- const isRequired = relation.validation?.required && !shadowedByInclude;
143
- lines.push(` ${toSafeIdentifier(fkKey)}${isRequired ? "" : "?"}: ${tsType};`);
282
+ const tsType = shadowedByInclude ? `${fkType} | ${includedRelationType(relation, accessors)}` : fkType;
283
+ const isRequired = Boolean(relation.validation?.required) && !shadowedByInclude;
284
+ lines.push(line(fkKey, isRequired ? tsType : `${tsType} | null`, !isRequired));
144
285
  emittedKeys.add(fkKey);
145
286
  }
146
287
  for (const [key, relation] of Object.entries(resolvedRelations)) {
147
288
  if (emittedKeys.has(key)) continue;
148
- lines.push(` ${toSafeIdentifier(key)}?: ${includedRelationType(relation, knownSlugs)};`);
289
+ lines.push(line(key, includedRelationType(relation, accessors), true));
149
290
  emittedKeys.add(key);
150
291
  }
151
292
  for (const [key, rawProp] of Object.entries(properties)) {
152
293
  if (rawProp.type !== "relation") continue;
153
294
  if (emittedKeys.has(key)) continue;
154
- lines.push(` ${toSafeIdentifier(key)}?: Record<string, unknown>;`);
295
+ lines.push(line(key, "Record<string, unknown>", true));
155
296
  emittedKeys.add(key);
156
297
  }
157
298
  lines.push(" };");
158
299
  lines.push(" Insert: {");
159
300
  emittedKeys.clear();
301
+ for (const key of excluded) emittedKeys.add(key);
160
302
  for (const [key, rawProp] of Object.entries(properties)) {
161
303
  const prop = rawProp;
162
304
  if (prop.type === "relation") continue;
305
+ if (excluded.has(key)) continue;
163
306
  const tsType = propertyToTypeScriptType(prop);
164
- const isRequired = prop.validation?.required;
165
- const typedProp = prop;
166
- const isAutoId = "isId" in prop && typedProp.isId && typedProp.isId !== "manual" && typedProp.isId !== true;
167
- const isOptional = !isRequired || isAutoId;
168
- lines.push(` ${toSafeIdentifier(key)}${isOptional ? "?" : ""}: ${tsType};`);
307
+ const isOptional = !prop.validation?.required || isAutoAssignedId(prop);
308
+ lines.push(line(key, tsType, isOptional));
169
309
  emittedKeys.add(key);
170
310
  }
171
- for (const [relKey, relation] of Object.entries(resolvedRelations)) if (relation.kind === "belongsTo" && relation.localKey) {
172
- const fkKey = relation.localKey;
173
- if (emittedKeys.has(fkKey)) continue;
174
- const fkType = "string | number";
175
- const isRequired = relation.validation?.required;
176
- lines.push(` ${toSafeIdentifier(fkKey)}${isRequired ? "" : "?"}: ${fkType};`);
177
- emittedKeys.add(fkKey);
178
- }
311
+ emitWritableRelations(lines, properties, resolvedRelations, emittedKeys, false);
179
312
  lines.push(" };");
180
313
  lines.push(" Update: {");
181
314
  emittedKeys.clear();
315
+ for (const key of excluded) emittedKeys.add(key);
182
316
  for (const [key, rawProp] of Object.entries(properties)) {
183
317
  const prop = rawProp;
184
318
  if (prop.type === "relation") continue;
185
- const tsType = propertyToTypeScriptType(prop);
186
- lines.push(` ${toSafeIdentifier(key)}?: ${tsType};`);
319
+ if (isPrimaryKey(prop)) continue;
320
+ if (excluded.has(key)) continue;
321
+ lines.push(line(key, propertyToTypeScriptType(prop), true));
187
322
  emittedKeys.add(key);
188
323
  }
189
- for (const [relKey, relation] of Object.entries(resolvedRelations)) if (relation.kind === "belongsTo" && relation.localKey) {
190
- const fkKey = relation.localKey;
191
- if (emittedKeys.has(fkKey)) continue;
192
- lines.push(` ${toSafeIdentifier(fkKey)}?: string | number;`);
193
- emittedKeys.add(fkKey);
194
- }
324
+ emitWritableRelations(lines, properties, resolvedRelations, emittedKeys, true);
195
325
  lines.push(" };");
196
326
  lines.push(" };");
197
327
  }
198
328
  lines.push("}");
199
329
  lines.push("");
200
330
  lines.push("export type CollectionName = keyof Database;");
201
- lines.push("export type CollectionsDictionary = { [K in CollectionName]: K };");
202
331
  lines.push("");
203
332
  lines.push("export const collectionsDictionary = {");
204
- for (const collection of collections) lines.push(` ${toSafeIdentifier(collection.slug)}: "${collection.slug}",`);
333
+ for (const collection of collections) lines.push(` ${emitKey(accessors.get(collection.slug))}: ${emitString(collection.slug)},`);
205
334
  lines.push("} as const;");
206
335
  lines.push("");
336
+ lines.push("export type CollectionsDictionary = typeof collectionsDictionary;");
337
+ lines.push("");
207
338
  return lines.join("\n");
208
339
  }
340
+ /**
341
+ * The two ways a write can name a `belongsTo` target, both of which the server
342
+ * accepts: the foreign-key column itself (`{ author_id: 5 }`, which passes
343
+ * through untouched) and the relation *property* (`{ author: 5 }`, which the
344
+ * write transformer maps onto that column).
345
+ *
346
+ * Only the first was generated, so the documented and idiomatic write shape was
347
+ * a type error.
348
+ *
349
+ * The second form is emitted under the **property key**, not the resolved
350
+ * relation name, because that is what the transformer keys off: it looks the
351
+ * payload key up in `properties` and only treats it as a relation if what it
352
+ * finds there is one. A relation whose `relationName` differs from its property
353
+ * key is reachable as the property and not as the name, so emitting the name
354
+ * would have offered a key that writes to a column that does not exist.
355
+ */
356
+ function emitWritableRelations(lines, properties, resolvedRelations, emittedKeys, allOptional) {
357
+ const emit = (key, relation) => {
358
+ if (emittedKeys.has(key)) return;
359
+ const optional = allOptional || !relation.validation?.required;
360
+ lines.push(line(key, foreignKeyType(relation), optional));
361
+ emittedKeys.add(key);
362
+ };
363
+ for (const relation of Object.values(resolvedRelations)) if (relation.kind === "belongsTo" && relation.localKey) emit(relation.localKey, relation);
364
+ for (const [key, rawProp] of Object.entries(properties)) {
365
+ if (rawProp.type !== "relation") continue;
366
+ const relation = findRelation(resolvedRelations, key);
367
+ if (relation?.kind === "belongsTo" && relation.localKey) emit(key, relation);
368
+ }
369
+ }
209
370
  //#endregion
210
371
  //#region src/index.ts
211
372
  function generateSDK(collections, options = {}) {
@@ -230,25 +391,51 @@ function generateSDK(collections, options = {}) {
230
391
  2. Initialize with your generated types:
231
392
  \`\`\`typescript
232
393
  import { createRebaseClient } from '@rebasepro/client';
233
- import { Database, collectionsDictionary } from './database.types';
394
+ import { collectionsDictionary, type Database } from './database.types';
234
395
 
235
396
  const rebase = createRebaseClient<Database>({
236
397
  baseUrl: 'http://localhost:3001',
398
+ // Maps each accessor back to the slug the wire uses. Without it a
399
+ // hyphenated slug is not resolvable from the property name alone.
237
400
  collections: collectionsDictionary,
238
401
  });
239
402
 
240
- // Both syntax styles are fully typed!
403
+ // Property access is the typed surface: rows, filters and sorts are all
404
+ // checked against the generated Database.
241
405
  const { data: users } = await rebase.data.users.find();
242
406
  console.log(users[0].email); // flat access — no .values wrapper
243
-
244
- const { data: posts } = await rebase.data.collection('posts').find();
245
- console.log(posts[0].title); // just post.title, not post.values.title
246
407
  \`\`\`
408
+
409
+ ## Field names are the ones the API serves
410
+
411
+ The generated \`Row\` uses each column's real name, unchanged — a \`created_at\`
412
+ column is \`row.created_at\`, not \`row.createdAt\`. \`where\` and \`orderBy\` are keyed
413
+ off the same type, so what compiles is what the backend answers to.
414
+
415
+ Only the *collection accessor* is turned into a property name
416
+ (\`my-notes\` → \`rebase.data.myNotes\`), which is what \`collectionsDictionary\` maps
417
+ back.
418
+
419
+ ## \`Row\` vs \`Insert\` vs \`Update\`
420
+
421
+ | Type | What it describes |
422
+ |---|---|
423
+ | \`Row\` | What a read serves. Nullable columns are \`T \\| null\`; relations appear only when \`include\` names them. |
424
+ | \`Insert\` | What \`create()\` accepts. Server-assigned ids are optional; a \`belongsTo\` target may be named either way (\`{ author: 5 }\` or \`{ author_id: 5 }\`). |
425
+ | \`Update\` | What \`update()\` accepts. Everything optional, and the primary key is not settable. |
426
+
427
+ A property marked \`excludeFromApi\` is absent from all three: the API surface
428
+ does not mention it, in either direction. The server still accepts one on a
429
+ write — these types describe the surface, they do not enforce it — but nothing
430
+ generated names a password hash.
431
+
432
+ If you need an untyped escape hatch, \`rebase.data.collection(slug)\` still works —
433
+ but it is generic over \`Record<string, unknown>\` and gives up everything above.
247
434
  `
248
435
  });
249
436
  return files;
250
437
  }
251
438
  //#endregion
252
- export { generateSDK, generateTypedefs, indent, toCamelCase, toPascalCase, toSafeIdentifier };
439
+ export { CodegenError, generateSDK, generateTypedefs, indent, toCamelCase, toPascalCase, toSafeIdentifier };
253
440
 
254
441
  //# sourceMappingURL=index.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","names":[],"sources":["../src/utils.ts","../src/generate-types.ts","../src/index.ts"],"sourcesContent":["/**\n * Utility functions for the SDK generator\n */\n\n/**\n * Convert a slug/snake_case string to PascalCase\n * e.g. \"private_notes\" → \"PrivateNotes\"\n */\nexport function toPascalCase(str: string): string {\n return str\n .split(/[_\\-\\s]+/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\"\");\n}\n\n/**\n * Convert a slug/snake_case string to camelCase\n * e.g. \"private_notes\" → \"privateNotes\"\n */\nexport function toCamelCase(str: string): string {\n if (!/[_\\-\\s]/.test(str)) {\n return str.charAt(0).toLowerCase() + str.slice(1);\n }\n const pascal = toPascalCase(str);\n return pascal.charAt(0).toLowerCase() + pascal.slice(1);\n}\n\n/**\n * Convert a slug to a safe JS identifier\n * e.g. \"private-notes\" → \"privateNotes\"\n */\nexport function toSafeIdentifier(str: string): string {\n return toCamelCase(str.replace(/[^a-zA-Z0-9_]/g, \"_\"));\n}\n\n/**\n * Indent a block of text by a given number of spaces\n */\nexport function indent(text: string, spaces: number): string {\n const pad = \" \".repeat(spaces);\n return text\n .split(\"\\n\")\n .map(line => (line.trim() ? pad + line : line))\n .join(\"\\n\");\n}\n","import { CollectionConfig, PostgresCollectionConfig, Property, Properties, MapProperty, ArrayProperty, Relation, RelationProperty, StringProperty, NumberProperty, ResolvedRelation } from \"@rebasepro/types\";\nimport { resolveCollectionRelations } from \"@rebasepro/common\";\nimport { toPascalCase, toSafeIdentifier } from \"./utils\";\n\nfunction propertyToTypeScriptType(prop: Property): string {\n switch (prop.type) {\n case \"string\": {\n const sp = prop as StringProperty;\n if (sp.enum) {\n const ids = Array.isArray(sp.enum)\n ? sp.enum.map((e: string | number | { id: string | number }) => typeof e === \"object\" ? String(e.id) : String(e))\n : Object.keys(sp.enum);\n return ids.map(v => `\"${v}\"`).join(\" | \");\n }\n return \"string\";\n }\n case \"number\": {\n const np = prop as NumberProperty;\n if (np.enum) {\n const ids = Array.isArray(np.enum)\n ? np.enum.map((e: string | number | { id: string | number }) => typeof e === \"object\" ? String(e.id) : String(e))\n : Object.keys(np.enum);\n return ids.join(\" | \");\n }\n return \"number\";\n }\n case \"boolean\":\n return \"boolean\";\n case \"date\":\n return \"string\"; // ISO 8601 string over the wire\n case \"geopoint\":\n return \"{ latitude: number; longitude: number; }\";\n case \"reference\":\n return \"string | number\";\n case \"relation\":\n return \"string | number\";\n case \"map\": {\n const mapProp = prop as MapProperty;\n if (mapProp.properties) {\n const inner = Object.entries(mapProp.properties)\n .map(([k, v]) => `${toSafeIdentifier(k)}: ${propertyToTypeScriptType(v as Property)};`)\n .join(\" \");\n return `{ ${inner} }`;\n }\n return \"Record<string, unknown>\";\n }\n case \"array\": {\n const arrProp = prop as ArrayProperty;\n if (arrProp.of) {\n return `Array<${propertyToTypeScriptType(arrProp.of as Property)}>`;\n }\n return \"Array<unknown>\";\n }\n case \"vector\":\n return \"number[]\";\n case \"binary\":\n return \"string\";\n default:\n return \"unknown\";\n }\n}\n\n/**\n * Unwrap a relation target that arrived as a module namespace rather than the\n * collection itself — `target: () => import(\"./authors\")` is a common slip.\n */\nfunction resolveTargetCollection(relation: ResolvedRelation): CollectionConfig | undefined {\n try {\n let target = relation.target() as CollectionConfig & { default?: CollectionConfig; __esModule?: boolean };\n if (target && (target.default || target.__esModule)) {\n target = (target.default ?? target) as typeof target;\n }\n return target;\n } catch {\n return undefined;\n }\n}\n\n/** The TypeScript type of a foreign key: whatever the target's primary key is. */\nfunction foreignKeyType(relation: ResolvedRelation): string {\n const target = resolveTargetCollection(relation);\n if (!target?.properties) return \"string | number\";\n const idProp = Object.entries(target.properties).find(([_, p]) => (p as Record<string, unknown>).isId);\n if (!idProp) return \"string | number\";\n return (idProp[1] as Property).type === \"number\" ? \"number\" : \"string\";\n}\n\n/**\n * The type an *included* relation arrives as: the target's own row, inlined.\n *\n * This is what the read pipeline actually serves — `toRestRow` puts the\n * target's flat columns where the relation was, and the SDK and the HTTP API\n * both go through it. It is deliberately *not* a `{ __type: \"relation\" }`\n * envelope: that shape is the admin's view-model and never reaches a\n * developer's `find()`.\n *\n * Falls back to an open record when the target is not part of this generation\n * run, since there is no `Row` to point at.\n */\nfunction includedRelationType(relation: ResolvedRelation, knownSlugs: Set<string>): string {\n const target = resolveTargetCollection(relation);\n const slug = target?.slug ?? relation.targetSlug;\n const rowType = slug && knownSlugs.has(slug)\n ? `Database[${JSON.stringify(toSafeIdentifier(slug))}][\"Row\"]`\n : \"Record<string, unknown>\";\n return relation.cardinality === \"many\" ? `Array<${rowType}>` : rowType;\n}\n\nexport function generateTypedefs(collections: CollectionConfig[]): string {\n const knownSlugs = new Set(collections.map(c => c.slug).filter(Boolean) as string[]);\n const lines: string[] = [\n \"/**\",\n \" * This file was auto-generated by Rebase.\",\n \" * Do not make direct changes to the file.\",\n \" */\",\n \"\",\n \"export interface Database {\"\n ];\n\n for (const collection of collections) {\n const typeName = toPascalCase(collection.slug);\n const properties = (collection.properties ?? {}) as Properties;\n\n // Resolve relations\n let resolvedRelations: Record<string, ResolvedRelation> = {};\n try {\n resolvedRelations = resolveCollectionRelations(collection);\n } catch { /* ignore */ }\n\n lines.push(` ${toSafeIdentifier(collection.slug)}: {`);\n\n // ── Row Type ──\n lines.push(\" Row: {\");\n const emittedKeys = new Set<string>();\n\n // 1. Direct properties\n for (const [key, rawProp] of Object.entries(properties)) {\n const prop = rawProp as Property;\n if (prop.type === \"relation\") continue;\n\n const tsType = propertyToTypeScriptType(prop);\n const isRequired = prop.validation?.required;\n lines.push(` ${toSafeIdentifier(key)}${isRequired ? \"\" : \"?\"}: ${tsType};`);\n emittedKeys.add(key);\n }\n\n // 2. FK columns from relations\n for (const [relKey, relation] of Object.entries(resolvedRelations)) {\n if (relation.kind === \"belongsTo\" && relation.localKey) {\n const fkKey = relation.localKey;\n if (emittedKeys.has(fkKey)) continue;\n\n const fkType = foreignKeyType(relation);\n\n // A relation addressed by the same name as its own foreign key\n // is served *over* that column when the read includes it: the\n // query nests the target under the relation name, and the\n // scalar it shadows is gone. Both outcomes are real, so the\n // column is typed as both — which is what stops a plain\n // `const id: string = row.author_id` from compiling.\n const shadowedByInclude = relKey === fkKey;\n const tsType = shadowedByInclude\n ? `${fkType} | ${includedRelationType(relation, knownSlugs)}`\n : fkType;\n\n const isRequired = relation.validation?.required && !shadowedByInclude;\n lines.push(` ${toSafeIdentifier(fkKey)}${isRequired ? \"\" : \"?\"}: ${tsType};`);\n emittedKeys.add(fkKey);\n }\n }\n\n // 3. Relation fields — the target's own row, inlined.\n //\n // Optional throughout: a relation is only loaded when the read names it\n // in `include`, so it is absent from every other read.\n for (const [key, relation] of Object.entries(resolvedRelations)) {\n if (emittedKeys.has(key)) continue;\n lines.push(` ${toSafeIdentifier(key)}?: ${includedRelationType(relation, knownSlugs)};`);\n emittedKeys.add(key);\n }\n\n // A `relation` property whose relation could not be resolved — an\n // engine without relation support, or a target that did not load. It is\n // still a column on the row, so it is still typed, just not precisely.\n for (const [key, rawProp] of Object.entries(properties)) {\n if ((rawProp as Property).type !== \"relation\") continue;\n if (emittedKeys.has(key)) continue;\n lines.push(` ${toSafeIdentifier(key)}?: Record<string, unknown>;`);\n emittedKeys.add(key);\n }\n lines.push(\" };\");\n\n // ── Insert Type ──\n lines.push(\" Insert: {\");\n emittedKeys.clear();\n\n for (const [key, rawProp] of Object.entries(properties)) {\n const prop = rawProp as Property;\n if (prop.type === \"relation\") continue;\n const tsType = propertyToTypeScriptType(prop);\n const isRequired = prop.validation?.required;\n const typedProp = prop as StringProperty | NumberProperty;\n const isAutoId = \"isId\" in prop && typedProp.isId && typedProp.isId !== \"manual\" && typedProp.isId !== true;\n const isOptional = !isRequired || isAutoId;\n lines.push(` ${toSafeIdentifier(key)}${isOptional ? \"?\" : \"\"}: ${tsType};`);\n emittedKeys.add(key);\n }\n\n for (const [relKey, relation] of Object.entries(resolvedRelations)) {\n if (relation.kind === \"belongsTo\" && relation.localKey) {\n const fkKey = relation.localKey;\n if (emittedKeys.has(fkKey)) continue;\n const fkType = \"string | number\";\n // simple fallback\n const isRequired = relation.validation?.required;\n lines.push(` ${toSafeIdentifier(fkKey)}${isRequired ? \"\" : \"?\"}: ${fkType};`);\n emittedKeys.add(fkKey);\n }\n }\n lines.push(\" };\");\n\n // ── Update Type ──\n lines.push(\" Update: {\");\n emittedKeys.clear();\n for (const [key, rawProp] of Object.entries(properties)) {\n const prop = rawProp as Property;\n if (prop.type === \"relation\") continue;\n const tsType = propertyToTypeScriptType(prop);\n lines.push(` ${toSafeIdentifier(key)}?: ${tsType};`);\n emittedKeys.add(key);\n }\n for (const [relKey, relation] of Object.entries(resolvedRelations)) {\n if (relation.kind === \"belongsTo\" && relation.localKey) {\n const fkKey = relation.localKey;\n if (emittedKeys.has(fkKey)) continue;\n lines.push(` ${toSafeIdentifier(fkKey)}?: string | number;`);\n emittedKeys.add(fkKey);\n }\n }\n lines.push(\" };\");\n\n lines.push(\" };\");\n }\n\n lines.push(\"}\");\n lines.push(\"\");\n lines.push(\"export type CollectionName = keyof Database;\");\n lines.push(\"export type CollectionsDictionary = { [K in CollectionName]: K };\");\n lines.push(\"\");\n lines.push(\"export const collectionsDictionary = {\");\n for (const collection of collections) {\n lines.push(` ${toSafeIdentifier(collection.slug)}: \"${collection.slug}\",`);\n }\n lines.push(\"} as const;\");\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n","/**\n * @rebasepro/codegen\n *\n * Generates a purely typed Typescript database definition.\n */\n\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { generateTypedefs } from \"./generate-types\";\n\nexport { generateTypedefs } from \"./generate-types\";\nexport { toPascalCase, toCamelCase, toSafeIdentifier, indent } from \"./utils\";\n\n// ─── Public API ────────────────────────────────────────────────────\n\nexport interface GeneratedFile {\n /** Relative file path within the output directory */\n path: string;\n /** File content */\n content: string;\n}\n\nexport interface GenerateSDKOptions {\n /** Whether to include a README file (default: true) */\n includeReadme?: boolean;\n}\n\nexport function generateSDK(\n collections: CollectionConfig[],\n options: GenerateSDKOptions = {}\n): GeneratedFile[] {\n const files: GeneratedFile[] = [];\n\n files.push({\n path: \"database.types.ts\",\n content: generateTypedefs(collections)\n });\n\n if (options.includeReadme !== false) {\n files.push({\n path: \"README.md\",\n content: `# Rebase SDK\n\n> Auto-generated by \\`rebase generate-sdk\\`. Do not edit manually.\n\n## Usage\n\n1. Install the client package:\n \\`\\`\\`bash\n npm install @rebasepro/client\n \\`\\`\\`\n\n2. Initialize with your generated types:\n \\`\\`\\`typescript\n import { createRebaseClient } from '@rebasepro/client';\n import { Database, collectionsDictionary } from './database.types';\n\n const rebase = createRebaseClient<Database>({\n baseUrl: 'http://localhost:3001',\n collections: collectionsDictionary,\n });\n\n // Both syntax styles are fully typed!\n const { data: users } = await rebase.data.users.find();\n console.log(users[0].email); // flat access — no .values wrapper\n\n const { data: posts } = await rebase.data.collection('posts').find();\n console.log(posts[0].title); // just post.title, not post.values.title\n \\`\\`\\`\n`\n });\n }\n\n return files;\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,aAAa,KAAqB;CAC9C,OAAO,IACF,MAAM,UAAU,EAChB,KAAI,SAAQ,KAAK,OAAO,CAAC,EAAE,YAAY,IAAI,KAAK,MAAM,CAAC,EAAE,YAAY,CAAC,EACtE,KAAK,EAAE;AAChB;;;;;AAMA,SAAgB,YAAY,KAAqB;CAC7C,IAAI,CAAC,UAAU,KAAK,GAAG,GACnB,OAAO,IAAI,OAAO,CAAC,EAAE,YAAY,IAAI,IAAI,MAAM,CAAC;CAEpD,MAAM,SAAS,aAAa,GAAG;CAC/B,OAAO,OAAO,OAAO,CAAC,EAAE,YAAY,IAAI,OAAO,MAAM,CAAC;AAC1D;;;;;AAMA,SAAgB,iBAAiB,KAAqB;CAClD,OAAO,YAAY,IAAI,QAAQ,kBAAkB,GAAG,CAAC;AACzD;;;;AAKA,SAAgB,OAAO,MAAc,QAAwB;CACzD,MAAM,MAAM,IAAI,OAAO,MAAM;CAC7B,OAAO,KACF,MAAM,IAAI,EACV,KAA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AAM,KAAK,GAAG;CACd,MAAM,KAAK,EAAE;CACb,MAAM,KAAK,8CAA8C;CACzD,MAAM,KAAK,mEAAmE;CAC9E,MAAM,KAAK,EAAE;CACb,MAAM,KAAK,wCAAwC;CACnD,KAAK,MAAM,cAAc,aACrB,MAAM,KAAK,KAAK,iBAAiB,WAAW,IAAI,EAAE,KAAK,WAAW,KAAK,GAAG;CAE9E,MAAM,KAAK,aAAa;CACxB,MAAM,KAAK,EAAE;CAEb,OAAO,MAAM,KAAK,IAAI;AAC1B;;;ACvOA,SAAgB,YACZ,aACA,UAA8B,CAAC,GAChB;CACf,MAAM,QAAyB,CAAC;CAEhC,MAAM,KAAK;EACP,MAAM;EACN,SAAS,iBAAiB,WAAW;CACzC,CAAC;CAED,IAAI,QAAQ,kBAAkB,OAC1B,MAAM,KAAK;EACP,MAAM;EACN,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6Bb,CAAC;CAGL,OAAO;AACX"}
1
+ {"version":3,"file":"index.es.js","names":[],"sources":["../src/utils.ts","../src/generate-types.ts","../src/index.ts"],"sourcesContent":["/**\n * Utility functions for the SDK generator\n */\n\n/**\n * Convert a slug/snake_case string to PascalCase\n * e.g. \"private_notes\" → \"PrivateNotes\"\n *\n * Capitals already inside a word are meaningful and are kept: lowercasing the\n * tail of every chunk turned \"TestEntities\" into \"Testentities\", which is what\n * ended up in the generated type names. SHOUTING_CASE is the one shape where\n * the tail is not meaningful, so it is folded down.\n */\nexport function toPascalCase(str: string): string {\n return str\n .split(/[_\\-\\s]+/)\n .filter(Boolean)\n .map(word => {\n const rest = /^[A-Z0-9]+$/.test(word) ? word.slice(1).toLowerCase() : word.slice(1);\n return word.charAt(0).toUpperCase() + rest;\n })\n .join(\"\");\n}\n\n/**\n * Convert a slug/snake_case string to camelCase\n * e.g. \"private_notes\" → \"privateNotes\"\n */\nexport function toCamelCase(str: string): string {\n if (!/[_\\-\\s]/.test(str)) {\n return str.charAt(0).toLowerCase() + str.slice(1);\n }\n const pascal = toPascalCase(str);\n return pascal.charAt(0).toLowerCase() + pascal.slice(1);\n}\n\n/**\n * Convert a slug to a safe JS identifier\n * e.g. \"private-notes\" → \"privateNotes\"\n */\nexport function toSafeIdentifier(str: string): string {\n return toCamelCase(str.replace(/[^a-zA-Z0-9_]/g, \"_\"));\n}\n\n/**\n * Indent a block of text by a given number of spaces\n */\nexport function indent(text: string, spaces: number): string {\n const pad = \" \".repeat(spaces);\n return text\n .split(\"\\n\")\n .map(line => (line.trim() ? pad + line : line))\n .join(\"\\n\");\n}\n","import { CollectionConfig, Property, Properties, MapProperty, ArrayProperty, StringProperty, NumberProperty, ResolvedRelation } from \"@rebasepro/types\";\nimport { findRelation, resolveCollectionRelations, sortCollectionsBySlug } from \"@rebasepro/common\";\nimport { toSafeIdentifier } from \"./utils\";\n\n/**\n * A schema that cannot be expressed as a valid TypeScript file.\n *\n * Thrown rather than emitted. The generator used to concatenate whatever it was\n * given, so a slug that collided with another one, or that was not an\n * identifier, produced a file that either failed to compile or — worse —\n * compiled while quietly routing one collection to another's slug.\n */\nexport class CodegenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodegenError\";\n }\n}\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * A property name for the emitted TypeScript: verbatim when it is a valid\n * identifier, quoted otherwise.\n *\n * Every key that reaches the output goes through here. Column names are not\n * required to be identifiers — `\"order\"`, `\"user id\"`, a quoted Postgres\n * identifier — and the previous behaviour of camel-casing them into shape\n * renamed the column in the type while the wire kept the original, so the\n * generated `Row` described fields that did not exist.\n */\nfunction emitKey(key: string): string {\n return IDENTIFIER.test(key) ? key : JSON.stringify(key);\n}\n\n/**\n * A string literal, escaped.\n *\n * `\"${value}\"` was the previous form. A value containing a quote closed the\n * literal early, which at best broke the file and at worst let a slug from a\n * remote contract inject top-level statements into a file the developer\n * compiles and bundles.\n */\nfunction emitString(value: string): string {\n return JSON.stringify(value);\n}\n\n/** The `id`s of an enum declared as an array, an array of `{ id }`, or an object map. */\nfunction enumIds(raw: unknown): (string | number)[] {\n if (Array.isArray(raw)) {\n return raw.map((entry: string | number | { id: string | number }) =>\n entry && typeof entry === \"object\" ? entry.id : entry);\n }\n if (raw && typeof raw === \"object\") return Object.keys(raw);\n return [];\n}\n\nfunction propertyToTypeScriptType(prop: Property): string {\n switch (prop.type) {\n case \"string\": {\n const sp = prop as StringProperty;\n if (sp.enum) {\n const ids = enumIds(sp.enum);\n if (ids.length === 0) return \"string\";\n return ids.map(v => emitString(String(v))).join(\" | \");\n }\n return \"string\";\n }\n case \"number\": {\n const np = prop as NumberProperty;\n if (np.enum) {\n const ids = enumIds(np.enum);\n const numbers = ids.map(Number);\n // A numeric enum carrying something that is not a number cannot\n // be written as a union of numeric literals. Widening to\n // `number` is imprecise; emitting `NaN | undefined` is invalid.\n if (ids.length === 0 || numbers.some(n => !Number.isFinite(n))) return \"number\";\n return numbers.map(n => String(n)).join(\" | \");\n }\n return \"number\";\n }\n case \"boolean\":\n return \"boolean\";\n case \"date\":\n return \"string\"; // ISO 8601 string over the wire\n case \"geopoint\":\n return \"{ latitude: number; longitude: number; }\";\n case \"reference\":\n return \"string | number\";\n case \"relation\":\n return \"string | number\";\n case \"map\": {\n const mapProp = prop as MapProperty;\n if (mapProp.properties) {\n const inner = Object.entries(mapProp.properties)\n .map(([k, v]) => {\n const child = v as Property;\n // Nested fields carry validation like any other. Emitting\n // them all required claimed a shape the payload does not\n // have to satisfy.\n const optional = !child.validation?.required;\n const type = propertyToTypeScriptType(child);\n return `${emitKey(k)}${optional ? \"?\" : \"\"}: ${optional ? `${type} | null` : type};`;\n })\n .join(\" \");\n return `{ ${inner} }`;\n }\n return \"Record<string, unknown>\";\n }\n case \"array\": {\n const arrProp = prop as ArrayProperty;\n if (arrProp.of) {\n return `Array<${propertyToTypeScriptType(arrProp.of as Property)}>`;\n }\n return \"Array<unknown>\";\n }\n case \"vector\":\n return \"number[]\";\n case \"binary\":\n return \"string\";\n default:\n return \"unknown\";\n }\n}\n\n/**\n * Unwrap a relation target that arrived as a module namespace rather than the\n * collection itself — `target: () => import(\"./authors\")` is a common slip.\n */\nfunction resolveTargetCollection(relation: ResolvedRelation): CollectionConfig | undefined {\n try {\n let target = relation.target() as CollectionConfig & { default?: CollectionConfig; __esModule?: boolean };\n if (target && (target.default || target.__esModule)) {\n target = (target.default ?? target) as typeof target;\n }\n return target;\n } catch {\n return undefined;\n }\n}\n\n/** The TypeScript type of a foreign key: whatever the target's primary key is. */\nfunction foreignKeyType(relation: ResolvedRelation): string {\n const target = resolveTargetCollection(relation);\n if (!target?.properties) return \"string | number\";\n const idProp = Object.entries(target.properties).find(([_, p]) => (p as Record<string, unknown>).isId);\n if (!idProp) return \"string | number\";\n return (idProp[1] as Property).type === \"number\" ? \"number\" : \"string\";\n}\n\n/** Whether a property is the collection's primary key. */\nfunction isPrimaryKey(prop: Property): boolean {\n return Boolean((prop as unknown as Record<string, unknown>).isId);\n}\n\n/**\n * Whether the server assigns this primary key, so a write does not have to.\n * `true` and `\"manual\"` both mean the caller supplies it.\n */\nfunction isAutoAssignedId(prop: Property): boolean {\n const isId = (prop as unknown as Record<string, unknown>).isId;\n return Boolean(isId) && isId !== \"manual\" && isId !== true;\n}\n\n/**\n * The type an *included* relation arrives as: the target's own row, inlined.\n *\n * This is what the read pipeline actually serves — `toRestRow` puts the\n * target's flat columns where the relation was, and the SDK and the HTTP API\n * both go through it. It is deliberately *not* a `{ __type: \"relation\" }`\n * envelope: that shape is the admin's view-model and never reaches a\n * developer's `find()`.\n *\n * Falls back to an open record when the target is not part of this generation\n * run, since there is no `Row` to point at.\n */\nfunction includedRelationType(\n relation: ResolvedRelation,\n accessors: Map<string, string>\n): string {\n const target = resolveTargetCollection(relation);\n const slug = target?.slug ?? relation.targetSlug;\n const accessor = slug ? accessors.get(slug) : undefined;\n const rowType = accessor\n ? `Database[${emitString(accessor)}][\"Row\"]`\n : \"Record<string, unknown>\";\n return relation.cardinality === \"many\" ? `Array<${rowType}>` : rowType;\n}\n\n/**\n * Map every slug to the property name it is reachable under on `client.data`.\n *\n * The accessor is a safe identifier because `client.data.myNotes` is the point\n * of generating this at all, and `collectionsDictionary` maps it back to the\n * slug the wire uses. Two slugs that safe down to the same identifier cannot\n * both have it: the interface would not compile, and the dictionary — an object\n * literal — would silently keep only the last, routing one collection's reads\n * to the other's table. There is no defensible way to pick, so this refuses.\n */\nfunction buildAccessors(collections: CollectionConfig[]): Map<string, string> {\n const accessors = new Map<string, string>();\n const bySafeName = new Map<string, string>();\n\n for (const collection of collections) {\n const slug = collection.slug;\n if (typeof slug !== \"string\" || slug.length === 0) {\n throw new CodegenError(\n \"A collection has no slug, so it has no name to generate a type for. \" +\n \"Every collection needs a unique `slug`.\"\n );\n }\n\n const safe = toSafeIdentifier(slug);\n if (safe.length === 0) {\n throw new CodegenError(\n `The slug ${emitString(slug)} has no characters that can form a property name, ` +\n \"so it cannot be reached as `client.data.<name>`. Use a slug containing \" +\n \"letters, digits, underscores or dashes.\"\n );\n }\n\n const existing = bySafeName.get(safe);\n if (existing !== undefined) {\n throw new CodegenError(\n `The collections ${emitString(existing)} and ${emitString(slug)} both generate the ` +\n `accessor \"${safe}\", so only one of them could be reached from the generated client ` +\n \"and the other's reads would silently go to the wrong table. Rename one of the slugs.\"\n );\n }\n\n bySafeName.set(safe, slug);\n accessors.set(slug, safe);\n }\n\n return accessors;\n}\n\n/** One emitted `key: type;` line, already indented. */\nfunction line(key: string, type: string, optional: boolean): string {\n return ` ${emitKey(key)}${optional ? \"?\" : \"\"}: ${type};`;\n}\n\n/**\n * The keys `excludeFromApi` takes off the API surface — in *both* directions.\n *\n * `excludeFromApi` means one thing: the API surface does not mention this\n * property. `Row` already honoured that; `Insert` and `Update` deliberately did\n * not, on the reading that the column is stripped from responses rather than\n * from writes. That left the generated types as the one place a password hash\n * was still named, and it invited a client to send one. The server still\n * *accepts* such a field on a write — this describes the surface, it does not\n * add an enforcement point — but nothing generated advertises it.\n *\n * Keyed by the property name *and* by its column name, the same pair the\n * server's `stripExcluded` deletes, so a foreign key or a relation addressed\n * under the column name cannot put the property back.\n */\nfunction excludedApiKeys(properties: Properties): Set<string> {\n const excluded = new Set<string>();\n for (const [key, rawProp] of Object.entries(properties)) {\n const prop = rawProp as Property;\n if (!prop?.excludeFromApi) continue;\n excluded.add(key);\n if (prop.columnName) excluded.add(prop.columnName);\n }\n return excluded;\n}\n\nexport function generateTypedefs(input: CollectionConfig[]): string {\n // Sorted here rather than only in `generate-sdk`: the output is\n // order-dependent and `rebase doctor` regenerates it in memory to diff\n // against the file on disk. While only the writer sorted, a project whose\n // file order differed from its slug order was reported permanently stale.\n const collections = sortCollectionsBySlug(input);\n const accessors = buildAccessors(collections);\n const lines: string[] = [\n \"/**\",\n \" * This file was auto-generated by Rebase.\",\n \" * Do not make direct changes to the file.\",\n \" */\",\n \"\",\n \"export interface Database {\"\n ];\n\n for (const collection of collections) {\n const properties = (collection.properties ?? {}) as Properties;\n\n // Resolve relations\n let resolvedRelations: Record<string, ResolvedRelation> = {};\n try {\n resolvedRelations = resolveCollectionRelations(collection);\n } catch (e) {\n // Swallowed before, which made this the quietest way to ship a\n // wrong type. The foreign-key columns are emitted from the resolved\n // relations rather than from the properties, so losing them drops\n // both the relation fields *and* columns that exist in the\n // database — and the resulting error surfaces in the user's code,\n // typechecking against a `Database` that is missing `author_id`,\n // with nothing pointing back at generation.\n //\n // A target thunk usually throws because of a circular import; the\n // boot-time relation validator names the same cause.\n console.warn(\n `[rebase] Could not resolve the relations of \"${collection.slug}\", so its generated ` +\n \"type has no relation fields and none of their foreign-key columns. This is usually a \" +\n \"circular import in the collection files — make sure the target is `() => otherCollection` \" +\n `and not evaluated at module load.\\n ${e instanceof Error ? e.message : String(e)}`\n );\n }\n\n // Subcollections are collections in their own right and are addressed\n // over a nested path, not as `client.data.<name>`. Generating them here\n // would invent an accessor the client does not serve, so they are\n // skipped — loudly, because doing it silently is how a developer\n // concludes the generator is broken.\n const subcollections = (collection as unknown as { subcollections?: unknown[] }).subcollections;\n if (Array.isArray(subcollections) && subcollections.length > 0) {\n console.warn(\n `[rebase] \"${collection.slug}\" declares ${subcollections.length} subcollection(s), which are ` +\n \"not part of the generated Database: they are reached over a nested path \" +\n `(\\`data/${collection.slug}/<id>/<relation>\\`), not as a top-level accessor. Register a ` +\n \"subcollection as a collection of its own if you want a typed accessor for it.\"\n );\n }\n\n lines.push(` ${emitKey(accessors.get(collection.slug)!)}: {`);\n\n // ── Row Type ──\n //\n // What a read serves. There is no field selection in the query API, so\n // every column of a row comes back on every read; a column is optional\n // here only because the value may be absent or null, never because the\n // caller might not have asked for it.\n lines.push(\" Row: {\");\n const emittedKeys = new Set<string>();\n\n // Off the surface entirely — see `excludedApiKeys`. Seeding the emitted\n // set means every later pass (foreign keys, relations, unresolved\n // relations) skips them too, since each of those already refuses to\n // emit a key twice.\n const excluded = excludedApiKeys(properties);\n for (const key of excluded) emittedKeys.add(key);\n\n // 1. Direct properties\n for (const [key, rawProp] of Object.entries(properties)) {\n const prop = rawProp as Property;\n if (prop.type === \"relation\") continue;\n if (excluded.has(key)) continue;\n\n const tsType = propertyToTypeScriptType(prop);\n // A primary key is on every row a read can return, whether or not\n // anyone wrote `validation: { required: true }` next to it —\n // introspection never does, so `row.id` was `string | undefined`\n // for every baas project.\n const isRequired = Boolean(prop.validation?.required) || isPrimaryKey(prop);\n lines.push(line(key, isRequired ? tsType : `${tsType} | null`, !isRequired));\n emittedKeys.add(key);\n }\n\n // 2. FK columns from relations.\n //\n // Emitted under `localKey` verbatim: that is the Drizzle field key, so\n // it is the JSON key the row arrives with. Reshaping it into\n // `authorId` described a column that does not exist and hid the one\n // that does — including from `where` and `orderBy`, which are keyed off\n // this type.\n for (const [relKey, relation] of Object.entries(resolvedRelations)) {\n if (relation.kind === \"belongsTo\" && relation.localKey) {\n const fkKey = relation.localKey;\n if (emittedKeys.has(fkKey)) continue;\n\n const fkType = foreignKeyType(relation);\n\n // A relation addressed by the same name as its own foreign key\n // is served *over* that column when the read includes it: the\n // query nests the target under the relation name, and the\n // scalar it shadows is gone. Both outcomes are real, so the\n // column is typed as both — which is what stops a plain\n // `const id: string = row.author_id` from compiling.\n const shadowedByInclude = relKey === fkKey;\n const tsType = shadowedByInclude\n ? `${fkType} | ${includedRelationType(relation, accessors)}`\n : fkType;\n\n const isRequired = Boolean(relation.validation?.required) && !shadowedByInclude;\n lines.push(line(fkKey, isRequired ? tsType : `${tsType} | null`, !isRequired));\n emittedKeys.add(fkKey);\n }\n }\n\n // 3. Relation fields — the target's own row, inlined.\n //\n // Optional throughout: a relation is only loaded when the read names it\n // in `include`, so it is absent from every other read.\n for (const [key, relation] of Object.entries(resolvedRelations)) {\n if (emittedKeys.has(key)) continue;\n lines.push(line(key, includedRelationType(relation, accessors), true));\n emittedKeys.add(key);\n }\n\n // A `relation` property whose relation could not be resolved — an\n // engine without relation support, or a target that did not load. It is\n // still a column on the row, so it is still typed, just not precisely.\n for (const [key, rawProp] of Object.entries(properties)) {\n if ((rawProp as Property).type !== \"relation\") continue;\n if (emittedKeys.has(key)) continue;\n lines.push(line(key, \"Record<string, unknown>\", true));\n emittedKeys.add(key);\n }\n lines.push(\" };\");\n\n // ── Insert Type ──\n //\n // What `create()` accepts, minus the `excludeFromApi` columns: the\n // property is off the API surface in both directions, so a generated\n // client never names it.\n lines.push(\" Insert: {\");\n emittedKeys.clear();\n for (const key of excluded) emittedKeys.add(key);\n\n for (const [key, rawProp] of Object.entries(properties)) {\n const prop = rawProp as Property;\n if (prop.type === \"relation\") continue;\n if (excluded.has(key)) continue;\n const tsType = propertyToTypeScriptType(prop);\n const isOptional = !prop.validation?.required || isAutoAssignedId(prop);\n lines.push(line(key, tsType, isOptional));\n emittedKeys.add(key);\n }\n\n emitWritableRelations(lines, properties, resolvedRelations, emittedKeys, false);\n lines.push(\" };\");\n\n // ── Update Type ──\n //\n // Everything optional, and the primary key left out: an update\n // addresses a row by id, it does not reassign one. Accepting `id` here\n // typechecked `update(id, { id: someoneElses })`.\n lines.push(\" Update: {\");\n emittedKeys.clear();\n for (const key of excluded) emittedKeys.add(key);\n for (const [key, rawProp] of Object.entries(properties)) {\n const prop = rawProp as Property;\n if (prop.type === \"relation\") continue;\n if (isPrimaryKey(prop)) continue;\n if (excluded.has(key)) continue;\n lines.push(line(key, propertyToTypeScriptType(prop), true));\n emittedKeys.add(key);\n }\n emitWritableRelations(lines, properties, resolvedRelations, emittedKeys, true);\n lines.push(\" };\");\n\n lines.push(\" };\");\n }\n\n lines.push(\"}\");\n lines.push(\"\");\n lines.push(\"export type CollectionName = keyof Database;\");\n lines.push(\"\");\n lines.push(\"export const collectionsDictionary = {\");\n for (const collection of collections) {\n lines.push(` ${emitKey(accessors.get(collection.slug)!)}: ${emitString(collection.slug)},`);\n }\n lines.push(\"} as const;\");\n lines.push(\"\");\n // Describes the const above rather than restating its keys. The previous\n // `{ [K in CollectionName]: K }` said every value equalled its key, which is\n // false for any slug that is not already an identifier — `myNotes` maps to\n // `\"my-notes\"` — so the export the CLI tells people to pass did not satisfy\n // its own published type.\n lines.push(\"export type CollectionsDictionary = typeof collectionsDictionary;\");\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n\n/**\n * The two ways a write can name a `belongsTo` target, both of which the server\n * accepts: the foreign-key column itself (`{ author_id: 5 }`, which passes\n * through untouched) and the relation *property* (`{ author: 5 }`, which the\n * write transformer maps onto that column).\n *\n * Only the first was generated, so the documented and idiomatic write shape was\n * a type error.\n *\n * The second form is emitted under the **property key**, not the resolved\n * relation name, because that is what the transformer keys off: it looks the\n * payload key up in `properties` and only treats it as a relation if what it\n * finds there is one. A relation whose `relationName` differs from its property\n * key is reachable as the property and not as the name, so emitting the name\n * would have offered a key that writes to a column that does not exist.\n */\nfunction emitWritableRelations(\n lines: string[],\n properties: Properties,\n resolvedRelations: Record<string, ResolvedRelation>,\n emittedKeys: Set<string>,\n allOptional: boolean\n): void {\n // The target's primary key type is the same one `Row` uses. A hardcoded\n // `string | number` here accepted a string for a numeric-keyed target.\n const emit = (key: string, relation: ResolvedRelation): void => {\n if (emittedKeys.has(key)) return;\n const optional = allOptional || !relation.validation?.required;\n lines.push(line(key, foreignKeyType(relation), optional));\n emittedKeys.add(key);\n };\n\n for (const relation of Object.values(resolvedRelations)) {\n if (relation.kind === \"belongsTo\" && relation.localKey) emit(relation.localKey, relation);\n }\n\n for (const [key, rawProp] of Object.entries(properties)) {\n if ((rawProp as Property).type !== \"relation\") continue;\n const relation = findRelation(resolvedRelations, key);\n if (relation?.kind === \"belongsTo\" && relation.localKey) emit(key, relation);\n }\n}\n","/**\n * @rebasepro/codegen\n *\n * Generates a purely typed Typescript database definition.\n */\n\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { generateTypedefs } from \"./generate-types\";\n\nexport { generateTypedefs, CodegenError } from \"./generate-types\";\nexport { toPascalCase, toCamelCase, toSafeIdentifier, indent } from \"./utils\";\n\n// ─── Public API ────────────────────────────────────────────────────\n\nexport interface GeneratedFile {\n /** Relative file path within the output directory */\n path: string;\n /** File content */\n content: string;\n}\n\nexport interface GenerateSDKOptions {\n /** Whether to include a README file (default: true) */\n includeReadme?: boolean;\n}\n\nexport function generateSDK(\n collections: CollectionConfig[],\n options: GenerateSDKOptions = {}\n): GeneratedFile[] {\n const files: GeneratedFile[] = [];\n\n files.push({\n path: \"database.types.ts\",\n content: generateTypedefs(collections)\n });\n\n if (options.includeReadme !== false) {\n files.push({\n path: \"README.md\",\n content: `# Rebase SDK\n\n> Auto-generated by \\`rebase generate-sdk\\`. Do not edit manually.\n\n## Usage\n\n1. Install the client package:\n \\`\\`\\`bash\n npm install @rebasepro/client\n \\`\\`\\`\n\n2. Initialize with your generated types:\n \\`\\`\\`typescript\n import { createRebaseClient } from '@rebasepro/client';\n import { collectionsDictionary, type Database } from './database.types';\n\n const rebase = createRebaseClient<Database>({\n baseUrl: 'http://localhost:3001',\n // Maps each accessor back to the slug the wire uses. Without it a\n // hyphenated slug is not resolvable from the property name alone.\n collections: collectionsDictionary,\n });\n\n // Property access is the typed surface: rows, filters and sorts are all\n // checked against the generated Database.\n const { data: users } = await rebase.data.users.find();\n console.log(users[0].email); // flat access — no .values wrapper\n \\`\\`\\`\n\n## Field names are the ones the API serves\n\nThe generated \\`Row\\` uses each column's real name, unchanged — a \\`created_at\\`\ncolumn is \\`row.created_at\\`, not \\`row.createdAt\\`. \\`where\\` and \\`orderBy\\` are keyed\noff the same type, so what compiles is what the backend answers to.\n\nOnly the *collection accessor* is turned into a property name\n(\\`my-notes\\` → \\`rebase.data.myNotes\\`), which is what \\`collectionsDictionary\\` maps\nback.\n\n## \\`Row\\` vs \\`Insert\\` vs \\`Update\\`\n\n| Type | What it describes |\n|---|---|\n| \\`Row\\` | What a read serves. Nullable columns are \\`T \\\\| null\\`; relations appear only when \\`include\\` names them. |\n| \\`Insert\\` | What \\`create()\\` accepts. Server-assigned ids are optional; a \\`belongsTo\\` target may be named either way (\\`{ author: 5 }\\` or \\`{ author_id: 5 }\\`). |\n| \\`Update\\` | What \\`update()\\` accepts. Everything optional, and the primary key is not settable. |\n\nA property marked \\`excludeFromApi\\` is absent from all three: the API surface\ndoes not mention it, in either direction. The server still accepts one on a\nwrite — these types describe the surface, they do not enforce it — but nothing\ngenerated names a password hash.\n\nIf you need an untyped escape hatch, \\`rebase.data.collection(slug)\\` still works —\nbut it is generic over \\`Record<string, unknown>\\` and gives up everything above.\n`\n });\n }\n\n return files;\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,SAAgB,aAAa,KAAqB;CAC9C,OAAO,IACF,MAAM,UAAU,CAAC,CACjB,OAAO,OAAO,CAAC,CACf,KAAI,SAAQ;EACT,MAAM,OAAO,cAAc,KAAK,IAAI,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,YAAY,IAAI,KAAK,MAAM,CAAC;EAClF,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI;CAC1C,CAAC,CAAC,CACD,KAAK,EAAE;AAChB;;;;;AAMA,SA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,CAAE,EAAE,IAAI,WAAW,WAAW,IAAI,EAAE,EAAE;CAE/F,MAAM,KAAK,aAAa;CACxB,MAAM,KAAK,EAAE;CAMb,MAAM,KAAK,mEAAmE;CAC9E,MAAM,KAAK,EAAE;CAEb,OAAO,MAAM,KAAK,IAAI;AAC1B;;;;;;;;;;;;;;;;;AAkBA,SAAS,sBACL,OACA,YACA,mBACA,aACA,aACI;CAGJ,MAAM,QAAQ,KAAa,aAAqC;EAC5D,IAAI,YAAY,IAAI,GAAG,GAAG;EAC1B,MAAM,WAAW,eAAe,CAAC,SAAS,YAAY;EACtD,MAAM,KAAK,KAAK,KAAK,eAAe,QAAQ,GAAG,QAAQ,CAAC;EACxD,YAAY,IAAI,GAAG;CACvB;CAEA,KAAK,MAAM,YAAY,OAAO,OAAO,iBAAiB,GAClD,IAAI,SAAS,SAAS,eAAe,SAAS,UAAU,KAAK,SAAS,UAAU,QAAQ;CAG5F,KAAK,MAAM,CAAC,KAAK,YAAY,OAAO,QAAQ,UAAU,GAAG;EACrD,IAAK,QAAqB,SAAS,YAAY;EAC/C,MAAM,WAAW,aAAa,mBAAmB,GAAG;EACpD,IAAI,UAAU,SAAS,eAAe,SAAS,UAAU,KAAK,KAAK,QAAQ;CAC/E;AACJ;;;AC3eA,SAAgB,YACZ,aACA,UAA8B,CAAC,GAChB;CACf,MAAM,QAAyB,CAAC;CAEhC,MAAM,KAAK;EACP,MAAM;EACN,SAAS,iBAAiB,WAAW;CACzC,CAAC;CAED,IAAI,QAAQ,kBAAkB,OAC1B,MAAM,KAAK;EACP,MAAM;EACN,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuDb,CAAC;CAGL,OAAO;AACX"}
package/dist/utils.d.ts CHANGED
@@ -4,6 +4,11 @@
4
4
  /**
5
5
  * Convert a slug/snake_case string to PascalCase
6
6
  * e.g. "private_notes" → "PrivateNotes"
7
+ *
8
+ * Capitals already inside a word are meaningful and are kept: lowercasing the
9
+ * tail of every chunk turned "TestEntities" into "Testentities", which is what
10
+ * ended up in the generated type names. SHOUTING_CASE is the one shape where
11
+ * the tail is not meaningful, so it is folded down.
7
12
  */
8
13
  export declare function toPascalCase(str: string): string;
9
14
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rebasepro/codegen",
3
- "version": "0.12.1-canary.gf5f1d39",
3
+ "version": "0.13.1-canary.g06dbe5b",
4
4
  "description": "Generate a typed JS SDK from Rebase collection definitions",
5
5
  "main": "./dist/index.es.js",
6
6
  "module": "./dist/index.es.js",
@@ -22,19 +22,17 @@
22
22
  "author": "rebase.pro",
23
23
  "license": "MIT",
24
24
  "peerDependencies": {
25
- "@rebasepro/types": "0.12.1-canary.gf5f1d39",
26
- "@rebasepro/common": "0.12.1-canary.gf5f1d39"
25
+ "@rebasepro/types": "0.13.1-canary.g06dbe5b"
27
26
  },
28
27
  "devDependencies": {
29
28
  "@jest/globals": "^30.4.1",
30
29
  "@types/jest": "^30.0.0",
31
- "@types/node": "^25.9.3",
30
+ "@types/node": "^26.1.2",
32
31
  "jest": "^30.4.2",
33
- "ts-jest": "^29.4.11",
32
+ "ts-jest": "^29.4.12",
34
33
  "typescript": "^6.0.3",
35
- "vite": "^8.0.16",
36
- "@rebasepro/common": "0.12.1-canary.gf5f1d39",
37
- "@rebasepro/types": "0.12.1-canary.gf5f1d39"
34
+ "vite": "^8.1.5",
35
+ "@rebasepro/types": "0.13.1-canary.g06dbe5b"
38
36
  },
39
37
  "exports": {
40
38
  ".": {
@@ -44,7 +42,7 @@
44
42
  },
45
43
  "gitHead": "d935eefa5aa8d1009a2398cfac2c1e4ee9aeb6b6",
46
44
  "dependencies": {
47
- "@rebasepro/client": "0.12.1-canary.gf5f1d39"
45
+ "@rebasepro/common": "0.13.1-canary.g06dbe5b"
48
46
  },
49
47
  "repository": {
50
48
  "type": "git",