@pear-protocol/core-sdk 0.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.
@@ -0,0 +1,85 @@
1
+ class Trade {
2
+ client;
3
+ constructor(client) {
4
+ this.client = client;
5
+ }
6
+ async open(body, headers) {
7
+ return await this.client.fetch(`/trade/open`, {
8
+ method: "POST",
9
+ headers,
10
+ body
11
+ });
12
+ }
13
+ async adjust(positionId, body, headers) {
14
+ return await this.client.fetch(`/trade/${positionId}/adjust`, {
15
+ method: "POST",
16
+ headers,
17
+ body
18
+ });
19
+ }
20
+ async close(positionId, body, headers) {
21
+ return await this.client.fetch(`/trade/${positionId}/close`, {
22
+ method: "POST",
23
+ headers,
24
+ body
25
+ });
26
+ }
27
+ async closeAll(body, headers) {
28
+ return await this.client.fetch(`/trade/close-all`, {
29
+ method: "POST",
30
+ headers,
31
+ body
32
+ });
33
+ }
34
+ schedules = {
35
+ create: async (body, headers) => {
36
+ return await this.client.fetch(`/schedules`, {
37
+ method: "POST",
38
+ headers,
39
+ body
40
+ });
41
+ },
42
+ cancel: async (scheduleId, headers) => {
43
+ return await this.client.fetch(`/schedules/${scheduleId}/cancel`, {
44
+ method: "PATCH",
45
+ headers
46
+ });
47
+ },
48
+ cancelAll: async (headers) => {
49
+ return await this.client.fetch(`/schedules/cancel-all`, {
50
+ method: "PATCH",
51
+ headers
52
+ });
53
+ }
54
+ };
55
+ triggers = {
56
+ open: async (body, headers) => {
57
+ return await this.client.fetch(`/triggers/open`, {
58
+ method: "POST",
59
+ headers,
60
+ body
61
+ });
62
+ },
63
+ close: async (body, headers) => {
64
+ return await this.client.fetch(`/triggers/close`, {
65
+ method: "POST",
66
+ headers,
67
+ body
68
+ });
69
+ },
70
+ cancel: async (triggerId, headers) => {
71
+ return await this.client.fetch(`/triggers/${triggerId}/cancel`, {
72
+ method: "PATCH",
73
+ headers
74
+ });
75
+ },
76
+ cancelAll: async (headers) => {
77
+ return await this.client.fetch(`/triggers/cancel-all`, {
78
+ method: "PATCH",
79
+ headers
80
+ });
81
+ }
82
+ };
83
+ }
84
+
85
+ export { Trade };
@@ -0,0 +1,93 @@
1
+ type AuthMode = 'session' | 'bearer';
2
+ type SDKConfig = {
3
+ /**
4
+ * Trade + Info endpoints.
5
+ *
6
+ * Example: 'https://api.pear.garden'
7
+ */
8
+ apiUrl: string;
9
+ /**
10
+ * Authentication endpoint.
11
+ *
12
+ * Example: 'https://auth.pear.garden'
13
+ */
14
+ authUrl: string;
15
+ /**
16
+ * Authentication transport mode:
17
+ *
18
+ * Session (default):
19
+ * Cookies sent via `credentials: 'include'`. No tokens in JS memory.
20
+ * SDK retries once on 401 by calling `POST /auth/refresh`.
21
+ * Used by web applications.
22
+ *
23
+ * Bearer:
24
+ * Token set on every request via `Authorization` header. Provide
25
+ * `token` getter to supply the API key or JWT. No client-side refresh.
26
+ * If 401, caller handles re-auth. Used by headless / API-key clients.
27
+ */
28
+ auth?: {
29
+ type: AuthMode;
30
+ /**
31
+ * Token getter for bearer mode (e.g. () => apiKey). Ignored in session mode.
32
+ *
33
+ * Example: () => localStorage.getItem('apiKey')
34
+ */
35
+ token?: () => string | null;
36
+ };
37
+ /**
38
+ * Trade account ID getter (used in both modes)
39
+ *
40
+ * Example: () => localStorage.getState().activeTradeAccountId
41
+ */
42
+ getTradeAccountId?: () => string | null;
43
+ /**
44
+ * Called when server returns 401 (bearer mode only)
45
+ *
46
+ * Example: () => {
47
+ * console.error('Unauthorized. Token may be expired or revoked.');
48
+ * localStorage.removeItem('apiKey');
49
+ * }
50
+ */
51
+ onAuthError?: () => void;
52
+ /**
53
+ * Logger for debugging
54
+ *
55
+ * Example: {
56
+ * error: console.error,
57
+ * warn: console.warn,
58
+ * info: console.info,
59
+ * debug: console.debug,
60
+ * }
61
+ */
62
+ logger?: Logger;
63
+ /**
64
+ * Whether to print debug messages to the console.
65
+ *
66
+ * Example: true
67
+ */
68
+ debug?: boolean;
69
+ };
70
+ type Logger = {
71
+ error: (...messages: string[]) => void;
72
+ warn: (...messages: string[]) => void;
73
+ info: (...messages: string[]) => void;
74
+ debug: (...messages: string[]) => void;
75
+ };
76
+ type FetchParams = Parameters<typeof fetch>;
77
+ type ClientHeaders = Record<string, string | null | {
78
+ /**
79
+ * Tags to cache data under for Next.js applications.
80
+ * https://nextjs.org/docs/app/building-your-application/caching#fetch-optionsnexttags-and-revalidatetag
81
+ */
82
+ tags: string[];
83
+ }>;
84
+ type FetchInput = FetchParams[0];
85
+ type FetchArgs = Omit<RequestInit, 'headers' | 'body'> & {
86
+ query?: Record<string, any>;
87
+ headers?: ClientHeaders;
88
+ body?: RequestInit['body'] | Record<string, any>;
89
+ };
90
+ type RequestMiddleware = (request: Request, next: () => Promise<Response>) => Promise<Response>;
91
+ type ResponseMiddleware = (response: Response, retry: () => Promise<Response>, request: Request) => Promise<Response>;
92
+
93
+ export type { AuthMode, ClientHeaders, FetchArgs, FetchInput, FetchParams, Logger, RequestMiddleware, ResponseMiddleware, SDKConfig };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,12 @@
1
+ import { FetchArgs, AuthMode } from './types.js';
2
+
3
+ declare function getBaseUrl(passedBaseUrl: string): string;
4
+ declare function normalizeRequest(init: FetchArgs | undefined, headers: Headers, authMode: AuthMode): RequestInit | undefined;
5
+ declare function normalizeResponseData(resp: Response, reqHeaders: Headers): Promise<any>;
6
+ declare class FetchError extends Error {
7
+ status: number | undefined;
8
+ statusText: string | undefined;
9
+ constructor(message: string, statusText?: string, status?: number);
10
+ }
11
+
12
+ export { FetchError, getBaseUrl, normalizeRequest, normalizeResponseData };
package/dist/utils.js ADDED
@@ -0,0 +1,45 @@
1
+ function getBaseUrl(passedBaseUrl) {
2
+ if (typeof window === "undefined") {
3
+ return passedBaseUrl;
4
+ }
5
+ if (passedBaseUrl === "" || passedBaseUrl === "/") {
6
+ return window.location.origin;
7
+ }
8
+ return passedBaseUrl;
9
+ }
10
+ function normalizeRequest(init, headers, authMode) {
11
+ let body = init?.body;
12
+ if (body && headers.get("content-type")?.includes("application/json")) {
13
+ body = JSON.stringify(body);
14
+ }
15
+ return {
16
+ ...init,
17
+ headers,
18
+ ...body ? { body } : {},
19
+ // In session mode, include cookies with every request
20
+ // WHY: httpOnly cookies are sent automatically — no JS token management needed
21
+ ...authMode === "session" ? { credentials: "include" } : {}
22
+ };
23
+ }
24
+ async function normalizeResponseData(resp, reqHeaders) {
25
+ if (resp.status === 304) {
26
+ return null;
27
+ }
28
+ if (resp.status >= 300) {
29
+ const jsonError = await resp.json().catch(() => ({}));
30
+ throw new FetchError(jsonError.message ?? resp.statusText, resp.statusText, resp.status);
31
+ }
32
+ const isJsonRequest = reqHeaders.get("accept")?.includes("application/json");
33
+ return isJsonRequest ? await resp.json() : resp;
34
+ }
35
+ class FetchError extends Error {
36
+ status;
37
+ statusText;
38
+ constructor(message, statusText, status) {
39
+ super(message);
40
+ this.statusText = statusText;
41
+ this.status = status;
42
+ }
43
+ }
44
+
45
+ export { FetchError, getBaseUrl, normalizeRequest, normalizeResponseData };
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@pear-protocol/core-sdk",
3
+ "version": "0.0.1",
4
+ "description": "Pear Protocol Core SDK",
5
+ "private": false,
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "sideEffects": false,
22
+ "scripts": {
23
+ "build": "tsup",
24
+ "clean": "rm -rf dist .turbo",
25
+ "typecheck": "tsc --noEmit"
26
+ },
27
+ "dependencies": {
28
+ "@pear-protocol/types": "0.0.1",
29
+ "@pear-protocol/utils": "0.0.1",
30
+ "qs": "^6.14.0"
31
+ },
32
+ "devDependencies": {
33
+ "@backend/typescript-config": "workspace:*",
34
+ "@types/qs": "^6.14.0",
35
+ "tsup": "8.5.1",
36
+ "typescript": "5.9.3"
37
+ }
38
+ }