@alepha/protobuf 0.5.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Feunard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # @alepha/protobuf
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@alepha/protobuf",
3
+ "version": "0.5.0",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.mjs",
8
+ "types": "./dist/index.d.cts",
9
+ "dependencies": {
10
+ "@alepha/core": "0.5.0",
11
+ "protobufjs": "^7.4.0"
12
+ },
13
+ "devDependencies": {
14
+ "pkgroll": "^2.12.1",
15
+ "vitest": "^3.1.1"
16
+ },
17
+ "scripts": {
18
+ "build": "pkgroll --clean-dist"
19
+ },
20
+ "exports": {
21
+ "require": {
22
+ "types": "./dist/index.d.cts",
23
+ "default": "./dist/index.cjs"
24
+ },
25
+ "import": {
26
+ "types": "./dist/index.d.mts",
27
+ "default": "./dist/index.mjs"
28
+ }
29
+ }
30
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./providers/ProtobufProvider";
@@ -0,0 +1,150 @@
1
+ import type { Static, TObject, TSchema } from "@alepha/core";
2
+ import { $inject, Alepha, TypeGuard } from "@alepha/core";
3
+ import type { Type } from "protobufjs";
4
+ import protobufjs from "protobufjs";
5
+
6
+ export class ProtobufProvider {
7
+ protected readonly alepha = $inject(Alepha);
8
+ protected readonly schemas = new Map<TObject | string, Type>();
9
+ protected readonly protobuf = protobufjs;
10
+
11
+ /**
12
+ * Encode an object to a Uint8Array.
13
+ *
14
+ * @param schema - TypeBox schema used to generate the Protobuf schema.
15
+ * @param data - Object to encode. Can be any object or string.
16
+ */
17
+ public encode(schema: TObject, data: any): Uint8Array {
18
+ return this.parse(schema).encode(this.alepha.parse(schema, data)).finish();
19
+ }
20
+
21
+ /**
22
+ * Decode a Uint8Array to an object.
23
+ *
24
+ * @param schema
25
+ * @param data
26
+ */
27
+ public decode<T extends TObject>(schema: T, data: Uint8Array): Static<T> {
28
+ return this.alepha.parse(schema, this.parse(schema).decode(data));
29
+ }
30
+
31
+ /**
32
+ * Parse a TypeBox schema to a Protobuf Type schema ready for encoding/decoding.
33
+ *
34
+ * @param schema
35
+ * @param typeName
36
+ */
37
+ public parse(
38
+ schema: ProtobufSchema | TObject,
39
+ typeName = "root.Target",
40
+ ): Type {
41
+ const exists = this.schemas.get(schema);
42
+ if (exists) return exists;
43
+
44
+ const pbSchema =
45
+ typeof schema === "string" ? schema : this.createProtobufSchema(schema);
46
+ const result = this.protobuf.parse(pbSchema);
47
+ const type = result.root.lookupType(typeName);
48
+ this.schemas.set(schema, type);
49
+ return type;
50
+ }
51
+
52
+ /**
53
+ * Convert a TypeBox schema to a Protobuf schema as a string.
54
+ *
55
+ * @param schema
56
+ * @param options
57
+ */
58
+ public createProtobufSchema(
59
+ schema: TSchema,
60
+ options: CreateProtobufSchemaOptions = {},
61
+ ): string {
62
+ const { rootName = "root", mainMessageName = "Target" } = options;
63
+ const context = {
64
+ proto: `package ${rootName};\nsyntax = "proto3";\n\n`,
65
+ fieldIndex: 1,
66
+ };
67
+
68
+ if (TypeGuard.IsObject(schema)) {
69
+ const proto = this.parseObject(schema, mainMessageName, context);
70
+ context.proto += proto;
71
+ }
72
+
73
+ return context.proto;
74
+ }
75
+
76
+ /**
77
+ * Parse an object schema to a Protobuf message.
78
+ *
79
+ * @param obj
80
+ * @param parentName
81
+ * @param context
82
+ * @protected
83
+ */
84
+ protected parseObject(
85
+ obj: TSchema,
86
+ parentName: string,
87
+ context: { proto: string; fieldIndex: number },
88
+ ): string {
89
+ if (!TypeGuard.IsObject(obj)) {
90
+ return "";
91
+ }
92
+
93
+ const fields: string[] = [];
94
+
95
+ for (const [key, value] of Object.entries(obj.properties)) {
96
+ if (TypeGuard.IsArray(value)) {
97
+ if (TypeGuard.IsObject(value.items)) {
98
+ const subMessageName = value.items.title ?? `${parentName}_${key}`;
99
+ context.proto += this.parseObject(value.items, subMessageName, {
100
+ ...context,
101
+ fieldIndex: 1,
102
+ });
103
+ fields.push(
104
+ ` repeated ${subMessageName} ${key} = ${context.fieldIndex++};`,
105
+ );
106
+ continue;
107
+ }
108
+
109
+ const itemType = this.convertType(value.items);
110
+ fields.push(` repeated ${itemType} ${key} = ${context.fieldIndex++};`);
111
+ continue;
112
+ }
113
+
114
+ if (TypeGuard.IsObject(value)) {
115
+ const subMessageName = `${parentName}_${key}`;
116
+ context.proto += this.parseObject(value, subMessageName, context);
117
+ fields.push(` ${subMessageName} ${key} = ${context.fieldIndex++};`);
118
+ continue;
119
+ }
120
+
121
+ fields.push(
122
+ ` ${this.convertType(value)} ${key} = ${context.fieldIndex++};`,
123
+ );
124
+ }
125
+
126
+ return `message ${parentName} {\n${fields.join("\n")}\n}\n`;
127
+ }
128
+
129
+ /**
130
+ * Convert a primitive TypeBox schema type to a Protobuf spec type.
131
+ *
132
+ * @param schema
133
+ * @protected
134
+ */
135
+ protected convertType(schema: TSchema): string {
136
+ if (TypeGuard.IsInteger(schema)) return "int32";
137
+ if (TypeGuard.IsNumber(schema)) return "double";
138
+ if (TypeGuard.IsString(schema)) return "string";
139
+ if (TypeGuard.IsBoolean(schema)) return "bool";
140
+
141
+ throw new Error(`Unsupported type: ${JSON.stringify(schema)}`);
142
+ }
143
+ }
144
+
145
+ export type ProtobufSchema = string;
146
+
147
+ export interface CreateProtobufSchemaOptions {
148
+ rootName?: string;
149
+ mainMessageName?: string;
150
+ }
@@ -0,0 +1,41 @@
1
+ import { Alepha, t } from "@alepha/core";
2
+ import { test } from "vitest";
3
+ import { ProtobufProvider } from "../src";
4
+
5
+ const protobuf = Alepha.create().get(ProtobufProvider);
6
+ const userSchema = t.object({
7
+ username: t.string(),
8
+ createdAt: t.datetime(),
9
+ age: t.int(),
10
+ isActive: t.boolean(),
11
+ });
12
+
13
+ test("ProtobufProvider#typeboxToProtobuf", async ({ expect }) => {
14
+ const schema = protobuf.createProtobufSchema(userSchema);
15
+ expect(schema).toBe(
16
+ `package root;
17
+ syntax = "proto3";
18
+
19
+ message Target {
20
+ string username = 1;
21
+ string createdAt = 2;
22
+ int32 age = 3;
23
+ bool isActive = 4;
24
+ }
25
+ `,
26
+ );
27
+ });
28
+
29
+ test("ProtobufProvider#encode", async ({ expect }) => {
30
+ const data = {
31
+ username: "John Doe",
32
+ createdAt: new Date().toISOString(),
33
+ age: 30,
34
+ isActive: true,
35
+ };
36
+ const buf = protobuf.encode(userSchema, data);
37
+ expect(buf).toBeInstanceOf(Uint8Array);
38
+
39
+ const user = protobuf.decode(userSchema, buf);
40
+ expect(user).toEqual(data);
41
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "extends": "../../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "lib"
5
+ }
6
+ }