@ecency/sdk 1.2.1 → 1.3.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.
@@ -0,0 +1,1648 @@
1
+ import { QueryClient, useQuery, useInfiniteQuery, useMutation, queryOptions, useQueryClient, infiniteQueryOptions } from '@tanstack/react-query';
2
+ import { Client, PrivateKey, cryptoUtils, RCAPI } from '@hiveio/dhive';
3
+ import hs from 'hivesigner';
4
+ import * as R from 'remeda';
5
+
6
+ var __defProp = Object.defineProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+
12
+ // src/modules/core/mock-storage.ts
13
+ var MockStorage = class {
14
+ length = 0;
15
+ clear() {
16
+ throw new Error("Method not implemented.");
17
+ }
18
+ getItem(key) {
19
+ return this[key];
20
+ }
21
+ key(index) {
22
+ return Object.keys(this)[index];
23
+ }
24
+ removeItem(key) {
25
+ delete this[key];
26
+ }
27
+ setItem(key, value) {
28
+ this[key] = value;
29
+ }
30
+ };
31
+ var CONFIG = {
32
+ privateApiHost: "https://ecency.com",
33
+ storage: typeof window === "undefined" ? new MockStorage() : window.localStorage,
34
+ storagePrefix: "ecency",
35
+ hiveClient: new Client(
36
+ [
37
+ "https://api.hive.blog",
38
+ "https://api.deathwing.me",
39
+ "https://rpc.mahdiyari.info",
40
+ "https://api.openhive.network",
41
+ "https://techcoderx.com",
42
+ "https://hive-api.arcange.eu",
43
+ "https://api.syncad.com",
44
+ "https://anyx.io",
45
+ "https://api.c0ff33a.uk",
46
+ "https://hiveapi.actifit.io",
47
+ "https://hive-api.3speak.tv"
48
+ ],
49
+ {
50
+ timeout: 2e3,
51
+ failoverThreshold: 2,
52
+ consoleOnFailover: true
53
+ }
54
+ ),
55
+ heliusApiKey: process.env.VITE_HELIUS_API_KEY,
56
+ queryClient: new QueryClient(),
57
+ plausibleHost: "https://pl.ecency.com",
58
+ spkNode: "https://spk.good-karma.xyz"
59
+ };
60
+ var ConfigManager;
61
+ ((ConfigManager2) => {
62
+ function setQueryClient(client) {
63
+ CONFIG.queryClient = client;
64
+ }
65
+ ConfigManager2.setQueryClient = setQueryClient;
66
+ })(ConfigManager || (ConfigManager = {}));
67
+
68
+ // src/modules/core/utils/decoder-encoder.ts
69
+ function encodeObj(o) {
70
+ return btoa(JSON.stringify(o));
71
+ }
72
+ function decodeObj(o) {
73
+ let dataToParse = atob(o);
74
+ if (dataToParse[0] !== "{") {
75
+ return void 0;
76
+ }
77
+ return JSON.parse(dataToParse);
78
+ }
79
+
80
+ // src/modules/core/utils/parse-asset.ts
81
+ var Symbol2 = /* @__PURE__ */ ((Symbol3) => {
82
+ Symbol3["HIVE"] = "HIVE";
83
+ Symbol3["HBD"] = "HBD";
84
+ Symbol3["VESTS"] = "VESTS";
85
+ Symbol3["SPK"] = "SPK";
86
+ return Symbol3;
87
+ })(Symbol2 || {});
88
+ var NaiMap = /* @__PURE__ */ ((NaiMap2) => {
89
+ NaiMap2["@@000000021"] = "HIVE";
90
+ NaiMap2["@@000000013"] = "HBD";
91
+ NaiMap2["@@000000037"] = "VESTS";
92
+ return NaiMap2;
93
+ })(NaiMap || {});
94
+ function parseAsset(sval) {
95
+ if (typeof sval === "string") {
96
+ const sp = sval.split(" ");
97
+ return {
98
+ amount: parseFloat(sp[0]),
99
+ // @ts-ignore
100
+ symbol: Symbol2[sp[1]]
101
+ };
102
+ } else {
103
+ return {
104
+ amount: parseFloat(sval.amount.toString()) / Math.pow(10, sval.precision),
105
+ // @ts-ignore
106
+ symbol: NaiMap[sval.nai]
107
+ };
108
+ }
109
+ }
110
+
111
+ // src/modules/core/utils/get-bound-fetch.ts
112
+ var cachedFetch;
113
+ function getBoundFetch() {
114
+ if (!cachedFetch) {
115
+ if (typeof globalThis.fetch !== "function") {
116
+ throw new Error("[Ecency][SDK] - global fetch is not available");
117
+ }
118
+ cachedFetch = globalThis.fetch.bind(globalThis);
119
+ }
120
+ return cachedFetch;
121
+ }
122
+
123
+ // src/modules/core/storage.ts
124
+ var getUser = (username) => {
125
+ try {
126
+ const raw = CONFIG.storage.getItem(
127
+ CONFIG.storagePrefix + "_user_" + username
128
+ );
129
+ return decodeObj(JSON.parse(raw));
130
+ } catch (e) {
131
+ console.error(e);
132
+ return void 0;
133
+ }
134
+ };
135
+ var getAccessToken = (username) => getUser(username) && getUser(username).accessToken;
136
+ var getPostingKey = (username) => getUser(username) && getUser(username).postingKey;
137
+ var getLoginType = (username) => getUser(username) && getUser(username).loginType;
138
+ var getRefreshToken = (username) => getUser(username) && getUser(username).refreshToken;
139
+
140
+ // src/modules/keychain/keychain.ts
141
+ var keychain_exports = {};
142
+ __export(keychain_exports, {
143
+ broadcast: () => broadcast,
144
+ customJson: () => customJson,
145
+ handshake: () => handshake
146
+ });
147
+ function handshake() {
148
+ return new Promise((resolve) => {
149
+ window.hive_keychain?.requestHandshake(() => {
150
+ resolve();
151
+ });
152
+ });
153
+ }
154
+ var broadcast = (account, operations, key, rpc = null) => new Promise((resolve, reject) => {
155
+ window.hive_keychain?.requestBroadcast(
156
+ account,
157
+ operations,
158
+ key,
159
+ (resp) => {
160
+ if (!resp.success) {
161
+ reject({ message: "Operation cancelled" });
162
+ }
163
+ resolve(resp);
164
+ },
165
+ rpc
166
+ );
167
+ });
168
+ var customJson = (account, id, key, json, display_msg, rpc = null) => new Promise((resolve, reject) => {
169
+ window.hive_keychain?.requestCustomJson(
170
+ account,
171
+ id,
172
+ key,
173
+ json,
174
+ display_msg,
175
+ (resp) => {
176
+ if (!resp.success) {
177
+ reject({ message: "Operation cancelled" });
178
+ }
179
+ resolve(resp);
180
+ },
181
+ rpc
182
+ );
183
+ });
184
+
185
+ // src/modules/core/mutations/use-broadcast-mutation.ts
186
+ function useBroadcastMutation(mutationKey = [], username, operations, onSuccess = () => {
187
+ }) {
188
+ return useMutation({
189
+ onSuccess,
190
+ mutationKey: [...mutationKey, username],
191
+ mutationFn: async (payload) => {
192
+ if (!username) {
193
+ throw new Error(
194
+ "[Core][Broadcast] Attempted to call broadcast API with anon user"
195
+ );
196
+ }
197
+ const postingKey = getPostingKey(username);
198
+ if (postingKey) {
199
+ const privateKey = PrivateKey.fromString(postingKey);
200
+ return CONFIG.hiveClient.broadcast.sendOperations(
201
+ operations(payload),
202
+ privateKey
203
+ );
204
+ }
205
+ const loginType = getLoginType(username);
206
+ if (loginType && loginType == "keychain") {
207
+ return keychain_exports.broadcast(
208
+ username,
209
+ operations(payload),
210
+ "Posting"
211
+ ).then((r) => r.result);
212
+ }
213
+ let token = getAccessToken(username);
214
+ if (token) {
215
+ const f = getBoundFetch();
216
+ const res = await f("https://hivesigner.com/api/broadcast", {
217
+ method: "POST",
218
+ headers: {
219
+ Authorization: token,
220
+ "Content-Type": "application/json",
221
+ Accept: "application/json"
222
+ },
223
+ body: JSON.stringify({ operations: operations(payload) })
224
+ });
225
+ if (!res.ok) {
226
+ const txt = await res.text().catch(() => "");
227
+ throw new Error(`[Hivesigner] ${res.status} ${res.statusText} ${txt}`);
228
+ }
229
+ const json = await res.json();
230
+ if (json?.errors) {
231
+ throw new Error(`[Hivesigner] ${JSON.stringify(json.errors)}`);
232
+ }
233
+ return json.result;
234
+ }
235
+ throw new Error(
236
+ "[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token"
237
+ );
238
+ }
239
+ });
240
+ }
241
+ async function broadcastJson(username, id, payload) {
242
+ if (!username) {
243
+ throw new Error(
244
+ "[Core][Broadcast] Attempted to call broadcast API with anon user"
245
+ );
246
+ }
247
+ const jjson = {
248
+ id,
249
+ required_auths: [],
250
+ required_posting_auths: [username],
251
+ json: JSON.stringify(payload)
252
+ };
253
+ const postingKey = getPostingKey(username);
254
+ if (postingKey) {
255
+ const privateKey = PrivateKey.fromString(postingKey);
256
+ return CONFIG.hiveClient.broadcast.json(
257
+ jjson,
258
+ privateKey
259
+ );
260
+ }
261
+ const loginType = getLoginType(username);
262
+ if (loginType && loginType == "keychain") {
263
+ return keychain_exports.broadcast(username, [["custom_json", jjson]], "Posting").then((r) => r.result);
264
+ }
265
+ let token = getAccessToken(username);
266
+ if (token) {
267
+ const response = await new hs.Client({
268
+ accessToken: token
269
+ }).customJson([], [username], id, JSON.stringify(payload));
270
+ return response.result;
271
+ }
272
+ throw new Error(
273
+ "[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token"
274
+ );
275
+ }
276
+ function makeQueryClient() {
277
+ return new QueryClient({
278
+ defaultOptions: {
279
+ queries: {
280
+ // With SSR, we usually want to set some default staleTime
281
+ // above 0 to avoid refetching immediately on the client
282
+ // staleTime: 60 * 1000,
283
+ refetchOnWindowFocus: false,
284
+ refetchOnMount: false
285
+ }
286
+ }
287
+ });
288
+ }
289
+ var getQueryClient = () => CONFIG.queryClient;
290
+ var EcencyQueriesManager;
291
+ ((EcencyQueriesManager2) => {
292
+ function getQueryData(queryKey) {
293
+ const queryClient = getQueryClient();
294
+ return queryClient.getQueryData(queryKey);
295
+ }
296
+ EcencyQueriesManager2.getQueryData = getQueryData;
297
+ function getInfiniteQueryData(queryKey) {
298
+ const queryClient = getQueryClient();
299
+ return queryClient.getQueryData(queryKey);
300
+ }
301
+ EcencyQueriesManager2.getInfiniteQueryData = getInfiniteQueryData;
302
+ async function prefetchQuery(options) {
303
+ const queryClient = getQueryClient();
304
+ await queryClient.prefetchQuery(options);
305
+ return getQueryData(options.queryKey);
306
+ }
307
+ EcencyQueriesManager2.prefetchQuery = prefetchQuery;
308
+ async function prefetchInfiniteQuery(options) {
309
+ const queryClient = getQueryClient();
310
+ await queryClient.prefetchInfiniteQuery(options);
311
+ return getInfiniteQueryData(options.queryKey);
312
+ }
313
+ EcencyQueriesManager2.prefetchInfiniteQuery = prefetchInfiniteQuery;
314
+ function generateClientServerQuery(options) {
315
+ return {
316
+ prefetch: () => prefetchQuery(options),
317
+ getData: () => getQueryData(options.queryKey),
318
+ useClientQuery: () => useQuery(options),
319
+ fetchAndGet: () => getQueryClient().fetchQuery(options)
320
+ };
321
+ }
322
+ EcencyQueriesManager2.generateClientServerQuery = generateClientServerQuery;
323
+ function generateClientServerInfiniteQuery(options) {
324
+ return {
325
+ prefetch: () => prefetchInfiniteQuery(options),
326
+ getData: () => getInfiniteQueryData(options.queryKey),
327
+ useClientQuery: () => useInfiniteQuery(options),
328
+ fetchAndGet: () => getQueryClient().fetchInfiniteQuery(options)
329
+ };
330
+ }
331
+ EcencyQueriesManager2.generateClientServerInfiniteQuery = generateClientServerInfiniteQuery;
332
+ })(EcencyQueriesManager || (EcencyQueriesManager = {}));
333
+ function getDynamicPropsQueryOptions() {
334
+ return queryOptions({
335
+ queryKey: ["core", "dynamic-props"],
336
+ refetchInterval: 6e4,
337
+ staleTime: 6e4,
338
+ refetchOnMount: true,
339
+ queryFn: async () => {
340
+ const globalDynamic = await CONFIG.hiveClient.database.getDynamicGlobalProperties().then((r) => ({
341
+ total_vesting_fund_hive: r.total_vesting_fund_hive || r.total_vesting_fund_steem,
342
+ total_vesting_shares: r.total_vesting_shares,
343
+ hbd_print_rate: r.hbd_print_rate || r.sbd_print_rate,
344
+ hbd_interest_rate: r.hbd_interest_rate,
345
+ head_block_number: r.head_block_number,
346
+ vesting_reward_percent: r.vesting_reward_percent,
347
+ virtual_supply: r.virtual_supply
348
+ }));
349
+ const feedHistory = await CONFIG.hiveClient.database.call("get_feed_history");
350
+ const chainProps = await CONFIG.hiveClient.database.call(
351
+ "get_chain_properties"
352
+ );
353
+ const rewardFund = await CONFIG.hiveClient.database.call(
354
+ "get_reward_fund",
355
+ ["post"]
356
+ );
357
+ const hivePerMVests = parseAsset(globalDynamic.total_vesting_fund_hive).amount / parseAsset(globalDynamic.total_vesting_shares).amount * 1e6;
358
+ const base = parseAsset(feedHistory.current_median_history.base).amount;
359
+ const quote = parseAsset(feedHistory.current_median_history.quote).amount;
360
+ const fundRecentClaims = parseFloat(rewardFund.recent_claims);
361
+ const fundRewardBalance = parseAsset(rewardFund.reward_balance).amount;
362
+ const hbdPrintRate = globalDynamic.hbd_print_rate;
363
+ const hbdInterestRate = globalDynamic.hbd_interest_rate;
364
+ const headBlock = globalDynamic.head_block_number;
365
+ const totalVestingFund = parseAsset(
366
+ globalDynamic.total_vesting_fund_hive
367
+ ).amount;
368
+ const totalVestingShares = parseAsset(
369
+ globalDynamic.total_vesting_shares
370
+ ).amount;
371
+ const virtualSupply = parseAsset(globalDynamic.virtual_supply).amount;
372
+ const vestingRewardPercent = globalDynamic.vesting_reward_percent;
373
+ const accountCreationFee = chainProps.account_creation_fee;
374
+ return {
375
+ hivePerMVests,
376
+ base,
377
+ quote,
378
+ fundRecentClaims,
379
+ fundRewardBalance,
380
+ hbdPrintRate,
381
+ hbdInterestRate,
382
+ headBlock,
383
+ totalVestingFund,
384
+ totalVestingShares,
385
+ virtualSupply,
386
+ vestingRewardPercent,
387
+ accountCreationFee
388
+ };
389
+ }
390
+ });
391
+ }
392
+ function getAccountFullQueryOptions(username) {
393
+ return queryOptions({
394
+ queryKey: ["get-account-full", username],
395
+ queryFn: async () => {
396
+ if (!username) {
397
+ throw new Error("[SDK] Username is empty");
398
+ }
399
+ const response = await CONFIG.hiveClient.database.getAccounts([
400
+ username
401
+ ]);
402
+ if (!response[0]) {
403
+ throw new Error("[SDK] No account with given username");
404
+ }
405
+ let profile = {};
406
+ try {
407
+ profile = JSON.parse(response[0].posting_json_metadata).profile;
408
+ } catch (e) {
409
+ }
410
+ let follow_stats;
411
+ try {
412
+ follow_stats = await CONFIG.hiveClient.database.call(
413
+ "get_follow_count",
414
+ [username]
415
+ );
416
+ } catch (e) {
417
+ }
418
+ let reputationValue = 0;
419
+ try {
420
+ const reputation = await CONFIG.hiveClient.call(
421
+ "condenser_api",
422
+ "get_account_reputations",
423
+ [username, 1]
424
+ );
425
+ reputationValue = reputation[0]?.reputation ?? 0;
426
+ } catch (e) {
427
+ }
428
+ return {
429
+ name: response[0].name,
430
+ owner: response[0].owner,
431
+ active: response[0].active,
432
+ posting: response[0].posting,
433
+ memo_key: response[0].memo_key,
434
+ post_count: response[0].post_count,
435
+ created: response[0].created,
436
+ posting_json_metadata: response[0].posting_json_metadata,
437
+ last_vote_time: response[0].last_vote_time,
438
+ last_post: response[0].last_post,
439
+ json_metadata: response[0].json_metadata,
440
+ reward_hive_balance: response[0].reward_hive_balance,
441
+ reward_hbd_balance: response[0].reward_hbd_balance,
442
+ reward_vesting_hive: response[0].reward_vesting_hive,
443
+ reward_vesting_balance: response[0].reward_vesting_balance,
444
+ balance: response[0].balance,
445
+ hbd_balance: response[0].hbd_balance,
446
+ savings_balance: response[0].savings_balance,
447
+ savings_hbd_balance: response[0].savings_hbd_balance,
448
+ savings_hbd_last_interest_payment: response[0].savings_hbd_last_interest_payment,
449
+ savings_hbd_seconds_last_update: response[0].savings_hbd_seconds_last_update,
450
+ savings_hbd_seconds: response[0].savings_hbd_seconds,
451
+ next_vesting_withdrawal: response[0].next_vesting_withdrawal,
452
+ pending_claimed_accounts: response[0].pending_claimed_accounts,
453
+ vesting_shares: response[0].vesting_shares,
454
+ delegated_vesting_shares: response[0].delegated_vesting_shares,
455
+ received_vesting_shares: response[0].received_vesting_shares,
456
+ vesting_withdraw_rate: response[0].vesting_withdraw_rate,
457
+ to_withdraw: response[0].to_withdraw,
458
+ withdrawn: response[0].withdrawn,
459
+ witness_votes: response[0].witness_votes,
460
+ proxy: response[0].proxy,
461
+ recovery_account: response[0].recovery_account,
462
+ proxied_vsf_votes: response[0].proxied_vsf_votes,
463
+ voting_manabar: response[0].voting_manabar,
464
+ voting_power: response[0].voting_power,
465
+ downvote_manabar: response[0].downvote_manabar,
466
+ follow_stats,
467
+ reputation: reputationValue,
468
+ profile
469
+ };
470
+ },
471
+ enabled: !!username,
472
+ staleTime: 6e4
473
+ });
474
+ }
475
+ function getSearchAccountsByUsernameQueryOptions(query, limit = 5, excludeList = []) {
476
+ return queryOptions({
477
+ queryKey: ["accounts", "search", query, excludeList],
478
+ enabled: !!query,
479
+ queryFn: async () => {
480
+ const response = await CONFIG.hiveClient.database.call(
481
+ "lookup_accounts",
482
+ [query, limit]
483
+ );
484
+ return response.filter(
485
+ (item) => excludeList.length > 0 ? !excludeList.includes(item) : true
486
+ );
487
+ }
488
+ });
489
+ }
490
+ function checkUsernameWalletsPendingQueryOptions(username) {
491
+ return queryOptions({
492
+ queryKey: ["accounts", "check-wallet-pending", username],
493
+ queryFn: async () => {
494
+ const fetchApi = getBoundFetch();
495
+ const response = await fetchApi(
496
+ CONFIG.privateApiHost + "/private-api/wallets-chkuser",
497
+ {
498
+ method: "POST",
499
+ headers: {
500
+ "Content-Type": "application/json"
501
+ },
502
+ body: JSON.stringify({
503
+ username
504
+ })
505
+ }
506
+ );
507
+ return await response.json();
508
+ },
509
+ enabled: !!username,
510
+ refetchOnMount: true
511
+ });
512
+ }
513
+ function getRelationshipBetweenAccountsQueryOptions(reference, target) {
514
+ return queryOptions({
515
+ queryKey: ["accounts", "relations", reference, target],
516
+ enabled: !!reference && !!target,
517
+ refetchOnMount: false,
518
+ refetchInterval: 36e5,
519
+ queryFn: async () => {
520
+ return await CONFIG.hiveClient.call(
521
+ "bridge",
522
+ "get_relationship_between_accounts",
523
+ [reference, target]
524
+ );
525
+ }
526
+ });
527
+ }
528
+ function getAccountSubscriptionsQueryOptions(username) {
529
+ return queryOptions({
530
+ queryKey: ["accounts", "subscriptions", username],
531
+ enabled: !!username,
532
+ queryFn: async () => {
533
+ const response = await CONFIG.hiveClient.call(
534
+ "bridge",
535
+ "list_all_subscriptions",
536
+ {
537
+ account: username
538
+ }
539
+ );
540
+ return response ?? [];
541
+ }
542
+ });
543
+ }
544
+ function getActiveAccountBookmarksQueryOptions(activeUsername) {
545
+ return queryOptions({
546
+ queryKey: ["accounts", "bookmarks", activeUsername],
547
+ enabled: !!activeUsername,
548
+ queryFn: async () => {
549
+ if (!activeUsername) {
550
+ throw new Error("[SDK][Accounts][Bookmarks] \u2013 no active user");
551
+ }
552
+ const fetchApi = getBoundFetch();
553
+ const response = await fetchApi(
554
+ CONFIG.privateApiHost + "/private-api/bookmarks",
555
+ {
556
+ method: "POST",
557
+ headers: {
558
+ "Content-Type": "application/json"
559
+ },
560
+ body: JSON.stringify({ code: getAccessToken(activeUsername) })
561
+ }
562
+ );
563
+ return await response.json();
564
+ }
565
+ });
566
+ }
567
+ function getActiveAccountFavouritesQueryOptions(activeUsername) {
568
+ return queryOptions({
569
+ queryKey: ["accounts", "favourites", activeUsername],
570
+ enabled: !!activeUsername,
571
+ queryFn: async () => {
572
+ if (!activeUsername) {
573
+ throw new Error("[SDK][Accounts][Favourites] \u2013 no active user");
574
+ }
575
+ const fetchApi = getBoundFetch();
576
+ const response = await fetchApi(
577
+ CONFIG.privateApiHost + "/private-api/favorites",
578
+ {
579
+ method: "POST",
580
+ headers: {
581
+ "Content-Type": "application/json"
582
+ },
583
+ body: JSON.stringify({ code: getAccessToken(activeUsername) })
584
+ }
585
+ );
586
+ return await response.json();
587
+ }
588
+ });
589
+ }
590
+ function getAccountRecoveriesQueryOptions(username) {
591
+ return queryOptions({
592
+ enabled: !!username,
593
+ queryKey: ["accounts", "recoveries", username],
594
+ queryFn: async () => {
595
+ const fetchApi = getBoundFetch();
596
+ const response = await fetchApi(
597
+ CONFIG.privateApiHost + "/private-api/recoveries",
598
+ {
599
+ method: "POST",
600
+ headers: {
601
+ "Content-Type": "application/json"
602
+ },
603
+ body: JSON.stringify({ code: getAccessToken(username) })
604
+ }
605
+ );
606
+ return response.json();
607
+ }
608
+ });
609
+ }
610
+ function getAccountPendingRecoveryQueryOptions(username) {
611
+ return queryOptions({
612
+ enabled: !!username,
613
+ queryKey: ["accounts", "recoveries", username, "pending-request"],
614
+ queryFn: () => CONFIG.hiveClient.call(
615
+ "database_api",
616
+ "find_change_recovery_account_requests",
617
+ { accounts: [username] }
618
+ )
619
+ });
620
+ }
621
+ function sanitizeTokens(tokens) {
622
+ return tokens?.map(({ meta, ...rest }) => {
623
+ if (!meta || typeof meta !== "object") {
624
+ return { ...rest, meta };
625
+ }
626
+ const { privateKey, username, ...safeMeta } = meta;
627
+ return { ...rest, meta: safeMeta };
628
+ });
629
+ }
630
+ function getBuiltProfile({
631
+ profile,
632
+ tokens,
633
+ data
634
+ }) {
635
+ const metadata = R.pipe(
636
+ JSON.parse(data?.posting_json_metadata || "{}").profile,
637
+ R.mergeDeep(profile ?? {})
638
+ );
639
+ if (tokens && tokens.length > 0) {
640
+ metadata.tokens = tokens;
641
+ }
642
+ metadata.tokens = sanitizeTokens(metadata.tokens);
643
+ return metadata;
644
+ }
645
+ function useAccountUpdate(username) {
646
+ const queryClient = useQueryClient();
647
+ const { data } = useQuery(getAccountFullQueryOptions(username));
648
+ return useBroadcastMutation(
649
+ ["accounts", "update"],
650
+ username,
651
+ (payload) => {
652
+ if (!data) {
653
+ throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");
654
+ }
655
+ return [
656
+ [
657
+ "account_update2",
658
+ {
659
+ account: username,
660
+ json_metadata: "",
661
+ extensions: [],
662
+ posting_json_metadata: JSON.stringify({
663
+ profile: getBuiltProfile({ ...payload, data })
664
+ })
665
+ }
666
+ ]
667
+ ];
668
+ },
669
+ (_, variables) => queryClient.setQueryData(
670
+ getAccountFullQueryOptions(username).queryKey,
671
+ (data2) => {
672
+ if (!data2) {
673
+ return data2;
674
+ }
675
+ const obj = R.clone(data2);
676
+ obj.profile = getBuiltProfile({ ...variables, data: data2 });
677
+ return obj;
678
+ }
679
+ )
680
+ );
681
+ }
682
+ function useAccountRelationsUpdate(reference, target, onSuccess, onError) {
683
+ return useMutation({
684
+ mutationKey: ["accounts", "relation", "update", reference, target],
685
+ mutationFn: async (kind) => {
686
+ const relationsQuery = getRelationshipBetweenAccountsQueryOptions(
687
+ reference,
688
+ target
689
+ );
690
+ await getQueryClient().prefetchQuery(relationsQuery);
691
+ const actualRelation = getQueryClient().getQueryData(
692
+ relationsQuery.queryKey
693
+ );
694
+ await broadcastJson(reference, "follow", [
695
+ "follow",
696
+ {
697
+ follower: reference,
698
+ following: target,
699
+ what: [
700
+ ...kind === "toggle-ignore" && !actualRelation?.ignores ? ["ignore"] : [],
701
+ ...kind === "toggle-follow" && !actualRelation?.follows ? ["blog"] : []
702
+ ]
703
+ }
704
+ ]);
705
+ return {
706
+ ...actualRelation,
707
+ ignores: kind === "toggle-ignore" ? !actualRelation?.ignores : actualRelation?.ignores,
708
+ follows: kind === "toggle-follow" ? !actualRelation?.follows : actualRelation?.follows
709
+ };
710
+ },
711
+ onError,
712
+ onSuccess(data) {
713
+ onSuccess(data);
714
+ getQueryClient().setQueryData(
715
+ ["accounts", "relations", reference, target],
716
+ data
717
+ );
718
+ }
719
+ });
720
+ }
721
+ function useBookmarkAdd(username, onSuccess, onError) {
722
+ return useMutation({
723
+ mutationKey: ["accounts", "bookmarks", "add", username],
724
+ mutationFn: async ({ author, permlink }) => {
725
+ if (!username) {
726
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
727
+ }
728
+ const fetchApi = getBoundFetch();
729
+ const response = await fetchApi(
730
+ CONFIG.privateApiHost + "/private-api/bookmarks-add",
731
+ {
732
+ method: "POST",
733
+ headers: {
734
+ "Content-Type": "application/json"
735
+ },
736
+ body: JSON.stringify({
737
+ author,
738
+ permlink,
739
+ code: getAccessToken(username)
740
+ })
741
+ }
742
+ );
743
+ return response.json();
744
+ },
745
+ onSuccess: () => {
746
+ onSuccess();
747
+ getQueryClient().invalidateQueries({
748
+ queryKey: ["accounts", "bookmarks", username]
749
+ });
750
+ },
751
+ onError
752
+ });
753
+ }
754
+ function useBookmarkDelete(username, onSuccess, onError) {
755
+ return useMutation({
756
+ mutationKey: ["accounts", "bookmarks", "delete", username],
757
+ mutationFn: async (bookmarkId) => {
758
+ if (!username) {
759
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
760
+ }
761
+ const fetchApi = getBoundFetch();
762
+ const response = await fetchApi(
763
+ CONFIG.privateApiHost + "/private-api/bookmarks-delete",
764
+ {
765
+ method: "POST",
766
+ headers: {
767
+ "Content-Type": "application/json"
768
+ },
769
+ body: JSON.stringify({
770
+ id: bookmarkId,
771
+ code: getAccessToken(username)
772
+ })
773
+ }
774
+ );
775
+ return response.json();
776
+ },
777
+ onSuccess: () => {
778
+ onSuccess();
779
+ getQueryClient().invalidateQueries({
780
+ queryKey: ["accounts", "bookmarks", username]
781
+ });
782
+ },
783
+ onError
784
+ });
785
+ }
786
+ function useAccountFavouriteAdd(username, onSuccess, onError) {
787
+ return useMutation({
788
+ mutationKey: ["accounts", "favourites", "add", username],
789
+ mutationFn: async (account) => {
790
+ if (!username) {
791
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
792
+ }
793
+ const fetchApi = getBoundFetch();
794
+ const response = await fetchApi(
795
+ CONFIG.privateApiHost + "/private-api/favorites-add",
796
+ {
797
+ method: "POST",
798
+ headers: {
799
+ "Content-Type": "application/json"
800
+ },
801
+ body: JSON.stringify({
802
+ account,
803
+ code: getAccessToken(username)
804
+ })
805
+ }
806
+ );
807
+ return response.json();
808
+ },
809
+ onSuccess: () => {
810
+ onSuccess();
811
+ getQueryClient().invalidateQueries({
812
+ queryKey: ["accounts", "favourites", username]
813
+ });
814
+ },
815
+ onError
816
+ });
817
+ }
818
+ function useAccountFavouriteDelete(username, onSuccess, onError) {
819
+ return useMutation({
820
+ mutationKey: ["accounts", "favourites", "add", username],
821
+ mutationFn: async (account) => {
822
+ if (!username) {
823
+ throw new Error("[SDK][Account][Bookmarks] \u2013 no active user");
824
+ }
825
+ const fetchApi = getBoundFetch();
826
+ const response = await fetchApi(
827
+ CONFIG.privateApiHost + "/private-api/favorites-delete",
828
+ {
829
+ method: "POST",
830
+ headers: {
831
+ "Content-Type": "application/json"
832
+ },
833
+ body: JSON.stringify({
834
+ account,
835
+ code: getAccessToken(username)
836
+ })
837
+ }
838
+ );
839
+ return response.json();
840
+ },
841
+ onSuccess: () => {
842
+ onSuccess();
843
+ getQueryClient().invalidateQueries({
844
+ queryKey: ["accounts", "favourites", username]
845
+ });
846
+ },
847
+ onError
848
+ });
849
+ }
850
+ function dedupeAndSortKeyAuths(existing, additions) {
851
+ const merged = /* @__PURE__ */ new Map();
852
+ existing.forEach(([key, weight]) => {
853
+ merged.set(key.toString(), weight);
854
+ });
855
+ additions.forEach(([key, weight]) => {
856
+ merged.set(key.toString(), weight);
857
+ });
858
+ return Array.from(merged.entries()).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)).map(([key, weight]) => [key, weight]);
859
+ }
860
+ function useAccountUpdateKeyAuths(username, options) {
861
+ const { data: accountData } = useQuery(getAccountFullQueryOptions(username));
862
+ return useMutation({
863
+ mutationKey: ["accounts", "keys-update", username],
864
+ mutationFn: async ({ keys, keepCurrent = false, currentKey }) => {
865
+ if (!accountData) {
866
+ throw new Error(
867
+ "[SDK][Update password] \u2013 cannot update keys for anon user"
868
+ );
869
+ }
870
+ const prepareAuth = (keyName) => {
871
+ const auth = R.clone(accountData[keyName]);
872
+ auth.key_auths = dedupeAndSortKeyAuths(
873
+ keepCurrent ? auth.key_auths : [],
874
+ keys.map(
875
+ (values, i) => [values[keyName].createPublic().toString(), i + 1]
876
+ )
877
+ );
878
+ return auth;
879
+ };
880
+ return CONFIG.hiveClient.broadcast.updateAccount(
881
+ {
882
+ account: username,
883
+ json_metadata: accountData.json_metadata,
884
+ owner: prepareAuth("owner"),
885
+ active: prepareAuth("active"),
886
+ posting: prepareAuth("posting"),
887
+ memo_key: keepCurrent ? accountData.memo_key : keys[0].memo_key.createPublic().toString()
888
+ },
889
+ currentKey
890
+ );
891
+ },
892
+ ...options
893
+ });
894
+ }
895
+ function useAccountUpdatePassword(username, options) {
896
+ const { data: accountData } = useQuery(getAccountFullQueryOptions(username));
897
+ const { mutateAsync: updateKeys } = useAccountUpdateKeyAuths(username);
898
+ return useMutation({
899
+ mutationKey: ["accounts", "password-update", username],
900
+ mutationFn: async ({
901
+ newPassword,
902
+ currentPassword,
903
+ keepCurrent
904
+ }) => {
905
+ if (!accountData) {
906
+ throw new Error(
907
+ "[SDK][Update password] \u2013 cannot update password for anon user"
908
+ );
909
+ }
910
+ const currentKey = PrivateKey.fromLogin(
911
+ username,
912
+ currentPassword,
913
+ "owner"
914
+ );
915
+ return updateKeys({
916
+ currentKey,
917
+ keepCurrent,
918
+ keys: [
919
+ {
920
+ owner: PrivateKey.fromLogin(username, newPassword, "owner"),
921
+ active: PrivateKey.fromLogin(username, newPassword, "active"),
922
+ posting: PrivateKey.fromLogin(username, newPassword, "posting"),
923
+ memo_key: PrivateKey.fromLogin(username, newPassword, "memo")
924
+ }
925
+ ]
926
+ });
927
+ },
928
+ ...options
929
+ });
930
+ }
931
+ function useAccountRevokePosting(username, options) {
932
+ const queryClient = useQueryClient();
933
+ const { data } = useQuery(getAccountFullQueryOptions(username));
934
+ return useMutation({
935
+ mutationKey: ["accounts", "revoke-posting", data?.name],
936
+ mutationFn: async ({ accountName, type, key }) => {
937
+ if (!data) {
938
+ throw new Error(
939
+ "[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user"
940
+ );
941
+ }
942
+ const posting = R.pipe(
943
+ {},
944
+ R.mergeDeep(data.posting)
945
+ );
946
+ posting.account_auths = posting.account_auths.filter(
947
+ ([account]) => account !== accountName
948
+ );
949
+ const operationBody = {
950
+ account: data.name,
951
+ posting,
952
+ memo_key: data.memo_key,
953
+ json_metadata: data.json_metadata
954
+ };
955
+ if (type === "key" && key) {
956
+ return CONFIG.hiveClient.broadcast.updateAccount(operationBody, key);
957
+ } else if (type === "keychain") {
958
+ return keychain_exports.broadcast(
959
+ data.name,
960
+ [["account_update", operationBody]],
961
+ "Active"
962
+ );
963
+ } else {
964
+ const params = {
965
+ callback: `https://ecency.com/@${data.name}/permissions`
966
+ };
967
+ return hs.sendOperation(
968
+ ["account_update", operationBody],
969
+ params,
970
+ () => {
971
+ }
972
+ );
973
+ }
974
+ },
975
+ onError: options.onError,
976
+ onSuccess: (resp, payload, ctx) => {
977
+ options.onSuccess?.(resp, payload, ctx);
978
+ queryClient.setQueryData(
979
+ getAccountFullQueryOptions(username).queryKey,
980
+ (data2) => ({
981
+ ...data2,
982
+ posting: {
983
+ ...data2?.posting,
984
+ account_auths: data2?.posting?.account_auths?.filter(
985
+ ([account]) => account !== payload.accountName
986
+ ) ?? []
987
+ }
988
+ })
989
+ );
990
+ }
991
+ });
992
+ }
993
+ function useAccountUpdateRecovery(username, options) {
994
+ const { data } = useQuery(getAccountFullQueryOptions(username));
995
+ return useMutation({
996
+ mutationKey: ["accounts", "recovery", data?.name],
997
+ mutationFn: async ({ accountName, type, key, email }) => {
998
+ if (!data) {
999
+ throw new Error(
1000
+ "[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user"
1001
+ );
1002
+ }
1003
+ const operationBody = {
1004
+ account_to_recover: data.name,
1005
+ new_recovery_account: accountName,
1006
+ extensions: []
1007
+ };
1008
+ if (type === "ecency") {
1009
+ const fetchApi = getBoundFetch();
1010
+ return fetchApi(CONFIG.privateApiHost + "/private-api/recoveries-add", {
1011
+ method: "POST",
1012
+ body: JSON.stringify({
1013
+ code: getAccessToken(data.name),
1014
+ email,
1015
+ publicKeys: [
1016
+ ...data.owner.key_auths,
1017
+ ...data.active.key_auths,
1018
+ ...data.posting.key_auths,
1019
+ data.memo_key
1020
+ ]
1021
+ })
1022
+ });
1023
+ } else if (type === "key" && key) {
1024
+ return CONFIG.hiveClient.broadcast.sendOperations(
1025
+ [["change_recovery_account", operationBody]],
1026
+ key
1027
+ );
1028
+ } else if (type === "keychain") {
1029
+ return keychain_exports.broadcast(
1030
+ data.name,
1031
+ [["change_recovery_account", operationBody]],
1032
+ "Active"
1033
+ );
1034
+ } else {
1035
+ const params = {
1036
+ callback: `https://ecency.com/@${data.name}/permissions`
1037
+ };
1038
+ return hs.sendOperation(
1039
+ ["change_recovery_account", operationBody],
1040
+ params,
1041
+ () => {
1042
+ }
1043
+ );
1044
+ }
1045
+ },
1046
+ onError: options.onError,
1047
+ onSuccess: options.onSuccess
1048
+ });
1049
+ }
1050
+ function useAccountRevokeKey(username, options) {
1051
+ const { data: accountData } = useQuery(getAccountFullQueryOptions(username));
1052
+ return useMutation({
1053
+ mutationKey: ["accounts", "revoke-key", accountData?.name],
1054
+ mutationFn: async ({ currentKey, revokingKey }) => {
1055
+ if (!accountData) {
1056
+ throw new Error(
1057
+ "[SDK][Update password] \u2013 cannot update keys for anon user"
1058
+ );
1059
+ }
1060
+ const prepareAuth = (keyName) => {
1061
+ const auth = R.clone(accountData[keyName]);
1062
+ auth.key_auths = auth.key_auths.filter(
1063
+ ([key]) => key !== revokingKey.toString()
1064
+ );
1065
+ return auth;
1066
+ };
1067
+ return CONFIG.hiveClient.broadcast.updateAccount(
1068
+ {
1069
+ account: accountData.name,
1070
+ json_metadata: accountData.json_metadata,
1071
+ owner: prepareAuth("owner"),
1072
+ active: prepareAuth("active"),
1073
+ posting: prepareAuth("posting"),
1074
+ memo_key: accountData.memo_key
1075
+ },
1076
+ currentKey
1077
+ );
1078
+ },
1079
+ ...options
1080
+ });
1081
+ }
1082
+ function useSignOperationByKey(username) {
1083
+ return useMutation({
1084
+ mutationKey: ["operations", "sign", username],
1085
+ mutationFn: ({
1086
+ operation,
1087
+ keyOrSeed
1088
+ }) => {
1089
+ if (!username) {
1090
+ throw new Error("[Operations][Sign] \u2013 cannot sign op with anon user");
1091
+ }
1092
+ let privateKey;
1093
+ if (keyOrSeed.split(" ").length === 12) {
1094
+ privateKey = PrivateKey.fromLogin(username, keyOrSeed, "active");
1095
+ } else if (cryptoUtils.isWif(keyOrSeed)) {
1096
+ privateKey = PrivateKey.fromString(keyOrSeed);
1097
+ } else {
1098
+ privateKey = PrivateKey.from(keyOrSeed);
1099
+ }
1100
+ return CONFIG.hiveClient.broadcast.sendOperations(
1101
+ [operation],
1102
+ privateKey
1103
+ );
1104
+ }
1105
+ });
1106
+ }
1107
+ function useSignOperationByKeychain(username, keyType = "Active") {
1108
+ return useMutation({
1109
+ mutationKey: ["operations", "sign-keychain", username],
1110
+ mutationFn: ({ operation }) => {
1111
+ if (!username) {
1112
+ throw new Error(
1113
+ "[SDK][Keychain] \u2013\xA0cannot sign operation with anon user"
1114
+ );
1115
+ }
1116
+ return keychain_exports.broadcast(username, [operation], keyType);
1117
+ }
1118
+ });
1119
+ }
1120
+ function useSignOperationByHivesigner(callbackUri = "/") {
1121
+ return useMutation({
1122
+ mutationKey: ["operations", "sign-hivesigner", callbackUri],
1123
+ mutationFn: async ({ operation }) => {
1124
+ return hs.sendOperation(operation, { callback: callbackUri }, () => {
1125
+ });
1126
+ }
1127
+ });
1128
+ }
1129
+ function getChainPropertiesQueryOptions() {
1130
+ return queryOptions({
1131
+ queryKey: ["operations", "chain-properties"],
1132
+ queryFn: async () => {
1133
+ return await CONFIG.hiveClient.database.getChainProperties();
1134
+ }
1135
+ });
1136
+ }
1137
+ function getTrendingTagsQueryOptions(limit = 20) {
1138
+ return infiniteQueryOptions({
1139
+ queryKey: ["posts", "trending-tags"],
1140
+ queryFn: async ({ pageParam: { afterTag } }) => CONFIG.hiveClient.database.call("get_trending_tags", [afterTag, limit]).then(
1141
+ (tags) => tags.filter((x) => x.name !== "").filter((x) => !x.name.startsWith("hive-")).map((x) => x.name)
1142
+ ),
1143
+ initialPageParam: { afterTag: "" },
1144
+ getNextPageParam: (lastPage) => ({
1145
+ afterTag: lastPage?.[lastPage?.length - 1]
1146
+ }),
1147
+ staleTime: Infinity,
1148
+ refetchOnMount: true
1149
+ });
1150
+ }
1151
+ function getFragmentsQueryOptions(username) {
1152
+ return queryOptions({
1153
+ queryKey: ["posts", "fragments", username],
1154
+ queryFn: async () => {
1155
+ const fetchApi = getBoundFetch();
1156
+ const response = await fetchApi(
1157
+ CONFIG.privateApiHost + "/private-api/fragments",
1158
+ {
1159
+ method: "POST",
1160
+ body: JSON.stringify({
1161
+ code: getAccessToken(username)
1162
+ }),
1163
+ headers: {
1164
+ "Content-Type": "application/json"
1165
+ }
1166
+ }
1167
+ );
1168
+ return response.json();
1169
+ },
1170
+ enabled: !!username
1171
+ });
1172
+ }
1173
+ function getPromotedPostsQuery(type = "feed") {
1174
+ return queryOptions({
1175
+ queryKey: ["posts", "promoted", type],
1176
+ queryFn: async () => {
1177
+ const url = new URL(
1178
+ CONFIG.privateApiHost + "/private-api/promoted-entries"
1179
+ );
1180
+ if (type === "waves") {
1181
+ url.searchParams.append("short_content", "1");
1182
+ }
1183
+ const fetchApi = getBoundFetch();
1184
+ const response = await fetchApi(url.toString(), {
1185
+ method: "GET",
1186
+ headers: {
1187
+ "Content-Type": "application/json"
1188
+ }
1189
+ });
1190
+ const data = await response.json();
1191
+ return data;
1192
+ }
1193
+ });
1194
+ }
1195
+ function useAddFragment(username) {
1196
+ return useMutation({
1197
+ mutationKey: ["posts", "add-fragment", username],
1198
+ mutationFn: async ({ title, body }) => {
1199
+ const fetchApi = getBoundFetch();
1200
+ const response = await fetchApi(
1201
+ CONFIG.privateApiHost + "/private-api/fragments-add",
1202
+ {
1203
+ method: "POST",
1204
+ body: JSON.stringify({
1205
+ code: getAccessToken(username),
1206
+ title,
1207
+ body
1208
+ }),
1209
+ headers: {
1210
+ "Content-Type": "application/json"
1211
+ }
1212
+ }
1213
+ );
1214
+ return response.json();
1215
+ },
1216
+ onSuccess(response) {
1217
+ getQueryClient().setQueryData(
1218
+ getFragmentsQueryOptions(username).queryKey,
1219
+ (data) => [response, ...data ?? []]
1220
+ );
1221
+ }
1222
+ });
1223
+ }
1224
+ function useEditFragment(username, fragmentId) {
1225
+ return useMutation({
1226
+ mutationKey: ["posts", "edit-fragment", username, fragmentId],
1227
+ mutationFn: async ({ title, body }) => {
1228
+ const fetchApi = getBoundFetch();
1229
+ const response = await fetchApi(
1230
+ CONFIG.privateApiHost + "/private-api/fragments-update",
1231
+ {
1232
+ method: "POST",
1233
+ body: JSON.stringify({
1234
+ code: getAccessToken(username),
1235
+ id: fragmentId,
1236
+ title,
1237
+ body
1238
+ }),
1239
+ headers: {
1240
+ "Content-Type": "application/json"
1241
+ }
1242
+ }
1243
+ );
1244
+ return response.json();
1245
+ },
1246
+ onSuccess(response) {
1247
+ getQueryClient().setQueryData(
1248
+ getFragmentsQueryOptions(username).queryKey,
1249
+ (data) => {
1250
+ if (!data) {
1251
+ return [];
1252
+ }
1253
+ const index = data.findIndex(({ id }) => id === fragmentId);
1254
+ if (index >= 0) {
1255
+ data[index] = response;
1256
+ }
1257
+ return [...data];
1258
+ }
1259
+ );
1260
+ }
1261
+ });
1262
+ }
1263
+ function useRemoveFragment(username, fragmentId) {
1264
+ return useMutation({
1265
+ mutationKey: ["posts", "remove-fragment", username],
1266
+ mutationFn: async () => {
1267
+ const fetchApi = getBoundFetch();
1268
+ return fetchApi(CONFIG.privateApiHost + "/private-api/fragments-delete", {
1269
+ method: "POST",
1270
+ body: JSON.stringify({
1271
+ code: getAccessToken(username),
1272
+ id: fragmentId
1273
+ }),
1274
+ headers: {
1275
+ "Content-Type": "application/json"
1276
+ }
1277
+ });
1278
+ },
1279
+ onSuccess() {
1280
+ getQueryClient().setQueryData(
1281
+ getFragmentsQueryOptions(username).queryKey,
1282
+ (data) => [...data ?? []].filter(({ id }) => id !== fragmentId)
1283
+ );
1284
+ }
1285
+ });
1286
+ }
1287
+
1288
+ // src/modules/analytics/mutations/index.ts
1289
+ var mutations_exports = {};
1290
+ __export(mutations_exports, {
1291
+ useRecordActivity: () => useRecordActivity
1292
+ });
1293
+ function useRecordActivity(username, activityType) {
1294
+ return useMutation({
1295
+ mutationKey: ["analytics", activityType],
1296
+ mutationFn: async () => {
1297
+ if (!activityType) {
1298
+ throw new Error("[SDK][Analytics] \u2013 no activity type provided");
1299
+ }
1300
+ const fetchApi = getBoundFetch();
1301
+ await fetchApi(CONFIG.plausibleHost + "/api/event", {
1302
+ method: "POST",
1303
+ headers: {
1304
+ "Content-Type": "application/json"
1305
+ },
1306
+ body: JSON.stringify({
1307
+ name: activityType,
1308
+ url: window.location.href,
1309
+ domain: window.location.host,
1310
+ props: {
1311
+ username
1312
+ }
1313
+ })
1314
+ });
1315
+ }
1316
+ });
1317
+ }
1318
+
1319
+ // src/modules/integrations/3speak/queries/index.ts
1320
+ var queries_exports2 = {};
1321
+ __export(queries_exports2, {
1322
+ getAccountTokenQueryOptions: () => getAccountTokenQueryOptions,
1323
+ getAccountVideosQueryOptions: () => getAccountVideosQueryOptions
1324
+ });
1325
+
1326
+ // src/modules/integrations/hivesigner/queries/index.ts
1327
+ var queries_exports = {};
1328
+ __export(queries_exports, {
1329
+ getDecodeMemoQueryOptions: () => getDecodeMemoQueryOptions
1330
+ });
1331
+ function getDecodeMemoQueryOptions(username, memo) {
1332
+ return queryOptions({
1333
+ queryKey: ["integrations", "hivesigner", "decode-memo", username],
1334
+ queryFn: async () => {
1335
+ const accessToken = getAccessToken(username);
1336
+ if (accessToken) {
1337
+ const hsClient = new hs.Client({
1338
+ accessToken
1339
+ });
1340
+ return hsClient.decode(memo);
1341
+ }
1342
+ }
1343
+ });
1344
+ }
1345
+
1346
+ // src/modules/integrations/hivesigner/index.ts
1347
+ var HiveSignerIntegration = {
1348
+ queries: queries_exports
1349
+ };
1350
+
1351
+ // src/modules/integrations/3speak/queries/get-account-token-query-options.ts
1352
+ function getAccountTokenQueryOptions(username) {
1353
+ return queryOptions({
1354
+ queryKey: ["integrations", "3speak", "authenticate", username],
1355
+ enabled: !!username,
1356
+ queryFn: async () => {
1357
+ if (!username) {
1358
+ throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");
1359
+ }
1360
+ const fetchApi = getBoundFetch();
1361
+ const response = await fetchApi(
1362
+ `https://studio.3speak.tv/mobile/login?username=${username}&hivesigner=true`,
1363
+ {
1364
+ headers: {
1365
+ "Content-Type": "application/json"
1366
+ }
1367
+ }
1368
+ );
1369
+ const memoQueryOptions = HiveSignerIntegration.queries.getDecodeMemoQueryOptions(
1370
+ username,
1371
+ (await response.json()).memo
1372
+ );
1373
+ await getQueryClient().prefetchQuery(memoQueryOptions);
1374
+ const { memoDecoded } = getQueryClient().getQueryData(
1375
+ memoQueryOptions.queryKey
1376
+ );
1377
+ return memoDecoded.replace("#", "");
1378
+ }
1379
+ });
1380
+ }
1381
+ function getAccountVideosQueryOptions(username) {
1382
+ return queryOptions({
1383
+ queryKey: ["integrations", "3speak", "videos", username],
1384
+ enabled: !!username,
1385
+ queryFn: async () => {
1386
+ await getQueryClient().prefetchQuery(
1387
+ getAccountTokenQueryOptions(username)
1388
+ );
1389
+ const token = getQueryClient().getQueryData(
1390
+ getAccountTokenQueryOptions(username).queryKey
1391
+ );
1392
+ const fetchApi = getBoundFetch();
1393
+ const response = await fetchApi(
1394
+ `https://studio.3speak.tv/mobile/api/my-videos`,
1395
+ {
1396
+ headers: {
1397
+ "Content-Type": "application/json",
1398
+ Authorization: `Bearer ${token}`
1399
+ }
1400
+ }
1401
+ );
1402
+ return await response.json();
1403
+ }
1404
+ });
1405
+ }
1406
+
1407
+ // src/modules/integrations/3speak/index.ts
1408
+ var ThreeSpeakIntegration = {
1409
+ queries: queries_exports2
1410
+ };
1411
+ function getHivePoshLinksQueryOptions(username) {
1412
+ return queryOptions({
1413
+ queryKey: ["integrations", "hiveposh", "links", username],
1414
+ queryFn: async () => {
1415
+ const fetchApi = getBoundFetch();
1416
+ const response = await fetchApi(
1417
+ `https://hiveposh.com/api/v0/linked-accounts/${username}`,
1418
+ {
1419
+ headers: {
1420
+ "Content-Type": "application/json"
1421
+ }
1422
+ }
1423
+ );
1424
+ const data = await response.json();
1425
+ return {
1426
+ twitter: {
1427
+ username: data.twitter_username,
1428
+ profile: data.twitter_profile
1429
+ },
1430
+ reddit: {
1431
+ username: data.reddit_username,
1432
+ profile: data.reddit_profile
1433
+ }
1434
+ };
1435
+ }
1436
+ });
1437
+ }
1438
+ function getStatsQueryOptions({
1439
+ url,
1440
+ dimensions = [],
1441
+ metrics = ["visitors", "pageviews", "visit_duration"],
1442
+ enabled = true
1443
+ }) {
1444
+ return queryOptions({
1445
+ queryKey: ["integrations", "plausible", url, dimensions, metrics],
1446
+ queryFn: async () => {
1447
+ const fetchApi = getBoundFetch();
1448
+ const response = await fetchApi(`https://ecency.com/api/stats`, {
1449
+ method: "POST",
1450
+ body: JSON.stringify({
1451
+ metrics,
1452
+ url: encodeURIComponent(url),
1453
+ dimensions
1454
+ }),
1455
+ headers: {
1456
+ "Content-Type": "application/json"
1457
+ }
1458
+ });
1459
+ return await response.json();
1460
+ },
1461
+ enabled: !!url && enabled
1462
+ });
1463
+ }
1464
+ function getRcStatsQueryOptions() {
1465
+ return queryOptions({
1466
+ queryKey: ["resource-credits", "stats"],
1467
+ queryFn: async () => {
1468
+ const response = await CONFIG.hiveClient.call(
1469
+ "rc_api",
1470
+ "get_rc_stats",
1471
+ {}
1472
+ );
1473
+ return response.rc_stats;
1474
+ }
1475
+ });
1476
+ }
1477
+ function getAccountRcQueryOptions(username) {
1478
+ return queryOptions({
1479
+ queryKey: ["resource-credits", "account", username],
1480
+ queryFn: async () => {
1481
+ const rcClient = new RCAPI(CONFIG.hiveClient);
1482
+ return rcClient.findRCAccounts([username]);
1483
+ },
1484
+ enabled: !!username
1485
+ });
1486
+ }
1487
+ function getGameStatusCheckQueryOptions(username, gameType) {
1488
+ return queryOptions({
1489
+ queryKey: ["games", "status-check", gameType, username],
1490
+ enabled: !!username,
1491
+ queryFn: async () => {
1492
+ if (!username) {
1493
+ throw new Error("[SDK][Games] \u2013 anon user in status check");
1494
+ }
1495
+ const fetchApi = getBoundFetch();
1496
+ const response = await fetchApi(
1497
+ CONFIG.privateApiHost + "/private-api/get-game",
1498
+ {
1499
+ method: "POST",
1500
+ body: JSON.stringify({
1501
+ game_type: gameType,
1502
+ code: getAccessToken(username)
1503
+ }),
1504
+ headers: {
1505
+ "Content-Type": "application/json"
1506
+ }
1507
+ }
1508
+ );
1509
+ return await response.json();
1510
+ }
1511
+ });
1512
+ }
1513
+ function useGameClaim(username, gameType, key) {
1514
+ const { mutateAsync: recordActivity } = useRecordActivity(
1515
+ username,
1516
+ "spin-rolled"
1517
+ );
1518
+ return useMutation({
1519
+ mutationKey: ["games", "post", gameType, username],
1520
+ mutationFn: async () => {
1521
+ if (!username) {
1522
+ throw new Error("[SDK][Games] \u2013 anon user in game post");
1523
+ }
1524
+ const fetchApi = getBoundFetch();
1525
+ const response = await fetchApi(
1526
+ CONFIG.privateApiHost + "/private-api/post-game",
1527
+ {
1528
+ method: "POST",
1529
+ body: JSON.stringify({
1530
+ game_type: gameType,
1531
+ code: getAccessToken(username),
1532
+ key
1533
+ }),
1534
+ headers: {
1535
+ "Content-Type": "application/json"
1536
+ }
1537
+ }
1538
+ );
1539
+ return await response.json();
1540
+ },
1541
+ onSuccess() {
1542
+ recordActivity();
1543
+ }
1544
+ });
1545
+ }
1546
+ function getCommunitiesQueryOptions(sort, query, limit = 100, observer = void 0, enabled = true) {
1547
+ return queryOptions({
1548
+ queryKey: ["communities", "list", sort, query, limit],
1549
+ enabled,
1550
+ queryFn: async () => {
1551
+ const response = await CONFIG.hiveClient.call(
1552
+ "bridge",
1553
+ "list_communities",
1554
+ {
1555
+ last: "",
1556
+ limit,
1557
+ sort: sort === "hot" ? "rank" : sort,
1558
+ query: query ? query : null,
1559
+ observer
1560
+ }
1561
+ );
1562
+ return response ? sort === "hot" ? response.sort(() => Math.random() - 0.5) : response : [];
1563
+ }
1564
+ });
1565
+ }
1566
+ function getCommunityContextQueryOptions(username, communityName) {
1567
+ return queryOptions({
1568
+ queryKey: ["community", "context", username, communityName],
1569
+ enabled: !!username && !!communityName,
1570
+ queryFn: async () => {
1571
+ const response = await CONFIG.hiveClient.call(
1572
+ "bridge",
1573
+ "get_community_context",
1574
+ {
1575
+ account: username,
1576
+ name: communityName
1577
+ }
1578
+ );
1579
+ return {
1580
+ role: response?.role ?? "guest",
1581
+ subscribed: response?.subscribed ?? false
1582
+ };
1583
+ }
1584
+ });
1585
+ }
1586
+
1587
+ // src/modules/communities/types/community.ts
1588
+ var ROLES = /* @__PURE__ */ ((ROLES2) => {
1589
+ ROLES2["OWNER"] = "owner";
1590
+ ROLES2["ADMIN"] = "admin";
1591
+ ROLES2["MOD"] = "mod";
1592
+ ROLES2["MEMBER"] = "member";
1593
+ ROLES2["GUEST"] = "guest";
1594
+ ROLES2["MUTED"] = "muted";
1595
+ return ROLES2;
1596
+ })(ROLES || {});
1597
+ var roleMap = {
1598
+ ["owner" /* OWNER */]: [
1599
+ "admin" /* ADMIN */,
1600
+ "mod" /* MOD */,
1601
+ "member" /* MEMBER */,
1602
+ "guest" /* GUEST */,
1603
+ "muted" /* MUTED */
1604
+ ],
1605
+ ["admin" /* ADMIN */]: ["mod" /* MOD */, "member" /* MEMBER */, "guest" /* GUEST */, "muted" /* MUTED */],
1606
+ ["mod" /* MOD */]: ["member" /* MEMBER */, "guest" /* GUEST */, "muted" /* MUTED */]
1607
+ };
1608
+
1609
+ // src/modules/communities/utils/index.ts
1610
+ function getCommunityType(name, type_id) {
1611
+ if (name.startsWith("hive-3") || type_id === 3) return "Council";
1612
+ if (name.startsWith("hive-2") || type_id === 2) return "Journal";
1613
+ return "Topic";
1614
+ }
1615
+ function getCommunityPermissions({
1616
+ communityType,
1617
+ userRole,
1618
+ subscribed
1619
+ }) {
1620
+ const canPost = (() => {
1621
+ if (userRole === "muted" /* MUTED */) return false;
1622
+ if (communityType === "Topic") return true;
1623
+ return ["owner" /* OWNER */, "admin" /* ADMIN */, "mod" /* MOD */, "member" /* MEMBER */].includes(
1624
+ userRole
1625
+ );
1626
+ })();
1627
+ const canComment = (() => {
1628
+ if (userRole === "muted" /* MUTED */) return false;
1629
+ switch (communityType) {
1630
+ case "Topic":
1631
+ return true;
1632
+ case "Journal":
1633
+ return userRole !== "guest" /* GUEST */ || subscribed;
1634
+ case "Council":
1635
+ return canPost;
1636
+ }
1637
+ })();
1638
+ const isModerator = ["owner" /* OWNER */, "admin" /* ADMIN */, "mod" /* MOD */].includes(userRole);
1639
+ return {
1640
+ canPost,
1641
+ canComment,
1642
+ isModerator
1643
+ };
1644
+ }
1645
+
1646
+ export { CONFIG, ConfigManager, mutations_exports as EcencyAnalytics, EcencyQueriesManager, HiveSignerIntegration, keychain_exports as Keychain, NaiMap, ROLES, Symbol2 as Symbol, ThreeSpeakIntegration, broadcastJson, checkUsernameWalletsPendingQueryOptions, decodeObj, dedupeAndSortKeyAuths, encodeObj, getAccessToken, getAccountFullQueryOptions, getAccountPendingRecoveryQueryOptions, getAccountRcQueryOptions, getAccountRecoveriesQueryOptions, getAccountSubscriptionsQueryOptions, getActiveAccountBookmarksQueryOptions, getActiveAccountFavouritesQueryOptions, getBoundFetch, getChainPropertiesQueryOptions, getCommunitiesQueryOptions, getCommunityContextQueryOptions, getCommunityPermissions, getCommunityType, getDynamicPropsQueryOptions, getFragmentsQueryOptions, getGameStatusCheckQueryOptions, getHivePoshLinksQueryOptions, getLoginType, getPostingKey, getPromotedPostsQuery, getQueryClient, getRcStatsQueryOptions, getRefreshToken, getRelationshipBetweenAccountsQueryOptions, getSearchAccountsByUsernameQueryOptions, getStatsQueryOptions, getTrendingTagsQueryOptions, getUser, makeQueryClient, parseAsset, roleMap, useAccountFavouriteAdd, useAccountFavouriteDelete, useAccountRelationsUpdate, useAccountRevokeKey, useAccountRevokePosting, useAccountUpdate, useAccountUpdateKeyAuths, useAccountUpdatePassword, useAccountUpdateRecovery, useAddFragment, useBookmarkAdd, useBookmarkDelete, useBroadcastMutation, useEditFragment, useGameClaim, useRemoveFragment, useSignOperationByHivesigner, useSignOperationByKey, useSignOperationByKeychain };
1647
+ //# sourceMappingURL=index.mjs.map
1648
+ //# sourceMappingURL=index.mjs.map