@axcode/axcloud-sdk 0.1.6 → 0.1.7-dev.580a922

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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { createContext, useContext, useMemo, useCallback, useRef } from 'react';
1
+ import { createContext, useContext, useMemo, useCallback, useState, useRef } from 'react';
2
2
  import { Auth0Provider, useAuth0 } from '@auth0/auth0-react';
3
3
  import { QueryClient, QueryClientProvider, useQuery, useQueryClient, useMutation } from '@tanstack/react-query';
4
4
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
@@ -122,7 +122,7 @@ var AxCloudClient = class {
122
122
  */
123
123
  shouldAttachApiKey(path) {
124
124
  const normalized = path.startsWith("/") ? path : `/${path}`;
125
- return normalized.startsWith("/public/") || normalized.startsWith("/api/public/") || normalized.startsWith("/content/public/");
125
+ return normalized.startsWith("/public/") || normalized.startsWith("/api/public/") || normalized.startsWith("/content/public/") || normalized.startsWith("/media/public/") || normalized.startsWith("/documents/public/") || normalized.startsWith("/barnsport/public/") || normalized.startsWith("/api/barnsport/public/");
126
126
  }
127
127
  /**
128
128
  * Make an authenticated request
@@ -431,6 +431,98 @@ function createFormHelper(config) {
431
431
  })
432
432
  };
433
433
  }
434
+
435
+ // src/core/voting.ts
436
+ function baseOf(votingApiUrl) {
437
+ return votingApiUrl.replace(/\/$/, "");
438
+ }
439
+ async function readJson(response) {
440
+ const json = await response.json().catch(() => ({}));
441
+ if (json && typeof json === "object" && "success" in json && "data" in json) {
442
+ return json.data;
443
+ }
444
+ return json;
445
+ }
446
+ async function ensureOk(response) {
447
+ if (!response.ok) {
448
+ const body = await response.json().catch(() => ({}));
449
+ const message = body && (body.error || body.message) || `Request failed with status ${response.status}`;
450
+ throw new Error(message);
451
+ }
452
+ }
453
+ async function checkVotingCode(votingApiUrl, params) {
454
+ const response = await fetch(
455
+ `${baseOf(votingApiUrl)}/public/organizations/${params.orgId}/polls/${params.pollId}/eligibility`,
456
+ {
457
+ method: "POST",
458
+ headers: { "Content-Type": "application/json" },
459
+ body: JSON.stringify({ code: params.code })
460
+ }
461
+ );
462
+ await ensureOk(response);
463
+ return readJson(response);
464
+ }
465
+ async function castVoteWithCode(votingApiUrl, params) {
466
+ const response = await fetch(
467
+ `${baseOf(votingApiUrl)}/public/organizations/${params.orgId}/polls/${params.pollId}/vote`,
468
+ {
469
+ method: "POST",
470
+ headers: { "Content-Type": "application/json" },
471
+ body: JSON.stringify({ code: params.code, selected_options: params.selectedOptions, rankings: params.rankings })
472
+ }
473
+ );
474
+ await ensureOk(response);
475
+ return readJson(response);
476
+ }
477
+ async function getVotingReceipt(votingApiUrl, params) {
478
+ const response = await fetch(
479
+ `${baseOf(votingApiUrl)}/public/organizations/${params.orgId}/polls/${params.pollId}/receipt`,
480
+ {
481
+ method: "POST",
482
+ headers: { "Content-Type": "application/json" },
483
+ body: JSON.stringify({ code: params.code })
484
+ }
485
+ );
486
+ await ensureOk(response);
487
+ return readJson(response);
488
+ }
489
+ function authHeaders(accessToken) {
490
+ return { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}` };
491
+ }
492
+ async function getBallot(votingApiUrl, params) {
493
+ const base = `${baseOf(votingApiUrl)}/organizations/${params.orgId}/polls/${params.pollId}`;
494
+ const pollResp = await fetch(base, { headers: authHeaders(params.accessToken) });
495
+ await ensureOk(pollResp);
496
+ const poll = await readJson(pollResp);
497
+ let candidates = [];
498
+ if (poll.poll_type === "election") {
499
+ const candResp = await fetch(`${base}/candidates`, { headers: authHeaders(params.accessToken) });
500
+ await ensureOk(candResp);
501
+ const data = await readJson(candResp);
502
+ candidates = data.candidates || [];
503
+ }
504
+ return { ...poll, candidates };
505
+ }
506
+ async function checkEligibility(votingApiUrl, params) {
507
+ const response = await fetch(
508
+ `${baseOf(votingApiUrl)}/organizations/${params.orgId}/polls/${params.pollId}/eligibility`,
509
+ { headers: authHeaders(params.accessToken) }
510
+ );
511
+ await ensureOk(response);
512
+ return readJson(response);
513
+ }
514
+ async function castVote(votingApiUrl, params) {
515
+ const response = await fetch(
516
+ `${baseOf(votingApiUrl)}/organizations/${params.orgId}/polls/${params.pollId}/vote`,
517
+ {
518
+ method: "POST",
519
+ headers: authHeaders(params.accessToken),
520
+ body: JSON.stringify({ selected_options: params.selectedOptions, rankings: params.rankings })
521
+ }
522
+ );
523
+ await ensureOk(response);
524
+ return readJson(response);
525
+ }
434
526
  var AxCloudContext = createContext(null);
435
527
  function useAxCloudContext() {
436
528
  const context = useContext(AxCloudContext);
@@ -741,6 +833,7 @@ function useNews(options = {}) {
741
833
  search,
742
834
  sortBy = "publishedAt",
743
835
  sortOrder = "desc",
836
+ lang,
744
837
  publicOnly = false
745
838
  } = options;
746
839
  const usePublicEndpoint = isPublicMode || publicOnly;
@@ -757,7 +850,8 @@ function useNews(options = {}) {
757
850
  sectionId,
758
851
  search,
759
852
  sortBy,
760
- sortOrder
853
+ sortOrder,
854
+ lang
761
855
  ],
762
856
  queryFn: async () => {
763
857
  const endpoint = usePublicEndpoint ? `/content/public/${orgId}/news` : `/content/members/${orgId}/news`;
@@ -769,7 +863,8 @@ function useNews(options = {}) {
769
863
  sectionId,
770
864
  search,
771
865
  sortBy,
772
- sortOrder
866
+ sortOrder,
867
+ lang
773
868
  });
774
869
  },
775
870
  staleTime: 1e3 * 60 * 5
@@ -998,6 +1093,76 @@ function useUpdateFormSubmission() {
998
1093
  }
999
1094
  });
1000
1095
  }
1096
+ function useCodeBallot({ pollId, votingApiUrl }) {
1097
+ const { orgId, config } = useAxCloudContext();
1098
+ const baseUrl = votingApiUrl || `${config.apiUrl.replace(/\/$/, "")}/voting`;
1099
+ const [stage, setStage] = useState("enter_code");
1100
+ const [code, setCode] = useState("");
1101
+ const [ballot, setBallot] = useState(null);
1102
+ const [receipt, setReceipt] = useState(null);
1103
+ const [reason, setReason] = useState(void 0);
1104
+ const [loading, setLoading] = useState(false);
1105
+ const [error, setError] = useState(null);
1106
+ const validateCode = useCallback(
1107
+ async (inputCode) => {
1108
+ setLoading(true);
1109
+ setError(null);
1110
+ try {
1111
+ const result = await checkVotingCode(baseUrl, { orgId, pollId, code: inputCode });
1112
+ setCode(inputCode);
1113
+ setReason(result.reason);
1114
+ if (result.has_voted) {
1115
+ const r = await getVotingReceipt(baseUrl, { orgId, pollId, code: inputCode }).catch(() => null);
1116
+ setReceipt(r);
1117
+ setStage("already_voted");
1118
+ } else if (result.eligible && result.ballot) {
1119
+ setBallot(result.ballot);
1120
+ setStage("ballot");
1121
+ } else {
1122
+ setError(result.reason || "This code cannot be used to vote right now.");
1123
+ }
1124
+ return result;
1125
+ } catch (e) {
1126
+ setError(e instanceof Error ? e.message : "Failed to validate code");
1127
+ return null;
1128
+ } finally {
1129
+ setLoading(false);
1130
+ }
1131
+ },
1132
+ [baseUrl, orgId, pollId]
1133
+ );
1134
+ const submitVote = useCallback(
1135
+ async (selectedOptions, rankings) => {
1136
+ setLoading(true);
1137
+ setError(null);
1138
+ try {
1139
+ await castVoteWithCode(baseUrl, { orgId, pollId, code, selectedOptions, rankings });
1140
+ const r = await getVotingReceipt(baseUrl, { orgId, pollId, code }).catch(() => null);
1141
+ setReceipt(r);
1142
+ setStage("submitted");
1143
+ return true;
1144
+ } catch (e) {
1145
+ setError(e instanceof Error ? e.message : "Failed to submit vote");
1146
+ return false;
1147
+ } finally {
1148
+ setLoading(false);
1149
+ }
1150
+ },
1151
+ [baseUrl, orgId, pollId, code]
1152
+ );
1153
+ const reset = useCallback(() => {
1154
+ setStage("enter_code");
1155
+ setCode("");
1156
+ setBallot(null);
1157
+ setReceipt(null);
1158
+ setReason(void 0);
1159
+ setError(null);
1160
+ }, []);
1161
+ return useMemo(
1162
+ () => ({ stage, code, ballot, receipt, reason, loading, error, validateCode, submitVote, reset }),
1163
+ [stage, code, ballot, receipt, reason, loading, error, validateCode, submitVote, reset]
1164
+ );
1165
+ }
1001
1166
  var LINKED_ACCOUNTS_QUERY_KEY = ["axcloud", "linked-accounts"];
1002
1167
  function useLinkedAccounts() {
1003
1168
  const { client, stage } = useAxCloudContext();
@@ -1156,6 +1321,245 @@ function useMedia(mediaId) {
1156
1321
  refetch: query.refetch
1157
1322
  };
1158
1323
  }
1324
+ function buildDocumentParams(options) {
1325
+ return {
1326
+ search: options?.search,
1327
+ tags: options?.tags?.join(","),
1328
+ limit: options?.limit
1329
+ };
1330
+ }
1331
+ function useDocuments(options) {
1332
+ const { client, orgId } = useAxCloudContext();
1333
+ const params = buildDocumentParams(options);
1334
+ const query = useQuery({
1335
+ queryKey: ["axcloud", "documents", "list", orgId, options],
1336
+ queryFn: async () => {
1337
+ return client.get(`/documents/public/${orgId}/documents`, params);
1338
+ },
1339
+ staleTime: 1e3 * 60 * 5
1340
+ });
1341
+ return {
1342
+ documents: query.data?.items ?? [],
1343
+ items: query.data?.items ?? [],
1344
+ count: query.data?.count ?? 0,
1345
+ isLoading: query.isLoading,
1346
+ isError: query.isError,
1347
+ error: query.error,
1348
+ refetch: query.refetch
1349
+ };
1350
+ }
1351
+ function useDocumentDownload(documentId) {
1352
+ const { client, orgId } = useAxCloudContext();
1353
+ const query = useQuery({
1354
+ queryKey: ["axcloud", "documents", "download", orgId, documentId],
1355
+ queryFn: async () => {
1356
+ return client.get(
1357
+ `/documents/public/${orgId}/documents/${encodeURIComponent(documentId || "")}/download`
1358
+ );
1359
+ },
1360
+ enabled: !!documentId,
1361
+ staleTime: 1e3 * 60 * 10,
1362
+ gcTime: 1e3 * 60 * 14
1363
+ });
1364
+ return {
1365
+ url: query.data?.url ?? null,
1366
+ documentUrl: query.data?.url ?? null,
1367
+ filename: query.data?.filename ?? null,
1368
+ mimeType: query.data?.mimeType ?? null,
1369
+ expiresIn: query.data?.expiresIn ?? null,
1370
+ isLoading: query.isLoading,
1371
+ isError: query.isError,
1372
+ error: query.error,
1373
+ refetch: query.refetch
1374
+ };
1375
+ }
1376
+ function useMemberDocuments(options) {
1377
+ const { client, orgId } = useAxCloudContext();
1378
+ const params = buildDocumentParams(options);
1379
+ const folderId = options?.folderId;
1380
+ const query = useQuery({
1381
+ queryKey: ["axcloud", "documents", "member", "list", orgId, options],
1382
+ queryFn: async () => {
1383
+ return client.get(`/documents/members/${orgId}/documents`, params);
1384
+ },
1385
+ staleTime: 1e3 * 60 * 5
1386
+ });
1387
+ const allItems = query.data?.items ?? [];
1388
+ const items = folderId ? allItems.filter((doc) => doc.folder_ids?.includes(folderId)) : allItems;
1389
+ return {
1390
+ documents: items,
1391
+ items,
1392
+ count: folderId ? items.length : query.data?.count ?? 0,
1393
+ isLoading: query.isLoading,
1394
+ isError: query.isError,
1395
+ error: query.error,
1396
+ refetch: query.refetch
1397
+ };
1398
+ }
1399
+ function useMemberDocumentFolders() {
1400
+ const { client, orgId } = useAxCloudContext();
1401
+ const query = useQuery({
1402
+ queryKey: ["axcloud", "documents", "member", "folders", orgId],
1403
+ queryFn: async () => {
1404
+ return client.get(
1405
+ `/documents/members/${orgId}/document-folders`
1406
+ );
1407
+ },
1408
+ staleTime: 1e3 * 60 * 5
1409
+ });
1410
+ return {
1411
+ folders: query.data?.folders ?? [],
1412
+ isLoading: query.isLoading,
1413
+ isError: query.isError,
1414
+ error: query.error,
1415
+ refetch: query.refetch
1416
+ };
1417
+ }
1418
+ function useMemberDocumentDownload(documentId) {
1419
+ const { client, orgId } = useAxCloudContext();
1420
+ const query = useQuery({
1421
+ queryKey: ["axcloud", "documents", "member", "download", orgId, documentId],
1422
+ queryFn: async () => {
1423
+ return client.get(
1424
+ `/documents/members/${orgId}/documents/${encodeURIComponent(documentId || "")}/download`
1425
+ );
1426
+ },
1427
+ enabled: !!documentId,
1428
+ staleTime: 1e3 * 60 * 10,
1429
+ gcTime: 1e3 * 60 * 14
1430
+ });
1431
+ return {
1432
+ url: query.data?.url ?? null,
1433
+ documentUrl: query.data?.url ?? null,
1434
+ filename: query.data?.filename ?? null,
1435
+ mimeType: query.data?.mimeType ?? null,
1436
+ expiresIn: query.data?.expiresIn ?? null,
1437
+ isLoading: query.isLoading,
1438
+ isError: query.isError,
1439
+ error: query.error,
1440
+ refetch: query.refetch
1441
+ };
1442
+ }
1443
+ function useBarnsportMunicipalities() {
1444
+ const { client, orgId } = useAxCloudContext();
1445
+ const query = useQuery({
1446
+ queryKey: ["axcloud", "barnsport", "municipalities", orgId],
1447
+ queryFn: () => client.get(
1448
+ `/barnsport/public/${orgId}/municipalities`
1449
+ ),
1450
+ staleTime: 1e3 * 60 * 30
1451
+ });
1452
+ return {
1453
+ municipalities: query.data?.items ?? [],
1454
+ count: query.data?.count ?? 0,
1455
+ isLoading: query.isLoading,
1456
+ isError: query.isError,
1457
+ error: query.error,
1458
+ refetch: query.refetch
1459
+ };
1460
+ }
1461
+ function useBarnsportSports() {
1462
+ const { client, orgId } = useAxCloudContext();
1463
+ const query = useQuery({
1464
+ queryKey: ["axcloud", "barnsport", "sports", orgId],
1465
+ queryFn: () => client.get(
1466
+ `/barnsport/public/${orgId}/sports`
1467
+ ),
1468
+ staleTime: 1e3 * 60 * 30
1469
+ });
1470
+ return {
1471
+ sports: query.data?.items ?? [],
1472
+ count: query.data?.count ?? 0,
1473
+ isLoading: query.isLoading,
1474
+ isError: query.isError,
1475
+ error: query.error,
1476
+ refetch: query.refetch
1477
+ };
1478
+ }
1479
+ function useBarnsportSport(slug) {
1480
+ const { client, orgId } = useAxCloudContext();
1481
+ const query = useQuery({
1482
+ queryKey: ["axcloud", "barnsport", "sport", orgId, slug],
1483
+ queryFn: () => client.get(
1484
+ `/barnsport/public/${orgId}/sports/${slug || ""}`
1485
+ ),
1486
+ enabled: Boolean(slug),
1487
+ staleTime: 1e3 * 60 * 15
1488
+ });
1489
+ return {
1490
+ sport: query.data?.sport ?? null,
1491
+ isLoading: query.isLoading,
1492
+ isError: query.isError,
1493
+ error: query.error,
1494
+ refetch: query.refetch
1495
+ };
1496
+ }
1497
+ function useBarnsportActivities(filters = {}) {
1498
+ const { client, orgId } = useAxCloudContext();
1499
+ const params = { ...filters };
1500
+ const query = useQuery({
1501
+ queryKey: ["axcloud", "barnsport", "activities", orgId, filters],
1502
+ queryFn: () => client.get(
1503
+ `/barnsport/public/${orgId}/activities`,
1504
+ params
1505
+ ),
1506
+ staleTime: 1e3 * 60 * 5
1507
+ });
1508
+ return {
1509
+ activities: query.data?.items ?? [],
1510
+ count: query.data?.count ?? 0,
1511
+ nextCursor: query.data?.nextCursor ?? null,
1512
+ isLoading: query.isLoading,
1513
+ isError: query.isError,
1514
+ error: query.error,
1515
+ refetch: query.refetch
1516
+ };
1517
+ }
1518
+ function useBarnsportActivity(slug) {
1519
+ const { client, orgId } = useAxCloudContext();
1520
+ const query = useQuery({
1521
+ queryKey: ["axcloud", "barnsport", "activity", orgId, slug],
1522
+ queryFn: () => client.get(
1523
+ `/barnsport/public/${orgId}/activities/${slug || ""}`
1524
+ ),
1525
+ enabled: Boolean(slug),
1526
+ staleTime: 1e3 * 60 * 5
1527
+ });
1528
+ return {
1529
+ activity: query.data?.activity ?? null,
1530
+ isLoading: query.isLoading,
1531
+ isError: query.isError,
1532
+ error: query.error,
1533
+ refetch: query.refetch
1534
+ };
1535
+ }
1536
+ function useBarnsportSitemap(baseUrl) {
1537
+ const { client, orgId } = useAxCloudContext();
1538
+ const query = useQuery({
1539
+ queryKey: ["axcloud", "barnsport", "sitemap", orgId, baseUrl],
1540
+ queryFn: () => client.get(`/barnsport/public/${orgId}/sitemap`, {
1541
+ baseUrl
1542
+ }),
1543
+ staleTime: 1e3 * 60 * 15
1544
+ });
1545
+ return {
1546
+ sitemap: query.data ?? null,
1547
+ urls: query.data?.urls ?? [],
1548
+ isLoading: query.isLoading,
1549
+ isError: query.isError,
1550
+ error: query.error,
1551
+ refetch: query.refetch
1552
+ };
1553
+ }
1554
+ function useSubmitBarnsportInterest() {
1555
+ const { client, orgId } = useAxCloudContext();
1556
+ return useMutation({
1557
+ mutationFn: (submission) => client.post(
1558
+ `/barnsport/public/${orgId}/interest`,
1559
+ submission
1560
+ )
1561
+ });
1562
+ }
1159
1563
  function LoginButton({
1160
1564
  children = "Log in",
1161
1565
  returnTo,
@@ -1399,6 +1803,6 @@ function LinkedAccountsList({
1399
1803
  ] });
1400
1804
  }
1401
1805
 
1402
- export { AxCloudClient, AxCloudError, AxCloudProvider, LinkedAccountsList, LoginButton, LogoutButton, ModuleGate, ProtectedRoute, createClient, createContentSlotReader, createFormHelper, getClient, getContentSlotMap, isAxCloudError, submitForm, useAuth, useAvatar, useAxCloudContext, useBranding, useContent, useContentItem, useFormStats, useForms, useLinkedAccounts, useLogo, useMedia, useMediaList, useModuleAccess, useMySection, useNews, useOrg, usePageContent, useSections, useUpdateFormSubmission, useUser, userHasAllPermissions, userHasAnyPermission, userHasPermission };
1806
+ export { AxCloudClient, AxCloudError, AxCloudProvider, LinkedAccountsList, LoginButton, LogoutButton, ModuleGate, ProtectedRoute, castVote, castVoteWithCode, checkEligibility, checkVotingCode, createClient, createContentSlotReader, createFormHelper, getBallot, getClient, getContentSlotMap, getVotingReceipt, isAxCloudError, submitForm, useAuth, useAvatar, useAxCloudContext, useBarnsportActivities, useBarnsportActivity, useBarnsportMunicipalities, useBarnsportSitemap, useBarnsportSport, useBarnsportSports, useBranding, useCodeBallot, useContent, useContentItem, useDocumentDownload, useDocuments, useFormStats, useForms, useLinkedAccounts, useLogo, useMedia, useMediaList, useMemberDocumentDownload, useMemberDocumentFolders, useMemberDocuments, useModuleAccess, useMySection, useNews, useOrg, usePageContent, useSections, useSubmitBarnsportInterest, useUpdateFormSubmission, useUser, userHasAllPermissions, userHasAnyPermission, userHasPermission };
1403
1807
  //# sourceMappingURL=index.mjs.map
1404
1808
  //# sourceMappingURL=index.mjs.map