@sintaksdev/sdk 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,83 @@
1
- # Temporary Holding Version
1
+ # @sintaksdev/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
+ TypeScript client for the [sintaks.dev](https://sintaks.dev) OpenAI-compatible AI API gateway. Top up in IDR via QRIS/iPaymu, call chat and image models, and pay per request. Zero runtime dependencies (Node >= 18, global `fetch`).
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @sintaksdev/sdk
9
+ # or
10
+ npm install @sintaksdev/sdk
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { Sintaks } from "@sintaksdev/sdk";
17
+
18
+ const client = new Sintaks({ apiKey: "sk-..." });
19
+
20
+ // Non-streaming chat
21
+ const resp = await client.chat.completions.create({
22
+ model: "claude-sonnet-5-5",
23
+ messages: [{ role: "user", content: "Halo!" }],
24
+ });
25
+ console.log(resp.choices[0]?.message.content);
26
+
27
+ // Streaming
28
+ const stream = await client.chat.completions.create({
29
+ model: "claude-sonnet-5-5",
30
+ messages: [{ role: "user", content: "Halo!" }],
31
+ stream: true,
32
+ });
33
+ for await (const chunk of stream) {
34
+ process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
35
+ }
36
+
37
+ // Image generation
38
+ const images = await client.images.generate({
39
+ prompt: "A futuristic Jakarta skyline at dusk",
40
+ });
41
+ console.log(images.data[0]?.url);
42
+
43
+ // List active models
44
+ const models = await client.models.list();
45
+ console.log(models.data.map((m) => m.id));
46
+ ```
47
+
48
+ `model` defaults to `claude-sonnet-5-5` for chat and `stable-image-core` for
49
+ images when omitted. Streaming requests ask for `stream_options.include_usage`,
50
+ so the final chunk carries `usage`. Point at another environment with `baseURL`:
51
+
52
+ ```ts
53
+ const client = new Sintaks({ apiKey: "sk-...", baseURL: "http://localhost:8080" });
54
+ ```
55
+
56
+ ## Errors
57
+
58
+ Failures throw `SintaksError` with `status`, `type`, `code`, and `requestId` (the gateway `X-Request-ID`, useful for support). Convenience getters map the gateway's status semantics:
59
+
60
+ ```ts
61
+ try {
62
+ await client.chat.completions.create({ messages: [{ role: "user", content: "x" }] });
63
+ } catch (err) {
64
+ if (err instanceof SintaksError) {
65
+ if (err.isUnauthorized) console.error("invalid or revoked api key");
66
+ if (err.isInsufficientCredits) console.error("insufficient balance, top up first");
67
+ if (err.isRetryable) console.error(`retry after ${err.requestId}`);
68
+ }
69
+ }
70
+ ```
71
+
72
+ ## Development & publishing
73
+
74
+ ```bash
75
+ pnpm install
76
+ pnpm typecheck
77
+ pnpm build # tsup → dist/ (ESM + CJS + types)
78
+ pnpm pack # inspect the publish tarball
79
+ npm login # one-time auth for your npm account
80
+ npm publish # requires an account with access to the @sintaksdev scope
81
+ ```
82
+
83
+ `prepublishOnly` runs the build automatically, so `npm publish` ships fresh `dist/`. Publish to a different registry (e.g. GitHub Packages, Verdaccio) with `npm publish --registry <url>`.
package/dist/index.cjs ADDED
@@ -0,0 +1,212 @@
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
+ DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
24
+ DEFAULT_CHAT_MODEL: () => DEFAULT_CHAT_MODEL,
25
+ DEFAULT_IMAGE_MODEL: () => DEFAULT_IMAGE_MODEL,
26
+ Sintaks: () => Sintaks,
27
+ SintaksError: () => SintaksError,
28
+ default: () => index_default
29
+ });
30
+ module.exports = __toCommonJS(index_exports);
31
+ var DEFAULT_BASE_URL = "https://api.sintaks.dev";
32
+ var DEFAULT_CHAT_MODEL = "claude-sonnet-5-5";
33
+ var DEFAULT_IMAGE_MODEL = "stable-image-core";
34
+ var SintaksError = class extends Error {
35
+ status;
36
+ type;
37
+ code;
38
+ requestId;
39
+ constructor(status, message, opts = {}) {
40
+ super(message);
41
+ this.name = "SintaksError";
42
+ this.status = status;
43
+ this.type = opts.type;
44
+ this.code = opts.code ?? null;
45
+ this.requestId = opts.requestId ?? null;
46
+ }
47
+ /** True for missing, malformed, revoked, or invalid API keys (401). */
48
+ get isUnauthorized() {
49
+ return this.status === 401;
50
+ }
51
+ /** True when the account balance can't cover the request (402). Top up first. */
52
+ get isInsufficientCredits() {
53
+ return this.status === 402;
54
+ }
55
+ /** True for upstream throttling (429). */
56
+ get isRateLimited() {
57
+ return this.status === 429;
58
+ }
59
+ /** True for errors worth retrying with backoff: 429, 503, 504. */
60
+ get isRetryable() {
61
+ return this.status === 429 || this.status === 503 || this.status === 504;
62
+ }
63
+ };
64
+ var Sintaks = class {
65
+ apiKey;
66
+ baseURL;
67
+ chat;
68
+ images;
69
+ models;
70
+ /** @internal */
71
+ fetchFn;
72
+ /** @internal */
73
+ extraHeaders;
74
+ constructor(options) {
75
+ if (!options.apiKey) throw new Error("Sintaks: apiKey is required");
76
+ this.apiKey = options.apiKey;
77
+ this.baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
78
+ this.fetchFn = options.fetch ?? fetch;
79
+ this.extraHeaders = options.headers ?? {};
80
+ this.chat = new ChatResource(this);
81
+ this.images = new ImagesResource(this);
82
+ this.models = new ModelsResource(this);
83
+ }
84
+ async request(method, path, body) {
85
+ const res = await this.fetchFn(`${this.baseURL}${path}`, {
86
+ method,
87
+ headers: {
88
+ Authorization: `Bearer ${this.apiKey}`,
89
+ "Content-Type": "application/json",
90
+ ...this.extraHeaders
91
+ },
92
+ body: body === void 0 ? void 0 : JSON.stringify(body)
93
+ });
94
+ if (!res.ok) {
95
+ let envelope = {};
96
+ try {
97
+ envelope = await res.json();
98
+ } catch {
99
+ }
100
+ throw new SintaksError(res.status, envelope.error?.message ?? `request failed with ${res.status}`, {
101
+ type: envelope.error?.type,
102
+ code: envelope.error?.code,
103
+ requestId: res.headers.get("x-request-id")
104
+ });
105
+ }
106
+ return await res.json();
107
+ }
108
+ };
109
+ var ChatResource = class {
110
+ constructor(client) {
111
+ this.client = client;
112
+ }
113
+ client;
114
+ completions = this;
115
+ async create(params) {
116
+ if (params.stream) {
117
+ return this.createStream(params);
118
+ }
119
+ return this.client.request("POST", "/v1/chat/completions", {
120
+ ...params,
121
+ model: params.model ?? DEFAULT_CHAT_MODEL
122
+ });
123
+ }
124
+ async createStream(params) {
125
+ const res = await this.client.fetchFn(`${this.client.baseURL}/v1/chat/completions`, {
126
+ method: "POST",
127
+ headers: {
128
+ Authorization: `Bearer ${this.client.apiKey}`,
129
+ "Content-Type": "application/json",
130
+ Accept: "text/event-stream",
131
+ ...this.client.extraHeaders
132
+ },
133
+ body: JSON.stringify({
134
+ ...params,
135
+ model: params.model ?? DEFAULT_CHAT_MODEL,
136
+ stream_options: { include_usage: true }
137
+ })
138
+ });
139
+ if (!res.ok || !res.body) {
140
+ let envelope = {};
141
+ try {
142
+ envelope = await res.json();
143
+ } catch {
144
+ }
145
+ throw new SintaksError(res.status, envelope.error?.message ?? `request failed with ${res.status}`, {
146
+ type: envelope.error?.type,
147
+ code: envelope.error?.code,
148
+ requestId: res.headers.get("x-request-id")
149
+ });
150
+ }
151
+ return parseSSE(res.body);
152
+ }
153
+ };
154
+ async function* parseSSE(body) {
155
+ const reader = body.getReader();
156
+ const decoder = new TextDecoder();
157
+ let buffer = "";
158
+ try {
159
+ while (true) {
160
+ const { done, value } = await reader.read();
161
+ if (done) break;
162
+ buffer += decoder.decode(value, { stream: true });
163
+ let boundary;
164
+ while ((boundary = buffer.indexOf("\n\n")) !== -1) {
165
+ const chunk = buffer.slice(0, boundary);
166
+ buffer = buffer.slice(boundary + 2);
167
+ const dataLine = chunk.split("\n").find((line) => line.startsWith("data:"));
168
+ if (!dataLine) continue;
169
+ const payload = dataLine.slice(5).trim();
170
+ if (payload === "[DONE]") return;
171
+ try {
172
+ yield JSON.parse(payload);
173
+ } catch {
174
+ }
175
+ }
176
+ }
177
+ } finally {
178
+ reader.releaseLock();
179
+ }
180
+ }
181
+ var ImagesResource = class {
182
+ constructor(client) {
183
+ this.client = client;
184
+ }
185
+ client;
186
+ async generate(params) {
187
+ return this.client.request("POST", "/v1/images/generations", {
188
+ ...params,
189
+ model: params.model ?? DEFAULT_IMAGE_MODEL
190
+ });
191
+ }
192
+ };
193
+ var ModelsResource = class {
194
+ constructor(client) {
195
+ this.client = client;
196
+ }
197
+ client;
198
+ /** Lists the active models served by the gateway (GET /v1/models). */
199
+ async list() {
200
+ return this.client.request("GET", "/v1/models");
201
+ }
202
+ };
203
+ var index_default = Sintaks;
204
+ // Annotate the CommonJS export names for ESM import in node:
205
+ 0 && (module.exports = {
206
+ DEFAULT_BASE_URL,
207
+ DEFAULT_CHAT_MODEL,
208
+ DEFAULT_IMAGE_MODEL,
209
+ Sintaks,
210
+ SintaksError
211
+ });
212
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @sintaksdev/sdk — TypeScript client for the sintaks.dev OpenAI-compatible\n * AI API gateway. Zero runtime dependencies; requires Node >= 18 (global fetch).\n */\n\nexport const DEFAULT_BASE_URL = \"https://api.sintaks.dev\";\nexport const DEFAULT_CHAT_MODEL = \"claude-sonnet-5-5\";\nexport const DEFAULT_IMAGE_MODEL = \"stable-image-core\";\n\n/* ------------------------------------------------------------------ */\n/* Types (OpenAI-compatible shapes) */\n/* ------------------------------------------------------------------ */\n\nexport type MessageContentPart = { type: \"text\"; text: string };\n\nexport interface ChatMessage {\n role: \"system\" | \"developer\" | \"user\" | \"assistant\" | \"tool\";\n content: string | MessageContentPart[];\n name?: string;\n}\n\nexport interface ChatCompletionCreateParams {\n model?: string;\n messages: ChatMessage[];\n stream?: boolean;\n stream_options?: { include_usage?: boolean };\n temperature?: number;\n top_p?: number;\n max_tokens?: number;\n max_completion_tokens?: number;\n stop?: string | string[];\n [key: string]: unknown;\n}\n\nexport interface Usage {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n}\n\nexport interface ChatCompletion {\n id: string;\n object: \"chat.completion\";\n created: number;\n model: string;\n choices: {\n index: number;\n message: ChatMessage;\n finish_reason: string | null;\n }[];\n usage?: Usage;\n}\n\nexport interface ChatCompletionChunk {\n id: string;\n object: \"chat.completion.chunk\";\n created: number;\n model: string;\n choices: {\n index: number;\n delta: { role?: string; content?: string | null };\n finish_reason: string | null;\n }[];\n usage?: Usage;\n}\n\nexport interface Model {\n id: string;\n object: \"model\";\n created: number;\n owned_by: string;\n}\n\nexport interface ModelList {\n object: \"list\";\n data: Model[];\n}\n\nexport interface ImageGenerationParams {\n model?: string;\n prompt: string;\n n?: number;\n size?: string;\n [key: string]: unknown;\n}\n\nexport interface GeneratedImage {\n url?: string;\n b64_json?: string;\n}\n\nexport interface ImageGenerationResult {\n created: number;\n data: GeneratedImage[];\n}\n\nexport interface ErrorEnvelope {\n error?: {\n message?: string;\n type?: string;\n param?: string | null;\n code?: string | null;\n };\n}\n\n/* ------------------------------------------------------------------ */\n/* Error */\n/* ------------------------------------------------------------------ */\n\nexport class SintaksError extends Error {\n readonly status: number;\n readonly type: string | undefined;\n readonly code: string | null;\n readonly requestId: string | null;\n\n constructor(\n status: number,\n message: string,\n opts: { type?: string; code?: string | null; requestId?: string | null } = {},\n ) {\n super(message);\n this.name = \"SintaksError\";\n this.status = status;\n this.type = opts.type;\n this.code = opts.code ?? null;\n this.requestId = opts.requestId ?? null;\n }\n\n /** True for missing, malformed, revoked, or invalid API keys (401). */\n get isUnauthorized(): boolean {\n return this.status === 401;\n }\n\n /** True when the account balance can't cover the request (402). Top up first. */\n get isInsufficientCredits(): boolean {\n return this.status === 402;\n }\n\n /** True for upstream throttling (429). */\n get isRateLimited(): boolean {\n return this.status === 429;\n }\n\n /** True for errors worth retrying with backoff: 429, 503, 504. */\n get isRetryable(): boolean {\n return this.status === 429 || this.status === 503 || this.status === 504;\n }\n}\n\n/* ------------------------------------------------------------------ */\n/* Client */\n/* ------------------------------------------------------------------ */\n\nexport interface SintaksOptions {\n apiKey: string;\n baseURL?: string;\n fetch?: typeof fetch;\n headers?: Record<string, string>;\n}\n\nexport class Sintaks {\n readonly apiKey: string;\n readonly baseURL: string;\n readonly chat: ChatResource;\n readonly images: ImagesResource;\n readonly models: ModelsResource;\n\n /** @internal */\n readonly fetchFn: typeof fetch;\n /** @internal */\n readonly extraHeaders: Record<string, string>;\n\n constructor(options: SintaksOptions) {\n if (!options.apiKey) throw new Error(\"Sintaks: apiKey is required\");\n this.apiKey = options.apiKey;\n this.baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n this.fetchFn = options.fetch ?? fetch;\n this.extraHeaders = options.headers ?? {};\n this.chat = new ChatResource(this);\n this.images = new ImagesResource(this);\n this.models = new ModelsResource(this);\n }\n\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const res = await this.fetchFn(`${this.baseURL}${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...this.extraHeaders,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n\n if (!res.ok) {\n let envelope: ErrorEnvelope = {};\n try {\n envelope = (await res.json()) as ErrorEnvelope;\n } catch {\n // non-JSON error body; fall through with defaults\n }\n throw new SintaksError(res.status, envelope.error?.message ?? `request failed with ${res.status}`, {\n type: envelope.error?.type,\n code: envelope.error?.code,\n requestId: res.headers.get(\"x-request-id\"),\n });\n }\n return (await res.json()) as T;\n }\n}\n\n/* ------------------------------------------------------------------ */\n/* Chat */\n/* ------------------------------------------------------------------ */\n\nclass ChatResource {\n readonly completions = this;\n\n constructor(private client: Sintaks) {}\n\n async create(params: ChatCompletionCreateParams): Promise<ChatCompletion>;\n async create(params: ChatCompletionCreateParams & { stream: true }): Promise<AsyncIterable<ChatCompletionChunk>>;\n async create(\n params: ChatCompletionCreateParams,\n ): Promise<ChatCompletion | AsyncIterable<ChatCompletionChunk>> {\n if (params.stream) {\n return this.createStream(params as ChatCompletionCreateParams & { stream: true });\n }\n return this.client.request<ChatCompletion>(\"POST\", \"/v1/chat/completions\", {\n ...params,\n model: params.model ?? DEFAULT_CHAT_MODEL,\n });\n }\n\n private async createStream(\n params: ChatCompletionCreateParams & { stream: true },\n ): Promise<AsyncIterable<ChatCompletionChunk>> {\n const res = await this.client.fetchFn(`${this.client.baseURL}/v1/chat/completions`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.client.apiKey}`,\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n ...this.client.extraHeaders,\n },\n body: JSON.stringify({\n ...params,\n model: params.model ?? DEFAULT_CHAT_MODEL,\n stream_options: { include_usage: true },\n }),\n });\n\n if (!res.ok || !res.body) {\n let envelope: ErrorEnvelope = {};\n try {\n envelope = (await res.json()) as ErrorEnvelope;\n } catch {\n // ignore\n }\n throw new SintaksError(res.status, envelope.error?.message ?? `request failed with ${res.status}`, {\n type: envelope.error?.type,\n code: envelope.error?.code,\n requestId: res.headers.get(\"x-request-id\"),\n });\n }\n\n return parseSSE<ChatCompletionChunk>(res.body);\n }\n}\n\n/** Minimal SSE parser for OpenAI-style `data:` events. */\nasync function* parseSSE<T>(body: ReadableStream<Uint8Array>): AsyncIterable<T> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let boundary: number;\n while ((boundary = buffer.indexOf(\"\\n\\n\")) !== -1) {\n const chunk = buffer.slice(0, boundary);\n buffer = buffer.slice(boundary + 2);\n const dataLine = chunk\n .split(\"\\n\")\n .find((line) => line.startsWith(\"data:\"));\n if (!dataLine) continue;\n const payload = dataLine.slice(5).trim();\n if (payload === \"[DONE]\") return;\n try {\n yield JSON.parse(payload) as T;\n } catch {\n // skip malformed event\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/* ------------------------------------------------------------------ */\n/* Images */\n/* ------------------------------------------------------------------ */\n\nclass ImagesResource {\n constructor(private client: Sintaks) {}\n\n async generate(params: ImageGenerationParams): Promise<ImageGenerationResult> {\n return this.client.request<ImageGenerationResult>(\"POST\", \"/v1/images/generations\", {\n ...params,\n model: params.model ?? DEFAULT_IMAGE_MODEL,\n });\n }\n}\n\nclass ModelsResource {\n constructor(private client: Sintaks) {}\n\n /** Lists the active models served by the gateway (GET /v1/models). */\n async list(): Promise<ModelList> {\n return this.client.request<ModelList>(\"GET\", \"/v1/models\");\n }\n}\n\nexport default Sintaks;"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKO,IAAM,mBAAmB;AACzB,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB;AAsG5B,IAAM,eAAN,cAA2B,MAAM;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,QACA,SACA,OAA2E,CAAC,GAC5E;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO,KAAK;AACjB,SAAK,OAAO,KAAK,QAAQ;AACzB,SAAK,YAAY,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AAiB;AAAjB;AAAA,EAAkB;AAAA,EAAlB;AAAA;AAAA,EAGpB,MAAM,OAA2B;AAC/B,WAAO,KAAK,OAAO,QAAmB,OAAO,YAAY;AAAA,EAC3D;AACF;AAEA,IAAO,gBAAQ;","names":[]}
@@ -0,0 +1,156 @@
1
+ /**
2
+ * @sintaksdev/sdk — TypeScript client for the sintaks.dev OpenAI-compatible
3
+ * AI API gateway. Zero runtime dependencies; requires Node >= 18 (global fetch).
4
+ */
5
+ declare const DEFAULT_BASE_URL = "https://api.sintaks.dev";
6
+ declare const DEFAULT_CHAT_MODEL = "claude-sonnet-5-5";
7
+ declare const DEFAULT_IMAGE_MODEL = "stable-image-core";
8
+ type MessageContentPart = {
9
+ type: "text";
10
+ text: string;
11
+ };
12
+ interface ChatMessage {
13
+ role: "system" | "developer" | "user" | "assistant" | "tool";
14
+ content: string | MessageContentPart[];
15
+ name?: string;
16
+ }
17
+ interface ChatCompletionCreateParams {
18
+ model?: string;
19
+ messages: ChatMessage[];
20
+ stream?: boolean;
21
+ stream_options?: {
22
+ include_usage?: boolean;
23
+ };
24
+ temperature?: number;
25
+ top_p?: number;
26
+ max_tokens?: number;
27
+ max_completion_tokens?: number;
28
+ stop?: string | string[];
29
+ [key: string]: unknown;
30
+ }
31
+ interface Usage {
32
+ prompt_tokens: number;
33
+ completion_tokens: number;
34
+ total_tokens: number;
35
+ }
36
+ interface ChatCompletion {
37
+ id: string;
38
+ object: "chat.completion";
39
+ created: number;
40
+ model: string;
41
+ choices: {
42
+ index: number;
43
+ message: ChatMessage;
44
+ finish_reason: string | null;
45
+ }[];
46
+ usage?: Usage;
47
+ }
48
+ interface ChatCompletionChunk {
49
+ id: string;
50
+ object: "chat.completion.chunk";
51
+ created: number;
52
+ model: string;
53
+ choices: {
54
+ index: number;
55
+ delta: {
56
+ role?: string;
57
+ content?: string | null;
58
+ };
59
+ finish_reason: string | null;
60
+ }[];
61
+ usage?: Usage;
62
+ }
63
+ interface Model {
64
+ id: string;
65
+ object: "model";
66
+ created: number;
67
+ owned_by: string;
68
+ }
69
+ interface ModelList {
70
+ object: "list";
71
+ data: Model[];
72
+ }
73
+ interface ImageGenerationParams {
74
+ model?: string;
75
+ prompt: string;
76
+ n?: number;
77
+ size?: string;
78
+ [key: string]: unknown;
79
+ }
80
+ interface GeneratedImage {
81
+ url?: string;
82
+ b64_json?: string;
83
+ }
84
+ interface ImageGenerationResult {
85
+ created: number;
86
+ data: GeneratedImage[];
87
+ }
88
+ interface ErrorEnvelope {
89
+ error?: {
90
+ message?: string;
91
+ type?: string;
92
+ param?: string | null;
93
+ code?: string | null;
94
+ };
95
+ }
96
+ declare class SintaksError extends Error {
97
+ readonly status: number;
98
+ readonly type: string | undefined;
99
+ readonly code: string | null;
100
+ readonly requestId: string | null;
101
+ constructor(status: number, message: string, opts?: {
102
+ type?: string;
103
+ code?: string | null;
104
+ requestId?: string | null;
105
+ });
106
+ /** True for missing, malformed, revoked, or invalid API keys (401). */
107
+ get isUnauthorized(): boolean;
108
+ /** True when the account balance can't cover the request (402). Top up first. */
109
+ get isInsufficientCredits(): boolean;
110
+ /** True for upstream throttling (429). */
111
+ get isRateLimited(): boolean;
112
+ /** True for errors worth retrying with backoff: 429, 503, 504. */
113
+ get isRetryable(): boolean;
114
+ }
115
+ interface SintaksOptions {
116
+ apiKey: string;
117
+ baseURL?: string;
118
+ fetch?: typeof fetch;
119
+ headers?: Record<string, string>;
120
+ }
121
+ declare class Sintaks {
122
+ readonly apiKey: string;
123
+ readonly baseURL: string;
124
+ readonly chat: ChatResource;
125
+ readonly images: ImagesResource;
126
+ readonly models: ModelsResource;
127
+ /** @internal */
128
+ readonly fetchFn: typeof fetch;
129
+ /** @internal */
130
+ readonly extraHeaders: Record<string, string>;
131
+ constructor(options: SintaksOptions);
132
+ request<T>(method: string, path: string, body?: unknown): Promise<T>;
133
+ }
134
+ declare class ChatResource {
135
+ private client;
136
+ readonly completions: this;
137
+ constructor(client: Sintaks);
138
+ create(params: ChatCompletionCreateParams): Promise<ChatCompletion>;
139
+ create(params: ChatCompletionCreateParams & {
140
+ stream: true;
141
+ }): Promise<AsyncIterable<ChatCompletionChunk>>;
142
+ private createStream;
143
+ }
144
+ declare class ImagesResource {
145
+ private client;
146
+ constructor(client: Sintaks);
147
+ generate(params: ImageGenerationParams): Promise<ImageGenerationResult>;
148
+ }
149
+ declare class ModelsResource {
150
+ private client;
151
+ constructor(client: Sintaks);
152
+ /** Lists the active models served by the gateway (GET /v1/models). */
153
+ list(): Promise<ModelList>;
154
+ }
155
+
156
+ export { type ChatCompletion, type ChatCompletionChunk, type ChatCompletionCreateParams, type ChatMessage, DEFAULT_BASE_URL, DEFAULT_CHAT_MODEL, DEFAULT_IMAGE_MODEL, type ErrorEnvelope, type GeneratedImage, type ImageGenerationParams, type ImageGenerationResult, type MessageContentPart, type Model, type ModelList, Sintaks, SintaksError, type SintaksOptions, type Usage, Sintaks as default };
@@ -0,0 +1,156 @@
1
+ /**
2
+ * @sintaksdev/sdk — TypeScript client for the sintaks.dev OpenAI-compatible
3
+ * AI API gateway. Zero runtime dependencies; requires Node >= 18 (global fetch).
4
+ */
5
+ declare const DEFAULT_BASE_URL = "https://api.sintaks.dev";
6
+ declare const DEFAULT_CHAT_MODEL = "claude-sonnet-5-5";
7
+ declare const DEFAULT_IMAGE_MODEL = "stable-image-core";
8
+ type MessageContentPart = {
9
+ type: "text";
10
+ text: string;
11
+ };
12
+ interface ChatMessage {
13
+ role: "system" | "developer" | "user" | "assistant" | "tool";
14
+ content: string | MessageContentPart[];
15
+ name?: string;
16
+ }
17
+ interface ChatCompletionCreateParams {
18
+ model?: string;
19
+ messages: ChatMessage[];
20
+ stream?: boolean;
21
+ stream_options?: {
22
+ include_usage?: boolean;
23
+ };
24
+ temperature?: number;
25
+ top_p?: number;
26
+ max_tokens?: number;
27
+ max_completion_tokens?: number;
28
+ stop?: string | string[];
29
+ [key: string]: unknown;
30
+ }
31
+ interface Usage {
32
+ prompt_tokens: number;
33
+ completion_tokens: number;
34
+ total_tokens: number;
35
+ }
36
+ interface ChatCompletion {
37
+ id: string;
38
+ object: "chat.completion";
39
+ created: number;
40
+ model: string;
41
+ choices: {
42
+ index: number;
43
+ message: ChatMessage;
44
+ finish_reason: string | null;
45
+ }[];
46
+ usage?: Usage;
47
+ }
48
+ interface ChatCompletionChunk {
49
+ id: string;
50
+ object: "chat.completion.chunk";
51
+ created: number;
52
+ model: string;
53
+ choices: {
54
+ index: number;
55
+ delta: {
56
+ role?: string;
57
+ content?: string | null;
58
+ };
59
+ finish_reason: string | null;
60
+ }[];
61
+ usage?: Usage;
62
+ }
63
+ interface Model {
64
+ id: string;
65
+ object: "model";
66
+ created: number;
67
+ owned_by: string;
68
+ }
69
+ interface ModelList {
70
+ object: "list";
71
+ data: Model[];
72
+ }
73
+ interface ImageGenerationParams {
74
+ model?: string;
75
+ prompt: string;
76
+ n?: number;
77
+ size?: string;
78
+ [key: string]: unknown;
79
+ }
80
+ interface GeneratedImage {
81
+ url?: string;
82
+ b64_json?: string;
83
+ }
84
+ interface ImageGenerationResult {
85
+ created: number;
86
+ data: GeneratedImage[];
87
+ }
88
+ interface ErrorEnvelope {
89
+ error?: {
90
+ message?: string;
91
+ type?: string;
92
+ param?: string | null;
93
+ code?: string | null;
94
+ };
95
+ }
96
+ declare class SintaksError extends Error {
97
+ readonly status: number;
98
+ readonly type: string | undefined;
99
+ readonly code: string | null;
100
+ readonly requestId: string | null;
101
+ constructor(status: number, message: string, opts?: {
102
+ type?: string;
103
+ code?: string | null;
104
+ requestId?: string | null;
105
+ });
106
+ /** True for missing, malformed, revoked, or invalid API keys (401). */
107
+ get isUnauthorized(): boolean;
108
+ /** True when the account balance can't cover the request (402). Top up first. */
109
+ get isInsufficientCredits(): boolean;
110
+ /** True for upstream throttling (429). */
111
+ get isRateLimited(): boolean;
112
+ /** True for errors worth retrying with backoff: 429, 503, 504. */
113
+ get isRetryable(): boolean;
114
+ }
115
+ interface SintaksOptions {
116
+ apiKey: string;
117
+ baseURL?: string;
118
+ fetch?: typeof fetch;
119
+ headers?: Record<string, string>;
120
+ }
121
+ declare class Sintaks {
122
+ readonly apiKey: string;
123
+ readonly baseURL: string;
124
+ readonly chat: ChatResource;
125
+ readonly images: ImagesResource;
126
+ readonly models: ModelsResource;
127
+ /** @internal */
128
+ readonly fetchFn: typeof fetch;
129
+ /** @internal */
130
+ readonly extraHeaders: Record<string, string>;
131
+ constructor(options: SintaksOptions);
132
+ request<T>(method: string, path: string, body?: unknown): Promise<T>;
133
+ }
134
+ declare class ChatResource {
135
+ private client;
136
+ readonly completions: this;
137
+ constructor(client: Sintaks);
138
+ create(params: ChatCompletionCreateParams): Promise<ChatCompletion>;
139
+ create(params: ChatCompletionCreateParams & {
140
+ stream: true;
141
+ }): Promise<AsyncIterable<ChatCompletionChunk>>;
142
+ private createStream;
143
+ }
144
+ declare class ImagesResource {
145
+ private client;
146
+ constructor(client: Sintaks);
147
+ generate(params: ImageGenerationParams): Promise<ImageGenerationResult>;
148
+ }
149
+ declare class ModelsResource {
150
+ private client;
151
+ constructor(client: Sintaks);
152
+ /** Lists the active models served by the gateway (GET /v1/models). */
153
+ list(): Promise<ModelList>;
154
+ }
155
+
156
+ export { type ChatCompletion, type ChatCompletionChunk, type ChatCompletionCreateParams, type ChatMessage, DEFAULT_BASE_URL, DEFAULT_CHAT_MODEL, DEFAULT_IMAGE_MODEL, type ErrorEnvelope, type GeneratedImage, type ImageGenerationParams, type ImageGenerationResult, type MessageContentPart, type Model, type ModelList, Sintaks, SintaksError, type SintaksOptions, type Usage, Sintaks as default };
package/dist/index.js ADDED
@@ -0,0 +1,183 @@
1
+ // src/index.ts
2
+ var DEFAULT_BASE_URL = "https://api.sintaks.dev";
3
+ var DEFAULT_CHAT_MODEL = "claude-sonnet-5-5";
4
+ var DEFAULT_IMAGE_MODEL = "stable-image-core";
5
+ var SintaksError = class extends Error {
6
+ status;
7
+ type;
8
+ code;
9
+ requestId;
10
+ constructor(status, message, opts = {}) {
11
+ super(message);
12
+ this.name = "SintaksError";
13
+ this.status = status;
14
+ this.type = opts.type;
15
+ this.code = opts.code ?? null;
16
+ this.requestId = opts.requestId ?? null;
17
+ }
18
+ /** True for missing, malformed, revoked, or invalid API keys (401). */
19
+ get isUnauthorized() {
20
+ return this.status === 401;
21
+ }
22
+ /** True when the account balance can't cover the request (402). Top up first. */
23
+ get isInsufficientCredits() {
24
+ return this.status === 402;
25
+ }
26
+ /** True for upstream throttling (429). */
27
+ get isRateLimited() {
28
+ return this.status === 429;
29
+ }
30
+ /** True for errors worth retrying with backoff: 429, 503, 504. */
31
+ get isRetryable() {
32
+ return this.status === 429 || this.status === 503 || this.status === 504;
33
+ }
34
+ };
35
+ var Sintaks = class {
36
+ apiKey;
37
+ baseURL;
38
+ chat;
39
+ images;
40
+ models;
41
+ /** @internal */
42
+ fetchFn;
43
+ /** @internal */
44
+ extraHeaders;
45
+ constructor(options) {
46
+ if (!options.apiKey) throw new Error("Sintaks: apiKey is required");
47
+ this.apiKey = options.apiKey;
48
+ this.baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
49
+ this.fetchFn = options.fetch ?? fetch;
50
+ this.extraHeaders = options.headers ?? {};
51
+ this.chat = new ChatResource(this);
52
+ this.images = new ImagesResource(this);
53
+ this.models = new ModelsResource(this);
54
+ }
55
+ async request(method, path, body) {
56
+ const res = await this.fetchFn(`${this.baseURL}${path}`, {
57
+ method,
58
+ headers: {
59
+ Authorization: `Bearer ${this.apiKey}`,
60
+ "Content-Type": "application/json",
61
+ ...this.extraHeaders
62
+ },
63
+ body: body === void 0 ? void 0 : JSON.stringify(body)
64
+ });
65
+ if (!res.ok) {
66
+ let envelope = {};
67
+ try {
68
+ envelope = await res.json();
69
+ } catch {
70
+ }
71
+ throw new SintaksError(res.status, envelope.error?.message ?? `request failed with ${res.status}`, {
72
+ type: envelope.error?.type,
73
+ code: envelope.error?.code,
74
+ requestId: res.headers.get("x-request-id")
75
+ });
76
+ }
77
+ return await res.json();
78
+ }
79
+ };
80
+ var ChatResource = class {
81
+ constructor(client) {
82
+ this.client = client;
83
+ }
84
+ client;
85
+ completions = this;
86
+ async create(params) {
87
+ if (params.stream) {
88
+ return this.createStream(params);
89
+ }
90
+ return this.client.request("POST", "/v1/chat/completions", {
91
+ ...params,
92
+ model: params.model ?? DEFAULT_CHAT_MODEL
93
+ });
94
+ }
95
+ async createStream(params) {
96
+ const res = await this.client.fetchFn(`${this.client.baseURL}/v1/chat/completions`, {
97
+ method: "POST",
98
+ headers: {
99
+ Authorization: `Bearer ${this.client.apiKey}`,
100
+ "Content-Type": "application/json",
101
+ Accept: "text/event-stream",
102
+ ...this.client.extraHeaders
103
+ },
104
+ body: JSON.stringify({
105
+ ...params,
106
+ model: params.model ?? DEFAULT_CHAT_MODEL,
107
+ stream_options: { include_usage: true }
108
+ })
109
+ });
110
+ if (!res.ok || !res.body) {
111
+ let envelope = {};
112
+ try {
113
+ envelope = await res.json();
114
+ } catch {
115
+ }
116
+ throw new SintaksError(res.status, envelope.error?.message ?? `request failed with ${res.status}`, {
117
+ type: envelope.error?.type,
118
+ code: envelope.error?.code,
119
+ requestId: res.headers.get("x-request-id")
120
+ });
121
+ }
122
+ return parseSSE(res.body);
123
+ }
124
+ };
125
+ async function* parseSSE(body) {
126
+ const reader = body.getReader();
127
+ const decoder = new TextDecoder();
128
+ let buffer = "";
129
+ try {
130
+ while (true) {
131
+ const { done, value } = await reader.read();
132
+ if (done) break;
133
+ buffer += decoder.decode(value, { stream: true });
134
+ let boundary;
135
+ while ((boundary = buffer.indexOf("\n\n")) !== -1) {
136
+ const chunk = buffer.slice(0, boundary);
137
+ buffer = buffer.slice(boundary + 2);
138
+ const dataLine = chunk.split("\n").find((line) => line.startsWith("data:"));
139
+ if (!dataLine) continue;
140
+ const payload = dataLine.slice(5).trim();
141
+ if (payload === "[DONE]") return;
142
+ try {
143
+ yield JSON.parse(payload);
144
+ } catch {
145
+ }
146
+ }
147
+ }
148
+ } finally {
149
+ reader.releaseLock();
150
+ }
151
+ }
152
+ var ImagesResource = class {
153
+ constructor(client) {
154
+ this.client = client;
155
+ }
156
+ client;
157
+ async generate(params) {
158
+ return this.client.request("POST", "/v1/images/generations", {
159
+ ...params,
160
+ model: params.model ?? DEFAULT_IMAGE_MODEL
161
+ });
162
+ }
163
+ };
164
+ var ModelsResource = class {
165
+ constructor(client) {
166
+ this.client = client;
167
+ }
168
+ client;
169
+ /** Lists the active models served by the gateway (GET /v1/models). */
170
+ async list() {
171
+ return this.client.request("GET", "/v1/models");
172
+ }
173
+ };
174
+ var index_default = Sintaks;
175
+ export {
176
+ DEFAULT_BASE_URL,
177
+ DEFAULT_CHAT_MODEL,
178
+ DEFAULT_IMAGE_MODEL,
179
+ Sintaks,
180
+ SintaksError,
181
+ index_default as default
182
+ };
183
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @sintaksdev/sdk — TypeScript client for the sintaks.dev OpenAI-compatible\n * AI API gateway. Zero runtime dependencies; requires Node >= 18 (global fetch).\n */\n\nexport const DEFAULT_BASE_URL = \"https://api.sintaks.dev\";\nexport const DEFAULT_CHAT_MODEL = \"claude-sonnet-5-5\";\nexport const DEFAULT_IMAGE_MODEL = \"stable-image-core\";\n\n/* ------------------------------------------------------------------ */\n/* Types (OpenAI-compatible shapes) */\n/* ------------------------------------------------------------------ */\n\nexport type MessageContentPart = { type: \"text\"; text: string };\n\nexport interface ChatMessage {\n role: \"system\" | \"developer\" | \"user\" | \"assistant\" | \"tool\";\n content: string | MessageContentPart[];\n name?: string;\n}\n\nexport interface ChatCompletionCreateParams {\n model?: string;\n messages: ChatMessage[];\n stream?: boolean;\n stream_options?: { include_usage?: boolean };\n temperature?: number;\n top_p?: number;\n max_tokens?: number;\n max_completion_tokens?: number;\n stop?: string | string[];\n [key: string]: unknown;\n}\n\nexport interface Usage {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n}\n\nexport interface ChatCompletion {\n id: string;\n object: \"chat.completion\";\n created: number;\n model: string;\n choices: {\n index: number;\n message: ChatMessage;\n finish_reason: string | null;\n }[];\n usage?: Usage;\n}\n\nexport interface ChatCompletionChunk {\n id: string;\n object: \"chat.completion.chunk\";\n created: number;\n model: string;\n choices: {\n index: number;\n delta: { role?: string; content?: string | null };\n finish_reason: string | null;\n }[];\n usage?: Usage;\n}\n\nexport interface Model {\n id: string;\n object: \"model\";\n created: number;\n owned_by: string;\n}\n\nexport interface ModelList {\n object: \"list\";\n data: Model[];\n}\n\nexport interface ImageGenerationParams {\n model?: string;\n prompt: string;\n n?: number;\n size?: string;\n [key: string]: unknown;\n}\n\nexport interface GeneratedImage {\n url?: string;\n b64_json?: string;\n}\n\nexport interface ImageGenerationResult {\n created: number;\n data: GeneratedImage[];\n}\n\nexport interface ErrorEnvelope {\n error?: {\n message?: string;\n type?: string;\n param?: string | null;\n code?: string | null;\n };\n}\n\n/* ------------------------------------------------------------------ */\n/* Error */\n/* ------------------------------------------------------------------ */\n\nexport class SintaksError extends Error {\n readonly status: number;\n readonly type: string | undefined;\n readonly code: string | null;\n readonly requestId: string | null;\n\n constructor(\n status: number,\n message: string,\n opts: { type?: string; code?: string | null; requestId?: string | null } = {},\n ) {\n super(message);\n this.name = \"SintaksError\";\n this.status = status;\n this.type = opts.type;\n this.code = opts.code ?? null;\n this.requestId = opts.requestId ?? null;\n }\n\n /** True for missing, malformed, revoked, or invalid API keys (401). */\n get isUnauthorized(): boolean {\n return this.status === 401;\n }\n\n /** True when the account balance can't cover the request (402). Top up first. */\n get isInsufficientCredits(): boolean {\n return this.status === 402;\n }\n\n /** True for upstream throttling (429). */\n get isRateLimited(): boolean {\n return this.status === 429;\n }\n\n /** True for errors worth retrying with backoff: 429, 503, 504. */\n get isRetryable(): boolean {\n return this.status === 429 || this.status === 503 || this.status === 504;\n }\n}\n\n/* ------------------------------------------------------------------ */\n/* Client */\n/* ------------------------------------------------------------------ */\n\nexport interface SintaksOptions {\n apiKey: string;\n baseURL?: string;\n fetch?: typeof fetch;\n headers?: Record<string, string>;\n}\n\nexport class Sintaks {\n readonly apiKey: string;\n readonly baseURL: string;\n readonly chat: ChatResource;\n readonly images: ImagesResource;\n readonly models: ModelsResource;\n\n /** @internal */\n readonly fetchFn: typeof fetch;\n /** @internal */\n readonly extraHeaders: Record<string, string>;\n\n constructor(options: SintaksOptions) {\n if (!options.apiKey) throw new Error(\"Sintaks: apiKey is required\");\n this.apiKey = options.apiKey;\n this.baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n this.fetchFn = options.fetch ?? fetch;\n this.extraHeaders = options.headers ?? {};\n this.chat = new ChatResource(this);\n this.images = new ImagesResource(this);\n this.models = new ModelsResource(this);\n }\n\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const res = await this.fetchFn(`${this.baseURL}${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...this.extraHeaders,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n\n if (!res.ok) {\n let envelope: ErrorEnvelope = {};\n try {\n envelope = (await res.json()) as ErrorEnvelope;\n } catch {\n // non-JSON error body; fall through with defaults\n }\n throw new SintaksError(res.status, envelope.error?.message ?? `request failed with ${res.status}`, {\n type: envelope.error?.type,\n code: envelope.error?.code,\n requestId: res.headers.get(\"x-request-id\"),\n });\n }\n return (await res.json()) as T;\n }\n}\n\n/* ------------------------------------------------------------------ */\n/* Chat */\n/* ------------------------------------------------------------------ */\n\nclass ChatResource {\n readonly completions = this;\n\n constructor(private client: Sintaks) {}\n\n async create(params: ChatCompletionCreateParams): Promise<ChatCompletion>;\n async create(params: ChatCompletionCreateParams & { stream: true }): Promise<AsyncIterable<ChatCompletionChunk>>;\n async create(\n params: ChatCompletionCreateParams,\n ): Promise<ChatCompletion | AsyncIterable<ChatCompletionChunk>> {\n if (params.stream) {\n return this.createStream(params as ChatCompletionCreateParams & { stream: true });\n }\n return this.client.request<ChatCompletion>(\"POST\", \"/v1/chat/completions\", {\n ...params,\n model: params.model ?? DEFAULT_CHAT_MODEL,\n });\n }\n\n private async createStream(\n params: ChatCompletionCreateParams & { stream: true },\n ): Promise<AsyncIterable<ChatCompletionChunk>> {\n const res = await this.client.fetchFn(`${this.client.baseURL}/v1/chat/completions`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.client.apiKey}`,\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n ...this.client.extraHeaders,\n },\n body: JSON.stringify({\n ...params,\n model: params.model ?? DEFAULT_CHAT_MODEL,\n stream_options: { include_usage: true },\n }),\n });\n\n if (!res.ok || !res.body) {\n let envelope: ErrorEnvelope = {};\n try {\n envelope = (await res.json()) as ErrorEnvelope;\n } catch {\n // ignore\n }\n throw new SintaksError(res.status, envelope.error?.message ?? `request failed with ${res.status}`, {\n type: envelope.error?.type,\n code: envelope.error?.code,\n requestId: res.headers.get(\"x-request-id\"),\n });\n }\n\n return parseSSE<ChatCompletionChunk>(res.body);\n }\n}\n\n/** Minimal SSE parser for OpenAI-style `data:` events. */\nasync function* parseSSE<T>(body: ReadableStream<Uint8Array>): AsyncIterable<T> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let boundary: number;\n while ((boundary = buffer.indexOf(\"\\n\\n\")) !== -1) {\n const chunk = buffer.slice(0, boundary);\n buffer = buffer.slice(boundary + 2);\n const dataLine = chunk\n .split(\"\\n\")\n .find((line) => line.startsWith(\"data:\"));\n if (!dataLine) continue;\n const payload = dataLine.slice(5).trim();\n if (payload === \"[DONE]\") return;\n try {\n yield JSON.parse(payload) as T;\n } catch {\n // skip malformed event\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/* ------------------------------------------------------------------ */\n/* Images */\n/* ------------------------------------------------------------------ */\n\nclass ImagesResource {\n constructor(private client: Sintaks) {}\n\n async generate(params: ImageGenerationParams): Promise<ImageGenerationResult> {\n return this.client.request<ImageGenerationResult>(\"POST\", \"/v1/images/generations\", {\n ...params,\n model: params.model ?? DEFAULT_IMAGE_MODEL,\n });\n }\n}\n\nclass ModelsResource {\n constructor(private client: Sintaks) {}\n\n /** Lists the active models served by the gateway (GET /v1/models). */\n async list(): Promise<ModelList> {\n return this.client.request<ModelList>(\"GET\", \"/v1/models\");\n }\n}\n\nexport default Sintaks;"],"mappings":";AAKO,IAAM,mBAAmB;AACzB,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB;AAsG5B,IAAM,eAAN,cAA2B,MAAM;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,QACA,SACA,OAA2E,CAAC,GAC5E;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO,KAAK;AACjB,SAAK,OAAO,KAAK,QAAQ;AACzB,SAAK,YAAY,KAAK,aAAa;AAAA,EACrC;AAAA;AAAA,EAGA,IAAI,iBAA0B;AAC5B,WAAO,KAAK,WAAW;AAAA,EACzB;AAAA;AAAA,EAGA,IAAI,wBAAiC;AACnC,WAAO,KAAK,WAAW;AAAA,EACzB;AAAA;AAAA,EAGA,IAAI,gBAAyB;AAC3B,WAAO,KAAK,WAAW;AAAA,EACzB;AAAA;AAAA,EAGA,IAAI,cAAuB;AACzB,WAAO,KAAK,WAAW,OAAO,KAAK,WAAW,OAAO,KAAK,WAAW;AAAA,EACvE;AACF;AAaO,IAAM,UAAN,MAAc;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,SAAyB;AACnC,QAAI,CAAC,QAAQ,OAAQ,OAAM,IAAI,MAAM,6BAA6B;AAClE,SAAK,SAAS,QAAQ;AACtB,SAAK,WAAW,QAAQ,WAAW,kBAAkB,Q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W,CAAC;AAClC,cAAM,WAAW,MACd,MAAM,IAAI,EACV,KAAK,CAAC,SAAS,KAAK,WAAW,OAAO,CAAC;AAC1C,YAAI,CAAC,SAAU;AACf,cAAM,UAAU,SAAS,MAAM,CAAC,EAAE,KAAK;AACvC,YAAI,YAAY,SAAU;AAC1B,YAAI;AACF,gBAAM,KAAK,MAAM,OAAO;AAAA,QAC1B,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAAA,EACF,UAAE;AACA,WAAO,YAAY;AAAA,EACrB;AACF;AAMA,IAAM,iBAAN,MAAqB;AAAA,EACnB,YAAoB,QAAiB;AAAjB;AAAA,EAAkB;AAAA,EAAlB;AAAA,EAEpB,MAAM,SAAS,QAA+D;AAC5E,WAAO,KAAK,OAAO,QAA+B,QAAQ,0BAA0B;AAAA,MAClF,GAAG;AAAA,MACH,OAAO,OAAO,SAAS;AAAA,IACzB,CAAC;AAAA,EACH;AACF;AAEA,IAAM,iBAAN,MAAqB;AAAA,EACnB,YAAoB,QAAiB;AAAjB;AAAA,EAAkB;AAAA,EAAlB;AAAA;AAAA,EAGpB,MAAM,OAA2B;AAC/B,WAAO,KAAK,OAAO,QAAmB,OAAO,YAAY;AAAA,EAC3D;AACF;AAEA,IAAO,gBAAQ;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@sintaksdev/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "TypeScript client for the sintaks.dev OpenAI-compatible AI API gateway. Top up in IDR, call chat and image models, pay per request.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.cjs"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "sideEffects": false,
21
+ "engines": {
22
+ "node": ">=18"
23
+ },
24
+ "scripts": {
25
+ "build": "tsup",
26
+ "typecheck": "tsc --noEmit",
27
+ "prepublishOnly": "pnpm build"
28
+ },
29
+ "keywords": [
30
+ "openai",
31
+ "sintaks",
32
+ "ai",
33
+ "api",
34
+ "llm",
35
+ "indonesia",
36
+ "qris"
37
+ ],
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/rendies/sintaks-dev-sdk-js.git"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "packageManager": "pnpm@10.29.3",
46
+ "devDependencies": {
47
+ "@types/node": "^26.6.5",
48
+ "tsup": "^8.5.1",
49
+ "typescript": "^5.9.3"
50
+ }
51
+ }