@stellar-snaps/sdk 0.1.0 → 0.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.
package/dist/index.mjs CHANGED
@@ -1,6 +1,236 @@
1
1
  import * as StellarSdk from '@stellar/stellar-sdk';
2
2
  import { isConnected, isAllowed, getNetwork, setAllowed, getAddress, signTransaction } from '@stellar/freighter-api';
3
3
 
4
+ // src/create-snap.ts
5
+ async function createSnap(options) {
6
+ const {
7
+ creator,
8
+ title,
9
+ destination,
10
+ description,
11
+ amount,
12
+ assetCode = "XLM",
13
+ assetIssuer,
14
+ memo,
15
+ memoType = "MEMO_TEXT",
16
+ network = "testnet",
17
+ imageUrl,
18
+ serverUrl = "https://stellarsnaps.com"
19
+ } = options;
20
+ if (!creator || creator.length !== 56 || !creator.startsWith("G")) {
21
+ throw new Error("Invalid creator address");
22
+ }
23
+ if (!title || title.trim().length === 0) {
24
+ throw new Error("Title is required");
25
+ }
26
+ if (!destination || destination.length !== 56 || !destination.startsWith("G")) {
27
+ throw new Error("Invalid destination address");
28
+ }
29
+ if (assetCode !== "XLM" && !assetIssuer) {
30
+ throw new Error("Asset issuer is required for non-XLM assets");
31
+ }
32
+ const body = {
33
+ creator,
34
+ title,
35
+ destination,
36
+ description,
37
+ amount,
38
+ assetCode,
39
+ assetIssuer,
40
+ memo,
41
+ memoType,
42
+ network,
43
+ imageUrl
44
+ };
45
+ const response = await fetch(`${serverUrl}/api/snaps`, {
46
+ method: "POST",
47
+ headers: {
48
+ "Content-Type": "application/json"
49
+ },
50
+ body: JSON.stringify(body)
51
+ });
52
+ if (!response.ok) {
53
+ const error = await response.json().catch(() => ({ error: "Unknown error" }));
54
+ throw new Error(error.error || `Failed to create snap: ${response.status}`);
55
+ }
56
+ const snap = await response.json();
57
+ return {
58
+ id: snap.id,
59
+ url: `${serverUrl}/s/${snap.id}`,
60
+ snap
61
+ };
62
+ }
63
+ async function getSnap(id, options = {}) {
64
+ const { serverUrl = "https://stellarsnaps.com" } = options;
65
+ const response = await fetch(`${serverUrl}/api/snaps/${id}`);
66
+ if (response.status === 404) {
67
+ return null;
68
+ }
69
+ if (!response.ok) {
70
+ throw new Error(`Failed to fetch snap: ${response.status}`);
71
+ }
72
+ return response.json();
73
+ }
74
+ async function listSnaps(creator, options = {}) {
75
+ const { serverUrl = "https://stellarsnaps.com" } = options;
76
+ const response = await fetch(`${serverUrl}/api/snaps?creator=${encodeURIComponent(creator)}`);
77
+ if (!response.ok) {
78
+ throw new Error(`Failed to list snaps: ${response.status}`);
79
+ }
80
+ return response.json();
81
+ }
82
+ async function deleteSnap(id, options = {}) {
83
+ const { serverUrl = "https://stellarsnaps.com" } = options;
84
+ const response = await fetch(`${serverUrl}/api/snaps/${id}`, {
85
+ method: "DELETE"
86
+ });
87
+ if (!response.ok && response.status !== 404) {
88
+ throw new Error(`Failed to delete snap: ${response.status}`);
89
+ }
90
+ }
91
+
92
+ // src/snap-id.ts
93
+ var ALPHABET = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
94
+ function generateSnapId(length = 8) {
95
+ let id = "";
96
+ const randomValues = new Uint8Array(length);
97
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
98
+ crypto.getRandomValues(randomValues);
99
+ } else {
100
+ for (let i = 0; i < length; i++) {
101
+ randomValues[i] = Math.floor(Math.random() * 256);
102
+ }
103
+ }
104
+ for (let i = 0; i < length; i++) {
105
+ id += ALPHABET[randomValues[i] % ALPHABET.length];
106
+ }
107
+ return id;
108
+ }
109
+ function isValidSnapId(id) {
110
+ if (!id || typeof id !== "string") return false;
111
+ if (id.length < 4 || id.length > 32) return false;
112
+ return /^[a-zA-Z0-9_-]+$/.test(id);
113
+ }
114
+ function extractSnapId(url, patterns = ["/s/", "/snap/", "/pay/"]) {
115
+ try {
116
+ const parsed = new URL(url);
117
+ const path = parsed.pathname;
118
+ for (const pattern of patterns) {
119
+ const index = path.indexOf(pattern);
120
+ if (index !== -1) {
121
+ const idStart = index + pattern.length;
122
+ const remaining = path.slice(idStart);
123
+ const match = remaining.match(/^([a-zA-Z0-9_-]+)/);
124
+ if (match && isValidSnapId(match[1])) {
125
+ return match[1];
126
+ }
127
+ }
128
+ }
129
+ return null;
130
+ } catch {
131
+ return null;
132
+ }
133
+ }
134
+
135
+ // src/schema.ts
136
+ function validateSnapInput(input) {
137
+ if (!input.creator || input.creator.length !== 56 || !input.creator.startsWith("G")) {
138
+ throw new Error("Invalid creator address");
139
+ }
140
+ if (!input.destination || input.destination.length !== 56 || !input.destination.startsWith("G")) {
141
+ throw new Error("Invalid destination address");
142
+ }
143
+ if (!input.title || input.title.trim().length === 0) {
144
+ throw new Error("Title is required");
145
+ }
146
+ if (input.title.length > 100) {
147
+ throw new Error("Title must be 100 characters or less");
148
+ }
149
+ if (input.description && input.description.length > 500) {
150
+ throw new Error("Description must be 500 characters or less");
151
+ }
152
+ if (input.assetCode && input.assetCode !== "XLM" && !input.assetIssuer) {
153
+ throw new Error("Asset issuer is required for non-XLM assets");
154
+ }
155
+ if (input.assetIssuer && (input.assetIssuer.length !== 56 || !input.assetIssuer.startsWith("G"))) {
156
+ throw new Error("Invalid asset issuer address");
157
+ }
158
+ if (input.amount) {
159
+ const amountNum = parseFloat(input.amount);
160
+ if (isNaN(amountNum) || amountNum <= 0) {
161
+ throw new Error("Amount must be a positive number");
162
+ }
163
+ }
164
+ if (input.network && !["public", "testnet"].includes(input.network)) {
165
+ throw new Error('Network must be "public" or "testnet"');
166
+ }
167
+ if (input.memoType && !["MEMO_TEXT", "MEMO_ID", "MEMO_HASH", "MEMO_RETURN"].includes(input.memoType)) {
168
+ throw new Error("Invalid memo type");
169
+ }
170
+ }
171
+ function createSnapObject(id, input) {
172
+ validateSnapInput(input);
173
+ const now = (/* @__PURE__ */ new Date()).toISOString();
174
+ return {
175
+ id,
176
+ creator: input.creator,
177
+ title: input.title.trim(),
178
+ description: input.description?.trim() || null,
179
+ imageUrl: input.imageUrl || null,
180
+ destination: input.destination,
181
+ assetCode: input.assetCode || "XLM",
182
+ assetIssuer: input.assetIssuer || null,
183
+ amount: input.amount || null,
184
+ memo: input.memo || null,
185
+ memoType: input.memoType || "MEMO_TEXT",
186
+ network: input.network || "testnet",
187
+ createdAt: now,
188
+ updatedAt: now
189
+ };
190
+ }
191
+ var POSTGRES_SCHEMA = `
192
+ CREATE TABLE IF NOT EXISTS snaps (
193
+ id TEXT PRIMARY KEY,
194
+ creator TEXT NOT NULL,
195
+ title TEXT NOT NULL,
196
+ description TEXT,
197
+ image_url TEXT,
198
+ destination TEXT NOT NULL,
199
+ asset_code TEXT NOT NULL DEFAULT 'XLM',
200
+ asset_issuer TEXT,
201
+ amount TEXT,
202
+ memo TEXT,
203
+ memo_type TEXT NOT NULL DEFAULT 'MEMO_TEXT',
204
+ network TEXT NOT NULL DEFAULT 'testnet',
205
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
206
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
207
+ );
208
+
209
+ CREATE INDEX IF NOT EXISTS idx_snaps_creator ON snaps(creator);
210
+ CREATE INDEX IF NOT EXISTS idx_snaps_destination ON snaps(destination);
211
+ `;
212
+ var SQLITE_SCHEMA = `
213
+ CREATE TABLE IF NOT EXISTS snaps (
214
+ id TEXT PRIMARY KEY,
215
+ creator TEXT NOT NULL,
216
+ title TEXT NOT NULL,
217
+ description TEXT,
218
+ image_url TEXT,
219
+ destination TEXT NOT NULL,
220
+ asset_code TEXT NOT NULL DEFAULT 'XLM',
221
+ asset_issuer TEXT,
222
+ amount TEXT,
223
+ memo TEXT,
224
+ memo_type TEXT NOT NULL DEFAULT 'MEMO_TEXT',
225
+ network TEXT NOT NULL DEFAULT 'testnet',
226
+ created_at TEXT DEFAULT (datetime('now')),
227
+ updated_at TEXT DEFAULT (datetime('now'))
228
+ );
229
+
230
+ CREATE INDEX IF NOT EXISTS idx_snaps_creator ON snaps(creator);
231
+ CREATE INDEX IF NOT EXISTS idx_snaps_destination ON snaps(destination);
232
+ `;
233
+
4
234
  // src/create-payment-snap.ts
5
235
  var NETWORK_PASSPHRASES = {
6
236
  public: "Public Global Stellar Network ; September 2015",
@@ -456,6 +686,452 @@ function matchUrlToRule(pathname, rules) {
456
686
  return null;
457
687
  }
458
688
 
459
- export { HORIZON_URLS, InvalidAddressError, InvalidAmountError, InvalidAssetError, InvalidUriError, NETWORK_PASSPHRASES2 as NETWORK_PASSPHRASES, StellarSnapError, buildPaymentTransaction, connectFreighter, createAsset, createDiscoveryFile, createPaymentSnap, createTransactionSnap, getFreighterNetwork, isFreighterConnected, isValidAmount, isValidAssetCode, isValidStellarAddress, matchUrlToRule, parseSnapUri, signWithFreighter, submitTransaction, validateDiscoveryFile };
689
+ // src/url-resolver.ts
690
+ var SHORTENER_DOMAINS = [
691
+ "t.co",
692
+ "bit.ly",
693
+ "goo.gl",
694
+ "tinyurl.com",
695
+ "ow.ly",
696
+ "is.gd",
697
+ "buff.ly",
698
+ "adf.ly",
699
+ "bit.do",
700
+ "mcaf.ee",
701
+ "su.pr",
702
+ "twit.ac",
703
+ "tiny.cc",
704
+ "lnkd.in",
705
+ "db.tt",
706
+ "qr.ae",
707
+ "cur.lv",
708
+ "ity.im",
709
+ "q.gs",
710
+ "po.st",
711
+ "bc.vc",
712
+ "u.to",
713
+ "j.mp",
714
+ "buzurl.com",
715
+ "cutt.us",
716
+ "u.bb",
717
+ "yourls.org",
718
+ "x.co",
719
+ "prettylinkpro.com",
720
+ "viralurl.com",
721
+ "twitthis.com",
722
+ "shorturl.at",
723
+ "rb.gy",
724
+ "shorturl.com"
725
+ ];
726
+ function isShortenerUrl(url) {
727
+ try {
728
+ const parsed = new URL(url);
729
+ const domain = parsed.hostname.toLowerCase();
730
+ return SHORTENER_DOMAINS.some(
731
+ (shortener) => domain === shortener || domain.endsWith(`.${shortener}`)
732
+ );
733
+ } catch {
734
+ return false;
735
+ }
736
+ }
737
+ function extractDomain(url) {
738
+ try {
739
+ const parsed = new URL(url);
740
+ return parsed.hostname.toLowerCase();
741
+ } catch {
742
+ return "";
743
+ }
744
+ }
745
+ function extractPath(url) {
746
+ try {
747
+ const parsed = new URL(url);
748
+ return parsed.pathname;
749
+ } catch {
750
+ return "";
751
+ }
752
+ }
753
+ async function resolveUrl(url) {
754
+ const originalUrl = url;
755
+ const wasShortened = isShortenerUrl(url);
756
+ if (!wasShortened) {
757
+ return {
758
+ url,
759
+ domain: extractDomain(url),
760
+ originalUrl,
761
+ wasShortened: false
762
+ };
763
+ }
764
+ try {
765
+ const response = await fetch(url, {
766
+ method: "HEAD",
767
+ redirect: "follow"
768
+ });
769
+ const finalUrl = response.url;
770
+ return {
771
+ url: finalUrl,
772
+ domain: extractDomain(finalUrl),
773
+ originalUrl,
774
+ wasShortened: true
775
+ };
776
+ } catch (error) {
777
+ return {
778
+ url,
779
+ domain: extractDomain(url),
780
+ originalUrl,
781
+ wasShortened: true
782
+ };
783
+ }
784
+ }
785
+ async function resolveUrls(urls) {
786
+ return Promise.all(urls.map(resolveUrl));
787
+ }
788
+
789
+ // src/registry.ts
790
+ function createRegistry(domains = []) {
791
+ return {
792
+ domains,
793
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
794
+ version: "1.0.0"
795
+ };
796
+ }
797
+ function addDomain(registry, entry) {
798
+ const existing = registry.domains.findIndex((d) => d.domain === entry.domain);
799
+ const newDomains = existing >= 0 ? registry.domains.map((d, i) => i === existing ? entry : d) : [...registry.domains, entry];
800
+ return {
801
+ ...registry,
802
+ domains: newDomains,
803
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
804
+ };
805
+ }
806
+ function removeDomain(registry, domain) {
807
+ return {
808
+ ...registry,
809
+ domains: registry.domains.filter((d) => d.domain !== domain),
810
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
811
+ };
812
+ }
813
+ function getDomainStatus(registry, domain) {
814
+ const normalizedDomain = domain.toLowerCase().replace(/^www\./, "");
815
+ const entry = registry.domains.find(
816
+ (d) => d.domain.toLowerCase() === normalizedDomain
817
+ );
818
+ return entry || null;
819
+ }
820
+ function isDomainVerified(registry, domain) {
821
+ const entry = getDomainStatus(registry, domain);
822
+ return entry?.status === "verified";
823
+ }
824
+ function isDomainBlocked(registry, domain) {
825
+ const entry = getDomainStatus(registry, domain);
826
+ return entry?.status === "blocked";
827
+ }
828
+ function getVerifiedDomains(registry) {
829
+ return registry.domains.filter((d) => d.status === "verified");
830
+ }
831
+ function getBlockedDomains(registry) {
832
+ return registry.domains.filter((d) => d.status === "blocked");
833
+ }
834
+ function validateRegistry(registry) {
835
+ if (!registry || typeof registry !== "object") return false;
836
+ const r = registry;
837
+ if (!Array.isArray(r.domains)) return false;
838
+ if (typeof r.updatedAt !== "string") return false;
839
+ if (typeof r.version !== "string") return false;
840
+ return r.domains.every((d) => {
841
+ if (!d || typeof d !== "object") return false;
842
+ const entry = d;
843
+ return typeof entry.domain === "string" && ["verified", "unverified", "blocked"].includes(entry.status);
844
+ });
845
+ }
846
+
847
+ // src/explorer.ts
848
+ var EXPLORER_URLS = {
849
+ "stellar.expert": {
850
+ public: "https://stellar.expert/explorer/public",
851
+ testnet: "https://stellar.expert/explorer/testnet"
852
+ },
853
+ stellarchain: {
854
+ public: "https://stellarchain.io",
855
+ testnet: "https://testnet.stellarchain.io"
856
+ },
857
+ horizon: {
858
+ public: "https://horizon.stellar.org",
859
+ testnet: "https://horizon-testnet.stellar.org"
860
+ }
861
+ };
862
+ function getTransactionUrl(hash, network = "testnet", explorer = "stellar.expert") {
863
+ const baseUrl = EXPLORER_URLS[explorer][network];
864
+ switch (explorer) {
865
+ case "stellar.expert":
866
+ return `${baseUrl}/tx/${hash}`;
867
+ case "stellarchain":
868
+ return `${baseUrl}/transactions/${hash}`;
869
+ case "horizon":
870
+ return `${baseUrl}/transactions/${hash}`;
871
+ default:
872
+ return `${baseUrl}/tx/${hash}`;
873
+ }
874
+ }
875
+ function getAccountUrl(address, network = "testnet", explorer = "stellar.expert") {
876
+ const baseUrl = EXPLORER_URLS[explorer][network];
877
+ switch (explorer) {
878
+ case "stellar.expert":
879
+ return `${baseUrl}/account/${address}`;
880
+ case "stellarchain":
881
+ return `${baseUrl}/accounts/${address}`;
882
+ case "horizon":
883
+ return `${baseUrl}/accounts/${address}`;
884
+ default:
885
+ return `${baseUrl}/account/${address}`;
886
+ }
887
+ }
888
+ function getAssetUrl(code, issuer, network = "testnet", explorer = "stellar.expert") {
889
+ const baseUrl = EXPLORER_URLS[explorer][network];
890
+ switch (explorer) {
891
+ case "stellar.expert":
892
+ return `${baseUrl}/asset/${code}-${issuer}`;
893
+ case "stellarchain":
894
+ return `${baseUrl}/assets/${code}:${issuer}`;
895
+ case "horizon":
896
+ return `${baseUrl}/assets?asset_code=${code}&asset_issuer=${issuer}`;
897
+ default:
898
+ return `${baseUrl}/asset/${code}-${issuer}`;
899
+ }
900
+ }
901
+ function getOperationUrl(operationId, network = "testnet", explorer = "stellar.expert") {
902
+ const baseUrl = EXPLORER_URLS[explorer][network];
903
+ switch (explorer) {
904
+ case "stellar.expert":
905
+ return `${baseUrl}/op/${operationId}`;
906
+ case "stellarchain":
907
+ return `${baseUrl}/operations/${operationId}`;
908
+ case "horizon":
909
+ return `${baseUrl}/operations/${operationId}`;
910
+ default:
911
+ return `${baseUrl}/op/${operationId}`;
912
+ }
913
+ }
914
+
915
+ // src/meta-tags.ts
916
+ function generateMetaTags(metadata) {
917
+ const {
918
+ title,
919
+ description,
920
+ imageUrl,
921
+ amount,
922
+ assetCode = "XLM",
923
+ url,
924
+ siteName = "Stellar Snaps"
925
+ } = metadata;
926
+ const autoDescription = description || (amount ? `Pay ${amount} ${assetCode} - ${title}` : `Make a payment - ${title}`);
927
+ return {
928
+ og: {
929
+ "og:title": title,
930
+ "og:description": autoDescription,
931
+ "og:url": url,
932
+ "og:site_name": siteName,
933
+ "og:type": "website",
934
+ ...imageUrl && { "og:image": imageUrl }
935
+ },
936
+ twitter: {
937
+ "twitter:card": imageUrl ? "summary_large_image" : "summary",
938
+ "twitter:title": title,
939
+ "twitter:description": autoDescription,
940
+ ...imageUrl && { "twitter:image": imageUrl }
941
+ },
942
+ standard: {
943
+ title: `${title} | ${siteName}`,
944
+ description: autoDescription
945
+ }
946
+ };
947
+ }
948
+ function metaTagsToHtml(tags) {
949
+ const lines = [];
950
+ if (tags.standard.title) {
951
+ lines.push(`<title>${escapeHtml(tags.standard.title)}</title>`);
952
+ }
953
+ if (tags.standard.description) {
954
+ lines.push(
955
+ `<meta name="description" content="${escapeHtml(tags.standard.description)}" />`
956
+ );
957
+ }
958
+ for (const [property, content] of Object.entries(tags.og)) {
959
+ lines.push(
960
+ `<meta property="${escapeHtml(property)}" content="${escapeHtml(content)}" />`
961
+ );
962
+ }
963
+ for (const [name, content] of Object.entries(tags.twitter)) {
964
+ lines.push(
965
+ `<meta name="${escapeHtml(name)}" content="${escapeHtml(content)}" />`
966
+ );
967
+ }
968
+ return lines.join("\n");
969
+ }
970
+ function escapeHtml(str) {
971
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
972
+ }
973
+ function generateJsonLd(metadata) {
974
+ const { title, description, amount, assetCode = "XLM", url, imageUrl } = metadata;
975
+ return {
976
+ "@context": "https://schema.org",
977
+ "@type": "PaymentService",
978
+ name: title,
979
+ description: description || `Pay ${amount || "any amount"} ${assetCode}`,
980
+ url,
981
+ ...imageUrl && { image: imageUrl },
982
+ ...amount && {
983
+ offers: {
984
+ "@type": "Offer",
985
+ price: amount,
986
+ priceCurrency: assetCode
987
+ }
988
+ }
989
+ };
990
+ }
991
+
992
+ // src/server.ts
993
+ var CORS_HEADERS = {
994
+ "Access-Control-Allow-Origin": "*",
995
+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
996
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
997
+ "Access-Control-Max-Age": "86400"
998
+ };
999
+ var CACHE_HEADERS = {
1000
+ /** No caching */
1001
+ none: {
1002
+ "Cache-Control": "no-store, no-cache, must-revalidate"
1003
+ },
1004
+ /** Short cache (1 minute) */
1005
+ short: {
1006
+ "Cache-Control": "public, max-age=60, stale-while-revalidate=30"
1007
+ },
1008
+ /** Medium cache (5 minutes) */
1009
+ medium: {
1010
+ "Cache-Control": "public, max-age=300, stale-while-revalidate=60"
1011
+ },
1012
+ /** Long cache (1 hour) */
1013
+ long: {
1014
+ "Cache-Control": "public, max-age=3600, stale-while-revalidate=300"
1015
+ },
1016
+ /** Immutable (1 year) */
1017
+ immutable: {
1018
+ "Cache-Control": "public, max-age=31536000, immutable"
1019
+ }
1020
+ };
1021
+ function successResponse(data) {
1022
+ return {
1023
+ success: true,
1024
+ data
1025
+ };
1026
+ }
1027
+ function errorResponse(message, code) {
1028
+ return {
1029
+ success: false,
1030
+ error: message,
1031
+ code
1032
+ };
1033
+ }
1034
+ function validateRequired(body, fields) {
1035
+ for (const field of fields) {
1036
+ if (body[field] === void 0 || body[field] === null || body[field] === "") {
1037
+ throw new Error(`Missing required field: ${field}`);
1038
+ }
1039
+ }
1040
+ }
1041
+ function parseQueryParams(url) {
1042
+ try {
1043
+ const parsed = new URL(url);
1044
+ const params = {};
1045
+ parsed.searchParams.forEach((value, key) => {
1046
+ params[key] = value;
1047
+ });
1048
+ return params;
1049
+ } catch {
1050
+ return {};
1051
+ }
1052
+ }
1053
+ function buildUrl(base, params) {
1054
+ const url = new URL(base);
1055
+ for (const [key, value] of Object.entries(params)) {
1056
+ if (value !== void 0) {
1057
+ url.searchParams.set(key, value);
1058
+ }
1059
+ }
1060
+ return url.toString();
1061
+ }
1062
+ function createRateLimiter(options) {
1063
+ const buckets = /* @__PURE__ */ new Map();
1064
+ return {
1065
+ /**
1066
+ * Checks if a key is within rate limits.
1067
+ * Returns true if allowed, false if rate limited.
1068
+ */
1069
+ check(key) {
1070
+ const now = Date.now();
1071
+ const bucket = buckets.get(key);
1072
+ if (bucket && bucket.resetAt <= now) {
1073
+ buckets.delete(key);
1074
+ }
1075
+ const current = buckets.get(key);
1076
+ if (!current) {
1077
+ buckets.set(key, {
1078
+ count: 1,
1079
+ resetAt: now + options.windowMs
1080
+ });
1081
+ return true;
1082
+ }
1083
+ if (current.count >= options.maxRequests) {
1084
+ return false;
1085
+ }
1086
+ current.count++;
1087
+ return true;
1088
+ },
1089
+ /**
1090
+ * Gets remaining requests for a key.
1091
+ */
1092
+ remaining(key) {
1093
+ const bucket = buckets.get(key);
1094
+ if (!bucket || bucket.resetAt <= Date.now()) {
1095
+ return options.maxRequests;
1096
+ }
1097
+ return Math.max(0, options.maxRequests - bucket.count);
1098
+ },
1099
+ /**
1100
+ * Resets the limiter for a key.
1101
+ */
1102
+ reset(key) {
1103
+ buckets.delete(key);
1104
+ },
1105
+ /**
1106
+ * Clears all rate limit data.
1107
+ */
1108
+ clear() {
1109
+ buckets.clear();
1110
+ }
1111
+ };
1112
+ }
1113
+ function parseAddress(input) {
1114
+ const trimmed = input.trim();
1115
+ if (trimmed.includes("*")) {
1116
+ return {
1117
+ address: trimmed,
1118
+ federation: trimmed
1119
+ };
1120
+ }
1121
+ if (trimmed.startsWith("M") && trimmed.length === 69) {
1122
+ return {
1123
+ address: trimmed,
1124
+ muxedId: trimmed
1125
+ };
1126
+ }
1127
+ if (trimmed.startsWith("G") && trimmed.length === 56) {
1128
+ return {
1129
+ address: trimmed
1130
+ };
1131
+ }
1132
+ throw new Error("Invalid address format");
1133
+ }
1134
+
1135
+ export { CACHE_HEADERS, CORS_HEADERS, EXPLORER_URLS, HORIZON_URLS, InvalidAddressError, InvalidAmountError, InvalidAssetError, InvalidUriError, NETWORK_PASSPHRASES2 as NETWORK_PASSPHRASES, POSTGRES_SCHEMA, SHORTENER_DOMAINS, SQLITE_SCHEMA, StellarSnapError, addDomain, buildPaymentTransaction, buildUrl, connectFreighter, createAsset, createDiscoveryFile, createPaymentSnap, createRateLimiter, createRegistry, createSnap, createSnapObject, createTransactionSnap, deleteSnap, errorResponse, extractDomain, extractPath, extractSnapId, generateJsonLd, generateMetaTags, generateSnapId, getAccountUrl, getAssetUrl, getBlockedDomains, getDomainStatus, getFreighterNetwork, getOperationUrl, getSnap, getTransactionUrl, getVerifiedDomains, isDomainBlocked, isDomainVerified, isFreighterConnected, isShortenerUrl, isValidAmount, isValidAssetCode, isValidSnapId, isValidStellarAddress, listSnaps, matchUrlToRule, metaTagsToHtml, parseAddress, parseQueryParams, parseSnapUri, removeDomain, resolveUrl, resolveUrls, signWithFreighter, submitTransaction, successResponse, validateDiscoveryFile, validateRegistry, validateRequired, validateSnapInput };
460
1136
  //# sourceMappingURL=index.mjs.map
461
1137
  //# sourceMappingURL=index.mjs.map