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