@cmssy/react 9.10.0 → 10.0.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/client.js CHANGED
@@ -1,14 +1,11 @@
1
1
  "use client";
2
- import { createContext, useState, useRef, useEffect, useMemo, useContext, useCallback, createElement } from 'react';
3
- import { fields, resolveInitialTarget, buildBlockContext, postToEditor, PROTOCOL_VERSION, parseEditorMessage, getBlockContentForLanguage, normalizeRelationContent, asBucket, toMinorUnits, formatPrice } from '@cmssy/core';
4
- export { formatPrice, fractionDigits, fromMinorUnits, toMinorUnits } from '@cmssy/core';
2
+ import { useState, useRef, useEffect, useMemo, createElement } from 'react';
3
+ import { buildBlockContext, postToEditor, PROTOCOL_VERSION, parseEditorMessage } from '@cmssy/core';
4
+ import { resolveInitialTarget, getBlockContentForLanguage, normalizeRelationContent, asBucket } from '@cmssy/core/internal';
5
5
  import { BlockErrorBoundary } from '@cmssy/react/block-error-boundary';
6
6
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
7
7
 
8
8
  // src/registry.ts
9
- function defineBlock(def) {
10
- return def;
11
- }
12
9
  function buildBlockMap(blocks) {
13
10
  const map = /* @__PURE__ */ Object.create(null);
14
11
  for (const block of blocks) map[block.type] = block.component;
@@ -865,694 +862,5 @@ function CmssyLazyLayout({ load, ...props }) {
865
862
  if (!blocks) return null;
866
863
  return /* @__PURE__ */ jsx(CmssyEditableLayout, { ...props, blocks });
867
864
  }
868
- var LocaleContext = createContext(null);
869
- function CmssyLocaleProvider({
870
- value,
871
- children
872
- }) {
873
- return /* @__PURE__ */ jsx(LocaleContext.Provider, { value, children });
874
- }
875
- function useCmssyLocale() {
876
- return useContext(LocaleContext);
877
- }
878
- var CmssyAuthContext = createContext(null);
879
- function CmssyAuthProvider({
880
- children,
881
- basePath = "/api/cmssy/auth",
882
- initialUser
883
- }) {
884
- const seeded = initialUser !== void 0;
885
- const [user, setUser] = useState(initialUser ?? null);
886
- const [loading, setLoading] = useState(!seeded);
887
- const generation = useRef(0);
888
- const base = useMemo(() => basePath.replace(/\/+$/, ""), [basePath]);
889
- const commitUser = useCallback((next) => {
890
- generation.current += 1;
891
- setUser(next);
892
- }, []);
893
- const fetchUser = useCallback(async () => {
894
- try {
895
- const res = await fetch(`${base}/me`, {
896
- credentials: "same-origin",
897
- cache: "no-store"
898
- });
899
- const data = await res.json();
900
- return data.user ?? null;
901
- } catch {
902
- return null;
903
- }
904
- }, [base]);
905
- useEffect(() => {
906
- if (seeded) return;
907
- const gen = generation.current;
908
- void (async () => {
909
- const next = await fetchUser();
910
- if (gen === generation.current) {
911
- setUser(next);
912
- setLoading(false);
913
- }
914
- })();
915
- }, [fetchUser, seeded]);
916
- const postAction = useCallback(
917
- async (action, body) => {
918
- const res = await fetch(`${base}/${action}`, {
919
- method: "POST",
920
- credentials: "same-origin",
921
- headers: { "content-type": "application/json" },
922
- body: JSON.stringify(body)
923
- });
924
- return await res.json();
925
- },
926
- [base]
927
- );
928
- const signIn = useCallback(
929
- async (identity, password) => {
930
- const data = await postAction("sign-in", { identity, password });
931
- if (data.ok && data.user) commitUser(data.user);
932
- return { ok: Boolean(data.ok), message: data.message };
933
- },
934
- [postAction, commitUser]
935
- );
936
- const register = useCallback(
937
- async (identity, password, fields3) => {
938
- const data = await postAction("register", {
939
- identity,
940
- password,
941
- fields: fields3 ?? {}
942
- });
943
- return { ok: Boolean(data.ok), message: data.message };
944
- },
945
- [postAction]
946
- );
947
- const signOut = useCallback(async () => {
948
- try {
949
- await postAction("sign-out", {});
950
- } finally {
951
- commitUser(null);
952
- }
953
- }, [postAction, commitUser]);
954
- const refresh = useCallback(async () => {
955
- const gen = generation.current;
956
- const next = await fetchUser();
957
- if (gen === generation.current) setUser(next);
958
- }, [fetchUser]);
959
- const value = useMemo(
960
- () => ({ user, loading, signIn, register, signOut, refresh }),
961
- [user, loading, signIn, register, signOut, refresh]
962
- );
963
- return /* @__PURE__ */ jsx(CmssyAuthContext.Provider, { value, children });
964
- }
965
- function useCmssyUser() {
966
- const ctx = useContext(CmssyAuthContext);
967
- if (!ctx) {
968
- throw new Error("useCmssyUser must be used within <CmssyAuthProvider>");
969
- }
970
- return ctx;
971
- }
972
- var CmssyCommerceContext = createContext(null);
973
- function CmssyCommerceProvider({
974
- children,
975
- basePath = "/api/cmssy/cart"
976
- }) {
977
- const base = useMemo(() => basePath.replace(/\/+$/, ""), [basePath]);
978
- const generation = useRef(0);
979
- const [cart, setCart] = useState(null);
980
- const [loading, setLoading] = useState(true);
981
- const [error, setError] = useState(null);
982
- const post = useCallback(
983
- async (action, body) => {
984
- const res = await fetch(`${base}/${action}`, {
985
- method: "POST",
986
- credentials: "same-origin",
987
- headers: { "content-type": "application/json" },
988
- body: JSON.stringify(body)
989
- });
990
- const data = await res.json().catch(() => ({}));
991
- if (!res.ok) {
992
- throw new Error(
993
- typeof data.message === "string" ? data.message : "Commerce request failed"
994
- );
995
- }
996
- return data;
997
- },
998
- [base]
999
- );
1000
- const runCart = useCallback(
1001
- async (action, body) => {
1002
- const gen = ++generation.current;
1003
- setError(null);
1004
- try {
1005
- const data = await post(action, body);
1006
- if (gen === generation.current) setCart(data.cart);
1007
- } catch (err) {
1008
- if (gen === generation.current) {
1009
- setError(
1010
- err instanceof Error ? err.message : "Commerce request failed"
1011
- );
1012
- }
1013
- throw err;
1014
- }
1015
- },
1016
- [post]
1017
- );
1018
- const refresh = useCallback(async () => {
1019
- setLoading(true);
1020
- try {
1021
- await runCart("cart", {});
1022
- } catch {
1023
- return;
1024
- } finally {
1025
- setLoading(false);
1026
- }
1027
- }, [runCart]);
1028
- useEffect(() => {
1029
- void refresh();
1030
- }, [refresh]);
1031
- const addToCart = useCallback(
1032
- (recordId, quantity = 1, options) => runCart("add", {
1033
- recordId,
1034
- quantity,
1035
- variantSelections: options?.variantSelections,
1036
- notes: options?.notes
1037
- }),
1038
- [runCart]
1039
- );
1040
- const updateItem = useCallback(
1041
- (itemId, quantity) => runCart("update", { itemId, quantity }),
1042
- [runCart]
1043
- );
1044
- const removeItem = useCallback(
1045
- (itemId) => runCart("remove", { itemId }),
1046
- [runCart]
1047
- );
1048
- const clearCart = useCallback(() => runCart("clear", {}), [runCart]);
1049
- const applyDiscount = useCallback(
1050
- (code) => runCart("apply-discount", { code }),
1051
- [runCart]
1052
- );
1053
- const removeDiscount = useCallback(
1054
- () => runCart("remove-discount", {}),
1055
- [runCart]
1056
- );
1057
- const setShippingMethod = useCallback(
1058
- (shippingMethodId) => runCart("set-shipping", { shippingMethodId }),
1059
- [runCart]
1060
- );
1061
- const merge = useCallback(() => runCart("merge", {}), [runCart]);
1062
- const checkout = useCallback(
1063
- async (input) => {
1064
- const gen = ++generation.current;
1065
- setError(null);
1066
- try {
1067
- const data = await post("checkout", {
1068
- ...input
1069
- });
1070
- if (gen === generation.current) setCart(null);
1071
- return data.order;
1072
- } catch (err) {
1073
- if (gen === generation.current) {
1074
- setError(err instanceof Error ? err.message : "Checkout failed");
1075
- }
1076
- throw err;
1077
- }
1078
- },
1079
- [post]
1080
- );
1081
- const fetchProduct = useCallback(
1082
- async (modelSlug, filter) => {
1083
- const data = await post("product", {
1084
- modelSlug,
1085
- filter
1086
- });
1087
- return data.product;
1088
- },
1089
- [post]
1090
- );
1091
- const value = useMemo(
1092
- () => ({
1093
- cart,
1094
- loading,
1095
- error,
1096
- addToCart,
1097
- updateItem,
1098
- removeItem,
1099
- clearCart,
1100
- applyDiscount,
1101
- removeDiscount,
1102
- setShippingMethod,
1103
- merge,
1104
- checkout,
1105
- refresh,
1106
- fetchProduct
1107
- }),
1108
- [
1109
- cart,
1110
- loading,
1111
- error,
1112
- addToCart,
1113
- updateItem,
1114
- removeItem,
1115
- clearCart,
1116
- applyDiscount,
1117
- removeDiscount,
1118
- setShippingMethod,
1119
- merge,
1120
- checkout,
1121
- refresh,
1122
- fetchProduct
1123
- ]
1124
- );
1125
- return /* @__PURE__ */ jsx(CmssyCommerceContext.Provider, { value, children });
1126
- }
1127
- function useCart() {
1128
- const ctx = useContext(CmssyCommerceContext);
1129
- if (!ctx) {
1130
- throw new Error("useCart must be used within <CmssyCommerceProvider>");
1131
- }
1132
- return ctx;
1133
- }
1134
- var productProps = {
1135
- modelSlug: fields.text({ label: "Model slug" }),
1136
- slugField: fields.text({ label: "Slug field" }),
1137
- slug: fields.text({ label: "Product slug" }),
1138
- nameField: fields.text({ label: "Name field" }),
1139
- priceField: fields.text({ label: "Price field" }),
1140
- imageField: fields.text({ label: "Image field" })
1141
- };
1142
- function deriveAxes(variants) {
1143
- const axes = /* @__PURE__ */ new Map();
1144
- for (const variant of variants) {
1145
- for (const option of variant.selectedOptions) {
1146
- if (!axes.has(option.name)) axes.set(option.name, /* @__PURE__ */ new Set());
1147
- axes.get(option.name).add(option.value);
1148
- }
1149
- }
1150
- return [...axes.entries()].map(([name, values]) => ({
1151
- name,
1152
- values: [...values]
1153
- }));
1154
- }
1155
- function matchVariant(variants, selections) {
1156
- return variants.find(
1157
- (variant) => variant.selectedOptions.every(
1158
- (opt) => selections[opt.name] === opt.value
1159
- )
1160
- ) ?? null;
1161
- }
1162
- function ProductComponent({ content: c }) {
1163
- const { fetchProduct, addToCart } = useCart();
1164
- const injected = c.product ?? null;
1165
- const [product, setProduct] = useState(injected);
1166
- const [loading, setLoading] = useState(!injected && Boolean(c.slug));
1167
- const [selections, setSelections] = useState({});
1168
- const [adding, setAdding] = useState(false);
1169
- const [added, setAdded] = useState(false);
1170
- const [addError, setAddError] = useState(null);
1171
- const modelSlug = c.modelSlug ?? "products";
1172
- const slugField = c.slugField ?? "slug";
1173
- const slug = c.slug ?? "";
1174
- useEffect(() => {
1175
- if (injected || !slug) return;
1176
- let active = true;
1177
- setLoading(true);
1178
- void (async () => {
1179
- try {
1180
- const result = await fetchProduct(modelSlug, { [slugField]: slug });
1181
- if (active) setProduct(result);
1182
- } finally {
1183
- if (active) setLoading(false);
1184
- }
1185
- })();
1186
- return () => {
1187
- active = false;
1188
- };
1189
- }, [injected, fetchProduct, modelSlug, slugField, slug]);
1190
- const axes = useMemo(
1191
- () => product ? deriveAxes(product.variants) : [],
1192
- [product]
1193
- );
1194
- const variant = useMemo(
1195
- () => product ? matchVariant(product.variants, selections) : null,
1196
- [product, selections]
1197
- );
1198
- if (loading) {
1199
- return /* @__PURE__ */ jsx("div", { "data-cmssy-product": "loading", children: "Loading\u2026" });
1200
- }
1201
- if (!product) {
1202
- return /* @__PURE__ */ jsx("div", { "data-cmssy-product": "not-found", children: "Product not found" });
1203
- }
1204
- const data = product.data;
1205
- const name = String(data[c.nameField ?? "name"] ?? "");
1206
- const imageUrl = c.imageField ? data[c.imageField] : null;
1207
- const hasVariants = product.variants.length > 0;
1208
- const currency = data.currency ?? "USD";
1209
- const priceMinor = hasVariants ? variant?.price : toMinorUnits(Number(data[c.priceField ?? "price"] ?? 0), currency);
1210
- const showPrice = priceMinor != null && Number.isFinite(priceMinor);
1211
- const allAxesSelected = axes.every((axis) => selections[axis.name]);
1212
- const outOfStock = variant != null && variant.inventory != null && variant.inventory <= 0;
1213
- const canAdd = hasVariants ? Boolean(variant) && !outOfStock : true;
1214
- async function onAdd() {
1215
- if (!product) return;
1216
- setAdding(true);
1217
- setAdded(false);
1218
- setAddError(null);
1219
- try {
1220
- await addToCart(
1221
- product.id,
1222
- 1,
1223
- hasVariants ? { variantSelections: selections } : void 0
1224
- );
1225
- setAdded(true);
1226
- } catch (err) {
1227
- setAddError(err instanceof Error ? err.message : "Could not add to cart");
1228
- } finally {
1229
- setAdding(false);
1230
- }
1231
- }
1232
- return /* @__PURE__ */ jsxs("div", { "data-cmssy-product": product.id, children: [
1233
- imageUrl ? /* @__PURE__ */ jsx("img", { src: imageUrl, alt: name }) : null,
1234
- /* @__PURE__ */ jsx("h3", { "data-cmssy-product-name": true, children: name }),
1235
- showPrice ? /* @__PURE__ */ jsx("p", { "data-cmssy-product-price": true, children: formatPrice(priceMinor, currency) }) : null,
1236
- axes.map((axis) => /* @__PURE__ */ jsxs("label", { "data-cmssy-variant-axis": axis.name, children: [
1237
- /* @__PURE__ */ jsx("span", { children: axis.name }),
1238
- /* @__PURE__ */ jsxs(
1239
- "select",
1240
- {
1241
- value: selections[axis.name] ?? "",
1242
- onChange: (e) => setSelections((prev) => ({
1243
- ...prev,
1244
- [axis.name]: e.target.value
1245
- })),
1246
- children: [
1247
- /* @__PURE__ */ jsx("option", { value: "", children: "\u2014" }),
1248
- axis.values.map((v) => /* @__PURE__ */ jsx("option", { value: v, children: v }, v))
1249
- ]
1250
- }
1251
- )
1252
- ] }, axis.name)),
1253
- /* @__PURE__ */ jsx(
1254
- "button",
1255
- {
1256
- type: "button",
1257
- onClick: onAdd,
1258
- disabled: adding || !canAdd || hasVariants && !allAxesSelected,
1259
- "data-cmssy-add-to-cart": true,
1260
- children: adding ? "Adding\u2026" : outOfStock ? "Out of stock" : added ? "Added" : "Add to cart"
1261
- }
1262
- ),
1263
- addError ? /* @__PURE__ */ jsx("p", { "data-cmssy-product-error": true, children: addError }) : null
1264
- ] });
1265
- }
1266
- var productBlock = defineBlock({
1267
- type: "product",
1268
- label: "Product",
1269
- category: "Commerce",
1270
- props: productProps,
1271
- component: ProductComponent
1272
- });
1273
- function CartComponent() {
1274
- const {
1275
- cart,
1276
- loading,
1277
- error,
1278
- updateItem,
1279
- removeItem,
1280
- applyDiscount,
1281
- removeDiscount
1282
- } = useCart();
1283
- const [code, setCode] = useState("");
1284
- const [busy, setBusy] = useState(false);
1285
- if (loading) {
1286
- return /* @__PURE__ */ jsx("div", { "data-cmssy-cart": "loading", children: "Loading\u2026" });
1287
- }
1288
- if (!cart || cart.items.length === 0) {
1289
- return /* @__PURE__ */ jsx("div", { "data-cmssy-cart": "empty", children: "Your cart is empty." });
1290
- }
1291
- const currency = cart.currency ?? "USD";
1292
- async function withBusy(fn) {
1293
- setBusy(true);
1294
- try {
1295
- await fn();
1296
- } catch {
1297
- setBusy(false);
1298
- } finally {
1299
- setBusy(false);
1300
- }
1301
- }
1302
- return /* @__PURE__ */ jsxs("div", { "data-cmssy-cart": cart.id, children: [
1303
- error ? /* @__PURE__ */ jsx("p", { "data-cmssy-cart-error": true, children: error }) : null,
1304
- /* @__PURE__ */ jsx("ul", { "data-cmssy-cart-items": true, children: cart.items.map((item) => /* @__PURE__ */ jsxs("li", { "data-cmssy-cart-item": item.id, children: [
1305
- /* @__PURE__ */ jsx("span", { "data-cmssy-item-name": true, children: item.snapshot.name }),
1306
- /* @__PURE__ */ jsx(
1307
- "input",
1308
- {
1309
- type: "number",
1310
- min: "1",
1311
- value: item.quantity,
1312
- disabled: busy,
1313
- onChange: (e) => {
1314
- const qty = Number(e.target.value);
1315
- if (Number.isInteger(qty) && qty >= 1) {
1316
- void withBusy(() => updateItem(item.id, qty));
1317
- }
1318
- },
1319
- "data-cmssy-item-qty": true
1320
- }
1321
- ),
1322
- /* @__PURE__ */ jsx("span", { "data-cmssy-item-price": true, children: formatPrice(item.snapshot.price * item.quantity, currency) }),
1323
- /* @__PURE__ */ jsx(
1324
- "button",
1325
- {
1326
- type: "button",
1327
- disabled: busy,
1328
- onClick: () => void withBusy(() => removeItem(item.id)),
1329
- "data-cmssy-item-remove": true,
1330
- children: "Remove"
1331
- }
1332
- )
1333
- ] }, item.id)) }),
1334
- /* @__PURE__ */ jsx("div", { "data-cmssy-cart-discount": true, children: cart.appliedDiscount ? /* @__PURE__ */ jsxs("p", { children: [
1335
- /* @__PURE__ */ jsx("span", { children: cart.appliedDiscount.code }),
1336
- /* @__PURE__ */ jsx(
1337
- "button",
1338
- {
1339
- type: "button",
1340
- disabled: busy,
1341
- onClick: () => void withBusy(() => removeDiscount()),
1342
- children: "Remove"
1343
- }
1344
- )
1345
- ] }) : /* @__PURE__ */ jsxs("p", { children: [
1346
- /* @__PURE__ */ jsx(
1347
- "input",
1348
- {
1349
- type: "text",
1350
- value: code,
1351
- placeholder: "Discount code",
1352
- onChange: (e) => setCode(e.target.value),
1353
- disabled: busy
1354
- }
1355
- ),
1356
- /* @__PURE__ */ jsx(
1357
- "button",
1358
- {
1359
- type: "button",
1360
- disabled: busy || !code.trim(),
1361
- onClick: () => void withBusy(async () => {
1362
- await applyDiscount(code.trim());
1363
- setCode("");
1364
- }),
1365
- children: "Apply"
1366
- }
1367
- )
1368
- ] }) }),
1369
- /* @__PURE__ */ jsxs("dl", { "data-cmssy-cart-totals": true, children: [
1370
- /* @__PURE__ */ jsxs("div", { children: [
1371
- /* @__PURE__ */ jsx("dt", { children: "Subtotal" }),
1372
- /* @__PURE__ */ jsx("dd", { children: formatPrice(cart.subtotal, currency) })
1373
- ] }),
1374
- /* @__PURE__ */ jsxs("div", { children: [
1375
- /* @__PURE__ */ jsx("dt", { children: "Total" }),
1376
- /* @__PURE__ */ jsx("dd", { "data-cmssy-cart-total": true, children: formatPrice(cart.discountedTotal, currency) })
1377
- ] })
1378
- ] })
1379
- ] });
1380
- }
1381
- var cartBlock = defineBlock({
1382
- type: "cart",
1383
- label: "Cart",
1384
- category: "Commerce",
1385
- props: {},
1386
- component: CartComponent
1387
- });
1388
- var checkoutProps = {
1389
- successMessage: fields.text({ label: "Success message" })
1390
- };
1391
- var EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
1392
- function CheckoutComponent({
1393
- content: c
1394
- }) {
1395
- const { cart, loading, checkout } = useCart();
1396
- const [email, setEmail] = useState("");
1397
- const [busy, setBusy] = useState(false);
1398
- const [error, setError] = useState(null);
1399
- const [order, setOrder] = useState(null);
1400
- if (order) {
1401
- return /* @__PURE__ */ jsxs("div", { "data-cmssy-checkout": "done", children: [
1402
- /* @__PURE__ */ jsx("p", { children: c.successMessage ?? "Order placed - awaiting payment." }),
1403
- /* @__PURE__ */ jsx("p", { "data-cmssy-order-id": true, children: order.id }),
1404
- /* @__PURE__ */ jsx("p", { "data-cmssy-order-total": true, children: formatPrice(order.total, order.currency) })
1405
- ] });
1406
- }
1407
- if (loading) {
1408
- return /* @__PURE__ */ jsx("div", { "data-cmssy-checkout": "loading", children: "Loading\u2026" });
1409
- }
1410
- if (!cart || cart.items.length === 0) {
1411
- return /* @__PURE__ */ jsx("div", { "data-cmssy-checkout": "empty", children: "Your cart is empty." });
1412
- }
1413
- const emailValid = EMAIL_RE.test(email.trim());
1414
- async function onSubmit() {
1415
- setBusy(true);
1416
- setError(null);
1417
- try {
1418
- setOrder(await checkout({ customerEmail: email.trim() }));
1419
- } catch (err) {
1420
- setError(err instanceof Error ? err.message : "Checkout failed");
1421
- } finally {
1422
- setBusy(false);
1423
- }
1424
- }
1425
- return /* @__PURE__ */ jsxs(
1426
- "form",
1427
- {
1428
- "data-cmssy-checkout": cart.id,
1429
- onSubmit: (e) => {
1430
- e.preventDefault();
1431
- if (emailValid && !busy) void onSubmit();
1432
- },
1433
- children: [
1434
- error ? /* @__PURE__ */ jsx("p", { "data-cmssy-checkout-error": true, children: error }) : null,
1435
- /* @__PURE__ */ jsxs("label", { children: [
1436
- /* @__PURE__ */ jsx("span", { children: "Email" }),
1437
- /* @__PURE__ */ jsx(
1438
- "input",
1439
- {
1440
- type: "email",
1441
- value: email,
1442
- onChange: (e) => setEmail(e.target.value),
1443
- required: true,
1444
- "data-cmssy-checkout-email": true
1445
- }
1446
- )
1447
- ] }),
1448
- /* @__PURE__ */ jsx("p", { "data-cmssy-checkout-total": true, children: formatPrice(cart.discountedTotal, cart.currency ?? "USD") }),
1449
- /* @__PURE__ */ jsx(
1450
- "button",
1451
- {
1452
- type: "submit",
1453
- disabled: busy || !emailValid,
1454
- "data-cmssy-checkout-submit": true,
1455
- children: busy ? "Placing order\u2026" : "Place order"
1456
- }
1457
- )
1458
- ]
1459
- }
1460
- );
1461
- }
1462
- var checkoutBlock = defineBlock({
1463
- type: "checkout",
1464
- label: "Checkout",
1465
- category: "Commerce",
1466
- props: checkoutProps,
1467
- component: CheckoutComponent
1468
- });
1469
- function useCmssyOrders(options = {}) {
1470
- const base = (options.basePath ?? "/api/cmssy/orders").replace(/\/+$/, "");
1471
- const skip = options.skip ?? 0;
1472
- const limit = options.limit ?? 20;
1473
- const [orders, setOrders] = useState([]);
1474
- const [total, setTotal] = useState(0);
1475
- const [hasMore, setHasMore] = useState(false);
1476
- const [loading, setLoading] = useState(true);
1477
- const [error, setError] = useState(null);
1478
- const load = useCallback(async () => {
1479
- setLoading(true);
1480
- setError(null);
1481
- try {
1482
- const qs = new URLSearchParams({
1483
- skip: String(skip),
1484
- limit: String(limit)
1485
- });
1486
- const res = await fetch(`${base}?${qs.toString()}`, {
1487
- credentials: "same-origin",
1488
- cache: "no-store"
1489
- });
1490
- if (res.status === 401) {
1491
- setOrders([]);
1492
- setTotal(0);
1493
- setHasMore(false);
1494
- return;
1495
- }
1496
- if (!res.ok) {
1497
- const body = await res.json().catch(() => ({}));
1498
- throw new Error(
1499
- body.message ?? `Orders request failed (${res.status})`
1500
- );
1501
- }
1502
- const data = await res.json();
1503
- setOrders(data.items ?? []);
1504
- setTotal(data.total ?? 0);
1505
- setHasMore(Boolean(data.hasMore));
1506
- } catch (e) {
1507
- setError(e instanceof Error ? e.message : "Could not load orders");
1508
- } finally {
1509
- setLoading(false);
1510
- }
1511
- }, [base, skip, limit]);
1512
- useEffect(() => {
1513
- void load();
1514
- }, [load]);
1515
- return { orders, total, hasMore, loading, error, refresh: load };
1516
- }
1517
- function useCmssyOrder(id, options = {}) {
1518
- const base = (options.basePath ?? "/api/cmssy/orders").replace(/\/+$/, "");
1519
- const [order, setOrder] = useState(null);
1520
- const [loading, setLoading] = useState(Boolean(id));
1521
- const [error, setError] = useState(null);
1522
- const load = useCallback(async () => {
1523
- if (!id) {
1524
- setOrder(null);
1525
- setLoading(false);
1526
- return;
1527
- }
1528
- setLoading(true);
1529
- setError(null);
1530
- try {
1531
- const qs = new URLSearchParams({ id });
1532
- const res = await fetch(`${base}?${qs.toString()}`, {
1533
- credentials: "same-origin",
1534
- cache: "no-store"
1535
- });
1536
- if (res.status === 401) {
1537
- setOrder(null);
1538
- return;
1539
- }
1540
- if (!res.ok) {
1541
- const body = await res.json().catch(() => ({}));
1542
- throw new Error(body.message ?? `Order request failed (${res.status})`);
1543
- }
1544
- const data = await res.json();
1545
- setOrder(data.order ?? null);
1546
- } catch (e) {
1547
- setError(e instanceof Error ? e.message : "Could not load the order");
1548
- } finally {
1549
- setLoading(false);
1550
- }
1551
- }, [base, id]);
1552
- useEffect(() => {
1553
- void load();
1554
- }, [load]);
1555
- return { order, loading, error, refresh: load };
1556
- }
1557
865
 
1558
- export { CmssyAuthProvider, CmssyCommerceProvider, CmssyEditableLayout, CmssyEditablePage, CmssyLazyEditor, CmssyLazyLayout, CmssyLocaleProvider, cartBlock, checkoutBlock, productBlock, useCart, useCmssyLocale, useCmssyOrder, useCmssyOrders, useCmssyUser, useEditBridge };
866
+ export { CmssyEditableLayout, CmssyEditablePage, CmssyLazyEditor, CmssyLazyLayout, useEditBridge };