@rebasepro/codegen 0.17.3-canary.gdd23447 → 0.18.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.
package/README.md CHANGED
@@ -8,6 +8,10 @@ Generates typed TypeScript definitions from Rebase collection definitions — pr
8
8
  pnpm add @rebasepro/codegen
9
9
  ```
10
10
 
11
+ ESM-only: `"type": "module"` with no CommonJS build, so it is loaded with
12
+ `import`. `require()` of it resolves only on Node 22.12+, which supports
13
+ `require(esm)`.
14
+
11
15
  ### Dependencies
12
16
 
13
17
  - `@rebasepro/common` — a runtime dependency (`resolveCollectionRelations`)
@@ -17,7 +21,7 @@ pnpm add @rebasepro/codegen
17
21
 
18
22
  `@rebasepro/codegen` takes an array of `CollectionConfig` definitions and produces TypeScript type files that provide full autocompletion when used with `@rebasepro/client`. It handles property types, enums, relations, maps, arrays, geopoints, vectors, and validation-based optionality.
19
23
 
20
- This is typically invoked via the CLI (`npx rebase generate-sdk`) rather than called directly.
24
+ This is typically invoked via the CLI (`pnpm rebase generate-sdk`) rather than called directly.
21
25
 
22
26
  ## Key Exports
23
27
 
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import { fieldKeyForColumn, findRelation, resolveCollectionRelations, sortCollectionsBySlug } from "@rebasepro/common";
1
+ import { fieldKeyForColumn, findRelation, isRelationRequired, resolveCollectionRelations, sortCollectionsBySlug } from "@rebasepro/common";
2
2
  //#region src/utils.ts
3
3
  /**
4
4
  * Utility functions for the SDK generator
@@ -280,7 +280,7 @@ function generateTypedefs(input) {
280
280
  const fkType = foreignKeyType(relation);
281
281
  const shadowedByInclude = relKey === fkKey;
282
282
  const tsType = shadowedByInclude ? `${fkType} | ${includedRelationType(relation, accessors)}` : fkType;
283
- const isRequired = Boolean(relation.validation?.required) && !shadowedByInclude;
283
+ const isRequired = isRelationRequired(collection, relation) && !shadowedByInclude;
284
284
  lines.push(line(fkKey, isRequired ? tsType : `${tsType} | null`, !isRequired));
285
285
  emittedKeys.add(fkKey);
286
286
  }
@@ -357,7 +357,7 @@ function generateTypedefs(input) {
357
357
  function emitWritableRelations(lines, collection, properties, resolvedRelations, emittedKeys, allOptional) {
358
358
  const emit = (key, relation) => {
359
359
  if (emittedKeys.has(key)) return;
360
- const optional = allOptional || !relation.validation?.required;
360
+ const optional = allOptional || !isRelationRequired(collection, relation);
361
361
  lines.push(line(key, foreignKeyType(relation), optional));
362
362
  emittedKeys.add(key);
363
363
  };
@@ -409,26 +409,34 @@ function generateSDK(collections, options = {}) {
409
409
 
410
410
  ## Field names are the ones the API serves
411
411
 
412
- The generated \`Row\` uses each column's real name, unchanged a \`created_at\`
413
- column is \`row.created_at\`, not \`row.createdAt\`. \`where\` and \`orderBy\` are keyed
414
- off the same type, so what compiles is what the backend answers to.
412
+ The generated \`Row\` uses each field's **wire** name — the key it arrives under in
413
+ JSON and nothing here renames anything.
415
414
 
416
- Only the *collection accessor* is turned into a property name
417
- (\`my-notes\` \`rebase.data.myNotes\`), which is what \`collectionsDictionary\` maps
418
- back.
415
+ - **A declared property is its key in the collection.** A property keyed
416
+ \`createdAt\` is \`row.createdAt\`, whatever \`columnName\` says. A column name is
417
+ the name of a different thing: where the value lives, not what the API calls it.
418
+ - **A foreign key derived from a relation is camelCase**, because that is what
419
+ the wire carries. A \`belongsTo\` named \`author\` gives you \`row.authorId\`, not
420
+ the column spelling.
421
+ - **A collection accessor is camelCase too** (\`my-notes\` → \`rebase.data.myNotes\`),
422
+ which is what \`collectionsDictionary\` maps back to the slug.
423
+
424
+ \`where\` and \`orderBy\` are keyed off the same type, so what compiles is what the
425
+ backend answers to.
419
426
 
420
427
  ## \`Row\` vs \`Insert\` vs \`Update\`
421
428
 
422
429
  | Type | What it describes |
423
430
  |---|---|
424
431
  | \`Row\` | What a read serves. Nullable columns are \`T \\| null\`; relations appear only when \`include\` names them. |
425
- | \`Insert\` | What \`create()\` accepts. Server-assigned ids are optional; a \`belongsTo\` target may be named either way (\`{ author: 5 }\` or \`{ author_id: 5 }\`). |
432
+ | \`Insert\` | What \`create()\` accepts. Server-assigned ids are optional; a \`belongsTo\` target may be named either way (\`{ author: 5 }\` or \`{ authorId: 5 }\`). |
426
433
  | \`Update\` | What \`update()\` accepts. Everything optional, and the primary key is not settable. |
427
434
 
428
435
  A property marked \`excludeFromApi\` is absent from all three: the API surface
429
- does not mention it, in either direction. The server still accepts one on a
430
- write these types describe the surface, they do not enforce it — but nothing
431
- generated names a password hash.
436
+ does not mention it, in either direction. The server holds the same line a
437
+ read never serves the column and a write naming it is refused so this is a
438
+ guarantee rather than a description, and nothing generated names a password
439
+ hash.
432
440
 
433
441
  If you need an untyped escape hatch, \`rebase.data.collection(slug)\` still works —
434
442
  but it is generic over \`Record<string, unknown>\` and gives up everything above.
@@ -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 *\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 { fieldKeyForColumn, 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 the relation's *wire* name, which is what\n // `fieldKeyForColumn` answers: `localKey` is the database column\n // (`author_id`) and the row arrives keyed `authorId`. Emitting the\n // column, which this used to do, described a key the JSON does not\n // carry and hid the one it does — including from `where` and `orderBy`,\n // which are keyed off this type. The column name is not a second name\n // for the field: it is the name of a different thing.\n for (const [relKey, relation] of Object.entries(resolvedRelations)) {\n if (relation.kind === \"belongsTo\" && relation.localKey) {\n const fkKey = fieldKeyForColumn(collection, 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, collection, 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, collection, 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 under its own wire name (`{ authorId: 5 }`, which\n * passes through to the `author_id` column untouched) and the relation\n * *property* (`{ author: 5 }`, which the write transformer maps onto that\n * 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 collection: CollectionConfig,\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) {\n emit(fieldKeyForColumn(collection, relation.localKey), relation);\n }\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;CA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["../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 { fieldKeyForColumn, findRelation, isRelationRequired, 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 the relation's *wire* name, which is what\n // `fieldKeyForColumn` answers: `localKey` is the database column\n // (`author_id`) and the row arrives keyed `authorId`. Emitting the\n // column, which this used to do, described a key the JSON does not\n // carry and hid the one it does — including from `where` and `orderBy`,\n // which are keyed off this type. The column name is not a second name\n // for the field: it is the name of a different thing.\n for (const [relKey, relation] of Object.entries(resolvedRelations)) {\n if (relation.kind === \"belongsTo\" && relation.localKey) {\n const fkKey = fieldKeyForColumn(collection, 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 = isRelationRequired(collection, relation) && !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, collection, 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, collection, 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 under its own wire name (`{ authorId: 5 }`, which\n * passes through to the `author_id` column untouched) and the relation\n * *property* (`{ author: 5 }`, which the write transformer maps onto that\n * 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 collection: CollectionConfig,\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 || !isRelationRequired(collection, relation);\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) {\n emit(fieldKeyForColumn(collection, relation.localKey), relation);\n }\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 field's **wire** name — the key it arrives under in\nJSON — and nothing here renames anything.\n\n- **A declared property is its key in the collection.** A property keyed\n \\`createdAt\\` is \\`row.createdAt\\`, whatever \\`columnName\\` says. A column name is\n the name of a different thing: where the value lives, not what the API calls it.\n- **A foreign key derived from a relation is camelCase**, because that is what\n the wire carries. A \\`belongsTo\\` named \\`author\\` gives you \\`row.authorId\\`, not\n the column spelling.\n- **A collection accessor is camelCase too** (\\`my-notes\\` → \\`rebase.data.myNotes\\`),\n which is what \\`collectionsDictionary\\` maps back to the slug.\n\n\\`where\\` and \\`orderBy\\` are keyed off the same type, so what compiles is what the\nbackend answers to.\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 \\`{ authorId: 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 holds the same line — a\nread never serves the column and a write naming it is refused — so this is a\nguarantee rather than a description, and nothing generated names a password\nhash.\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,SAAgB,YAAY,KAAqB;CAC7C,IAAI,CAAC,UAAU,KAAK,GAAG,GACnB,OAAO,IAAI,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,IAAI,MAAM,CAAC;CAEpD,MAAM,SAAS,aAAa,GAAG;CAC/B,OAAO,OAAO,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,OAAO,MAAM,CAAC;AAC1D;;;;;AAMA,SAAgB,iBAAiB,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YACA,mBACA,aACA,aACI;CAGJ,MAAM,QAAQ,KAAa,aAAqC;EAC5D,IAAI,YAAY,IAAI,GAAG,GAAG;EAC1B,MAAM,WAAW,eAAe,CAAC,mBAAmB,YAAY,QAAQ;EACxE,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,UAC1C,KAAK,kBAAkB,YAAY,SAAS,QAAQ,GAAG,QAAQ;CAIvE,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;;;ACjfA,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+Db,CAAC;CAGL,OAAO;AACX"}
package/package.json CHANGED
@@ -1,28 +1,39 @@
1
1
  {
2
2
  "name": "@rebasepro/codegen",
3
- "version": "0.17.3-canary.gdd23447",
3
+ "version": "0.18.0",
4
4
  "description": "Generate a typed JS SDK from Rebase collection definitions",
5
+ "keywords": [
6
+ "sdk",
7
+ "codegen",
8
+ "rebase",
9
+ "rest-api"
10
+ ],
11
+ "homepage": "https://rebase.pro",
12
+ "bugs": {
13
+ "url": "https://github.com/rebasepro/rebase/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/rebasepro/rebase.git",
18
+ "directory": "packages/codegen"
19
+ },
20
+ "license": "MIT",
21
+ "engines": {
22
+ "node": ">=22.22.0"
23
+ },
24
+ "author": "rebase.pro",
5
25
  "main": "./dist/index.es.js",
6
26
  "module": "./dist/index.es.js",
7
27
  "types": "./dist/index.d.ts",
8
28
  "type": "module",
9
- "source": "src/index.ts",
10
29
  "publishConfig": {
11
30
  "access": "public"
12
31
  },
13
32
  "files": [
14
33
  "dist"
15
34
  ],
16
- "keywords": [
17
- "sdk",
18
- "codegen",
19
- "rebase",
20
- "rest-api"
21
- ],
22
- "author": "rebase.pro",
23
- "license": "MIT",
24
35
  "peerDependencies": {
25
- "@rebasepro/types": "0.17.3-canary.gdd23447"
36
+ "@rebasepro/types": "0.18.0"
26
37
  },
27
38
  "devDependencies": {
28
39
  "@jest/globals": "^30.4.1",
@@ -32,25 +43,22 @@
32
43
  "ts-jest": "^29.4.12",
33
44
  "typescript": "^6.0.3",
34
45
  "vite": "^8.1.5",
35
- "@rebasepro/types": "0.17.3-canary.gdd23447"
46
+ "@rebasepro/types": "0.18.0"
36
47
  },
37
48
  "exports": {
38
49
  ".": {
39
50
  "types": "./dist/index.d.ts",
40
- "import": "./dist/index.es.js"
51
+ "import": "./dist/index.es.js",
52
+ "default": "./dist/index.es.js"
41
53
  }
42
54
  },
43
55
  "gitHead": "d935eefa5aa8d1009a2398cfac2c1e4ee9aeb6b6",
44
56
  "dependencies": {
45
- "@rebasepro/common": "0.17.3-canary.gdd23447"
46
- },
47
- "repository": {
48
- "type": "git",
49
- "url": "https://github.com/rebasepro/rebase.git",
50
- "directory": "packages/codegen"
57
+ "@rebasepro/common": "0.18.0"
51
58
  },
52
59
  "scripts": {
53
60
  "test": "jest --config jest.config.cjs",
61
+ "test:watch": "jest --config jest.config.cjs --watch",
54
62
  "build": "vite build && tsc --emitDeclarationOnly -p tsconfig.prod.json && node ../../tooling/scripts/add-dts-extensions.mjs dist && node ../../tooling/scripts/assert-build-output.mjs",
55
63
  "clean": "rm -rf dist && find ./src -name '*.js' -type f | xargs rm -f"
56
64
  }