@singi-labs/sifa-sdk 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,150 @@
1
+ import { createContext, useContext } from 'react';
2
+ import { jsx } from 'react/jsx-runtime';
3
+ import { useQueryClient, useMutation, useQuery } from '@tanstack/react-query';
4
+
5
+ // src/query/client.ts
6
+ var ApiError = class extends Error {
7
+ status;
8
+ body;
9
+ constructor(message, status, body) {
10
+ super(message);
11
+ this.name = "ApiError";
12
+ this.status = status;
13
+ this.body = body;
14
+ }
15
+ };
16
+ var DEFAULT_TIMEOUT_MS = 1e4;
17
+ var MAX_RATE_LIMIT_RETRIES = 3;
18
+ var RATE_LIMIT_RETRY_CAP_SECONDS = 3;
19
+ async function apiFetch(config, path, options = {}) {
20
+ const fetchFn = config.fetch ?? globalThis.fetch;
21
+ const url = `${config.baseUrl}${path}`;
22
+ const maxRetries = options.retryOn429 ? MAX_RATE_LIMIT_RETRIES : 0;
23
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
24
+ const signal = options.signal ?? AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
25
+ const headers = { ...options.headers ?? {} };
26
+ let body;
27
+ if (options.body !== void 0) {
28
+ headers["Content-Type"] ??= "application/json";
29
+ body = JSON.stringify(options.body);
30
+ }
31
+ const init = {
32
+ method: options.method ?? "GET",
33
+ headers,
34
+ body,
35
+ signal,
36
+ credentials: options.credentials,
37
+ cache: options.cache,
38
+ ...options.next ? { next: options.next } : {}
39
+ };
40
+ const res = await fetchFn(url, init);
41
+ if (res.status === 429 && attempt < maxRetries) {
42
+ const retryAfterRaw = res.headers.get("retry-after");
43
+ const retryAfter = retryAfterRaw ? Number.parseInt(retryAfterRaw, 10) : 2;
44
+ const waitSeconds = Math.min(
45
+ Number.isFinite(retryAfter) ? retryAfter : 2,
46
+ RATE_LIMIT_RETRY_CAP_SECONDS
47
+ );
48
+ await new Promise((r) => setTimeout(r, waitSeconds * 1e3));
49
+ continue;
50
+ }
51
+ if (!res.ok) {
52
+ let errBody;
53
+ try {
54
+ errBody = await res.json();
55
+ } catch {
56
+ try {
57
+ errBody = await res.text();
58
+ } catch {
59
+ errBody = void 0;
60
+ }
61
+ }
62
+ throw new ApiError(`Sifa API ${res.status} on ${path}`, res.status, errBody);
63
+ }
64
+ return await res.json();
65
+ }
66
+ throw new ApiError(`Sifa API exhausted retries on ${path}`, 429);
67
+ }
68
+ async function apiFetchOrNull(config, path, options = {}) {
69
+ try {
70
+ return await apiFetch(config, path, options);
71
+ } catch (e) {
72
+ if (e instanceof ApiError && e.status === 404) return null;
73
+ throw e;
74
+ }
75
+ }
76
+ var SifaConfigContext = createContext(null);
77
+ function SifaProvider({ config, children }) {
78
+ return /* @__PURE__ */ jsx(SifaConfigContext.Provider, { value: config, children });
79
+ }
80
+ function useSifaConfig() {
81
+ const ctx = useContext(SifaConfigContext);
82
+ if (!ctx) {
83
+ throw new Error(
84
+ "useSifaConfig must be used inside <SifaProvider>. Wrap your app once with <SifaProvider config={...}>."
85
+ );
86
+ }
87
+ return ctx;
88
+ }
89
+
90
+ // src/query/fetchers/profile.ts
91
+ function fetchProfile(config, handleOrDid, options = {}) {
92
+ const path = `/api/profile/${encodeURIComponent(handleOrDid)}`;
93
+ return apiFetchOrNull(config, path, {
94
+ retryOn429: true,
95
+ ...options
96
+ });
97
+ }
98
+
99
+ // src/query/fetchers/positions.ts
100
+ function createPosition(config, data, options = {}) {
101
+ return apiFetch(config, "/api/positions", {
102
+ method: "POST",
103
+ body: data,
104
+ credentials: "include",
105
+ ...options
106
+ });
107
+ }
108
+
109
+ // src/query/keys.ts
110
+ var sifaQueryKeys = {
111
+ all: () => ["sifa"],
112
+ profile: {
113
+ all: () => ["sifa", "profile"],
114
+ byHandle: (handleOrDid) => ["sifa", "profile", handleOrDid]
115
+ },
116
+ position: {
117
+ all: () => ["sifa", "position"],
118
+ byOwner: (did) => ["sifa", "position", "by-owner", did]
119
+ }
120
+ };
121
+
122
+ // src/query/hooks/use-create-position.ts
123
+ function useCreatePosition(ownerDid, options) {
124
+ const config = useSifaConfig();
125
+ const queryClient = useQueryClient();
126
+ return useMutation({
127
+ mutationFn: (data) => createPosition(config, data),
128
+ onSuccess: async (result, variables, onMutateResult, context) => {
129
+ if (result.success) {
130
+ await queryClient.invalidateQueries({ queryKey: sifaQueryKeys.profile.byHandle(ownerDid) });
131
+ await queryClient.invalidateQueries({ queryKey: sifaQueryKeys.position.byOwner(ownerDid) });
132
+ }
133
+ await options?.onSuccess?.(result, variables, onMutateResult, context);
134
+ },
135
+ ...options
136
+ });
137
+ }
138
+ function useProfile(handleOrDid, options) {
139
+ const config = useSifaConfig();
140
+ return useQuery({
141
+ queryKey: sifaQueryKeys.profile.byHandle(handleOrDid ?? ""),
142
+ queryFn: () => fetchProfile(config, handleOrDid ?? ""),
143
+ enabled: Boolean(handleOrDid) && (options?.enabled ?? true),
144
+ ...options
145
+ });
146
+ }
147
+
148
+ export { ApiError, SifaProvider, apiFetch, apiFetchOrNull, createPosition, fetchProfile, sifaQueryKeys, useCreatePosition, useProfile, useSifaConfig };
149
+ //# sourceMappingURL=index.js.map
150
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/query/client.ts","../../src/query/config.tsx","../../src/query/fetchers/profile.ts","../../src/query/fetchers/positions.ts","../../src/query/keys.ts","../../src/query/hooks/use-create-position.ts","../../src/query/hooks/use-profile.ts"],"names":[],"mappings":";;;;;AA2CO,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA,EACzB,MAAA;AAAA,EACA,IAAA;AAAA,EAET,WAAA,CAAY,OAAA,EAAiB,MAAA,EAAgB,IAAA,EAAgB;AAC3D,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,UAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAA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AA,IACd,QAAA,EAAU,aAAA,CAAc,OAAA,CAAQ,QAAA,CAAS,eAAe,EAAE,CAAA;AAAA,IAC1D,OAAA,EAAS,MAAM,YAAA,CAAa,MAAA,EAAQ,eAAe,EAAE,CAAA;AAAA,IACrD,OAAA,EAAS,OAAA,CAAQ,WAAW,CAAA,KAAM,SAAS,OAAA,IAAW,IAAA,CAAA;AAAA,IACtD,GAAG;AAAA,GACJ,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * Foundation HTTP client for talking to the Sifa AppView.\n *\n * Stateless. Consumers supply a {@link SifaApiConfig} per call (the React\n * hooks read it from context; non-React consumers pass it explicitly). No\n * singletons, no module-level state.\n */\n\n/** Configuration passed to every fetcher. */\nexport interface SifaApiConfig {\n /** Base URL of the sifa-api AppView, e.g. `https://api.sifa.id`. No trailing slash. */\n baseUrl: string;\n /**\n * Optional fetch implementation. Defaults to {@link globalThis.fetch}.\n * Lets Next.js consumers pass their cache-enhanced fetch; node/Expo\n * consumers can leave this unset.\n */\n fetch?: typeof fetch;\n}\n\n/** Options accepted by {@link apiFetch}. */\nexport interface ApiFetchOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n /** Request body. Serialized to JSON automatically. */\n body?: unknown;\n /** AbortSignal. Defaults to `AbortSignal.timeout(timeoutMs)` if `timeoutMs` is set. */\n signal?: AbortSignal;\n /** Per-call timeout in milliseconds. Default: 10_000. Ignored if `signal` is provided. */\n timeoutMs?: number;\n /** Retry on HTTP 429 up to 3 times with the server's `Retry-After` delay (capped at 3s). */\n retryOn429?: boolean;\n /** Additional headers. `Content-Type: application/json` is set automatically when `body` is present. */\n headers?: Record<string, string>;\n credentials?: RequestCredentials;\n cache?: RequestCache;\n /**\n * Next.js-specific cache hints. Ignored on non-Next runtimes. Passed\n * through transparently as part of {@link RequestInit}.\n */\n next?: { revalidate?: number | false; tags?: string[] };\n}\n\n/** Error thrown by {@link apiFetch} on non-2xx responses. */\nexport class ApiError extends Error {\n readonly status: number;\n readonly body: unknown;\n\n constructor(message: string, status: number, body?: unknown) {\n super(message);\n this.name = 'ApiError';\n this.status = status;\n this.body = body;\n }\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst MAX_RATE_LIMIT_RETRIES = 3;\nconst RATE_LIMIT_RETRY_CAP_SECONDS = 3;\n\n/**\n * Generic fetcher used by all SDK query and mutation functions.\n *\n * Returns parsed JSON typed as `T`. Throws {@link ApiError} on non-2xx\n * responses. Use {@link apiFetchOrNull} when 404 should resolve to `null`\n * instead.\n */\nexport async function apiFetch<T = unknown>(\n config: SifaApiConfig,\n path: string,\n options: ApiFetchOptions = {},\n): Promise<T> {\n const fetchFn = config.fetch ?? globalThis.fetch;\n const url = `${config.baseUrl}${path}`;\n const maxRetries = options.retryOn429 ? MAX_RATE_LIMIT_RETRIES : 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const signal = options.signal ?? AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n\n const headers: Record<string, string> = { ...(options.headers ?? {}) };\n let body: BodyInit | undefined;\n if (options.body !== undefined) {\n headers['Content-Type'] ??= 'application/json';\n body = JSON.stringify(options.body);\n }\n\n // `next` is a Next.js extension to RequestInit; cast through.\n const init = {\n method: options.method ?? 'GET',\n headers,\n body,\n signal,\n credentials: options.credentials,\n cache: options.cache,\n ...(options.next ? { next: options.next } : {}),\n } as RequestInit;\n\n const res = await fetchFn(url, init);\n\n if (res.status === 429 && attempt < maxRetries) {\n const retryAfterRaw = res.headers.get('retry-after');\n const retryAfter = retryAfterRaw ? Number.parseInt(retryAfterRaw, 10) : 2;\n const waitSeconds = Math.min(\n Number.isFinite(retryAfter) ? retryAfter : 2,\n RATE_LIMIT_RETRY_CAP_SECONDS,\n );\n await new Promise((r) => setTimeout(r, waitSeconds * 1000));\n continue;\n }\n\n if (!res.ok) {\n let errBody: unknown;\n try {\n errBody = (await res.json()) as unknown;\n } catch {\n try {\n errBody = await res.text();\n } catch {\n errBody = undefined;\n }\n }\n throw new ApiError(`Sifa API ${res.status} on ${path}`, res.status, errBody);\n }\n\n return (await res.json()) as T;\n }\n\n throw new ApiError(`Sifa API exhausted retries on ${path}`, 429);\n}\n\n/**\n * Variant of {@link apiFetch} that resolves to `null` on HTTP 404 instead\n * of throwing. Useful for \"fetch by handle\" reads where missing is\n * expected (e.g. unknown profile).\n */\nexport async function apiFetchOrNull<T>(\n config: SifaApiConfig,\n path: string,\n options: ApiFetchOptions = {},\n): Promise<T | null> {\n try {\n return await apiFetch<T>(config, path, options);\n } catch (e) {\n if (e instanceof ApiError && e.status === 404) return null;\n throw e;\n }\n}\n","'use client';\n\nimport { createContext, useContext, type ReactNode } from 'react';\n\nimport type { SifaApiConfig } from './client.js';\n\nconst SifaConfigContext = createContext<SifaApiConfig | null>(null);\n\nexport interface SifaProviderProps {\n config: SifaApiConfig;\n children: ReactNode;\n}\n\n/**\n * Provides the {@link SifaApiConfig} that hooks under it can read via\n * {@link useSifaConfig}. Wrap the React tree once; hooks consume it.\n *\n * @example\n * ```tsx\n * <QueryClientProvider client={queryClient}>\n * <SifaProvider config={{ baseUrl: process.env.NEXT_PUBLIC_API_URL! }}>\n * <App />\n * </SifaProvider>\n * </QueryClientProvider>\n * ```\n */\nexport function SifaProvider({ config, children }: SifaProviderProps) {\n return <SifaConfigContext.Provider value={config}>{children}</SifaConfigContext.Provider>;\n}\n\n/**\n * Read the SDK's {@link SifaApiConfig} from context. Throws if no\n * {@link SifaProvider} is mounted above.\n */\nexport function useSifaConfig(): SifaApiConfig {\n const ctx = useContext(SifaConfigContext);\n if (!ctx) {\n throw new Error(\n 'useSifaConfig must be used inside <SifaProvider>. Wrap your app once with <SifaProvider config={...}>.',\n );\n }\n return ctx;\n}\n","import type { Profile } from '../../types/index.js';\nimport { apiFetchOrNull, type ApiFetchOptions, type SifaApiConfig } from '../client.js';\n\n/**\n * Read the aggregated profile for a handle or DID.\n *\n * Returns `null` when the AppView has no profile for the given identifier\n * (HTTP 404). Throws {@link ApiError} on other non-2xx responses.\n *\n * Server-callable (Next.js RSC) and client-callable (Expo, browser).\n */\nexport function fetchProfile(\n config: SifaApiConfig,\n handleOrDid: string,\n options: ApiFetchOptions = {},\n): Promise<Profile | null> {\n const path = `/api/profile/${encodeURIComponent(handleOrDid)}`;\n return apiFetchOrNull<Profile>(config, path, {\n retryOn429: true,\n ...options,\n });\n}\n","import { apiFetch, type ApiFetchOptions, type SifaApiConfig } from '../client.js';\n\n/** Result returned by record-write mutations (create / update / delete). */\nexport interface WriteResult {\n success: boolean;\n error?: string;\n pdsHost?: string;\n}\n\n/** Result returned by create mutations. Includes the newly created `rkey`. */\nexport interface CreateResult extends WriteResult {\n rkey?: string;\n}\n\n/**\n * Create a new `id.sifa.profile.position` record on the authenticated\n * user's PDS. The AppView signs and writes via the user's OAuth session.\n *\n * `data` should be a lexicon-shaped position record (without `createdAt`\n * or `rkey`; the AppView fills both). Validate with\n * `ProfilePositionRecordSchema.omit({ createdAt: true })` before calling\n * if you want client-side guarantees.\n */\nexport function createPosition(\n config: SifaApiConfig,\n data: Record<string, unknown>,\n options: ApiFetchOptions = {},\n): Promise<CreateResult> {\n return apiFetch<CreateResult>(config, '/api/positions', {\n method: 'POST',\n body: data,\n credentials: 'include',\n ...options,\n });\n}\n","/**\n * Query key factory for TanStack Query.\n *\n * Keys are read-only tuples; the hierarchy matches the SDK's fetcher\n * grouping. Use these instead of inline arrays so consumers can target\n * `queryClient.invalidateQueries({ queryKey: keys.profile.all() })` and\n * similar patterns without typos.\n *\n * Convention: every leaf key starts with the namespace ('sifa') so\n * consumers can invalidate everything Sifa-related in one call.\n */\nexport const sifaQueryKeys = {\n all: () => ['sifa'] as const,\n\n profile: {\n all: () => ['sifa', 'profile'] as const,\n byHandle: (handleOrDid: string) => ['sifa', 'profile', handleOrDid] as const,\n },\n\n position: {\n all: () => ['sifa', 'position'] as const,\n byOwner: (did: string) => ['sifa', 'position', 'by-owner', did] as const,\n },\n} as const;\n\nexport type SifaQueryKey =\n | ReturnType<typeof sifaQueryKeys.all>\n | ReturnType<typeof sifaQueryKeys.profile.all>\n | ReturnType<typeof sifaQueryKeys.profile.byHandle>\n | ReturnType<typeof sifaQueryKeys.position.all>\n | ReturnType<typeof sifaQueryKeys.position.byOwner>;\n","'use client';\n\nimport { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query';\n\nimport { useSifaConfig } from '../config.js';\nimport { createPosition, type CreateResult } from '../fetchers/positions.js';\nimport { sifaQueryKeys } from '../keys.js';\n\n/**\n * React hook for creating a new position record. On success, invalidates\n * the owner's profile cache so the new position is reflected on the next\n * read.\n *\n * The owner DID is required so the mutation can target the correct\n * profile cache entry for invalidation.\n */\nexport function useCreatePosition(\n ownerDid: string,\n options?: Omit<UseMutationOptions<CreateResult, Error, Record<string, unknown>>, 'mutationFn'>,\n) {\n const config = useSifaConfig();\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: (data: Record<string, unknown>) => createPosition(config, data),\n onSuccess: async (result, variables, onMutateResult, context) => {\n if (result.success) {\n await queryClient.invalidateQueries({ queryKey: sifaQueryKeys.profile.byHandle(ownerDid) });\n await queryClient.invalidateQueries({ queryKey: sifaQueryKeys.position.byOwner(ownerDid) });\n }\n await options?.onSuccess?.(result, variables, onMutateResult, context);\n },\n ...options,\n });\n}\n","'use client';\n\nimport { useQuery, type UseQueryOptions } from '@tanstack/react-query';\n\nimport type { Profile } from '../../types/index.js';\nimport { useSifaConfig } from '../config.js';\nimport { fetchProfile } from '../fetchers/profile.js';\nimport { sifaQueryKeys } from '../keys.js';\n\n/**\n * React hook that reads an aggregated profile by handle or DID via\n * TanStack Query. Returns `null` data when the profile does not exist.\n *\n * Pass `{ enabled: false }` (or an empty `handleOrDid`) to defer the\n * fetch.\n */\nexport function useProfile(\n handleOrDid: string | undefined | null,\n options?: Omit<\n UseQueryOptions<\n Profile | null,\n Error,\n Profile | null,\n ReturnType<typeof sifaQueryKeys.profile.byHandle>\n >,\n 'queryKey' | 'queryFn'\n >,\n) {\n const config = useSifaConfig();\n return useQuery({\n queryKey: sifaQueryKeys.profile.byHandle(handleOrDid ?? ''),\n queryFn: () => fetchProfile(config, handleOrDid ?? ''),\n enabled: Boolean(handleOrDid) && (options?.enabled ?? true),\n ...options,\n });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@singi-labs/sifa-sdk",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Sifa SDK — public client library for the Sifa AppView on AT Protocol. Shared by sifa-web and sifa-app.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -51,31 +51,59 @@
51
51
  "default": "./dist/schemas/index.cjs"
52
52
  }
53
53
  },
54
+ "./query": {
55
+ "import": {
56
+ "types": "./dist/query/index.d.ts",
57
+ "default": "./dist/query/index.js"
58
+ },
59
+ "require": {
60
+ "types": "./dist/query/index.d.cts",
61
+ "default": "./dist/query/index.cjs"
62
+ }
63
+ },
54
64
  "./package.json": "./package.json"
55
65
  },
56
66
  "main": "./dist/index.cjs",
57
67
  "module": "./dist/index.js",
58
68
  "types": "./dist/index.d.ts",
59
69
  "sideEffects": false,
70
+ "engines": {
71
+ "node": ">=22"
72
+ },
73
+ "dependencies": {
74
+ "zod": "4.4.3"
75
+ },
76
+ "peerDependencies": {
77
+ "@tanstack/react-query": "^5.100.0",
78
+ "react": ">=19"
79
+ },
80
+ "peerDependenciesMeta": {
81
+ "@tanstack/react-query": {
82
+ "optional": true
83
+ },
84
+ "react": {
85
+ "optional": true
86
+ }
87
+ },
60
88
  "devDependencies": {
61
89
  "@changesets/cli": "2.31.0",
62
90
  "@commitlint/cli": "21.0.1",
63
91
  "@commitlint/config-conventional": "21.0.1",
92
+ "@tanstack/react-query": "5.100.10",
93
+ "@testing-library/react": "16.3.2",
94
+ "@types/react": "19.2.14",
64
95
  "@vitest/coverage-v8": "3.2.1",
65
96
  "eslint": "10.3.0",
66
97
  "husky": "9.1.7",
98
+ "jsdom": "27.0.0",
67
99
  "prettier": "3.8.3",
100
+ "react": "19.2.4",
101
+ "react-dom": "19.2.4",
68
102
  "tsup": "8.5.1",
69
103
  "typescript": "5.9.3",
70
104
  "typescript-eslint": "8.59.3",
71
105
  "vitest": "3.2.1"
72
106
  },
73
- "engines": {
74
- "node": ">=22"
75
- },
76
- "dependencies": {
77
- "zod": "4.4.3"
78
- },
79
107
  "scripts": {
80
108
  "build": "tsup",
81
109
  "dev": "tsup --watch",