@ecency/sdk 1.5.27 → 2.0.0

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