@mp3quran/sdk 0.0.0-stage → 0.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.
- package/LICENSE +21 -0
- package/README.md +752 -2
- package/dist/generated/operations-meta.d.ts +13 -0
- package/dist/generated/operations-meta.js +310 -0
- package/dist/generated/types.d.ts +4302 -0
- package/dist/generated/types.js +6 -0
- package/dist/index.d.ts +75 -0
- package/dist/index.js +176 -0
- package/package.json +60 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { operations } from './generated/types.js';
|
|
2
|
+
export type { OperationMeta } from './generated/operations-meta.js';
|
|
3
|
+
export type { operations, components, paths } from './generated/types.js';
|
|
4
|
+
/** The error envelope every `/v4` route returns for a non-2xx response: `{ error: {...} }`. */
|
|
5
|
+
export interface ApiErrorBody {
|
|
6
|
+
readonly error: {
|
|
7
|
+
readonly code: string;
|
|
8
|
+
readonly message: string;
|
|
9
|
+
readonly field?: string;
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
/** Thrown for every non-2xx, non-304 response. Carries the HTTP status plus the error envelope. */
|
|
13
|
+
export declare class ApiError extends Error {
|
|
14
|
+
readonly status: number;
|
|
15
|
+
readonly code: string;
|
|
16
|
+
readonly field?: string;
|
|
17
|
+
constructor(status: number, body: ApiErrorBody);
|
|
18
|
+
static fromResponse(status: number, body: unknown): ApiError;
|
|
19
|
+
}
|
|
20
|
+
type Operations = operations;
|
|
21
|
+
export type OperationId = keyof Operations;
|
|
22
|
+
type OpParameters<Op extends OperationId> = Operations[Op] extends {
|
|
23
|
+
parameters: infer P;
|
|
24
|
+
} ? P : Record<string, never>;
|
|
25
|
+
type OpSuccessBody<Op extends OperationId> = Operations[Op] extends {
|
|
26
|
+
responses: {
|
|
27
|
+
200: {
|
|
28
|
+
content: {
|
|
29
|
+
'application/json': infer Body;
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
} ? Body : unknown;
|
|
34
|
+
/** The clip is being cut: the `202` body, `{ data: { key, status: 'queued' } }`. Ask again later. */
|
|
35
|
+
export type SurahClipQueued = Operations['getSurahClip']['responses'][202]['content']['application/json'];
|
|
36
|
+
/**
|
|
37
|
+
* The clip is ready: `url` is its download address. The client does not download the audio — it
|
|
38
|
+
* stops at the address and leaves fetching the file to the caller.
|
|
39
|
+
*/
|
|
40
|
+
export interface SurahClipReady {
|
|
41
|
+
readonly status: 'ready';
|
|
42
|
+
readonly url: string;
|
|
43
|
+
}
|
|
44
|
+
/** What `getSurahClip()` resolves to. Tell the two apart with `'url' in result`. */
|
|
45
|
+
export type SurahClipResult = SurahClipQueued | SurahClipReady;
|
|
46
|
+
/** The success value a method resolves to: the JSON body, except for the clip, which may be audio. */
|
|
47
|
+
type OpResult<Op extends OperationId> = Op extends 'getSurahClip' ? SurahClipResult : OpSuccessBody<Op>;
|
|
48
|
+
type ClientMethod<Op extends OperationId> = (params?: OpParameters<Op>) => Promise<OpResult<Op>>;
|
|
49
|
+
/** One typed method per `operationId` — `client.listSurahs()`, `client.getSurah({ path: { number: '2' } })`, … */
|
|
50
|
+
export type ClientMethods = {
|
|
51
|
+
[Op in OperationId]: ClientMethod<Op>;
|
|
52
|
+
};
|
|
53
|
+
export interface CreateClientOptions {
|
|
54
|
+
/** e.g. `https://api.mp3quran.net` or `http://localhost:8787` — no trailing slash. */
|
|
55
|
+
readonly baseUrl: string;
|
|
56
|
+
/** Applied as `?locale=` on every call whose operation accepts it, unless the call overrides it. */
|
|
57
|
+
readonly locale?: string;
|
|
58
|
+
/** Injectable for tests / non-global-fetch runtimes. Defaults to the global `fetch`. */
|
|
59
|
+
readonly fetch?: typeof fetch;
|
|
60
|
+
}
|
|
61
|
+
export interface Client extends ClientMethods {
|
|
62
|
+
/** Untyped escape hatch — every `call()` a generated method makes goes through this. */
|
|
63
|
+
readonly call: <Op extends OperationId>(operationId: Op, params?: OpParameters<Op>) => Promise<OpResult<Op>>;
|
|
64
|
+
/**
|
|
65
|
+
* Walks a list operation across every page, following the envelope's `links.next` (a full
|
|
66
|
+
* path + query, as every list route emits it), yielding one item at a time. Stops when a
|
|
67
|
+
* response has no `links.next`. Works today even though no `/v4` list route paginates yet
|
|
68
|
+
* (see the WP-15 report) — it walks a single page and stops, exactly as `links.next` describes.
|
|
69
|
+
*/
|
|
70
|
+
readonly paginate: <Op extends OperationId>(operationId: Op, params?: OpParameters<Op>) => AsyncGenerator<unknown, void, void>;
|
|
71
|
+
/** Drops every cached `ETag`. */
|
|
72
|
+
readonly clearCache: () => void;
|
|
73
|
+
}
|
|
74
|
+
/** `createClient({ baseUrl, locale?, fetch? })` — see the file header for the design. */
|
|
75
|
+
export declare function createClient(options: CreateClientOptions): Client;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @mp3quran/sdk — TypeScript client generated from `apps/api/openapi.json` — WP-15.
|
|
3
|
+
*
|
|
4
|
+
* `createClient()` builds one typed method per `operationId` at runtime, driven entirely by
|
|
5
|
+
* `generated/operations-meta.ts` (path template, HTTP method, path/query parameter names) — a new
|
|
6
|
+
* route in the doc gets a new client method the next time `pnpm sdk:generate` runs, no change
|
|
7
|
+
* needed here. The *types* for each method's params/response come from `generated/types.ts`'s
|
|
8
|
+
* `operations['<operationId>']`, produced by `openapi-typescript` from the same doc — both outputs
|
|
9
|
+
* are keyed by the same `operationId` string, so they can never drift from each other.
|
|
10
|
+
*/
|
|
11
|
+
import { operationsMeta } from './generated/operations-meta.js';
|
|
12
|
+
function isApiErrorBody(value) {
|
|
13
|
+
if (value === null || typeof value !== 'object')
|
|
14
|
+
return false;
|
|
15
|
+
const error = value.error;
|
|
16
|
+
return (error !== null &&
|
|
17
|
+
typeof error === 'object' &&
|
|
18
|
+
typeof error.code === 'string' &&
|
|
19
|
+
typeof error.message === 'string');
|
|
20
|
+
}
|
|
21
|
+
/** Thrown for every non-2xx, non-304 response. Carries the HTTP status plus the error envelope. */
|
|
22
|
+
export class ApiError extends Error {
|
|
23
|
+
status;
|
|
24
|
+
code;
|
|
25
|
+
field;
|
|
26
|
+
constructor(status, body) {
|
|
27
|
+
super(body.error.message);
|
|
28
|
+
this.name = 'ApiError';
|
|
29
|
+
this.status = status;
|
|
30
|
+
this.code = body.error.code;
|
|
31
|
+
if (body.error.field !== undefined)
|
|
32
|
+
this.field = body.error.field;
|
|
33
|
+
}
|
|
34
|
+
static fromResponse(status, body) {
|
|
35
|
+
if (isApiErrorBody(body))
|
|
36
|
+
return new ApiError(status, body);
|
|
37
|
+
return new ApiError(status, {
|
|
38
|
+
error: { code: 'unknown', message: `Request failed with status ${String(status)}.` },
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** Renders a path/query param value the way `String()` would; a list is comma-separated. */
|
|
43
|
+
function paramToString(value) {
|
|
44
|
+
if (typeof value === 'string')
|
|
45
|
+
return value;
|
|
46
|
+
return Array.isArray(value) ? value.join(',') : String(value);
|
|
47
|
+
}
|
|
48
|
+
function buildPath(meta, params) {
|
|
49
|
+
const pathParams = params?.path ?? {};
|
|
50
|
+
let path = meta.path;
|
|
51
|
+
for (const name of meta.pathParams) {
|
|
52
|
+
const value = pathParams[name];
|
|
53
|
+
if (value === undefined) {
|
|
54
|
+
throw new Error(`${meta.operationId}: missing required path parameter "${name}".`);
|
|
55
|
+
}
|
|
56
|
+
path = path.replace(`{${name}}`, encodeURIComponent(paramToString(value)));
|
|
57
|
+
}
|
|
58
|
+
return path;
|
|
59
|
+
}
|
|
60
|
+
function buildQuery(meta, params, defaultLocale) {
|
|
61
|
+
const queryParams = params?.query ?? {};
|
|
62
|
+
const search = new URLSearchParams();
|
|
63
|
+
for (const name of meta.queryParams) {
|
|
64
|
+
const value = name === 'locale' && !(name in queryParams) ? defaultLocale : queryParams[name];
|
|
65
|
+
if (value !== undefined)
|
|
66
|
+
search.set(name, paramToString(value));
|
|
67
|
+
}
|
|
68
|
+
const qs = search.toString();
|
|
69
|
+
return qs === '' ? '' : `?${qs}`;
|
|
70
|
+
}
|
|
71
|
+
/** `createClient({ baseUrl, locale?, fetch? })` — see the file header for the design. */
|
|
72
|
+
export function createClient(options) {
|
|
73
|
+
const baseUrl = options.baseUrl.replace(/\/$/, '');
|
|
74
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
75
|
+
const cache = new Map();
|
|
76
|
+
/** Sends the request, following a permanent (canonical) redirect even with an injected fetch. */
|
|
77
|
+
async function send(method, url, headers) {
|
|
78
|
+
let res = await fetchImpl(url, { method, headers });
|
|
79
|
+
// WP-47: a reciter named by code, alias or slug (or a recording by its folder) answers 301 to
|
|
80
|
+
// the canonical URL. The global `fetch` follows that itself; an injected one may not, so the
|
|
81
|
+
// client follows a permanent redirect here too — a few hops at most, never a loop.
|
|
82
|
+
for (let hops = 0; (res.status === 301 || res.status === 308) && hops < 5; hops += 1) {
|
|
83
|
+
const location = res.headers.get('location');
|
|
84
|
+
if (location === null)
|
|
85
|
+
break;
|
|
86
|
+
res = await fetchImpl(new URL(location, url).toString(), { method, headers });
|
|
87
|
+
}
|
|
88
|
+
return res;
|
|
89
|
+
}
|
|
90
|
+
async function fetchJson(method, url) {
|
|
91
|
+
const cacheKey = `${method} ${url}`;
|
|
92
|
+
const cached = method === 'GET' ? cache.get(cacheKey) : undefined;
|
|
93
|
+
const headers = { accept: 'application/json' };
|
|
94
|
+
if (cached)
|
|
95
|
+
headers['if-none-match'] = cached.etag;
|
|
96
|
+
const res = await send(method, url, headers);
|
|
97
|
+
if (res.status === 304 && cached)
|
|
98
|
+
return cached.body;
|
|
99
|
+
const text = await res.text();
|
|
100
|
+
const body = text === '' ? undefined : JSON.parse(text);
|
|
101
|
+
if (!res.ok)
|
|
102
|
+
throw ApiError.fromResponse(res.status, body);
|
|
103
|
+
const etag = res.headers.get('etag');
|
|
104
|
+
if (method === 'GET' && etag)
|
|
105
|
+
cache.set(cacheKey, { etag, body });
|
|
106
|
+
return body;
|
|
107
|
+
}
|
|
108
|
+
async function call(operationId, params) {
|
|
109
|
+
const meta = operationsMeta.find((m) => m.operationId === operationId);
|
|
110
|
+
if (!meta)
|
|
111
|
+
throw new Error(`Unknown operationId: ${operationId}`);
|
|
112
|
+
const path = buildPath(meta, params);
|
|
113
|
+
const query = buildQuery(meta, params, options.locale);
|
|
114
|
+
const url = `${baseUrl}${path}${query}`;
|
|
115
|
+
if (operationId === 'getSurahClip')
|
|
116
|
+
return fetchClip(url);
|
|
117
|
+
return fetchJson(meta.method.toUpperCase(), url);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* The clip route answers `202` with JSON while the cut is queued and `302` to the audio file once
|
|
121
|
+
* it is ready. A `302` that reaches us (an injected fetch that does not follow it) gives the URL
|
|
122
|
+
* directly; a followed one ends on the audio itself, so the final `res.url` is the URL and the
|
|
123
|
+
* body is cancelled unread. Errors are JSON and throw `ApiError`. Never cached: the answer
|
|
124
|
+
* changes from queued to ready.
|
|
125
|
+
*/
|
|
126
|
+
async function fetchClip(url) {
|
|
127
|
+
const res = await send('GET', url, { accept: 'application/json' });
|
|
128
|
+
const location = res.headers.get('location');
|
|
129
|
+
if ((res.status === 302 || res.status === 303 || res.status === 307) && location !== null) {
|
|
130
|
+
await res.body?.cancel();
|
|
131
|
+
return { status: 'ready', url: new URL(location, url).toString() };
|
|
132
|
+
}
|
|
133
|
+
const isJson = /\bjson\b/i.test(res.headers.get('content-type') ?? '');
|
|
134
|
+
if (res.ok && !isJson) {
|
|
135
|
+
await res.body?.cancel();
|
|
136
|
+
return { status: 'ready', url: res.url === '' ? url : res.url };
|
|
137
|
+
}
|
|
138
|
+
const text = isJson ? await res.text() : '';
|
|
139
|
+
if (!isJson)
|
|
140
|
+
await res.body?.cancel();
|
|
141
|
+
const body = text === '' ? undefined : JSON.parse(text);
|
|
142
|
+
if (!res.ok)
|
|
143
|
+
throw ApiError.fromResponse(res.status, body);
|
|
144
|
+
return body;
|
|
145
|
+
}
|
|
146
|
+
async function* paginate(operationId, params) {
|
|
147
|
+
let body = (await call(operationId, params));
|
|
148
|
+
for (;;) {
|
|
149
|
+
const data = body.data;
|
|
150
|
+
if (Array.isArray(data)) {
|
|
151
|
+
for (const item of data)
|
|
152
|
+
yield item;
|
|
153
|
+
}
|
|
154
|
+
else if (data !== undefined) {
|
|
155
|
+
yield data;
|
|
156
|
+
}
|
|
157
|
+
const next = body.links?.next;
|
|
158
|
+
if (!next)
|
|
159
|
+
return;
|
|
160
|
+
const nextUrl = next.startsWith('http') ? next : `${baseUrl}${next}`;
|
|
161
|
+
body = (await fetchJson('GET', nextUrl));
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const methods = Object.fromEntries(operationsMeta.map((meta) => [
|
|
165
|
+
meta.operationId,
|
|
166
|
+
(params) => call(meta.operationId, params),
|
|
167
|
+
]));
|
|
168
|
+
return {
|
|
169
|
+
...methods,
|
|
170
|
+
call,
|
|
171
|
+
paginate,
|
|
172
|
+
clearCache: () => {
|
|
173
|
+
cache.clear();
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mp3quran/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Typed TypeScript client for the MP3Quran API v4: reciters, recitations by riwayah, surah audio, clips, radios, and ayah, word, letter and phoneme timings.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"author": "MP3Quran",
|
|
8
|
+
"homepage": "https://docs.mp3quran.net/",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/AbdullahObaid/mp3quran-api-v4.git",
|
|
12
|
+
"directory": "packages/sdk"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"mp3quran",
|
|
16
|
+
"quran",
|
|
17
|
+
"recitation",
|
|
18
|
+
"reciter",
|
|
19
|
+
"audio",
|
|
20
|
+
"timings",
|
|
21
|
+
"riwayah",
|
|
22
|
+
"api",
|
|
23
|
+
"sdk",
|
|
24
|
+
"openapi"
|
|
25
|
+
],
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=18"
|
|
29
|
+
},
|
|
30
|
+
"main": "./dist/index.js",
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"default": "./dist/index.js"
|
|
36
|
+
},
|
|
37
|
+
"./package.json": "./package.json"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"README.md",
|
|
42
|
+
"LICENSE"
|
|
43
|
+
],
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@hono/node-server": "^2.1.1",
|
|
49
|
+
"@types/pg": "^8.23.1",
|
|
50
|
+
"drizzle-orm": "^0.45.2",
|
|
51
|
+
"openapi-typescript": "^7.13.0",
|
|
52
|
+
"pg": "^8.23.0",
|
|
53
|
+
"@mp3quran/schema": "^0.0.0",
|
|
54
|
+
"@mp3quran/test-support": "^0.0.0",
|
|
55
|
+
"@mp3quran/api": "^0.0.0"
|
|
56
|
+
},
|
|
57
|
+
"scripts": {
|
|
58
|
+
"build": "tsc -p tsconfig.build.json",
|
|
59
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
60
|
+
"lint": "eslint src",
|
|
61
|
+
"test": "vitest run --passWithNoTests"
|
|
62
|
+
}
|
|
6
63
|
}
|