finget-sdk 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Finget
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,90 @@
1
- # Temporary Holding Version
1
+ # finget-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ کلاینت رسمی **[فینگت](https://finget.ir)** برای **Node.js**، **JavaScript** و **TypeScript**: ورود بدون رمز و ارسال اعلان.
4
+
5
+ - وب‌سایت: [finget.ir](https://finget.ir)
6
+ - افزونه‌ها و SDKها: [finget.ir/plugins](https://finget.ir/plugins)
7
+ - مستندات API: [finget.ir/provider/panel/docs](https://finget.ir/provider/panel/docs)
8
+ - npm: [npmjs.com/package/finget-sdk](https://www.npmjs.com/package/finget-sdk)
9
+ - نیازمندی: **Node.js 18+** (native `fetch`)
10
+
11
+ ## نصب
12
+
13
+ ```bash
14
+ npm install finget-sdk
15
+ ```
16
+
17
+ ## شروع سریع
18
+
19
+ ```bash
20
+ export FINGET_API_KEY=fg_live_...
21
+ ```
22
+
23
+ ```ts
24
+ import { Client } from "finget-sdk";
25
+
26
+ const finget = Client.fromEnv();
27
+ // یا: new Client({ apiKey: process.env.FINGET_API_KEY! })
28
+
29
+ const { site } = await finget.getSite();
30
+ ```
31
+
32
+ ## ورود با فینگت
33
+
34
+ ```ts
35
+ import { Client } from "finget-sdk";
36
+
37
+ const finget = Client.fromEnv();
38
+ const clientId = process.env.FINGET_CLIENT_ID!;
39
+
40
+ // شروع ورود
41
+ const { url, state } = finget.loginUrl(clientId);
42
+ req.session.fingetState = state;
43
+ res.redirect(url);
44
+
45
+ // callback
46
+ const expected = req.session.fingetState;
47
+ delete req.session.fingetState;
48
+ if (!req.query.code || !expected || req.query.state !== expected) {
49
+ return res.redirect("/login");
50
+ }
51
+
52
+ const { user, isNew } = await finget.exchangeCode(String(req.query.code));
53
+ // حساب را با user.id پیدا یا بسازید
54
+ ```
55
+
56
+ ## ارسال اعلان
57
+
58
+ ```ts
59
+ await finget.sendNotification({
60
+ id: `order-${order.id}-shipped`,
61
+ kind: "notice",
62
+ title: "سفارش شما ارسال شد",
63
+ body: `سفارش ${order.id} تحویل پست شد.`,
64
+ link: { url: `https://shop.ir/orders/${order.id}`, label: "پیگیری سفارش" },
65
+ users: [user.fingetId],
66
+ });
67
+ ```
68
+
69
+ ## JavaScript (بدون TypeScript)
70
+
71
+ ```js
72
+ const { Client } = require("finget-sdk");
73
+ // یا: import { Client } from "finget-sdk";
74
+
75
+ const finget = new Client({ apiKey: process.env.FINGET_API_KEY });
76
+ ```
77
+
78
+ ## توسعهٔ محلی
79
+
80
+ ```ts
81
+ const finget = new Client({
82
+ apiKey: process.env.FINGET_API_KEY!,
83
+ baseUrl: "http://localhost:3001/api/v1",
84
+ authUrl: "http://localhost:5173/auth",
85
+ });
86
+ ```
87
+
88
+ ## مجوز
89
+
90
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ApiError: () => ApiError,
24
+ Client: () => Client,
25
+ DEFAULT_AUTH_URL: () => DEFAULT_AUTH_URL,
26
+ DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
27
+ FingetError: () => FingetError,
28
+ VERSION: () => VERSION
29
+ });
30
+ module.exports = __toCommonJS(index_exports);
31
+
32
+ // src/errors.ts
33
+ var FingetError = class extends Error {
34
+ constructor(message) {
35
+ super(message);
36
+ this.name = "FingetError";
37
+ }
38
+ };
39
+ var ApiError = class extends FingetError {
40
+ status;
41
+ errorCode;
42
+ body;
43
+ constructor(message, status, errorCode = null, body = {}) {
44
+ super(message);
45
+ this.name = "ApiError";
46
+ this.status = status;
47
+ this.errorCode = errorCode;
48
+ this.body = body;
49
+ }
50
+ };
51
+
52
+ // src/client.ts
53
+ var VERSION = "1.0.0";
54
+ var DEFAULT_BASE_URL = "https://finget.ir/api/v1";
55
+ var DEFAULT_AUTH_URL = "https://finget.ir/auth";
56
+ var Client = class _Client {
57
+ apiKey;
58
+ baseUrl;
59
+ authUrl;
60
+ timeoutMs;
61
+ constructor(options) {
62
+ const apiKey = options.apiKey.trim();
63
+ if (!apiKey) {
64
+ throw new FingetError("\u06A9\u0644\u06CC\u062F API \u0641\u06CC\u0646\u06AF\u062A \u062E\u0627\u0644\u06CC \u0627\u0633\u062A.");
65
+ }
66
+ const timeoutMs = options.timeoutMs ?? 2e4;
67
+ if (timeoutMs < 1) {
68
+ throw new FingetError("\u0645\u0647\u0644\u062A \u062F\u0631\u062E\u0648\u0627\u0633\u062A \u0628\u0627\u06CC\u062F \u062D\u062F\u0627\u0642\u0644 \u06F1 \u0645\u06CC\u0644\u06CC\u200C\u062B\u0627\u0646\u06CC\u0647 \u0628\u0627\u0634\u062F.");
69
+ }
70
+ this.apiKey = apiKey;
71
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
72
+ this.authUrl = (options.authUrl ?? DEFAULT_AUTH_URL).replace(/\/$/, "");
73
+ this.timeoutMs = timeoutMs;
74
+ }
75
+ /** از process.env.FINGET_API_KEY (و اختیاری FINGET_BASE_URL / FINGET_AUTH_URL). */
76
+ static fromEnv(apiKeyEnv = "FINGET_API_KEY") {
77
+ const key = process.env[apiKeyEnv];
78
+ if (!key?.trim()) {
79
+ throw new FingetError(`\u0645\u062A\u063A\u06CC\u0631 \u0645\u062D\u06CC\u0637\u06CC ${apiKeyEnv} \u062A\u0646\u0638\u06CC\u0645 \u0646\u0634\u062F\u0647 \u0627\u0633\u062A.`);
80
+ }
81
+ return new _Client({
82
+ apiKey: key,
83
+ baseUrl: process.env.FINGET_BASE_URL || void 0,
84
+ authUrl: process.env.FINGET_AUTH_URL || void 0
85
+ });
86
+ }
87
+ /** آزمودن کلید؛ مشخصات سایت صاحب کلید. */
88
+ async getSite() {
89
+ return this.request("GET", "/site");
90
+ }
91
+ /** کد یک‌بارمصرف callback را به اطلاعات کاربر تبدیل می‌کند. */
92
+ async exchangeCode(code) {
93
+ const trimmed = code.trim();
94
+ if (!trimmed) {
95
+ throw new FingetError("\u06A9\u062F \u0648\u0631\u0648\u062F (code) \u062E\u0627\u0644\u06CC \u0627\u0633\u062A.");
96
+ }
97
+ return this.request("POST", "/auth/token", { code: trimmed });
98
+ }
99
+ /** اطلاعات تازه‌ی کاربر وصل به سایت. */
100
+ async getUser(userId) {
101
+ const id = userId.trim();
102
+ if (!id) {
103
+ throw new FingetError("\u0634\u0646\u0627\u0633\u0647\u200C\u06CC \u06A9\u0627\u0631\u0628\u0631 \u062E\u0627\u0644\u06CC \u0627\u0633\u062A.");
104
+ }
105
+ return this.request("GET", `/users/${encodeURIComponent(id)}`);
106
+ }
107
+ /** ارسال اعلان به کاربران وصل سایت. */
108
+ async sendNotification(payload) {
109
+ return this.request("POST", "/notifications", payload, 201);
110
+ }
111
+ /** وضعیت یک پیام. */
112
+ async getNotification(notificationId) {
113
+ const id = notificationId.trim();
114
+ if (!id) {
115
+ throw new FingetError("\u0634\u0646\u0627\u0633\u0647\u200C\u06CC \u0627\u0639\u0644\u0627\u0646 \u062E\u0627\u0644\u06CC \u0627\u0633\u062A.");
116
+ }
117
+ return this.request("GET", `/notifications/${encodeURIComponent(id)}`);
118
+ }
119
+ /** رشته‌ی تصادفی امن برای پارامتر state ورود. */
120
+ createState(bytes = 16) {
121
+ if (bytes < 8) {
122
+ throw new FingetError("\u0637\u0648\u0644 state \u062E\u06CC\u0644\u06CC \u06A9\u0648\u062A\u0627\u0647 \u0627\u0633\u062A.");
123
+ }
124
+ const buf = new Uint8Array(bytes);
125
+ crypto.getRandomValues(buf);
126
+ return [...buf].map((b) => b.toString(16).padStart(2, "0")).join("");
127
+ }
128
+ /**
129
+ * آدرس دکمه‌ی «ورود با فینگت».
130
+ * اگر state ندهید ساخته می‌شود؛ همان را در نشست نگه دارید.
131
+ */
132
+ loginUrl(clientId, state) {
133
+ const id = clientId.trim();
134
+ if (!id) {
135
+ throw new FingetError("\u0634\u0646\u0627\u0633\u0647\u200C\u06CC \u0633\u0627\u06CC\u062A (client_id) \u062E\u0627\u0644\u06CC \u0627\u0633\u062A.");
136
+ }
137
+ const s = state ?? this.createState();
138
+ const url = new URL(this.authUrl);
139
+ url.searchParams.set("client_id", id);
140
+ url.searchParams.set("state", s);
141
+ return { url: url.toString(), state: s };
142
+ }
143
+ async request(method, path, body, okStatuses = 200) {
144
+ const ok = Array.isArray(okStatuses) ? okStatuses : [okStatuses];
145
+ const controller = new AbortController();
146
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
147
+ try {
148
+ const res = await fetch(`${this.baseUrl}${path}`, {
149
+ method,
150
+ redirect: "manual",
151
+ signal: controller.signal,
152
+ headers: {
153
+ Accept: "application/json",
154
+ Authorization: `Bearer ${this.apiKey}`,
155
+ "User-Agent": `finget-js/${VERSION}`,
156
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {}
157
+ },
158
+ body: body !== void 0 ? JSON.stringify(body) : void 0
159
+ });
160
+ let data = {};
161
+ const text = await res.text();
162
+ if (text) {
163
+ try {
164
+ const parsed = JSON.parse(text);
165
+ data = parsed && typeof parsed === "object" ? parsed : {};
166
+ } catch {
167
+ data = {};
168
+ }
169
+ }
170
+ if (!ok.includes(res.status)) {
171
+ const message = typeof data.message === "string" ? data.message : `\u062F\u0631\u062E\u0648\u0627\u0633\u062A \u0628\u0647 \u0641\u06CC\u0646\u06AF\u062A \u0646\u0627\u0645\u0648\u0641\u0642 \u0628\u0648\u062F (HTTP ${res.status}).`;
172
+ const code = typeof data.code === "string" ? data.code : null;
173
+ throw new ApiError(message, res.status, code, data);
174
+ }
175
+ return data;
176
+ } catch (err) {
177
+ if (err instanceof ApiError) {
178
+ throw err;
179
+ }
180
+ if (err instanceof Error && err.name === "AbortError") {
181
+ throw new ApiError("\u0645\u0647\u0644\u062A \u0627\u062A\u0635\u0627\u0644 \u0628\u0647 \u0641\u06CC\u0646\u06AF\u062A \u062A\u0645\u0627\u0645 \u0634\u062F.", 0);
182
+ }
183
+ const message = err instanceof Error ? err.message : "\u0627\u062A\u0635\u0627\u0644 \u0628\u0647 \u0641\u06CC\u0646\u06AF\u062A \u0628\u0631\u0642\u0631\u0627\u0631 \u0646\u0634\u062F.";
184
+ throw new ApiError(message, 0);
185
+ } finally {
186
+ clearTimeout(timer);
187
+ }
188
+ }
189
+ };
190
+ // Annotate the CommonJS export names for ESM import in node:
191
+ 0 && (module.exports = {
192
+ ApiError,
193
+ Client,
194
+ DEFAULT_AUTH_URL,
195
+ DEFAULT_BASE_URL,
196
+ FingetError,
197
+ VERSION
198
+ });
199
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/client.ts"],"sourcesContent":["export { Client, VERSION, DEFAULT_BASE_URL, DEFAULT_AUTH_URL } from \"./client.js\";\nexport { FingetError, ApiError } from \"./errors.js\";\nexport type {\n ClientOptions,\n FingetUser,\n SiteInfo,\n TokenResult,\n NotificationLink,\n NotificationCoupon,\n SendNotificationInput,\n NotificationResult,\n} from \"./types.js\";\n","/** خطای پایهٔ SDK فینگت. */\nexport class FingetError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FingetError\";\n }\n}\n\n/** پاسخ ناموفق API فینگت. */\nexport class ApiError extends FingetError {\n readonly status: number;\n readonly errorCode: string | null;\n readonly body: Record<string, unknown>;\n\n constructor(\n message: string,\n status: number,\n errorCode: string | null = null,\n body: Record<string, unknown> = {},\n ) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.errorCode = errorCode;\n this.body = body;\n }\n}\n","import { ApiError, FingetError } from \"./errors.js\";\nimport type {\n ClientOptions,\n NotificationResult,\n SendNotificationInput,\n SiteInfo,\n TokenResult,\n FingetUser,\n} from \"./types.js\";\n\nexport const VERSION = \"1.0.0\";\nexport const DEFAULT_BASE_URL = \"https://finget.ir/api/v1\";\nexport const DEFAULT_AUTH_URL = \"https://finget.ir/auth\";\n\n/**\n * کلاینت رسمی API عمومی فینگت (/api/v1).\n * کلید API را فقط سمت سرور نگه دارید.\n */\nexport class Client {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly authUrl: string;\n private readonly timeoutMs: number;\n\n constructor(options: ClientOptions) {\n const apiKey = options.apiKey.trim();\n if (!apiKey) {\n throw new FingetError(\"کلید API فینگت خالی است.\");\n }\n const timeoutMs = options.timeoutMs ?? 20_000;\n if (timeoutMs < 1) {\n throw new FingetError(\"مهلت درخواست باید حداقل ۱ میلی‌ثانیه باشد.\");\n }\n\n this.apiKey = apiKey;\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n this.authUrl = (options.authUrl ?? DEFAULT_AUTH_URL).replace(/\\/$/, \"\");\n this.timeoutMs = timeoutMs;\n }\n\n /** از process.env.FINGET_API_KEY (و اختیاری FINGET_BASE_URL / FINGET_AUTH_URL). */\n static fromEnv(apiKeyEnv = \"FINGET_API_KEY\"): Client {\n const key = process.env[apiKeyEnv];\n if (!key?.trim()) {\n throw new FingetError(`متغیر محیطی ${apiKeyEnv} تنظیم نشده است.`);\n }\n return new Client({\n apiKey: key,\n baseUrl: process.env.FINGET_BASE_URL || undefined,\n authUrl: process.env.FINGET_AUTH_URL || undefined,\n });\n }\n\n /** آزمودن کلید؛ مشخصات سایت صاحب کلید. */\n async getSite(): Promise<{ site: SiteInfo }> {\n return this.request(\"GET\", \"/site\");\n }\n\n /** کد یک‌بارمصرف callback را به اطلاعات کاربر تبدیل می‌کند. */\n async exchangeCode(code: string): Promise<TokenResult> {\n const trimmed = code.trim();\n if (!trimmed) {\n throw new FingetError(\"کد ورود (code) خالی است.\");\n }\n return this.request(\"POST\", \"/auth/token\", { code: trimmed });\n }\n\n /** اطلاعات تازه‌ی کاربر وصل به سایت. */\n async getUser(userId: string): Promise<{ user: FingetUser }> {\n const id = userId.trim();\n if (!id) {\n throw new FingetError(\"شناسه‌ی کاربر خالی است.\");\n }\n return this.request(\"GET\", `/users/${encodeURIComponent(id)}`);\n }\n\n /** ارسال اعلان به کاربران وصل سایت. */\n async sendNotification(payload: SendNotificationInput): Promise<NotificationResult> {\n return this.request(\"POST\", \"/notifications\", payload, 201);\n }\n\n /** وضعیت یک پیام. */\n async getNotification(notificationId: string): Promise<Record<string, unknown>> {\n const id = notificationId.trim();\n if (!id) {\n throw new FingetError(\"شناسه‌ی اعلان خالی است.\");\n }\n return this.request(\"GET\", `/notifications/${encodeURIComponent(id)}`);\n }\n\n /** رشته‌ی تصادفی امن برای پارامتر state ورود. */\n createState(bytes = 16): string {\n if (bytes < 8) {\n throw new FingetError(\"طول state خیلی کوتاه است.\");\n }\n const buf = new Uint8Array(bytes);\n crypto.getRandomValues(buf);\n return [...buf].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n }\n\n /**\n * آدرس دکمه‌ی «ورود با فینگت».\n * اگر state ندهید ساخته می‌شود؛ همان را در نشست نگه دارید.\n */\n loginUrl(clientId: string, state?: string): { url: string; state: string } {\n const id = clientId.trim();\n if (!id) {\n throw new FingetError(\"شناسه‌ی سایت (client_id) خالی است.\");\n }\n const s = state ?? this.createState();\n const url = new URL(this.authUrl);\n url.searchParams.set(\"client_id\", id);\n url.searchParams.set(\"state\", s);\n return { url: url.toString(), state: s };\n }\n\n private async request<T = Record<string, unknown>>(\n method: string,\n path: string,\n body?: unknown,\n okStatuses: number | number[] = 200,\n ): Promise<T> {\n const ok = Array.isArray(okStatuses) ? okStatuses : [okStatuses];\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const res = await fetch(`${this.baseUrl}${path}`, {\n method,\n redirect: \"manual\",\n signal: controller.signal,\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n \"User-Agent\": `finget-js/${VERSION}`,\n ...(body !== undefined ? { \"Content-Type\": \"application/json\" } : {}),\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n });\n\n let data: Record<string, unknown> = {};\n const text = await res.text();\n if (text) {\n try {\n const parsed: unknown = JSON.parse(text);\n data = parsed && typeof parsed === \"object\" ? (parsed as Record<string, unknown>) : {};\n } catch {\n data = {};\n }\n }\n\n if (!ok.includes(res.status)) {\n const message =\n typeof data.message === \"string\"\n ? data.message\n : `درخواست به فینگت ناموفق بود (HTTP ${res.status}).`;\n const code = typeof data.code === \"string\" ? data.code : null;\n throw new ApiError(message, res.status, code, data);\n }\n\n return data as T;\n } catch (err) {\n if (err instanceof ApiError) {\n throw err;\n }\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new ApiError(\"مهلت اتصال به فینگت تمام شد.\", 0);\n }\n const message = err instanceof Error ? err.message : \"اتصال به فینگت برقرار نشد.\";\n throw new ApiError(message, 0);\n } finally {\n clearTimeout(timer);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,WAAN,cAAuB,YAAY;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,SACA,QACA,YAA2B,MAC3B,OAAgC,CAAC,GACjC;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,YAAY;AACjB,SAAK,OAAO;AAAA,EACd;AACF;;;AChBO,IAAM,UAAU;AAChB,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AAMzB,IAAM,SAAN,MAAM,QAAO;AAAA,EACD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,SAAwB;AAClC,UAAM,SAAS,QAAQ,OAAO,KAAK;AACnC,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI,YAAY,0GAA0B;AAAA,IAClD;AACA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Q;AAAA,UACR,eAAe,UAAU,KAAK,MAAM;AAAA,UACpC,cAAc,aAAa,OAAO;AAAA,UAClC,GAAI,SAAS,SAAY,EAAE,gBAAgB,mBAAmB,IAAI,CAAC;AAAA,QACrE;AAAA,QACA,MAAM,SAAS,SAAY,KAAK,UAAU,IAAI,IAAI;AAAA,MACpD,CAAC;AAED,UAAI,OAAgC,CAAC;AACrC,YAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,UAAI,MAAM;AACR,YAAI;AACF,gBAAM,SAAkB,KAAK,MAAM,IAAI;AACvC,iBAAO,UAAU,OAAO,WAAW,WAAY,SAAqC,CAAC;AAAA,QACvF,QAAQ;AACN,iBAAO,CAAC;AAAA,QACV;AAAA,MACF;AAEA,UAAI,CAAC,GAAG,SAAS,IAAI,MAAM,GAAG;AAC5B,cAAM,UACJ,OAAO,KAAK,YAAY,WACpB,KAAK,UACL,wJAAqC,IAAI,MAAM;AACrD,cAAM,OAAO,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;AACzD,cAAM,IAAI,SAAS,SAAS,IAAI,QAAQ,MAAM,IAAI;AAAA,MACpD;AAEA,aAAO;AAAA,IACT,SAAS,KAAK;AACZ,UAAI,eAAe,UAAU;AAC3B,cAAM;AAAA,MACR;AACA,UAAI,eAAe,SAAS,IAAI,SAAS,cAAc;AACrD,cAAM,IAAI,SAAS,8IAAgC,CAAC;AAAA,MACtD;AACA,YAAM,UAAU,eAAe,QAAQ,IAAI,UAAU;AACrD,YAAM,IAAI,SAAS,SAAS,CAAC;AAAA,IAC/B,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,105 @@
1
+ type FingetUser = {
2
+ id: string;
3
+ name: string;
4
+ phone: string;
5
+ };
6
+ type SiteInfo = {
7
+ domain: string;
8
+ displayDomain: string;
9
+ name: string | null;
10
+ verifiedAt: string;
11
+ };
12
+ type TokenResult = {
13
+ user: FingetUser;
14
+ isNew: boolean;
15
+ };
16
+ type NotificationLink = {
17
+ url: string;
18
+ label?: string;
19
+ };
20
+ type NotificationCoupon = {
21
+ code: string;
22
+ note?: string;
23
+ expiresAt?: string;
24
+ };
25
+ type SendNotificationInput = {
26
+ title: string;
27
+ body?: string;
28
+ kind?: "notice" | "reminder" | "security" | "promo";
29
+ id?: string;
30
+ users?: string[];
31
+ audience?: "all";
32
+ link?: NotificationLink;
33
+ coupon?: NotificationCoupon;
34
+ };
35
+ type NotificationResult = {
36
+ notification: Record<string, unknown>;
37
+ skipped?: Record<string, number>;
38
+ duplicate?: boolean;
39
+ };
40
+ type ClientOptions = {
41
+ /** کلید API سایت (fg_live_…) — فقط سمت سرور */
42
+ apiKey: string;
43
+ /** پیش‌فرض: https://finget.ir/api/v1 */
44
+ baseUrl?: string;
45
+ /** پیش‌فرض: https://finget.ir/auth */
46
+ authUrl?: string;
47
+ /** مهلت درخواست بر حسب میلی‌ثانیه */
48
+ timeoutMs?: number;
49
+ };
50
+
51
+ declare const VERSION = "1.0.0";
52
+ declare const DEFAULT_BASE_URL = "https://finget.ir/api/v1";
53
+ declare const DEFAULT_AUTH_URL = "https://finget.ir/auth";
54
+ /**
55
+ * کلاینت رسمی API عمومی فینگت (/api/v1).
56
+ * کلید API را فقط سمت سرور نگه دارید.
57
+ */
58
+ declare class Client {
59
+ private readonly apiKey;
60
+ private readonly baseUrl;
61
+ private readonly authUrl;
62
+ private readonly timeoutMs;
63
+ constructor(options: ClientOptions);
64
+ /** از process.env.FINGET_API_KEY (و اختیاری FINGET_BASE_URL / FINGET_AUTH_URL). */
65
+ static fromEnv(apiKeyEnv?: string): Client;
66
+ /** آزمودن کلید؛ مشخصات سایت صاحب کلید. */
67
+ getSite(): Promise<{
68
+ site: SiteInfo;
69
+ }>;
70
+ /** کد یک‌بارمصرف callback را به اطلاعات کاربر تبدیل می‌کند. */
71
+ exchangeCode(code: string): Promise<TokenResult>;
72
+ /** اطلاعات تازه‌ی کاربر وصل به سایت. */
73
+ getUser(userId: string): Promise<{
74
+ user: FingetUser;
75
+ }>;
76
+ /** ارسال اعلان به کاربران وصل سایت. */
77
+ sendNotification(payload: SendNotificationInput): Promise<NotificationResult>;
78
+ /** وضعیت یک پیام. */
79
+ getNotification(notificationId: string): Promise<Record<string, unknown>>;
80
+ /** رشته‌ی تصادفی امن برای پارامتر state ورود. */
81
+ createState(bytes?: number): string;
82
+ /**
83
+ * آدرس دکمه‌ی «ورود با فینگت».
84
+ * اگر state ندهید ساخته می‌شود؛ همان را در نشست نگه دارید.
85
+ */
86
+ loginUrl(clientId: string, state?: string): {
87
+ url: string;
88
+ state: string;
89
+ };
90
+ private request;
91
+ }
92
+
93
+ /** خطای پایهٔ SDK فینگت. */
94
+ declare class FingetError extends Error {
95
+ constructor(message: string);
96
+ }
97
+ /** پاسخ ناموفق API فینگت. */
98
+ declare class ApiError extends FingetError {
99
+ readonly status: number;
100
+ readonly errorCode: string | null;
101
+ readonly body: Record<string, unknown>;
102
+ constructor(message: string, status: number, errorCode?: string | null, body?: Record<string, unknown>);
103
+ }
104
+
105
+ export { ApiError, Client, type ClientOptions, DEFAULT_AUTH_URL, DEFAULT_BASE_URL, FingetError, type FingetUser, type NotificationCoupon, type NotificationLink, type NotificationResult, type SendNotificationInput, type SiteInfo, type TokenResult, VERSION };
@@ -0,0 +1,105 @@
1
+ type FingetUser = {
2
+ id: string;
3
+ name: string;
4
+ phone: string;
5
+ };
6
+ type SiteInfo = {
7
+ domain: string;
8
+ displayDomain: string;
9
+ name: string | null;
10
+ verifiedAt: string;
11
+ };
12
+ type TokenResult = {
13
+ user: FingetUser;
14
+ isNew: boolean;
15
+ };
16
+ type NotificationLink = {
17
+ url: string;
18
+ label?: string;
19
+ };
20
+ type NotificationCoupon = {
21
+ code: string;
22
+ note?: string;
23
+ expiresAt?: string;
24
+ };
25
+ type SendNotificationInput = {
26
+ title: string;
27
+ body?: string;
28
+ kind?: "notice" | "reminder" | "security" | "promo";
29
+ id?: string;
30
+ users?: string[];
31
+ audience?: "all";
32
+ link?: NotificationLink;
33
+ coupon?: NotificationCoupon;
34
+ };
35
+ type NotificationResult = {
36
+ notification: Record<string, unknown>;
37
+ skipped?: Record<string, number>;
38
+ duplicate?: boolean;
39
+ };
40
+ type ClientOptions = {
41
+ /** کلید API سایت (fg_live_…) — فقط سمت سرور */
42
+ apiKey: string;
43
+ /** پیش‌فرض: https://finget.ir/api/v1 */
44
+ baseUrl?: string;
45
+ /** پیش‌فرض: https://finget.ir/auth */
46
+ authUrl?: string;
47
+ /** مهلت درخواست بر حسب میلی‌ثانیه */
48
+ timeoutMs?: number;
49
+ };
50
+
51
+ declare const VERSION = "1.0.0";
52
+ declare const DEFAULT_BASE_URL = "https://finget.ir/api/v1";
53
+ declare const DEFAULT_AUTH_URL = "https://finget.ir/auth";
54
+ /**
55
+ * کلاینت رسمی API عمومی فینگت (/api/v1).
56
+ * کلید API را فقط سمت سرور نگه دارید.
57
+ */
58
+ declare class Client {
59
+ private readonly apiKey;
60
+ private readonly baseUrl;
61
+ private readonly authUrl;
62
+ private readonly timeoutMs;
63
+ constructor(options: ClientOptions);
64
+ /** از process.env.FINGET_API_KEY (و اختیاری FINGET_BASE_URL / FINGET_AUTH_URL). */
65
+ static fromEnv(apiKeyEnv?: string): Client;
66
+ /** آزمودن کلید؛ مشخصات سایت صاحب کلید. */
67
+ getSite(): Promise<{
68
+ site: SiteInfo;
69
+ }>;
70
+ /** کد یک‌بارمصرف callback را به اطلاعات کاربر تبدیل می‌کند. */
71
+ exchangeCode(code: string): Promise<TokenResult>;
72
+ /** اطلاعات تازه‌ی کاربر وصل به سایت. */
73
+ getUser(userId: string): Promise<{
74
+ user: FingetUser;
75
+ }>;
76
+ /** ارسال اعلان به کاربران وصل سایت. */
77
+ sendNotification(payload: SendNotificationInput): Promise<NotificationResult>;
78
+ /** وضعیت یک پیام. */
79
+ getNotification(notificationId: string): Promise<Record<string, unknown>>;
80
+ /** رشته‌ی تصادفی امن برای پارامتر state ورود. */
81
+ createState(bytes?: number): string;
82
+ /**
83
+ * آدرس دکمه‌ی «ورود با فینگت».
84
+ * اگر state ندهید ساخته می‌شود؛ همان را در نشست نگه دارید.
85
+ */
86
+ loginUrl(clientId: string, state?: string): {
87
+ url: string;
88
+ state: string;
89
+ };
90
+ private request;
91
+ }
92
+
93
+ /** خطای پایهٔ SDK فینگت. */
94
+ declare class FingetError extends Error {
95
+ constructor(message: string);
96
+ }
97
+ /** پاسخ ناموفق API فینگت. */
98
+ declare class ApiError extends FingetError {
99
+ readonly status: number;
100
+ readonly errorCode: string | null;
101
+ readonly body: Record<string, unknown>;
102
+ constructor(message: string, status: number, errorCode?: string | null, body?: Record<string, unknown>);
103
+ }
104
+
105
+ export { ApiError, Client, type ClientOptions, DEFAULT_AUTH_URL, DEFAULT_BASE_URL, FingetError, type FingetUser, type NotificationCoupon, type NotificationLink, type NotificationResult, type SendNotificationInput, type SiteInfo, type TokenResult, VERSION };
package/dist/index.js ADDED
@@ -0,0 +1,167 @@
1
+ // src/errors.ts
2
+ var FingetError = class extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "FingetError";
6
+ }
7
+ };
8
+ var ApiError = class extends FingetError {
9
+ status;
10
+ errorCode;
11
+ body;
12
+ constructor(message, status, errorCode = null, body = {}) {
13
+ super(message);
14
+ this.name = "ApiError";
15
+ this.status = status;
16
+ this.errorCode = errorCode;
17
+ this.body = body;
18
+ }
19
+ };
20
+
21
+ // src/client.ts
22
+ var VERSION = "1.0.0";
23
+ var DEFAULT_BASE_URL = "https://finget.ir/api/v1";
24
+ var DEFAULT_AUTH_URL = "https://finget.ir/auth";
25
+ var Client = class _Client {
26
+ apiKey;
27
+ baseUrl;
28
+ authUrl;
29
+ timeoutMs;
30
+ constructor(options) {
31
+ const apiKey = options.apiKey.trim();
32
+ if (!apiKey) {
33
+ throw new FingetError("\u06A9\u0644\u06CC\u062F API \u0641\u06CC\u0646\u06AF\u062A \u062E\u0627\u0644\u06CC \u0627\u0633\u062A.");
34
+ }
35
+ const timeoutMs = options.timeoutMs ?? 2e4;
36
+ if (timeoutMs < 1) {
37
+ throw new FingetError("\u0645\u0647\u0644\u062A \u062F\u0631\u062E\u0648\u0627\u0633\u062A \u0628\u0627\u06CC\u062F \u062D\u062F\u0627\u0642\u0644 \u06F1 \u0645\u06CC\u0644\u06CC\u200C\u062B\u0627\u0646\u06CC\u0647 \u0628\u0627\u0634\u062F.");
38
+ }
39
+ this.apiKey = apiKey;
40
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
41
+ this.authUrl = (options.authUrl ?? DEFAULT_AUTH_URL).replace(/\/$/, "");
42
+ this.timeoutMs = timeoutMs;
43
+ }
44
+ /** از process.env.FINGET_API_KEY (و اختیاری FINGET_BASE_URL / FINGET_AUTH_URL). */
45
+ static fromEnv(apiKeyEnv = "FINGET_API_KEY") {
46
+ const key = process.env[apiKeyEnv];
47
+ if (!key?.trim()) {
48
+ throw new FingetError(`\u0645\u062A\u063A\u06CC\u0631 \u0645\u062D\u06CC\u0637\u06CC ${apiKeyEnv} \u062A\u0646\u0638\u06CC\u0645 \u0646\u0634\u062F\u0647 \u0627\u0633\u062A.`);
49
+ }
50
+ return new _Client({
51
+ apiKey: key,
52
+ baseUrl: process.env.FINGET_BASE_URL || void 0,
53
+ authUrl: process.env.FINGET_AUTH_URL || void 0
54
+ });
55
+ }
56
+ /** آزمودن کلید؛ مشخصات سایت صاحب کلید. */
57
+ async getSite() {
58
+ return this.request("GET", "/site");
59
+ }
60
+ /** کد یک‌بارمصرف callback را به اطلاعات کاربر تبدیل می‌کند. */
61
+ async exchangeCode(code) {
62
+ const trimmed = code.trim();
63
+ if (!trimmed) {
64
+ throw new FingetError("\u06A9\u062F \u0648\u0631\u0648\u062F (code) \u062E\u0627\u0644\u06CC \u0627\u0633\u062A.");
65
+ }
66
+ return this.request("POST", "/auth/token", { code: trimmed });
67
+ }
68
+ /** اطلاعات تازه‌ی کاربر وصل به سایت. */
69
+ async getUser(userId) {
70
+ const id = userId.trim();
71
+ if (!id) {
72
+ throw new FingetError("\u0634\u0646\u0627\u0633\u0647\u200C\u06CC \u06A9\u0627\u0631\u0628\u0631 \u062E\u0627\u0644\u06CC \u0627\u0633\u062A.");
73
+ }
74
+ return this.request("GET", `/users/${encodeURIComponent(id)}`);
75
+ }
76
+ /** ارسال اعلان به کاربران وصل سایت. */
77
+ async sendNotification(payload) {
78
+ return this.request("POST", "/notifications", payload, 201);
79
+ }
80
+ /** وضعیت یک پیام. */
81
+ async getNotification(notificationId) {
82
+ const id = notificationId.trim();
83
+ if (!id) {
84
+ throw new FingetError("\u0634\u0646\u0627\u0633\u0647\u200C\u06CC \u0627\u0639\u0644\u0627\u0646 \u062E\u0627\u0644\u06CC \u0627\u0633\u062A.");
85
+ }
86
+ return this.request("GET", `/notifications/${encodeURIComponent(id)}`);
87
+ }
88
+ /** رشته‌ی تصادفی امن برای پارامتر state ورود. */
89
+ createState(bytes = 16) {
90
+ if (bytes < 8) {
91
+ throw new FingetError("\u0637\u0648\u0644 state \u062E\u06CC\u0644\u06CC \u06A9\u0648\u062A\u0627\u0647 \u0627\u0633\u062A.");
92
+ }
93
+ const buf = new Uint8Array(bytes);
94
+ crypto.getRandomValues(buf);
95
+ return [...buf].map((b) => b.toString(16).padStart(2, "0")).join("");
96
+ }
97
+ /**
98
+ * آدرس دکمه‌ی «ورود با فینگت».
99
+ * اگر state ندهید ساخته می‌شود؛ همان را در نشست نگه دارید.
100
+ */
101
+ loginUrl(clientId, state) {
102
+ const id = clientId.trim();
103
+ if (!id) {
104
+ throw new FingetError("\u0634\u0646\u0627\u0633\u0647\u200C\u06CC \u0633\u0627\u06CC\u062A (client_id) \u062E\u0627\u0644\u06CC \u0627\u0633\u062A.");
105
+ }
106
+ const s = state ?? this.createState();
107
+ const url = new URL(this.authUrl);
108
+ url.searchParams.set("client_id", id);
109
+ url.searchParams.set("state", s);
110
+ return { url: url.toString(), state: s };
111
+ }
112
+ async request(method, path, body, okStatuses = 200) {
113
+ const ok = Array.isArray(okStatuses) ? okStatuses : [okStatuses];
114
+ const controller = new AbortController();
115
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
116
+ try {
117
+ const res = await fetch(`${this.baseUrl}${path}`, {
118
+ method,
119
+ redirect: "manual",
120
+ signal: controller.signal,
121
+ headers: {
122
+ Accept: "application/json",
123
+ Authorization: `Bearer ${this.apiKey}`,
124
+ "User-Agent": `finget-js/${VERSION}`,
125
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {}
126
+ },
127
+ body: body !== void 0 ? JSON.stringify(body) : void 0
128
+ });
129
+ let data = {};
130
+ const text = await res.text();
131
+ if (text) {
132
+ try {
133
+ const parsed = JSON.parse(text);
134
+ data = parsed && typeof parsed === "object" ? parsed : {};
135
+ } catch {
136
+ data = {};
137
+ }
138
+ }
139
+ if (!ok.includes(res.status)) {
140
+ const message = typeof data.message === "string" ? data.message : `\u062F\u0631\u062E\u0648\u0627\u0633\u062A \u0628\u0647 \u0641\u06CC\u0646\u06AF\u062A \u0646\u0627\u0645\u0648\u0641\u0642 \u0628\u0648\u062F (HTTP ${res.status}).`;
141
+ const code = typeof data.code === "string" ? data.code : null;
142
+ throw new ApiError(message, res.status, code, data);
143
+ }
144
+ return data;
145
+ } catch (err) {
146
+ if (err instanceof ApiError) {
147
+ throw err;
148
+ }
149
+ if (err instanceof Error && err.name === "AbortError") {
150
+ throw new ApiError("\u0645\u0647\u0644\u062A \u0627\u062A\u0635\u0627\u0644 \u0628\u0647 \u0641\u06CC\u0646\u06AF\u062A \u062A\u0645\u0627\u0645 \u0634\u062F.", 0);
151
+ }
152
+ const message = err instanceof Error ? err.message : "\u0627\u062A\u0635\u0627\u0644 \u0628\u0647 \u0641\u06CC\u0646\u06AF\u062A \u0628\u0631\u0642\u0631\u0627\u0631 \u0646\u0634\u062F.";
153
+ throw new ApiError(message, 0);
154
+ } finally {
155
+ clearTimeout(timer);
156
+ }
157
+ }
158
+ };
159
+ export {
160
+ ApiError,
161
+ Client,
162
+ DEFAULT_AUTH_URL,
163
+ DEFAULT_BASE_URL,
164
+ FingetError,
165
+ VERSION
166
+ };
167
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts"],"sourcesContent":["/** خطای پایهٔ SDK فینگت. */\nexport class FingetError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FingetError\";\n }\n}\n\n/** پاسخ ناموفق API فینگت. */\nexport class ApiError extends FingetError {\n readonly status: number;\n readonly errorCode: string | null;\n readonly body: Record<string, unknown>;\n\n constructor(\n message: string,\n status: number,\n errorCode: string | null = null,\n body: Record<string, unknown> = {},\n ) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.errorCode = errorCode;\n this.body = body;\n }\n}\n","import { ApiError, FingetError } from \"./errors.js\";\nimport type {\n ClientOptions,\n NotificationResult,\n SendNotificationInput,\n SiteInfo,\n TokenResult,\n FingetUser,\n} from \"./types.js\";\n\nexport const VERSION = \"1.0.0\";\nexport const DEFAULT_BASE_URL = \"https://finget.ir/api/v1\";\nexport const DEFAULT_AUTH_URL = \"https://finget.ir/auth\";\n\n/**\n * کلاینت رسمی API عمومی فینگت (/api/v1).\n * کلید API را فقط سمت سرور نگه دارید.\n */\nexport class Client {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly authUrl: string;\n private readonly timeoutMs: number;\n\n constructor(options: ClientOptions) {\n const apiKey = options.apiKey.trim();\n if (!apiKey) {\n throw new FingetError(\"کلید API فینگت خالی است.\");\n }\n const timeoutMs = options.timeoutMs ?? 20_000;\n if (timeoutMs < 1) {\n throw new FingetError(\"مهلت درخواست باید حداقل ۱ میلی‌ثانیه باشد.\");\n }\n\n this.apiKey = apiKey;\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n this.authUrl = (options.authUrl ?? DEFAULT_AUTH_URL).replace(/\\/$/, \"\");\n this.timeoutMs = timeoutMs;\n }\n\n /** از process.env.FINGET_API_KEY (و اختیاری FINGET_BASE_URL / FINGET_AUTH_URL). */\n static fromEnv(apiKeyEnv = \"FINGET_API_KEY\"): Client {\n const key = process.env[apiKeyEnv];\n if (!key?.trim()) {\n throw new FingetError(`متغیر محیطی ${apiKeyEnv} تنظیم نشده است.`);\n }\n return new Client({\n apiKey: key,\n baseUrl: process.env.FINGET_BASE_URL || undefined,\n authUrl: process.env.FINGET_AUTH_URL || undefined,\n });\n }\n\n /** آزمودن کلید؛ مشخصات سایت صاحب کلید. */\n async getSite(): Promise<{ site: SiteInfo }> {\n return this.request(\"GET\", \"/site\");\n }\n\n /** کد یک‌بارمصرف callback را به اطلاعات کاربر تبدیل می‌کند. */\n async exchangeCode(code: string): Promise<TokenResult> {\n const trimmed = code.trim();\n if (!trimmed) {\n throw new FingetError(\"کد ورود (code) خالی است.\");\n }\n return this.request(\"POST\", \"/auth/token\", { code: trimmed });\n }\n\n /** اطلاعات تازه‌ی کاربر وصل به سایت. */\n async getUser(userId: string): Promise<{ user: FingetUser }> {\n const id = userId.trim();\n if (!id) {\n throw new FingetError(\"شناسه‌ی کاربر خالی است.\");\n }\n return this.request(\"GET\", `/users/${encodeURIComponent(id)}`);\n }\n\n /** ارسال اعلان به کاربران وصل سایت. */\n async sendNotification(payload: SendNotificationInput): Promise<NotificationResult> {\n return this.request(\"POST\", \"/notifications\", payload, 201);\n }\n\n /** وضعیت یک پیام. */\n async getNotification(notificationId: string): Promise<Record<string, unknown>> {\n const id = notificationId.trim();\n if (!id) {\n throw new FingetError(\"شناسه‌ی اعلان خالی است.\");\n }\n return this.request(\"GET\", `/notifications/${encodeURIComponent(id)}`);\n }\n\n /** رشته‌ی تصادفی امن برای پارامتر state ورود. */\n createState(bytes = 16): string {\n if (bytes < 8) {\n throw new FingetError(\"طول state خیلی کوتاه است.\");\n }\n const buf = new Uint8Array(bytes);\n crypto.getRandomValues(buf);\n return [...buf].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n }\n\n /**\n * آدرس دکمه‌ی «ورود با فینگت».\n * اگر state ندهید ساخته می‌شود؛ همان را در نشست نگه دارید.\n */\n loginUrl(clientId: string, state?: string): { url: string; state: string } {\n const id = clientId.trim();\n if (!id) {\n throw new FingetError(\"شناسه‌ی سایت (client_id) خالی است.\");\n }\n const s = state ?? this.createState();\n const url = new URL(this.authUrl);\n url.searchParams.set(\"client_id\", id);\n url.searchParams.set(\"state\", s);\n return { url: url.toString(), state: s };\n }\n\n private async request<T = Record<string, unknown>>(\n method: string,\n path: string,\n body?: unknown,\n okStatuses: number | number[] = 200,\n ): Promise<T> {\n const ok = Array.isArray(okStatuses) ? okStatuses : [okStatuses];\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const res = await fetch(`${this.baseUrl}${path}`, {\n method,\n redirect: \"manual\",\n signal: controller.signal,\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n \"User-Agent\": `finget-js/${VERSION}`,\n ...(body !== undefined ? { \"Content-Type\": \"application/json\" } : {}),\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n });\n\n let data: Record<string, unknown> = {};\n const text = await res.text();\n if (text) {\n try {\n const parsed: unknown = JSON.parse(text);\n data = parsed && typeof parsed === \"object\" ? (parsed as Record<string, unknown>) : {};\n } catch {\n data = {};\n }\n }\n\n if (!ok.includes(res.status)) {\n const message =\n typeof data.message === \"string\"\n ? data.message\n : `درخواست به فینگت ناموفق بود (HTTP ${res.status}).`;\n const code = typeof data.code === \"string\" ? data.code : null;\n throw new ApiError(message, res.status, code, data);\n }\n\n return data as T;\n } catch (err) {\n if (err instanceof ApiError) {\n throw err;\n }\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new ApiError(\"مهلت اتصال به فینگت تمام شد.\", 0);\n }\n const message = err instanceof Error ? err.message : \"اتصال به فینگت برقرار نشد.\";\n throw new ApiError(message, 0);\n } finally {\n clearTimeout(timer);\n }\n }\n}\n"],"mappings":";AACO,I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ACzD,cAAM,IAAI,SAAS,SAAS,IAAI,QAAQ,MAAM,IAAI;AAAA,MACpD;AAEA,aAAO;AAAA,IACT,SAAS,KAAK;AACZ,UAAI,eAAe,UAAU;AAC3B,cAAM;AAAA,MACR;AACA,UAAI,eAAe,SAAS,IAAI,SAAS,cAAc;AACrD,cAAM,IAAI,SAAS,8IAAgC,CAAC;AAAA,MACtD;AACA,YAAM,UAAU,eAAe,QAAQ,IAAI,UAAU;AACrD,YAAM,IAAI,SAAS,SAAS,CAAC;AAAA,IAC/B,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "finget-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Official Node.js / JavaScript / TypeScript SDK for the Finget passwordless login and notification API",
5
+ "license": "MIT",
6
+ "author": {
7
+ "name": "Finget",
8
+ "url": "https://finget.ir"
9
+ },
10
+ "homepage": "https://finget.ir",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/amirsafaridevs/finget-js.git"
14
+ },
15
+ "bugs": {
16
+ "url": "https://github.com/amirsafaridevs/finget-js/issues"
17
+ },
18
+ "keywords": [
19
+ "finget",
20
+ "login",
21
+ "otp",
22
+ "passwordless",
23
+ "notifications",
24
+ "iran",
25
+ "nodejs",
26
+ "typescript"
27
+ ],
28
+ "type": "module",
29
+ "main": "./dist/index.cjs",
30
+ "module": "./dist/index.js",
31
+ "types": "./dist/index.d.ts",
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.js",
36
+ "require": "./dist/index.cjs"
37
+ }
38
+ },
39
+ "files": [
40
+ "dist",
41
+ "LICENSE",
42
+ "README.md"
43
+ ],
44
+ "engines": {
45
+ "node": ">=18"
46
+ },
47
+ "scripts": {
48
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean --sourcemap",
49
+ "prepublishOnly": "npm run build"
50
+ },
51
+ "devDependencies": {
52
+ "@types/node": "^26.6.6",
53
+ "tsup": "^8.5.0",
54
+ "typescript": "^5.9.3"
55
+ },
56
+ "publishConfig": {
57
+ "access": "public"
58
+ }
59
+ }