@panomc/client 0.0.0-stage → 1.0.0-dev.61
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/package.json +23 -4
- package/scripts/generate-core.js +33 -0
- package/scripts/generate-core.test.js +43 -0
- package/src/client.js +267 -0
- package/src/client.test.js +348 -0
- package/src/core/index.js +522 -0
- package/src/core/openapi.json +5820 -0
- package/src/core/operations.js +69 -0
- package/src/core/types.js +360 -0
- package/src/errors.js +55 -0
- package/src/index.js +2 -0
- package/src/types.js +61 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@panomc/client",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0-dev.61",
|
|
4
|
+
"description": "Typed JavaScript client for the Pano HTTP API (JSDoc types, no dependencies, no framework).",
|
|
5
|
+
"author": "PanoMC",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"repository": {
|
|
9
|
+
"url": "https://github.com/PanoMC/sdk"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": "./src/client.js",
|
|
13
|
+
"./core": "./src/core/index.js",
|
|
14
|
+
"./core/types": "./src/core/types.js",
|
|
15
|
+
"./core/openapi.json": "./src/core/openapi.json",
|
|
16
|
+
"./package.json": "./package.json"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"src",
|
|
20
|
+
"scripts"
|
|
21
|
+
],
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Regenerates src/core/ from the platform's core OpenAPI snapshot (doc 06 section 2.4, Builds).
|
|
4
|
+
*
|
|
5
|
+
* node scripts/generate-core.js [path/to/openapi-core.json]
|
|
6
|
+
*
|
|
7
|
+
* Default input: pano-web-platform/Pano/api/openapi-core.json next to this repo (umbrella layout), or
|
|
8
|
+
* $PANO_OPENAPI_CORE. The result is committed; a second run changes nothing.
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
|
|
11
|
+
import { dirname, resolve } from "node:path";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { generateClient } from "../../client-gen/src/generate.js";
|
|
14
|
+
import { writeFiles } from "../../client-gen/src/pull.js";
|
|
15
|
+
|
|
16
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
17
|
+
const outDir = resolve(here, "../src/core");
|
|
18
|
+
const defaultInput = resolve(here, "../../../../pano-web-platform/Pano/api/openapi-core.json");
|
|
19
|
+
const input = resolve(process.argv[2] ?? process.env.PANO_OPENAPI_CORE ?? defaultInput);
|
|
20
|
+
|
|
21
|
+
if (!existsSync(input)) {
|
|
22
|
+
console.error(`generate-core: cannot read ${input}`);
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const gen = generateClient(readFileSync(input, "utf8"));
|
|
27
|
+
gen.warnings.forEach((w) => console.error(`warning: ${w}`));
|
|
28
|
+
|
|
29
|
+
// the folder is entirely generated: drop stale files so a removed output cannot linger
|
|
30
|
+
rmSync(outDir, { recursive: true, force: true });
|
|
31
|
+
mkdirSync(outDir, { recursive: true });
|
|
32
|
+
writeFiles(outDir, gen.files);
|
|
33
|
+
console.log(`generated ${gen.operations.length} operations in ${outDir}`);
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { panoClientGen } from "../../plugin-kit/src/rollup/client-gen.js";
|
|
8
|
+
|
|
9
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
const script = join(here, "generate-core.js");
|
|
11
|
+
const mini = resolve(here, "../../client-gen/src/golden/mini");
|
|
12
|
+
|
|
13
|
+
test("generate-core.js is deterministic: a run over the committed snapshot changes no file", () => {
|
|
14
|
+
const core = join(here, "../src/core");
|
|
15
|
+
const read = () => Object.fromEntries(readdirSync(core).sort().map((f) => [f, readFileSync(join(core, f), "utf8")]));
|
|
16
|
+
const before = read();
|
|
17
|
+
expect(Object.keys(before)).toEqual(["index.js", "openapi.json", "operations.js", "types.js"]);
|
|
18
|
+
execFileSync("node", [script, join(core, "openapi.json")]);
|
|
19
|
+
expect(read()).toEqual(before);
|
|
20
|
+
expect(before["types.js"].trimEnd().endsWith("export {};")).toBe(true);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test("the panoClientGen hook writes client/ from api/openapi.json and keeps an existing package.json", async () => {
|
|
24
|
+
const root = mkdtempSync(join(tmpdir(), "client-hook-"));
|
|
25
|
+
try {
|
|
26
|
+
// no snapshot: nothing written
|
|
27
|
+
await panoClientGen({ pluginId: "pano-plugin-demo", namespace: "demo", root }).buildStart.call({ warn() {} });
|
|
28
|
+
expect(existsSync(join(root, "client"))).toBe(false);
|
|
29
|
+
|
|
30
|
+
mkdirSync(join(root, "api"));
|
|
31
|
+
cpSync(join(mini, "openapi.json"), join(root, "api/openapi.json"));
|
|
32
|
+
await panoClientGen({ pluginId: "pano-plugin-demo", namespace: "demo", root }).buildStart.call({ warn() {} });
|
|
33
|
+
expect(readFileSync(join(root, "client/index.js"), "utf8")).toBe(readFileSync(join(mini, "index.js"), "utf8"));
|
|
34
|
+
const pkg = JSON.parse(readFileSync(join(root, "client/package.json"), "utf8"));
|
|
35
|
+
expect(pkg.name).toBe("pano-client-demo");
|
|
36
|
+
|
|
37
|
+
writeFileSync(join(root, "client/package.json"), '{"name":"@panomc/client-demo"}\n');
|
|
38
|
+
await panoClientGen({ pluginId: "pano-plugin-demo", namespace: "demo", root }).buildStart.call({ warn() {} });
|
|
39
|
+
expect(readFileSync(join(root, "client/package.json"), "utf8")).toBe('{"name":"@panomc/client-demo"}\n');
|
|
40
|
+
} finally {
|
|
41
|
+
rmSync(root, { recursive: true, force: true });
|
|
42
|
+
}
|
|
43
|
+
});
|
package/src/client.js
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { PanoApiError, failure, failureFromBody } from './errors.js'
|
|
2
|
+
|
|
3
|
+
/** @typedef {import('./types.js').PanoClientOptions} PanoClientOptions */
|
|
4
|
+
/** @typedef {import('./types.js').PanoClient} PanoClient */
|
|
5
|
+
/** @typedef {import('./types.js').PanoOperation} PanoOperation */
|
|
6
|
+
/** @typedef {import('./types.js').RequestParams} RequestParams */
|
|
7
|
+
/** @typedef {import('./types.js').ApiFailure} ApiFailure */
|
|
8
|
+
/** @template T @typedef {import('./types.js').ApiResult<T>} ApiResult */
|
|
9
|
+
|
|
10
|
+
const CSRF_PATH = '/api/v1/auth/csrf'
|
|
11
|
+
const AUTH_PREFIX = '/api/v1/auth/'
|
|
12
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
|
|
13
|
+
|
|
14
|
+
/** @param {any} body */
|
|
15
|
+
function isRawBody(body) {
|
|
16
|
+
return (
|
|
17
|
+
typeof body === 'string' ||
|
|
18
|
+
(typeof FormData !== 'undefined' && body instanceof FormData) ||
|
|
19
|
+
(typeof Blob !== 'undefined' && body instanceof Blob) ||
|
|
20
|
+
(typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) ||
|
|
21
|
+
(typeof ArrayBuffer !== 'undefined' && (body instanceof ArrayBuffer || ArrayBuffer.isView(body))) ||
|
|
22
|
+
(typeof ReadableStream !== 'undefined' && body instanceof ReadableStream)
|
|
23
|
+
)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param {string} path @param {Record<string, any>|undefined} values */
|
|
27
|
+
function fillPath(path, values) {
|
|
28
|
+
return path.replace(/\{([^}]+)\}/g, (whole, name) => {
|
|
29
|
+
const value = values?.[name]
|
|
30
|
+
return value === undefined || value === null ? whole : encodeURIComponent(String(value))
|
|
31
|
+
})
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @param {Record<string, any>|undefined} query */
|
|
35
|
+
function queryString(query) {
|
|
36
|
+
if (!query) return ''
|
|
37
|
+
const search = new URLSearchParams()
|
|
38
|
+
|
|
39
|
+
for (const [key, value] of Object.entries(query)) {
|
|
40
|
+
if (value === undefined || value === null) continue
|
|
41
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
42
|
+
if (item === undefined || item === null) continue
|
|
43
|
+
search.append(key, item instanceof Date ? item.toISOString() : String(item))
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const text = search.toString()
|
|
48
|
+
return text ? `?${text}` : ''
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** @param {Response} response */
|
|
52
|
+
async function readBody(response) {
|
|
53
|
+
if (response.status === 204 || response.status === 205) return undefined
|
|
54
|
+
|
|
55
|
+
const text = await response.text()
|
|
56
|
+
if (!text) return undefined
|
|
57
|
+
|
|
58
|
+
const type = response.headers.get('content-type') || ''
|
|
59
|
+
if (type.includes('json') || /^\s*[[{]/.test(text)) {
|
|
60
|
+
try {
|
|
61
|
+
return JSON.parse(text)
|
|
62
|
+
} catch {
|
|
63
|
+
return text
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return text
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @param {PanoClientOptions} options
|
|
72
|
+
* @returns {PanoClient}
|
|
73
|
+
*/
|
|
74
|
+
export function createClient(options) {
|
|
75
|
+
if (!options || typeof options.baseUrl !== 'string') {
|
|
76
|
+
throw new TypeError('createClient: options.baseUrl is required (Pano origin or proxy prefix, e.g. "/pano")')
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const baseUrl = options.baseUrl.replace(/\/+$/, '')
|
|
80
|
+
const inBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'
|
|
81
|
+
const credentials = options.credentials ?? (inBrowser ? 'include' : 'omit')
|
|
82
|
+
const csrfMode = options.csrf ?? (credentials === 'include' && !options.sessionToken ? 'auto' : 'off')
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* CSRF cache. `undefined` = unknown, `null` = probed and there is none (anonymous or Bearer), string = token.
|
|
86
|
+
* @type {string|null|undefined}
|
|
87
|
+
*/
|
|
88
|
+
let csrfToken
|
|
89
|
+
/** @type {Promise<void>|null} */
|
|
90
|
+
let probing = null
|
|
91
|
+
|
|
92
|
+
/** @param {Record<string, string>|undefined} extra */
|
|
93
|
+
async function buildHeaders(extra) {
|
|
94
|
+
/** @type {Record<string, string>} */
|
|
95
|
+
const headers = { Accept: 'application/json' }
|
|
96
|
+
|
|
97
|
+
if (options.locale) headers['Accept-Language'] = options.locale
|
|
98
|
+
|
|
99
|
+
if (options.frontendKey) {
|
|
100
|
+
headers['X-Pano-Frontend-Key'] = options.frontendKey
|
|
101
|
+
if (options.clientIp) headers['X-Pano-Client-Ip'] = options.clientIp
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const token = typeof options.sessionToken === 'function' ? await options.sessionToken() : options.sessionToken
|
|
105
|
+
if (token) headers.Authorization = `Bearer ${token}`
|
|
106
|
+
|
|
107
|
+
if (extra) {
|
|
108
|
+
for (const [name, value] of Object.entries(extra)) {
|
|
109
|
+
if (value === undefined || value === null) continue
|
|
110
|
+
const lower = name.toLowerCase()
|
|
111
|
+
// The key and the visitor IP travel together or not at all: a per-request header cannot add one without the other.
|
|
112
|
+
if (lower === 'x-pano-frontend-key' || lower === 'x-pano-client-ip') continue
|
|
113
|
+
headers[name] = value
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return headers
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* One fetch with the shared error handling. Never throws.
|
|
122
|
+
* @param {string} method
|
|
123
|
+
* @param {string} path resolved path, starting with "/api/v1/"
|
|
124
|
+
* @param {string} search
|
|
125
|
+
* @param {Record<string, string>} headers
|
|
126
|
+
* @param {any} body
|
|
127
|
+
* @param {AbortSignal|undefined} signal
|
|
128
|
+
* @returns {Promise<{ result: ApiResult<any> }>}
|
|
129
|
+
*/
|
|
130
|
+
async function send(method, path, search, headers, body, signal) {
|
|
131
|
+
const fetchImpl = options.fetch ?? globalThis.fetch
|
|
132
|
+
|
|
133
|
+
if (typeof fetchImpl !== 'function') {
|
|
134
|
+
return { result: failure(0, 'NETWORK_ERROR', { message: 'No fetch implementation available' }) }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** @type {RequestInit} */
|
|
138
|
+
const init = { method, headers, credentials }
|
|
139
|
+
if (body !== undefined) init.body = body
|
|
140
|
+
if (signal) init.signal = signal
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
const response = await fetchImpl(`${baseUrl}${path}${search}`, init)
|
|
144
|
+
const parsed = await readBody(response)
|
|
145
|
+
|
|
146
|
+
if (response.ok) {
|
|
147
|
+
return { result: { ok: true, status: response.status, data: parsed } }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return { result: failureFromBody(response.status, parsed) }
|
|
151
|
+
} catch (error) {
|
|
152
|
+
const aborted = /** @type {any} */ (error)?.name === 'AbortError'
|
|
153
|
+
return {
|
|
154
|
+
result: failure(0, 'NETWORK_ERROR', {
|
|
155
|
+
message: error instanceof Error ? error.message : 'Network request failed',
|
|
156
|
+
...(aborted ? { details: { aborted: true } } : {})
|
|
157
|
+
})
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** @param {any} data */
|
|
163
|
+
function adoptToken(data) {
|
|
164
|
+
if (data && typeof data === 'object' && typeof data.csrfToken === 'string') csrfToken = data.csrfToken
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** GET /auth/csrf once at a time. Never reports to onUnauthorized. */
|
|
168
|
+
function probe() {
|
|
169
|
+
if (!probing) {
|
|
170
|
+
probing = (async () => {
|
|
171
|
+
try {
|
|
172
|
+
const headers = await buildHeaders(undefined)
|
|
173
|
+
const { result } = await send('GET', CSRF_PATH, '', headers, undefined, undefined)
|
|
174
|
+
|
|
175
|
+
if (result.ok) {
|
|
176
|
+
const token = result.data?.csrfToken
|
|
177
|
+
csrfToken = typeof token === 'string' ? token : null
|
|
178
|
+
} else if (result.status === 401) {
|
|
179
|
+
csrfToken = null
|
|
180
|
+
}
|
|
181
|
+
// any other failure (network, 5xx): stay unknown, the next mutation probes again
|
|
182
|
+
} finally {
|
|
183
|
+
probing = null
|
|
184
|
+
}
|
|
185
|
+
})()
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return probing
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* @param {PanoOperation} operation
|
|
193
|
+
* @param {RequestParams} [params]
|
|
194
|
+
* @returns {Promise<ApiResult<any>>}
|
|
195
|
+
*/
|
|
196
|
+
async function request(operation, params = {}) {
|
|
197
|
+
try {
|
|
198
|
+
const method = String(operation.method).toUpperCase()
|
|
199
|
+
const path = fillPath(operation.path, params.path)
|
|
200
|
+
const search = queryString(params.query)
|
|
201
|
+
const mutation = !SAFE_METHODS.has(method)
|
|
202
|
+
const useCsrf = csrfMode === 'auto' && mutation && path !== CSRF_PATH
|
|
203
|
+
|
|
204
|
+
let body = params.body
|
|
205
|
+
let jsonBody = false
|
|
206
|
+
if (body !== undefined && body !== null && !isRawBody(body)) {
|
|
207
|
+
body = JSON.stringify(body)
|
|
208
|
+
jsonBody = true
|
|
209
|
+
} else if (body === null) {
|
|
210
|
+
body = undefined
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** @param {string|null|undefined} token */
|
|
214
|
+
const attempt = async (token) => {
|
|
215
|
+
const headers = await buildHeaders(params.headers)
|
|
216
|
+
if (jsonBody && !Object.keys(headers).some((name) => name.toLowerCase() === 'content-type')) {
|
|
217
|
+
headers['Content-Type'] = 'application/json'
|
|
218
|
+
}
|
|
219
|
+
if (token) headers['X-CSRF-Token'] = token
|
|
220
|
+
return send(method, path, search, headers, body, params.signal)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (useCsrf && csrfToken === undefined) await probe()
|
|
224
|
+
|
|
225
|
+
let { result } = await attempt(useCsrf ? csrfToken : undefined)
|
|
226
|
+
|
|
227
|
+
if (useCsrf && !result.ok && result.error.code === 'INVALID_CSRF_TOKEN') {
|
|
228
|
+
csrfToken = undefined
|
|
229
|
+
await probe()
|
|
230
|
+
|
|
231
|
+
if (csrfToken) {
|
|
232
|
+
;({ result } = await attempt(csrfToken))
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (result.ok) {
|
|
237
|
+
if (mutation && path.startsWith(AUTH_PREFIX)) csrfToken = undefined
|
|
238
|
+
adoptToken(result.data)
|
|
239
|
+
} else if (result.status === 401 && options.onUnauthorized) {
|
|
240
|
+
try {
|
|
241
|
+
options.onUnauthorized(result)
|
|
242
|
+
} catch {
|
|
243
|
+
// a throwing callback must not turn a failed request into a rejected promise
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
return result
|
|
248
|
+
} catch (error) {
|
|
249
|
+
return failure(0, 'NETWORK_ERROR', {
|
|
250
|
+
message: error instanceof Error ? error.message : 'Request failed before it was sent'
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return { request, options: Object.freeze({ ...options }) }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* The data of a successful result, or a thrown PanoApiError.
|
|
260
|
+
* @template T
|
|
261
|
+
* @param {ApiResult<T>} result
|
|
262
|
+
* @returns {T}
|
|
263
|
+
*/
|
|
264
|
+
export function unwrap(result) {
|
|
265
|
+
if (result.ok) return result.data
|
|
266
|
+
throw new PanoApiError(result)
|
|
267
|
+
}
|