@lumibase/sdk 1.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -187,16 +187,35 @@ function createLumiClient(opts) {
187
187
  }
188
188
  return refreshInFlight;
189
189
  }
190
- async function rawRequest(path, init = {}, retried = false) {
190
+ function buildHeaders(init) {
191
191
  const headers = new Headers(init.headers);
192
192
  for (const [key, value] of Object.entries(opts.headers ?? {})) {
193
193
  headers.set(key, value);
194
194
  }
195
195
  headers.set("authorization", `Bearer ${currentToken}`);
196
196
  headers.set("x-lumi-site", opts.siteId);
197
- if (!headers.has("content-type") && init.body) {
197
+ const isForm = typeof FormData !== "undefined" && init.body instanceof FormData;
198
+ if (!headers.has("content-type") && init.body && !isForm) {
198
199
  headers.set("content-type", "application/json");
199
200
  }
201
+ return headers;
202
+ }
203
+ async function rawFetch(path, init = {}, retried = false) {
204
+ const res = await fetcher(`${base}${path}`, { ...init, headers: buildHeaders(init) });
205
+ if (res.ok) return res;
206
+ if (res.status === 401 && !retried && currentRefreshToken && await attemptRefresh()) {
207
+ return rawFetch(path, init, true);
208
+ }
209
+ if (res.status === 401 && opts.onUnauthorized) {
210
+ try {
211
+ opts.onUnauthorized();
212
+ } catch {
213
+ }
214
+ }
215
+ throw new LumiError(res.status, toErrorBody(res.status, parseResponseBody(await res.text())), res.headers);
216
+ }
217
+ async function rawRequest(path, init = {}, retried = false) {
218
+ const headers = buildHeaders(init);
200
219
  const res = await fetcher(`${base}${path}`, { ...init, headers });
201
220
  const text = await res.text();
202
221
  const body = parseResponseBody(text);
@@ -224,6 +243,7 @@ function createLumiClient(opts) {
224
243
  siteId: opts.siteId,
225
244
  fetcher,
226
245
  rawRequest,
246
+ rawFetch: (path, init) => rawFetch(path, init),
227
247
  async request(command) {
228
248
  return command(this);
229
249
  },
@@ -724,7 +744,19 @@ function legacyRest() {
724
744
  deleteField: fields.delete,
725
745
  listRelations: relations.list,
726
746
  createRelation: relations.create,
727
- deleteRelation: relations.delete
747
+ deleteRelation: relations.delete,
748
+ /**
749
+ * Collection form layout (#750): tabs / groups / dividers + conditions.
750
+ * Typed loosely so the SDK stays decoupled from contracts; parse with
751
+ * `parseFormLayout` from `@lumibase/contracts/form-layout`.
752
+ */
753
+ getFormLayout: (name) => client.rawRequest(
754
+ `/api/v1/collections/${name}/form-layout`
755
+ ),
756
+ setFormLayout: (name, layout) => client.rawRequest(
757
+ `/api/v1/collections/${name}/form-layout`,
758
+ { method: "PUT", body: JSON.stringify({ layout }) }
759
+ )
728
760
  };
729
761
  function items(name) {
730
762
  function buildQuery(params) {
@@ -764,10 +796,55 @@ function legacyRest() {
764
796
  body: JSON.stringify(input)
765
797
  }),
766
798
  delete: (id) => client.rawRequest(`${base}/${id}`, { method: "DELETE" }),
799
+ /**
800
+ * Stream the collection as CSV or JSON (#727). Resolves with the
801
+ * unread `Response`: pipe `res.body` to a file, or `await res.text()`.
802
+ * Uses the caller's read permission; filters use the list syntax.
803
+ */
804
+ export: (params = {}) => {
805
+ const qs = new URLSearchParams();
806
+ if (params.format) qs.set("format", params.format);
807
+ if (params.fields?.length) qs.set("fields", params.fields.join(","));
808
+ if (params.locales?.length) qs.set("locales", params.locales.join(","));
809
+ if (params.relations) qs.set("relations", params.relations);
810
+ if (params.filter) qs.set("filter", JSON.stringify(params.filter));
811
+ if (params.sort?.length) qs.set("sort", params.sort.join(","));
812
+ if (params.status) qs.set("status", params.status);
813
+ const s = qs.toString();
814
+ return client.rawFetch(`${base}/export${s ? `?${s}` : ""}`);
815
+ },
767
816
  bulk: (op, payload) => client.rawRequest(`${base}/bulk`, {
768
817
  method: "POST",
769
818
  body: JSON.stringify({ op, items: payload })
770
819
  }),
820
+ /**
821
+ * Hierarchical collections (#749) on a `meta.tree.enabled` collection.
822
+ * Reads apply the caller's row rules; the anchor must be readable.
823
+ */
824
+ tree: {
825
+ children: (parent, params) => {
826
+ const q = buildQuery(params);
827
+ const sep = q ? "&" : "?";
828
+ return client.rawRequest(
829
+ `${base}${q}${sep}tree=children&parent=${encodeURIComponent(parent ?? "null")}`
830
+ );
831
+ },
832
+ subtree: (parent, params) => {
833
+ const q = buildQuery(params);
834
+ const sep = q ? "&" : "?";
835
+ return client.rawRequest(
836
+ `${base}${q}${sep}tree=subtree&parent=${encodeURIComponent(parent ?? "null")}`
837
+ );
838
+ },
839
+ ancestors: (node) => client.rawRequest(
840
+ `${base}?tree=ancestors&node=${encodeURIComponent(node)}`
841
+ ),
842
+ /** Move an item and its subtree; `position` is its 0-based index among the new siblings. */
843
+ move: (id, input) => client.rawRequest(`${base}/${id}/move`, {
844
+ method: "POST",
845
+ body: JSON.stringify(input)
846
+ })
847
+ },
771
848
  listRevisions: (id) => client.rawRequest(`${base}/${id}/revisions`),
772
849
  revertRevision: (id, revisionId) => client.rawRequest(`${base}/${id}/revert/${revisionId}`, {
773
850
  method: "POST"
@@ -1195,10 +1272,44 @@ function legacyRest() {
1195
1272
  body: JSON.stringify(patch)
1196
1273
  }),
1197
1274
  delete: (id) => client.rawRequest(`/api/v1/deployments/targets/${id}`, { method: "DELETE" }),
1198
- deploy: (id, input = {}) => client.rawRequest(`/api/v1/deployments/targets/${id}/deploy`, {
1199
- method: "POST",
1200
- body: JSON.stringify(input)
1201
- })
1275
+ /**
1276
+ * Resolves with the deployment (201), or — when the target belongs to
1277
+ * an approval-gated environment (#743) — with a `pending_approval`
1278
+ * outcome (202).
1279
+ */
1280
+ deploy: (id, input = {}) => client.rawRequest(
1281
+ `/api/v1/deployments/targets/${id}/deploy`,
1282
+ {
1283
+ method: "POST",
1284
+ body: JSON.stringify(input)
1285
+ }
1286
+ )
1287
+ },
1288
+ // Environments, promotion and deploy approvals (#743).
1289
+ access: () => client.rawRequest("/api/v1/deployments/access"),
1290
+ environments: {
1291
+ list: () => client.rawRequest("/api/v1/deployments/environments"),
1292
+ update: (environments) => client.rawRequest("/api/v1/deployments/environments", {
1293
+ method: "PUT",
1294
+ body: JSON.stringify({ environments })
1295
+ }),
1296
+ deploy: (key, input = {}) => client.rawRequest(
1297
+ `/api/v1/deployments/environments/${encodeURIComponent(key)}/deploy`,
1298
+ { method: "POST", body: JSON.stringify(input) }
1299
+ ),
1300
+ promote: (key, input = {}) => client.rawRequest(
1301
+ `/api/v1/deployments/environments/${encodeURIComponent(key)}/promote`,
1302
+ { method: "POST", body: JSON.stringify(input) }
1303
+ )
1304
+ },
1305
+ approvals: {
1306
+ list: (status = "pending") => client.rawRequest(
1307
+ `/api/v1/deployments/approvals?status=${encodeURIComponent(status)}`
1308
+ ),
1309
+ decide: (id, input) => client.rawRequest(
1310
+ `/api/v1/deployments/approvals/${encodeURIComponent(id)}/decide`,
1311
+ { method: "POST", body: JSON.stringify(input) }
1312
+ )
1202
1313
  },
1203
1314
  list: (params) => {
1204
1315
  const qs = new URLSearchParams();
@@ -1211,9 +1322,40 @@ function legacyRest() {
1211
1322
  logs: (id) => client.rawRequest(`/api/v1/deployments/${id}/logs`),
1212
1323
  refresh: (id) => client.rawRequest(`/api/v1/deployments/${id}/refresh`, { method: "POST" })
1213
1324
  };
1325
+ const imports = {
1326
+ /**
1327
+ * Upload a CSV or JSON export file and queue it. Resolves with the job
1328
+ * (`202`); poll `get(id)` until `status` is terminal.
1329
+ */
1330
+ create: (collection, file, opts = {}) => {
1331
+ const qs = new URLSearchParams({ collection });
1332
+ if (opts.format) qs.set("format", opts.format);
1333
+ if (opts.mode) qs.set("mode", opts.mode);
1334
+ const form = new FormData();
1335
+ const blob = typeof file === "string" ? new Blob([file], { type: "application/octet-stream" }) : file;
1336
+ form.append("file", blob, opts.filename ?? `${collection}.${opts.format ?? "csv"}`);
1337
+ return client.rawRequest(`/api/v1/imports?${qs.toString()}`, { method: "POST", body: form });
1338
+ },
1339
+ list: (params = {}) => {
1340
+ const qs = new URLSearchParams();
1341
+ if (params.collection) qs.set("collection", params.collection);
1342
+ if (params.status) qs.set("status", params.status);
1343
+ if (params.limit !== void 0) qs.set("limit", String(params.limit));
1344
+ const s = qs.toString();
1345
+ return client.rawRequest(`/api/v1/imports${s ? `?${s}` : ""}`);
1346
+ },
1347
+ get: (id) => client.rawRequest(`/api/v1/imports/${encodeURIComponent(id)}`),
1348
+ errors: (id) => client.rawRequest(
1349
+ `/api/v1/imports/${encodeURIComponent(id)}/errors`
1350
+ ),
1351
+ /** The error report as a CSV download (`row,id,message`). */
1352
+ errorsCsv: (id) => client.rawFetch(`/api/v1/imports/${encodeURIComponent(id)}/errors?format=csv`),
1353
+ cancel: (id) => client.rawRequest(`/api/v1/imports/${encodeURIComponent(id)}/cancel`, { method: "POST" })
1354
+ };
1214
1355
  return {
1215
1356
  schema,
1216
1357
  items,
1358
+ imports,
1217
1359
  roles,
1218
1360
  policies,
1219
1361
  access,
@@ -1906,33 +2048,32 @@ function generateTypes(manifest, options = {}) {
1906
2048
  return generatePerCollection(manifest, branded, importSource);
1907
2049
  }
1908
2050
  function generateSingleFile(manifest, branded, importSource) {
2051
+ const known = new Set(manifest.collections.map((c) => c.name));
1909
2052
  const imports = [
1910
2053
  `import type { ID, Locale } from '${importSource}';`,
1911
2054
  branded ? `import type { Brand } from '${importSource}';` : ""
1912
2055
  ].filter(Boolean).join("\n");
1913
2056
  const collectionInterfaces = manifest.collections.map((coll) => {
1914
- const base = generateCollectionInterface(coll, branded);
2057
+ const base = generateCollectionInterface(coll, branded, known);
1915
2058
  const expanded = generateExpandedType(coll);
1916
2059
  return [base, expanded].filter(Boolean).join("\n\n");
1917
2060
  }).join("\n\n");
2061
+ const blockTypes = generateBlockTypes(manifest, branded, known);
1918
2062
  const collectionsMap = `export interface LumibaseCollections {
1919
2063
  ${manifest.collections.map((c) => ` ${c.name}: ${capitalize(c.name)};`).join("\n")}
1920
2064
  }`;
1921
2065
  const schemaType = "export type LumibaseSchema = LumibaseCollections;";
2066
+ const body = [collectionInterfaces, blockTypes, collectionsMap, schemaType].filter(Boolean).join("\n\n");
1922
2067
  return `${imports}
1923
2068
 
1924
- ${collectionInterfaces}
1925
-
1926
- ${collectionsMap}
1927
-
1928
- ${schemaType}`;
2069
+ ${body}`;
1929
2070
  }
1930
2071
  function generatePerCollection(manifest, branded, importSource) {
1931
2072
  return generateSingleFile(manifest, branded, importSource);
1932
2073
  }
1933
- function generateCollectionInterface(coll, branded) {
2074
+ function generateCollectionInterface(coll, branded, known) {
1934
2075
  const fields = coll.fields.map((f) => {
1935
- const tsType = mapFieldTypeToTs(f, coll, branded);
2076
+ const tsType = mapFieldTypeToTs(f, coll, branded, known);
1936
2077
  const optional = f.required ? "" : "?";
1937
2078
  const readonly = f.readonly || f.generated ? "readonly " : "";
1938
2079
  return ` ${readonly}${f.name}${optional}: ${tsType};`;
@@ -1961,7 +2102,43 @@ function expandedRelationType(relation) {
1961
2102
  }
1962
2103
  return `Array<{ collection: string; item: unknown }>`;
1963
2104
  }
1964
- function mapFieldTypeToTs(field, coll, branded) {
2105
+ function generateBlockTypes(manifest, branded, known) {
2106
+ const byName = new Map(manifest.collections.map((c) => [c.name, c]));
2107
+ const referenced = /* @__PURE__ */ new Set();
2108
+ for (const coll of manifest.collections) {
2109
+ for (const f of coll.fields) {
2110
+ if (f.type === "blocks") for (const t of f.allowedBlocks ?? []) referenced.add(t);
2111
+ }
2112
+ }
2113
+ return [...referenced].filter((name) => byName.has(name)).sort().map((name) => {
2114
+ const coll = byName.get(name);
2115
+ const dataFields = coll.fields.filter((f) => !f.system && !f.primaryKey).map((f) => {
2116
+ const optional = f.required ? "" : "?";
2117
+ return ` ${f.name}${optional}: ${mapFieldTypeToTs(f, coll, branded, known)};`;
2118
+ }).join("\n");
2119
+ const t = capitalize(name);
2120
+ return `export interface ${t}BlockData {
2121
+ ${dataFields}
2122
+ }
2123
+
2124
+ export interface ${t}Block {
2125
+ id: string;
2126
+ type: ${JSON.stringify(name)};
2127
+ data: ${t}BlockData;
2128
+ }`;
2129
+ }).join("\n\n");
2130
+ }
2131
+ function blocksUnionType(field, isKnown) {
2132
+ const members = (field.allowedBlocks ?? []).map(
2133
+ (name) => isKnown(name) ? `${capitalize(name)}Block` : `{ id: string; type: ${JSON.stringify(name)}; data: Record<string, unknown> }`
2134
+ );
2135
+ if (members.length === 0) return "Array<{ id: string; type: string; data: Record<string, unknown> }>";
2136
+ return `Array<${members.join(" | ")}>`;
2137
+ }
2138
+ function mapFieldTypeToTs(field, coll, branded, known = /* @__PURE__ */ new Set()) {
2139
+ if (field.type === "blocks") {
2140
+ return nullable(field, blocksUnionType(field, (name) => known.has(name)));
2141
+ }
1965
2142
  if (field.kind === "m2o") {
1966
2143
  return nullable(field, mapScalarFieldType(field, branded));
1967
2144
  }
@@ -1983,7 +2160,9 @@ function mapFieldTypeToTs(field, coll, branded) {
1983
2160
  const tsType = mapScalarFieldType(field, branded);
1984
2161
  return nullable(field, field.encrypted ? `${tsType} | '***'` : tsType);
1985
2162
  }
2163
+ var ZONED_DATETIME_TS = "{ instant: string; tz: string; offset: string }";
1986
2164
  function mapScalarFieldType(field, branded) {
2165
+ if (field.timezone) return ZONED_DATETIME_TS;
1987
2166
  const typeMap = {
1988
2167
  string: "string",
1989
2168
  text: "string",
@@ -1999,7 +2178,8 @@ function mapScalarFieldType(field, branded) {
1999
2178
  datetime: "string",
2000
2179
  time: "string",
2001
2180
  timestamp: "string",
2002
- geometry: "GeoJSON.Geometry"
2181
+ geometry: "GeoJSON.Geometry",
2182
+ geopoint: "{ lat: number; lng: number }"
2003
2183
  };
2004
2184
  return typeMap[field.type] || "unknown";
2005
2185
  }