@rebasepro/server 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/{GCSStorageController-sCw2c4aA.js → GCSStorageController-B3p3aUX-.js} +5 -5
  2. package/dist/{GCSStorageController-sCw2c4aA.js.map → GCSStorageController-B3p3aUX-.js.map} +1 -1
  3. package/dist/{S3StorageController-DDAq8Kt5.js → S3StorageController-C9LjuMhL.js} +5 -5
  4. package/dist/{S3StorageController-DDAq8Kt5.js.map → S3StorageController-C9LjuMhL.js.map} +1 -1
  5. package/dist/{access-Dtu87BMj.js → access-BxkEYQh1.js} +5 -5
  6. package/dist/{access-Dtu87BMj.js.map → access-BxkEYQh1.js.map} +1 -1
  7. package/dist/api/errors.d.ts +4 -0
  8. package/dist/api/rest/api-generator.d.ts +8 -0
  9. package/dist/{auth-BOz84vIr.js → auth-Bfwjg4Bg.js} +37 -13
  10. package/dist/auth-Bfwjg4Bg.js.map +1 -0
  11. package/dist/backend/create-backend.d.ts +6 -0
  12. package/dist/backend/options.d.ts +10 -0
  13. package/dist/backend/services.d.ts +9 -0
  14. package/dist/{backup-B-1oW6qX.js → backup-g2ohsDe0.js} +7 -7
  15. package/dist/{backup-B-1oW6qX.js.map → backup-g2ohsDe0.js.map} +1 -1
  16. package/dist/boot/bundle.d.ts +11 -1
  17. package/dist/boot/env.d.ts +5 -0
  18. package/dist/boot/security-headers.d.ts +15 -5
  19. package/dist/boot/static-routing.d.ts +58 -0
  20. package/dist/{branch-routes-0xhHXlGq.js → branch-routes-DtNtc0Vh.js} +3 -3
  21. package/dist/{branch-routes-0xhHXlGq.js.map → branch-routes-DtNtc0Vh.js.map} +1 -1
  22. package/dist/{contract-routes-o5oqNhfc.js → contract-routes-CZTlAP7p.js} +3 -3
  23. package/dist/{contract-routes-o5oqNhfc.js.map → contract-routes-CZTlAP7p.js.map} +1 -1
  24. package/dist/{cron-loader-BDN8plQK.js → cron-loader-BBP0kBIl.js} +2 -2
  25. package/dist/{cron-loader-BDN8plQK.js.map → cron-loader-BBP0kBIl.js.map} +1 -1
  26. package/dist/{cron-routes-BOu-bY7I.js → cron-routes-Du03uJ7K.js} +5 -5
  27. package/dist/{cron-routes-BOu-bY7I.js.map → cron-routes-Du03uJ7K.js.map} +1 -1
  28. package/dist/{cron-scheduler-DgrsqyQQ.js → cron-scheduler-CopTWKYB.js} +2 -2
  29. package/dist/{cron-scheduler-DgrsqyQQ.js.map → cron-scheduler-CopTWKYB.js.map} +1 -1
  30. package/dist/{cron-store-91cd9Qzv.js → cron-store-FGaZOdMf.js} +3 -3
  31. package/dist/{cron-store-91cd9Qzv.js.map → cron-store-FGaZOdMf.js.map} +1 -1
  32. package/dist/dist-C1vNURUy.js +19354 -0
  33. package/dist/dist-C1vNURUy.js.map +1 -0
  34. package/dist/{errors-DpTMfX77.js → errors-NVbAQU25.js} +5 -1
  35. package/dist/errors-NVbAQU25.js.map +1 -0
  36. package/dist/{filter-dialect-DAVl1Nsm.js → filter-dialect-XtPJOCbD.js} +2 -2
  37. package/dist/{filter-dialect-DAVl1Nsm.js.map → filter-dialect-XtPJOCbD.js.map} +1 -1
  38. package/dist/{function-loader-BeFbN1-A.js → function-loader-D3YEHF6E.js} +2 -2
  39. package/dist/{function-loader-BeFbN1-A.js.map → function-loader-D3YEHF6E.js.map} +1 -1
  40. package/dist/{function-routes-CIwLXsZF.js → function-routes-DNDFIa7t.js} +3 -3
  41. package/dist/{function-routes-CIwLXsZF.js.map → function-routes-DNDFIa7t.js.map} +1 -1
  42. package/dist/functions/index.d.ts +2 -0
  43. package/dist/functions/index.js +162 -1
  44. package/dist/functions/index.js.map +1 -1
  45. package/dist/functions/rate-limit.d.ts +71 -0
  46. package/dist/{history-recorder-CNeqtTaR.js → history-recorder-C5RkbKS2.js} +3 -3
  47. package/dist/{history-recorder-CNeqtTaR.js.map → history-recorder-C5RkbKS2.js.map} +1 -1
  48. package/dist/{history-store-DseUt_dm.js → history-store-DzrJeEKv.js} +2 -2
  49. package/dist/{history-store-DseUt_dm.js.map → history-store-DzrJeEKv.js.map} +1 -1
  50. package/dist/index.d.ts +6 -0
  51. package/dist/index.es.js +1241 -213
  52. package/dist/index.es.js.map +1 -1
  53. package/dist/{internal-tables-CHFJHH7N.js → internal-tables-XxM_NdR_.js} +2 -2
  54. package/dist/{internal-tables-CHFJHH7N.js.map → internal-tables-XxM_NdR_.js.map} +1 -1
  55. package/dist/{jobs-WCyKVsUf.js → jobs-CFUwQTao.js} +3 -3
  56. package/dist/{jobs-WCyKVsUf.js.map → jobs-CFUwQTao.js.map} +1 -1
  57. package/dist/{jwt-JtQiewBW.js → jwt-CqhXs8Iz.js} +3 -3
  58. package/dist/{jwt-JtQiewBW.js.map → jwt-CqhXs8Iz.js.map} +1 -1
  59. package/dist/{keys-BTPoSvUs.js → keys-Btt6ZNqF.js} +2 -2
  60. package/dist/{keys-BTPoSvUs.js.map → keys-Btt6ZNqF.js.map} +1 -1
  61. package/dist/{load-schema-Cv5XLVjW.js → load-schema-B4Nv1mwq.js} +32 -4
  62. package/dist/{load-schema-Cv5XLVjW.js.map → load-schema-B4Nv1mwq.js.map} +1 -1
  63. package/dist/{logs-routes-BT4af1Or.js → logs-routes-C3CLYP-n.js} +3 -3
  64. package/dist/{logs-routes-BT4af1Or.js.map → logs-routes-C3CLYP-n.js.map} +1 -1
  65. package/dist/{offline-D_wKJcO3-RV6C9HnX.js → offline-ET6xI1ZO-BQpLQ7wh.js} +124 -7
  66. package/dist/offline-ET6xI1ZO-BQpLQ7wh.js.map +1 -0
  67. package/dist/{offline-store-DtmBwmKE-B17N4609.js → offline-store-DtmBwmKE-C9ba2NJv.js} +3 -3
  68. package/dist/{offline-store-DtmBwmKE-B17N4609.js.map → offline-store-DtmBwmKE-C9ba2NJv.js.map} +1 -1
  69. package/dist/{openapi-generator-CoAFACMx.js → openapi-generator-CAhJiwBm.js} +3 -3
  70. package/dist/{openapi-generator-CoAFACMx.js.map → openapi-generator-CAhJiwBm.js.map} +1 -1
  71. package/dist/{project-root-qDQzmsUD.js → project-root-CIrVZi-r.js} +2 -2
  72. package/dist/{project-root-qDQzmsUD.js.map → project-root-CIrVZi-r.js.map} +1 -1
  73. package/dist/{proxy-D18_bcQI.js → proxy-clweqa43.js} +3 -3
  74. package/dist/{proxy-D18_bcQI.js.map → proxy-clweqa43.js.map} +1 -1
  75. package/dist/push/push-options.d.ts +26 -0
  76. package/dist/push/push-routes.d.ts +30 -0
  77. package/dist/push/push-service.d.ts +13 -0
  78. package/dist/push/push-store.d.ts +45 -0
  79. package/dist/push/set-up.d.ts +25 -0
  80. package/dist/push/subscription-input.d.ts +26 -0
  81. package/dist/push/vapid-config.d.ts +35 -0
  82. package/dist/push/web-push-crypto.d.ts +44 -0
  83. package/dist/push/web-push-sender.d.ts +10 -0
  84. package/dist/{query-parser-D9Uf8aha.js → query-parser-Cd70kZO8.js} +5 -5
  85. package/dist/{query-parser-D9Uf8aha.js.map → query-parser-Cd70kZO8.js.map} +1 -1
  86. package/dist/{request-timeout-CpOgfQPK.js → request-timeout-cC3HT1Pf.js} +3 -3
  87. package/dist/{request-timeout-CpOgfQPK.js.map → request-timeout-cC3HT1Pf.js.map} +1 -1
  88. package/dist/{rls-simulator-routes-BvH6wI64.js → rls-simulator-routes-DI2sYaQt.js} +4 -4
  89. package/dist/{rls-simulator-routes-BvH6wI64.js.map → rls-simulator-routes-DI2sYaQt.js.map} +1 -1
  90. package/dist/{schema-editor-routes-CzITcAgt.js → schema-editor-routes-DEGwyQmx.js} +5 -5
  91. package/dist/{schema-editor-routes-CzITcAgt.js.map → schema-editor-routes-DEGwyQmx.js.map} +1 -1
  92. package/dist/{schema-tables-lJHnyqj4.js → schema-tables-DKFg6vMV.js} +3 -3
  93. package/dist/{schema-tables-lJHnyqj4.js.map → schema-tables-DKFg6vMV.js.map} +1 -1
  94. package/dist/{schema-tables-routes-Uss-ljon.js → schema-tables-routes-BfsNG4c4.js} +5 -5
  95. package/dist/{schema-tables-routes-Uss-ljon.js.map → schema-tables-routes-BfsNG4c4.js.map} +1 -1
  96. package/dist/{securityRuleToConditions-DD40f3ml.js → securityRuleToConditions-Bk5zRSoa.js} +2 -2
  97. package/dist/{securityRuleToConditions-DD40f3ml.js.map → securityRuleToConditions-Bk5zRSoa.js.map} +1 -1
  98. package/dist/{selection-hgC1szl6.js → selection-BOnbJvXD.js} +2 -2
  99. package/dist/{selection-hgC1szl6.js.map → selection-BOnbJvXD.js.map} +1 -1
  100. package/dist/serve-spa.d.ts +12 -0
  101. package/dist/{soft-delete-params-DDRmxT2z.js → soft-delete-params-Dhn0qKFv.js} +2 -2
  102. package/dist/{soft-delete-params-DDRmxT2z.js.map → soft-delete-params-Dhn0qKFv.js.map} +1 -1
  103. package/dist/{sql-export-routes-BKmQZ3xh.js → sql-export-routes-B3oqb1Jw.js} +3 -3
  104. package/dist/{sql-export-routes-BKmQZ3xh.js.map → sql-export-routes-B3oqb1Jw.js.map} +1 -1
  105. package/dist/{src-DLIb1O9l.js → src-CNZB3fuE.js} +192 -3
  106. package/dist/src-CNZB3fuE.js.map +1 -0
  107. package/dist/{table-source-editor-qmyi5vxX.js → table-source-editor-D_zNDhEU.js} +3 -3
  108. package/dist/{table-source-editor-qmyi5vxX.js.map → table-source-editor-D_zNDhEU.js.map} +1 -1
  109. package/dist/{upload-validation-B-psYLaN.js → upload-validation-BnIwo78L.js} +2 -2
  110. package/dist/{upload-validation-B-psYLaN.js.map → upload-validation-BnIwo78L.js.map} +1 -1
  111. package/package.json +5 -5
  112. package/dist/auth-BOz84vIr.js.map +0 -1
  113. package/dist/dist-fBcYxf4h.js +0 -19354
  114. package/dist/dist-fBcYxf4h.js.map +0 -1
  115. package/dist/errors-DpTMfX77.js.map +0 -1
  116. package/dist/offline-D_wKJcO3-RV6C9HnX.js.map +0 -1
  117. package/dist/src-DLIb1O9l.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"openapi-generator-CoAFACMx.js","names":[],"sources":["../../utils/dist/regexp.es.js","../../utils/dist/labels.es.js","../../common/src/table/table-options.ts","../../common/src/table/validation.ts","../src/api/openapi-generator.ts"],"sourcesContent":["//#region src/regexp.ts\n/** A missing RegExp serializes to the empty string. */\nfunction serializeRegExp(input) {\n\tif (!input) return \"\";\n\treturn input.toString();\n}\n/**\n* Get a RegExp out of a serialized string\n* @param input\n*/\nfunction hydrateRegExp(input) {\n\tif (!input) return void 0;\n\tconst fragments = input.match(/^\\/(.*)\\/([a-z]*)$/i);\n\tif (fragments) return new RegExp(fragments[1], fragments[2] || \"\");\n\telse return new RegExp(input, \"\");\n}\n/**\n* Is `input` something {@link hydrateRegExp} can turn into a working RegExp?\n*\n* This used to pattern-match the *shape* of a regex literal and, failing that,\n* fall back to \"does it contain any regex-ish character\" — which said yes to\n* malformed input like `/[a-z/g`. The only answer that matters to a caller is\n* whether hydration succeeds, so ask the engine instead of approximating it.\n*/\nfunction isValidRegExp(input) {\n\tif (!input) return false;\n\ttry {\n\t\treturn hydrateRegExp(input) !== void 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n//#endregion\nexport { hydrateRegExp, isValidRegExp, serializeRegExp };\n\n//# sourceMappingURL=regexp.es.js.map","import { prettifyIdentifier } from \"./strings.es.js\";\nimport { singular } from \"./plurals.es.js\";\n//#region src/labels.ts\n/**\n* The words an identifier reads as, for a person.\n*\n* One rule, shared by every party that derives a label from a name the\n* backend serves: the zero-config CMS (`@rebasepro/cms`, which labels every\n* projected table, column, relation and enum value with these) and the\n* collections-to-tables codemod (which drops a legacy label equal to the\n* derived one, so a migrated `customizeTable` file states only real deltas).\n* Two copies of the rule would disagree, and the codemod would then drop a\n* label the panel does not derive.\n*\n* Every label is a pure function of the identifier — no translation, because\n* an identifier has no language.\n*/\n/**\n* Words that read as initialisms. `prettifyIdentifier` title-cases them\n* (`author_id` → \"Author Id\"), which is the one place its output looks wrong.\n*/\nvar INITIALISMS = {\n\tid: \"ID\",\n\tids: \"IDs\",\n\turl: \"URL\",\n\turls: \"URLs\",\n\tuuid: \"UUID\",\n\tapi: \"API\",\n\tip: \"IP\"\n};\n/**\n* A human label for a column, relation or table key.\n*\n* `first_name`, `firstName` and `FirstName` all read \"First Name\"; `author_id`\n* reads \"Author ID\"; leading underscores are dropped (`__order` → \"Order\").\n*\n* @group Labels\n*/\nfunction labelFromIdentifier(identifier) {\n\treturn prettifyIdentifier(identifier).split(\" \").filter((word) => word.length > 0).map((word) => INITIALISMS[word.toLowerCase()] ?? word).join(\" \");\n}\n/**\n* The singular of a plural label, changing only its last word.\n*\n* {@link singular} strips any trailing \"s\", so words that only look plural\n* are kept as they are: a double-s ending (`Address`, `Class`), and the Latin\n* `-us` / `-is` endings (`Status`, `Analysis`). The first letter keeps its\n* case, because `singular` lower-cases irregular forms (\"People\" → \"person\").\n*\n* @group Labels\n*/\nfunction singularLabel(label) {\n\tconst words = label.split(\" \");\n\tconst last = words[words.length - 1];\n\tif (!last || /(ss|us|is)$/i.test(last)) return label;\n\tconst single = singular(last);\n\tif (single.length === 0) return label;\n\tconst cased = last[0] === last[0].toUpperCase() ? single.charAt(0).toUpperCase() + single.slice(1) : single;\n\treturn [...words.slice(0, -1), cased].join(\" \");\n}\n/**\n* The label of one value of a closed set (an enum): a string reads as its\n* identifier does (`needs_review` → \"Needs Review\"), a number as itself.\n*\n* @group Labels\n*/\nfunction enumValueLabel(value) {\n\treturn typeof value === \"string\" ? labelFromIdentifier(value) : String(value);\n}\n//#endregion\nexport { enumValueLabel, labelFromIdentifier, singularLabel };\n\n//# sourceMappingURL=labels.es.js.map","import type { ColumnDescriptor, TableDescriptor, TenantDescriptor } from \"@rebasepro/types\";\nimport { DEFAULT_TENANT_BYPASS_ROLES } from \"@rebasepro/types\";\nimport { DEFAULT_TABLE_SCHEMA } from \"../schema/derive-names\";\n\n/**\n * Table-level options read from a {@link TableDescriptor}: the schema it is\n * declared in, soft delete and tenancy. The compiler already checked them (the soft-delete column exists\n * and is temporal, the tenant column exists and has a key type), so these do\n * no defaulting of their own.\n *\n * @module\n */\n\n/**\n * The column a soft-delete table records a deletion in — what a delete\n * stamps and a restore (an update setting it to `null`) clears — or\n * `undefined` for a table without soft delete.\n *\n * Replaces `softDeleteFieldOf(collection)` plus the `columnName ??\n * toSnakeCase(field)` that found its SQL name: both names are on the column.\n *\n * @group Table\n */\nexport function softDeleteColumn(table: TableDescriptor): ColumnDescriptor | undefined {\n const field = table.softDelete?.field;\n if (field === undefined) return undefined;\n return table.columns.find(column => column.key === field);\n}\n\n/**\n * Whether an update's values restore a soft-deleted row: they set the\n * soft-delete column back to `null`.\n *\n * Replaces `restoresSoftDeletedRow(collection, values)`.\n *\n * @group Table\n */\nexport function isSoftDeleteRestore(table: TableDescriptor, values: Record<string, unknown> | undefined): boolean {\n const field = table.softDelete?.field;\n return field !== undefined && values?.[field] === null;\n}\n\n/**\n * A table's tenancy with its defaults applied, or `undefined` for a table\n * rows of which are not scoped to a tenant.\n *\n * Replaces `getTenantConfig(collection)` and `tenantBypassRoles(tenant)`.\n *\n * @group Table\n */\nexport function tenantOf(table: TableDescriptor): (TenantDescriptor & { bypassRoles: readonly string[] }) | undefined {\n const tenant = table.tenant;\n if (!tenant) return undefined;\n return { ...tenant, bypassRoles: tenant.bypassRoles ?? DEFAULT_TENANT_BYPASS_ROLES };\n}\n\n/**\n * The Postgres schema a table names apart from the default one, or\n * `undefined` for a table in `public`.\n *\n * `public` is where a table lands without a qualifier, so nothing declares it:\n * no `CREATE SCHEMA`, no `pgSchema(\"public\")` in a generated Drizzle file\n * (Drizzle refuses that one). Every other schema is created and qualified.\n *\n * @group Table\n */\nexport function declaredSchemaOf(table: Pick<TableDescriptor, \"schema\">): string | undefined {\n return table.schema === DEFAULT_TABLE_SCHEMA ? undefined : table.schema;\n}\n","import type { ColumnDescriptor, ColumnValidation } from \"@rebasepro/types\";\nimport { hydrateRegExp } from \"@rebasepro/utils\";\n\n/**\n * The validation rules of a column, as the API checks them and the documents\n * that describe the API (OpenAPI, the panel's forms) state them.\n *\n * @module\n */\n\n/**\n * The pattern `validate({ matches })` holds a text value to, as a `RegExp`\n * that can be tested repeatedly, or `undefined` when there is none (or it does\n * not compile).\n *\n * A pattern given as a `RegExp` is stored as its source and `matchesFlags`;\n * one given as a string is read the way the panel reads it (`hydrateRegExp`),\n * so `\"/^[A-Z]{2}$/i\"` means the same on both sides. `g` and `y` are dropped:\n * they keep `lastIndex` between calls, so one pattern would accept and refuse\n * the same value on alternate rows of a bulk write.\n *\n * @group Table\n */\nexport function validationPattern(rules: Pick<ColumnValidation, \"matches\" | \"matchesFlags\"> | undefined): RegExp | undefined {\n const matches = rules?.matches;\n if (matches === undefined || matches === \"\") return undefined;\n try {\n const pattern = rules?.matchesFlags !== undefined ? new RegExp(matches, rules.matchesFlags) : hydrateRegExp(matches);\n if (!pattern) return undefined;\n return new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, \"\"));\n } catch {\n return undefined;\n }\n}\n\n/**\n * The longest text the API accepts for a column: `validate({ max })` when the\n * column states one, else the length of a `varchar(n)` / `char(n)` other than\n * the default 255, else `undefined`.\n *\n * The default length is not checked by the API: it is what a text column with\n * no stated length has always been given, and Postgres refuses a longer value\n * itself.\n *\n * @group Table\n */\nexport function textMaxLength(column: Pick<ColumnDescriptor, \"type\" | \"validate\">): number | undefined {\n const max = column.validate?.max;\n if (typeof max === \"number\") return max;\n const type = column.type;\n if ((type.kind === \"varchar\" || type.kind === \"char\") && type.length !== 255) return type.length;\n return undefined;\n}\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && !(value instanceof Date);\n\n/**\n * A value as a key two equal values share: JSON with sorted object keys, a\n * date as its ISO instant. What `uniqueItems` and `uniqueBy` compare by.\n *\n * @group Table\n */\nexport function sameValueKey(value: unknown): string {\n const stable = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(stable);\n if (v instanceof Date) return v.toISOString();\n if (isPlainRecord(v)) return Object.fromEntries(Object.keys(v).sort().map(k => [k, stable(v[k])]));\n return v;\n };\n return `${typeof value}:${JSON.stringify(stable(value))}`;\n}\n\n/**\n * The positions of the first two equal items of a list — compared whole, or,\n * with `field`, by that field of each object item (`uniqueBy`) — or\n * `undefined` when every item differs. With `field`, an item that is not an\n * object or has no value there (absent or `null`) is not compared: a rule of\n * uniqueness says nothing about a value that is not there.\n *\n * @group Table\n *\n * @internal Shared with @rebasepro/server's write validation; not part of the public API.\n */\nexport function firstDuplicate(items: readonly unknown[], field?: string): [number, number] | undefined {\n const seen = new Map<string, number>();\n for (const [index, item] of items.entries()) {\n let value: unknown = item;\n if (field !== undefined) {\n value = isPlainRecord(item) ? item[field] : undefined;\n if (value === undefined || value === null) continue;\n }\n const key = sameValueKey(value);\n const first = seen.get(key);\n if (first !== undefined) return [first, index];\n seen.set(key, index);\n }\n return undefined;\n}\n","import {\n DEFAULT_LIST_LIMIT,\n MAX_LIST_LIMIT,\n isNumericColumnType,\n isTemporalColumnType,\n isTextColumnType,\n type ColumnAccess,\n type ColumnDescriptor,\n type ColumnStorage,\n type ColumnType,\n type ColumnValidation,\n type JsonShape,\n type RelationDescriptor,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport { boundKeyColumn, columnAccess, relationJoinColumns, tenantOf, textMaxLength, validationPattern } from \"@rebasepro/common\";\nimport { labelFromIdentifier, singularLabel } from \"@rebasepro/utils\";\nimport { DELETED_QUERY_PARAM, HARD_DELETE_QUERY_PARAM } from \"./rest/soft-delete-params\";\nimport type { TableLookup } from \"./rest/served-table\";\n\n/**\n * OpenAPI 3.0.3 specification generator.\n *\n * Produces a spec that exactly mirrors the REST API consumed by the\n * Rebase SDK client (`@rebasepro/client`).\n *\n * Routes are mounted at `{basePath}/data/{slug}` by `initializeRebaseBackend`.\n */\n\nexport interface OpenApiGeneratorOptions {\n /** Base path for the API (e.g. \"/api\"). Defaults to \"/api\". */\n basePath?: string;\n /** Whether auth is enabled on data routes. Defaults to true. */\n requireAuth?: boolean;\n /**\n * The list-pagination bounds the REST layer applies, so the spec states the\n * ones a request will actually meet.\n *\n * These were hardcoded as `default: 20, maximum: 100` — neither of which\n * the server has ever used. The spec drives the API Explorer and is what a\n * generated client is built from, so an understated ceiling is a request\n * the client refuses to make, and an overstated one is a 400 nobody\n * predicted.\n */\n listLimits?: { defaultLimit?: number; maxLimit?: number };\n}\n\n/**\n * A table as the document names it: its descriptor, and the labels its tags,\n * summaries and component names are built from.\n */\ninterface DocumentedTable {\n table: TableDescriptor;\n slug: string;\n /** \"Order Items\": the tag, and the plural in summaries. */\n name: string;\n /** \"Order Item\": the singular in summaries, and the stem of the component name. */\n singularName: string;\n description?: string;\n}\n\n/**\n * The labels a table is documented under, from its slug alone.\n *\n * A table has no labels of its own (presentation is the panel's,\n * `customizeTable`); these are the defaults a collection that declared none\n * was always given — `order_items` → \"Order Items\" / \"Order Item\" — through\n * the same `@rebasepro/utils` helpers, so every component name, `$ref` and\n * `operationId` in the document stays what it was.\n */\nfunction documentedNames(slug: string): Pick<DocumentedTable, \"slug\" | \"name\" | \"singularName\"> {\n const name = labelFromIdentifier(slug);\n return { slug, name, singularName: singularLabel(name) };\n}\n\n/**\n * The OpenAPI document of the data API, built from the served tables'\n * descriptors.\n *\n * @param tables the tables the data routes serve, in the order they are\n * documented. A relation's target is described from this list too; one that\n * is not in it is documented as an open object.\n */\nexport function generateOpenApiSpec(\n tables: readonly TableDescriptor[],\n options: OpenApiGeneratorOptions = {}\n): Record<string, unknown> {\n const lookup: TableLookup = name => tables.find(table => table.slug === name) ?? tables.find(table => table.table === name);\n const collections: DocumentedTable[] = tables.map(table => ({\n table,\n ...documentedNames(table.slug),\n ...(table.description !== undefined ? { description: table.description } : {})\n }));\n const basePath = options.basePath ?? \"/api\";\n const requireAuth = options.requireAuth ?? true;\n const defaultLimit = options.listLimits?.defaultLimit ?? DEFAULT_LIST_LIMIT;\n const maxLimit = options.listLimits?.maxLimit ?? MAX_LIST_LIMIT;\n\n /**\n * The query parameters every list endpoint honours.\n *\n * Written once because it was written twice: the root listing named eight\n * and the subcollection listing named four, though both go through the same\n * `parseQueryOptions` and the same fetch. Four capabilities were therefore\n * unreachable from a generated client on nested routes, and `or`/`and` were\n * undocumented on both.\n */\n const listQueryParameters = () => [\n { name: \"limit\", in: \"query\", schema: { type: \"integer\", default: defaultLimit, minimum: 1, maximum: maxLimit },\n description: `Maximum number of records to return. Must be a whole number between 1 and ${maxLimit}; a larger one is rejected with 400 INVALID_LIMIT rather than trimmed, so a short page always means a short table. Page past the ceiling with \\`offset\\`.` },\n { name: \"offset\", in: \"query\", schema: { type: \"integer\", default: 0 },\n description: \"Number of records to skip\" },\n { name: \"page\", in: \"query\", schema: { type: \"integer\", minimum: 1 },\n description: \"Page number (alternative to offset). Calculates offset as (page-1)*limit. Cannot be combined with `offset` (400 PAGE_WITH_OFFSET).\" },\n {\n name: \"after\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Keyset cursor: continue after the row the previous page ended on. Pass back \"\n + \"`meta.nextCursor` from that response, unchanged — it is opaque, and encodes both the \"\n + \"sort keys and the last row's values for them. Unlike `offset`, a row inserted or \"\n + \"deleted before the cursor cannot shift the window, so a walk neither repeats nor \"\n + \"skips rows. Cannot be combined with `offset`/`page` (400 CURSOR_WITH_OFFSET), and an \"\n + \"`orderBy` different from the one the cursor was issued under is refused \"\n + \"(400 CURSOR_ORDER_MISMATCH) rather than seeked in an order nobody asked for.\"\n },\n {\n name: \"orderBy\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Sort field and direction. Accepts `field:asc`, `field:desc`, or `field:desc:last` — \"\n + \"the third segment places NULLs (`first`/`last`), defaulting to Postgres's own \"\n + \"convention (last ascending, first descending). Also accepts a JSON array \"\n + \"`[{\\\"field\\\":\\\"name\\\",\\\"direction\\\":\\\"asc\\\",\\\"nulls\\\":\\\"last\\\"}]` — several entries sort by \"\n + \"each in turn, the second breaking ties on the first.\",\n example: \"created_at:desc:last\"\n },\n {\n name: \"where\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"JSON object filter, mapping each field to a `[operator, value]` tuple. \"\n + \"Combines with the per-field `?field=op.value` parameters below; on the same field, the per-field parameter wins.\",\n example: \"{\\\"status\\\":[\\\"==\\\",\\\"active\\\"]}\"\n },\n {\n name: \"or\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"Disjunction of conditions, AND-ed with `where` and `searchString`.\",\n example: \"(status.eq.draft,status.eq.review)\"\n },\n {\n name: \"and\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"Conjunction of conditions, AND-ed with `where` and `searchString`. Ignored when `or` is also present.\",\n example: \"(views.gte.10,status.eq.draft)\"\n },\n {\n name: \"not\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Negation, AND-ed with `where` and `searchString`. Negates the **conjunction** of its \"\n + \"conditions: `not(a)` is `NOT a`, `not(a,b)` is `NOT (a AND b)`. Groups nest, so \"\n + \"`not(or(a,b))` is the De Morgan case. Compiles to a real SQL `NOT (...)`, which — \"\n + \"three-valued logic — also excludes rows whose column is NULL. Ignored when `or` or \"\n + \"`and` is also present.\",\n example: \"(status.eq.draft,views.gte.10)\"\n },\n {\n name: \"include\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Relations to load, in either of two spellings. **Comma-separated names or dotted \"\n + \"paths** — `author,comments.author`, up to 3 hops deep; `*` loads every relation one \"\n + \"hop deep. **JSON**, when a relation needs narrowing — \"\n + \"`{\\\"comments\\\":{\\\"limit\\\":5,\\\"where\\\":{\\\"published\\\":[\\\"==\\\",true]},\"\n + \"\\\"orderBy\\\":\\\"created_at:desc\\\",\\\"fields\\\":\\\"id,body\\\",\\\"include\\\":{\\\"author\\\":true}}}`. \"\n + \"A value starting with `{` is read as the JSON form. A name that is not a relation of \"\n + \"the table is a 400 UNKNOWN_RELATION, not a silently missing field.\",\n example: \"author,comments.author\"\n },\n {\n name: \"fields\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Comma-separated columns to return. A projection pushed into the SELECT, so a query \"\n + \"that needs two fields of a wide row reads two columns. The primary key is always \"\n + \"returned (a row that cannot be addressed cannot be updated, deleted, or paged past), \"\n + \"and `excludeFromApi` columns stay hidden whether or not they are named here. An \"\n + \"unknown column is a 400 UNKNOWN_FIELD.\",\n example: \"id,name,created_at\"\n },\n {\n name: \"distinct\",\n in: \"query\",\n schema: { type: \"boolean\" },\n description:\n \"`SELECT DISTINCT` over the returned columns. Only meaningful alongside `fields`: the \"\n + \"primary key is always in the projection, so without narrowing it every row is \"\n + \"already distinct. The response has no `meta.total` — the rows before deduplication \"\n + \"are a different set, so their count would not describe the page — and `meta.hasMore` \"\n + \"comes from reading one row past the page. Refused (400) alongside \"\n + \"`searchString` or a vector search, which attach a per-row score that makes every row \"\n + \"distinct by construction, and (400 DISTINCT_ORDER_BY_NOT_SELECTED) when `orderBy` \"\n + \"names a column `fields` does not return.\",\n example: \"true\"\n },\n {\n name: \"count\",\n in: \"query\",\n schema: { type: \"string\", enum: [\"exact\", \"none\"], default: \"exact\" },\n description:\n \"Whether to count every matching row for `meta.total`. `exact` (the default) runs a \"\n + \"`COUNT(*)` beside the page, which on a large table costs more than the page itself; \"\n + \"`none` skips it, and the response then has no `meta.total`. `meta.hasMore` is exact \"\n + \"either way — without a count it comes from reading one row past the page — so a walk \"\n + \"that pages until `hasMore` is false needs no count. Anything else is a 400 INVALID_COUNT.\",\n example: \"none\"\n },\n {\n name: \"searchString\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Text search. By default a case-insensitive substring match OR-ed across the \" +\n \"table's top-level text columns. A table declaring a `search` block \" +\n \"gets ranked full-text matching over the fields it names, and rows carry a `_score`.\"\n },\n // Vector search has been served here since vectors landed and was\n // documented nowhere, so the only way to find it was to read the query\n // parser. All four are needed together; `vector_search` and `vector`\n // are ignored unless both are present.\n {\n name: \"vector_search\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"Name of the `vector` property to run a nearest-neighbour search against. Requires `vector`.\",\n example: \"embedding\"\n },\n {\n name: \"vector\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"The query embedding, as a JSON array of numbers. Its length must match the property's declared `dimensions`.\",\n example: \"[0.12,-0.04,0.98]\"\n },\n {\n name: \"vector_distance\",\n in: \"query\",\n schema: { type: \"string\", enum: [\"cosine\", \"l2\", \"inner_product\"], default: \"cosine\" },\n description: \"Distance function used for ordering.\"\n },\n {\n name: \"vector_threshold\",\n in: \"query\",\n schema: { type: \"number\" },\n description: \"Drop rows farther than this distance. Rows are returned closest-first with a `_distance` field. \"\n + \"The response then has no `meta.total`: counting the rows within a distance computes it for every row \"\n + \"of the table. `meta.hasMore` is exact, from reading one row past the page.\"\n }\n ];\n\n const spec: Record<string, unknown> = {\n openapi: \"3.0.3\",\n info: {\n title: \"Rebase API\",\n version: \"1.0.0\",\n description:\n \"Auto-generated REST API from Rebase table definitions. \" +\n \"This is the same API consumed by the `@rebasepro/client` SDK.\"\n },\n servers: [\n {\n url: basePath,\n description: \"API Server\"\n }\n ],\n paths: {} as Record<string, unknown>,\n components: {\n schemas: {\n ErrorResponse: {\n type: \"object\",\n properties: {\n error: {\n type: \"object\",\n required: [\"message\", \"code\"],\n properties: {\n message: { type: \"string\" },\n code: { type: \"string\" },\n details: {}\n }\n }\n }\n },\n PaginationMeta: {\n type: \"object\",\n properties: {\n total: { type: \"integer\",\ndescription: \"Total number of matching records. Absent on a `distinct` read, which has no count of the rows it returns, on a vector search with a `vector_threshold`, whose count would compute a distance for every row, and when the request asked for `count=none`.\" },\n limit: { type: \"integer\",\ndescription: \"Page size used for this query\" },\n offset: { type: \"integer\",\ndescription: \"Number of records skipped\" },\n hasMore: { type: \"boolean\",\ndescription: \"Whether more records exist beyond this page\" },\n nextCursor: {\n type: \"string\",\n description:\n \"Opaque keyset cursor continuing this listing — pass it back as `?after=`. \"\n + \"Present when `hasMore` is true and the page returned at least one row; \"\n + \"absent on the last page and on an ordering no cursor can describe \"\n + \"(relevance, whose scores are computed per query and not stored). Do not \"\n + \"parse it: the encoding exists to be changed.\"\n }\n }\n }\n } as Record<string, unknown>,\n securitySchemes: {} as Record<string, unknown>\n },\n tags: [] as Array<{ name: string; description?: string }>\n };\n\n // ── Security Schemes ─────────────────────────────────────────────────\n if (requireAuth) {\n (spec.components as Record<string, unknown>).securitySchemes = {\n bearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n description:\n \"JWT access token obtained from `POST /auth/login` or `POST /auth/register`. \" +\n \"Can also be a static service key for server-to-server authentication.\"\n }\n // No `?token=` scheme. It was declared here — globally, so on every\n // operation — and no data route has ever accepted one: both\n // `createAuthMiddleware` and `createAdapterAuthMiddleware` read the\n // `Authorization` header and nothing else, deliberately, because\n // URLs leak into access logs, proxies, Referer headers and browser\n // history (`auth/middleware.ts`). Following it cost a caller twice:\n // unauthenticated, *and* a 400, since `token` is not in the query\n // parser's `reservedQueryKeys` and so compiles as a filter on a\n // column named `token`. `queryTokenAuth` is real but is mounted\n // only on storage file serving, for `<img src>`; if those routes\n // are ever documented, the scheme belongs on them, per-operation.\n };\n (spec as Record<string, unknown>).security = [\n { bearerAuth: [] }\n ];\n }\n\n const paths = spec.paths as Record<string, unknown>;\n const schemas = (spec.components as Record<string, unknown>).schemas as Record<string, unknown>;\n const tags = spec.tags as Array<{ name: string; description?: string }>;\n\n // The names a listing has already spent. A collection is free to have a\n // `limit` or a `fields` column, and the query parser reads those names as\n // pagination and field selection before any filter is compiled — so the\n // per-field filter could never fire, and documenting it a second time put\n // two parameters with the same (`name`, `in`) pair on one operation, which\n // is invalid OpenAPI: Swagger UI renders a duplicate and several generators\n // abort. Taken from the parameter list itself so the two cannot drift.\n //\n // `deleted` too: the parser reads it as the soft-delete parameter on every\n // collection (a value other than `include`/`only` is a 400), so a filter\n // on a column of that name never runs either.\n const reservedParameterNames = new Set([...listQueryParameters().map(p => p.name), DELETED_QUERY_PARAM]);\n\n /**\n * `?deleted=` on the reads of a `softDelete` collection. A delete there\n * moves the row to the trash, and every read hides trashed rows unless it\n * asks for them; the list, the single row, the count and the aggregate all\n * honour this. Empty for any other collection.\n */\n const deletedParameters = (collection: DocumentedTable) => {\n const field = collection.table.softDelete?.field;\n if (!field) return [];\n return [{\n name: DELETED_QUERY_PARAM,\n in: \"query\",\n required: false,\n schema: { type: \"string\", enum: [\"include\", \"only\"] },\n description:\n `Rows a delete moved to the trash (\\`${field}\\` set) are left out unless this asks for them: ` +\n \"`include` reads them with the live rows, `only` reads them alone. Any other value is a \" +\n \"400 INVALID_DELETED_PARAM.\"\n }];\n };\n\n /**\n * `?hard=` on the deletes of a `softDelete` collection: delete for good\n * rather than move to the trash. Empty for any other collection.\n */\n const hardDeleteParameters = (collection: DocumentedTable) => {\n if (!collection.table.softDelete) return [];\n return [{\n name: HARD_DELETE_QUERY_PARAM,\n in: \"query\",\n required: false,\n schema: { type: \"boolean\", default: false },\n description:\n \"`true` deletes for good instead of moving to the trash — a row already in the trash \" +\n \"included, which is how the trash is emptied. Only `true`/`1` and `false`/`0` are \" +\n \"accepted; anything else is a 400 INVALID_HARD_PARAM.\"\n }];\n };\n\n /** What a delete does to a `softDelete` collection's row, for the delete operations' descriptions. */\n const softDeleteBehaviour = (collection: DocumentedTable): string | undefined => {\n const field = collection.table.softDelete?.field;\n if (!field) return undefined;\n return `This table soft-deletes: a delete moves the row to the trash by stamping \\`${field}\\`, ` +\n \"and every read leaves it out unless it passes `?deleted=include` or `?deleted=only`. A PATCH \" +\n `setting \\`${field}\\` back to \\`null\\` restores it. Pass \\`?hard=true\\` to delete for good.`;\n };\n\n // Every component name this document will carry, known before the first\n // schema is built: a relation may point at a collection that appears later\n // in the list, or at one that is not documented here at all, and a `$ref`\n // at a component that does not exist is a document Swagger UI renders empty\n // and a strict generator refuses.\n const registeredSchemas = new Set((collections || []).map(schemaNameFor));\n\n /**\n * `Prefer: return=minimal`, on every route that would otherwise send a row\n * back. Documented rather than left implicit because a client generated\n * from this spec cannot send a header the spec does not mention.\n */\n const preferHeader = {\n name: \"Prefer\",\n in: \"header\",\n required: false,\n schema: { type: \"string\", enum: [\"return=minimal\"] },\n description:\n \"`return=minimal` asks the server not to send the written row back. Single writes then \" +\n \"answer `204 No Content`; bulk and batch writes answer `200` carrying the ids only. \" +\n \"The response repeats it in `Preference-Applied` when it was honoured.\"\n };\n\n const ifMatchHeader = {\n name: \"If-Match\",\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description:\n \"The `ETag` this edit was made against, from the `GET` that read the row. The write is \" +\n \"refused with `412` if the row has changed since — which is the difference between \" +\n \"\\\"update the row I read\\\" and \\\"overwrite whatever is there now\\\". `*` means only that \" +\n \"the row must exist.\"\n };\n\n const preconditionFailed = {\n 412: {\n description:\n \"The row changed since the ETag in `If-Match` was issued. Nothing was written: \" +\n \"re-read the row, re-apply the change, and send the new ETag\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n }\n };\n\n const minimalResponse = {\n 204: {\n description: \"Written. `Prefer: return=minimal` was honoured, so there is no body\",\n headers: {\n \"Preference-Applied\": { schema: { type: \"string\" }, description: \"`return=minimal`\" }\n }\n }\n };\n\n // ── POST /data/_batch — writes across collections, one transaction ────\n //\n // Registered before the per-collection paths for the same reason the route\n // is: `_batch` is not a collection, and reading it as one would document a\n // table that does not exist.\n if ((collections || []).length > 0) {\n paths[\"/data/_batch\"] = {\n post: {\n tags: [\"Data\"],\n summary: \"Write across tables in one transaction\",\n description:\n \"All-or-nothing across tables — an order and its line items, a user and \" +\n \"their membership row. `/bulk` is one table at a time, and sending the two \" +\n \"halves as separate requests is exactly the sequence that can half-succeed.\\n\\n\" +\n \"Operations run in order, each through the same pipeline its single-row route \" +\n \"uses: the same validation, callbacks and row-level security, as the same role. \" +\n \"An operation may name itself with `ref`, and a later one may stand \" +\n \"`{ \\\"$ref\\\": \\\"order.id\\\" }` wherever a value goes — in `values`, at any depth, \" +\n \"or as an `id`. Only backward references resolve.\\n\\n\" +\n \"Capped at the same number of entries as a bulk write, because one batch is one \" +\n \"transaction and holds its locks for the whole of it.\",\n operationId: \"batchWrite\",\n parameters: [\n {\n name: \"Idempotency-Key\",\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description:\n \"Names this batch so a retry is recognised instead of repeated. Without it a \" +\n \"client that lost the response cannot tell a replay from a second batch, and \" +\n \"the whole batch is written twice.\"\n },\n preferHeader\n ],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"operations\"],\n properties: {\n operations: {\n type: \"array\",\n items: { $ref: \"#/components/schemas/BatchOperation\" }\n }\n }\n }\n }\n }\n },\n responses: {\n 200: {\n description:\n \"One entry per operation, in order: the written row for a create, update or \" +\n \"upsert, and `null` for a delete\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n data: { type: \"array\", items: { type: \"object\", nullable: true } },\n meta: { type: \"object\", properties: { operations: { type: \"integer\" } } }\n }\n }\n }\n }\n },\n 400: {\n description:\n \"Malformed body, an unknown table or field, an illegal field operation \" +\n \"or conflict target, a forward `$ref`, or more operations than the limit. \" +\n \"Nothing was written\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 404: {\n description: \"An `update` or `delete` names a row that does not exist; nothing was written\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 409: {\n description: \"A request with the same Idempotency-Key is still in flight\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 422: {\n description: \"The Idempotency-Key was already used for a different request\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n ...errorResponses(requireAuth)\n }\n }\n };\n\n schemas.FieldOperation = {\n type: \"object\",\n description:\n \"A change to the column's current value rather than the value to store. Exactly one \" +\n \"operator per field. Only on an update: an operation over a value that does not exist \" +\n \"yet is refused with a 400.\",\n properties: {\n $inc: { type: \"number\", description: \"Add to a `number` column; negative to subtract.\" },\n $push: { description: \"Append a value, or each of an array of values, to an `array` column.\" },\n $pull: { description: \"Remove every occurrence of a value from an `array` column.\" },\n $merge: { type: \"object\", description: \"Shallow-merge an object into a `map` column.\" }\n }\n };\n\n schemas.BatchOperation = {\n type: \"object\",\n required: [\"op\", \"table\"],\n properties: {\n op: { type: \"string\", enum: [\"create\", \"update\", \"upsert\", \"delete\"] },\n table: { type: \"string\", description: \"The slug of the table this operation writes to.\" },\n id: {\n description:\n \"Required for `update` and `delete`. May instead be a reference marker — an \" +\n \"object whose single key is `$ref` and whose value is `<ref name>.<field>`, \" +\n \"e.g. `{ \\\"$ref\\\": \\\"order.id\\\" }` — naming a column of the row an earlier \" +\n \"operation wrote. (Described rather than declared as a schema: `$ref` is a \" +\n \"reserved word to every OpenAPI reader, and a property named `$ref` is read \" +\n \"as a reference and mangled.)\",\n oneOf: [{ type: \"string\" }, { type: \"integer\" }, { type: \"object\" }]\n },\n values: {\n type: \"object\",\n description:\n \"The row's fields. Values may be `$ref` markers; an `update` may also carry \" +\n \"field operations.\",\n additionalProperties: true\n },\n onConflict: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"`upsert` only: the columns the conflict is matched on. Must carry a declared \" +\n \"uniqueness guarantee. Defaults to the primary key.\"\n },\n ref: {\n type: \"string\",\n description: \"Names this operation's result, so a later one can `$ref` its columns.\"\n }\n }\n };\n }\n\n // ── Collection routes ────────────────────────────────────────────────\n for (const collection of (collections || [])) {\n const schemaName = schemaNameFor(collection);\n const slug = collection.slug;\n\n tags.push({\n name: collection.name,\n description: collection.description || `CRUD operations for ${collection.name}`\n });\n\n // Build component schema for this collection\n schemas[schemaName] = buildTableSchema(collection.table, registeredSchemas, lookup);\n\n // Build an \"input\" schema (no read-only/auto fields like autoValue dates)\n schemas[`${schemaName}Input`] = buildTableInputSchema(collection.table, lookup);\n\n // The update body — same columns, no `required`. PATCH and PUT both\n // merge, so a field left out means \"unchanged\", not \"omitted by mistake\".\n schemas[`${schemaName}Update`] = buildTableUpdateSchema(collection.table, lookup);\n\n const dataPath = `/data/${slug}`;\n const softDeleteNote = softDeleteBehaviour(collection);\n\n // ── GET /data/{slug}/count — How many rows match ──────────────\n //\n // Served for every collection since the route existed and described\n // here for the first time. A spec is what a generated client can see,\n // so an endpoint missing from it is an endpoint that client does not\n // have — and this is the one a paginating UI needs to know how many\n // pages there are.\n //\n // Registered before the list path so its literal segment cannot be read\n // as an `{id}`, which is the same ordering the router uses.\n //\n // Its parameters are the listing's that narrow the rows — the filters,\n // the logical groups, the search and the vector search, all of which\n // the route reads (`countRawEntities`) — and not the ones that page or\n // shape them. The vector search and the groups were read and not\n // described, which left a generated client unable to count what its\n // own `find()` had asked for.\n const countNarrowing = new Set([\n \"where\", \"or\", \"and\", \"not\", \"searchString\",\n \"vector_search\", \"vector\", \"vector_distance\", \"vector_threshold\"\n ]);\n const countParameters = [\n ...listQueryParameters()\n .filter(p => countNarrowing.has(p.name))\n .map(p => p.name === \"vector_threshold\"\n ? { ...p, description: \"Count only the rows within this distance of `vector`.\" }\n : p),\n ...deletedParameters(collection),\n ...buildFilterParameters(collection.table, reservedParameterNames)\n ];\n const countResponses = {\n 200: {\n description: \"The number of matching rows\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"count\"],\n properties: {\n count: { type: \"integer\", description: \"Rows matching the filters\" }\n }\n }\n }\n }\n },\n ...errorResponses(requireAuth)\n };\n paths[`${dataPath}/count`] = {\n get: {\n tags: [collection.name],\n summary: `Count ${collection.name}`,\n description:\n \"The number of rows the same filters would return, without returning them. \" +\n \"Takes the filter and search parameters of the list endpoint; `limit`, `offset` \" +\n \"and `orderBy` are not part of the question and are ignored.\",\n operationId: `count${schemaName}`,\n parameters: countParameters,\n responses: countResponses\n },\n // The same count, its parameters in the body — documented from\n // the GET's own list, as `POST …/query` is from the listing's.\n post: queryOperation({\n tags: [collection.name],\n summary: `Count ${collection.name}, parameters in the body`,\n description:\n \"The count `GET` answers, with its query parameters in a JSON body instead of the URL: \" +\n \"the same filters, search and vector search, the same row-level security, and the same \" +\n \"errors. It reads and never writes, so a credential needs `data:read` for it. Use it when \" +\n \"the URL would not fit: a vector search's embedding, a long `in` list. A parameter also on \" +\n \"the URL is a 400 INVALID_QUERY_BODY.\",\n operationId: `count${schemaName}Query`,\n parameters: countParameters,\n responses: countResponses,\n reserved: reservedParameterNames\n })\n };\n\n // ── GET /data/{slug}/aggregate — count/sum/avg/min/max ────────\n //\n // Before the list path for the same reason `/count` is: a literal\n // segment that a generated client would otherwise be told is an `{id}`.\n paths[`${dataPath}/aggregate`] = {\n get: {\n tags: [collection.name],\n summary: `Aggregate ${collection.name}`,\n description:\n \"Aggregate values over the rows the same filters would return. Takes the filter and \" +\n \"search parameters of the list endpoint. Row-level security applies to the rows \" +\n \"being aggregated, so a caller who can read nothing counts nothing.\",\n operationId: `aggregate${schemaName}`,\n parameters: [\n {\n name: \"select\",\n in: \"query\",\n required: true,\n description:\n \"Comma-separated aggregates, e.g. `count()`, `sum(total)`, `avg(total),max(total)`. \" +\n \"Results are keyed `count`, `sum_total`, `avg_total` and so on.\",\n schema: { type: \"string\" },\n example: \"count(),sum(total)\"\n },\n {\n name: \"groupBy\",\n in: \"query\",\n required: false,\n description: \"Comma-separated fields to group by. Each grouped field is returned alongside the aggregates.\",\n schema: { type: \"string\" },\n example: \"status\"\n },\n // `limit`, `offset` and `page` bound and page the groups,\n // exactly as they do a listing's rows.\n ...listQueryParameters().filter(p =>\n p.name === \"searchString\" || p.name === \"limit\" || p.name === \"offset\" || p.name === \"page\"),\n {\n name: \"orderBy\",\n in: \"query\",\n required: false,\n description:\n \"Sort for the groups, by a `groupBy` field or an aggregate's result key (`count`, \" +\n \"`sum_total`): `key:asc`, `key:desc` or `key:desc:last`. Groups it leaves tied are \" +\n \"ordered by the `groupBy` fields, so every page boundary falls in the same place. \" +\n \"`offset`, `page` and `orderBy` need `groupBy` — without it the result is one row — \" +\n \"and are otherwise a 400 INVALID_AGGREGATE_WINDOW.\",\n schema: { type: \"string\" },\n example: \"count:desc\"\n },\n ...deletedParameters(collection),\n ...buildFilterParameters(collection.table, reservedParameterNames)\n ],\n responses: {\n 200: {\n description: \"One row per group, or a single row when `groupBy` is absent\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"data\"],\n properties: {\n data: {\n type: \"array\",\n items: { type: \"object\", additionalProperties: true }\n },\n meta: {\n type: \"object\",\n description: \"The page of groups. Present when `groupBy` is.\",\n properties: {\n limit: { type: \"integer\" },\n offset: { type: \"integer\" },\n hasMore: { type: \"boolean\", description: \"Whether a group follows this page.\" }\n }\n }\n }\n }\n }\n }\n },\n 501: { description: \"This backend's data driver does not implement aggregates\" },\n ...errorResponses(requireAuth)\n }\n }\n };\n\n // ── GET /data/{slug} — List entities ──────────────────────────\n const listParameters = [\n ...listQueryParameters(),\n ...deletedParameters(collection),\n ...buildFilterParameters(collection.table, reservedParameterNames)\n ];\n const listResponses = {\n 200: {\n description: \"Paginated list of entities\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n data: {\n type: \"array\",\n items: { $ref: `#/components/schemas/${schemaName}` }\n },\n meta: { $ref: \"#/components/schemas/PaginationMeta\" }\n }\n }\n }\n }\n },\n ...errorResponses(requireAuth)\n };\n\n // ── POST /data/{slug}/query — the same listing, parameters in the body\n //\n // Before the list path, as `/count` is. Documented from the list's own\n // parameter list, so the two cannot describe different listings.\n paths[`${dataPath}/query`] = {\n post: queryOperation({\n tags: [collection.name],\n summary: `List ${collection.name}, parameters in the body`,\n operationId: `query${schemaName}`,\n parameters: listParameters,\n responses: listResponses,\n reserved: reservedParameterNames\n })\n };\n\n paths[dataPath] = {\n get: {\n tags: [collection.name],\n summary: `List ${collection.name}`,\n operationId: `list${schemaName}`,\n parameters: listParameters,\n responses: listResponses\n },\n post: {\n tags: [collection.name],\n summary: `Create ${collection.singularName || collection.name}`,\n operationId: `create${schemaName}`,\n parameters: [\n {\n name: \"on_conflict\",\n in: \"query\",\n required: false,\n schema: { type: \"string\" },\n description:\n \"Comma-separated columns to upsert on, turning the create into \" +\n \"INSERT ... ON CONFLICT DO UPDATE. They must carry a declared uniqueness \" +\n \"guarantee — `validation.unique`, a `unique` index, or the primary key — \" +\n \"or the request is refused with a 400 naming the targets that do exist. \" +\n \"Left off, this is a plain insert and a duplicate key still raises. \" +\n \"Refused (400 `INVALID_CONFLICT_TARGET`) on the auth table, whose rows are \" +\n \"the users: create them with a plain POST and change them with PATCH.\",\n example: \"sku\"\n },\n preferHeader\n ],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${schemaName}Input` }\n }\n }\n },\n responses: {\n 201: {\n description: \"Created entity\",\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${schemaName}` }\n }\n }\n },\n ...minimalResponse,\n ...errorResponses(requireAuth)\n }\n }\n };\n\n // ── Bulk: one transaction, all-or-nothing ─────────────────────\n //\n // These went undocumented while they existed, which is the same defect\n // the update verb had: an endpoint the server serves and the spec does\n // not mention cannot be reached by a generated client at all.\n const idempotencyHeader = {\n name: \"Idempotency-Key\",\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description:\n \"Names this write so a retry is recognised instead of repeated. Without it a \" +\n \"client that lost the response cannot distinguish a replay from a second \" +\n \"genuine batch, and the whole batch is written twice. A key names one request: \" +\n \"re-send the identical request to replay its answer, and use a new key for a \" +\n \"different one.\"\n };\n\n const bulkErrors = {\n 400: {\n description: \"Malformed body, an unknown field, or more rows than the per-batch limit\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 409: {\n description:\n \"A request with the same Idempotency-Key is still in flight. Retry it: the \" +\n \"first attempt's result is replayed once it lands\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 422: {\n description: \"The Idempotency-Key was already used for a different request\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n ...errorResponses(requireAuth)\n };\n\n paths[`/data/${slug}/bulk`] = {\n post: {\n tags: [collection.name],\n summary: `Create many ${collection.name} in one transaction`,\n description:\n \"All-or-nothing: if any row is rejected none of them land, and the error names \" +\n \"the offending index. Every row still runs callbacks, relations and row-level \" +\n \"security. Capped server-side because one batch holds its locks for its whole \" +\n \"duration.\",\n operationId: `createMany${schemaName}`,\n parameters: [idempotencyHeader, preferHeader],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"rows\"],\n properties: {\n rows: { type: \"array\", items: { $ref: `#/components/schemas/${schemaName}Input` } },\n upsert: {\n type: \"boolean\",\n description:\n \"Write each row as INSERT ... ON CONFLICT DO UPDATE. Refused \" +\n \"(400 `INVALID_CONFLICT_TARGET`) on the auth table, whose rows are the users.\"\n },\n onConflict: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"The columns the conflict is matched on, instead of the primary key. \" +\n \"They must carry a declared uniqueness guarantee. Naming them without \" +\n \"`upsert: true` is a 400 rather than a silently ignored field.\"\n }\n }\n }\n }\n }\n },\n responses: {\n 200: {\n description: \"The written rows, in the order given\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n data: { type: \"array\", items: { $ref: `#/components/schemas/${schemaName}` } },\n meta: { type: \"object\", properties: { written: { type: \"integer\" } } }\n }\n }\n }\n }\n },\n ...bulkErrors\n }\n },\n patch: {\n tags: [collection.name],\n summary: `Update many ${collection.name} in one transaction`,\n description:\n \"Each entry names its row and the fields to change. `{ id, data }` rather than \" +\n \"flat rows carrying their own key, because on a table keyed on something other \" +\n \"than `id` a flat row cannot say whether a column is the address or a value to \" +\n \"write. An id matching no row fails the batch.\",\n operationId: `updateMany${schemaName}`,\n parameters: [idempotencyHeader, preferHeader],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"updates\"],\n properties: {\n updates: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"id\", \"data\"],\n properties: {\n id: { type: \"string\", description: \"The row to update\" },\n data: { $ref: `#/components/schemas/${schemaName}Update` }\n }\n }\n }\n }\n }\n }\n }\n },\n responses: {\n 200: {\n description: \"The updated rows, in the order given\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n data: { type: \"array\", items: { $ref: `#/components/schemas/${schemaName}` } },\n meta: { type: \"object\", properties: { written: { type: \"integer\" } } }\n }\n }\n }\n }\n },\n 404: {\n description: \"One of the ids matches no row; nothing was written\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n ...bulkErrors\n }\n }\n };\n\n paths[`/data/${slug}/bulk/delete`] = {\n post: {\n tags: [collection.name],\n summary: `Delete many ${collection.name} in one transaction`,\n description:\n \"A POST, not `DELETE /bulk` with a body. Bodies on DELETE are permitted but \" +\n \"widely dropped by proxies and CDNs, and several generators ignore \" +\n \"`requestBody` on a DELETE operation — a generated client would send the \" +\n \"request with no ids at all. Takes ids rather than a filter: a mistyped \" +\n \"condition that empties a table cannot be reviewed at the call site the way \" +\n \"an explicit list can. `beforeDelete`/`afterDelete` fire per row.\" +\n (softDeleteNote ? `\\n\\n${softDeleteNote}` : \"\"),\n operationId: `deleteMany${schemaName}`,\n parameters: [idempotencyHeader, ...hardDeleteParameters(collection)],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"ids\"],\n properties: {\n ids: {\n type: \"array\",\n items: { oneOf: [{ type: \"string\" }, { type: \"integer\" }] }\n }\n }\n }\n }\n }\n },\n responses: {\n 200: {\n description: softDeleteNote\n ? \"How many rows were moved to the trash, or deleted for good with `?hard=true`\"\n : \"How many rows were deleted\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n meta: { type: \"object\", properties: { deleted: { type: \"integer\" } } }\n }\n }\n }\n }\n },\n 404: {\n description: \"One of the ids matches no row; nothing was deleted\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n ...bulkErrors\n }\n }\n };\n\n // ── GET/PUT/DELETE /data/{slug}/{id} ──────────────────────────\n const entityPath = `/data/${slug}/{id}`;\n paths[entityPath] = {\n get: {\n tags: [collection.name],\n summary: `Get ${collection.singularName || collection.name} by ID`,\n operationId: `get${schemaName}ById`,\n parameters: [\n { name: \"id\",\nin: \"path\",\nrequired: true,\nschema: { type: \"string\" },\ndescription: \"Entity ID\" },\n // The same two parameters the list route documents, and the\n // same code serves them — one row and a page of them go\n // through one pipeline, so anything true of `include` or\n // `fields` there is true here.\n {\n name: \"include\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Relations to load: comma-separated names or dotted paths \"\n + \"(`author,comments.author`, up to 3 hops), `*` for all one hop deep, or the \"\n + \"JSON form for per-relation `limit`/`where`/`orderBy`/`fields`. An unknown \"\n + \"name is a 400 UNKNOWN_RELATION.\",\n example: \"author,comments.author\"\n },\n {\n name: \"fields\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Comma-separated columns to return, as a SELECT projection. The primary key \"\n + \"always survives and `excludeFromApi` columns stay hidden.\",\n example: \"id,title\"\n },\n ...deletedParameters(collection)\n ],\n responses: {\n 200: {\n description: \"Entity found\",\n headers: {\n ETag: {\n schema: { type: \"string\" },\n description:\n \"This row's version. Send it back as `If-Match` on a later PATCH or \" +\n \"DELETE to have the write refused if the row has changed in between.\"\n }\n },\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${schemaName}` }\n }\n }\n },\n 404: { description: \"Entity not found\",\ncontent: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } } },\n ...errorResponses(requireAuth)\n }\n },\n patch: updateOperation(collection, schemaName, requireAuth, {\n ifMatchHeader,\n preferHeader,\n preconditionFailed,\n minimalResponse\n }),\n delete: {\n tags: [collection.name],\n summary: `Delete ${collection.singularName || collection.name}`,\n ...(softDeleteNote ? { description: softDeleteNote } : {}),\n operationId: `delete${schemaName}`,\n parameters: [\n { name: \"id\",\nin: \"path\",\nrequired: true,\nschema: { type: \"string\" },\ndescription: \"Entity ID\" },\n ifMatchHeader,\n {\n name: \"Idempotency-Key\",\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description:\n \"Names this delete so a retry replays its answer. A delete replayed after \" +\n \"the first attempt committed would otherwise answer 404 — which an offline \" +\n \"queue reads as a permanent failure for a delete that in fact succeeded.\"\n },\n ...hardDeleteParameters(collection)\n ],\n responses: {\n 204: {\n description: softDeleteNote\n ? \"Moved to the trash: the row still exists and can be restored. With `?hard=true`, deleted for good\"\n : \"Deleted successfully\"\n },\n 404: { description: \"Entity not found\",\ncontent: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } } },\n 409: {\n description: \"A request with the same Idempotency-Key is still in flight\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 422: {\n description: \"The Idempotency-Key was already used for a different request\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n ...preconditionFailed,\n ...errorResponses(requireAuth)\n }\n }\n };\n\n }\n\n // ── Subcollection routes ─────────────────────────────────────────────\n //\n // A second pass, after every collection's component schema exists. These\n // routes `$ref` the *target's* schema, and the first pass builds schemas in\n // array order — so doing this inline meant a subcollection whose target\n // appeared later in the list silently degraded to an untyped `object`.\n //\n // The names come from the *resolved* relations, not from the authored\n // `relations` array. `relationName` is optional at the authoring surface —\n // it defaults to the property key, or to the target's slug — so reading the\n // raw field skipped every relation that relied on the default, and missed\n // relations declared inline on a property entirely, since those are not in\n // the array. These are the same resolved names the nested-path router\n // matches, so the spec and the routes cannot drift apart.\n //\n // A to-one relation is left out. `posts/1/author` resolves, but it\n // addresses a single row, and documenting it as a paginated list would\n // describe a response shape the client never gets.\n for (const collection of (collections || [])) {\n const slug = collection.slug;\n const schemaName = schemaNameFor(collection);\n const relations = collection.table.relations.filter(relation => relation.cardinality === \"many\");\n for (const relation of relations) {\n const relationName = relation.name;\n const targetSchema = schemaNameFor(documentedNames(relation.target));\n\n const subPath = `/data/${slug}/{parentId}/${relationName}`;\n const nestedParameters = [\n { name: \"parentId\",\nin: \"path\",\nrequired: true,\nschema: { type: \"string\" },\ndescription: `${collection.singularName || collection.name} ID` },\n // The nested list handler goes through the same\n // `parseQueryOptions` and the same fetch as the root\n // one, so it honours the same parameters. It documented\n // four of them.\n ...listQueryParameters()\n ];\n const nestedResponses = {\n 200: {\n description: `List of related ${relationName}`,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n data: {\n type: \"array\",\n items: schemas[targetSchema]\n ? { $ref: `#/components/schemas/${targetSchema}` }\n : { type: \"object\" }\n },\n meta: { $ref: \"#/components/schemas/PaginationMeta\" }\n }\n }\n }\n }\n },\n ...errorResponses(requireAuth)\n };\n\n // Only add if the schema exists (target collection is also registered)\n paths[subPath] = {\n get: {\n tags: [collection.name],\n summary: `List ${relationName} for ${withIndefiniteArticle(collection.singularName || collection.name)}`,\n operationId: `list${schemaName}${toPascalCase(relationName)}`,\n parameters: nestedParameters,\n responses: nestedResponses\n }\n };\n paths[`${subPath}/query`] = {\n post: queryOperation({\n tags: [collection.name],\n summary: `List ${relationName} for ${withIndefiniteArticle(collection.singularName || collection.name)}, parameters in the body`,\n operationId: `query${schemaName}${toPascalCase(relationName)}`,\n parameters: nestedParameters,\n responses: nestedResponses,\n reserved: reservedParameterNames\n })\n };\n }\n }\n\n return spec;\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────\n\n/**\n * Is this column (or relation) part of the shape the document may describe?\n *\n * One exclusion, and it is the document telling the truth about what the\n * server does: a `.private()` column is stripped from every row the API\n * serves, for every caller, including admins and service keys, and a list\n * `access.read: []` closes it to everybody the same way. A schema that lists\n * such a column describes a field that is never present, and it describes it\n * to everyone: `/docs` is mounted on the app, not on the data router, so it\n * carries none of the auth middleware `{basePath}/data` does.\n *\n * The write half adds `.readOnly()` and generated columns: nobody writes them\n * through the API (`write-validation.ts` refuses them), so an input body that\n * offered them would offer a 400.\n *\n * The same rule the SDK generator applies to its `Row` type\n * (`packages/codegen/src/generate-types.ts`).\n */\nfunction isDocumented(target: Pick<ColumnDescriptor, \"private\" | \"access\" | \"readOnly\">, direction: \"read\" | \"write\" = \"read\"): boolean {\n if (direction === \"write\" && target.readOnly) return false;\n const access = columnAccess(target);\n return access?.[direction]?.length !== 0;\n}\n\n/**\n * The access rules a reader of the document is told about: the column's role\n * lists, with `.readOnly()` stated as \"writable by nobody\". A generated column\n * is left unannotated — its read-only-ness is the database's, not a rule.\n */\nfunction documentedAccess(column: Pick<ColumnDescriptor, \"private\" | \"access\" | \"readOnly\" | \"generated\">): ColumnAccess | undefined {\n const access = columnAccess(column);\n if (column.readOnly && column.generated === undefined && !column.private) {\n return { ...(access?.read !== undefined ? { read: access.read } : {}), write: [] };\n }\n return access;\n}\n\n/**\n * The `x-rebase-access` annotation, or nothing for a column with no rule.\n *\n * A vendor extension rather than a schema keyword because OpenAPI has no way to\n * say \"this property is present for some callers\" — `readOnly` is about the\n * direction of a field, not about who. Generators ignore what they do not know,\n * so a client built from this spec still compiles; a *human* reading `/docs`, or\n * a gateway that wants to enforce the same rule at the edge, gets the role lists\n * verbatim. Emitted for the role case only: a column closed to everybody is\n * absent from the document entirely, which is a stronger statement.\n */\nfunction accessAnnotation(access: ColumnAccess | undefined): Record<string, unknown> | undefined {\n if (!access) return undefined;\n const annotation: Record<string, unknown> = {};\n if (access.read !== undefined) annotation.read = [...access.read];\n if (access.write !== undefined) annotation.write = [...access.write];\n return Object.keys(annotation).length > 0 ? annotation : undefined;\n}\n\n/** The sentence `x-rebase-access` deserves in prose, for a reader of `/docs`. */\nfunction accessDescription(access: ColumnAccess | undefined): string | undefined {\n if (!access) return undefined;\n const parts: string[] = [];\n const phrase = (roles: readonly string[]) =>\n roles.length === 0 ? \"nobody through the API\" : roles.map(r => `\\`${r}\\``).join(\", \") + \" (and `admin`)\";\n if (access.read !== undefined) parts.push(`readable by ${phrase(access.read)}`);\n if (access.write !== undefined) parts.push(`writable by ${phrase(access.write)}`);\n if (parts.length === 0) return undefined;\n return `Field access: ${parts.join(\"; \")}. A caller without the role does not receive the field at all — it is absent, not null.`;\n}\n\n/**\n * The names an undocumented column or relation is served under — its key and\n * its SQL name — so a foreign key derived from a relation cannot put a hidden\n * column back on the surface under its other name. Same pair, same reason, as\n * `excludedApiKeys` in the SDK generator.\n */\nfunction excludedApiKeys(table: TableDescriptor, direction: \"read\" | \"write\" = \"read\", lookup?: TableLookup): Set<string> {\n const excluded = new Set<string>();\n for (const column of table.columns) {\n if (isDocumented(column, direction)) continue;\n excluded.add(column.key);\n excluded.add(column.column);\n }\n for (const relation of table.relations) {\n // A link is documented exactly when its key column is (`{ reviewer }`\n // writes the `.readOnly()` `reviewerId`); a relation is read only if\n // every column its join reads is (`staff.handledCases` reads the\n // private `cases.informantId`).\n const bound = boundKeyColumn(table, relation);\n const joined = direction === \"read\" ? relationJoinColumns(table, relation, lookup) : [];\n if (!isDocumented(relation, direction)\n || (bound !== undefined && !isDocumented(bound, direction))\n || joined.some(column => !isDocumented(column, \"read\"))) {\n excluded.add(relation.name);\n }\n }\n return excluded;\n}\n\n/**\n * The column a table is addressed by on the wire: the first of its key.\n * `undefined` for a table introspected without a key.\n */\nfunction keyColumnOf(table: TableDescriptor | undefined): ColumnDescriptor | undefined {\n const key = table?.primaryKey[0];\n return key === undefined ? undefined : table?.columns.find(column => column.key === key);\n}\n\n/**\n * The schema of a primary key or of a foreign key pointing at one: the key\n * column's own type, stripped of the column-level facts (description,\n * validation bounds) that belong to the column and not to a reference to it.\n *\n * Falls back to `string` for a table without a key.\n */\nfunction idSchemaFor(table: TableDescriptor | undefined): Record<string, unknown> {\n const key = keyColumnOf(table);\n if (!key) return { type: \"string\" };\n const converted = columnTypeSchema(key);\n const schema: Record<string, unknown> = { type: converted.type ?? \"string\" };\n if (converted.format) schema.format = converted.format;\n return schema;\n}\n\n/**\n * Whether a key column is the planner's implicit `id` — text, keyed, filled by\n * `gen_random_uuid()::text`, declared first. It has always been documented as\n * a \"Unique identifier\", with no column facts of its own.\n */\nfunction isImplicitIdColumn(table: TableDescriptor, column: ColumnDescriptor): boolean {\n return column.key === \"id\" && table.columns[0] === column && column.type.kind === \"text\"\n && column.default?.kind === \"sql\" && column.default.expression === \"gen_random_uuid()::text\";\n}\n\n/**\n * The schema an *included* relation arrives as: the target's own row.\n *\n * `$ref` when the target is one of the tables this document describes, and an\n * open object when it is not — a dangling pointer makes Swagger UI render an\n * empty model and makes a strict generator abort, which is worse than a vague\n * one.\n */\nfunction includedRelationSchema(\n relation: RelationDescriptor,\n registeredSchemas: ReadonlySet<string>\n): Record<string, unknown> {\n const targetSchema = schemaNameFor(documentedNames(relation.target));\n const item: Record<string, unknown> = registeredSchemas.has(targetSchema)\n ? { $ref: `#/components/schemas/${targetSchema}` }\n : { type: \"object\" };\n return relation.cardinality === \"many\" ? { type: \"array\", items: item } : item;\n}\n\n/**\n * Emit a table's relations onto a read schema: the foreign keys first, then\n * the relations themselves.\n *\n * The order and the keys are the SDK `Row`'s, deliberately — the parity test\n * next door compares the two key sets.\n *\n * A `belongsTo` reaches the wire under its foreign-key column's key\n * (`authorId`); a relation addressed by the same name as its own foreign key\n * is served as either the scalar or the nested row depending on `include`, so\n * it is documented as both.\n */\nfunction emitRelationProperties(\n table: TableDescriptor,\n properties: Record<string, unknown>,\n required: string[],\n emitted: Set<string>,\n registeredSchemas: ReadonlySet<string>,\n lookup: TableLookup\n): void {\n for (const relation of table.relations) {\n if (relation.kind !== \"belongsTo\") continue;\n const fieldKey = relation.localField;\n if (emitted.has(fieldKey)) continue;\n\n const foreignKey = idSchemaFor(lookup(relation.target));\n const shadowedByInclude = relation.name === fieldKey;\n properties[fieldKey] = shadowedByInclude\n ? { oneOf: [foreignKey, includedRelationSchema(relation, registeredSchemas)] }\n : { ...foreignKey, description: `Foreign key into \\`${relation.target}\\`` };\n emitted.add(fieldKey);\n\n const column = table.columns.find(candidate => candidate.key === fieldKey);\n if (column && !column.nullable && !shadowedByInclude) required.push(fieldKey);\n }\n\n for (const relation of table.relations) {\n if (emitted.has(relation.name)) continue;\n properties[relation.name] = includedRelationSchema(relation, registeredSchemas);\n emitted.add(relation.name);\n }\n}\n\n/**\n * Whether a foreign-key column states anything of its own — a rule, a\n * default, access, a description, … — beyond being the key a relation points\n * with. Such a column is documented as the column it is; a plain foreign key\n * is documented from the relation, typed from its target's key.\n */\nfunction isExplicitForeignKey(column: ColumnDescriptor): boolean {\n if (column.derived) return false;\n return column.primaryKey !== undefined || column.default !== undefined || column.generated !== undefined\n || column.readOnly !== undefined || column.private !== undefined || column.access !== undefined\n || column.stamp !== undefined || column.validate !== undefined || column.oneOf !== undefined\n || column.description !== undefined || column.storage !== undefined || column.semantic !== undefined\n || column.vectorIndex !== undefined || column.json !== undefined || column.element !== undefined\n || column.transforms !== undefined;\n}\n\n/**\n * The columns a schema lists in the table's own pass, in physical order: every\n * column but the plain foreign keys of `belongsTo` relations, which\n * {@link emitRelationProperties} emits after them, in relation order.\n */\nfunction ownColumns(table: TableDescriptor): ColumnDescriptor[] {\n return table.columns.filter(column => column.foreignKeyOf === undefined || isExplicitForeignKey(column));\n}\n\n/**\n * Build the component schema for a table (output / read shape).\n *\n * Every column except the ones {@link isDocumented} rules out, plus the\n * foreign keys and relations {@link emitRelationProperties} adds.\n *\n * @param lookup any table's descriptor by slug, for the type of a foreign key.\n */\nexport function buildTableSchema(\n table: TableDescriptor,\n registeredSchemas: ReadonlySet<string>,\n lookup: TableLookup\n): Record<string, unknown> {\n const keyColumn = keyColumnOf(table);\n const idKey = keyColumn?.key ?? \"id\";\n const properties: Record<string, unknown> = {\n [idKey]: { ...idSchemaFor(table), description: \"Unique identifier\" }\n };\n const required: string[] = [idKey];\n const excluded = excludedApiKeys(table, \"read\", lookup);\n const emitted = new Set<string>(excluded);\n emitted.add(idKey);\n\n for (const column of ownColumns(table)) {\n if (!isDocumented(column)) continue;\n if (column === keyColumn && isImplicitIdColumn(table, column)) continue;\n\n properties[column.key] = columnSchema(column);\n emitted.add(column.key);\n\n if (!column.nullable && !column.primaryKey) required.push(column.key);\n }\n\n emitRelationProperties(table, properties, required, emitted, registeredSchemas, lookup);\n annotateTenantField(table, properties, \"read\");\n\n return {\n type: \"object\",\n required: required.length > 0 ? required : undefined,\n properties\n };\n}\n\n/**\n * Mark the tenant column, on whichever schema is being built.\n *\n * A vendor extension for the same reason `x-rebase-access` is one: OpenAPI has\n * no keyword for \"the server fills this in from who you are, and refuses a\n * value that is not yours\". `readOnly` is the closest and it is wrong — the\n * column *is* writable, by a caller sending their own tenant, and a bypass role\n * may send any.\n */\nfunction annotateTenantField(\n table: TableDescriptor,\n properties: Record<string, unknown>,\n direction: \"read\" | \"write\"\n): void {\n const tenant = tenantOf(table);\n if (!tenant) return;\n const schema = properties[tenant.field];\n if (!schema || typeof schema !== \"object\") return;\n\n const existing = \"description\" in schema ? schema.description : undefined;\n const sentence = direction === \"write\"\n ? \"The tenant this row belongs to. Omit it and the server stamps the tenant you are calling as; \" +\n \"send another tenant's and the write is refused with `TENANT_MISMATCH`. It cannot be changed \" +\n \"on an update (`TENANT_IMMUTABLE`).\"\n : \"The tenant this row belongs to. Rows of other tenants are not returned at all.\";\n\n properties[tenant.field] = {\n ...schema,\n description: typeof existing === \"string\" && existing ? `${existing} — ${sentence}` : sentence,\n \"x-rebase-tenant\": true\n };\n}\n\n/**\n * The PATCH/PUT operation for `/data/{slug}/{id}`.\n *\n * Split out because both verbs serve it and they must not drift: the update\n * body is a **partial**, and describing it with the create schema was the bug\n * this replaces. `<Name>Input` marks every `validation.required` property as\n * required — correct for POST, wrong for an update, where omitting a field\n * means \"leave it alone\" rather than \"I forgot it\". A client generated from\n * that spec demanded fields the server does not, and a spec-validating gateway\n * would have rejected partial updates the server accepts.\n */\nfunction updateOperation(\n collection: DocumentedTable,\n schemaName: string,\n requireAuth: boolean,\n shared: {\n ifMatchHeader: Record<string, unknown>;\n preferHeader: Record<string, unknown>;\n preconditionFailed: Record<string, unknown>;\n minimalResponse: Record<string, unknown>;\n }\n): Record<string, unknown> {\n return {\n tags: [collection.name],\n summary: `Update ${collection.singularName || collection.name}`,\n description:\n \"Partial update: only the properties present in the body are written; the rest are left \" +\n \"unchanged.\\n\\n\" +\n \"A property's value may instead be a field operation — `{ \\\"views\\\": { \\\"$inc\\\": 1 } }`, \" +\n \"`{ \\\"tags\\\": { \\\"$push\\\": \\\"new\\\" } }`, `{ \\\"tags\\\": { \\\"$pull\\\": \\\"old\\\" } }`, \" +\n \"`{ \\\"meta\\\": { \\\"$merge\\\": { \\\"seen\\\": true } } }` — which is applied inside the \" +\n \"statement holding the row lock. That is the difference between a counter that is correct \" +\n \"under concurrency and one that silently loses increments, because expressing the same \" +\n \"change as a value means reading it first. `$inc` needs a `number` property, `$push`/`$pull` \" +\n \"an `array`, `$merge` a `map`; anything else is a 400. Pushed elements and merged keys answer \" +\n \"to the property's own rules, as a value would. See the `FieldOperation` schema.\",\n operationId: `update${schemaName}`,\n parameters: [\n { name: \"id\", in: \"path\", required: true, schema: { type: \"string\" }, description: \"Entity ID\" },\n shared.ifMatchHeader,\n shared.preferHeader,\n {\n name: \"Idempotency-Key\",\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description:\n \"Names this update so a retry replays its answer instead of applying the edit \" +\n \"again. A PATCH is not naturally idempotent — a field operation emphatically is \" +\n \"not — so a retry after a lost response applies it twice.\"\n }\n ],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${schemaName}Update` }\n }\n }\n },\n responses: {\n 200: {\n description: \"Updated entity\",\n headers: {\n ETag: {\n schema: { type: \"string\" },\n description:\n \"The version this write produced — the tag a `GET` of the row now answers. Send \" +\n \"it as `If-Match` on the next write to chain conditional edits without reading \" +\n \"the row back. Absent on an answer replayed from an `Idempotency-Key`.\"\n }\n },\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${schemaName}` }\n }\n }\n },\n 404: {\n description: \"Entity not found\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 409: {\n description: \"A request with the same Idempotency-Key is still in flight\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 422: {\n description: \"The Idempotency-Key was already used for a different request\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n ...shared.preconditionFailed,\n ...shared.minimalResponse,\n ...errorResponses(requireAuth)\n }\n };\n}\n\n/**\n * The update body: the create schema with `required` dropped.\n *\n * Derived rather than rebuilt so the two cannot describe different columns —\n * the only difference between creating and updating is which columns you must\n * supply, and that is exactly the one thing removed here.\n */\nfunction buildTableUpdateSchema(table: TableDescriptor, lookup: TableLookup): Record<string, unknown> {\n const { required: _required, ...rest } = buildTableInputSchema(table, lookup);\n return rest;\n}\n\n/** Whether the database (or the server) fills a column a create leaves out: a non-literal default, or generation. */\nfunction databaseFills(column: ColumnDescriptor): boolean {\n const fill = column.default?.kind;\n return fill === \"database\" || fill === \"sql\" || fill === \"random-uuid\" || fill === \"identity\" || column.generated !== undefined;\n}\n\n/**\n * Build an input schema (for POST) — leaves out what the server fills.\n *\n * Private, read-only and generated columns are left out too, and the server\n * agrees: a write naming one is refused (`write-validation.ts`).\n *\n * @param lookup any table's descriptor by slug, for the type of a foreign key.\n */\nexport function buildTableInputSchema(table: TableDescriptor, lookup: TableLookup): Record<string, unknown> {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // The write half, not the read half: a column readable by nobody but\n // writable by an `admin` belongs in the input body and not in the row.\n const excluded = excludedApiKeys(table, \"write\");\n const emitted = new Set<string>(excluded);\n const idKey = keyColumnOf(table)?.key ?? \"id\";\n\n for (const column of ownColumns(table)) {\n if (!isDocumented(column, \"write\")) continue;\n\n // A time the server stamps is not the caller's to send.\n if (column.stamp?.value === \"now\") continue;\n\n // A key the database generates.\n if (column.primaryKey && (column.default?.kind === \"random-uuid\" || column.default?.kind === \"identity\" || column.default?.kind === \"sql\")) continue;\n\n properties[column.key] = columnSchema(column);\n emitted.add(column.key);\n\n // A column the database fills may be left out of a create.\n if (!column.nullable && !column.primaryKey && !databaseFills(column)) {\n required.push(column.key);\n }\n }\n\n // Allow an explicit key on create (optional), typed from the declared key.\n if (!emitted.has(idKey)) {\n properties[idKey] = {\n ...idSchemaFor(table),\n description: \"Optional: client-assigned ID. If omitted, the server generates one.\"\n };\n emitted.add(idKey);\n }\n\n // Every relation a write may set, as the generated SDK's `Insert` types\n // them. See `emitWritableRelations`.\n emitWritableRelations(table, properties, emitted, lookup);\n annotateTenantField(table, properties, \"write\");\n\n // The tenant column is never required on input: the server fills it.\n const tenantField = tenantOf(table)?.field;\n const requiredOnInput = tenantField ? required.filter(key => key !== tenantField) : required;\n\n return {\n type: \"object\",\n required: requiredOnInput.length > 0 ? requiredOnInput : undefined,\n properties\n };\n}\n\n/**\n * The writable half of a table's relations — the same set the SDK generator's\n * `emitWritableRelations` types on `Insert`, kind for kind:\n *\n * - a `belongsTo`, under both spellings the server accepts: the foreign key\n * (`authorId`) and the relation (`author`);\n * - a `hasOne`, and a single-hop to-one `via`, under the relation: the target's\n * id, or `null` to unlink;\n * - a to-many membership — `hasMany`, `manyToMany`, and a single-hop to-many\n * `via` — under the relation's name: a list of target ids or `{ id }`\n * objects, a `manyToMany`'s carrying a `_pivot` of its link columns.\n *\n * None is listed in `required`: a belongsTo's two keys are alternatives.\n */\nfunction emitWritableRelations(\n table: TableDescriptor,\n properties: Record<string, unknown>,\n emitted: Set<string>,\n lookup: TableLookup\n): void {\n const emit = (key: string, schema: Record<string, unknown>): void => {\n if (emitted.has(key)) return;\n properties[key] = schema;\n emitted.add(key);\n };\n const belongsTo = (relation: RelationDescriptor): Record<string, unknown> => ({\n ...idSchemaFor(lookup(relation.target)),\n description: `The \\`${relation.target}\\` row this belongs to.`\n });\n\n for (const relation of table.relations) {\n if (relation.kind === \"belongsTo\") emit(relation.localField, belongsTo(relation));\n }\n\n for (const relation of table.relations) {\n if (relation.kind === \"belongsTo\") {\n emit(relation.name, belongsTo(relation));\n } else if (relation.kind === \"hasOne\" || (relation.kind === \"via\" && relation.cardinality === \"one\" && relation.writable)) {\n emit(relation.name, {\n ...idSchemaFor(lookup(relation.target)),\n nullable: true,\n description: `The \\`${relation.target}\\` row to link to this one; \\`null\\` unlinks it.`\n });\n }\n }\n\n for (const relation of table.relations) {\n if (relation.cardinality !== \"many\") continue;\n if (relation.kind === \"via\" && !relation.writable) continue;\n const id = idSchemaFor(lookup(relation.target));\n const pivotColumns = relation.kind === \"manyToMany\" ? relation.through.pivot : [];\n const pivot = pivotColumns.length > 0\n ? {\n _pivot: {\n type: \"object\",\n properties: Object.fromEntries(pivotColumns.map(column => [column.key, columnSchema(column)]))\n }\n }\n : {};\n emit(relation.name, {\n type: \"array\",\n description: `The \\`${relation.target}\\` rows linked to this one — the whole set, replacing the current links.`,\n items: { oneOf: [id, { type: \"object\", required: [\"id\"], properties: { id, ...pivot } }] }\n });\n }\n}\n\n/**\n * A column as an OpenAPI 3.0 schema object, with its access rules annotated.\n */\nfunction columnSchema(column: ColumnDescriptor): Record<string, unknown> {\n const schema = columnTypeSchema(column);\n const access = documentedAccess(column);\n const annotation = accessAnnotation(access);\n if (!annotation) return schema;\n\n const sentence = accessDescription(access);\n return {\n ...schema,\n ...(sentence\n ? { description: schema.description ? `${schema.description} — ${sentence}` : sentence }\n : {}),\n \"x-rebase-access\": annotation\n };\n}\n\n/** A text value's rules as JSON Schema keywords: lengths, pattern, format, closed set. */\nfunction textSchema(\n base: Record<string, unknown>,\n rules: { validate?: ColumnValidation; oneOf?: readonly (string | number)[]; maxLength?: number; storage?: ColumnStorage }\n): Record<string, unknown> {\n base.type = \"string\";\n if (rules.oneOf && rules.oneOf.length > 0) base.enum = [...rules.oneOf];\n const validate = rules.validate;\n if (typeof validate?.min === \"number\") base.minLength = validate.min;\n if (rules.maxLength !== undefined) base.maxLength = rules.maxLength;\n if (validate?.length !== undefined) {\n base.minLength = validate.length;\n base.maxLength = validate.length;\n }\n const pattern = jsonSchemaPattern(validate);\n if (pattern !== undefined) base.pattern = pattern;\n if (validate?.email) base.format = \"email\";\n if (validate?.url) base.format = \"uri\";\n if (rules.storage) base.format = \"uri\";\n return base;\n}\n\n/** A number's rules as JSON Schema keywords. */\nfunction numberSchema(\n base: Record<string, unknown>,\n rules: { validate?: ColumnValidation; oneOf?: readonly (string | number)[]; integer: boolean }\n): Record<string, unknown> {\n base.type = rules.integer ? \"integer\" : \"number\";\n if (rules.oneOf && rules.oneOf.length > 0) base.enum = [...rules.oneOf];\n const validate = rules.validate;\n if (typeof validate?.min === \"number\") base.minimum = validate.min;\n if (typeof validate?.max === \"number\") base.maximum = validate.max;\n if (validate?.moreThan !== undefined) {\n base.minimum = validate.moreThan;\n base.exclusiveMinimum = true;\n }\n if (validate?.lessThan !== undefined) {\n base.maximum = validate.lessThan;\n base.exclusiveMaximum = true;\n }\n return base;\n}\n\n/** A list's rules as JSON Schema keywords. */\nfunction listRules(base: Record<string, unknown>, validate: ColumnValidation | undefined): Record<string, unknown> {\n if (validate?.minItems !== undefined) base.minItems = validate.minItems;\n if (validate?.maxItems !== undefined) base.maxItems = validate.maxItems;\n if (validate?.uniqueItems) base.uniqueItems = true;\n return base;\n}\n\n/** A point on Earth. */\nfunction geopointSchema(base: Record<string, unknown>): Record<string, unknown> {\n base.type = \"object\";\n base.properties = { latitude: { type: \"number\" }, longitude: { type: \"number\" } };\n base.required = [\"latitude\", \"longitude\"];\n return base;\n}\n\n/** A time the server stamps: read-only, and said so. */\nfunction stampedSchema(base: Record<string, unknown>, on: \"create\" | \"update\"): Record<string, unknown> {\n base.readOnly = true;\n base.description = (base.description || \"\") + (on === \"create\" ? \" (Auto-set on creation)\" : \" (Auto-updated)\");\n return base;\n}\n\n/** The items of a native array column. */\nfunction elementSchema(column: ColumnDescriptor, of: ColumnType): Record<string, unknown> {\n const element = column.element;\n const base: Record<string, unknown> = {};\n if (isTextColumnType(of) || of.kind === \"uuid\" || of.kind === \"enum\") {\n const max = element?.validate?.max;\n return textSchema(base, {\n validate: element?.validate,\n oneOf: element?.oneOf ?? (of.kind === \"enum\" ? of.values : undefined),\n maxLength: typeof max === \"number\" ? max : undefined,\n storage: element?.storage ?? column.storage\n });\n }\n if (of.kind === \"boolean\") {\n base.type = \"boolean\";\n return base;\n }\n if (isTemporalColumnType(of)) {\n base.type = \"string\";\n base.format = \"date-time\";\n return base;\n }\n return numberSchema(base, { validate: element?.validate, oneOf: element?.oneOf, integer: element?.validate?.integer === true });\n}\n\n/** One typed block of a `json.oneOf()`. */\nfunction variantSchema(node: Extract<JsonShape, { kind: \"oneOf\" }>, name: string, variant: JsonShape): Record<string, unknown> {\n return {\n type: \"object\",\n properties: {\n [node.typeField]: { type: \"string\", enum: [name] },\n [node.valueField]: jsonNodeSchema(variant)\n },\n required: [node.typeField, node.valueField]\n };\n}\n\n/** A node of a JSON document's shape. */\nfunction jsonNodeSchema(node: JsonShape, listValidate?: ColumnValidation): Record<string, unknown> {\n const base: Record<string, unknown> = {};\n if (node.description !== undefined) base.description = node.description;\n switch (node.kind) {\n case \"string\": {\n const max = node.validate?.max;\n return textSchema(base, { validate: node.validate, oneOf: node.oneOf, maxLength: typeof max === \"number\" ? max : undefined, storage: node.storage });\n }\n case \"number\":\n return numberSchema(base, { validate: node.validate, oneOf: node.oneOf, integer: node.validate?.integer === true });\n case \"boolean\":\n base.type = \"boolean\";\n return base;\n case \"date\":\n base.type = \"string\";\n base.format = \"date-time\";\n return node.stamp ? stampedSchema(base, node.stamp) : base;\n case \"geopoint\":\n return geopointSchema(base);\n case \"object\": {\n base.type = \"object\";\n const fields = Object.entries(node.fields);\n if (fields.length > 0) {\n base.properties = Object.fromEntries(fields.map(([key, field]) => [key, jsonNodeSchema(field)]));\n const required = fields.filter(([, field]) => field.required).map(([key]) => key);\n if (required.length > 0) base.required = required;\n } else if (node.additional) {\n base.additionalProperties = true;\n }\n return base;\n }\n case \"array\": {\n base.type = \"array\";\n const item = node.of;\n base.items = item.kind === \"oneOf\"\n ? { oneOf: Object.entries(item.variants).map(([name, variant]) => variantSchema(item, name, variant)) }\n : jsonNodeSchema(item);\n return listRules(base, { ...node.validate, ...listValidate });\n }\n case \"oneOf\":\n base.oneOf = Object.entries(node.variants).map(([name, variant]) => variantSchema(node, name, variant));\n return base;\n case \"unknown\":\n return base;\n }\n}\n\n/** The JSON Schema a column's *type* compiles to, before any access annotation. */\nfunction columnTypeSchema(column: ColumnDescriptor): Record<string, unknown> {\n const base: Record<string, unknown> = {};\n if (column.description !== undefined) base.description = column.description;\n if (column.semantic === \"geopoint\") return geopointSchema(base);\n\n const type = column.type;\n switch (type.kind) {\n case \"text\":\n case \"varchar\":\n case \"char\":\n case \"uuid\":\n case \"enum\":\n return textSchema(base, {\n validate: column.validate,\n oneOf: type.kind === \"enum\" ? type.values : column.oneOf,\n maxLength: textMaxLength(column),\n storage: column.storage\n });\n case \"smallint\":\n case \"integer\":\n case \"bigint\":\n case \"smallserial\":\n case \"serial\":\n case \"bigserial\":\n case \"real\":\n case \"doublePrecision\":\n case \"numeric\":\n // A key is an integer however it is declared, as are the integer\n // kinds the API has always called integers.\n return numberSchema(base, {\n validate: column.validate,\n oneOf: column.oneOf,\n integer: column.validate?.integer === true || column.primaryKey === true\n || type.kind === \"integer\" || type.kind === \"bigint\" || type.kind === \"serial\" || type.kind === \"bigserial\"\n });\n case \"boolean\":\n base.type = \"boolean\";\n return base;\n case \"timestamptz\":\n case \"date\":\n case \"time\":\n base.type = \"string\";\n base.format = \"date-time\";\n return column.stamp?.value === \"now\" ? stampedSchema(base, column.stamp.on) : base;\n case \"json\":\n case \"jsonb\": {\n const shape = column.json;\n if (shape === undefined || shape.kind === \"unknown\") {\n base.type = \"object\";\n return base;\n }\n const schema = jsonNodeSchema(shape, shape.kind === \"array\" ? column.validate : undefined);\n return base.description !== undefined ? { ...schema, description: base.description } : schema;\n }\n case \"vector\":\n base.type = \"array\";\n base.items = { type: \"number\" };\n base.description = (base.description || \"\") + ` (Vector(${type.dimensions}))`;\n return base;\n case \"bytea\":\n base.type = \"string\";\n base.description = (base.description || \"\") + \" (Binary/Base64)\";\n return base;\n case \"array\":\n base.type = \"array\";\n base.items = elementSchema(column, type.of);\n return listRules(base, column.validate);\n case \"other\":\n if (/\\]\\s*$/.test(type.sqlType)) {\n base.type = \"array\";\n base.items = {};\n return base;\n }\n base.type = \"string\";\n return base;\n }\n}\n\n/**\n * Build PostgREST-style filter parameters for a table.\n * These are additional query parameters like `?status=eq.active&price=gte.100`.\n *\n * Private columns are not offered: a filter on a column no response can\n * contain answers questions about the value one row at a time. A plain\n * foreign key is filterable and is still not offered here; JSON documents,\n * lists and points have no single value to compare.\n */\nfunction buildFilterParameters(\n table: TableDescriptor,\n reservedNames: ReadonlySet<string> = new Set()\n): Array<Record<string, unknown>> {\n const params: Array<Record<string, unknown>> = [];\n\n for (const column of ownColumns(table)) {\n if (!isDocumented(column)) continue;\n const kind = column.type.kind;\n if (column.semantic === \"geopoint\" || kind === \"json\" || kind === \"jsonb\" || kind === \"array\") continue;\n if (column.type.kind === \"other\" && /\\]\\s*$/.test(column.type.sqlType)) continue;\n // A column whose name a list parameter already owns is unfilterable\n // over the wire — see `reservedParameterNames`.\n if (reservedNames.has(column.key)) continue;\n\n const text = isTextColumnType(column.type) || kind === \"uuid\" || kind === \"enum\" || kind === \"other\";\n params.push({\n name: column.key,\n in: \"query\",\n required: false,\n schema: { type: \"string\" },\n description:\n `Filter by \\`${column.key}\\`. Supports PostgREST operators: ` +\n \"`eq.value`, `neq.value`, `gt.value`, `gte.value`, `lt.value`, `lte.value`, \" +\n \"`in.(a,b,c)`, `nin.(a,b,c)`, `cs.value` (array-contains), `csa.(a,b)` (array-contains-any), \" +\n \"`csall.(a,b)` (array-contains-all), `cd.(a,b)` (array-contained-by). \" +\n \"Plain values imply equality.\",\n example: text ? \"eq.active\" : isNumericColumnType(column.type) ? \"gte.100\" : undefined\n });\n }\n\n return params;\n}\n\n/**\n * A `POST …/query` operation: the listing whose `parameters` are given, with\n * its query parameters moved into a JSON body.\n *\n * Built from the `GET`'s own parameter list, so the body documents exactly\n * what the route accepts — it turns the body back into those parameters and\n * runs the `GET`'s parser (`query-body.ts`). A filter parameter takes a list\n * where the URL would repeat it, and the four parameters whose URL value is\n * JSON take the JSON value itself.\n */\nfunction queryOperation(operation: {\n tags: string[];\n summary: string;\n /** What the operation answers; the listing's description when unset. */\n description?: string;\n operationId: string;\n parameters: Array<Record<string, unknown>>;\n responses: Record<string, unknown>;\n /** The listing's own parameter names; every other query parameter is a per-field filter. */\n reserved: ReadonlySet<string>;\n}): Record<string, unknown> {\n const jsonValued: Record<string, Record<string, unknown>> = {\n where: { oneOf: [{ type: \"object\", additionalProperties: true }, { type: \"string\" }] },\n include: { oneOf: [{ type: \"object\", additionalProperties: true }, { type: \"string\" }] },\n orderBy: { oneOf: [{ type: \"array\", items: {} }, { type: \"string\" }] },\n vector: { oneOf: [{ type: \"array\", items: { type: \"number\" } }, { type: \"string\" }] }\n };\n const properties: Record<string, unknown> = {};\n for (const parameter of operation.parameters) {\n if (parameter.in !== \"query\") continue;\n const name = String(parameter.name);\n const schema = parameter.schema as Record<string, unknown>;\n const isFilter = !operation.reserved.has(name);\n properties[name] = {\n ...(jsonValued[name]\n ?? (isFilter ? { oneOf: [schema, { type: \"array\", items: schema }] } : schema)),\n ...(parameter.description ? { description: parameter.description } : {})\n };\n }\n return {\n tags: operation.tags,\n summary: operation.summary,\n description: operation.description ??\n \"The listing `GET` answers, with its query parameters in a JSON body instead of the URL: \" +\n \"the same filters, page, count, cursor and includes, the same row-level security, and the \" +\n \"same errors. It reads and never writes, so a credential needs `data:read` for it. Use it \" +\n \"when the URL would not fit: a vector search's embedding is a JSON array in `vector`, and \" +\n \"768 dimensions of it is 17 KB of URL, past what Node and most proxies accept. A parameter \" +\n \"also on the URL is a 400 INVALID_QUERY_BODY.\",\n operationId: operation.operationId,\n parameters: operation.parameters.filter(parameter => parameter.in !== \"query\"),\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: { type: \"object\", properties }\n }\n }\n },\n responses: operation.responses\n };\n}\n\n/**\n * Standard error responses included on every endpoint.\n */\nfunction errorResponses(requireAuth: boolean): Record<string, unknown> {\n const responses: Record<string, unknown> = {\n 400: {\n description: \"Bad request\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 500: {\n description: \"Internal server error\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n }\n };\n\n if (requireAuth) {\n responses[401] = {\n description: \"Authentication required or invalid token\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n };\n responses[403] = {\n description: \"Insufficient permissions\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n };\n }\n\n return responses;\n}\n\n/**\n * Prefix a noun with \"a\" or \"an\" based on its leading sound.\n */\nfunction withIndefiniteArticle(noun: string): string {\n return `${/^[aeiou]/i.test(noun) ? \"an\" : \"a\"} ${noun}`;\n}\n\n/**\n * The component-schema name for a collection — and the stem of every\n * `operationId` and `$ref` that mentions it.\n *\n * `toPascalCase` keeps ASCII letters and digits and nothing else, so a name\n * written in a script that has none of them — a Cyrillic or Japanese\n * `singularName`, which the docs' six locales make ordinary rather than exotic\n * — reduced to the empty string. The schema was then stored under `\"\"` and\n * every reference to it read `#/components/schemas/`, an unresolvable pointer:\n * Swagger UI renders the model empty and a strict generator fails outright. So\n * fall through the names until one survives, and keep a constant as the floor.\n *\n * Two collections whose names PascalCase identically still share one component;\n * that needs a disambiguation rule, not a fallback.\n */\nfunction schemaNameFor(collection: Pick<DocumentedTable, \"singularName\" | \"name\" | \"slug\">): string {\n return toPascalCase(collection.singularName || \"\")\n || toPascalCase(collection.name || \"\")\n || toPascalCase(collection.slug || \"\")\n || \"Collection\";\n}\n\n/**\n * Convert a string to PascalCase for schema names.\n */\nfunction toPascalCase(str: string): string {\n return str\n .replace(/[^a-zA-Z0-9]+/g, \" \")\n .split(\" \")\n .filter(Boolean)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\"\");\n}\n\n/**\n * A text column's `validate({ matches })` as a JSON Schema `pattern`, or\n * `undefined` when it cannot be stated as one.\n *\n * A pattern is a regex's source and nothing else: no delimiting slashes and no\n * flags. A flag that changes what the source matches (`i`, `m`, `s`) has no\n * JSON Schema spelling; the source alone would refuse values the server\n * accepts, so no pattern is stated.\n */\nfunction jsonSchemaPattern(validate: ColumnValidation | undefined): string | undefined {\n const regExp = validationPattern(validate);\n if (!regExp) return undefined;\n return /[ims]/.test(regExp.flags) ? undefined : regExp.source;\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,SAAS,cAAc,OAAO;CAC7B,IAAI,CAAC,OAAO,OAAO,KAAK;CACxB,MAAM,YAAY,MAAM,MAAM,qBAAqB;CACnD,IAAI,WAAW,OAAO,IAAI,OAAO,UAAU,IAAI,UAAU,MAAM,EAAE;MAC5D,OAAO,IAAI,OAAO,OAAO,EAAE;AACjC;;;;;;;;;;;;;;;;;;;;;ACMA,IAAI,cAAc;CACjB,IAAI;CACJ,KAAK;CACL,KAAK;CACL,MAAM;CACN,MAAM;CACN,KAAK;CACL,IAAI;AACL;;;;;;;;;AASA,SAAS,oBAAoB,YAAY;CACxC,OAAO,mBAAmB,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,QAAQ,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,SAAS,YAAY,KAAK,YAAY,MAAM,IAAI,CAAC,CAAC,KAAK,GAAG;AACnJ;;;;;;;;;;;AAWA,SAAS,cAAc,OAAO;CAC7B,MAAM,QAAQ,MAAM,MAAM,GAAG;CAC7B,MAAM,OAAO,MAAM,MAAM,SAAS;CAClC,IAAI,CAAC,QAAQ,eAAe,KAAK,IAAI,GAAG,OAAO;CAC/C,MAAM,SAAS,SAAS,IAAI;CAC5B,IAAI,OAAO,WAAW,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AC9F;EACA,KAAK;GACD,aAAa;GACb,SAAS,EAAE,oBAAoB,EAAE,QAAQ,EAAE,MAAM,qCAAqC,EAAE,EAAE;EAC9F;CACJ;CAEA,IAAI,aAAa;EACb,UAAU,OAAO;GACb,aAAa;GACb,SAAS,EAAE,oBAAoB,EAAE,QAAQ,EAAE,MAAM,qCAAqC,EAAE,EAAE;EAC9F;EACA,UAAU,OAAO;GACb,aAAa;GACb,SAAS,EAAE,oBAAoB,EAAE,QAAQ,EAAE,MAAM,qCAAqC,EAAE,EAAE;EAC9F;CACJ;CAEA,OAAO;AACX;;;;AAKA,SAAS,sBAAsB,MAAsB;CACjD,OAAO,GAAG,YAAY,KAAK,IAAI,IAAI,OAAO,IAAI,GAAG;AACrD;;;;;;;;;;;;;;;;AAiBA,SAAS,cAAc,YAA6E;CAChG,OAAO,aAAa,WAAW,gBAAgB,EAAE,KAC1C,aAAa,WAAW,QAAQ,EAAE,KAClC,aAAa,WAAW,QAAQ,EAAE,KAClC;AACX;;;;AAKA,SAAS,aAAa,KAAqB;CACvC,OAAO,IACF,QAAQ,kBAAkB,GAAG,CAAC,CAC9B,MAAM,GAAG,CAAC,CACV,OAAO,OAAO,CAAC,CACf,KAAI,SAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CACvE,KAAK,EAAE;AAChB;;;;;;;;;;AAWA,SAAS,kBAAkB,UAA4D;CACnF,MAAM,SAAS,kBAAkB,QAAQ;CACzC,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,OAAO,QAAQ,KAAK,OAAO,KAAK,IAAI,KAAA,IAAY,OAAO;AAC3D"}
1
+ {"version":3,"file":"openapi-generator-CAhJiwBm.js","names":[],"sources":["../../utils/dist/regexp.es.js","../../utils/dist/labels.es.js","../../common/src/table/table-options.ts","../../common/src/table/validation.ts","../src/api/openapi-generator.ts"],"sourcesContent":["//#region src/regexp.ts\n/** A missing RegExp serializes to the empty string. */\nfunction serializeRegExp(input) {\n\tif (!input) return \"\";\n\treturn input.toString();\n}\n/**\n* Get a RegExp out of a serialized string\n* @param input\n*/\nfunction hydrateRegExp(input) {\n\tif (!input) return void 0;\n\tconst fragments = input.match(/^\\/(.*)\\/([a-z]*)$/i);\n\tif (fragments) return new RegExp(fragments[1], fragments[2] || \"\");\n\telse return new RegExp(input, \"\");\n}\n/**\n* Is `input` something {@link hydrateRegExp} can turn into a working RegExp?\n*\n* This used to pattern-match the *shape* of a regex literal and, failing that,\n* fall back to \"does it contain any regex-ish character\" — which said yes to\n* malformed input like `/[a-z/g`. The only answer that matters to a caller is\n* whether hydration succeeds, so ask the engine instead of approximating it.\n*/\nfunction isValidRegExp(input) {\n\tif (!input) return false;\n\ttry {\n\t\treturn hydrateRegExp(input) !== void 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n//#endregion\nexport { hydrateRegExp, isValidRegExp, serializeRegExp };\n\n//# sourceMappingURL=regexp.es.js.map","import { prettifyIdentifier } from \"./strings.es.js\";\nimport { singular } from \"./plurals.es.js\";\n//#region src/labels.ts\n/**\n* The words an identifier reads as, for a person.\n*\n* One rule, shared by every party that derives a label from a name the\n* backend serves: the zero-config CMS (`@rebasepro/cms`, which labels every\n* projected table, column, relation and enum value with these) and the\n* collections-to-tables codemod (which drops a legacy label equal to the\n* derived one, so a migrated `customizeTable` file states only real deltas).\n* Two copies of the rule would disagree, and the codemod would then drop a\n* label the panel does not derive.\n*\n* Every label is a pure function of the identifier — no translation, because\n* an identifier has no language.\n*/\n/**\n* Words that read as initialisms. `prettifyIdentifier` title-cases them\n* (`author_id` → \"Author Id\"), which is the one place its output looks wrong.\n*/\nvar INITIALISMS = {\n\tid: \"ID\",\n\tids: \"IDs\",\n\turl: \"URL\",\n\turls: \"URLs\",\n\tuuid: \"UUID\",\n\tapi: \"API\",\n\tip: \"IP\"\n};\n/**\n* A human label for a column, relation or table key.\n*\n* `first_name`, `firstName` and `FirstName` all read \"First Name\"; `author_id`\n* reads \"Author ID\"; leading underscores are dropped (`__order` → \"Order\").\n*\n* @group Labels\n*/\nfunction labelFromIdentifier(identifier) {\n\treturn prettifyIdentifier(identifier).split(\" \").filter((word) => word.length > 0).map((word) => INITIALISMS[word.toLowerCase()] ?? word).join(\" \");\n}\n/**\n* The singular of a plural label, changing only its last word.\n*\n* {@link singular} strips any trailing \"s\", so words that only look plural\n* are kept as they are: a double-s ending (`Address`, `Class`), and the Latin\n* `-us` / `-is` endings (`Status`, `Analysis`). The first letter keeps its\n* case, because `singular` lower-cases irregular forms (\"People\" → \"person\").\n*\n* @group Labels\n*/\nfunction singularLabel(label) {\n\tconst words = label.split(\" \");\n\tconst last = words[words.length - 1];\n\tif (!last || /(ss|us|is)$/i.test(last)) return label;\n\tconst single = singular(last);\n\tif (single.length === 0) return label;\n\tconst cased = last[0] === last[0].toUpperCase() ? single.charAt(0).toUpperCase() + single.slice(1) : single;\n\treturn [...words.slice(0, -1), cased].join(\" \");\n}\n/**\n* The label of one value of a closed set (an enum): a string reads as its\n* identifier does (`needs_review` → \"Needs Review\"), a number as itself.\n*\n* @group Labels\n*/\nfunction enumValueLabel(value) {\n\treturn typeof value === \"string\" ? labelFromIdentifier(value) : String(value);\n}\n//#endregion\nexport { enumValueLabel, labelFromIdentifier, singularLabel };\n\n//# sourceMappingURL=labels.es.js.map","import type { ColumnDescriptor, TableDescriptor, TenantDescriptor } from \"@rebasepro/types\";\nimport { DEFAULT_TENANT_BYPASS_ROLES } from \"@rebasepro/types\";\nimport { DEFAULT_TABLE_SCHEMA } from \"../schema/derive-names\";\n\n/**\n * Table-level options read from a {@link TableDescriptor}: the schema it is\n * declared in, soft delete and tenancy. The compiler already checked them (the soft-delete column exists\n * and is temporal, the tenant column exists and has a key type), so these do\n * no defaulting of their own.\n *\n * @module\n */\n\n/**\n * The column a soft-delete table records a deletion in — what a delete\n * stamps and a restore (an update setting it to `null`) clears — or\n * `undefined` for a table without soft delete.\n *\n * Replaces `softDeleteFieldOf(collection)` plus the `columnName ??\n * toSnakeCase(field)` that found its SQL name: both names are on the column.\n *\n * @group Table\n */\nexport function softDeleteColumn(table: TableDescriptor): ColumnDescriptor | undefined {\n const field = table.softDelete?.field;\n if (field === undefined) return undefined;\n return table.columns.find(column => column.key === field);\n}\n\n/**\n * Whether an update's values restore a soft-deleted row: they set the\n * soft-delete column back to `null`.\n *\n * Replaces `restoresSoftDeletedRow(collection, values)`.\n *\n * @group Table\n */\nexport function isSoftDeleteRestore(table: TableDescriptor, values: Record<string, unknown> | undefined): boolean {\n const field = table.softDelete?.field;\n return field !== undefined && values?.[field] === null;\n}\n\n/**\n * A table's tenancy with its defaults applied, or `undefined` for a table\n * rows of which are not scoped to a tenant.\n *\n * Replaces `getTenantConfig(collection)` and `tenantBypassRoles(tenant)`.\n *\n * @group Table\n */\nexport function tenantOf(table: TableDescriptor): (TenantDescriptor & { bypassRoles: readonly string[] }) | undefined {\n const tenant = table.tenant;\n if (!tenant) return undefined;\n return { ...tenant, bypassRoles: tenant.bypassRoles ?? DEFAULT_TENANT_BYPASS_ROLES };\n}\n\n/**\n * The Postgres schema a table names apart from the default one, or\n * `undefined` for a table in `public`.\n *\n * `public` is where a table lands without a qualifier, so nothing declares it:\n * no `CREATE SCHEMA`, no `pgSchema(\"public\")` in a generated Drizzle file\n * (Drizzle refuses that one). Every other schema is created and qualified.\n *\n * @group Table\n */\nexport function declaredSchemaOf(table: Pick<TableDescriptor, \"schema\">): string | undefined {\n return table.schema === DEFAULT_TABLE_SCHEMA ? undefined : table.schema;\n}\n","import type { ColumnDescriptor, ColumnValidation } from \"@rebasepro/types\";\nimport { hydrateRegExp } from \"@rebasepro/utils\";\n\n/**\n * The validation rules of a column, as the API checks them and the documents\n * that describe the API (OpenAPI, the panel's forms) state them.\n *\n * @module\n */\n\n/**\n * The pattern `validate({ matches })` holds a text value to, as a `RegExp`\n * that can be tested repeatedly, or `undefined` when there is none (or it does\n * not compile).\n *\n * A pattern given as a `RegExp` is stored as its source and `matchesFlags`;\n * one given as a string is read the way the panel reads it (`hydrateRegExp`),\n * so `\"/^[A-Z]{2}$/i\"` means the same on both sides. `g` and `y` are dropped:\n * they keep `lastIndex` between calls, so one pattern would accept and refuse\n * the same value on alternate rows of a bulk write.\n *\n * @group Table\n */\nexport function validationPattern(rules: Pick<ColumnValidation, \"matches\" | \"matchesFlags\"> | undefined): RegExp | undefined {\n const matches = rules?.matches;\n if (matches === undefined || matches === \"\") return undefined;\n try {\n const pattern = rules?.matchesFlags !== undefined ? new RegExp(matches, rules.matchesFlags) : hydrateRegExp(matches);\n if (!pattern) return undefined;\n return new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, \"\"));\n } catch {\n return undefined;\n }\n}\n\n/**\n * The longest text the API accepts for a column: `validate({ max })` when the\n * column states one, else the length of a `varchar(n)` / `char(n)` other than\n * the default 255, else `undefined`.\n *\n * The default length is not checked by the API: it is what a text column with\n * no stated length has always been given, and Postgres refuses a longer value\n * itself.\n *\n * @group Table\n */\nexport function textMaxLength(column: Pick<ColumnDescriptor, \"type\" | \"validate\">): number | undefined {\n const max = column.validate?.max;\n if (typeof max === \"number\") return max;\n const type = column.type;\n if ((type.kind === \"varchar\" || type.kind === \"char\") && type.length !== 255) return type.length;\n return undefined;\n}\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && !(value instanceof Date);\n\n/**\n * A value as a key two equal values share: JSON with sorted object keys, a\n * date as its ISO instant. What `uniqueItems` and `uniqueBy` compare by.\n *\n * @group Table\n */\nexport function sameValueKey(value: unknown): string {\n const stable = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(stable);\n if (v instanceof Date) return v.toISOString();\n if (isPlainRecord(v)) return Object.fromEntries(Object.keys(v).sort().map(k => [k, stable(v[k])]));\n return v;\n };\n return `${typeof value}:${JSON.stringify(stable(value))}`;\n}\n\n/**\n * The positions of the first two equal items of a list — compared whole, or,\n * with `field`, by that field of each object item (`uniqueBy`) — or\n * `undefined` when every item differs. With `field`, an item that is not an\n * object or has no value there (absent or `null`) is not compared: a rule of\n * uniqueness says nothing about a value that is not there.\n *\n * @group Table\n *\n * @internal Shared with @rebasepro/server's write validation; not part of the public API.\n */\nexport function firstDuplicate(items: readonly unknown[], field?: string): [number, number] | undefined {\n const seen = new Map<string, number>();\n for (const [index, item] of items.entries()) {\n let value: unknown = item;\n if (field !== undefined) {\n value = isPlainRecord(item) ? item[field] : undefined;\n if (value === undefined || value === null) continue;\n }\n const key = sameValueKey(value);\n const first = seen.get(key);\n if (first !== undefined) return [first, index];\n seen.set(key, index);\n }\n return undefined;\n}\n","import {\n DEFAULT_LIST_LIMIT,\n MAX_LIST_LIMIT,\n isNumericColumnType,\n isTemporalColumnType,\n isTextColumnType,\n type ColumnAccess,\n type ColumnDescriptor,\n type ColumnStorage,\n type ColumnType,\n type ColumnValidation,\n type JsonShape,\n type RelationDescriptor,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport { boundKeyColumn, columnAccess, relationJoinColumns, tenantOf, textMaxLength, validationPattern } from \"@rebasepro/common\";\nimport { labelFromIdentifier, singularLabel } from \"@rebasepro/utils\";\nimport { DELETED_QUERY_PARAM, HARD_DELETE_QUERY_PARAM } from \"./rest/soft-delete-params\";\nimport type { TableLookup } from \"./rest/served-table\";\n\n/**\n * OpenAPI 3.0.3 specification generator.\n *\n * Produces a spec that exactly mirrors the REST API consumed by the\n * Rebase SDK client (`@rebasepro/client`).\n *\n * Routes are mounted at `{basePath}/data/{slug}` by `initializeRebaseBackend`.\n */\n\nexport interface OpenApiGeneratorOptions {\n /** Base path for the API (e.g. \"/api\"). Defaults to \"/api\". */\n basePath?: string;\n /** Whether auth is enabled on data routes. Defaults to true. */\n requireAuth?: boolean;\n /**\n * The list-pagination bounds the REST layer applies, so the spec states the\n * ones a request will actually meet.\n *\n * These were hardcoded as `default: 20, maximum: 100` — neither of which\n * the server has ever used. The spec drives the API Explorer and is what a\n * generated client is built from, so an understated ceiling is a request\n * the client refuses to make, and an overstated one is a 400 nobody\n * predicted.\n */\n listLimits?: { defaultLimit?: number; maxLimit?: number };\n}\n\n/**\n * A table as the document names it: its descriptor, and the labels its tags,\n * summaries and component names are built from.\n */\ninterface DocumentedTable {\n table: TableDescriptor;\n slug: string;\n /** \"Order Items\": the tag, and the plural in summaries. */\n name: string;\n /** \"Order Item\": the singular in summaries, and the stem of the component name. */\n singularName: string;\n description?: string;\n}\n\n/**\n * The labels a table is documented under, from its slug alone.\n *\n * A table has no labels of its own (presentation is the panel's,\n * `customizeTable`); these are the defaults a collection that declared none\n * was always given — `order_items` → \"Order Items\" / \"Order Item\" — through\n * the same `@rebasepro/utils` helpers, so every component name, `$ref` and\n * `operationId` in the document stays what it was.\n */\nfunction documentedNames(slug: string): Pick<DocumentedTable, \"slug\" | \"name\" | \"singularName\"> {\n const name = labelFromIdentifier(slug);\n return { slug, name, singularName: singularLabel(name) };\n}\n\n/**\n * The OpenAPI document of the data API, built from the served tables'\n * descriptors.\n *\n * @param tables the tables the data routes serve, in the order they are\n * documented. A relation's target is described from this list too; one that\n * is not in it is documented as an open object.\n */\nexport function generateOpenApiSpec(\n tables: readonly TableDescriptor[],\n options: OpenApiGeneratorOptions = {}\n): Record<string, unknown> {\n const lookup: TableLookup = name => tables.find(table => table.slug === name) ?? tables.find(table => table.table === name);\n const collections: DocumentedTable[] = tables.map(table => ({\n table,\n ...documentedNames(table.slug),\n ...(table.description !== undefined ? { description: table.description } : {})\n }));\n const basePath = options.basePath ?? \"/api\";\n const requireAuth = options.requireAuth ?? true;\n const defaultLimit = options.listLimits?.defaultLimit ?? DEFAULT_LIST_LIMIT;\n const maxLimit = options.listLimits?.maxLimit ?? MAX_LIST_LIMIT;\n\n /**\n * The query parameters every list endpoint honours.\n *\n * Written once because it was written twice: the root listing named eight\n * and the subcollection listing named four, though both go through the same\n * `parseQueryOptions` and the same fetch. Four capabilities were therefore\n * unreachable from a generated client on nested routes, and `or`/`and` were\n * undocumented on both.\n */\n const listQueryParameters = () => [\n { name: \"limit\", in: \"query\", schema: { type: \"integer\", default: defaultLimit, minimum: 1, maximum: maxLimit },\n description: `Maximum number of records to return. Must be a whole number between 1 and ${maxLimit}; a larger one is rejected with 400 INVALID_LIMIT rather than trimmed, so a short page always means a short table. Page past the ceiling with \\`offset\\`.` },\n { name: \"offset\", in: \"query\", schema: { type: \"integer\", default: 0 },\n description: \"Number of records to skip\" },\n { name: \"page\", in: \"query\", schema: { type: \"integer\", minimum: 1 },\n description: \"Page number (alternative to offset). Calculates offset as (page-1)*limit. Cannot be combined with `offset` (400 PAGE_WITH_OFFSET).\" },\n {\n name: \"after\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Keyset cursor: continue after the row the previous page ended on. Pass back \"\n + \"`meta.nextCursor` from that response, unchanged — it is opaque, and encodes both the \"\n + \"sort keys and the last row's values for them. Unlike `offset`, a row inserted or \"\n + \"deleted before the cursor cannot shift the window, so a walk neither repeats nor \"\n + \"skips rows. Cannot be combined with `offset`/`page` (400 CURSOR_WITH_OFFSET), and an \"\n + \"`orderBy` different from the one the cursor was issued under is refused \"\n + \"(400 CURSOR_ORDER_MISMATCH) rather than seeked in an order nobody asked for.\"\n },\n {\n name: \"orderBy\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Sort field and direction. Accepts `field:asc`, `field:desc`, or `field:desc:last` — \"\n + \"the third segment places NULLs (`first`/`last`), defaulting to Postgres's own \"\n + \"convention (last ascending, first descending). Also accepts a JSON array \"\n + \"`[{\\\"field\\\":\\\"name\\\",\\\"direction\\\":\\\"asc\\\",\\\"nulls\\\":\\\"last\\\"}]` — several entries sort by \"\n + \"each in turn, the second breaking ties on the first.\",\n example: \"created_at:desc:last\"\n },\n {\n name: \"where\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"JSON object filter, mapping each field to a `[operator, value]` tuple. \"\n + \"Combines with the per-field `?field=op.value` parameters below; on the same field, the per-field parameter wins.\",\n example: \"{\\\"status\\\":[\\\"==\\\",\\\"active\\\"]}\"\n },\n {\n name: \"or\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"Disjunction of conditions, AND-ed with `where` and `searchString`.\",\n example: \"(status.eq.draft,status.eq.review)\"\n },\n {\n name: \"and\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"Conjunction of conditions, AND-ed with `where` and `searchString`. Ignored when `or` is also present.\",\n example: \"(views.gte.10,status.eq.draft)\"\n },\n {\n name: \"not\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Negation, AND-ed with `where` and `searchString`. Negates the **conjunction** of its \"\n + \"conditions: `not(a)` is `NOT a`, `not(a,b)` is `NOT (a AND b)`. Groups nest, so \"\n + \"`not(or(a,b))` is the De Morgan case. Compiles to a real SQL `NOT (...)`, which — \"\n + \"three-valued logic — also excludes rows whose column is NULL. Ignored when `or` or \"\n + \"`and` is also present.\",\n example: \"(status.eq.draft,views.gte.10)\"\n },\n {\n name: \"include\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Relations to load, in either of two spellings. **Comma-separated names or dotted \"\n + \"paths** — `author,comments.author`, up to 3 hops deep; `*` loads every relation one \"\n + \"hop deep. **JSON**, when a relation needs narrowing — \"\n + \"`{\\\"comments\\\":{\\\"limit\\\":5,\\\"where\\\":{\\\"published\\\":[\\\"==\\\",true]},\"\n + \"\\\"orderBy\\\":\\\"created_at:desc\\\",\\\"fields\\\":\\\"id,body\\\",\\\"include\\\":{\\\"author\\\":true}}}`. \"\n + \"A value starting with `{` is read as the JSON form. A name that is not a relation of \"\n + \"the table is a 400 UNKNOWN_RELATION, not a silently missing field.\",\n example: \"author,comments.author\"\n },\n {\n name: \"fields\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Comma-separated columns to return. A projection pushed into the SELECT, so a query \"\n + \"that needs two fields of a wide row reads two columns. The primary key is always \"\n + \"returned (a row that cannot be addressed cannot be updated, deleted, or paged past), \"\n + \"and `excludeFromApi` columns stay hidden whether or not they are named here. An \"\n + \"unknown column is a 400 UNKNOWN_FIELD.\",\n example: \"id,name,created_at\"\n },\n {\n name: \"distinct\",\n in: \"query\",\n schema: { type: \"boolean\" },\n description:\n \"`SELECT DISTINCT` over the returned columns. Only meaningful alongside `fields`: the \"\n + \"primary key is always in the projection, so without narrowing it every row is \"\n + \"already distinct. The response has no `meta.total` — the rows before deduplication \"\n + \"are a different set, so their count would not describe the page — and `meta.hasMore` \"\n + \"comes from reading one row past the page. Refused (400) alongside \"\n + \"`searchString` or a vector search, which attach a per-row score that makes every row \"\n + \"distinct by construction, and (400 DISTINCT_ORDER_BY_NOT_SELECTED) when `orderBy` \"\n + \"names a column `fields` does not return.\",\n example: \"true\"\n },\n {\n name: \"count\",\n in: \"query\",\n schema: { type: \"string\", enum: [\"exact\", \"none\"], default: \"exact\" },\n description:\n \"Whether to count every matching row for `meta.total`. `exact` (the default) runs a \"\n + \"`COUNT(*)` beside the page, which on a large table costs more than the page itself; \"\n + \"`none` skips it, and the response then has no `meta.total`. `meta.hasMore` is exact \"\n + \"either way — without a count it comes from reading one row past the page — so a walk \"\n + \"that pages until `hasMore` is false needs no count. Anything else is a 400 INVALID_COUNT.\",\n example: \"none\"\n },\n {\n name: \"searchString\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Text search. By default a case-insensitive substring match OR-ed across the \" +\n \"table's top-level text columns. A table declaring a `search` block \" +\n \"gets ranked full-text matching over the fields it names, and rows carry a `_score`.\"\n },\n // Vector search has been served here since vectors landed and was\n // documented nowhere, so the only way to find it was to read the query\n // parser. All four are needed together; `vector_search` and `vector`\n // are ignored unless both are present.\n {\n name: \"vector_search\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"Name of the `vector` property to run a nearest-neighbour search against. Requires `vector`.\",\n example: \"embedding\"\n },\n {\n name: \"vector\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"The query embedding, as a JSON array of numbers. Its length must match the property's declared `dimensions`.\",\n example: \"[0.12,-0.04,0.98]\"\n },\n {\n name: \"vector_distance\",\n in: \"query\",\n schema: { type: \"string\", enum: [\"cosine\", \"l2\", \"inner_product\"], default: \"cosine\" },\n description: \"Distance function used for ordering.\"\n },\n {\n name: \"vector_threshold\",\n in: \"query\",\n schema: { type: \"number\" },\n description: \"Drop rows farther than this distance. Rows are returned closest-first with a `_distance` field. \"\n + \"The response then has no `meta.total`: counting the rows within a distance computes it for every row \"\n + \"of the table. `meta.hasMore` is exact, from reading one row past the page.\"\n }\n ];\n\n const spec: Record<string, unknown> = {\n openapi: \"3.0.3\",\n info: {\n title: \"Rebase API\",\n version: \"1.0.0\",\n description:\n \"Auto-generated REST API from Rebase table definitions. \" +\n \"This is the same API consumed by the `@rebasepro/client` SDK.\"\n },\n servers: [\n {\n url: basePath,\n description: \"API Server\"\n }\n ],\n paths: {} as Record<string, unknown>,\n components: {\n schemas: {\n ErrorResponse: {\n type: \"object\",\n properties: {\n error: {\n type: \"object\",\n required: [\"message\", \"code\"],\n properties: {\n message: { type: \"string\" },\n code: { type: \"string\" },\n details: {}\n }\n }\n }\n },\n PaginationMeta: {\n type: \"object\",\n properties: {\n total: { type: \"integer\",\ndescription: \"Total number of matching records. Absent on a `distinct` read, which has no count of the rows it returns, on a vector search with a `vector_threshold`, whose count would compute a distance for every row, and when the request asked for `count=none`.\" },\n limit: { type: \"integer\",\ndescription: \"Page size used for this query\" },\n offset: { type: \"integer\",\ndescription: \"Number of records skipped\" },\n hasMore: { type: \"boolean\",\ndescription: \"Whether more records exist beyond this page\" },\n nextCursor: {\n type: \"string\",\n description:\n \"Opaque keyset cursor continuing this listing — pass it back as `?after=`. \"\n + \"Present when `hasMore` is true and the page returned at least one row; \"\n + \"absent on the last page and on an ordering no cursor can describe \"\n + \"(relevance, whose scores are computed per query and not stored). Do not \"\n + \"parse it: the encoding exists to be changed.\"\n }\n }\n }\n } as Record<string, unknown>,\n securitySchemes: {} as Record<string, unknown>\n },\n tags: [] as Array<{ name: string; description?: string }>\n };\n\n // ── Security Schemes ─────────────────────────────────────────────────\n if (requireAuth) {\n (spec.components as Record<string, unknown>).securitySchemes = {\n bearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n description:\n \"JWT access token obtained from `POST /auth/login` or `POST /auth/register`. \" +\n \"Can also be a static service key for server-to-server authentication.\"\n }\n // No `?token=` scheme. It was declared here — globally, so on every\n // operation — and no data route has ever accepted one: both\n // `createAuthMiddleware` and `createAdapterAuthMiddleware` read the\n // `Authorization` header and nothing else, deliberately, because\n // URLs leak into access logs, proxies, Referer headers and browser\n // history (`auth/middleware.ts`). Following it cost a caller twice:\n // unauthenticated, *and* a 400, since `token` is not in the query\n // parser's `reservedQueryKeys` and so compiles as a filter on a\n // column named `token`. `queryTokenAuth` is real but is mounted\n // only on storage file serving, for `<img src>`; if those routes\n // are ever documented, the scheme belongs on them, per-operation.\n };\n (spec as Record<string, unknown>).security = [\n { bearerAuth: [] }\n ];\n }\n\n const paths = spec.paths as Record<string, unknown>;\n const schemas = (spec.components as Record<string, unknown>).schemas as Record<string, unknown>;\n const tags = spec.tags as Array<{ name: string; description?: string }>;\n\n // The names a listing has already spent. A collection is free to have a\n // `limit` or a `fields` column, and the query parser reads those names as\n // pagination and field selection before any filter is compiled — so the\n // per-field filter could never fire, and documenting it a second time put\n // two parameters with the same (`name`, `in`) pair on one operation, which\n // is invalid OpenAPI: Swagger UI renders a duplicate and several generators\n // abort. Taken from the parameter list itself so the two cannot drift.\n //\n // `deleted` too: the parser reads it as the soft-delete parameter on every\n // collection (a value other than `include`/`only` is a 400), so a filter\n // on a column of that name never runs either.\n const reservedParameterNames = new Set([...listQueryParameters().map(p => p.name), DELETED_QUERY_PARAM]);\n\n /**\n * `?deleted=` on the reads of a `softDelete` collection. A delete there\n * moves the row to the trash, and every read hides trashed rows unless it\n * asks for them; the list, the single row, the count and the aggregate all\n * honour this. Empty for any other collection.\n */\n const deletedParameters = (collection: DocumentedTable) => {\n const field = collection.table.softDelete?.field;\n if (!field) return [];\n return [{\n name: DELETED_QUERY_PARAM,\n in: \"query\",\n required: false,\n schema: { type: \"string\", enum: [\"include\", \"only\"] },\n description:\n `Rows a delete moved to the trash (\\`${field}\\` set) are left out unless this asks for them: ` +\n \"`include` reads them with the live rows, `only` reads them alone. Any other value is a \" +\n \"400 INVALID_DELETED_PARAM.\"\n }];\n };\n\n /**\n * `?hard=` on the deletes of a `softDelete` collection: delete for good\n * rather than move to the trash. Empty for any other collection.\n */\n const hardDeleteParameters = (collection: DocumentedTable) => {\n if (!collection.table.softDelete) return [];\n return [{\n name: HARD_DELETE_QUERY_PARAM,\n in: \"query\",\n required: false,\n schema: { type: \"boolean\", default: false },\n description:\n \"`true` deletes for good instead of moving to the trash — a row already in the trash \" +\n \"included, which is how the trash is emptied. Only `true`/`1` and `false`/`0` are \" +\n \"accepted; anything else is a 400 INVALID_HARD_PARAM.\"\n }];\n };\n\n /** What a delete does to a `softDelete` collection's row, for the delete operations' descriptions. */\n const softDeleteBehaviour = (collection: DocumentedTable): string | undefined => {\n const field = collection.table.softDelete?.field;\n if (!field) return undefined;\n return `This table soft-deletes: a delete moves the row to the trash by stamping \\`${field}\\`, ` +\n \"and every read leaves it out unless it passes `?deleted=include` or `?deleted=only`. A PATCH \" +\n `setting \\`${field}\\` back to \\`null\\` restores it. Pass \\`?hard=true\\` to delete for good.`;\n };\n\n // Every component name this document will carry, known before the first\n // schema is built: a relation may point at a collection that appears later\n // in the list, or at one that is not documented here at all, and a `$ref`\n // at a component that does not exist is a document Swagger UI renders empty\n // and a strict generator refuses.\n const registeredSchemas = new Set((collections || []).map(schemaNameFor));\n\n /**\n * `Prefer: return=minimal`, on every route that would otherwise send a row\n * back. Documented rather than left implicit because a client generated\n * from this spec cannot send a header the spec does not mention.\n */\n const preferHeader = {\n name: \"Prefer\",\n in: \"header\",\n required: false,\n schema: { type: \"string\", enum: [\"return=minimal\"] },\n description:\n \"`return=minimal` asks the server not to send the written row back. Single writes then \" +\n \"answer `204 No Content`; bulk and batch writes answer `200` carrying the ids only. \" +\n \"The response repeats it in `Preference-Applied` when it was honoured.\"\n };\n\n const ifMatchHeader = {\n name: \"If-Match\",\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description:\n \"The `ETag` this edit was made against, from the `GET` that read the row. The write is \" +\n \"refused with `412` if the row has changed since — which is the difference between \" +\n \"\\\"update the row I read\\\" and \\\"overwrite whatever is there now\\\". `*` means only that \" +\n \"the row must exist.\"\n };\n\n const preconditionFailed = {\n 412: {\n description:\n \"The row changed since the ETag in `If-Match` was issued. Nothing was written: \" +\n \"re-read the row, re-apply the change, and send the new ETag\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n }\n };\n\n const minimalResponse = {\n 204: {\n description: \"Written. `Prefer: return=minimal` was honoured, so there is no body\",\n headers: {\n \"Preference-Applied\": { schema: { type: \"string\" }, description: \"`return=minimal`\" }\n }\n }\n };\n\n // ── POST /data/_batch — writes across collections, one transaction ────\n //\n // Registered before the per-collection paths for the same reason the route\n // is: `_batch` is not a collection, and reading it as one would document a\n // table that does not exist.\n if ((collections || []).length > 0) {\n paths[\"/data/_batch\"] = {\n post: {\n tags: [\"Data\"],\n summary: \"Write across tables in one transaction\",\n description:\n \"All-or-nothing across tables — an order and its line items, a user and \" +\n \"their membership row. `/bulk` is one table at a time, and sending the two \" +\n \"halves as separate requests is exactly the sequence that can half-succeed.\\n\\n\" +\n \"Operations run in order, each through the same pipeline its single-row route \" +\n \"uses: the same validation, callbacks and row-level security, as the same role. \" +\n \"An operation may name itself with `ref`, and a later one may stand \" +\n \"`{ \\\"$ref\\\": \\\"order.id\\\" }` wherever a value goes — in `values`, at any depth, \" +\n \"or as an `id`. Only backward references resolve.\\n\\n\" +\n \"Capped at the same number of entries as a bulk write, because one batch is one \" +\n \"transaction and holds its locks for the whole of it.\",\n operationId: \"batchWrite\",\n parameters: [\n {\n name: \"Idempotency-Key\",\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description:\n \"Names this batch so a retry is recognised instead of repeated. Without it a \" +\n \"client that lost the response cannot tell a replay from a second batch, and \" +\n \"the whole batch is written twice.\"\n },\n preferHeader\n ],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"operations\"],\n properties: {\n operations: {\n type: \"array\",\n items: { $ref: \"#/components/schemas/BatchOperation\" }\n }\n }\n }\n }\n }\n },\n responses: {\n 200: {\n description:\n \"One entry per operation, in order: the written row for a create, update or \" +\n \"upsert, and `null` for a delete\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n data: { type: \"array\", items: { type: \"object\", nullable: true } },\n meta: { type: \"object\", properties: { operations: { type: \"integer\" } } }\n }\n }\n }\n }\n },\n 400: {\n description:\n \"Malformed body, an unknown table or field, an illegal field operation \" +\n \"or conflict target, a forward `$ref`, or more operations than the limit. \" +\n \"Nothing was written\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 404: {\n description: \"An `update` or `delete` names a row that does not exist; nothing was written\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 409: {\n description: \"A request with the same Idempotency-Key is still in flight\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 422: {\n description: \"The Idempotency-Key was already used for a different request\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n ...errorResponses(requireAuth)\n }\n }\n };\n\n schemas.FieldOperation = {\n type: \"object\",\n description:\n \"A change to the column's current value rather than the value to store. Exactly one \" +\n \"operator per field. Only on an update: an operation over a value that does not exist \" +\n \"yet is refused with a 400.\",\n properties: {\n $inc: { type: \"number\", description: \"Add to a `number` column; negative to subtract.\" },\n $push: { description: \"Append a value, or each of an array of values, to an `array` column.\" },\n $pull: { description: \"Remove every occurrence of a value from an `array` column.\" },\n $merge: { type: \"object\", description: \"Shallow-merge an object into a `map` column.\" }\n }\n };\n\n schemas.BatchOperation = {\n type: \"object\",\n required: [\"op\", \"table\"],\n properties: {\n op: { type: \"string\", enum: [\"create\", \"update\", \"upsert\", \"delete\"] },\n table: { type: \"string\", description: \"The slug of the table this operation writes to.\" },\n id: {\n description:\n \"Required for `update` and `delete`. May instead be a reference marker — an \" +\n \"object whose single key is `$ref` and whose value is `<ref name>.<field>`, \" +\n \"e.g. `{ \\\"$ref\\\": \\\"order.id\\\" }` — naming a column of the row an earlier \" +\n \"operation wrote. (Described rather than declared as a schema: `$ref` is a \" +\n \"reserved word to every OpenAPI reader, and a property named `$ref` is read \" +\n \"as a reference and mangled.)\",\n oneOf: [{ type: \"string\" }, { type: \"integer\" }, { type: \"object\" }]\n },\n values: {\n type: \"object\",\n description:\n \"The row's fields. Values may be `$ref` markers; an `update` may also carry \" +\n \"field operations.\",\n additionalProperties: true\n },\n onConflict: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"`upsert` only: the columns the conflict is matched on. Must carry a declared \" +\n \"uniqueness guarantee. Defaults to the primary key.\"\n },\n ref: {\n type: \"string\",\n description: \"Names this operation's result, so a later one can `$ref` its columns.\"\n }\n }\n };\n }\n\n // ── Collection routes ────────────────────────────────────────────────\n for (const collection of (collections || [])) {\n const schemaName = schemaNameFor(collection);\n const slug = collection.slug;\n\n tags.push({\n name: collection.name,\n description: collection.description || `CRUD operations for ${collection.name}`\n });\n\n // Build component schema for this collection\n schemas[schemaName] = buildTableSchema(collection.table, registeredSchemas, lookup);\n\n // Build an \"input\" schema (no read-only/auto fields like autoValue dates)\n schemas[`${schemaName}Input`] = buildTableInputSchema(collection.table, lookup);\n\n // The update body — same columns, no `required`. PATCH and PUT both\n // merge, so a field left out means \"unchanged\", not \"omitted by mistake\".\n schemas[`${schemaName}Update`] = buildTableUpdateSchema(collection.table, lookup);\n\n const dataPath = `/data/${slug}`;\n const softDeleteNote = softDeleteBehaviour(collection);\n\n // ── GET /data/{slug}/count — How many rows match ──────────────\n //\n // Served for every collection since the route existed and described\n // here for the first time. A spec is what a generated client can see,\n // so an endpoint missing from it is an endpoint that client does not\n // have — and this is the one a paginating UI needs to know how many\n // pages there are.\n //\n // Registered before the list path so its literal segment cannot be read\n // as an `{id}`, which is the same ordering the router uses.\n //\n // Its parameters are the listing's that narrow the rows — the filters,\n // the logical groups, the search and the vector search, all of which\n // the route reads (`countRawEntities`) — and not the ones that page or\n // shape them. The vector search and the groups were read and not\n // described, which left a generated client unable to count what its\n // own `find()` had asked for.\n const countNarrowing = new Set([\n \"where\", \"or\", \"and\", \"not\", \"searchString\",\n \"vector_search\", \"vector\", \"vector_distance\", \"vector_threshold\"\n ]);\n const countParameters = [\n ...listQueryParameters()\n .filter(p => countNarrowing.has(p.name))\n .map(p => p.name === \"vector_threshold\"\n ? { ...p, description: \"Count only the rows within this distance of `vector`.\" }\n : p),\n ...deletedParameters(collection),\n ...buildFilterParameters(collection.table, reservedParameterNames)\n ];\n const countResponses = {\n 200: {\n description: \"The number of matching rows\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"count\"],\n properties: {\n count: { type: \"integer\", description: \"Rows matching the filters\" }\n }\n }\n }\n }\n },\n ...errorResponses(requireAuth)\n };\n paths[`${dataPath}/count`] = {\n get: {\n tags: [collection.name],\n summary: `Count ${collection.name}`,\n description:\n \"The number of rows the same filters would return, without returning them. \" +\n \"Takes the filter and search parameters of the list endpoint; `limit`, `offset` \" +\n \"and `orderBy` are not part of the question and are ignored.\",\n operationId: `count${schemaName}`,\n parameters: countParameters,\n responses: countResponses\n },\n // The same count, its parameters in the body — documented from\n // the GET's own list, as `POST …/query` is from the listing's.\n post: queryOperation({\n tags: [collection.name],\n summary: `Count ${collection.name}, parameters in the body`,\n description:\n \"The count `GET` answers, with its query parameters in a JSON body instead of the URL: \" +\n \"the same filters, search and vector search, the same row-level security, and the same \" +\n \"errors. It reads and never writes, so a credential needs `data:read` for it. Use it when \" +\n \"the URL would not fit: a vector search's embedding, a long `in` list. A parameter also on \" +\n \"the URL is a 400 INVALID_QUERY_BODY.\",\n operationId: `count${schemaName}Query`,\n parameters: countParameters,\n responses: countResponses,\n reserved: reservedParameterNames\n })\n };\n\n // ── GET /data/{slug}/aggregate — count/sum/avg/min/max ────────\n //\n // Before the list path for the same reason `/count` is: a literal\n // segment that a generated client would otherwise be told is an `{id}`.\n paths[`${dataPath}/aggregate`] = {\n get: {\n tags: [collection.name],\n summary: `Aggregate ${collection.name}`,\n description:\n \"Aggregate values over the rows the same filters would return. Takes the filter and \" +\n \"search parameters of the list endpoint. Row-level security applies to the rows \" +\n \"being aggregated, so a caller who can read nothing counts nothing.\",\n operationId: `aggregate${schemaName}`,\n parameters: [\n {\n name: \"select\",\n in: \"query\",\n required: true,\n description:\n \"Comma-separated aggregates, e.g. `count()`, `sum(total)`, `avg(total),max(total)`. \" +\n \"Results are keyed `count`, `sum_total`, `avg_total` and so on.\",\n schema: { type: \"string\" },\n example: \"count(),sum(total)\"\n },\n {\n name: \"groupBy\",\n in: \"query\",\n required: false,\n description: \"Comma-separated fields to group by. Each grouped field is returned alongside the aggregates.\",\n schema: { type: \"string\" },\n example: \"status\"\n },\n // `limit`, `offset` and `page` bound and page the groups,\n // exactly as they do a listing's rows.\n ...listQueryParameters().filter(p =>\n p.name === \"searchString\" || p.name === \"limit\" || p.name === \"offset\" || p.name === \"page\"),\n {\n name: \"orderBy\",\n in: \"query\",\n required: false,\n description:\n \"Sort for the groups, by a `groupBy` field or an aggregate's result key (`count`, \" +\n \"`sum_total`): `key:asc`, `key:desc` or `key:desc:last`. Groups it leaves tied are \" +\n \"ordered by the `groupBy` fields, so every page boundary falls in the same place. \" +\n \"`offset`, `page` and `orderBy` need `groupBy` — without it the result is one row — \" +\n \"and are otherwise a 400 INVALID_AGGREGATE_WINDOW.\",\n schema: { type: \"string\" },\n example: \"count:desc\"\n },\n ...deletedParameters(collection),\n ...buildFilterParameters(collection.table, reservedParameterNames)\n ],\n responses: {\n 200: {\n description: \"One row per group, or a single row when `groupBy` is absent\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"data\"],\n properties: {\n data: {\n type: \"array\",\n items: { type: \"object\", additionalProperties: true }\n },\n meta: {\n type: \"object\",\n description: \"The page of groups. Present when `groupBy` is.\",\n properties: {\n limit: { type: \"integer\" },\n offset: { type: \"integer\" },\n hasMore: { type: \"boolean\", description: \"Whether a group follows this page.\" }\n }\n }\n }\n }\n }\n }\n },\n 501: { description: \"This backend's data driver does not implement aggregates\" },\n ...errorResponses(requireAuth)\n }\n }\n };\n\n // ── GET /data/{slug} — List entities ──────────────────────────\n const listParameters = [\n ...listQueryParameters(),\n ...deletedParameters(collection),\n ...buildFilterParameters(collection.table, reservedParameterNames)\n ];\n const listResponses = {\n 200: {\n description: \"Paginated list of entities\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n data: {\n type: \"array\",\n items: { $ref: `#/components/schemas/${schemaName}` }\n },\n meta: { $ref: \"#/components/schemas/PaginationMeta\" }\n }\n }\n }\n }\n },\n ...errorResponses(requireAuth)\n };\n\n // ── POST /data/{slug}/query — the same listing, parameters in the body\n //\n // Before the list path, as `/count` is. Documented from the list's own\n // parameter list, so the two cannot describe different listings.\n paths[`${dataPath}/query`] = {\n post: queryOperation({\n tags: [collection.name],\n summary: `List ${collection.name}, parameters in the body`,\n operationId: `query${schemaName}`,\n parameters: listParameters,\n responses: listResponses,\n reserved: reservedParameterNames\n })\n };\n\n paths[dataPath] = {\n get: {\n tags: [collection.name],\n summary: `List ${collection.name}`,\n operationId: `list${schemaName}`,\n parameters: listParameters,\n responses: listResponses\n },\n post: {\n tags: [collection.name],\n summary: `Create ${collection.singularName || collection.name}`,\n operationId: `create${schemaName}`,\n parameters: [\n {\n name: \"on_conflict\",\n in: \"query\",\n required: false,\n schema: { type: \"string\" },\n description:\n \"Comma-separated columns to upsert on, turning the create into \" +\n \"INSERT ... ON CONFLICT DO UPDATE. They must carry a declared uniqueness \" +\n \"guarantee — `validation.unique`, a `unique` index, or the primary key — \" +\n \"or the request is refused with a 400 naming the targets that do exist. \" +\n \"Left off, this is a plain insert and a duplicate key still raises. \" +\n \"Refused (400 `INVALID_CONFLICT_TARGET`) on the auth table, whose rows are \" +\n \"the users: create them with a plain POST and change them with PATCH.\",\n example: \"sku\"\n },\n preferHeader\n ],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${schemaName}Input` }\n }\n }\n },\n responses: {\n 201: {\n description: \"Created entity\",\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${schemaName}` }\n }\n }\n },\n ...minimalResponse,\n ...errorResponses(requireAuth)\n }\n }\n };\n\n // ── Bulk: one transaction, all-or-nothing ─────────────────────\n //\n // These went undocumented while they existed, which is the same defect\n // the update verb had: an endpoint the server serves and the spec does\n // not mention cannot be reached by a generated client at all.\n const idempotencyHeader = {\n name: \"Idempotency-Key\",\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description:\n \"Names this write so a retry is recognised instead of repeated. Without it a \" +\n \"client that lost the response cannot distinguish a replay from a second \" +\n \"genuine batch, and the whole batch is written twice. A key names one request: \" +\n \"re-send the identical request to replay its answer, and use a new key for a \" +\n \"different one.\"\n };\n\n const bulkErrors = {\n 400: {\n description: \"Malformed body, an unknown field, or more rows than the per-batch limit\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 409: {\n description:\n \"A request with the same Idempotency-Key is still in flight. Retry it: the \" +\n \"first attempt's result is replayed once it lands\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 422: {\n description: \"The Idempotency-Key was already used for a different request\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n ...errorResponses(requireAuth)\n };\n\n paths[`/data/${slug}/bulk`] = {\n post: {\n tags: [collection.name],\n summary: `Create many ${collection.name} in one transaction`,\n description:\n \"All-or-nothing: if any row is rejected none of them land, and the error names \" +\n \"the offending index. Every row still runs callbacks, relations and row-level \" +\n \"security. Capped server-side because one batch holds its locks for its whole \" +\n \"duration.\",\n operationId: `createMany${schemaName}`,\n parameters: [idempotencyHeader, preferHeader],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"rows\"],\n properties: {\n rows: { type: \"array\", items: { $ref: `#/components/schemas/${schemaName}Input` } },\n upsert: {\n type: \"boolean\",\n description:\n \"Write each row as INSERT ... ON CONFLICT DO UPDATE. Refused \" +\n \"(400 `INVALID_CONFLICT_TARGET`) on the auth table, whose rows are the users.\"\n },\n onConflict: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"The columns the conflict is matched on, instead of the primary key. \" +\n \"They must carry a declared uniqueness guarantee. Naming them without \" +\n \"`upsert: true` is a 400 rather than a silently ignored field.\"\n }\n }\n }\n }\n }\n },\n responses: {\n 200: {\n description: \"The written rows, in the order given\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n data: { type: \"array\", items: { $ref: `#/components/schemas/${schemaName}` } },\n meta: { type: \"object\", properties: { written: { type: \"integer\" } } }\n }\n }\n }\n }\n },\n ...bulkErrors\n }\n },\n patch: {\n tags: [collection.name],\n summary: `Update many ${collection.name} in one transaction`,\n description:\n \"Each entry names its row and the fields to change. `{ id, data }` rather than \" +\n \"flat rows carrying their own key, because on a table keyed on something other \" +\n \"than `id` a flat row cannot say whether a column is the address or a value to \" +\n \"write. An id matching no row fails the batch.\",\n operationId: `updateMany${schemaName}`,\n parameters: [idempotencyHeader, preferHeader],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"updates\"],\n properties: {\n updates: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"id\", \"data\"],\n properties: {\n id: { type: \"string\", description: \"The row to update\" },\n data: { $ref: `#/components/schemas/${schemaName}Update` }\n }\n }\n }\n }\n }\n }\n }\n },\n responses: {\n 200: {\n description: \"The updated rows, in the order given\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n data: { type: \"array\", items: { $ref: `#/components/schemas/${schemaName}` } },\n meta: { type: \"object\", properties: { written: { type: \"integer\" } } }\n }\n }\n }\n }\n },\n 404: {\n description: \"One of the ids matches no row; nothing was written\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n ...bulkErrors\n }\n }\n };\n\n paths[`/data/${slug}/bulk/delete`] = {\n post: {\n tags: [collection.name],\n summary: `Delete many ${collection.name} in one transaction`,\n description:\n \"A POST, not `DELETE /bulk` with a body. Bodies on DELETE are permitted but \" +\n \"widely dropped by proxies and CDNs, and several generators ignore \" +\n \"`requestBody` on a DELETE operation — a generated client would send the \" +\n \"request with no ids at all. Takes ids rather than a filter: a mistyped \" +\n \"condition that empties a table cannot be reviewed at the call site the way \" +\n \"an explicit list can. `beforeDelete`/`afterDelete` fire per row.\" +\n (softDeleteNote ? `\\n\\n${softDeleteNote}` : \"\"),\n operationId: `deleteMany${schemaName}`,\n parameters: [idempotencyHeader, ...hardDeleteParameters(collection)],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"ids\"],\n properties: {\n ids: {\n type: \"array\",\n items: { oneOf: [{ type: \"string\" }, { type: \"integer\" }] }\n }\n }\n }\n }\n }\n },\n responses: {\n 200: {\n description: softDeleteNote\n ? \"How many rows were moved to the trash, or deleted for good with `?hard=true`\"\n : \"How many rows were deleted\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n meta: { type: \"object\", properties: { deleted: { type: \"integer\" } } }\n }\n }\n }\n }\n },\n 404: {\n description: \"One of the ids matches no row; nothing was deleted\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n ...bulkErrors\n }\n }\n };\n\n // ── GET/PUT/DELETE /data/{slug}/{id} ──────────────────────────\n const entityPath = `/data/${slug}/{id}`;\n paths[entityPath] = {\n get: {\n tags: [collection.name],\n summary: `Get ${collection.singularName || collection.name} by ID`,\n operationId: `get${schemaName}ById`,\n parameters: [\n { name: \"id\",\nin: \"path\",\nrequired: true,\nschema: { type: \"string\" },\ndescription: \"Entity ID\" },\n // The same two parameters the list route documents, and the\n // same code serves them — one row and a page of them go\n // through one pipeline, so anything true of `include` or\n // `fields` there is true here.\n {\n name: \"include\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Relations to load: comma-separated names or dotted paths \"\n + \"(`author,comments.author`, up to 3 hops), `*` for all one hop deep, or the \"\n + \"JSON form for per-relation `limit`/`where`/`orderBy`/`fields`. An unknown \"\n + \"name is a 400 UNKNOWN_RELATION.\",\n example: \"author,comments.author\"\n },\n {\n name: \"fields\",\n in: \"query\",\n schema: { type: \"string\" },\n description:\n \"Comma-separated columns to return, as a SELECT projection. The primary key \"\n + \"always survives and `excludeFromApi` columns stay hidden.\",\n example: \"id,title\"\n },\n ...deletedParameters(collection)\n ],\n responses: {\n 200: {\n description: \"Entity found\",\n headers: {\n ETag: {\n schema: { type: \"string\" },\n description:\n \"This row's version. Send it back as `If-Match` on a later PATCH or \" +\n \"DELETE to have the write refused if the row has changed in between.\"\n }\n },\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${schemaName}` }\n }\n }\n },\n 404: { description: \"Entity not found\",\ncontent: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } } },\n ...errorResponses(requireAuth)\n }\n },\n patch: updateOperation(collection, schemaName, requireAuth, {\n ifMatchHeader,\n preferHeader,\n preconditionFailed,\n minimalResponse\n }),\n delete: {\n tags: [collection.name],\n summary: `Delete ${collection.singularName || collection.name}`,\n ...(softDeleteNote ? { description: softDeleteNote } : {}),\n operationId: `delete${schemaName}`,\n parameters: [\n { name: \"id\",\nin: \"path\",\nrequired: true,\nschema: { type: \"string\" },\ndescription: \"Entity ID\" },\n ifMatchHeader,\n {\n name: \"Idempotency-Key\",\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description:\n \"Names this delete so a retry replays its answer. A delete replayed after \" +\n \"the first attempt committed would otherwise answer 404 — which an offline \" +\n \"queue reads as a permanent failure for a delete that in fact succeeded.\"\n },\n ...hardDeleteParameters(collection)\n ],\n responses: {\n 204: {\n description: softDeleteNote\n ? \"Moved to the trash: the row still exists and can be restored. With `?hard=true`, deleted for good\"\n : \"Deleted successfully\"\n },\n 404: { description: \"Entity not found\",\ncontent: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } } },\n 409: {\n description: \"A request with the same Idempotency-Key is still in flight\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 422: {\n description: \"The Idempotency-Key was already used for a different request\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n ...preconditionFailed,\n ...errorResponses(requireAuth)\n }\n }\n };\n\n }\n\n // ── Subcollection routes ─────────────────────────────────────────────\n //\n // A second pass, after every collection's component schema exists. These\n // routes `$ref` the *target's* schema, and the first pass builds schemas in\n // array order — so doing this inline meant a subcollection whose target\n // appeared later in the list silently degraded to an untyped `object`.\n //\n // The names come from the *resolved* relations, not from the authored\n // `relations` array. `relationName` is optional at the authoring surface —\n // it defaults to the property key, or to the target's slug — so reading the\n // raw field skipped every relation that relied on the default, and missed\n // relations declared inline on a property entirely, since those are not in\n // the array. These are the same resolved names the nested-path router\n // matches, so the spec and the routes cannot drift apart.\n //\n // A to-one relation is left out. `posts/1/author` resolves, but it\n // addresses a single row, and documenting it as a paginated list would\n // describe a response shape the client never gets.\n for (const collection of (collections || [])) {\n const slug = collection.slug;\n const schemaName = schemaNameFor(collection);\n const relations = collection.table.relations.filter(relation => relation.cardinality === \"many\");\n for (const relation of relations) {\n const relationName = relation.name;\n const targetSchema = schemaNameFor(documentedNames(relation.target));\n\n const subPath = `/data/${slug}/{parentId}/${relationName}`;\n const nestedParameters = [\n { name: \"parentId\",\nin: \"path\",\nrequired: true,\nschema: { type: \"string\" },\ndescription: `${collection.singularName || collection.name} ID` },\n // The nested list handler goes through the same\n // `parseQueryOptions` and the same fetch as the root\n // one, so it honours the same parameters. It documented\n // four of them.\n ...listQueryParameters()\n ];\n const nestedResponses = {\n 200: {\n description: `List of related ${relationName}`,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n data: {\n type: \"array\",\n items: schemas[targetSchema]\n ? { $ref: `#/components/schemas/${targetSchema}` }\n : { type: \"object\" }\n },\n meta: { $ref: \"#/components/schemas/PaginationMeta\" }\n }\n }\n }\n }\n },\n ...errorResponses(requireAuth)\n };\n\n // Only add if the schema exists (target collection is also registered)\n paths[subPath] = {\n get: {\n tags: [collection.name],\n summary: `List ${relationName} for ${withIndefiniteArticle(collection.singularName || collection.name)}`,\n operationId: `list${schemaName}${toPascalCase(relationName)}`,\n parameters: nestedParameters,\n responses: nestedResponses\n }\n };\n paths[`${subPath}/query`] = {\n post: queryOperation({\n tags: [collection.name],\n summary: `List ${relationName} for ${withIndefiniteArticle(collection.singularName || collection.name)}, parameters in the body`,\n operationId: `query${schemaName}${toPascalCase(relationName)}`,\n parameters: nestedParameters,\n responses: nestedResponses,\n reserved: reservedParameterNames\n })\n };\n }\n }\n\n return spec;\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────\n\n/**\n * Is this column (or relation) part of the shape the document may describe?\n *\n * One exclusion, and it is the document telling the truth about what the\n * server does: a `.private()` column is stripped from every row the API\n * serves, for every caller, including admins and service keys, and a list\n * `access.read: []` closes it to everybody the same way. A schema that lists\n * such a column describes a field that is never present, and it describes it\n * to everyone: `/docs` is mounted on the app, not on the data router, so it\n * carries none of the auth middleware `{basePath}/data` does.\n *\n * The write half adds `.readOnly()` and generated columns: nobody writes them\n * through the API (`write-validation.ts` refuses them), so an input body that\n * offered them would offer a 400.\n *\n * The same rule the SDK generator applies to its `Row` type\n * (`packages/codegen/src/generate-types.ts`).\n */\nfunction isDocumented(target: Pick<ColumnDescriptor, \"private\" | \"access\" | \"readOnly\">, direction: \"read\" | \"write\" = \"read\"): boolean {\n if (direction === \"write\" && target.readOnly) return false;\n const access = columnAccess(target);\n return access?.[direction]?.length !== 0;\n}\n\n/**\n * The access rules a reader of the document is told about: the column's role\n * lists, with `.readOnly()` stated as \"writable by nobody\". A generated column\n * is left unannotated — its read-only-ness is the database's, not a rule.\n */\nfunction documentedAccess(column: Pick<ColumnDescriptor, \"private\" | \"access\" | \"readOnly\" | \"generated\">): ColumnAccess | undefined {\n const access = columnAccess(column);\n if (column.readOnly && column.generated === undefined && !column.private) {\n return { ...(access?.read !== undefined ? { read: access.read } : {}), write: [] };\n }\n return access;\n}\n\n/**\n * The `x-rebase-access` annotation, or nothing for a column with no rule.\n *\n * A vendor extension rather than a schema keyword because OpenAPI has no way to\n * say \"this property is present for some callers\" — `readOnly` is about the\n * direction of a field, not about who. Generators ignore what they do not know,\n * so a client built from this spec still compiles; a *human* reading `/docs`, or\n * a gateway that wants to enforce the same rule at the edge, gets the role lists\n * verbatim. Emitted for the role case only: a column closed to everybody is\n * absent from the document entirely, which is a stronger statement.\n */\nfunction accessAnnotation(access: ColumnAccess | undefined): Record<string, unknown> | undefined {\n if (!access) return undefined;\n const annotation: Record<string, unknown> = {};\n if (access.read !== undefined) annotation.read = [...access.read];\n if (access.write !== undefined) annotation.write = [...access.write];\n return Object.keys(annotation).length > 0 ? annotation : undefined;\n}\n\n/** The sentence `x-rebase-access` deserves in prose, for a reader of `/docs`. */\nfunction accessDescription(access: ColumnAccess | undefined): string | undefined {\n if (!access) return undefined;\n const parts: string[] = [];\n const phrase = (roles: readonly string[]) =>\n roles.length === 0 ? \"nobody through the API\" : roles.map(r => `\\`${r}\\``).join(\", \") + \" (and `admin`)\";\n if (access.read !== undefined) parts.push(`readable by ${phrase(access.read)}`);\n if (access.write !== undefined) parts.push(`writable by ${phrase(access.write)}`);\n if (parts.length === 0) return undefined;\n return `Field access: ${parts.join(\"; \")}. A caller without the role does not receive the field at all — it is absent, not null.`;\n}\n\n/**\n * The names an undocumented column or relation is served under — its key and\n * its SQL name — so a foreign key derived from a relation cannot put a hidden\n * column back on the surface under its other name. Same pair, same reason, as\n * `excludedApiKeys` in the SDK generator.\n */\nfunction excludedApiKeys(table: TableDescriptor, direction: \"read\" | \"write\" = \"read\", lookup?: TableLookup): Set<string> {\n const excluded = new Set<string>();\n for (const column of table.columns) {\n if (isDocumented(column, direction)) continue;\n excluded.add(column.key);\n excluded.add(column.column);\n }\n for (const relation of table.relations) {\n // A link is documented exactly when its key column is (`{ reviewer }`\n // writes the `.readOnly()` `reviewerId`); a relation is read only if\n // every column its join reads is (`staff.handledCases` reads the\n // private `cases.informantId`).\n const bound = boundKeyColumn(table, relation);\n const joined = direction === \"read\" ? relationJoinColumns(table, relation, lookup) : [];\n if (!isDocumented(relation, direction)\n || (bound !== undefined && !isDocumented(bound, direction))\n || joined.some(column => !isDocumented(column, \"read\"))) {\n excluded.add(relation.name);\n }\n }\n return excluded;\n}\n\n/**\n * The column a table is addressed by on the wire: the first of its key.\n * `undefined` for a table introspected without a key.\n */\nfunction keyColumnOf(table: TableDescriptor | undefined): ColumnDescriptor | undefined {\n const key = table?.primaryKey[0];\n return key === undefined ? undefined : table?.columns.find(column => column.key === key);\n}\n\n/**\n * The schema of a primary key or of a foreign key pointing at one: the key\n * column's own type, stripped of the column-level facts (description,\n * validation bounds) that belong to the column and not to a reference to it.\n *\n * Falls back to `string` for a table without a key.\n */\nfunction idSchemaFor(table: TableDescriptor | undefined): Record<string, unknown> {\n const key = keyColumnOf(table);\n if (!key) return { type: \"string\" };\n const converted = columnTypeSchema(key);\n const schema: Record<string, unknown> = { type: converted.type ?? \"string\" };\n if (converted.format) schema.format = converted.format;\n return schema;\n}\n\n/**\n * Whether a key column is the planner's implicit `id` — text, keyed, filled by\n * `gen_random_uuid()::text`, declared first. It has always been documented as\n * a \"Unique identifier\", with no column facts of its own.\n */\nfunction isImplicitIdColumn(table: TableDescriptor, column: ColumnDescriptor): boolean {\n return column.key === \"id\" && table.columns[0] === column && column.type.kind === \"text\"\n && column.default?.kind === \"sql\" && column.default.expression === \"gen_random_uuid()::text\";\n}\n\n/**\n * The schema an *included* relation arrives as: the target's own row.\n *\n * `$ref` when the target is one of the tables this document describes, and an\n * open object when it is not — a dangling pointer makes Swagger UI render an\n * empty model and makes a strict generator abort, which is worse than a vague\n * one.\n */\nfunction includedRelationSchema(\n relation: RelationDescriptor,\n registeredSchemas: ReadonlySet<string>\n): Record<string, unknown> {\n const targetSchema = schemaNameFor(documentedNames(relation.target));\n const item: Record<string, unknown> = registeredSchemas.has(targetSchema)\n ? { $ref: `#/components/schemas/${targetSchema}` }\n : { type: \"object\" };\n return relation.cardinality === \"many\" ? { type: \"array\", items: item } : item;\n}\n\n/**\n * Emit a table's relations onto a read schema: the foreign keys first, then\n * the relations themselves.\n *\n * The order and the keys are the SDK `Row`'s, deliberately — the parity test\n * next door compares the two key sets.\n *\n * A `belongsTo` reaches the wire under its foreign-key column's key\n * (`authorId`); a relation addressed by the same name as its own foreign key\n * is served as either the scalar or the nested row depending on `include`, so\n * it is documented as both.\n */\nfunction emitRelationProperties(\n table: TableDescriptor,\n properties: Record<string, unknown>,\n required: string[],\n emitted: Set<string>,\n registeredSchemas: ReadonlySet<string>,\n lookup: TableLookup\n): void {\n for (const relation of table.relations) {\n if (relation.kind !== \"belongsTo\") continue;\n const fieldKey = relation.localField;\n if (emitted.has(fieldKey)) continue;\n\n const foreignKey = idSchemaFor(lookup(relation.target));\n const shadowedByInclude = relation.name === fieldKey;\n properties[fieldKey] = shadowedByInclude\n ? { oneOf: [foreignKey, includedRelationSchema(relation, registeredSchemas)] }\n : { ...foreignKey, description: `Foreign key into \\`${relation.target}\\`` };\n emitted.add(fieldKey);\n\n const column = table.columns.find(candidate => candidate.key === fieldKey);\n if (column && !column.nullable && !shadowedByInclude) required.push(fieldKey);\n }\n\n for (const relation of table.relations) {\n if (emitted.has(relation.name)) continue;\n properties[relation.name] = includedRelationSchema(relation, registeredSchemas);\n emitted.add(relation.name);\n }\n}\n\n/**\n * Whether a foreign-key column states anything of its own — a rule, a\n * default, access, a description, … — beyond being the key a relation points\n * with. Such a column is documented as the column it is; a plain foreign key\n * is documented from the relation, typed from its target's key.\n */\nfunction isExplicitForeignKey(column: ColumnDescriptor): boolean {\n if (column.derived) return false;\n return column.primaryKey !== undefined || column.default !== undefined || column.generated !== undefined\n || column.readOnly !== undefined || column.private !== undefined || column.access !== undefined\n || column.stamp !== undefined || column.validate !== undefined || column.oneOf !== undefined\n || column.description !== undefined || column.storage !== undefined || column.semantic !== undefined\n || column.vectorIndex !== undefined || column.json !== undefined || column.element !== undefined\n || column.transforms !== undefined;\n}\n\n/**\n * The columns a schema lists in the table's own pass, in physical order: every\n * column but the plain foreign keys of `belongsTo` relations, which\n * {@link emitRelationProperties} emits after them, in relation order.\n */\nfunction ownColumns(table: TableDescriptor): ColumnDescriptor[] {\n return table.columns.filter(column => column.foreignKeyOf === undefined || isExplicitForeignKey(column));\n}\n\n/**\n * Build the component schema for a table (output / read shape).\n *\n * Every column except the ones {@link isDocumented} rules out, plus the\n * foreign keys and relations {@link emitRelationProperties} adds.\n *\n * @param lookup any table's descriptor by slug, for the type of a foreign key.\n */\nexport function buildTableSchema(\n table: TableDescriptor,\n registeredSchemas: ReadonlySet<string>,\n lookup: TableLookup\n): Record<string, unknown> {\n const keyColumn = keyColumnOf(table);\n const idKey = keyColumn?.key ?? \"id\";\n const properties: Record<string, unknown> = {\n [idKey]: { ...idSchemaFor(table), description: \"Unique identifier\" }\n };\n const required: string[] = [idKey];\n const excluded = excludedApiKeys(table, \"read\", lookup);\n const emitted = new Set<string>(excluded);\n emitted.add(idKey);\n\n for (const column of ownColumns(table)) {\n if (!isDocumented(column)) continue;\n if (column === keyColumn && isImplicitIdColumn(table, column)) continue;\n\n properties[column.key] = columnSchema(column);\n emitted.add(column.key);\n\n if (!column.nullable && !column.primaryKey) required.push(column.key);\n }\n\n emitRelationProperties(table, properties, required, emitted, registeredSchemas, lookup);\n annotateTenantField(table, properties, \"read\");\n\n return {\n type: \"object\",\n required: required.length > 0 ? required : undefined,\n properties\n };\n}\n\n/**\n * Mark the tenant column, on whichever schema is being built.\n *\n * A vendor extension for the same reason `x-rebase-access` is one: OpenAPI has\n * no keyword for \"the server fills this in from who you are, and refuses a\n * value that is not yours\". `readOnly` is the closest and it is wrong — the\n * column *is* writable, by a caller sending their own tenant, and a bypass role\n * may send any.\n */\nfunction annotateTenantField(\n table: TableDescriptor,\n properties: Record<string, unknown>,\n direction: \"read\" | \"write\"\n): void {\n const tenant = tenantOf(table);\n if (!tenant) return;\n const schema = properties[tenant.field];\n if (!schema || typeof schema !== \"object\") return;\n\n const existing = \"description\" in schema ? schema.description : undefined;\n const sentence = direction === \"write\"\n ? \"The tenant this row belongs to. Omit it and the server stamps the tenant you are calling as; \" +\n \"send another tenant's and the write is refused with `TENANT_MISMATCH`. It cannot be changed \" +\n \"on an update (`TENANT_IMMUTABLE`).\"\n : \"The tenant this row belongs to. Rows of other tenants are not returned at all.\";\n\n properties[tenant.field] = {\n ...schema,\n description: typeof existing === \"string\" && existing ? `${existing} — ${sentence}` : sentence,\n \"x-rebase-tenant\": true\n };\n}\n\n/**\n * The PATCH/PUT operation for `/data/{slug}/{id}`.\n *\n * Split out because both verbs serve it and they must not drift: the update\n * body is a **partial**, and describing it with the create schema was the bug\n * this replaces. `<Name>Input` marks every `validation.required` property as\n * required — correct for POST, wrong for an update, where omitting a field\n * means \"leave it alone\" rather than \"I forgot it\". A client generated from\n * that spec demanded fields the server does not, and a spec-validating gateway\n * would have rejected partial updates the server accepts.\n */\nfunction updateOperation(\n collection: DocumentedTable,\n schemaName: string,\n requireAuth: boolean,\n shared: {\n ifMatchHeader: Record<string, unknown>;\n preferHeader: Record<string, unknown>;\n preconditionFailed: Record<string, unknown>;\n minimalResponse: Record<string, unknown>;\n }\n): Record<string, unknown> {\n return {\n tags: [collection.name],\n summary: `Update ${collection.singularName || collection.name}`,\n description:\n \"Partial update: only the properties present in the body are written; the rest are left \" +\n \"unchanged.\\n\\n\" +\n \"A property's value may instead be a field operation — `{ \\\"views\\\": { \\\"$inc\\\": 1 } }`, \" +\n \"`{ \\\"tags\\\": { \\\"$push\\\": \\\"new\\\" } }`, `{ \\\"tags\\\": { \\\"$pull\\\": \\\"old\\\" } }`, \" +\n \"`{ \\\"meta\\\": { \\\"$merge\\\": { \\\"seen\\\": true } } }` — which is applied inside the \" +\n \"statement holding the row lock. That is the difference between a counter that is correct \" +\n \"under concurrency and one that silently loses increments, because expressing the same \" +\n \"change as a value means reading it first. `$inc` needs a `number` property, `$push`/`$pull` \" +\n \"an `array`, `$merge` a `map`; anything else is a 400. Pushed elements and merged keys answer \" +\n \"to the property's own rules, as a value would. See the `FieldOperation` schema.\",\n operationId: `update${schemaName}`,\n parameters: [\n { name: \"id\", in: \"path\", required: true, schema: { type: \"string\" }, description: \"Entity ID\" },\n shared.ifMatchHeader,\n shared.preferHeader,\n {\n name: \"Idempotency-Key\",\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description:\n \"Names this update so a retry replays its answer instead of applying the edit \" +\n \"again. A PATCH is not naturally idempotent — a field operation emphatically is \" +\n \"not — so a retry after a lost response applies it twice.\"\n }\n ],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${schemaName}Update` }\n }\n }\n },\n responses: {\n 200: {\n description: \"Updated entity\",\n headers: {\n ETag: {\n schema: { type: \"string\" },\n description:\n \"The version this write produced — the tag a `GET` of the row now answers. Send \" +\n \"it as `If-Match` on the next write to chain conditional edits without reading \" +\n \"the row back. Absent on an answer replayed from an `Idempotency-Key`.\"\n }\n },\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${schemaName}` }\n }\n }\n },\n 404: {\n description: \"Entity not found\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 409: {\n description: \"A request with the same Idempotency-Key is still in flight\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 422: {\n description: \"The Idempotency-Key was already used for a different request\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n ...shared.preconditionFailed,\n ...shared.minimalResponse,\n ...errorResponses(requireAuth)\n }\n };\n}\n\n/**\n * The update body: the create schema with `required` dropped.\n *\n * Derived rather than rebuilt so the two cannot describe different columns —\n * the only difference between creating and updating is which columns you must\n * supply, and that is exactly the one thing removed here.\n */\nfunction buildTableUpdateSchema(table: TableDescriptor, lookup: TableLookup): Record<string, unknown> {\n const { required: _required, ...rest } = buildTableInputSchema(table, lookup);\n return rest;\n}\n\n/** Whether the database (or the server) fills a column a create leaves out: a non-literal default, or generation. */\nfunction databaseFills(column: ColumnDescriptor): boolean {\n const fill = column.default?.kind;\n return fill === \"database\" || fill === \"sql\" || fill === \"random-uuid\" || fill === \"identity\" || column.generated !== undefined;\n}\n\n/**\n * Build an input schema (for POST) — leaves out what the server fills.\n *\n * Private, read-only and generated columns are left out too, and the server\n * agrees: a write naming one is refused (`write-validation.ts`).\n *\n * @param lookup any table's descriptor by slug, for the type of a foreign key.\n */\nexport function buildTableInputSchema(table: TableDescriptor, lookup: TableLookup): Record<string, unknown> {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // The write half, not the read half: a column readable by nobody but\n // writable by an `admin` belongs in the input body and not in the row.\n const excluded = excludedApiKeys(table, \"write\");\n const emitted = new Set<string>(excluded);\n const idKey = keyColumnOf(table)?.key ?? \"id\";\n\n for (const column of ownColumns(table)) {\n if (!isDocumented(column, \"write\")) continue;\n\n // A time the server stamps is not the caller's to send.\n if (column.stamp?.value === \"now\") continue;\n\n // A key the database generates.\n if (column.primaryKey && (column.default?.kind === \"random-uuid\" || column.default?.kind === \"identity\" || column.default?.kind === \"sql\")) continue;\n\n properties[column.key] = columnSchema(column);\n emitted.add(column.key);\n\n // A column the database fills may be left out of a create.\n if (!column.nullable && !column.primaryKey && !databaseFills(column)) {\n required.push(column.key);\n }\n }\n\n // Allow an explicit key on create (optional), typed from the declared key.\n if (!emitted.has(idKey)) {\n properties[idKey] = {\n ...idSchemaFor(table),\n description: \"Optional: client-assigned ID. If omitted, the server generates one.\"\n };\n emitted.add(idKey);\n }\n\n // Every relation a write may set, as the generated SDK's `Insert` types\n // them. See `emitWritableRelations`.\n emitWritableRelations(table, properties, emitted, lookup);\n annotateTenantField(table, properties, \"write\");\n\n // The tenant column is never required on input: the server fills it.\n const tenantField = tenantOf(table)?.field;\n const requiredOnInput = tenantField ? required.filter(key => key !== tenantField) : required;\n\n return {\n type: \"object\",\n required: requiredOnInput.length > 0 ? requiredOnInput : undefined,\n properties\n };\n}\n\n/**\n * The writable half of a table's relations — the same set the SDK generator's\n * `emitWritableRelations` types on `Insert`, kind for kind:\n *\n * - a `belongsTo`, under both spellings the server accepts: the foreign key\n * (`authorId`) and the relation (`author`);\n * - a `hasOne`, and a single-hop to-one `via`, under the relation: the target's\n * id, or `null` to unlink;\n * - a to-many membership — `hasMany`, `manyToMany`, and a single-hop to-many\n * `via` — under the relation's name: a list of target ids or `{ id }`\n * objects, a `manyToMany`'s carrying a `_pivot` of its link columns.\n *\n * None is listed in `required`: a belongsTo's two keys are alternatives.\n */\nfunction emitWritableRelations(\n table: TableDescriptor,\n properties: Record<string, unknown>,\n emitted: Set<string>,\n lookup: TableLookup\n): void {\n const emit = (key: string, schema: Record<string, unknown>): void => {\n if (emitted.has(key)) return;\n properties[key] = schema;\n emitted.add(key);\n };\n const belongsTo = (relation: RelationDescriptor): Record<string, unknown> => ({\n ...idSchemaFor(lookup(relation.target)),\n description: `The \\`${relation.target}\\` row this belongs to.`\n });\n\n for (const relation of table.relations) {\n if (relation.kind === \"belongsTo\") emit(relation.localField, belongsTo(relation));\n }\n\n for (const relation of table.relations) {\n if (relation.kind === \"belongsTo\") {\n emit(relation.name, belongsTo(relation));\n } else if (relation.kind === \"hasOne\" || (relation.kind === \"via\" && relation.cardinality === \"one\" && relation.writable)) {\n emit(relation.name, {\n ...idSchemaFor(lookup(relation.target)),\n nullable: true,\n description: `The \\`${relation.target}\\` row to link to this one; \\`null\\` unlinks it.`\n });\n }\n }\n\n for (const relation of table.relations) {\n if (relation.cardinality !== \"many\") continue;\n if (relation.kind === \"via\" && !relation.writable) continue;\n const id = idSchemaFor(lookup(relation.target));\n const pivotColumns = relation.kind === \"manyToMany\" ? relation.through.pivot : [];\n const pivot = pivotColumns.length > 0\n ? {\n _pivot: {\n type: \"object\",\n properties: Object.fromEntries(pivotColumns.map(column => [column.key, columnSchema(column)]))\n }\n }\n : {};\n emit(relation.name, {\n type: \"array\",\n description: `The \\`${relation.target}\\` rows linked to this one — the whole set, replacing the current links.`,\n items: { oneOf: [id, { type: \"object\", required: [\"id\"], properties: { id, ...pivot } }] }\n });\n }\n}\n\n/**\n * A column as an OpenAPI 3.0 schema object, with its access rules annotated.\n */\nfunction columnSchema(column: ColumnDescriptor): Record<string, unknown> {\n const schema = columnTypeSchema(column);\n const access = documentedAccess(column);\n const annotation = accessAnnotation(access);\n if (!annotation) return schema;\n\n const sentence = accessDescription(access);\n return {\n ...schema,\n ...(sentence\n ? { description: schema.description ? `${schema.description} — ${sentence}` : sentence }\n : {}),\n \"x-rebase-access\": annotation\n };\n}\n\n/** A text value's rules as JSON Schema keywords: lengths, pattern, format, closed set. */\nfunction textSchema(\n base: Record<string, unknown>,\n rules: { validate?: ColumnValidation; oneOf?: readonly (string | number)[]; maxLength?: number; storage?: ColumnStorage }\n): Record<string, unknown> {\n base.type = \"string\";\n if (rules.oneOf && rules.oneOf.length > 0) base.enum = [...rules.oneOf];\n const validate = rules.validate;\n if (typeof validate?.min === \"number\") base.minLength = validate.min;\n if (rules.maxLength !== undefined) base.maxLength = rules.maxLength;\n if (validate?.length !== undefined) {\n base.minLength = validate.length;\n base.maxLength = validate.length;\n }\n const pattern = jsonSchemaPattern(validate);\n if (pattern !== undefined) base.pattern = pattern;\n if (validate?.email) base.format = \"email\";\n if (validate?.url) base.format = \"uri\";\n if (rules.storage) base.format = \"uri\";\n return base;\n}\n\n/** A number's rules as JSON Schema keywords. */\nfunction numberSchema(\n base: Record<string, unknown>,\n rules: { validate?: ColumnValidation; oneOf?: readonly (string | number)[]; integer: boolean }\n): Record<string, unknown> {\n base.type = rules.integer ? \"integer\" : \"number\";\n if (rules.oneOf && rules.oneOf.length > 0) base.enum = [...rules.oneOf];\n const validate = rules.validate;\n if (typeof validate?.min === \"number\") base.minimum = validate.min;\n if (typeof validate?.max === \"number\") base.maximum = validate.max;\n if (validate?.moreThan !== undefined) {\n base.minimum = validate.moreThan;\n base.exclusiveMinimum = true;\n }\n if (validate?.lessThan !== undefined) {\n base.maximum = validate.lessThan;\n base.exclusiveMaximum = true;\n }\n return base;\n}\n\n/** A list's rules as JSON Schema keywords. */\nfunction listRules(base: Record<string, unknown>, validate: ColumnValidation | undefined): Record<string, unknown> {\n if (validate?.minItems !== undefined) base.minItems = validate.minItems;\n if (validate?.maxItems !== undefined) base.maxItems = validate.maxItems;\n if (validate?.uniqueItems) base.uniqueItems = true;\n return base;\n}\n\n/** A point on Earth. */\nfunction geopointSchema(base: Record<string, unknown>): Record<string, unknown> {\n base.type = \"object\";\n base.properties = { latitude: { type: \"number\" }, longitude: { type: \"number\" } };\n base.required = [\"latitude\", \"longitude\"];\n return base;\n}\n\n/** A time the server stamps: read-only, and said so. */\nfunction stampedSchema(base: Record<string, unknown>, on: \"create\" | \"update\"): Record<string, unknown> {\n base.readOnly = true;\n base.description = (base.description || \"\") + (on === \"create\" ? \" (Auto-set on creation)\" : \" (Auto-updated)\");\n return base;\n}\n\n/** The items of a native array column. */\nfunction elementSchema(column: ColumnDescriptor, of: ColumnType): Record<string, unknown> {\n const element = column.element;\n const base: Record<string, unknown> = {};\n if (isTextColumnType(of) || of.kind === \"uuid\" || of.kind === \"enum\") {\n const max = element?.validate?.max;\n return textSchema(base, {\n validate: element?.validate,\n oneOf: element?.oneOf ?? (of.kind === \"enum\" ? of.values : undefined),\n maxLength: typeof max === \"number\" ? max : undefined,\n storage: element?.storage ?? column.storage\n });\n }\n if (of.kind === \"boolean\") {\n base.type = \"boolean\";\n return base;\n }\n if (isTemporalColumnType(of)) {\n base.type = \"string\";\n base.format = \"date-time\";\n return base;\n }\n return numberSchema(base, { validate: element?.validate, oneOf: element?.oneOf, integer: element?.validate?.integer === true });\n}\n\n/** One typed block of a `json.oneOf()`. */\nfunction variantSchema(node: Extract<JsonShape, { kind: \"oneOf\" }>, name: string, variant: JsonShape): Record<string, unknown> {\n return {\n type: \"object\",\n properties: {\n [node.typeField]: { type: \"string\", enum: [name] },\n [node.valueField]: jsonNodeSchema(variant)\n },\n required: [node.typeField, node.valueField]\n };\n}\n\n/** A node of a JSON document's shape. */\nfunction jsonNodeSchema(node: JsonShape, listValidate?: ColumnValidation): Record<string, unknown> {\n const base: Record<string, unknown> = {};\n if (node.description !== undefined) base.description = node.description;\n switch (node.kind) {\n case \"string\": {\n const max = node.validate?.max;\n return textSchema(base, { validate: node.validate, oneOf: node.oneOf, maxLength: typeof max === \"number\" ? max : undefined, storage: node.storage });\n }\n case \"number\":\n return numberSchema(base, { validate: node.validate, oneOf: node.oneOf, integer: node.validate?.integer === true });\n case \"boolean\":\n base.type = \"boolean\";\n return base;\n case \"date\":\n base.type = \"string\";\n base.format = \"date-time\";\n return node.stamp ? stampedSchema(base, node.stamp) : base;\n case \"geopoint\":\n return geopointSchema(base);\n case \"object\": {\n base.type = \"object\";\n const fields = Object.entries(node.fields);\n if (fields.length > 0) {\n base.properties = Object.fromEntries(fields.map(([key, field]) => [key, jsonNodeSchema(field)]));\n const required = fields.filter(([, field]) => field.required).map(([key]) => key);\n if (required.length > 0) base.required = required;\n } else if (node.additional) {\n base.additionalProperties = true;\n }\n return base;\n }\n case \"array\": {\n base.type = \"array\";\n const item = node.of;\n base.items = item.kind === \"oneOf\"\n ? { oneOf: Object.entries(item.variants).map(([name, variant]) => variantSchema(item, name, variant)) }\n : jsonNodeSchema(item);\n return listRules(base, { ...node.validate, ...listValidate });\n }\n case \"oneOf\":\n base.oneOf = Object.entries(node.variants).map(([name, variant]) => variantSchema(node, name, variant));\n return base;\n case \"unknown\":\n return base;\n }\n}\n\n/** The JSON Schema a column's *type* compiles to, before any access annotation. */\nfunction columnTypeSchema(column: ColumnDescriptor): Record<string, unknown> {\n const base: Record<string, unknown> = {};\n if (column.description !== undefined) base.description = column.description;\n if (column.semantic === \"geopoint\") return geopointSchema(base);\n\n const type = column.type;\n switch (type.kind) {\n case \"text\":\n case \"varchar\":\n case \"char\":\n case \"uuid\":\n case \"enum\":\n return textSchema(base, {\n validate: column.validate,\n oneOf: type.kind === \"enum\" ? type.values : column.oneOf,\n maxLength: textMaxLength(column),\n storage: column.storage\n });\n case \"smallint\":\n case \"integer\":\n case \"bigint\":\n case \"smallserial\":\n case \"serial\":\n case \"bigserial\":\n case \"real\":\n case \"doublePrecision\":\n case \"numeric\":\n // A key is an integer however it is declared, as are the integer\n // kinds the API has always called integers.\n return numberSchema(base, {\n validate: column.validate,\n oneOf: column.oneOf,\n integer: column.validate?.integer === true || column.primaryKey === true\n || type.kind === \"integer\" || type.kind === \"bigint\" || type.kind === \"serial\" || type.kind === \"bigserial\"\n });\n case \"boolean\":\n base.type = \"boolean\";\n return base;\n case \"timestamptz\":\n case \"date\":\n case \"time\":\n base.type = \"string\";\n base.format = \"date-time\";\n return column.stamp?.value === \"now\" ? stampedSchema(base, column.stamp.on) : base;\n case \"json\":\n case \"jsonb\": {\n const shape = column.json;\n if (shape === undefined || shape.kind === \"unknown\") {\n base.type = \"object\";\n return base;\n }\n const schema = jsonNodeSchema(shape, shape.kind === \"array\" ? column.validate : undefined);\n return base.description !== undefined ? { ...schema, description: base.description } : schema;\n }\n case \"vector\":\n base.type = \"array\";\n base.items = { type: \"number\" };\n base.description = (base.description || \"\") + ` (Vector(${type.dimensions}))`;\n return base;\n case \"bytea\":\n base.type = \"string\";\n base.description = (base.description || \"\") + \" (Binary/Base64)\";\n return base;\n case \"array\":\n base.type = \"array\";\n base.items = elementSchema(column, type.of);\n return listRules(base, column.validate);\n case \"other\":\n if (/\\]\\s*$/.test(type.sqlType)) {\n base.type = \"array\";\n base.items = {};\n return base;\n }\n base.type = \"string\";\n return base;\n }\n}\n\n/**\n * Build PostgREST-style filter parameters for a table.\n * These are additional query parameters like `?status=eq.active&price=gte.100`.\n *\n * Private columns are not offered: a filter on a column no response can\n * contain answers questions about the value one row at a time. A plain\n * foreign key is filterable and is still not offered here; JSON documents,\n * lists and points have no single value to compare.\n */\nfunction buildFilterParameters(\n table: TableDescriptor,\n reservedNames: ReadonlySet<string> = new Set()\n): Array<Record<string, unknown>> {\n const params: Array<Record<string, unknown>> = [];\n\n for (const column of ownColumns(table)) {\n if (!isDocumented(column)) continue;\n const kind = column.type.kind;\n if (column.semantic === \"geopoint\" || kind === \"json\" || kind === \"jsonb\" || kind === \"array\") continue;\n if (column.type.kind === \"other\" && /\\]\\s*$/.test(column.type.sqlType)) continue;\n // A column whose name a list parameter already owns is unfilterable\n // over the wire — see `reservedParameterNames`.\n if (reservedNames.has(column.key)) continue;\n\n const text = isTextColumnType(column.type) || kind === \"uuid\" || kind === \"enum\" || kind === \"other\";\n params.push({\n name: column.key,\n in: \"query\",\n required: false,\n schema: { type: \"string\" },\n description:\n `Filter by \\`${column.key}\\`. Supports PostgREST operators: ` +\n \"`eq.value`, `neq.value`, `gt.value`, `gte.value`, `lt.value`, `lte.value`, \" +\n \"`in.(a,b,c)`, `nin.(a,b,c)`, `cs.value` (array-contains), `csa.(a,b)` (array-contains-any), \" +\n \"`csall.(a,b)` (array-contains-all), `cd.(a,b)` (array-contained-by). \" +\n \"Plain values imply equality.\",\n example: text ? \"eq.active\" : isNumericColumnType(column.type) ? \"gte.100\" : undefined\n });\n }\n\n return params;\n}\n\n/**\n * A `POST …/query` operation: the listing whose `parameters` are given, with\n * its query parameters moved into a JSON body.\n *\n * Built from the `GET`'s own parameter list, so the body documents exactly\n * what the route accepts — it turns the body back into those parameters and\n * runs the `GET`'s parser (`query-body.ts`). A filter parameter takes a list\n * where the URL would repeat it, and the four parameters whose URL value is\n * JSON take the JSON value itself.\n */\nfunction queryOperation(operation: {\n tags: string[];\n summary: string;\n /** What the operation answers; the listing's description when unset. */\n description?: string;\n operationId: string;\n parameters: Array<Record<string, unknown>>;\n responses: Record<string, unknown>;\n /** The listing's own parameter names; every other query parameter is a per-field filter. */\n reserved: ReadonlySet<string>;\n}): Record<string, unknown> {\n const jsonValued: Record<string, Record<string, unknown>> = {\n where: { oneOf: [{ type: \"object\", additionalProperties: true }, { type: \"string\" }] },\n include: { oneOf: [{ type: \"object\", additionalProperties: true }, { type: \"string\" }] },\n orderBy: { oneOf: [{ type: \"array\", items: {} }, { type: \"string\" }] },\n vector: { oneOf: [{ type: \"array\", items: { type: \"number\" } }, { type: \"string\" }] }\n };\n const properties: Record<string, unknown> = {};\n for (const parameter of operation.parameters) {\n if (parameter.in !== \"query\") continue;\n const name = String(parameter.name);\n const schema = parameter.schema as Record<string, unknown>;\n const isFilter = !operation.reserved.has(name);\n properties[name] = {\n ...(jsonValued[name]\n ?? (isFilter ? { oneOf: [schema, { type: \"array\", items: schema }] } : schema)),\n ...(parameter.description ? { description: parameter.description } : {})\n };\n }\n return {\n tags: operation.tags,\n summary: operation.summary,\n description: operation.description ??\n \"The listing `GET` answers, with its query parameters in a JSON body instead of the URL: \" +\n \"the same filters, page, count, cursor and includes, the same row-level security, and the \" +\n \"same errors. It reads and never writes, so a credential needs `data:read` for it. Use it \" +\n \"when the URL would not fit: a vector search's embedding is a JSON array in `vector`, and \" +\n \"768 dimensions of it is 17 KB of URL, past what Node and most proxies accept. A parameter \" +\n \"also on the URL is a 400 INVALID_QUERY_BODY.\",\n operationId: operation.operationId,\n parameters: operation.parameters.filter(parameter => parameter.in !== \"query\"),\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: { type: \"object\", properties }\n }\n }\n },\n responses: operation.responses\n };\n}\n\n/**\n * Standard error responses included on every endpoint.\n */\nfunction errorResponses(requireAuth: boolean): Record<string, unknown> {\n const responses: Record<string, unknown> = {\n 400: {\n description: \"Bad request\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n },\n 500: {\n description: \"Internal server error\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n }\n };\n\n if (requireAuth) {\n responses[401] = {\n description: \"Authentication required or invalid token\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n };\n responses[403] = {\n description: \"Insufficient permissions\",\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorResponse\" } } }\n };\n }\n\n return responses;\n}\n\n/**\n * Prefix a noun with \"a\" or \"an\" based on its leading sound.\n */\nfunction withIndefiniteArticle(noun: string): string {\n return `${/^[aeiou]/i.test(noun) ? \"an\" : \"a\"} ${noun}`;\n}\n\n/**\n * The component-schema name for a collection — and the stem of every\n * `operationId` and `$ref` that mentions it.\n *\n * `toPascalCase` keeps ASCII letters and digits and nothing else, so a name\n * written in a script that has none of them — a Cyrillic or Japanese\n * `singularName`, which the docs' six locales make ordinary rather than exotic\n * — reduced to the empty string. The schema was then stored under `\"\"` and\n * every reference to it read `#/components/schemas/`, an unresolvable pointer:\n * Swagger UI renders the model empty and a strict generator fails outright. So\n * fall through the names until one survives, and keep a constant as the floor.\n *\n * Two collections whose names PascalCase identically still share one component;\n * that needs a disambiguation rule, not a fallback.\n */\nfunction schemaNameFor(collection: Pick<DocumentedTable, \"singularName\" | \"name\" | \"slug\">): string {\n return toPascalCase(collection.singularName || \"\")\n || toPascalCase(collection.name || \"\")\n || toPascalCase(collection.slug || \"\")\n || \"Collection\";\n}\n\n/**\n * Convert a string to PascalCase for schema names.\n */\nfunction toPascalCase(str: string): string {\n return str\n .replace(/[^a-zA-Z0-9]+/g, \" \")\n .split(\" \")\n .filter(Boolean)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\"\");\n}\n\n/**\n * A text column's `validate({ matches })` as a JSON Schema `pattern`, or\n * `undefined` when it cannot be stated as one.\n *\n * A pattern is a regex's source and nothing else: no delimiting slashes and no\n * flags. A flag that changes what the source matches (`i`, `m`, `s`) has no\n * JSON Schema spelling; the source alone would refuse values the server\n * accepts, so no pattern is stated.\n */\nfunction jsonSchemaPattern(validate: ColumnValidation | undefined): string | undefined {\n const regExp = validationPattern(validate);\n if (!regExp) return undefined;\n return /[ims]/.test(regExp.flags) ? undefined : regExp.source;\n}\n"],"mappings":";;;;;;;;;;;;;;AAUA,SAAS,cAAc,OAAO;CAC7B,IAAI,CAAC,OAAO,OAAO,KAAK;CACxB,MAAM,YAAY,MAAM,MAAM,qBAAqB;CACnD,IAAI,WAAW,OAAO,IAAI,OAAO,UAAU,IAAI,UAAU,MAAM,EAAE;MAC5D,OAAO,IAAI,OAAO,OAAO,EAAE;AACjC;;;;;;;;;;;;;;;;;;;;;ACMA,IAAI,cAAc;CACjB,IAAI;CACJ,KAAK;CACL,KAAK;CACL,MAAM;CACN,MAAM;CACN,KAAK;CACL,IAAI;AACL;;;;;;;;;AASA,SAAS,oBAAoB,YAAY;CACxC,OAAO,mBAAmB,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,QAAQ,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,SAAS,YAAY,KAAK,YAAY,MAAM,IAAI,CAAC,CAAC,KAAK,GAAG;AACnJ;;;;;;;;;;;AAWA,SAAS,cAAc,OAAO;CAC7B,MAAM,QAAQ,MAAM,MAAM,GAAG;CAC7B,MAAM,OAAO,MAAM,MAAM,SAAS;CAClC,IAAI,CAAC,QAAQ,eAAe,KAAK,IAAI,GAAG,OAAO;CAC/C,MAAM,SAAS,SAAS,IAAI;CAC5B,IAAI,OAAO,WAAW,GAAG,OAAO;CAChC,MAAM,QAAQ,KAAK,OAAO,KAAK,EAAE,CAAC,YAAY,IAAI,OAAO,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,OAAO,MAAM,CAAC,IAAI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