@synap-core/sdk 0.2.0 → 1.1.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.
Files changed (48) hide show
  1. package/README.md +61 -135
  2. package/dist/index.cjs +115 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +80 -0
  5. package/dist/index.d.ts +72 -47
  6. package/dist/index.js +80 -47
  7. package/dist/index.js.map +1 -1
  8. package/package.json +39 -28
  9. package/src/client.ts +193 -0
  10. package/src/index.ts +2 -0
  11. package/src/public.ts +262 -0
  12. package/dist/client.d.ts +0 -105
  13. package/dist/client.d.ts.map +0 -1
  14. package/dist/client.js +0 -95
  15. package/dist/client.js.map +0 -1
  16. package/dist/index.d.ts.map +0 -1
  17. package/dist/resources/entities.d.ts +0 -90
  18. package/dist/resources/entities.d.ts.map +0 -1
  19. package/dist/resources/entities.js +0 -126
  20. package/dist/resources/entities.js.map +0 -1
  21. package/dist/resources/events.d.ts +0 -51
  22. package/dist/resources/events.d.ts.map +0 -1
  23. package/dist/resources/events.js +0 -92
  24. package/dist/resources/events.js.map +0 -1
  25. package/dist/resources/preferences.d.ts +0 -24
  26. package/dist/resources/preferences.d.ts.map +0 -1
  27. package/dist/resources/preferences.js +0 -30
  28. package/dist/resources/preferences.js.map +0 -1
  29. package/dist/resources/relations.d.ts +0 -71
  30. package/dist/resources/relations.d.ts.map +0 -1
  31. package/dist/resources/relations.js +0 -121
  32. package/dist/resources/relations.js.map +0 -1
  33. package/dist/resources/views.d.ts +0 -43
  34. package/dist/resources/views.d.ts.map +0 -1
  35. package/dist/resources/views.js +0 -54
  36. package/dist/resources/views.js.map +0 -1
  37. package/dist/resources/workspaces.d.ts +0 -50
  38. package/dist/resources/workspaces.d.ts.map +0 -1
  39. package/dist/resources/workspaces.js +0 -66
  40. package/dist/resources/workspaces.js.map +0 -1
  41. package/dist/types/events.d.ts +0 -24
  42. package/dist/types/events.d.ts.map +0 -1
  43. package/dist/types/events.js +0 -5
  44. package/dist/types/events.js.map +0 -1
  45. package/dist/types/relations.d.ts +0 -26
  46. package/dist/types/relations.d.ts.map +0 -1
  47. package/dist/types/relations.js +0 -5
  48. package/dist/types/relations.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,48 +1,81 @@
1
- /**
2
- * @synap/sdk - High-Level SDK for Synap
3
- *
4
- * Event-sourced personal data platform SDK with type-safe APIs.
5
- *
6
- * @example
7
- * ```typescript
8
- * import { SynapSDK } from '@synap/sdk';
9
- *
10
- * const synap = new SynapSDK({
11
- * url: 'https://api.synap.app',
12
- * apiKey: 'your-api-key',
13
- * realtime: {
14
- * userId: 'user-123',
15
- * userName: 'Alice',
16
- * },
17
- * });
18
- *
19
- * // Create entity (event-sourced)
20
- * const task = await synap.entities.create({
21
- * type: 'task',
22
- * title: 'Call Marie',
23
- * metadata: { dueDate: '2024-12-20', priority: 'high' }
24
- * });
25
- *
26
- * // Create workspace
27
- * const workspace = await synap.workspaces.create({ name: 'Team' });
28
- *
29
- * // Create whiteboard
30
- * const board = await synap.views.create({
31
- * type: 'whiteboard',
32
- * name: 'Brainstorm',
33
- * workspaceId: workspace.id,
34
- * });
35
- *
36
- * // Real-time collaboration
37
- * synap.realtime?.connectPresence(board.id);
38
- * const ydoc = synap.realtime?.connectYjs(board.id);
39
- * ```
40
- */
41
- export { SynapSDK } from './client.js';
42
- export { EntitiesAPI } from './resources/entities.js';
43
- export { RelationsAPI } from './resources/relations.js';
44
- export { EventsAPI } from './resources/events.js';
45
- export { WorkspacesAPI } from './resources/workspaces.js';
46
- export { ViewsAPI } from './resources/views.js';
47
- export { PreferencesAPI } from './resources/preferences.js';
1
+ // src/client.ts
2
+ import {
3
+ createTRPCClient,
4
+ httpBatchLink
5
+ } from "@trpc/client";
6
+ import superjson from "superjson";
7
+ function createSynapClient(options) {
8
+ const { podUrl, apiKey, workspaceId, extraHeaders, onAuthError } = options;
9
+ const url = `${podUrl.replace(/\/$/, "")}/trpc`;
10
+ const baseFetch = (input, init) => fetch(input, { ...init, credentials: "include" });
11
+ const wrappedFetch = onAuthError ? async (input, init) => {
12
+ const response = await baseFetch(input, init);
13
+ if (response.ok) return response;
14
+ const cloned = response.clone();
15
+ let body = "";
16
+ try {
17
+ body = await cloned.text();
18
+ } catch {
19
+ body = "";
20
+ }
21
+ let isTrpcFormat = false;
22
+ try {
23
+ isTrpcFormat = Array.isArray(JSON.parse(body));
24
+ } catch {
25
+ isTrpcFormat = false;
26
+ }
27
+ if (isTrpcFormat) return response;
28
+ const parsedMessage = (() => {
29
+ try {
30
+ const parsed = JSON.parse(body);
31
+ return parsed.error ?? parsed.message ?? null;
32
+ } catch {
33
+ return null;
34
+ }
35
+ })();
36
+ const message = response.status === 401 ? "Session expired. Please sign in again." : `Request failed (${response.status}).`;
37
+ if (response.status === 401) {
38
+ onAuthError({ status: 401, message });
39
+ }
40
+ const trpcError = [
41
+ {
42
+ error: {
43
+ message,
44
+ code: response.status === 401 ? -32001 : -32e3,
45
+ data: {
46
+ code: response.status === 401 ? "UNAUTHORIZED" : "INTERNAL_SERVER_ERROR",
47
+ httpStatus: response.status,
48
+ // Server-supplied detail — untrusted; consumers must escape it
49
+ // before rendering (never inject as HTML).
50
+ detail: parsedMessage ?? void 0
51
+ }
52
+ }
53
+ }
54
+ ];
55
+ return new Response(JSON.stringify(trpcError), {
56
+ status: response.status,
57
+ headers: { "content-type": "application/json" }
58
+ });
59
+ } : baseFetch;
60
+ return createTRPCClient({
61
+ links: [
62
+ httpBatchLink({
63
+ url,
64
+ transformer: superjson,
65
+ fetch: wrappedFetch,
66
+ headers: () => ({
67
+ // Session token mode (Kratos, preferred for non-browser clients)
68
+ ...options.sessionToken ? { "x-session-token": options.sessionToken } : {},
69
+ // API key mode (Bearer, for legacy SDK usage)
70
+ ...apiKey && !options.sessionToken ? { Authorization: `Bearer ${apiKey}` } : {},
71
+ ...workspaceId ? { "x-workspace-id": workspaceId } : {},
72
+ ...extraHeaders
73
+ })
74
+ })
75
+ ]
76
+ });
77
+ }
78
+ export {
79
+ createSynapClient
80
+ };
48
81
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,OAAO,EAAE,QAAQ,EAAuB,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC"}
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["/**\n * @synap-core/sdk — Type-safe tRPC client for Synap data pods.\n *\n * Usage:\n * ```typescript\n * import { createSynapClient } from \"@synap-core/sdk\";\n *\n * const synap = createSynapClient({\n * podUrl: \"https://pod.example.com\",\n * apiKey: \"sk_live_...\",\n * workspaceId: \"ws_...\",\n * });\n *\n * // Fully typed — autocomplete works on all 47+ routers\n * const entities = await synap.entities.list.query({ limit: 20 });\n * const workspace = await synap.workspaces.get.query();\n * ```\n */\n\nimport {\n createTRPCClient,\n httpBatchLink,\n type CreateTRPCClient,\n} from \"@trpc/client\";\nimport superjson from \"superjson\";\nimport type { AppRouter } from \"@synap-core/api-types\";\n\nexport interface SynapClientOptions {\n /**\n * Base URL of the data pod (no trailing slash, no `/trpc` suffix).\n * @example \"https://pod.example.com\"\n */\n podUrl: string;\n\n /**\n * Ory Kratos session token (for example, from the Pod's\n * `/api/federation/exchange` endpoint).\n * Sent as `X-Session-Token` header — preferred for non-browser clients\n * like extensions, CLI tools, and mobile apps.\n * @example \"oathkeeper_token_...\"\n */\n sessionToken?: string;\n\n /**\n * API key for authentication (Bearer token).\n * Generate one in your workspace developer settings.\n * If omitted, the client falls back to cookie-based Kratos session auth.\n * @example \"sk_live_abc123...\"\n */\n apiKey?: string;\n\n /**\n * Workspace ID to scope all requests to.\n * Pass empty string for procedures that don't require workspace context\n * (e.g. workspaces.list, which is protectedProcedure only).\n * @example \"ws_01jk...\"\n */\n workspaceId: string;\n\n /**\n * Additional headers to include in every request.\n */\n extraHeaders?: Record<string, string>;\n\n /**\n * Called when the pod returns a `401 Unauthorized` (expired/invalid session\n * or API key). The app should sign out and re-authenticate (re-handshake).\n *\n * The pod's auth middleware can reply with a plain-JSON body\n * (`{\"error\":\"Invalid session\"}`) that is NOT in tRPC batch format and would\n * otherwise crash the superjson transformer; when an `onAuthError` handler is\n * provided the client rewrites such responses into a well-formed tRPC error so\n * the query rejects gracefully instead of throwing a parse error.\n */\n onAuthError?: (error: { status: number; message: string }) => void;\n}\n\n/**\n * Creates a fully-typed tRPC client connected to a Synap data pod.\n *\n * All 47+ tRPC routers are available with full TypeScript autocomplete\n * and compile-time safety. Auth is handled via Bearer token + workspace header.\n */\nexport function createSynapClient(\n options: SynapClientOptions,\n): CreateTRPCClient<AppRouter> {\n const { podUrl, apiKey, workspaceId, extraHeaders, onAuthError } = options;\n\n const url = `${podUrl.replace(/\\/$/, \"\")}/trpc`;\n\n // Base fetch: always include credentials so session cookies are sent in\n // cookie-auth mode. When apiKey is present, the Bearer token takes precedence\n // on the pod.\n const baseFetch: typeof fetch = (input, init) =>\n fetch(input, { ...init, credentials: \"include\" });\n\n // When an onAuthError handler is provided, wrap fetch to catch 401 (and other\n // non-tRPC error) responses. The pod's auth middleware replies with a plain\n // JSON body that is not a tRPC batch array; left untouched it crashes the\n // superjson transformer. We notify the handler and rewrite the body into a\n // valid tRPC error envelope so the query rejects cleanly.\n const wrappedFetch: typeof fetch = onAuthError\n ? async (input, init) => {\n const response = await baseFetch(input, init);\n if (response.ok) return response;\n\n const cloned = response.clone();\n let body = \"\";\n try {\n body = await cloned.text();\n } catch {\n body = \"\";\n }\n\n let isTrpcFormat = false;\n try {\n isTrpcFormat = Array.isArray(JSON.parse(body));\n } catch {\n isTrpcFormat = false;\n }\n if (isTrpcFormat) return response;\n\n const parsedMessage = (() => {\n try {\n const parsed = JSON.parse(body) as {\n error?: string;\n message?: string;\n };\n return parsed.error ?? parsed.message ?? null;\n } catch {\n return null;\n }\n })();\n // Never forward a server-controlled string as user-facing copy — map by\n // status. The raw server detail is preserved (untrusted) on `data.detail`.\n const message =\n response.status === 401\n ? \"Session expired. Please sign in again.\"\n : `Request failed (${response.status}).`;\n\n if (response.status === 401) {\n onAuthError({ status: 401, message });\n }\n\n const trpcError = [\n {\n error: {\n message,\n code: response.status === 401 ? -32001 : -32000,\n data: {\n code:\n response.status === 401\n ? \"UNAUTHORIZED\"\n : \"INTERNAL_SERVER_ERROR\",\n httpStatus: response.status,\n // Server-supplied detail — untrusted; consumers must escape it\n // before rendering (never inject as HTML).\n detail: parsedMessage ?? undefined,\n },\n\n },\n },\n ];\n return new Response(JSON.stringify(trpcError), {\n status: response.status,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n : baseFetch;\n\n return createTRPCClient<AppRouter>({\n links: [\n httpBatchLink({\n url,\n transformer: superjson,\n fetch: wrappedFetch,\n headers: () => ({\n // Session token mode (Kratos, preferred for non-browser clients)\n ...(options.sessionToken ? { \"x-session-token\": options.sessionToken } : {}),\n // API key mode (Bearer, for legacy SDK usage)\n ...(apiKey && !options.sessionToken ? { Authorization: `Bearer ${apiKey}` } : {}),\n ...(workspaceId ? { \"x-workspace-id\": workspaceId } : {}),\n ...extraHeaders,\n }),\n }),\n ],\n });\n}\n\nexport type SynapClient = ReturnType<typeof createSynapClient>;\n\n// Re-export type helpers so consumers don't need @trpc/server\nexport type { AppRouter };\n"],"mappings":";AAmBA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,OAAO,eAAe;AA2Df,SAAS,kBACd,SAC6B;AAC7B,QAAM,EAAE,QAAQ,QAAQ,aAAa,cAAc,YAAY,IAAI;AAEnE,QAAM,MAAM,GAAG,OAAO,QAAQ,OAAO,EAAE,CAAC;AAKxC,QAAM,YAA0B,CAAC,OAAO,SACtC,MAAM,OAAO,EAAE,GAAG,MAAM,aAAa,UAAU,CAAC;AAOlD,QAAM,eAA6B,cAC/B,OAAO,OAAO,SAAS;AACrB,UAAM,WAAW,MAAM,UAAU,OAAO,IAAI;AAC5C,QAAI,SAAS,GAAI,QAAO;AAExB,UAAM,SAAS,SAAS,MAAM;AAC9B,QAAI,OAAO;AACX,QAAI;AACF,aAAO,MAAM,OAAO,KAAK;AAAA,IAC3B,QAAQ;AACN,aAAO;AAAA,IACT;AAEA,QAAI,eAAe;AACnB,QAAI;AACF,qBAAe,MAAM,QAAQ,KAAK,MAAM,IAAI,CAAC;AAAA,IAC/C,QAAQ;AACN,qBAAe;AAAA,IACjB;AACA,QAAI,aAAc,QAAO;AAEzB,UAAM,iBAAiB,MAAM;AAC3B,UAAI;AACF,cAAM,SAAS,KAAK,MAAM,IAAI;AAI9B,eAAO,OAAO,SAAS,OAAO,WAAW;AAAA,MAC3C,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF,GAAG;AAGH,UAAM,UACJ,SAAS,WAAW,MAChB,2CACA,mBAAmB,SAAS,MAAM;AAExC,QAAI,SAAS,WAAW,KAAK;AAC3B,kBAAY,EAAE,QAAQ,KAAK,QAAQ,CAAC;AAAA,IACtC;AAEA,UAAM,YAAY;AAAA,MAChB;AAAA,QACE,OAAO;AAAA,UACL;AAAA,UACA,MAAM,SAAS,WAAW,MAAM,SAAS;AAAA,UACzC,MAAM;AAAA,YACJ,MACE,SAAS,WAAW,MAChB,iBACA;AAAA,YACN,YAAY,SAAS;AAAA;AAAA;AAAA,YAGrB,QAAQ,iBAAiB;AAAA,UAC3B;AAAA,QAEF;AAAA,MACF;AAAA,IACF;AACA,WAAO,IAAI,SAAS,KAAK,UAAU,SAAS,GAAG;AAAA,MAC7C,QAAQ,SAAS;AAAA,MACjB,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAChD,CAAC;AAAA,EACH,IACA;AAEJ,SAAO,iBAA4B;AAAA,IACjC,OAAO;AAAA,MACL,cAAc;AAAA,QACZ;AAAA,QACA,aAAa;AAAA,QACb,OAAO;AAAA,QACP,SAAS,OAAO;AAAA;AAAA,UAEd,GAAI,QAAQ,eAAe,EAAE,mBAAmB,QAAQ,aAAa,IAAI,CAAC;AAAA;AAAA,UAE1E,GAAI,UAAU,CAAC,QAAQ,eAAe,EAAE,eAAe,UAAU,MAAM,GAAG,IAAI,CAAC;AAAA,UAC/E,GAAI,cAAc,EAAE,kBAAkB,YAAY,IAAI,CAAC;AAAA,UACvD,GAAG;AAAA,QACL;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;","names":[]}
package/package.json CHANGED
@@ -1,12 +1,9 @@
1
1
  {
2
2
  "name": "@synap-core/sdk",
3
- "version": "0.2.0",
4
- "publishConfig": {
5
- "access": "public"
6
- },
7
- "description": "High-level SDK for Synap - Event-sourced personal data platform",
3
+ "version": "1.1.0",
4
+ "description": "Type-safe tRPC client SDK for Synap data pods",
8
5
  "type": "module",
9
- "main": "./dist/index.js",
6
+ "main": "./dist/index.cjs",
10
7
  "module": "./dist/index.js",
11
8
  "types": "./dist/index.d.ts",
12
9
  "exports": {
@@ -14,39 +11,53 @@
14
11
  "types": "./dist/index.d.ts",
15
12
  "import": "./dist/index.js",
16
13
  "require": "./dist/index.cjs"
14
+ },
15
+ "./public": {
16
+ "types": "./dist/public.d.ts",
17
+ "import": "./dist/public.js",
18
+ "require": "./dist/public.cjs"
17
19
  }
18
20
  },
21
+ "files": [
22
+ "dist",
23
+ "src",
24
+ "!src/__tests__"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsup",
28
+ "typecheck": "tsc --noEmit",
29
+ "test": "vitest run"
30
+ },
19
31
  "keywords": [
20
32
  "synap",
21
33
  "sdk",
22
- "event-sourcing",
23
- "personal-data",
24
- "knowledge-graph"
34
+ "trpc",
35
+ "data-pod"
25
36
  ],
26
- "author": "Synap Team",
27
- "license": "AGPL-3.0",
28
37
  "dependencies": {
29
- "@synap-core/client": "^0.1.0",
30
- "@synap-core/types": "^0.1.0"
38
+ "@synap-core/api-types": "^1.25.7",
39
+ "@trpc/client": "^11.10.0",
40
+ "superjson": "^2.2.6"
31
41
  },
32
42
  "devDependencies": {
33
- "@types/node": "^20.10.0",
34
- "typescript": "^5.3.3"
43
+ "tsup": "^8.3.5",
44
+ "typescript": "^5.7.3"
45
+ },
46
+ "peerDependencies": {
47
+ "@trpc/server": "^11.0.0"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "@trpc/server": {
51
+ "optional": true
52
+ }
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
35
56
  },
36
- "files": [
37
- "dist",
38
- "README.md"
39
- ],
40
57
  "repository": {
41
58
  "type": "git",
42
- "url": "https://github.com/synap-core/synap-backend",
59
+ "url": "https://github.com/synap/synap-app.git",
43
60
  "directory": "packages/sdk"
44
61
  },
45
- "homepage": "https://github.com/synap-core/synap-backend#readme",
46
- "scripts": {
47
- "build": "tsc -p tsconfig.json",
48
- "dev": "tsc -p tsconfig.json --watch",
49
- "clean": "rm -rf dist",
50
- "typecheck": "tsc --noEmit"
51
- }
52
- }
62
+ "license": "MIT"
63
+ }
package/src/client.ts ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * @synap-core/sdk — Type-safe tRPC client for Synap data pods.
3
+ *
4
+ * Usage:
5
+ * ```typescript
6
+ * import { createSynapClient } from "@synap-core/sdk";
7
+ *
8
+ * const synap = createSynapClient({
9
+ * podUrl: "https://pod.example.com",
10
+ * apiKey: "sk_live_...",
11
+ * workspaceId: "ws_...",
12
+ * });
13
+ *
14
+ * // Fully typed — autocomplete works on all 47+ routers
15
+ * const entities = await synap.entities.list.query({ limit: 20 });
16
+ * const workspace = await synap.workspaces.get.query();
17
+ * ```
18
+ */
19
+
20
+ import {
21
+ createTRPCClient,
22
+ httpBatchLink,
23
+ type CreateTRPCClient,
24
+ } from "@trpc/client";
25
+ import superjson from "superjson";
26
+ import type { AppRouter } from "@synap-core/api-types";
27
+
28
+ export interface SynapClientOptions {
29
+ /**
30
+ * Base URL of the data pod (no trailing slash, no `/trpc` suffix).
31
+ * @example "https://pod.example.com"
32
+ */
33
+ podUrl: string;
34
+
35
+ /**
36
+ * Ory Kratos session token (for example, from the Pod's
37
+ * `/api/federation/exchange` endpoint).
38
+ * Sent as `X-Session-Token` header — preferred for non-browser clients
39
+ * like extensions, CLI tools, and mobile apps.
40
+ * @example "oathkeeper_token_..."
41
+ */
42
+ sessionToken?: string;
43
+
44
+ /**
45
+ * API key for authentication (Bearer token).
46
+ * Generate one in your workspace developer settings.
47
+ * If omitted, the client falls back to cookie-based Kratos session auth.
48
+ * @example "sk_live_abc123..."
49
+ */
50
+ apiKey?: string;
51
+
52
+ /**
53
+ * Workspace ID to scope all requests to.
54
+ * Pass empty string for procedures that don't require workspace context
55
+ * (e.g. workspaces.list, which is protectedProcedure only).
56
+ * @example "ws_01jk..."
57
+ */
58
+ workspaceId: string;
59
+
60
+ /**
61
+ * Additional headers to include in every request.
62
+ */
63
+ extraHeaders?: Record<string, string>;
64
+
65
+ /**
66
+ * Called when the pod returns a `401 Unauthorized` (expired/invalid session
67
+ * or API key). The app should sign out and re-authenticate (re-handshake).
68
+ *
69
+ * The pod's auth middleware can reply with a plain-JSON body
70
+ * (`{"error":"Invalid session"}`) that is NOT in tRPC batch format and would
71
+ * otherwise crash the superjson transformer; when an `onAuthError` handler is
72
+ * provided the client rewrites such responses into a well-formed tRPC error so
73
+ * the query rejects gracefully instead of throwing a parse error.
74
+ */
75
+ onAuthError?: (error: { status: number; message: string }) => void;
76
+ }
77
+
78
+ /**
79
+ * Creates a fully-typed tRPC client connected to a Synap data pod.
80
+ *
81
+ * All 47+ tRPC routers are available with full TypeScript autocomplete
82
+ * and compile-time safety. Auth is handled via Bearer token + workspace header.
83
+ */
84
+ export function createSynapClient(
85
+ options: SynapClientOptions,
86
+ ): CreateTRPCClient<AppRouter> {
87
+ const { podUrl, apiKey, workspaceId, extraHeaders, onAuthError } = options;
88
+
89
+ const url = `${podUrl.replace(/\/$/, "")}/trpc`;
90
+
91
+ // Base fetch: always include credentials so session cookies are sent in
92
+ // cookie-auth mode. When apiKey is present, the Bearer token takes precedence
93
+ // on the pod.
94
+ const baseFetch: typeof fetch = (input, init) =>
95
+ fetch(input, { ...init, credentials: "include" });
96
+
97
+ // When an onAuthError handler is provided, wrap fetch to catch 401 (and other
98
+ // non-tRPC error) responses. The pod's auth middleware replies with a plain
99
+ // JSON body that is not a tRPC batch array; left untouched it crashes the
100
+ // superjson transformer. We notify the handler and rewrite the body into a
101
+ // valid tRPC error envelope so the query rejects cleanly.
102
+ const wrappedFetch: typeof fetch = onAuthError
103
+ ? async (input, init) => {
104
+ const response = await baseFetch(input, init);
105
+ if (response.ok) return response;
106
+
107
+ const cloned = response.clone();
108
+ let body = "";
109
+ try {
110
+ body = await cloned.text();
111
+ } catch {
112
+ body = "";
113
+ }
114
+
115
+ let isTrpcFormat = false;
116
+ try {
117
+ isTrpcFormat = Array.isArray(JSON.parse(body));
118
+ } catch {
119
+ isTrpcFormat = false;
120
+ }
121
+ if (isTrpcFormat) return response;
122
+
123
+ const parsedMessage = (() => {
124
+ try {
125
+ const parsed = JSON.parse(body) as {
126
+ error?: string;
127
+ message?: string;
128
+ };
129
+ return parsed.error ?? parsed.message ?? null;
130
+ } catch {
131
+ return null;
132
+ }
133
+ })();
134
+ // Never forward a server-controlled string as user-facing copy — map by
135
+ // status. The raw server detail is preserved (untrusted) on `data.detail`.
136
+ const message =
137
+ response.status === 401
138
+ ? "Session expired. Please sign in again."
139
+ : `Request failed (${response.status}).`;
140
+
141
+ if (response.status === 401) {
142
+ onAuthError({ status: 401, message });
143
+ }
144
+
145
+ const trpcError = [
146
+ {
147
+ error: {
148
+ message,
149
+ code: response.status === 401 ? -32001 : -32000,
150
+ data: {
151
+ code:
152
+ response.status === 401
153
+ ? "UNAUTHORIZED"
154
+ : "INTERNAL_SERVER_ERROR",
155
+ httpStatus: response.status,
156
+ // Server-supplied detail — untrusted; consumers must escape it
157
+ // before rendering (never inject as HTML).
158
+ detail: parsedMessage ?? undefined,
159
+ },
160
+
161
+ },
162
+ },
163
+ ];
164
+ return new Response(JSON.stringify(trpcError), {
165
+ status: response.status,
166
+ headers: { "content-type": "application/json" },
167
+ });
168
+ }
169
+ : baseFetch;
170
+
171
+ return createTRPCClient<AppRouter>({
172
+ links: [
173
+ httpBatchLink({
174
+ url,
175
+ transformer: superjson,
176
+ fetch: wrappedFetch,
177
+ headers: () => ({
178
+ // Session token mode (Kratos, preferred for non-browser clients)
179
+ ...(options.sessionToken ? { "x-session-token": options.sessionToken } : {}),
180
+ // API key mode (Bearer, for legacy SDK usage)
181
+ ...(apiKey && !options.sessionToken ? { Authorization: `Bearer ${apiKey}` } : {}),
182
+ ...(workspaceId ? { "x-workspace-id": workspaceId } : {}),
183
+ ...extraHeaders,
184
+ }),
185
+ }),
186
+ ],
187
+ });
188
+ }
189
+
190
+ export type SynapClient = ReturnType<typeof createSynapClient>;
191
+
192
+ // Re-export type helpers so consumers don't need @trpc/server
193
+ export type { AppRouter };
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { createSynapClient } from "./client";
2
+ export type { SynapClient, SynapClientOptions, AppRouter } from "./client";