@bite-ninja/zenu-sdk 0.2.3

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.
@@ -0,0 +1,10 @@
1
+ import { createZenuClient } from "../src/client.js";
2
+
3
+ const client = createZenuClient({
4
+ baseUrl: "https://dev.api.biteninja.com",
5
+ getToken: async () => "",
6
+ });
7
+
8
+ const resp = await client.users.sayHello({ name: "John" });
9
+ console.log(resp.message);
10
+ console.log(resp.currentTime?.toISOString());
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@bite-ninja/zenu-sdk",
3
+ "version": "0.2.3",
4
+ "type": "module",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/index.js",
10
+ "types": "./dist/index.d.ts"
11
+ }
12
+ },
13
+ "scripts": {
14
+ "generate": "buf generate ../../protos",
15
+ "build": "rm -rf ./dist && tsc && bun build ./src/index.ts --outdir ./dist --target browser",
16
+ "lint": "npm run lint:types && npm run lint:format",
17
+ "lint:types": "tsc --noEmit",
18
+ "lint:format": "prettier --cache --check .",
19
+ "prepublishOnly": "bun run generate && bun run build"
20
+ },
21
+ "dependencies": {
22
+ "nice-grpc-web": "^3.3.9",
23
+ "nice-grpc-common": "^2.0.2"
24
+ },
25
+ "devDependencies": {
26
+ "@bufbuild/buf": "^1.64.0",
27
+ "@bufbuild/protobuf": "^2.11.0",
28
+ "@types/bun": "latest",
29
+ "prettier": "^3.8.1",
30
+ "ts-proto": "^2.11.0",
31
+ "typescript": "^5.9.3"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ }
36
+ }
package/src/client.ts ADDED
@@ -0,0 +1,86 @@
1
+ import { createChannel, createClientFactory, Metadata } from "nice-grpc-web";
2
+ import {
3
+ UsersServiceDefinition,
4
+ type UsersServiceClient,
5
+ } from "./gen/zenu/users/v1/users_service.js";
6
+
7
+ /**
8
+ * Configuration for the Zenu SDK client.
9
+ */
10
+ export interface ZenuClientOptions {
11
+ /**
12
+ * Base URL of the API Gateway (e.g., "https://api.biteninja.com")
13
+ */
14
+ baseUrl: string;
15
+
16
+ /**
17
+ * Function that returns a Firebase auth token.
18
+ * Called before each request to get a fresh token.
19
+ */
20
+ getToken: () => Promise<string>;
21
+ }
22
+
23
+ /**
24
+ * Zenu SDK client providing typed access to all services.
25
+ */
26
+ interface ZenuClient {
27
+ /**
28
+ * Users service client for authentication and user management.
29
+ */
30
+ users: UsersServiceClient;
31
+ }
32
+
33
+ /**
34
+ * Creates a new Zenu SDK client.
35
+ *
36
+ * @param opts - Configuration including baseUrl and token getter
37
+ * @returns A typed client with access to all Zenu services
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * import { createZenuClient } from "zenu-sdk";
42
+ * import { getAuth } from "firebase/auth";
43
+ *
44
+ * const client = createZenuClient({
45
+ * baseUrl: "https://api.biteninja.com",
46
+ * getToken: async () => {
47
+ * const auth = getAuth();
48
+ * const user = auth.currentUser;
49
+ * if (!user) throw new Error("Not authenticated");
50
+ * return user.getIdToken();
51
+ * },
52
+ * });
53
+ *
54
+ * // Get current user - createdAt is now a Date!
55
+ * const { user } = await client.users.whoAmI({});
56
+ * console.log(`Hello, ${user?.givenName}!`);
57
+ * console.log(`Account created: ${user?.createdAt?.toLocaleDateString()}`);
58
+ *
59
+ * // Say hello
60
+ * const { message, currentTime } = await client.users.sayHello({ name: "World" });
61
+ * console.log(message);
62
+ * console.log(`Server time: ${currentTime?.toISOString()}`);
63
+ * ```
64
+ */
65
+ export function createZenuClient({
66
+ baseUrl,
67
+ getToken,
68
+ }: ZenuClientOptions): ZenuClient {
69
+ const channel = createChannel(baseUrl);
70
+
71
+ const clientFactory = createClientFactory().use(
72
+ async function* (call, options) {
73
+ const token = await getToken();
74
+ const metadata = Metadata(options.metadata);
75
+ metadata.set("Authorization", `Bearer ${token}`);
76
+ return yield* call.next(call.request, {
77
+ ...options,
78
+ metadata,
79
+ });
80
+ },
81
+ );
82
+
83
+ return {
84
+ users: clientFactory.create(UsersServiceDefinition, channel),
85
+ };
86
+ }
@@ -0,0 +1,229 @@
1
+ // Code generated by protoc-gen-ts_proto. DO NOT EDIT.
2
+ // versions:
3
+ // protoc-gen-ts_proto v2.11.0
4
+ // protoc unknown
5
+ // source: google/protobuf/timestamp.proto
6
+
7
+ /* eslint-disable */
8
+ import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
9
+
10
+ export const protobufPackage = "google.protobuf";
11
+
12
+ /**
13
+ * A Timestamp represents a point in time independent of any time zone or local
14
+ * calendar, encoded as a count of seconds and fractions of seconds at
15
+ * nanosecond resolution. The count is relative to an epoch at UTC midnight on
16
+ * January 1, 1970, in the proleptic Gregorian calendar which extends the
17
+ * Gregorian calendar backwards to year one.
18
+ *
19
+ * All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
20
+ * second table is needed for interpretation, using a [24-hour linear
21
+ * smear](https://developers.google.com/time/smear).
22
+ *
23
+ * The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
24
+ * restricting to that range, we ensure that we can convert to and from [RFC
25
+ * 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
26
+ *
27
+ * # Examples
28
+ *
29
+ * Example 1: Compute Timestamp from POSIX `time()`.
30
+ *
31
+ * Timestamp timestamp;
32
+ * timestamp.set_seconds(time(NULL));
33
+ * timestamp.set_nanos(0);
34
+ *
35
+ * Example 2: Compute Timestamp from POSIX `gettimeofday()`.
36
+ *
37
+ * struct timeval tv;
38
+ * gettimeofday(&tv, NULL);
39
+ *
40
+ * Timestamp timestamp;
41
+ * timestamp.set_seconds(tv.tv_sec);
42
+ * timestamp.set_nanos(tv.tv_usec * 1000);
43
+ *
44
+ * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
45
+ *
46
+ * FILETIME ft;
47
+ * GetSystemTimeAsFileTime(&ft);
48
+ * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
49
+ *
50
+ * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
51
+ * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
52
+ * Timestamp timestamp;
53
+ * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
54
+ * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
55
+ *
56
+ * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
57
+ *
58
+ * long millis = System.currentTimeMillis();
59
+ *
60
+ * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
61
+ * .setNanos((int) ((millis % 1000) * 1000000)).build();
62
+ *
63
+ * Example 5: Compute Timestamp from Java `Instant.now()`.
64
+ *
65
+ * Instant now = Instant.now();
66
+ *
67
+ * Timestamp timestamp =
68
+ * Timestamp.newBuilder().setSeconds(now.getEpochSecond())
69
+ * .setNanos(now.getNano()).build();
70
+ *
71
+ * Example 6: Compute Timestamp from current time in Python.
72
+ *
73
+ * timestamp = Timestamp()
74
+ * timestamp.GetCurrentTime()
75
+ *
76
+ * # JSON Mapping
77
+ *
78
+ * In JSON format, the Timestamp type is encoded as a string in the
79
+ * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
80
+ * format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
81
+ * where {year} is always expressed using four digits while {month}, {day},
82
+ * {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
83
+ * seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
84
+ * are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
85
+ * is required. A proto3 JSON serializer should always use UTC (as indicated by
86
+ * "Z") when printing the Timestamp type and a proto3 JSON parser should be
87
+ * able to accept both UTC and other timezones (as indicated by an offset).
88
+ *
89
+ * For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
90
+ * 01:30 UTC on January 15, 2017.
91
+ *
92
+ * In JavaScript, one can convert a Date object to this format using the
93
+ * standard
94
+ * [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
95
+ * method. In Python, a standard `datetime.datetime` object can be converted
96
+ * to this format using
97
+ * [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
98
+ * the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
99
+ * the Joda Time's [`ISODateTimeFormat.dateTime()`](
100
+ * http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()
101
+ * ) to obtain a formatter capable of generating timestamps in this format.
102
+ */
103
+ export interface Timestamp {
104
+ /**
105
+ * Represents seconds of UTC time since Unix epoch
106
+ * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
107
+ * 9999-12-31T23:59:59Z inclusive.
108
+ */
109
+ seconds: number;
110
+ /**
111
+ * Non-negative fractions of a second at nanosecond resolution. Negative
112
+ * second values with fractions must still have non-negative nanos values
113
+ * that count forward in time. Must be from 0 to 999,999,999
114
+ * inclusive.
115
+ */
116
+ nanos: number;
117
+ }
118
+
119
+ function createBaseTimestamp(): Timestamp {
120
+ return { seconds: 0, nanos: 0 };
121
+ }
122
+
123
+ export const Timestamp: MessageFns<Timestamp> = {
124
+ encode(message: Timestamp, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
125
+ if (message.seconds !== 0) {
126
+ writer.uint32(8).int64(message.seconds);
127
+ }
128
+ if (message.nanos !== 0) {
129
+ writer.uint32(16).int32(message.nanos);
130
+ }
131
+ return writer;
132
+ },
133
+
134
+ decode(input: BinaryReader | Uint8Array, length?: number): Timestamp {
135
+ const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
136
+ const end = length === undefined ? reader.len : reader.pos + length;
137
+ const message = createBaseTimestamp();
138
+ while (reader.pos < end) {
139
+ const tag = reader.uint32();
140
+ switch (tag >>> 3) {
141
+ case 1: {
142
+ if (tag !== 8) {
143
+ break;
144
+ }
145
+
146
+ message.seconds = longToNumber(reader.int64());
147
+ continue;
148
+ }
149
+ case 2: {
150
+ if (tag !== 16) {
151
+ break;
152
+ }
153
+
154
+ message.nanos = reader.int32();
155
+ continue;
156
+ }
157
+ }
158
+ if ((tag & 7) === 4 || tag === 0) {
159
+ break;
160
+ }
161
+ reader.skip(tag & 7);
162
+ }
163
+ return message;
164
+ },
165
+
166
+ fromJSON(object: any): Timestamp {
167
+ return {
168
+ seconds: isSet(object.seconds) ? globalThis.Number(object.seconds) : 0,
169
+ nanos: isSet(object.nanos) ? globalThis.Number(object.nanos) : 0,
170
+ };
171
+ },
172
+
173
+ toJSON(message: Timestamp): unknown {
174
+ const obj: any = {};
175
+ if (message.seconds !== 0) {
176
+ obj.seconds = Math.round(message.seconds);
177
+ }
178
+ if (message.nanos !== 0) {
179
+ obj.nanos = Math.round(message.nanos);
180
+ }
181
+ return obj;
182
+ },
183
+
184
+ create<I extends Exact<DeepPartial<Timestamp>, I>>(base?: I): Timestamp {
185
+ return Timestamp.fromPartial(base ?? ({} as any));
186
+ },
187
+ fromPartial<I extends Exact<DeepPartial<Timestamp>, I>>(object: I): Timestamp {
188
+ const message = createBaseTimestamp();
189
+ message.seconds = object.seconds ?? 0;
190
+ message.nanos = object.nanos ?? 0;
191
+ return message;
192
+ },
193
+ };
194
+
195
+ type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
196
+
197
+ export type DeepPartial<T> = T extends Builtin ? T
198
+ : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>
199
+ : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>
200
+ : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }
201
+ : Partial<T>;
202
+
203
+ type KeysOfUnion<T> = T extends T ? keyof T : never;
204
+ export type Exact<P, I extends P> = P extends Builtin ? P
205
+ : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };
206
+
207
+ function longToNumber(int64: { toString(): string }): number {
208
+ const num = globalThis.Number(int64.toString());
209
+ if (num > globalThis.Number.MAX_SAFE_INTEGER) {
210
+ throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
211
+ }
212
+ if (num < globalThis.Number.MIN_SAFE_INTEGER) {
213
+ throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");
214
+ }
215
+ return num;
216
+ }
217
+
218
+ function isSet(value: any): boolean {
219
+ return value !== null && value !== undefined;
220
+ }
221
+
222
+ export interface MessageFns<T> {
223
+ encode(message: T, writer?: BinaryWriter): BinaryWriter;
224
+ decode(input: BinaryReader | Uint8Array, length?: number): T;
225
+ fromJSON(object: any): T;
226
+ toJSON(message: T): unknown;
227
+ create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;
228
+ fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;
229
+ }