@fractalshq/sync 0.0.11 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +51 -9
  2. package/dist/chunk-4ZYNBLY5.mjs +129 -0
  3. package/dist/chunk-DUDWBTA2.mjs +0 -0
  4. package/dist/chunk-FBL2T6BA.mjs +249 -0
  5. package/dist/chunk-ZIWHYEXE.mjs +498 -0
  6. package/dist/index.d.mts +1 -3
  7. package/dist/index.d.ts +1 -3
  8. package/dist/index.js +19 -649
  9. package/dist/index.mjs +7 -42
  10. package/dist/v1/core/index.d.mts +28 -0
  11. package/dist/v1/core/index.d.ts +28 -0
  12. package/dist/v1/core/index.js +320 -0
  13. package/dist/v1/core/index.mjs +51 -0
  14. package/dist/v1/index.d.mts +3 -0
  15. package/dist/v1/index.d.ts +3 -0
  16. package/dist/v1/index.js +816 -0
  17. package/dist/v1/index.mjs +63 -0
  18. package/dist/v1/react/index.d.mts +111 -0
  19. package/dist/v1/react/index.d.ts +111 -0
  20. package/dist/v1/react/index.js +552 -0
  21. package/dist/v1/react/index.mjs +330 -0
  22. package/dist/v1/server/index.d.mts +67 -0
  23. package/dist/v1/server/index.d.ts +67 -0
  24. package/dist/v1/server/index.js +540 -0
  25. package/dist/v1/server/index.mjs +15 -0
  26. package/dist/v1/widgets/index.d.mts +2 -0
  27. package/dist/v1/widgets/index.d.ts +2 -0
  28. package/dist/v1/widgets/index.js +18 -0
  29. package/dist/v1/widgets/index.mjs +0 -0
  30. package/dist/v2/core/index.d.mts +5 -21
  31. package/dist/v2/core/index.d.ts +5 -21
  32. package/dist/v2/core/index.js +8 -34
  33. package/dist/v2/core/index.mjs +3 -7
  34. package/dist/v2/index.d.mts +1 -1
  35. package/dist/v2/index.d.ts +1 -1
  36. package/dist/v2/index.js +8 -34
  37. package/dist/v2/index.mjs +4 -7
  38. package/dist/v2/react/index.d.mts +5 -27
  39. package/dist/v2/react/index.d.ts +5 -27
  40. package/dist/v2/react/index.js +25 -107
  41. package/dist/v2/react/index.mjs +20 -76
  42. package/package.json +52 -21
package/README.md CHANGED
@@ -1,24 +1,66 @@
1
1
  # @fractalshq/sync
2
2
 
3
- Fractals Sync is the all-in-one SDK for the distribution platform. It ships as a single package with subpath exports so integrators can pick only what they need:
3
+ Fractals Sync is the all-in-one SDK for the distribution platform. The default `@fractalshq/sync` export points to v2, and v1 is still available via explicit subpaths.
4
4
 
5
5
  ```
6
- @fractalshq/sync/core // shared types + helpers (pure TS)
7
- @fractalshq/sync/server // Node/Next client that talks to /api/v1
8
- @fractalshq/sync/react // hooks that assume AuthProvider + wallet context
9
- @fractalshq/sync/widgets // drop-in UI with its own provider stack
6
+ @fractalshq/sync // default v2 surface (claims + tx build only)
7
+ @fractalshq/sync/v2 // public v2 surface (claims + tx build only)
8
+ @fractalshq/sync/v2/core // v2 core helpers (build tx + list claims)
9
+ @fractalshq/sync/v2/react // v2 React hooks (useClaims, useClaimTransaction)
10
+ @fractalshq/sync/v1/core // shared types + helpers (pure TS)
11
+ @fractalshq/sync/v1/server // Node/Next client that talks to /api/v1
12
+ @fractalshq/sync/v1/react // hooks that assume AuthProvider + wallet context
13
+ @fractalshq/sync/v1/widgets // drop-in UI with its own provider stack
10
14
  ```
11
15
 
16
+ Legacy v1 aliases (mapped to v1): `@fractalshq/sync/core`, `@fractalshq/sync/server`, `@fractalshq/sync/react`, `@fractalshq/sync/widgets`.
17
+
12
18
  ## Layout
13
19
 
14
20
  ```
15
21
  packages/sync/
16
22
  ├── src/
17
- │ ├── core/ // typed constants, schemas, memo builders
18
- │ ├── server/ // moved from @fractalshq/distribution-server
19
- │ ├── react/ // hooks + helpers (will absorb old distribution-client work)
20
- └── widgets/ // claim panels, buttons, etc.
23
+ │ ├── v1/
24
+ ├── core/ // typed constants, schemas, memo builders
25
+ ├── server/ // moved from @fractalshq/distribution-server
26
+ │ ├── react/ // hooks + helpers (will absorb old distribution-client work)
27
+ │ │ └── widgets/ // claim panels, buttons, etc.
28
+ │ └── v2/ // public v2 API surface (claims + tx build)
21
29
  └── package.json // exports map for subpaths
22
30
  ```
23
31
 
32
+ ## V2 (public claims surface)
33
+
34
+ V2 is intentionally tiny and public-facing. It only exposes:
35
+
36
+ - `GET /api/v2/claims?wallet=<pubkey>` (claimable + claimed)
37
+ - `POST /api/v2/claims/[id]/create-transaction` (build claim tx)
38
+
39
+ ### Core usage
40
+
41
+ ```ts
42
+ import { listClaims, buildClaimTransaction } from "@fractalshq/sync/v2/core";
43
+
44
+ const claims = await listClaims(wallet);
45
+ const tx = await buildClaimTransaction({
46
+ distributionId,
47
+ claimant: wallet,
48
+ });
49
+ ```
50
+
51
+ ### React usage
52
+
53
+ ```tsx
54
+ import { useClaims, useClaimTransaction } from "@fractalshq/sync/v2/react";
55
+
56
+ const claimsQuery = useClaims(wallet);
57
+ const buildTx = useClaimTransaction();
58
+ buildTx.mutateAsync({ distributionId, claimant: wallet });
59
+ ```
60
+
61
+ Notes:
62
+ - Default base path is `/api/v2` (override via `NEXT_PUBLIC_SYNC_V2_PATH`).
63
+ - V2 requests are `credentials: "omit"` for public CORS mode.
64
+ - If `wallet` is omitted, `useClaims` falls back to the Solana wallet adapter context (`@solana/wallet-adapter-react`).
65
+
24
66
  See `docs/distro-sdk.md` and `docs/distribution-sdk-auth-facts.md` for the full design notes / TODOs.
@@ -0,0 +1,129 @@
1
+ import {
2
+ __objRest,
3
+ __spreadValues
4
+ } from "./chunk-FWCSY2DS.mjs";
5
+
6
+ // src/v2/core/http.ts
7
+ var FALLBACK_BASE_PATH = "/api/v2";
8
+ var _a, _b;
9
+ var ENV_BASE_PATH = typeof process !== "undefined" && (((_a = process.env) == null ? void 0 : _a.NEXT_PUBLIC_SYNC_V2_PATH) || ((_b = process.env) == null ? void 0 : _b.NEXT_PUBLIC_FRACTALS_SYNC_V2_PATH)) || void 0;
10
+ var DEFAULT_BASE_PATH = sanitizeBasePath(ENV_BASE_PATH || FALLBACK_BASE_PATH);
11
+ function resolveRequestConfig(options) {
12
+ return {
13
+ basePath: sanitizeBasePath((options == null ? void 0 : options.basePath) || DEFAULT_BASE_PATH),
14
+ fetcher: resolveFetcher(options == null ? void 0 : options.fetcher)
15
+ };
16
+ }
17
+ var SyncReactError = class extends Error {
18
+ constructor(status, code, details) {
19
+ super(code || `Sync request failed with status ${status}`);
20
+ this.status = status;
21
+ this.code = code;
22
+ this.details = details;
23
+ this.name = "SyncReactError";
24
+ }
25
+ };
26
+ async function requestJSON(config, path, init) {
27
+ var _a2;
28
+ const url = buildUrl(config.basePath, path);
29
+ const requestInit = prepareInit(init);
30
+ requestInit.credentials = (_a2 = requestInit.credentials) != null ? _a2 : "omit";
31
+ const response = await config.fetcher(url, requestInit);
32
+ const payload = await parseResponseBody(response);
33
+ if (!response.ok) {
34
+ const errorCode = typeof payload === "object" && payload && "error" in payload ? String(payload.error) : void 0;
35
+ throw new SyncReactError(response.status, errorCode, payload);
36
+ }
37
+ return payload;
38
+ }
39
+ function resolveFetcher(custom) {
40
+ if (custom) return custom;
41
+ if (typeof fetch === "function") return fetch.bind(globalThis);
42
+ throw new Error("Global fetch is not available. Provide a fetcher via Sync configuration.");
43
+ }
44
+ function sanitizeBasePath(path) {
45
+ if (!path) return FALLBACK_BASE_PATH;
46
+ const trimmed = path.trim();
47
+ if (!trimmed || trimmed === "/") return "/";
48
+ return trimmed.replace(/\/+$/, "");
49
+ }
50
+ function buildUrl(basePath, path) {
51
+ if (path && isAbsoluteUrl(path)) return path;
52
+ const normalizedBase = sanitizeBasePath(basePath);
53
+ const suffix = path ? `/${path.replace(/^\/+/, "")}` : "";
54
+ if (!normalizedBase || normalizedBase === "/") {
55
+ return suffix ? suffix : normalizedBase;
56
+ }
57
+ return `${normalizedBase}${suffix}`;
58
+ }
59
+ function isAbsoluteUrl(path) {
60
+ return /^https?:\/\//i.test(path);
61
+ }
62
+ function isRelativeUrl(path) {
63
+ return !isAbsoluteUrl(path);
64
+ }
65
+ function prepareInit(init) {
66
+ const finalInit = __spreadValues({}, init);
67
+ if ((init == null ? void 0 : init.headers) instanceof Headers) {
68
+ const cloned = new Headers(init.headers);
69
+ if (!cloned.has("content-type")) cloned.set("content-type", "application/json");
70
+ finalInit.headers = cloned;
71
+ return finalInit;
72
+ }
73
+ const headers = new Headers(init == null ? void 0 : init.headers);
74
+ if (!headers.has("content-type")) {
75
+ headers.set("content-type", "application/json");
76
+ }
77
+ finalInit.headers = headers;
78
+ return finalInit;
79
+ }
80
+ async function parseResponseBody(response) {
81
+ if (response.status === 204) return void 0;
82
+ const text = await response.text();
83
+ if (!text) return void 0;
84
+ try {
85
+ return JSON.parse(text);
86
+ } catch (e) {
87
+ return text;
88
+ }
89
+ }
90
+
91
+ // src/v2/core/api.ts
92
+ async function buildClaimTransaction(input, options) {
93
+ const distributionId = input == null ? void 0 : input.distributionId;
94
+ if (!distributionId) {
95
+ throw new SyncReactError(400, "distribution_id_required");
96
+ }
97
+ const config = resolveRequestConfig(options);
98
+ const _a2 = input, { distributionId: _unused } = _a2, body = __objRest(_a2, ["distributionId"]);
99
+ return requestJSON(
100
+ config,
101
+ `/claims/${encodeURIComponent(distributionId)}/create-transaction`,
102
+ {
103
+ method: "POST",
104
+ body: JSON.stringify(body)
105
+ }
106
+ );
107
+ }
108
+ async function listClaims(wallet, options) {
109
+ if (!wallet) {
110
+ throw new SyncReactError(400, "wallet_required");
111
+ }
112
+ const config = resolveRequestConfig(options);
113
+ const qs = new URLSearchParams({ wallet }).toString();
114
+ return requestJSON(config, `/claims?${qs}`, { method: "GET" });
115
+ }
116
+
117
+ export {
118
+ DEFAULT_BASE_PATH,
119
+ resolveRequestConfig,
120
+ SyncReactError,
121
+ requestJSON,
122
+ resolveFetcher,
123
+ sanitizeBasePath,
124
+ buildUrl,
125
+ isAbsoluteUrl,
126
+ isRelativeUrl,
127
+ buildClaimTransaction,
128
+ listClaims
129
+ };
File without changes
@@ -0,0 +1,249 @@
1
+ import {
2
+ __objRest,
3
+ __spreadProps,
4
+ __spreadValues
5
+ } from "./chunk-FWCSY2DS.mjs";
6
+
7
+ // src/v1/core/constants.ts
8
+ var MEMO_PROGRAM_ID = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr";
9
+ var XNET_2022_MINT = "xNETbUB7cRb3AAu2pNG2pUwQcJ2BHcktfvSB8x1Pq6L";
10
+ var DEFAULT_RPC_ENDPOINT = process.env.NEXT_PUBLIC_SOLANA_RPC_URL || "https://api.mainnet-beta.solana.com";
11
+ var DISTRIBUTION_MEMO_PREFIX = "dist";
12
+
13
+ // src/v1/core/helpers.ts
14
+ function buildDistributionMemoTag(distributionId, action = "claim") {
15
+ return `${DISTRIBUTION_MEMO_PREFIX}:${distributionId}:${action}`;
16
+ }
17
+ function assertTruthy(value, message) {
18
+ if (value === null || value === void 0) {
19
+ throw new Error(message);
20
+ }
21
+ return value;
22
+ }
23
+
24
+ // src/v1/core/persistence.ts
25
+ var STORAGE_PREFIX = "distribution:persistence-warning:";
26
+ var PERSISTENCE_WARNING_EVENT = "distribution:persistence-warning";
27
+ function isBrowser() {
28
+ return typeof window !== "undefined" && typeof localStorage !== "undefined";
29
+ }
30
+ function persistToStorage(record) {
31
+ if (!isBrowser()) return;
32
+ try {
33
+ localStorage.setItem(`${STORAGE_PREFIX}${record.id}`, JSON.stringify(record));
34
+ } catch (error) {
35
+ console.error("[sync:persistence-warning] Failed to write to localStorage", error);
36
+ }
37
+ }
38
+ function emitWarning(record) {
39
+ if (!isBrowser()) return;
40
+ try {
41
+ window.dispatchEvent(new CustomEvent(PERSISTENCE_WARNING_EVENT, { detail: record }));
42
+ } catch (error) {
43
+ console.error("[sync:persistence-warning] Failed to emit warning event", error);
44
+ }
45
+ }
46
+ function recordPersistenceWarning(input) {
47
+ var _a2;
48
+ if (!isBrowser()) return void 0;
49
+ const record = __spreadProps(__spreadValues({}, input), {
50
+ createdAt: (_a2 = input.createdAt) != null ? _a2 : Date.now()
51
+ });
52
+ persistToStorage(record);
53
+ emitWarning(record);
54
+ return record;
55
+ }
56
+ function handlePersistenceWarningResponse(response) {
57
+ var _a2;
58
+ if (!isBrowser() || !response || typeof response !== "object") return;
59
+ const warning = response.persistenceWarning;
60
+ if (!warning) return;
61
+ const distributionId = warning.distributionId || response.distributionId || "unknown";
62
+ const exportJson = (_a2 = response.exportJson) != null ? _a2 : warning.exportJson;
63
+ const reason = warning.reason || "persist_distribution_failed";
64
+ const message = warning.message || "We were unable to save your distribution draft. Download the JSON to avoid data loss.";
65
+ const key = warning.id || `${distributionId}:${reason}:${Date.now()}`;
66
+ recordPersistenceWarning({
67
+ id: key,
68
+ distributionId,
69
+ reason,
70
+ message,
71
+ detail: warning.detail,
72
+ exportJson
73
+ });
74
+ }
75
+ function loadPersistenceWarnings() {
76
+ if (!isBrowser()) return [];
77
+ const records = [];
78
+ try {
79
+ for (let i = 0; i < localStorage.length; i++) {
80
+ const key = localStorage.key(i);
81
+ if (!key || !key.startsWith(STORAGE_PREFIX)) continue;
82
+ const raw = localStorage.getItem(key);
83
+ if (!raw) continue;
84
+ try {
85
+ const parsed = JSON.parse(raw);
86
+ if (parsed && typeof parsed === "object") {
87
+ records.push(parsed);
88
+ }
89
+ } catch (e) {
90
+ }
91
+ }
92
+ } catch (error) {
93
+ console.error("[sync:persistence-warning] Failed to load warnings", error);
94
+ }
95
+ return records.sort((a, b) => b.createdAt - a.createdAt);
96
+ }
97
+ function clearPersistenceWarning(id) {
98
+ if (!isBrowser()) return;
99
+ try {
100
+ localStorage.removeItem(`${STORAGE_PREFIX}${id}`);
101
+ } catch (e) {
102
+ }
103
+ }
104
+
105
+ // src/v1/core/http.ts
106
+ var FALLBACK_BASE_PATH = "/api/v1/fractals-sync";
107
+ var _a, _b;
108
+ var ENV_BASE_PATH = typeof process !== "undefined" && (((_a = process.env) == null ? void 0 : _a.NEXT_PUBLIC_SYNC_PATH) || ((_b = process.env) == null ? void 0 : _b.NEXT_PUBLIC_FRACTALS_SYNC_PATH)) || void 0;
109
+ var DEFAULT_BASE_PATH = sanitizeBasePath(ENV_BASE_PATH || FALLBACK_BASE_PATH);
110
+ function resolveRequestConfig(options) {
111
+ return {
112
+ basePath: sanitizeBasePath((options == null ? void 0 : options.basePath) || DEFAULT_BASE_PATH),
113
+ fetcher: resolveFetcher(options == null ? void 0 : options.fetcher)
114
+ };
115
+ }
116
+ var SyncReactError = class extends Error {
117
+ constructor(status, code, details) {
118
+ super(code || `Sync request failed with status ${status}`);
119
+ this.status = status;
120
+ this.code = code;
121
+ this.details = details;
122
+ this.name = "SyncReactError";
123
+ }
124
+ };
125
+ async function requestJSON(config, path, init) {
126
+ var _a2;
127
+ const url = buildUrl(config.basePath, path);
128
+ const requestInit = prepareInit(init);
129
+ requestInit.credentials = (_a2 = requestInit.credentials) != null ? _a2 : isRelativeUrl(url) ? "include" : void 0;
130
+ const response = await config.fetcher(url, requestInit);
131
+ const payload = await parseResponseBody(response);
132
+ if (!response.ok) {
133
+ const errorCode = typeof payload === "object" && payload && "error" in payload ? String(payload.error) : void 0;
134
+ throw new SyncReactError(response.status, errorCode, payload);
135
+ }
136
+ return payload;
137
+ }
138
+ function resolveFetcher(custom) {
139
+ if (custom) return custom;
140
+ if (typeof fetch === "function") return fetch.bind(globalThis);
141
+ throw new Error("Global fetch is not available. Provide a fetcher via Sync configuration.");
142
+ }
143
+ function sanitizeBasePath(path) {
144
+ if (!path) return FALLBACK_BASE_PATH;
145
+ const trimmed = path.trim();
146
+ if (!trimmed || trimmed === "/") return "/";
147
+ return trimmed.replace(/\/+$/, "");
148
+ }
149
+ function buildUrl(basePath, path) {
150
+ if (path && isAbsoluteUrl(path)) return path;
151
+ const normalizedBase = sanitizeBasePath(basePath);
152
+ const suffix = path ? `/${path.replace(/^\/+/, "")}` : "";
153
+ if (!normalizedBase || normalizedBase === "/") {
154
+ return suffix ? suffix : normalizedBase;
155
+ }
156
+ return `${normalizedBase}${suffix}`;
157
+ }
158
+ function isAbsoluteUrl(path) {
159
+ return /^https?:\/\//i.test(path);
160
+ }
161
+ function isRelativeUrl(path) {
162
+ return !isAbsoluteUrl(path);
163
+ }
164
+ function prepareInit(init) {
165
+ const finalInit = __spreadValues({}, init);
166
+ if ((init == null ? void 0 : init.headers) instanceof Headers) {
167
+ const cloned = new Headers(init.headers);
168
+ if (!cloned.has("content-type")) cloned.set("content-type", "application/json");
169
+ finalInit.headers = cloned;
170
+ return finalInit;
171
+ }
172
+ const headers = new Headers(init == null ? void 0 : init.headers);
173
+ if (!headers.has("content-type")) {
174
+ headers.set("content-type", "application/json");
175
+ }
176
+ finalInit.headers = headers;
177
+ return finalInit;
178
+ }
179
+ async function parseResponseBody(response) {
180
+ if (response.status === 204) return void 0;
181
+ const text = await response.text();
182
+ if (!text) return void 0;
183
+ try {
184
+ return JSON.parse(text);
185
+ } catch (e) {
186
+ return text;
187
+ }
188
+ }
189
+
190
+ // src/v1/core/api.ts
191
+ async function buildDistributionTransaction(input, options) {
192
+ const config = resolveRequestConfig(options);
193
+ const path = (input == null ? void 0 : input.distributionId) ? `/distributions/${encodeURIComponent(input.distributionId)}/create-transaction` : "/distributions/create-transaction";
194
+ const payload = await requestJSON(config, path, {
195
+ method: "POST",
196
+ body: JSON.stringify(input)
197
+ });
198
+ handlePersistenceWarningResponse(payload);
199
+ return payload;
200
+ }
201
+ async function commitDistributionSignature(input, options) {
202
+ const distributionId = input == null ? void 0 : input.distributionId;
203
+ if (!distributionId) {
204
+ throw new SyncReactError(400, "distribution_id_required");
205
+ }
206
+ const config = resolveRequestConfig(options);
207
+ const _a2 = input, { distributionId: _unused } = _a2, body = __objRest(_a2, ["distributionId"]);
208
+ return requestJSON(
209
+ config,
210
+ `/distributions/${encodeURIComponent(distributionId)}/commit`,
211
+ {
212
+ method: "POST",
213
+ body: JSON.stringify(body)
214
+ }
215
+ );
216
+ }
217
+ async function prepareDistributionDraft(input, options) {
218
+ const config = resolveRequestConfig(options);
219
+ return requestJSON(config, "/distributions/prepare", {
220
+ method: "POST",
221
+ body: JSON.stringify(input)
222
+ });
223
+ }
224
+
225
+ export {
226
+ MEMO_PROGRAM_ID,
227
+ XNET_2022_MINT,
228
+ DEFAULT_RPC_ENDPOINT,
229
+ DISTRIBUTION_MEMO_PREFIX,
230
+ buildDistributionMemoTag,
231
+ assertTruthy,
232
+ PERSISTENCE_WARNING_EVENT,
233
+ recordPersistenceWarning,
234
+ handlePersistenceWarningResponse,
235
+ loadPersistenceWarnings,
236
+ clearPersistenceWarning,
237
+ DEFAULT_BASE_PATH,
238
+ resolveRequestConfig,
239
+ SyncReactError,
240
+ requestJSON,
241
+ resolveFetcher,
242
+ sanitizeBasePath,
243
+ buildUrl,
244
+ isAbsoluteUrl,
245
+ isRelativeUrl,
246
+ buildDistributionTransaction,
247
+ commitDistributionSignature,
248
+ prepareDistributionDraft
249
+ };