@lumibase/sdk 2.1.0 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -335,6 +335,29 @@ var AudienceClient = class {
335
335
  }
336
336
  };
337
337
 
338
+ // src/realtime/retain.ts
339
+ var holders = /* @__PURE__ */ new WeakMap();
340
+ function realtimeHolders(client) {
341
+ return holders.get(client) ?? 0;
342
+ }
343
+ function retainRealtime(client) {
344
+ const count = realtimeHolders(client);
345
+ holders.set(client, count + 1);
346
+ if (count === 0) client.connect();
347
+ let released = false;
348
+ return () => {
349
+ if (released) return;
350
+ released = true;
351
+ const next = realtimeHolders(client) - 1;
352
+ if (next <= 0) {
353
+ holders.delete(client);
354
+ client.disconnect();
355
+ } else {
356
+ holders.set(client, next);
357
+ }
358
+ };
359
+ }
360
+
338
361
  // src/realtime/index.ts
339
362
  var RealtimeClient = class {
340
363
  constructor(opts) {
@@ -537,6 +560,10 @@ var RealtimeClient = class {
537
560
  };
538
561
 
539
562
  // src/rest/legacy.ts
563
+ function ifMatchInit(options) {
564
+ if (options?.ifMatch === void 0) return {};
565
+ return { headers: { "if-match": `"${options.ifMatch}"` } };
566
+ }
540
567
  function withQuery(path, params = {}) {
541
568
  const qs = new URLSearchParams();
542
569
  for (const [key, value] of Object.entries(params)) {
@@ -657,7 +684,19 @@ function legacyRest() {
657
684
  setFormLayout: (name, layout) => client.rawRequest(
658
685
  `/api/v1/collections/${name}/form-layout`,
659
686
  { method: "PUT", body: JSON.stringify({ layout }) }
660
- )
687
+ ),
688
+ /**
689
+ * Expression index advice for filtering on a JSON path (#729). `cast`
690
+ * defaults to the declared type of a top-level field; nested paths
691
+ * must name it. Read-only: the DDL is returned, never executed.
692
+ */
693
+ indexAdvice: (name, path, cast) => {
694
+ const params = new URLSearchParams({ path });
695
+ if (cast) params.set("cast", cast);
696
+ return client.rawRequest(
697
+ `/api/v1/collections/${encodeURIComponent(name)}/index-advice?${params.toString()}`
698
+ );
699
+ }
661
700
  };
662
701
  function items(name) {
663
702
  function buildQuery(params) {
@@ -670,6 +709,8 @@ function legacyRest() {
670
709
  if (params.offset !== void 0)
671
710
  qs.set("offset", String(params.offset));
672
711
  if (params.status) qs.set("status", params.status);
712
+ if (params.publicationState) qs.set("publicationState", params.publicationState);
713
+ if (params.modifiedSincePublish) qs.set("modifiedSincePublish", "true");
673
714
  const s = qs.toString();
674
715
  return s ? `?${s}` : "";
675
716
  }
@@ -688,12 +729,14 @@ function legacyRest() {
688
729
  method: "POST",
689
730
  body: JSON.stringify(input)
690
731
  }),
691
- patch: (id, input) => client.rawRequest(`${base}/${id}`, {
732
+ patch: (id, input, options) => client.rawRequest(`${base}/${id}`, {
692
733
  method: "PATCH",
693
- body: JSON.stringify(input)
734
+ body: JSON.stringify(input),
735
+ ...ifMatchInit(options)
694
736
  }),
695
- replace: (id, input) => client.rawRequest(`${base}/${id}`, {
737
+ replace: (id, input, options) => client.rawRequest(`${base}/${id}`, {
696
738
  method: "PUT",
739
+ ...ifMatchInit(options),
697
740
  body: JSON.stringify(input)
698
741
  }),
699
742
  delete: (id) => client.rawRequest(`${base}/${id}`, { method: "DELETE" }),
@@ -718,6 +761,30 @@ function legacyRest() {
718
761
  method: "POST",
719
762
  body: JSON.stringify({ op, items: payload })
720
763
  }),
764
+ /**
765
+ * Save-as-copy (#689): a draft copy with unique fields suffixed
766
+ * (`-copy`, `-copy-2`, …). Goes through the normal create path.
767
+ */
768
+ duplicate: (id, options = {}) => client.rawRequest(`${base}/${encodeURIComponent(id)}/duplicate`, {
769
+ method: "POST",
770
+ body: JSON.stringify(options)
771
+ }),
772
+ /**
773
+ * Manual ordering (#690) on a `meta.manualSort` collection: place `id`
774
+ * right after `after` (null = first) or right before `before`.
775
+ */
776
+ reorder: (id, target) => client.rawRequest(`${base}/${encodeURIComponent(id)}/reorder`, {
777
+ method: "POST",
778
+ body: JSON.stringify(target)
779
+ }),
780
+ /**
781
+ * Patch without recording a revision (#693) — for autosave and
782
+ * machine writes. Agent-authored writes keep their revision anyway.
783
+ */
784
+ patchWithoutRevision: (id, input) => client.rawRequest(`${base}/${id}?saveRevision=false`, {
785
+ method: "PATCH",
786
+ body: JSON.stringify(input)
787
+ }),
721
788
  /**
722
789
  * Hierarchical collections (#749) on a `meta.tree.enabled` collection.
723
790
  * Reads apply the caller's row rules; the anchor must be readable.
@@ -1002,10 +1069,66 @@ function legacyRest() {
1002
1069
  method: "PATCH",
1003
1070
  body: JSON.stringify(patch)
1004
1071
  }),
1005
- delete: (id) => client.rawRequest(`/api/v1/files/folders/${id}`, { method: "DELETE" })
1072
+ delete: (id) => client.rawRequest(`/api/v1/files/folders/${id}`, { method: "DELETE" }),
1073
+ /** Nested folder tree with id paths (`/a/b/`) and name paths (#701). */
1074
+ tree: () => client.rawRequest("/api/v1/files/folders/tree")
1006
1075
  };
1007
1076
  const files = {
1008
- list: () => client.rawRequest("/api/v1/files"),
1077
+ /**
1078
+ * List / filter the library. Without a query: the first 1000 files,
1079
+ * newest first. `meta` carries `{ total, limit, offset }`.
1080
+ */
1081
+ list: (query) => {
1082
+ const q = new URLSearchParams();
1083
+ if (query?.folder !== void 0) q.set("folder", query.folder);
1084
+ if (query?.subfolders) q.set("subfolders", "true");
1085
+ if (query?.search) q.set("search", query.search);
1086
+ if (query?.mime?.length) q.set("mime", query.mime.join(","));
1087
+ if (query?.ids?.length) q.set("ids", query.ids.join(","));
1088
+ if (query?.limit !== void 0) q.set("limit", String(query.limit));
1089
+ if (query?.offset !== void 0) q.set("offset", String(query.offset));
1090
+ const qs = q.toString();
1091
+ return client.rawRequest(`/api/v1/files${qs ? `?${qs}` : ""}`);
1092
+ },
1093
+ get: (id) => client.rawRequest(`/api/v1/files/${encodeURIComponent(id)}`),
1094
+ /**
1095
+ * Replace the bytes behind a file in place (#703): same id, key, folder
1096
+ * and references; `version` bumps. Pass `expectedVersion` to refuse
1097
+ * (409) when someone replaced it since you loaded it.
1098
+ */
1099
+ replaceContent: (id, body, opts) => {
1100
+ const q = opts.filename ? `?filename=${encodeURIComponent(opts.filename)}` : "";
1101
+ const headers = { "content-type": opts.mime };
1102
+ if (opts.expectedVersion !== void 0) headers["if-match"] = `"v${opts.expectedVersion}"`;
1103
+ return client.rawRequest(`/api/v1/files/${encodeURIComponent(id)}/content${q}`, {
1104
+ method: "PUT",
1105
+ body,
1106
+ headers
1107
+ });
1108
+ },
1109
+ /** URL that serves the current bytes; pass `version` for an immutable, cacheable URL. */
1110
+ contentUrl: (id, version) => `${client.url.replace(/\/$/, "")}/api/v1/files/${encodeURIComponent(id)}/content${version !== void 0 ? `?v=${version}` : ""}`,
1111
+ versions: (id) => client.rawRequest(`/api/v1/files/${encodeURIComponent(id)}/versions`),
1112
+ restoreVersion: (id, versionId) => client.rawRequest(
1113
+ `/api/v1/files/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}/restore`,
1114
+ { method: "POST" }
1115
+ ),
1116
+ /** Items and pages that reference the file (#706). */
1117
+ usage: (id) => client.rawRequest(`/api/v1/files/${encodeURIComponent(id)}/usage`),
1118
+ /** Files with the same content hash (lowercase hex SHA-256). */
1119
+ duplicates: (hash) => client.rawRequest(`/api/v1/files/duplicates?hash=${encodeURIComponent(hash)}`),
1120
+ /** Bulk move and/or merge editorial metadata (alt, title, caption, credit, tags). */
1121
+ bulk: (input) => client.rawRequest("/api/v1/files/bulk", {
1122
+ method: "POST",
1123
+ body: JSON.stringify(input)
1124
+ }),
1125
+ settings: {
1126
+ get: () => client.rawRequest("/api/v1/files/settings"),
1127
+ update: (patch) => client.rawRequest("/api/v1/files/settings", {
1128
+ method: "PUT",
1129
+ body: JSON.stringify(patch)
1130
+ })
1131
+ },
1009
1132
  create: (input) => client.rawRequest("/api/v1/files", {
1010
1133
  method: "POST",
1011
1134
  body: JSON.stringify(input)
@@ -1014,7 +1137,12 @@ function legacyRest() {
1014
1137
  method: "PATCH",
1015
1138
  body: JSON.stringify(patch)
1016
1139
  }),
1017
- delete: (id) => client.rawRequest(`/api/v1/files/${id}`, { method: "DELETE" }),
1140
+ /**
1141
+ * Safe delete (#706): a referenced file answers 409 `FILE_IN_USE` with the
1142
+ * references in `errors[0].details.usage`; repeat with `{ confirm: true }`
1143
+ * to delete anyway (unless the site's policy is `block`).
1144
+ */
1145
+ delete: (id, opts) => client.rawRequest(`/api/v1/files/${id}${opts?.confirm ? "?confirm=true" : ""}`, { method: "DELETE" }),
1018
1146
  getPresignedUrl: (filename) => client.rawRequest("/api/v1/files/presigned-url", {
1019
1147
  method: "POST",
1020
1148
  body: JSON.stringify({ filename })
@@ -1145,6 +1273,23 @@ function legacyRest() {
1145
1273
  target: { type: "api_key", id }
1146
1274
  })
1147
1275
  };
1276
+ const preview = {
1277
+ mintToken: (input) => client.rawRequest("/api/v1/preview/token", {
1278
+ method: "POST",
1279
+ body: JSON.stringify(input)
1280
+ }),
1281
+ listTokens: () => client.rawRequest("/api/v1/preview/tokens"),
1282
+ revokeToken: (id) => client.rawRequest(`/api/v1/preview/tokens/${encodeURIComponent(id)}/revoke`, {
1283
+ method: "POST"
1284
+ }),
1285
+ /** Rotation: revoke every live preview token of the site (site admin). */
1286
+ revokeAll: () => client.rawRequest("/api/v1/preview/tokens/revoke-all", { method: "POST" }),
1287
+ getSettings: () => client.rawRequest("/api/v1/preview/settings"),
1288
+ updateSettings: (input) => client.rawRequest("/api/v1/preview/settings", {
1289
+ method: "PUT",
1290
+ body: JSON.stringify(input)
1291
+ })
1292
+ };
1148
1293
  const shares = {
1149
1294
  create: (input) => client.rawRequest("/api/v1/shares", {
1150
1295
  method: "POST",
@@ -1262,6 +1407,7 @@ function legacyRest() {
1262
1407
  access,
1263
1408
  apiKeys,
1264
1409
  shares,
1410
+ preview,
1265
1411
  me,
1266
1412
  permissions,
1267
1413
  presets,
@@ -1557,7 +1703,7 @@ function readItem(collection, id, fields) {
1557
1703
  const res = await client.rawRequest(
1558
1704
  `/api/v1/items/${collection}/${id}${fields?.length ? `?fields=${fields.join(",")}` : ""}`
1559
1705
  );
1560
- return res;
1706
+ return res.data;
1561
1707
  };
1562
1708
  }
1563
1709
  function exportAccessManifest() {
@@ -1939,6 +2085,583 @@ function graphql(endpoint = "/api/v1/graphql") {
1939
2085
  };
1940
2086
  }
1941
2087
 
2088
+ // src/typegen/shared.ts
2089
+ var TRANSLATABLE_INTERFACE = "translatable-text";
2090
+ var FILE_INTERFACE = "file";
2091
+ var FILES_INTERFACE = "files";
2092
+ function fieldShape(field) {
2093
+ if (field.kind === "m2o") return { kind: "m2o" };
2094
+ if (field.kind === "o2m" || field.kind === "m2m") {
2095
+ return { kind: "to-many", target: field.target || "unknown" };
2096
+ }
2097
+ if (field.kind === "m2a") return { kind: "m2a" };
2098
+ if (field.interface === TRANSLATABLE_INTERFACE) return { kind: "localized" };
2099
+ if (field.interface === FILES_INTERFACE || field.type === "files") return { kind: "files" };
2100
+ if (field.interface === FILE_INTERFACE) return { kind: "file" };
2101
+ if (field.enum && field.enum.length > 0) return { kind: "enum", values: field.enum };
2102
+ if (field.primaryKey) return { kind: "primary-key" };
2103
+ return { kind: "scalar" };
2104
+ }
2105
+ function isOptional(field) {
2106
+ return !field.required;
2107
+ }
2108
+ function isNullable(field) {
2109
+ return !field.required || field.nullable;
2110
+ }
2111
+ function hasIntegerPrimaryKey(collection) {
2112
+ return collection?.primaryKeyType === "integer" || collection?.primaryKeyType === "bigInteger";
2113
+ }
2114
+ function relationsOf(collection) {
2115
+ return collection.relations ?? [];
2116
+ }
2117
+ function capitalize(str) {
2118
+ return str.charAt(0).toUpperCase() + str.slice(1);
2119
+ }
2120
+ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
2121
+ function propertyKey(name) {
2122
+ return IDENTIFIER.test(name) ? name : JSON.stringify(name);
2123
+ }
2124
+ function filterManifest(manifest, filters) {
2125
+ const { include, exclude } = filters;
2126
+ if (!include?.length && !exclude?.length) return manifest;
2127
+ return {
2128
+ ...manifest,
2129
+ collections: manifest.collections.filter(
2130
+ (collection) => (!include?.length || include.includes(collection.name)) && !(exclude?.length && exclude.includes(collection.name))
2131
+ )
2132
+ };
2133
+ }
2134
+
2135
+ // src/typegen/richtext.ts
2136
+ var RICHTEXT_TS_DECLARATIONS = `export type RichTextMark = 'bold' | 'italic' | 'underline' | 'strike' | 'code' | 'superscript' | 'subscript';
2137
+
2138
+ export interface RichTextRef {
2139
+ kind: 'item' | 'file';
2140
+ collection?: string;
2141
+ id: string;
2142
+ }
2143
+
2144
+ export type RichTextInline =
2145
+ | { type: 'text'; text: string; marks?: RichTextMark[] }
2146
+ | { type: 'link'; href: string; content: RichTextInline[] }
2147
+ | { type: 'ref'; ref: RichTextRef; content: RichTextInline[] }
2148
+ | { type: 'embed'; ref: RichTextRef; alt?: string }
2149
+ | { type: 'break' }
2150
+ | { type: 'footnote'; label: string };
2151
+
2152
+ export interface RichTextTableRow {
2153
+ header?: boolean;
2154
+ cells: RichTextBlock[][];
2155
+ }
2156
+
2157
+ export type RichTextBlock =
2158
+ | { type: 'paragraph'; content: RichTextInline[] }
2159
+ | { type: 'heading'; level: 1 | 2 | 3 | 4 | 5 | 6; content: RichTextInline[] }
2160
+ | { type: 'quote'; content: RichTextBlock[] }
2161
+ | { type: 'list'; ordered: boolean; start?: number; items: RichTextBlock[][] }
2162
+ | { type: 'code'; language?: string; text: string }
2163
+ | { type: 'rule' }
2164
+ | { type: 'embed'; ref: RichTextRef; alt?: string }
2165
+ | { type: 'table'; rows: RichTextTableRow[]; caption?: string; headerColumn?: boolean; align?: Array<'left' | 'center' | 'right' | null> }
2166
+ | { type: 'footnote'; label: string; content: RichTextBlock[] }
2167
+ | { type: 'custom'; name: string; data: Record<string, unknown> };
2168
+
2169
+ export interface RichTextDocument {
2170
+ type: 'doc';
2171
+ version: 1;
2172
+ content: RichTextBlock[];
2173
+ }`;
2174
+ var RICHTEXT_ZOD = "z.object({ type: z.literal('doc'), version: z.literal(1), content: z.array(z.record(z.string(), z.unknown())) })";
2175
+
2176
+ // src/typegen/zod.ts
2177
+ var DEFAULT_ZOD_IMPORT = "zod";
2178
+ function generateZod(manifest, options = {}) {
2179
+ const importSource = options.importSource ?? DEFAULT_ZOD_IMPORT;
2180
+ const byName = new Map(manifest.collections.map((collection) => [collection.name, collection]));
2181
+ const blocks = manifest.collections.map((collection) => {
2182
+ const name = capitalize(collection.name);
2183
+ const props = collection.fields.map((field) => ` ${propertyKey(field.name)}: ${fieldValidator(field, collection, byName)},`).join("\n");
2184
+ return [
2185
+ `export const ${name}Schema = z.object({`,
2186
+ props,
2187
+ "});",
2188
+ `export type ${name} = z.infer<typeof ${name}Schema>;`
2189
+ ].filter((line) => line !== "").join("\n");
2190
+ });
2191
+ const map = [
2192
+ "export const LumibaseSchemas = {",
2193
+ ...manifest.collections.map(
2194
+ (collection) => ` ${propertyKey(collection.name)}: ${capitalize(collection.name)}Schema,`
2195
+ ),
2196
+ "} as const;"
2197
+ ].join("\n");
2198
+ return [`import { z } from ${JSON.stringify(importSource)};`, ...blocks, map].join("\n\n");
2199
+ }
2200
+ function fieldValidator(field, collection, byName) {
2201
+ const shape = fieldShape(field);
2202
+ let schema;
2203
+ switch (shape.kind) {
2204
+ case "to-many": {
2205
+ const target = byName.get(shape.target);
2206
+ const id = target ? primaryKeyValidator(target) : "z.union([z.string(), z.number()])";
2207
+ return withOptional(field, `z.array(z.union([${id}, z.record(z.string(), z.unknown())]))`);
2208
+ }
2209
+ case "m2a":
2210
+ return withOptional(
2211
+ field,
2212
+ "z.array(z.object({ collection: z.string(), item: z.unknown() }))"
2213
+ );
2214
+ case "localized":
2215
+ schema = "z.record(z.string(), z.string())";
2216
+ break;
2217
+ case "file":
2218
+ schema = "z.string()";
2219
+ break;
2220
+ case "files":
2221
+ schema = "z.array(z.string())";
2222
+ break;
2223
+ case "enum":
2224
+ return wrap(field, `z.enum(${JSON.stringify(shape.values)})`);
2225
+ case "primary-key":
2226
+ return wrap(field, primaryKeyValidator(collection));
2227
+ case "m2o":
2228
+ return wrap(field, scalarValidator(field.type));
2229
+ case "scalar":
2230
+ schema = scalarValidator(field.type);
2231
+ break;
2232
+ }
2233
+ if (field.encrypted) schema = `z.union([${schema}, z.literal('***')])`;
2234
+ return wrap(field, schema);
2235
+ }
2236
+ function primaryKeyValidator(collection) {
2237
+ const type = collection.primaryKeyType ?? "nanoid";
2238
+ return type === "integer" || type === "bigInteger" ? "z.number().int()" : "z.string()";
2239
+ }
2240
+ function scalarValidator(type) {
2241
+ switch (type) {
2242
+ case "string":
2243
+ case "text":
2244
+ case "hash":
2245
+ case "csv":
2246
+ case "uuid":
2247
+ case "date":
2248
+ case "datetime":
2249
+ case "dateTime":
2250
+ case "time":
2251
+ case "timestamp":
2252
+ return "z.string()";
2253
+ case "integer":
2254
+ return "z.number().int()";
2255
+ case "bigInteger":
2256
+ case "decimal":
2257
+ case "float":
2258
+ return "z.number()";
2259
+ case "boolean":
2260
+ return "z.boolean()";
2261
+ case "geometry":
2262
+ return "z.record(z.string(), z.unknown())";
2263
+ case "richtext":
2264
+ return RICHTEXT_ZOD;
2265
+ default:
2266
+ return "z.unknown()";
2267
+ }
2268
+ }
2269
+ function wrap(field, schema) {
2270
+ return withOptional(field, isNullable(field) ? `${schema}.nullable()` : schema);
2271
+ }
2272
+ function withOptional(field, schema) {
2273
+ return isOptional(field) ? `${schema}.optional()` : schema;
2274
+ }
2275
+
2276
+ // src/typegen/graphql-sdl.ts
2277
+ function generateGraphQLSdl(manifest) {
2278
+ const collections = manifest.collections.filter((collection) => GRAPHQL_NAME.test(collection.name));
2279
+ const typeNames = new Map(collections.map((collection) => [collection.name, pascalCase(collection.name)]));
2280
+ const blocks = ["scalar JSON", "scalar DateTime"];
2281
+ for (const collection of collections) {
2282
+ blocks.push(objectType(typeNames.get(collection.name), itemFields(collection, typeNames)));
2283
+ }
2284
+ if (collections.some((c) => c.fields.some((f) => !f.system && f.type === "richtext" && !RESERVED.has(f.name) && GRAPHQL_NAME.test(f.name)))) {
2285
+ blocks.push(objectType("RichText", ["json: JSON", "html: String", "markdown: String", "text: String"]));
2286
+ }
2287
+ const query = ["_collections: [String!]!"];
2288
+ const mutation = [];
2289
+ const subscription = [];
2290
+ for (const collection of collections) {
2291
+ const name = collection.name;
2292
+ const type = typeNames.get(name);
2293
+ query.push(
2294
+ `${name}(filter: JSON, sort: [String!], limit: Int, offset: Int, status: String, publicationState: PublicationState, modifiedSincePublish: Boolean): [${type}!]!`,
2295
+ `${name}_by_id(id: ID!, publicationState: PublicationState): ${type}`
2296
+ );
2297
+ mutation.push(
2298
+ `create_${name}(data: JSON!, status: String, sort: Int): ${type}!`,
2299
+ `update_${name}(id: ID!, data: JSON, status: String, sort: Int): ${type}!`,
2300
+ `delete_${name}(id: ID!): Boolean!`
2301
+ );
2302
+ subscription.push(`${name}_events: ItemEvent!`);
2303
+ }
2304
+ blocks.push(objectType("Query", query));
2305
+ if (collections.length > 0) blocks.push("enum PublicationState {\n live\n preview\n all\n}");
2306
+ if (mutation.length > 0) blocks.push(objectType("Mutation", mutation));
2307
+ if (subscription.length > 0) {
2308
+ blocks.push(objectType("Subscription", subscription));
2309
+ blocks.push(
2310
+ objectType("ItemEvent", [
2311
+ "collection: String!",
2312
+ "action: String!",
2313
+ "itemId: ID!",
2314
+ "item: JSON"
2315
+ ])
2316
+ );
2317
+ }
2318
+ return `${blocks.join("\n\n")}
2319
+ `;
2320
+ }
2321
+ var STRUCTURAL = [
2322
+ ["id", "ID!"],
2323
+ ["status", "String"],
2324
+ ["sort", "Int"],
2325
+ ["createdAt", "DateTime"],
2326
+ ["updatedAt", "DateTime"],
2327
+ ["userCreated", "String"],
2328
+ ["userUpdated", "String"],
2329
+ ["_data", "JSON"],
2330
+ // Publication state (#687), underscored so a content field keeps its name.
2331
+ ["_firstPublishedAt", "DateTime"],
2332
+ ["_publishedAt", "DateTime"],
2333
+ ["_hasUnpublishedChanges", "Boolean"]
2334
+ ];
2335
+ var RESERVED = /* @__PURE__ */ new Set([
2336
+ "id",
2337
+ "status",
2338
+ "sort",
2339
+ "createdAt",
2340
+ "updatedAt",
2341
+ "userCreated",
2342
+ "userUpdated",
2343
+ "created_at",
2344
+ "updated_at",
2345
+ "user_created",
2346
+ "user_updated",
2347
+ "_data",
2348
+ "_firstPublishedAt",
2349
+ "_publishedAt",
2350
+ "_hasUnpublishedChanges"
2351
+ ]);
2352
+ var GRAPHQL_NAME = /^[_A-Za-z][_0-9A-Za-z]*$/;
2353
+ function itemFields(collection, typeNames) {
2354
+ const fields = new Map(STRUCTURAL);
2355
+ for (const field of collection.fields) {
2356
+ if (field.system || RESERVED.has(field.name) || !GRAPHQL_NAME.test(field.name)) continue;
2357
+ fields.set(field.name, scalarFor(field.type));
2358
+ }
2359
+ for (const relation of relationsOf(collection)) {
2360
+ const nested = relationField(collection, relation, typeNames);
2361
+ if (!nested || !GRAPHQL_NAME.test(nested.name) || fields.has(nested.name)) continue;
2362
+ fields.set(nested.name, nested.args ? `${nested.args}: ${nested.type}` : nested.type);
2363
+ }
2364
+ return [...fields].map(([name, type]) => type.startsWith("(") ? `${name}${type}` : `${name}: ${type}`);
2365
+ }
2366
+ function relationField(collection, relation, typeNames) {
2367
+ const many = relation.manyCollection ?? (relation.kind === "m2o" ? collection.name : relation.target);
2368
+ const one = relation.oneCollection ?? (relation.kind === "m2o" ? relation.target : collection.name);
2369
+ const stored = relation.relationType ?? (many === collection.name ? relation.kind : void 0);
2370
+ if (stored === "m2o" && many === collection.name) {
2371
+ const target = typeNames.get(one);
2372
+ return target ? { name: relation.alias ?? m2oAlias(relation, one), type: target } : null;
2373
+ }
2374
+ if (stored === "o2m" && one === collection.name) {
2375
+ const target = typeNames.get(many);
2376
+ return target ? { name: relation.alias ?? many, args: "(limit: Int, offset: Int)", type: `[${target}!]!` } : null;
2377
+ }
2378
+ return null;
2379
+ }
2380
+ function m2oAlias(relation, oneCollection) {
2381
+ const manyField = relation.manyField ?? relation.field;
2382
+ return manyField.endsWith("_id") ? manyField.slice(0, -3) : oneCollection;
2383
+ }
2384
+ function scalarFor(type) {
2385
+ switch (type) {
2386
+ case "boolean":
2387
+ return "Boolean";
2388
+ case "integer":
2389
+ return "Int";
2390
+ case "float":
2391
+ case "decimal":
2392
+ return "Float";
2393
+ case "bigInteger":
2394
+ return "String";
2395
+ // `datetime` is the canonical FieldType spelling; `dateTime` is legacy (#865).
2396
+ case "datetime":
2397
+ case "dateTime":
2398
+ case "date":
2399
+ case "time":
2400
+ case "timestamp":
2401
+ return "DateTime";
2402
+ case "richtext":
2403
+ return "RichText";
2404
+ case "json":
2405
+ case "csv":
2406
+ case "geometry":
2407
+ case "files":
2408
+ case "m2o":
2409
+ case "o2m":
2410
+ case "m2m":
2411
+ case "m2a":
2412
+ return "JSON";
2413
+ default:
2414
+ return "String";
2415
+ }
2416
+ }
2417
+ function pascalCase(name) {
2418
+ return name.split("_").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
2419
+ }
2420
+ function objectType(name, fields) {
2421
+ return `type ${name} {
2422
+ ${fields.map((field) => ` ${field}`).join("\n")}
2423
+ }`;
2424
+ }
2425
+
2426
+ // src/typegen/openapi.ts
2427
+ function generateOpenApi(manifest, options = {}) {
2428
+ const byName = new Map(manifest.collections.map((collection) => [collection.name, collection]));
2429
+ const bases = /* @__PURE__ */ new Map();
2430
+ const taken = /* @__PURE__ */ new Set();
2431
+ for (const collection of manifest.collections) {
2432
+ const raw = collection.name.replace(/[^a-zA-Z0-9._-]/g, "_");
2433
+ let base = raw;
2434
+ for (let n = 2; taken.has(base); n += 1) base = `${raw}_${n}`;
2435
+ taken.add(base);
2436
+ bases.set(collection.name, base);
2437
+ }
2438
+ const ctx = {
2439
+ primaryKeySchema: (name) => hasIntegerPrimaryKey(byName.get(name)) ? { type: "integer" } : { type: "string" },
2440
+ projectionRef: (name) => {
2441
+ const base = bases.get(name);
2442
+ return base ? `#/components/schemas/${base}.Projection` : null;
2443
+ }
2444
+ };
2445
+ const schemas = {
2446
+ ErrorObject: {
2447
+ type: "object",
2448
+ properties: { code: { type: "string" }, message: { type: "string" } },
2449
+ required: ["code"]
2450
+ },
2451
+ ErrorResponse: {
2452
+ type: "object",
2453
+ properties: { errors: { type: "array", items: { $ref: "#/components/schemas/ErrorObject" } } },
2454
+ required: ["errors"]
2455
+ },
2456
+ PaginationMeta: {
2457
+ type: "object",
2458
+ properties: {
2459
+ total: { type: "integer", minimum: 0, description: "Omitted when the request passed `meta=none`." },
2460
+ limit: { type: "integer", minimum: 1, maximum: 200 },
2461
+ offset: { type: "integer", minimum: 0 }
2462
+ },
2463
+ required: ["limit", "offset"]
2464
+ }
2465
+ };
2466
+ for (const collection of manifest.collections) {
2467
+ addCollectionSchemas(schemas, collection, bases.get(collection.name), ctx);
2468
+ }
2469
+ return {
2470
+ openapi: "3.1.0",
2471
+ info: {
2472
+ title: options.title ?? "LumiBase content schemas",
2473
+ version: options.version ?? `manifest-v${manifest.version}`,
2474
+ description: "Component schemas generated by `lumibase types` from the typegen manifest. For paths and a per-caller view, use the live document at /api/v1/openapi.json."
2475
+ },
2476
+ components: { schemas }
2477
+ };
2478
+ }
2479
+ var timestamp = { type: "string", format: "date-time" };
2480
+ var nullableTimestamp = { type: ["string", "null"], format: "date-time" };
2481
+ var nullableString = { type: ["string", "null"] };
2482
+ var expandedObject = {
2483
+ type: "object",
2484
+ description: "Expanded record (requested with `fields=<name>.*`)."
2485
+ };
2486
+ var fileId = { type: "string", description: "File id (`/api/v1/files/{id}`)." };
2487
+ var FIELD_TYPE_JSON_SCHEMA = {
2488
+ string: { type: "string" },
2489
+ text: { type: "string" },
2490
+ hash: { type: "string" },
2491
+ csv: { type: "string" },
2492
+ integer: { type: "integer" },
2493
+ bigInteger: { type: "integer", format: "int64" },
2494
+ decimal: { type: "number" },
2495
+ float: { type: "number" },
2496
+ boolean: { type: "boolean" },
2497
+ json: {},
2498
+ uuid: { type: "string", format: "uuid" },
2499
+ date: { type: "string", format: "date" },
2500
+ datetime: { type: "string", format: "date-time" },
2501
+ dateTime: { type: "string", format: "date-time" },
2502
+ time: { type: "string", format: "time" },
2503
+ timestamp: { type: "string", format: "date-time" },
2504
+ geometry: { type: "object", additionalProperties: true, description: "GeoJSON geometry object." },
2505
+ richtext: {
2506
+ type: "object",
2507
+ required: ["type", "version", "content"],
2508
+ properties: {
2509
+ type: { type: "string", enum: ["doc"] },
2510
+ version: { type: "integer", enum: [1] },
2511
+ content: { type: "array", items: { type: "object", additionalProperties: true } }
2512
+ },
2513
+ description: "Portable rich-text document (see the RichTextDocument type)."
2514
+ }
2515
+ };
2516
+ function withNull(schema) {
2517
+ if (Object.keys(schema).length === 0) return schema;
2518
+ const type = schema["type"];
2519
+ if (typeof type === "string" && !("enum" in schema)) return { ...schema, type: [type, "null"] };
2520
+ if (typeof type === "string" && Array.isArray(schema["enum"])) {
2521
+ return { ...schema, type: [type, "null"], enum: [...schema["enum"], null] };
2522
+ }
2523
+ return { anyOf: [schema, { type: "null" }] };
2524
+ }
2525
+ function referenceOrId(target, ctx, shape) {
2526
+ const id = ctx.primaryKeySchema(target);
2527
+ if (shape !== "projection") return id;
2528
+ const ref = ctx.projectionRef(target);
2529
+ return ref ? { anyOf: [id, { $ref: ref }] } : { anyOf: [id, expandedObject] };
2530
+ }
2531
+ function fieldSchema(field, collection, ctx, shape) {
2532
+ const relation = relationsOf(collection).find((candidate) => candidate.field === field.name);
2533
+ const kind = fieldShape(field);
2534
+ let schema;
2535
+ if (field.kind === "m2o" && field.target) {
2536
+ schema = referenceOrId(field.target, ctx, shape);
2537
+ } else if (kind.kind === "to-many" || relation && (relation.kind === "o2m" || relation.kind === "m2m")) {
2538
+ const target = kind.kind === "to-many" ? kind.target : relation?.target;
2539
+ schema = { type: "array", items: referenceOrId(target, ctx, shape) };
2540
+ } else if (kind.kind === "m2a" || relation?.kind === "m2a") {
2541
+ schema = {
2542
+ type: "array",
2543
+ items: {
2544
+ type: "object",
2545
+ properties: { collection: { type: "string" }, item: {} },
2546
+ required: ["collection", "item"]
2547
+ }
2548
+ };
2549
+ } else if (kind.kind === "localized") {
2550
+ schema = {
2551
+ type: "object",
2552
+ description: 'Per-locale values keyed by locale code (e.g. `{ "en": "\u2026", "vi": "\u2026" }`).',
2553
+ additionalProperties: { type: "string" }
2554
+ };
2555
+ } else if (kind.kind === "file") {
2556
+ schema = shape === "projection" ? { anyOf: [fileId, expandedObject] } : fileId;
2557
+ } else if (kind.kind === "files") {
2558
+ schema = { type: "array", items: shape === "projection" ? { anyOf: [fileId, expandedObject] } : fileId };
2559
+ } else if (field.type === "alias") {
2560
+ return null;
2561
+ } else if (kind.kind === "enum") {
2562
+ schema = { type: "string", enum: [...new Set(kind.values)] };
2563
+ } else {
2564
+ schema = { ...FIELD_TYPE_JSON_SCHEMA[field.type] ?? {} };
2565
+ }
2566
+ if (field.encrypted && shape !== "input") {
2567
+ schema = { anyOf: [schema, { const: "***", description: "Masked: caller lacks `read_decrypted`." }] };
2568
+ }
2569
+ if (isNullable(field)) schema = withNull(schema);
2570
+ if (field.readonly && shape !== "input") schema = { ...schema, readOnly: true };
2571
+ return schema;
2572
+ }
2573
+ function addCollectionSchemas(schemas, collection, base, ctx) {
2574
+ const userFields = collection.fields.filter((field) => !field.system);
2575
+ const ref = (suffix) => ({ $ref: `#/components/schemas/${base}.${suffix}` });
2576
+ const fieldProps = {};
2577
+ const projectionProps = {
2578
+ id: { ...ctx.primaryKeySchema(collection.name), readOnly: true },
2579
+ status: { type: "string" },
2580
+ sort: { type: "integer" },
2581
+ user_created: nullableString,
2582
+ user_updated: nullableString,
2583
+ created_at: timestamp,
2584
+ updated_at: timestamp
2585
+ };
2586
+ const required = [];
2587
+ for (const field of userFields) {
2588
+ const item = fieldSchema(field, collection, ctx, "item");
2589
+ const projection = fieldSchema(field, collection, ctx, "projection");
2590
+ if (item) {
2591
+ fieldProps[field.name] = item;
2592
+ if (field.required) required.push(field.name);
2593
+ }
2594
+ if (projection) projectionProps[field.name] = projection;
2595
+ }
2596
+ schemas[`${base}.Fields`] = {
2597
+ type: "object",
2598
+ description: `User fields of \`${collection.name}\`.`,
2599
+ properties: fieldProps,
2600
+ ...required.length > 0 ? { required } : {}
2601
+ };
2602
+ schemas[`${base}.Item`] = {
2603
+ type: "object",
2604
+ properties: {
2605
+ id: { ...ctx.primaryKeySchema(collection.name), readOnly: true },
2606
+ status: { type: "string", description: "`draft`, `published`, `archived`, or a custom workflow value." },
2607
+ sort: { type: "integer" },
2608
+ data: ref("Fields"),
2609
+ publishAt: nullableTimestamp,
2610
+ unpublishAt: nullableTimestamp,
2611
+ userCreated: nullableString,
2612
+ userUpdated: nullableString,
2613
+ createdAt: { ...timestamp, readOnly: true },
2614
+ updatedAt: { ...timestamp, readOnly: true }
2615
+ },
2616
+ required: ["id", "status", "data"]
2617
+ };
2618
+ schemas[`${base}.Projection`] = {
2619
+ type: "object",
2620
+ description: "Flat shape returned when the request passes `fields=`; only requested keys are present.",
2621
+ properties: projectionProps
2622
+ };
2623
+ const inputSchema = (withRequired) => {
2624
+ const props = {};
2625
+ const req = [];
2626
+ for (const field of userFields) {
2627
+ if (field.readonly || field.generated) continue;
2628
+ const schema = fieldSchema(field, collection, ctx, "input");
2629
+ if (!schema) continue;
2630
+ props[field.name] = schema;
2631
+ if (withRequired && field.required) req.push(field.name);
2632
+ }
2633
+ return {
2634
+ type: "object",
2635
+ properties: {
2636
+ data: { type: "object", properties: props, ...req.length > 0 ? { required: req } : {} },
2637
+ status: { type: "string" },
2638
+ sort: { type: "integer" },
2639
+ publishAt: nullableTimestamp,
2640
+ unpublishAt: nullableTimestamp
2641
+ },
2642
+ ...withRequired ? { required: ["data"] } : {}
2643
+ };
2644
+ };
2645
+ schemas[`${base}.CreateInput`] = inputSchema(true);
2646
+ schemas[`${base}.UpdateInput`] = inputSchema(false);
2647
+ const itemOrProjection = { anyOf: [ref("Item"), ref("Projection")] };
2648
+ schemas[`${base}.Response`] = {
2649
+ type: "object",
2650
+ description: "Single-item envelope.",
2651
+ properties: { data: itemOrProjection },
2652
+ required: ["data"]
2653
+ };
2654
+ schemas[`${base}.ListResponse`] = {
2655
+ type: "object",
2656
+ description: "A page of items.",
2657
+ properties: {
2658
+ data: { type: "array", items: itemOrProjection },
2659
+ meta: { $ref: "#/components/schemas/PaginationMeta" }
2660
+ },
2661
+ required: ["data"]
2662
+ };
2663
+ }
2664
+
1942
2665
  // src/typegen/index.ts
1943
2666
  var DEFAULT_IMPORT_SOURCE = "@lumibase/sdk";
1944
2667
  function generateTypes(manifest, options = {}) {
@@ -1960,11 +2683,12 @@ function generateSingleFile(manifest, branded, importSource) {
1960
2683
  return [base, expanded].filter(Boolean).join("\n\n");
1961
2684
  }).join("\n\n");
1962
2685
  const blockTypes = generateBlockTypes(manifest, branded, known);
2686
+ const richText = manifest.collections.some((c) => c.fields.some((f) => f.type === "richtext")) ? RICHTEXT_TS_DECLARATIONS : "";
1963
2687
  const collectionsMap = `export interface LumibaseCollections {
1964
- ${manifest.collections.map((c) => ` ${c.name}: ${capitalize(c.name)};`).join("\n")}
2688
+ ${manifest.collections.map((c) => ` ${c.name}: ${capitalize2(c.name)};`).join("\n")}
1965
2689
  }`;
1966
2690
  const schemaType = "export type LumibaseSchema = LumibaseCollections;";
1967
- const body = [collectionInterfaces, blockTypes, collectionsMap, schemaType].filter(Boolean).join("\n\n");
2691
+ const body = [richText, collectionInterfaces, blockTypes, collectionsMap, schemaType].filter(Boolean).join("\n\n");
1968
2692
  return `${imports}
1969
2693
 
1970
2694
  ${body}`;
@@ -1979,27 +2703,27 @@ function generateCollectionInterface(coll, branded, known) {
1979
2703
  const readonly = f.readonly || f.generated ? "readonly " : "";
1980
2704
  return ` ${readonly}${f.name}${optional}: ${tsType};`;
1981
2705
  }).join("\n");
1982
- return `export interface ${capitalize(coll.name)} {
2706
+ return `export interface ${capitalize2(coll.name)} {
1983
2707
  ${fields}
1984
2708
  }`;
1985
2709
  }
1986
2710
  function generateExpandedType(coll) {
1987
2711
  const relations = coll.relations ?? [];
1988
2712
  if (relations.length === 0) {
1989
- return `export type ${capitalize(coll.name)}Expanded = ${capitalize(coll.name)};`;
2713
+ return `export type ${capitalize2(coll.name)}Expanded = ${capitalize2(coll.name)};`;
1990
2714
  }
1991
2715
  const omittedKeys = relations.map((relation) => quoteProperty(relation.field)).join(" | ");
1992
2716
  const fields = relations.map((relation) => ` ${relation.field}?: ${expandedRelationType(relation)};`).join("\n");
1993
- return `export type ${capitalize(coll.name)}Expanded = Omit<${capitalize(coll.name)}, ${omittedKeys}> & {
2717
+ return `export type ${capitalize2(coll.name)}Expanded = Omit<${capitalize2(coll.name)}, ${omittedKeys}> & {
1994
2718
  ${fields}
1995
2719
  };`;
1996
2720
  }
1997
2721
  function expandedRelationType(relation) {
1998
2722
  if (relation.kind === "m2o") {
1999
- return `${capitalize(relation.target)} | ${capitalize(relation.target)}Expanded | null`;
2723
+ return `${capitalize2(relation.target)} | ${capitalize2(relation.target)}Expanded | null`;
2000
2724
  }
2001
2725
  if (relation.kind === "o2m" || relation.kind === "m2m") {
2002
- return `Array<${capitalize(relation.target)} | ${capitalize(relation.target)}Expanded>`;
2726
+ return `Array<${capitalize2(relation.target)} | ${capitalize2(relation.target)}Expanded>`;
2003
2727
  }
2004
2728
  return `Array<{ collection: string; item: unknown }>`;
2005
2729
  }
@@ -2017,7 +2741,7 @@ function generateBlockTypes(manifest, branded, known) {
2017
2741
  const optional = f.required ? "" : "?";
2018
2742
  return ` ${f.name}${optional}: ${mapFieldTypeToTs(f, coll, branded, known)};`;
2019
2743
  }).join("\n");
2020
- const t = capitalize(name);
2744
+ const t = capitalize2(name);
2021
2745
  return `export interface ${t}BlockData {
2022
2746
  ${dataFields}
2023
2747
  }
@@ -2031,7 +2755,7 @@ export interface ${t}Block {
2031
2755
  }
2032
2756
  function blocksUnionType(field, isKnown) {
2033
2757
  const members = (field.allowedBlocks ?? []).map(
2034
- (name) => isKnown(name) ? `${capitalize(name)}Block` : `{ id: string; type: ${JSON.stringify(name)}; data: Record<string, unknown> }`
2758
+ (name) => isKnown(name) ? `${capitalize2(name)}Block` : `{ id: string; type: ${JSON.stringify(name)}; data: Record<string, unknown> }`
2035
2759
  );
2036
2760
  if (members.length === 0) return "Array<{ id: string; type: string; data: Record<string, unknown> }>";
2037
2761
  return `Array<${members.join(" | ")}>`;
@@ -2044,11 +2768,16 @@ function mapFieldTypeToTs(field, coll, branded, known = /* @__PURE__ */ new Set(
2044
2768
  return nullable(field, mapScalarFieldType(field, branded));
2045
2769
  }
2046
2770
  if (field.kind === "o2m" || field.kind === "m2m") {
2047
- return `${capitalize(field.target || "unknown")}[]`;
2771
+ return `${capitalize2(field.target || "unknown")}[]`;
2048
2772
  }
2049
2773
  if (field.kind === "m2a") {
2050
2774
  return `Array<{ collection: string; item: unknown }>`;
2051
2775
  }
2776
+ const shape = fieldShape(field);
2777
+ if (shape.kind === "localized" || shape.kind === "file" || shape.kind === "files") {
2778
+ const wire = shape.kind === "localized" ? "Partial<Record<Locale, string>>" : shape.kind === "file" ? "string" : "string[]";
2779
+ return nullable(field, field.encrypted ? `${wire} | '***'` : wire);
2780
+ }
2052
2781
  if (field.enum && field.enum.length > 0) {
2053
2782
  return nullable(field, field.enum.map((v) => JSON.stringify(v)).join(" | "));
2054
2783
  }
@@ -2072,15 +2801,18 @@ function mapScalarFieldType(field, branded) {
2072
2801
  integer: "number",
2073
2802
  bigInteger: "number",
2074
2803
  decimal: "number",
2804
+ float: "number",
2075
2805
  boolean: "boolean",
2076
2806
  json: "unknown",
2077
2807
  uuid: mapPrimaryKeyType("uuid", branded, field.branded),
2078
2808
  date: "string",
2079
2809
  datetime: "string",
2810
+ dateTime: "string",
2080
2811
  time: "string",
2081
2812
  timestamp: "string",
2082
2813
  geometry: "GeoJSON.Geometry",
2083
- geopoint: "{ lat: number; lng: number }"
2814
+ geopoint: "{ lat: number; lng: number }",
2815
+ richtext: "RichTextDocument"
2084
2816
  };
2085
2817
  return typeMap[field.type] || "unknown";
2086
2818
  }
@@ -2095,7 +2827,7 @@ function mapPrimaryKeyType(primaryKeyType, branded, brand) {
2095
2827
  if (branded) return `Brand<'${brand || "ID"}', string>`;
2096
2828
  return "ID";
2097
2829
  }
2098
- function capitalize(str) {
2830
+ function capitalize2(str) {
2099
2831
  return str.charAt(0).toUpperCase() + str.slice(1);
2100
2832
  }
2101
2833
  function quoteProperty(name) {
@@ -2128,8 +2860,12 @@ export {
2128
2860
  AudienceClient,
2129
2861
  DECISION_ERROR_CODES,
2130
2862
  DEFAULT_IMPORT_SOURCE,
2863
+ DEFAULT_ZOD_IMPORT,
2864
+ FILES_INTERFACE,
2865
+ FILE_INTERFACE,
2131
2866
  LumiError,
2132
2867
  RealtimeClient,
2868
+ TRANSLATABLE_INTERFACE,
2133
2869
  ackCdcSubscription,
2134
2870
  checkCdcPipelineHealth,
2135
2871
  createAgentArtifact,
@@ -2150,8 +2886,12 @@ export {
2150
2886
  evaluateAgentArtifact,
2151
2887
  exportAccessManifest,
2152
2888
  extractSeo,
2889
+ filterManifest,
2153
2890
  generateAgentApp,
2891
+ generateGraphQLSdl,
2892
+ generateOpenApi,
2154
2893
  generateTypes,
2894
+ generateZod,
2155
2895
  getEffectivePreset,
2156
2896
  getReview,
2157
2897
  getReviewProfile,
@@ -2180,7 +2920,9 @@ export {
2180
2920
  readCdcSubscription,
2181
2921
  readItem,
2182
2922
  readItems,
2923
+ realtimeHolders,
2183
2924
  replayCdcSubscription,
2925
+ retainRealtime,
2184
2926
  retryAgentRun,
2185
2927
  reviewContentHash,
2186
2928
  reviewDraft,