@b3-business/cherry 0.3.1 → 0.3.2

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
@@ -10,9 +10,9 @@ A tree-shakeable, minimal API client factory. Import only the routes you need
10
10
 
11
11
  ---
12
12
 
13
- ## Latest Changelog - 0.3.1
13
+ ## Latest Changelog - 0.3.2
14
14
 
15
- - Fix: Add `@types/bun` to monorepo root for editor TypeScript support
15
+ - Fix: Ship TypeScript source files in npm package to fix module resolution
16
16
 
17
17
  See [CHANGELOG.md](https://github.com/b3-business/cherry/blob/main/packages/cherry/CHANGELOG.md) for full history.
18
18
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@b3-business/cherry",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "A tree-shakeable, minimal API client factory. Import only the routes you need — nothing more.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -14,12 +14,12 @@
14
14
  "./package.json": "./package.json"
15
15
  },
16
16
  "files": [
17
- "dist"
17
+ "dist",
18
+ "src"
18
19
  ],
19
20
  "scripts": {
20
21
  "build": "tsdown",
21
- "check": "run-s lint typecheck",
22
- "lint": "oxlint src test",
22
+ "check": "oxlint --type-aware --type-check src test",
23
23
  "typecheck": "tsc --noEmit -p .",
24
24
  "test": "bun test",
25
25
  "prepublishOnly": "npm run check && npm run test && npm run build",
@@ -34,8 +34,6 @@
34
34
  "@types/bun": "^1.3.5",
35
35
  "expect-type": "^1.3.0",
36
36
  "jsr": "^0.13.5",
37
- "npm-run-all": "^4.1.5",
38
- "oxlint": "^1.36.0",
39
37
  "tsdown": "^0.19.0-beta.2",
40
38
  "typescript": "^5.9.3"
41
39
  },
@@ -0,0 +1,172 @@
1
+ import { ResultAsync } from "neverthrow";
2
+ import * as v from "valibot";
3
+ import type {
4
+ CherryRoute,
5
+ CherryResult,
6
+ InferRouteInput,
7
+ InferRouteOutput,
8
+ Fetcher,
9
+ FetchRequest,
10
+ ClientConfig,
11
+ Client,
12
+ RouteTree,
13
+ RoutesToClient,
14
+ QueryParamOptions,
15
+ } from "./types";
16
+ import { HttpError, ValidationError, NetworkError, SerializationError, UnknownCherryError } from "./errors";
17
+
18
+ const defaultFetcher: Fetcher = (req) => fetch(req.url, req.init);
19
+
20
+ export function serializeQueryParams(
21
+ params: Record<string, unknown>,
22
+ options?: QueryParamOptions,
23
+ ): string {
24
+ if (options?.customSerializer) {
25
+ return options.customSerializer(params);
26
+ }
27
+
28
+ const searchParams = new URLSearchParams();
29
+
30
+ for (const [key, value] of Object.entries(params)) {
31
+ if (value === undefined || value === null) continue;
32
+
33
+ if (Array.isArray(value)) {
34
+ switch (options?.arrayFormat ?? "repeat") {
35
+ case "repeat":
36
+ for (const item of value) {
37
+ searchParams.append(key, String(item));
38
+ }
39
+ break;
40
+ case "comma":
41
+ searchParams.set(key, value.join(","));
42
+ break;
43
+ case "brackets":
44
+ for (const item of value) {
45
+ searchParams.append(`${key}[]`, String(item));
46
+ }
47
+ break;
48
+ case "json":
49
+ try {
50
+ searchParams.set(key, JSON.stringify(value));
51
+ } catch (error) {
52
+ throw new SerializationError("query", key, error);
53
+ }
54
+ break;
55
+ }
56
+ } else {
57
+ searchParams.set(key, String(value));
58
+ }
59
+ }
60
+
61
+ return searchParams.toString();
62
+ }
63
+
64
+ export function createCherryClient<TRoutes extends RouteTree | undefined = undefined>(
65
+ config: ClientConfig<TRoutes>,
66
+ ): Client<TRoutes> {
67
+ const fetcher = config.fetcher ?? defaultFetcher;
68
+
69
+ function call<T extends CherryRoute<any, any, any, any>>(
70
+ route: T,
71
+ params: InferRouteInput<T>,
72
+ ): CherryResult<InferRouteOutput<T>> {
73
+ return ResultAsync.fromPromise(executeRoute(route, params), (error) => {
74
+ if (error instanceof HttpError) return error;
75
+ if (error instanceof ValidationError) return error;
76
+ if (error instanceof NetworkError) return error;
77
+ if (error instanceof SerializationError) return error;
78
+ return new UnknownCherryError(error);
79
+ });
80
+ }
81
+
82
+ async function executeRoute<T extends CherryRoute<any, any, any, any>>(
83
+ route: T,
84
+ params: InferRouteInput<T>,
85
+ ): Promise<InferRouteOutput<T>> {
86
+ let pathParams: Record<string, unknown> = {};
87
+ if (route.pathParams) {
88
+ const result = v.safeParse(route.pathParams, params);
89
+ if (!result.success) throw new ValidationError("request", result.issues);
90
+ pathParams = result.output;
91
+ }
92
+
93
+ let queryParams: Record<string, unknown> = {};
94
+ if (route.queryParams) {
95
+ const result = v.safeParse(route.queryParams, params);
96
+ if (!result.success) throw new ValidationError("request", result.issues);
97
+ queryParams = result.output;
98
+ }
99
+
100
+ let bodyParams: Record<string, unknown> | undefined;
101
+ if (route.bodyParams) {
102
+ const result = v.safeParse(route.bodyParams, params);
103
+ if (!result.success) throw new ValidationError("request", result.issues);
104
+ bodyParams = result.output;
105
+ }
106
+
107
+ let url = route.path.template;
108
+ for (const [key, value] of Object.entries(pathParams)) {
109
+ url = url.replace(`:${key}`, encodeURIComponent(String(value)));
110
+ }
111
+
112
+ const fullUrl = new URL(url, config.baseUrl);
113
+
114
+ if (Object.keys(queryParams).length > 0) {
115
+ fullUrl.search = serializeQueryParams(queryParams, route.queryParamOptions);
116
+ }
117
+
118
+ const headers: Record<string, string> = {
119
+ "Content-Type": "application/json",
120
+ ...(await config.headers?.()),
121
+ };
122
+
123
+ const init: RequestInit = {
124
+ method: route.method,
125
+ headers,
126
+ };
127
+
128
+ if (bodyParams && route.method !== "GET") {
129
+ init.body = JSON.stringify(bodyParams);
130
+ }
131
+
132
+ const req: FetchRequest = {
133
+ url: fullUrl.toString(),
134
+ init,
135
+ };
136
+
137
+ let response: Response;
138
+ try {
139
+ response = await fetcher(req);
140
+ } catch (error) {
141
+ throw new NetworkError(error);
142
+ }
143
+
144
+ if (!response.ok) {
145
+ const body = await response.text().catch(() => undefined);
146
+ throw new HttpError(response.status, response.statusText, body);
147
+ }
148
+
149
+ const json = await response.json();
150
+ const result = v.safeParse(route.response, json);
151
+ if (!result.success) throw new ValidationError("response", result.issues);
152
+
153
+ return result.output;
154
+ }
155
+
156
+ function forgeRouteMethods<T extends RouteTree>(routes: T): RoutesToClient<T> {
157
+ const out: any = {};
158
+
159
+ for (const [key, value] of Object.entries(routes)) {
160
+ if (value && typeof value === "object" && "method" in value && "path" in value) {
161
+ out[key] = (params: any) => call(value as any, params);
162
+ } else if (value && typeof value === "object") {
163
+ out[key] = forgeRouteMethods(value as RouteTree);
164
+ }
165
+ }
166
+
167
+ return out;
168
+ }
169
+
170
+ const routes = config.routes ? forgeRouteMethods(config.routes) : {};
171
+ return { call, ...routes } as Client<TRoutes>;
172
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,86 @@
1
+ import { errAsync, ResultAsync } from "neverthrow";
2
+
3
+ /** Base error class for all Cherry errors */
4
+ export abstract class CherryError extends Error {
5
+ abstract readonly type: string;
6
+ abstract readonly retryable: boolean;
7
+
8
+ constructor(message: string, options?: { cause?: unknown }) {
9
+ super(message, options);
10
+ this.name = this.constructor.name;
11
+ }
12
+ }
13
+
14
+ /** HTTP response errors (4xx, 5xx) */
15
+ export class HttpError extends CherryError {
16
+ readonly type = "HttpError";
17
+ readonly retryable: boolean;
18
+
19
+ constructor(
20
+ public readonly status: number,
21
+ public readonly statusText: string,
22
+ public readonly body?: unknown,
23
+ cause?: unknown,
24
+ ) {
25
+ super(`HTTP ${status}: ${statusText}`, { cause });
26
+ this.retryable = status >= 500 || status === 429;
27
+ }
28
+ }
29
+
30
+ /** Valibot validation errors */
31
+ export class ValidationError extends CherryError {
32
+ readonly type = "ValidationError";
33
+ readonly retryable = false;
34
+
35
+ constructor(
36
+ public readonly target: "request" | "response",
37
+ public readonly issues: unknown[],
38
+ cause?: unknown,
39
+ ) {
40
+ super(`Validation failed for ${target}`, { cause });
41
+ }
42
+ }
43
+
44
+ /** Network/fetch errors */
45
+ export class NetworkError extends CherryError {
46
+ readonly type = "NetworkError";
47
+ readonly retryable = true;
48
+
49
+ constructor(cause?: unknown) {
50
+ super(`Network error`, { cause });
51
+ }
52
+ }
53
+
54
+ /** Serialization errors (e.g., circular references, BigInt in JSON) */
55
+ export class SerializationError extends CherryError {
56
+ readonly type = "SerializationError";
57
+ readonly retryable = false;
58
+
59
+ constructor(
60
+ public readonly target: "query" | "body",
61
+ public readonly key: string,
62
+ cause?: unknown,
63
+ ) {
64
+ super(`Failed to serialize ${target} parameter "${key}"`, { cause });
65
+ }
66
+ }
67
+
68
+ /** Catch-all for unexpected errors */
69
+ export class UnknownCherryError extends CherryError {
70
+ readonly type = "UnknownCherryError";
71
+ readonly retryable = false;
72
+
73
+ constructor(cause?: unknown) {
74
+ super(`Unknown error`, { cause });
75
+ }
76
+ }
77
+
78
+ /** Type guard for CherryError */
79
+ export function isCherryError(error: unknown): error is CherryError {
80
+ return error instanceof CherryError;
81
+ }
82
+
83
+ /** Helper to create error ResultAsync */
84
+ export function cherryErr<T>(error: CherryError): ResultAsync<T, CherryError> {
85
+ return errAsync(error);
86
+ }
package/src/index.ts ADDED
@@ -0,0 +1,32 @@
1
+ export { createCherryClient, serializeQueryParams } from "./cherry_client";
2
+
3
+ export { route } from "./route";
4
+
5
+ export { path, param, optional, type PathParam, type OptionalParam, type AnyPathParam } from "./path";
6
+
7
+ export {
8
+ CherryError,
9
+ HttpError,
10
+ ValidationError,
11
+ NetworkError,
12
+ SerializationError,
13
+ UnknownCherryError,
14
+ isCherryError,
15
+ cherryErr,
16
+ } from "./errors";
17
+
18
+ export type {
19
+ HttpMethod,
20
+ PathTemplate,
21
+ CherryRoute,
22
+ QueryParamOptions,
23
+ InferRouteInput,
24
+ InferRouteOutput,
25
+ CherryResult,
26
+ FetchRequest,
27
+ Fetcher,
28
+ RouteTree,
29
+ ClientConfig,
30
+ Client,
31
+ RoutesToClient,
32
+ } from "./types";
package/src/path.ts ADDED
@@ -0,0 +1,70 @@
1
+ // path.ts - Tagged template functions for type-safe path building
2
+ import type { PathTemplate } from "./types";
3
+
4
+ /** Branded type for path parameter markers */
5
+ declare const PathParamBrand: unique symbol;
6
+ export type PathParam<T extends string = string> = string & {
7
+ readonly [PathParamBrand]: T;
8
+ };
9
+
10
+ /** Branded type for optional path parameter markers */
11
+ declare const OptionalParamBrand: unique symbol;
12
+ export type OptionalParam<T extends string = string> = string & {
13
+ readonly [OptionalParamBrand]: T;
14
+ };
15
+
16
+ /** Union type for any path param marker */
17
+ export type AnyPathParam = PathParam<string> | OptionalParam<string>;
18
+
19
+ /** Create a path parameter marker */
20
+ export function param<T extends string>(name: T): PathParam<T> {
21
+ return `:${name}` as PathParam<T>;
22
+ }
23
+
24
+ /** Create an optional path parameter marker */
25
+ export function optional<T extends string>(name: T): OptionalParam<T> {
26
+ return `(:${name})` as OptionalParam<T>;
27
+ }
28
+
29
+ /**
30
+ * Tagged template for building path templates.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * // Simple path with one param
35
+ * const userPath = path`/users/${param("id")}`;
36
+ * // { template: "/users/:id", paramNames: ["id"] }
37
+ *
38
+ * // Multiple params
39
+ * const postPath = path`/users/${param("userId")}/posts/${param("postId")}`;
40
+ * // { template: "/users/:userId/posts/:postId", paramNames: ["userId", "postId"] }
41
+ *
42
+ * // Optional params
43
+ * const versionedPath = path`/api${optional("version")}/users`;
44
+ * // { template: "/api(:version)/users", paramNames: ["version"] }
45
+ *
46
+ * // No params
47
+ * const staticPath = path`/health`;
48
+ * // { template: "/health", paramNames: [] }
49
+ * ```
50
+ */
51
+ export function path(
52
+ strings: TemplateStringsArray,
53
+ ...params: AnyPathParam[]
54
+ ): PathTemplate {
55
+ const paramNames: string[] = [];
56
+ let template = strings[0];
57
+
58
+ for (let i = 0; i < params.length; i++) {
59
+ const p = params[i];
60
+ template += p + strings[i + 1];
61
+
62
+ // Extract param name from `:name` or `(:name)`
63
+ const match = p.match(/^\(?:(\w+)\)?$/);
64
+ if (match) {
65
+ paramNames.push(match[1]);
66
+ }
67
+ }
68
+
69
+ return { template, paramNames };
70
+ }
package/src/route.ts ADDED
@@ -0,0 +1,63 @@
1
+ import * as v from "valibot";
2
+ import type { CherryRoute } from "./types";
3
+
4
+ const HttpMethodSchema = v.picklist(["GET", "POST", "PUT", "PATCH", "DELETE"]);
5
+
6
+ export function route<
7
+ TPathParams extends v.BaseSchema<any, any, any> | undefined = undefined,
8
+ TQueryParams extends v.BaseSchema<any, any, any> | undefined = undefined,
9
+ TBodyParams extends v.BaseSchema<any, any, any> | undefined = undefined,
10
+ TResponse extends v.BaseSchema<any, any, any> = v.BaseSchema<any, any, any>,
11
+ >(
12
+ config: CherryRoute<TPathParams, TQueryParams, TBodyParams, TResponse>,
13
+ ): CherryRoute<TPathParams, TQueryParams, TBodyParams, TResponse> {
14
+ // validate HTTP method
15
+ v.parse(HttpMethodSchema, config.method);
16
+
17
+ // validate availability and content of pathParams schema, if needed
18
+ if (config.path.paramNames.length > 0) {
19
+ if (!config.pathParams) {
20
+ throw new Error(
21
+ `Route has path params [${config.path.paramNames.join(", ")}] but no pathParams schema`,
22
+ );
23
+ }
24
+
25
+ const schemaKeys = getSchemaKeys(config.pathParams);
26
+
27
+ for (const paramName of config.path.paramNames) {
28
+ if (!schemaKeys.includes(paramName)) {
29
+ throw new Error(
30
+ `Path param ":${paramName}" not found in pathParams schema. ` +
31
+ `Available: [${schemaKeys.join(", ")}]`,
32
+ );
33
+ }
34
+ }
35
+
36
+ for (const schemaKey of schemaKeys) {
37
+ if (!config.path.paramNames.includes(schemaKey)) {
38
+ throw new Error(
39
+ `pathParams schema key "${schemaKey}" not present in path template. ` +
40
+ `Template params: [${config.path.paramNames.join(", ")}]`,
41
+ );
42
+ }
43
+ }
44
+ }
45
+
46
+ return config as CherryRoute<
47
+ TPathParams,
48
+ TQueryParams,
49
+ TBodyParams,
50
+ TResponse
51
+ >;
52
+ }
53
+
54
+ function getSchemaKeys(schema: v.BaseSchema<any, any, any>): string[] {
55
+ if (
56
+ "entries" in schema &&
57
+ typeof (schema as any).entries === "object" &&
58
+ (schema as any).entries !== null
59
+ ) {
60
+ return Object.keys((schema as any).entries);
61
+ }
62
+ return [];
63
+ }
package/src/types.ts ADDED
@@ -0,0 +1,107 @@
1
+ import type { BaseSchema, InferInput, InferOutput } from "valibot";
2
+ import type { ResultAsync } from "neverthrow";
3
+ import type { CherryError } from "./errors";
4
+
5
+ type AnySchema = BaseSchema<any, any, any>;
6
+
7
+ /** HTTP methods supported by Cherry */
8
+ export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
9
+
10
+ /** Path template result from path() tagged template */
11
+ export type PathTemplate = {
12
+ template: string; // "/users/:id/posts/:postId"
13
+ paramNames: string[]; // ["id", "postId"]
14
+ };
15
+
16
+ /** Route definition with separated parameter schemas */
17
+ export type CherryRoute<
18
+ TPathParams extends AnySchema | undefined = undefined,
19
+ TQueryParams extends AnySchema | undefined = undefined,
20
+ TBodyParams extends AnySchema | undefined = undefined,
21
+ TResponse extends AnySchema = AnySchema,
22
+ > = {
23
+ method: HttpMethod;
24
+ path: PathTemplate;
25
+ pathParams?: TPathParams;
26
+ queryParams?: TQueryParams;
27
+ bodyParams?: TBodyParams;
28
+ response: TResponse;
29
+ queryParamOptions?: QueryParamOptions;
30
+ description?: string;
31
+ };
32
+
33
+ /** Options for query parameter serialization */
34
+ export type QueryParamOptions = {
35
+ arrayFormat?: "repeat" | "comma" | "brackets" | "json";
36
+ customSerializer?: (params: Record<string, unknown>) => string;
37
+ };
38
+
39
+ type AnyCherryRoute = CherryRoute<any, any, any, any>;
40
+
41
+ type Prettify<T> = { [K in keyof T]: T[K] } & {};
42
+
43
+ type IsEmptyObject<T> = keyof T extends never ? true : false;
44
+
45
+ type InferSchemaInput<T> = T extends AnySchema ? InferInput<T> : {};
46
+
47
+ type BuildRouteInputFromProps<
48
+ TPathParams,
49
+ TQueryParams,
50
+ TBodyParams
51
+ > = InferSchemaInput<TPathParams> &
52
+ InferSchemaInput<TQueryParams> &
53
+ InferSchemaInput<TBodyParams>;
54
+
55
+ export type InferRouteInput<T> =
56
+ T extends { pathParams?: infer TPath; queryParams?: infer TQuery; bodyParams?: infer TBody }
57
+ ? IsEmptyObject<BuildRouteInputFromProps<TPath, TQuery, TBody>> extends true
58
+ ? void
59
+ : Prettify<BuildRouteInputFromProps<TPath, TQuery, TBody>>
60
+ : never;
61
+
62
+ /** Infer response output from a route */
63
+ export type InferRouteOutput<T extends AnyCherryRoute> =
64
+ T["response"] extends AnySchema ? InferOutput<T["response"]> : never;
65
+
66
+ /** Cherry result type - always ResultAsync */
67
+ export type CherryResult<T> = ResultAsync<T, CherryError>;
68
+
69
+ /** Fetcher request shape (extensible for middleware) */
70
+ export type FetchRequest = {
71
+ url: string;
72
+ init: RequestInit;
73
+ };
74
+
75
+ /** Fetcher function signature */
76
+ export type Fetcher = (req: FetchRequest) => Promise<Response>;
77
+
78
+ /** Route tree (supports namespacing via nested objects) */
79
+ export type RouteTree = {
80
+ [key: string]: AnyCherryRoute | RouteTree;
81
+ };
82
+
83
+ /** Client configuration */
84
+ export type ClientConfig<TRoutes extends RouteTree | undefined = undefined> = {
85
+ baseUrl: string;
86
+ headers?: () => Record<string, string> | Promise<Record<string, string>>;
87
+ fetcher?: Fetcher;
88
+ routes?: TRoutes;
89
+ };
90
+
91
+ export type Client<TRoutes extends RouteTree | undefined = undefined> = {
92
+ call: <T extends AnyCherryRoute>(
93
+ route: T,
94
+ ...args: InferRouteInput<T> extends void ? [] : [params: InferRouteInput<T>]
95
+ ) => CherryResult<InferRouteOutput<T>>;
96
+ } & (TRoutes extends RouteTree ? RoutesToClient<TRoutes> : {});
97
+
98
+ /** Convert a nested route tree into a nested client method tree */
99
+ export type RoutesToClient<TRoutes extends RouteTree> = {
100
+ [K in keyof TRoutes]: TRoutes[K] extends AnyCherryRoute
101
+ ? InferRouteInput<TRoutes[K]> extends void
102
+ ? () => CherryResult<InferRouteOutput<TRoutes[K]>>
103
+ : (params: InferRouteInput<TRoutes[K]>) => CherryResult<InferRouteOutput<TRoutes[K]>>
104
+ : TRoutes[K] extends RouteTree
105
+ ? RoutesToClient<TRoutes[K]>
106
+ : never;
107
+ };