@routar/fetch 1.0.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.
- package/dist/index.cjs +34 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +32 -7
- package/dist/index.js.map +1 -1
- package/package.json +2 -4
package/dist/index.cjs
CHANGED
|
@@ -1,14 +1,36 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
// ../core/dist/index.js
|
|
4
|
+
function createExecutor(execute, middlewares = []) {
|
|
5
|
+
const chain = middlewares.reduceRight((next, mw) => (opts) => mw(opts, next), execute);
|
|
6
|
+
return { execute: chain };
|
|
7
|
+
}
|
|
8
|
+
function serializeParams(params) {
|
|
9
|
+
const result = new URLSearchParams();
|
|
10
|
+
for (const [key, value] of Object.entries(params)) {
|
|
11
|
+
if (value == null) continue;
|
|
12
|
+
if (Array.isArray(value)) {
|
|
13
|
+
for (const item of value) {
|
|
14
|
+
if (item != null) result.append(key, String(item));
|
|
15
|
+
}
|
|
16
|
+
} else if (typeof value === "object") {
|
|
17
|
+
throw new TypeError(
|
|
18
|
+
`serializeParams: value for key "${key}" is a plain object. Serialize it to a string before passing as a query parameter.`
|
|
19
|
+
);
|
|
20
|
+
} else {
|
|
21
|
+
result.append(key, String(value));
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return result;
|
|
25
|
+
}
|
|
4
26
|
|
|
5
27
|
// src/create-fetch-executor.ts
|
|
6
28
|
function createFetchExecutor(baseURL, options) {
|
|
7
|
-
return
|
|
29
|
+
return createExecutor(
|
|
8
30
|
async ({ method, url, params, body, headers, signal }) => {
|
|
9
31
|
const fullURL = new URL(baseURL.replace(/\/$/, "") + url);
|
|
10
32
|
if (params) {
|
|
11
|
-
|
|
33
|
+
serializeParams(params).forEach((v, k) => {
|
|
12
34
|
fullURL.searchParams.set(k, v);
|
|
13
35
|
});
|
|
14
36
|
}
|
|
@@ -16,29 +38,32 @@ function createFetchExecutor(baseURL, options) {
|
|
|
16
38
|
const res = await fetch(fullURL.toString(), {
|
|
17
39
|
method,
|
|
18
40
|
headers: {
|
|
19
|
-
...body != null ? { "Content-Type": "application/json" } : {},
|
|
20
41
|
...defaultHeaders,
|
|
21
|
-
...headers
|
|
42
|
+
...headers,
|
|
43
|
+
...body != null ? { "Content-Type": "application/json" } : {}
|
|
22
44
|
},
|
|
23
45
|
body: body != null ? JSON.stringify(body) : void 0,
|
|
24
46
|
signal
|
|
25
47
|
});
|
|
26
48
|
if (!res.ok) {
|
|
27
|
-
|
|
49
|
+
const errorBody = await res.json().catch(() => null);
|
|
50
|
+
throw new HttpError(res.status, res.statusText, errorBody);
|
|
28
51
|
}
|
|
29
|
-
if (res.status === 204 || res.
|
|
52
|
+
if (res.status === 204 || res.status === 205 || res.status === 304) {
|
|
30
53
|
return null;
|
|
31
54
|
}
|
|
32
|
-
|
|
55
|
+
const text = await res.text();
|
|
56
|
+
return text === "" ? null : JSON.parse(text);
|
|
33
57
|
},
|
|
34
58
|
options?.middlewares
|
|
35
59
|
);
|
|
36
60
|
}
|
|
37
61
|
var HttpError = class extends Error {
|
|
38
|
-
constructor(status, statusText) {
|
|
62
|
+
constructor(status, statusText, body = null) {
|
|
39
63
|
super(`HTTP ${status}: ${statusText}`);
|
|
40
64
|
this.status = status;
|
|
41
65
|
this.statusText = statusText;
|
|
66
|
+
this.body = body;
|
|
42
67
|
this.name = "HttpError";
|
|
43
68
|
}
|
|
44
69
|
};
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/create-fetch-executor.ts"],"names":[
|
|
1
|
+
{"version":3,"sources":["../../core/src/create-executor.ts","../../core/src/utils/params.ts","../src/create-fetch-executor.ts"],"names":[],"mappings":";;;AAuBO,SAAS,cAAA,CACd,OAAA,EACA,WAAA,GAAoC,EAAA,EAC1B;A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ACnC,WAAA,CAEkB,MAAA,EAEA,UAAA,EAEA,IAAA,GAAgB,IAAA,EAChC;AACA,IAAA,KAAA,CAAM,CAAA,KAAA,EAAQ,MAAM,CAAA,EAAA,EAAK,UAAU,CAAA,CAAE,CAAA;AANrB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAEA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAEA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AAAA,EACd;AACF","file":"index.cjs","sourcesContent":["import type { ExecuteOptions, Executor, ExecutorMiddleware } from \"./types.js\";\n\n/**\n * Creates an {@link Executor} by wrapping a transport function with an\n * optional middleware chain.\n *\n * Middlewares are applied in declaration order — the first middleware is the\n * outermost wrapper and runs first on each request.\n *\n * @param execute - The underlying transport function (fetch, axios, etc.).\n * @param middlewares - Ordered list of middlewares to apply.\n *\n * @example\n * ```ts\n * const executor = createExecutor(\n * async ({ method, url, body }) => {\n * const res = await fetch(url, { method, body: JSON.stringify(body) });\n * return res.json();\n * },\n * [withTimeout(5000), withRetry(3), withLogger()],\n * );\n * ```\n */\nexport function createExecutor(\n execute: (options: ExecuteOptions) => Promise<unknown>,\n middlewares: ExecutorMiddleware[] = [],\n): Executor {\n const chain = middlewares.reduceRight<\n (options: ExecuteOptions) => Promise<unknown>\n >((next, mw) => (opts) => mw(opts, next), execute);\n return { execute: chain };\n}\n\n/**\n * Creates an {@link Executor} that selects the underlying transport at\n * request time based on the result of `resolver`.\n *\n * Use this to unify SSR and CSR behind a single API client — the resolver\n * picks the right executor per request, so `createApi` is called once and\n * works in both environments without duplicate `*ServerApi` instances.\n *\n * The resolver receives the full {@link ExecuteOptions} so it can branch on\n * environment, URL prefix, auth context, or any runtime condition.\n *\n * @param resolver - Called on every request; returns the executor to delegate to.\n *\n * @example\n * ```ts\n * // SSR vs CSR — pick transport based on environment\n * const apiExecutor = dispatchExecutor(() =>\n * typeof window === 'undefined' ? serverExecutor : clientExecutor,\n * );\n *\n * // Route by URL prefix — internal routes use a different transport\n * const apiExecutor = dispatchExecutor((opts) =>\n * opts.url.startsWith('/internal') ? internalExecutor : publicExecutor,\n * );\n * ```\n */\nexport function dispatchExecutor(\n resolver: (opts: ExecuteOptions) => Executor,\n): Executor {\n return {\n execute: (opts) => resolver(opts).execute(opts),\n };\n}\n","export function serializeParams(\n params: Record<string, unknown>,\n): URLSearchParams {\n const result = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value == null) continue;\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item != null) result.append(key, String(item));\n }\n } else if (typeof value === \"object\") {\n throw new TypeError(\n `serializeParams: value for key \"${key}\" is a plain object. Serialize it to a string before passing as a query parameter.`,\n );\n } else {\n result.append(key, String(value));\n }\n }\n return result;\n}\n","import type { Executor, ExecutorMiddleware } from \"@routar/core\";\nimport { createExecutor, serializeParams } from \"@routar/core\";\n\n/**\n * Creates an {@link Executor} backed by the browser / Node.js `fetch` API.\n *\n * Suited for SSR environments where you need per-request dynamic headers\n * (e.g. forwarding auth cookies) without sharing state across requests.\n *\n * - Query params are serialized and appended to the URL.\n * - A `Content-Type: application/json` header is added automatically when\n * a request body is present.\n * - Responses with status 204 or `Content-Length: 0` resolve to `null`.\n * - Non-2xx responses throw an {@link HttpError}.\n *\n * @param baseURL - Absolute base URL prepended to every endpoint path.\n * @param options.defaultHeaders - Async factory called on every request to\n * produce headers (e.g. reading cookies in a Next.js server component).\n * @param options.middlewares - Middleware chain applied before the fetch call.\n *\n * @example\n * ```ts\n * const executor = createFetchExecutor('https://api.example.com', {\n * defaultHeaders: async () => {\n * const token = await getServerToken();\n * return token ? { Authorization: `Bearer ${token}` } : {};\n * },\n * });\n * ```\n */\nexport function createFetchExecutor(\n baseURL: string,\n options?: {\n defaultHeaders?: () =>\n | Record<string, string>\n | Promise<Record<string, string>>;\n middlewares?: ExecutorMiddleware[];\n },\n): Executor {\n return createExecutor(\n async ({ method, url, params, body, headers, signal }) => {\n const fullURL = new URL(baseURL.replace(/\\/$/, \"\") + url);\n if (params) {\n serializeParams(params).forEach((v, k) => {\n fullURL.searchParams.set(k, v);\n });\n }\n\n const defaultHeaders = (await options?.defaultHeaders?.()) ?? {};\n\n const res = await fetch(fullURL.toString(), {\n method,\n headers: {\n ...defaultHeaders,\n ...headers,\n ...(body != null ? { \"Content-Type\": \"application/json\" } : {}),\n },\n body: body != null ? JSON.stringify(body) : undefined,\n signal,\n });\n\n if (!res.ok) {\n const errorBody = await res.json().catch(() => null);\n throw new HttpError(res.status, res.statusText, errorBody);\n }\n if (res.status === 204 || res.status === 205 || res.status === 304) {\n return null;\n }\n const text = await res.text();\n return text === \"\" ? null : JSON.parse(text);\n },\n options?.middlewares,\n );\n}\n\n/**\n * Thrown by {@link createFetchExecutor} when the server returns a non-2xx\n * status code.\n *\n * @example\n * ```ts\n * try {\n * await api.getDetail({ path: { id: 999 } });\n * } catch (err) {\n * if (err instanceof HttpError && err.status === 404) {\n * // handle not-found\n * }\n * }\n * ```\n */\nexport class HttpError extends Error {\n constructor(\n /** HTTP status code (e.g. 404, 500). */\n public readonly status: number,\n /** HTTP status text (e.g. \"Not Found\"). */\n public readonly statusText: string,\n /** Parsed response body, or `null` if the body was empty or not JSON. */\n public readonly body: unknown = null,\n ) {\n super(`HTTP ${status}: ${statusText}`);\n this.name = \"HttpError\";\n }\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -51,11 +51,15 @@ declare class HttpError extends Error {
|
|
|
51
51
|
readonly status: number;
|
|
52
52
|
/** HTTP status text (e.g. "Not Found"). */
|
|
53
53
|
readonly statusText: string;
|
|
54
|
+
/** Parsed response body, or `null` if the body was empty or not JSON. */
|
|
55
|
+
readonly body: unknown;
|
|
54
56
|
constructor(
|
|
55
57
|
/** HTTP status code (e.g. 404, 500). */
|
|
56
58
|
status: number,
|
|
57
59
|
/** HTTP status text (e.g. "Not Found"). */
|
|
58
|
-
statusText: string
|
|
60
|
+
statusText: string,
|
|
61
|
+
/** Parsed response body, or `null` if the body was empty or not JSON. */
|
|
62
|
+
body?: unknown);
|
|
59
63
|
}
|
|
60
64
|
|
|
61
65
|
export { HttpError, createFetchExecutor };
|
package/dist/index.d.ts
CHANGED
|
@@ -51,11 +51,15 @@ declare class HttpError extends Error {
|
|
|
51
51
|
readonly status: number;
|
|
52
52
|
/** HTTP status text (e.g. "Not Found"). */
|
|
53
53
|
readonly statusText: string;
|
|
54
|
+
/** Parsed response body, or `null` if the body was empty or not JSON. */
|
|
55
|
+
readonly body: unknown;
|
|
54
56
|
constructor(
|
|
55
57
|
/** HTTP status code (e.g. 404, 500). */
|
|
56
58
|
status: number,
|
|
57
59
|
/** HTTP status text (e.g. "Not Found"). */
|
|
58
|
-
statusText: string
|
|
60
|
+
statusText: string,
|
|
61
|
+
/** Parsed response body, or `null` if the body was empty or not JSON. */
|
|
62
|
+
body?: unknown);
|
|
59
63
|
}
|
|
60
64
|
|
|
61
65
|
export { HttpError, createFetchExecutor };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,26 @@
|
|
|
1
|
-
|
|
1
|
+
// ../core/dist/index.js
|
|
2
|
+
function createExecutor(execute, middlewares = []) {
|
|
3
|
+
const chain = middlewares.reduceRight((next, mw) => (opts) => mw(opts, next), execute);
|
|
4
|
+
return { execute: chain };
|
|
5
|
+
}
|
|
6
|
+
function serializeParams(params) {
|
|
7
|
+
const result = new URLSearchParams();
|
|
8
|
+
for (const [key, value] of Object.entries(params)) {
|
|
9
|
+
if (value == null) continue;
|
|
10
|
+
if (Array.isArray(value)) {
|
|
11
|
+
for (const item of value) {
|
|
12
|
+
if (item != null) result.append(key, String(item));
|
|
13
|
+
}
|
|
14
|
+
} else if (typeof value === "object") {
|
|
15
|
+
throw new TypeError(
|
|
16
|
+
`serializeParams: value for key "${key}" is a plain object. Serialize it to a string before passing as a query parameter.`
|
|
17
|
+
);
|
|
18
|
+
} else {
|
|
19
|
+
result.append(key, String(value));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return result;
|
|
23
|
+
}
|
|
2
24
|
|
|
3
25
|
// src/create-fetch-executor.ts
|
|
4
26
|
function createFetchExecutor(baseURL, options) {
|
|
@@ -14,29 +36,32 @@ function createFetchExecutor(baseURL, options) {
|
|
|
14
36
|
const res = await fetch(fullURL.toString(), {
|
|
15
37
|
method,
|
|
16
38
|
headers: {
|
|
17
|
-
...body != null ? { "Content-Type": "application/json" } : {},
|
|
18
39
|
...defaultHeaders,
|
|
19
|
-
...headers
|
|
40
|
+
...headers,
|
|
41
|
+
...body != null ? { "Content-Type": "application/json" } : {}
|
|
20
42
|
},
|
|
21
43
|
body: body != null ? JSON.stringify(body) : void 0,
|
|
22
44
|
signal
|
|
23
45
|
});
|
|
24
46
|
if (!res.ok) {
|
|
25
|
-
|
|
47
|
+
const errorBody = await res.json().catch(() => null);
|
|
48
|
+
throw new HttpError(res.status, res.statusText, errorBody);
|
|
26
49
|
}
|
|
27
|
-
if (res.status === 204 || res.
|
|
50
|
+
if (res.status === 204 || res.status === 205 || res.status === 304) {
|
|
28
51
|
return null;
|
|
29
52
|
}
|
|
30
|
-
|
|
53
|
+
const text = await res.text();
|
|
54
|
+
return text === "" ? null : JSON.parse(text);
|
|
31
55
|
},
|
|
32
56
|
options?.middlewares
|
|
33
57
|
);
|
|
34
58
|
}
|
|
35
59
|
var HttpError = class extends Error {
|
|
36
|
-
constructor(status, statusText) {
|
|
60
|
+
constructor(status, statusText, body = null) {
|
|
37
61
|
super(`HTTP ${status}: ${statusText}`);
|
|
38
62
|
this.status = status;
|
|
39
63
|
this.statusText = statusText;
|
|
64
|
+
this.body = body;
|
|
40
65
|
this.name = "HttpError";
|
|
41
66
|
}
|
|
42
67
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/create-fetch-executor.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"sources":["../../core/src/create-executor.ts","../../core/src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A,IAC7C,CAAA;AAAA,IACA,OAAA,EAAS;AAAA,GACX;AACF;AAiBO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EACnC,WAAA,CAEkB,MAAA,EAEA,UAAA,EAEA,IAAA,GAAgB,IAAA,EAChC;AACA,IAAA,KAAA,CAAM,CAAA,KAAA,EAAQ,MAAM,CAAA,EAAA,EAAK,UAAU,CAAA,CAAE,CAAA;AANrB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAEA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAEA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AAAA,EACd;AACF","file":"index.js","sourcesContent":["import type { ExecuteOptions, Executor, ExecutorMiddleware } from \"./types.js\";\n\n/**\n * Creates an {@link Executor} by wrapping a transport function with an\n * optional middleware chain.\n *\n * Middlewares are applied in declaration order — the first middleware is the\n * outermost wrapper and runs first on each request.\n *\n * @param execute - The underlying transport function (fetch, axios, etc.).\n * @param middlewares - Ordered list of middlewares to apply.\n *\n * @example\n * ```ts\n * const executor = createExecutor(\n * async ({ method, url, body }) => {\n * const res = await fetch(url, { method, body: JSON.stringify(body) });\n * return res.json();\n * },\n * [withTimeout(5000), withRetry(3), withLogger()],\n * );\n * ```\n */\nexport function createExecutor(\n execute: (options: ExecuteOptions) => Promise<unknown>,\n middlewares: ExecutorMiddleware[] = [],\n): Executor {\n const chain = middlewares.reduceRight<\n (options: ExecuteOptions) => Promise<unknown>\n >((next, mw) => (opts) => mw(opts, next), execute);\n return { execute: chain };\n}\n\n/**\n * Creates an {@link Executor} that selects the underlying transport at\n * request time based on the result of `resolver`.\n *\n * Use this to unify SSR and CSR behind a single API client — the resolver\n * picks the right executor per request, so `createApi` is called once and\n * works in both environments without duplicate `*ServerApi` instances.\n *\n * The resolver receives the full {@link ExecuteOptions} so it can branch on\n * environment, URL prefix, auth context, or any runtime condition.\n *\n * @param resolver - Called on every request; returns the executor to delegate to.\n *\n * @example\n * ```ts\n * // SSR vs CSR — pick transport based on environment\n * const apiExecutor = dispatchExecutor(() =>\n * typeof window === 'undefined' ? serverExecutor : clientExecutor,\n * );\n *\n * // Route by URL prefix — internal routes use a different transport\n * const apiExecutor = dispatchExecutor((opts) =>\n * opts.url.startsWith('/internal') ? internalExecutor : publicExecutor,\n * );\n * ```\n */\nexport function dispatchExecutor(\n resolver: (opts: ExecuteOptions) => Executor,\n): Executor {\n return {\n execute: (opts) => resolver(opts).execute(opts),\n };\n}\n","export function serializeParams(\n params: Record<string, unknown>,\n): URLSearchParams {\n const result = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value == null) continue;\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item != null) result.append(key, String(item));\n }\n } else if (typeof value === \"object\") {\n throw new TypeError(\n `serializeParams: value for key \"${key}\" is a plain object. Serialize it to a string before passing as a query parameter.`,\n );\n } else {\n result.append(key, String(value));\n }\n }\n return result;\n}\n","import type { Executor, ExecutorMiddleware } from \"@routar/core\";\nimport { createExecutor, serializeParams } from \"@routar/core\";\n\n/**\n * Creates an {@link Executor} backed by the browser / Node.js `fetch` API.\n *\n * Suited for SSR environments where you need per-request dynamic headers\n * (e.g. forwarding auth cookies) without sharing state across requests.\n *\n * - Query params are serialized and appended to the URL.\n * - A `Content-Type: application/json` header is added automatically when\n * a request body is present.\n * - Responses with status 204 or `Content-Length: 0` resolve to `null`.\n * - Non-2xx responses throw an {@link HttpError}.\n *\n * @param baseURL - Absolute base URL prepended to every endpoint path.\n * @param options.defaultHeaders - Async factory called on every request to\n * produce headers (e.g. reading cookies in a Next.js server component).\n * @param options.middlewares - Middleware chain applied before the fetch call.\n *\n * @example\n * ```ts\n * const executor = createFetchExecutor('https://api.example.com', {\n * defaultHeaders: async () => {\n * const token = await getServerToken();\n * return token ? { Authorization: `Bearer ${token}` } : {};\n * },\n * });\n * ```\n */\nexport function createFetchExecutor(\n baseURL: string,\n options?: {\n defaultHeaders?: () =>\n | Record<string, string>\n | Promise<Record<string, string>>;\n middlewares?: ExecutorMiddleware[];\n },\n): Executor {\n return createExecutor(\n async ({ method, url, params, body, headers, signal }) => {\n const fullURL = new URL(baseURL.replace(/\\/$/, \"\") + url);\n if (params) {\n serializeParams(params).forEach((v, k) => {\n fullURL.searchParams.set(k, v);\n });\n }\n\n const defaultHeaders = (await options?.defaultHeaders?.()) ?? {};\n\n const res = await fetch(fullURL.toString(), {\n method,\n headers: {\n ...defaultHeaders,\n ...headers,\n ...(body != null ? { \"Content-Type\": \"application/json\" } : {}),\n },\n body: body != null ? JSON.stringify(body) : undefined,\n signal,\n });\n\n if (!res.ok) {\n const errorBody = await res.json().catch(() => null);\n throw new HttpError(res.status, res.statusText, errorBody);\n }\n if (res.status === 204 || res.status === 205 || res.status === 304) {\n return null;\n }\n const text = await res.text();\n return text === \"\" ? null : JSON.parse(text);\n },\n options?.middlewares,\n );\n}\n\n/**\n * Thrown by {@link createFetchExecutor} when the server returns a non-2xx\n * status code.\n *\n * @example\n * ```ts\n * try {\n * await api.getDetail({ path: { id: 999 } });\n * } catch (err) {\n * if (err instanceof HttpError && err.status === 404) {\n * // handle not-found\n * }\n * }\n * ```\n */\nexport class HttpError extends Error {\n constructor(\n /** HTTP status code (e.g. 404, 500). */\n public readonly status: number,\n /** HTTP status text (e.g. \"Not Found\"). */\n public readonly statusText: string,\n /** Parsed response body, or `null` if the body was empty or not JSON. */\n public readonly body: unknown = null,\n ) {\n super(`HTTP ${status}: ${statusText}`);\n this.name = \"HttpError\";\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@routar/fetch",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Fetch-based executor for routar — transport adapter using the native fetch API",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"api",
|
|
@@ -38,9 +38,7 @@
|
|
|
38
38
|
"build": "tsup",
|
|
39
39
|
"dev": "tsup --watch"
|
|
40
40
|
},
|
|
41
|
-
"peerDependencies": {
|
|
42
|
-
"@routar/core": "^1.0.0"
|
|
43
|
-
},
|
|
41
|
+
"peerDependencies": {},
|
|
44
42
|
"devDependencies": {
|
|
45
43
|
"@routar/core": "workspace:*",
|
|
46
44
|
"tsup": "^8.5.1"
|