go2typebox 0.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.
Files changed (42) hide show
  1. package/README.md +56 -0
  2. package/dist/generator.d.ts +14 -0
  3. package/dist/generator.d.ts.map +1 -0
  4. package/dist/generator.js +165 -0
  5. package/dist/generator.js.map +1 -0
  6. package/dist/go2typebox.d.ts +54 -0
  7. package/dist/go2typebox.d.ts.map +1 -0
  8. package/dist/go2typebox.js +219 -0
  9. package/dist/go2typebox.js.map +1 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +15 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/parser.d.ts +10 -0
  15. package/dist/parser.d.ts.map +1 -0
  16. package/dist/parser.js +87 -0
  17. package/dist/parser.js.map +1 -0
  18. package/dist/pruneTypeboxFile.d.ts +18 -0
  19. package/dist/pruneTypeboxFile.d.ts.map +1 -0
  20. package/dist/pruneTypeboxFile.js +192 -0
  21. package/dist/pruneTypeboxFile.js.map +1 -0
  22. package/dist/sorter.d.ts +15 -0
  23. package/dist/sorter.d.ts.map +1 -0
  24. package/dist/sorter.js +113 -0
  25. package/dist/sorter.js.map +1 -0
  26. package/dist/standardizeTypeboxTypes.d.ts +48 -0
  27. package/dist/standardizeTypeboxTypes.d.ts.map +1 -0
  28. package/dist/standardizeTypeboxTypes.js +351 -0
  29. package/dist/standardizeTypeboxTypes.js.map +1 -0
  30. package/dist/types.d.ts +67 -0
  31. package/dist/types.d.ts.map +1 -0
  32. package/dist/types.js +3 -0
  33. package/dist/types.js.map +1 -0
  34. package/dist/utils.d.ts +19 -0
  35. package/dist/utils.d.ts.map +1 -0
  36. package/dist/utils.js +64 -0
  37. package/dist/utils.js.map +1 -0
  38. package/dist/writer.d.ts +16 -0
  39. package/dist/writer.d.ts.map +1 -0
  40. package/dist/writer.js +105 -0
  41. package/dist/writer.js.map +1 -0
  42. package/package.json +53 -0
package/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # go2typebox
2
+
3
+ Convert Go `struct` definitions into [Sinclair TypeBox](https://github.com/sinclairzx81/typebox) schemas: one or more `.go` files → one `.ts` file with `Type.Object` and `Static<…>` types.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install go2typebox @sinclair/typebox
9
+ ```
10
+
11
+ `typescript` is a runtime dependency (used by `pruneTypeboxFileByRequestResponseRoots` to parse and transform generated TypeScript).
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { Go2Typebox } from 'go2typebox';
17
+
18
+ const g = new Go2Typebox();
19
+ await g.convertFile('models.go', 'models.typebox.ts');
20
+ await g.convertMany(['a.go', 'b.go'], 'out.ts', { firstMode: 'overwrite', nextMode: 'append' });
21
+ ```
22
+
23
+ ### Post-processing
24
+
25
+ Normalizes the generated file: `Schema` postfix on const names, PascalCase exports, and unwraps `Type.Ref(FooSchema)` → `FooSchema` (TypeBox ≥ 0.34).
26
+
27
+ ```ts
28
+ import { standardizeTypeboxTypes } from 'go2typebox';
29
+
30
+ await standardizeTypeboxTypes('out.ts');
31
+ ```
32
+
33
+ Optional JSON-RPC style wrappers and a helper import:
34
+
35
+ ```ts
36
+ await standardizeTypeboxTypes('out.ts', {
37
+ jsonRpc: {
38
+ helpersImportPath: './rpcHelpers',
39
+ requestArrSchemaNames: ['RequestMyListSchema'],
40
+ },
41
+ });
42
+ ```
43
+
44
+ ### Prune unused schemas
45
+
46
+ Keeps only `Request*Schema` / `Response*Schema` roots and schemas they reference; removes the rest from the file.
47
+
48
+ ```ts
49
+ import { pruneTypeboxFileByRequestResponseRoots } from 'go2typebox';
50
+
51
+ pruneTypeboxFileByRequestResponseRoots('out.ts');
52
+ ```
53
+
54
+ ## Publishing
55
+
56
+ Run `npm run build`, then `npm publish`. If you publish under a scope, set `name` in `package.json` (for example `@your-scope/go2typebox`).
@@ -0,0 +1,14 @@
1
+ import { EmptyStructStrategy, GoStruct, GoSliceTypeAliasMap, GoTypeAliasMap } from './types';
2
+ /** Default TypeScript import line for TypeBox + Static. */
3
+ export declare function getTypeboxImports(): string;
4
+ /**
5
+ * Concatenates TypeBox schema and Static type declarations for each struct in order.
6
+ */
7
+ export declare function buildTypeBoxSource(structs: GoStruct[], structMap: Map<string, GoStruct>, opts?: {
8
+ knownSchemaIdents?: Set<string>;
9
+ emptyStructStrategy?: EmptyStructStrategy;
10
+ typeAliases?: GoTypeAliasMap;
11
+ sliceTypeAliases?: GoSliceTypeAliasMap;
12
+ warn?: (msg: string) => void;
13
+ }): string;
14
+ //# sourceMappingURL=generator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EAEnB,QAAQ,EACR,mBAAmB,EACnB,cAAc,EACf,MAAM,SAAS,CAAC;AAGjB,2DAA2D;AAC3D,wBAAgB,iBAAiB,IAAI,MAAM,CAE1C;AAiND;;GAEG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,QAAQ,EAAE,EACnB,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,EAChC,IAAI,CAAC,EAAE;IACL,iBAAiB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAChC,mBAAmB,CAAC,EAAE,mBAAmB,CAAC;IAC1C,WAAW,CAAC,EAAE,cAAc,CAAC;IAC7B,gBAAgB,CAAC,EAAE,mBAAmB,CAAC;IACvC,IAAI,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;CAC9B,GACA,MAAM,CAqBR"}
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTypeboxImports = getTypeboxImports;
4
+ exports.buildTypeBoxSource = buildTypeBoxSource;
5
+ const utils_1 = require("./utils");
6
+ /** Default TypeScript import line for TypeBox + Static. */
7
+ function getTypeboxImports() {
8
+ return `import { Type, Static } from '@sinclair/typebox';`;
9
+ }
10
+ /**
11
+ * True when the field is not a Go pointer but the type resolves through aliases to `*T`
12
+ * (JSON may contain null).
13
+ */
14
+ function resolvesToPointerThroughAlias(goType, typeAliases) {
15
+ let normalized = (0, utils_1.stripGoPackagePrefix)(goType);
16
+ if (!typeAliases?.size)
17
+ return false;
18
+ const visited = new Set();
19
+ while (typeAliases.has(normalized) && !visited.has(normalized)) {
20
+ visited.add(normalized);
21
+ const target = typeAliases.get(normalized);
22
+ if (target.startsWith('*'))
23
+ return true;
24
+ normalized = (0, utils_1.stripGoPackagePrefix)(target);
25
+ }
26
+ return false;
27
+ }
28
+ /**
29
+ * Maps a non-array Go base type to a TypeBox expression (primitives, maps, structs, aliases).
30
+ */
31
+ function getBaseTypeBoxType(goType, currentStruct, structMap, knownSchemaIdents, typeAliases, sliceTypeAliases, warn) {
32
+ switch (goType) {
33
+ case 'string':
34
+ return 'Type.String()';
35
+ case 'uuid.UUID':
36
+ return 'Type.String({ format: "uuid" })';
37
+ case 'int':
38
+ case 'int8':
39
+ case 'int16':
40
+ case 'int32':
41
+ case 'int64':
42
+ case 'uint':
43
+ case 'uint8':
44
+ case 'uint16':
45
+ case 'uint32':
46
+ case 'uint64':
47
+ case 'float32':
48
+ case 'float64':
49
+ return 'Type.Number()';
50
+ case 'bool':
51
+ return 'Type.Boolean()';
52
+ case 'interface{}':
53
+ case 'any':
54
+ return 'Type.Any()';
55
+ case 'time.Time':
56
+ return 'Type.String({ format: "date-time" })';
57
+ case 'byte':
58
+ return 'Type.Number()';
59
+ case 'map[string]interface{}':
60
+ case 'map[string]any':
61
+ return 'Type.Record(Type.String(), Type.Any())';
62
+ default: {
63
+ if (goType.startsWith('map[')) {
64
+ return 'Type.Record(Type.String(), Type.Any())';
65
+ }
66
+ let normalized = (0, utils_1.stripGoPackagePrefix)(goType);
67
+ if (typeAliases?.size) {
68
+ const visited = new Set();
69
+ while (typeAliases.has(normalized) && !visited.has(normalized)) {
70
+ visited.add(normalized);
71
+ let target = typeAliases.get(normalized);
72
+ while (target.startsWith('*'))
73
+ target = target.slice(1);
74
+ normalized = (0, utils_1.stripGoPackagePrefix)(target);
75
+ }
76
+ }
77
+ const sliceDef = sliceTypeAliases?.get(normalized);
78
+ if (sliceDef) {
79
+ let inner = getBaseTypeBoxType(sliceDef.elementType, currentStruct, structMap, knownSchemaIdents, typeAliases, sliceTypeAliases, warn);
80
+ for (let i = 0; i < sliceDef.arrayDepth; i++) {
81
+ inner = `Type.Array(${inner})`;
82
+ }
83
+ return inner;
84
+ }
85
+ const exportName = (0, utils_1.toPascalExportName)(normalized);
86
+ if (structMap.has(normalized)) {
87
+ return `${exportName}Schema`;
88
+ }
89
+ if (knownSchemaIdents && knownSchemaIdents.has(`${exportName}Schema`)) {
90
+ return `${exportName}Schema`;
91
+ }
92
+ warn?.(`⚠️ Unknown type ${goType} in struct ${currentStruct}, using Type.Any()`);
93
+ return 'Type.Any()';
94
+ }
95
+ }
96
+ }
97
+ /**
98
+ * Builds the full TypeBox type for a struct field (arrays, pointers, optional, byte slices).
99
+ */
100
+ function mapGoTypeToTypeBox(field, currentStruct, structMap, knownSchemaIdents, typeAliases, sliceTypeAliases, warn) {
101
+ let typeBoxType;
102
+ if (field.type === 'byte' && field.arrayDepth >= 1) {
103
+ typeBoxType = `Type.String({ format: "byte" })`;
104
+ for (let i = 0; i < field.arrayDepth - 1; i++) {
105
+ typeBoxType = `Type.Array(${typeBoxType})`;
106
+ }
107
+ }
108
+ else {
109
+ typeBoxType = getBaseTypeBoxType(field.type, currentStruct, structMap, knownSchemaIdents, typeAliases, sliceTypeAliases, warn);
110
+ for (let i = 0; i < field.arrayDepth; i++) {
111
+ typeBoxType = `Type.Array(${typeBoxType})`;
112
+ }
113
+ }
114
+ const effectivePointer = field.isPointer || resolvesToPointerThroughAlias(field.type, typeAliases);
115
+ if (effectivePointer) {
116
+ typeBoxType = `Type.Union([${typeBoxType}, Type.Null()])`;
117
+ }
118
+ if (field.jsonOmitempty) {
119
+ typeBoxType = `Type.Optional(${typeBoxType})`;
120
+ }
121
+ return typeBoxType;
122
+ }
123
+ /** Emits `export const …Schema` and `export type … = Static<…>` for one struct. */
124
+ function generateSchemaForStruct(struct, structMap, knownSchemaIdents, typeAliases, sliceTypeAliases, emptyStructStrategy = 'object', warn) {
125
+ const exportName = (0, utils_1.toPascalExportName)(struct.name);
126
+ if (struct.fields.length === 0) {
127
+ const schemaExpr = emptyStructStrategy === 'recordUnknown'
128
+ ? 'Type.Record(Type.String(), Type.Unknown())'
129
+ : 'Type.Object({})';
130
+ return (`export const ${exportName}Schema = ${schemaExpr};\n\n` +
131
+ `export type ${exportName} = Static<typeof ${exportName}Schema>;\n`);
132
+ }
133
+ let schemaCode = `export const ${exportName}Schema = Type.Object({\n`;
134
+ for (const field of struct.fields) {
135
+ const fieldName = field.jsonName;
136
+ if (fieldName === '-') {
137
+ continue;
138
+ }
139
+ const typeBoxType = mapGoTypeToTypeBox(field, struct.name, structMap, knownSchemaIdents, typeAliases, sliceTypeAliases, warn);
140
+ const key = /^[A-Za-z_$][\w$]*$/.test(fieldName)
141
+ ? fieldName
142
+ : JSON.stringify(fieldName);
143
+ schemaCode += ` ${key}: ${typeBoxType},\n`;
144
+ }
145
+ schemaCode += `});\n\n`;
146
+ schemaCode += `export type ${exportName} = Static<typeof ${exportName}Schema>;\n`;
147
+ return schemaCode;
148
+ }
149
+ /**
150
+ * Concatenates TypeBox schema and Static type declarations for each struct in order.
151
+ */
152
+ function buildTypeBoxSource(structs, structMap, opts) {
153
+ const knownSchemaIdents = opts?.knownSchemaIdents;
154
+ const emptyStructStrategy = opts?.emptyStructStrategy ?? 'object';
155
+ const typeAliases = opts?.typeAliases;
156
+ const sliceTypeAliases = opts?.sliceTypeAliases;
157
+ const warn = opts?.warn;
158
+ let code = '';
159
+ for (const struct of structs) {
160
+ code += generateSchemaForStruct(struct, structMap, knownSchemaIdents, typeAliases, sliceTypeAliases, emptyStructStrategy, warn);
161
+ code += '\n';
162
+ }
163
+ return code.trimEnd() + '\n';
164
+ }
165
+ //# sourceMappingURL=generator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.js","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":";;AAUA,8CAEC;AAoND,gDA+BC;AAxPD,mCAAmE;AAEnE,2DAA2D;AAC3D,SAAgB,iBAAiB;IAC/B,OAAO,mDAAmD,CAAC;AAC7D,CAAC;AAED;;;GAGG;AACH,SAAS,6BAA6B,CACpC,MAAc,EACd,WAA4B;IAE5B,IAAI,UAAU,GAAG,IAAA,4BAAoB,EAAC,MAAM,CAAC,CAAC;IAC9C,IAAI,CAAC,WAAW,EAAE,IAAI;QAAE,OAAO,KAAK,CAAC;IACrC,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAClC,OAAO,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;QAC/D,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACxB,MAAM,MAAM,GAAG,WAAW,CAAC,GAAG,CAAC,UAAU,CAAE,CAAC;QAC5C,IAAI,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC;YAAE,OAAO,IAAI,CAAC;QACxC,UAAU,GAAG,IAAA,4BAAoB,EAAC,MAAM,CAAC,CAAC;IAC5C,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;GAEG;AACH,SAAS,kBAAkB,CACzB,MAAc,EACd,aAAqB,EACrB,SAAgC,EAChC,iBAA+B,EAC/B,WAA4B,EAC5B,gBAAsC,EACtC,IAA4B;IAE5B,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,QAAQ;YACX,OAAO,eAAe,CAAC;QACzB,KAAK,WAAW;YACd,OAAO,iCAAiC,CAAC;QAC3C,KAAK,KAAK,CAAC;QACX,KAAK,MAAM,CAAC;QACZ,KAAK,OAAO,CAAC;QACb,KAAK,OAAO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I,IAAI,IAAI,CAAC;IACf,CAAC;IACD,OAAO,IAAI,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC;AAC/B,CAAC"}
@@ -0,0 +1,54 @@
1
+ import { ConvertGoToTypeboxOptions, Go2TypeboxConfig, WriteMode } from './types';
2
+ /** Converts Go struct definitions to TypeBox schemas and writes TypeScript output. */
3
+ export declare class Go2Typebox {
4
+ private prettierCommand;
5
+ private logger;
6
+ private defaultLogMode;
7
+ private defaultSuppressWarnings;
8
+ private typeAliases;
9
+ private sliceTypeAliases;
10
+ /** When true (inside `convertMany`), avoid logging “written” for every file in silent mode. */
11
+ private convertManyActive;
12
+ /**
13
+ * @param config - Optional Prettier command, logger, default log mode, and warning suppression.
14
+ */
15
+ constructor(config?: Go2TypeboxConfig);
16
+ /** Resolves effective log mode from per-call options or constructor default. */
17
+ private effectiveLogMode;
18
+ /** Resolves whether warnings are suppressed for this conversion call. */
19
+ private effectiveSuppressWarnings;
20
+ /**
21
+ * Runs Prettier on the output file. In silent mode, keeps `--log-level silent` (or adds it);
22
+ * in verbose mode, strips silent so Prettier can print lines like `…ms (unchanged)`.
23
+ */
24
+ private runPrettierOnOutput;
25
+ /**
26
+ * Parses one Go file, merges type aliases into instance state, generates TypeBox for structs,
27
+ * writes to `outputFile`, and optionally formats with Prettier.
28
+ *
29
+ * @returns `true` if at least one struct was written, `false` if skipped (no structs).
30
+ */
31
+ convertFile(inputFile: string, outputFile: string, opts?: ConvertGoToTypeboxOptions): Promise<boolean>;
32
+ /**
33
+ * Converts multiple Go sources into one TypeBox output file.
34
+ * First file uses `firstMode` (default overwrite); subsequent files use `nextMode` (default append).
35
+ * Type and slice aliases accumulate across files in the same instance.
36
+ */
37
+ convertMany(inputFiles: string[], outputFile: string, opts?: Omit<ConvertGoToTypeboxOptions, 'mode'> & {
38
+ firstMode?: WriteMode;
39
+ nextMode?: WriteMode;
40
+ }): Promise<void>;
41
+ convertMany(input: {
42
+ files?: string[];
43
+ dirs?: string[];
44
+ tailFiles?: string[];
45
+ }, outputFile: string, opts?: Omit<ConvertGoToTypeboxOptions, 'mode'> & {
46
+ firstMode?: WriteMode;
47
+ nextMode?: WriteMode;
48
+ }): Promise<void>;
49
+ /**
50
+ * Like `convertFile` but resolves `inputFile` and `outputFile` with `path.resolve` (CLI helper).
51
+ */
52
+ convertFileResolved(inputFile: string, outputFile: string, opts?: ConvertGoToTypeboxOptions): Promise<void>;
53
+ }
54
+ //# sourceMappingURL=go2typebox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"go2typebox.d.ts","sourceRoot":"","sources":["../src/go2typebox.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,yBAAyB,EAEzB,gBAAgB,EAKhB,SAAS,EACV,MAAM,SAAS,CAAC;AAQjB,sFAAsF;AACtF,qBAAa,UAAU;IACrB,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,MAAM,CAAmB;IACjC,OAAO,CAAC,cAAc,CAAoB;IAC1C,OAAO,CAAC,uBAAuB,CAAU;IACzC,OAAO,CAAC,WAAW,CAA6B;IAChD,OAAO,CAAC,gBAAgB,CAAkC;IAC1D,+FAA+F;IAC/F,OAAO,CAAC,iBAAiB,CAAS;IAElC;;OAEG;gBACS,MAAM,CAAC,EAAE,gBAAgB;IAQrC,gFAAgF;IAChF,OAAO,CAAC,gBAAgB;IAMxB,yEAAyE;IACzE,OAAO,CAAC,yBAAyB;IAIjC;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IAgB3B;;;;;OAKG;IACG,WAAW,CACf,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,IAAI,CAAC,EAAE,yBAAyB,GAC/B,OAAO,CAAC,OAAO,CAAC;IA6FnB;;;;OAIG;IACG,WAAW,CACf,UAAU,EAAE,MAAM,EAAE,EACpB,UAAU,EAAE,MAAM,EAClB,IAAI,CAAC,EAAE,IAAI,CAAC,yBAAyB,EAAE,MAAM,CAAC,GAAG;QAC/C,SAAS,CAAC,EAAE,SAAS,CAAC;QACtB,QAAQ,CAAC,EAAE,SAAS,CAAC;KACtB,GACA,OAAO,CAAC,IAAI,CAAC;IACV,WAAW,CACf,KAAK,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,EAClE,UAAU,EAAE,MAAM,EAClB,IAAI,CAAC,EAAE,IAAI,CAAC,yBAAyB,EAAE,MAAM,CAAC,GAAG;QAC/C,SAAS,CAAC,EAAE,SAAS,CAAC;QACtB,QAAQ,CAAC,EAAE,SAAS,CAAC;KACtB,GACA,OAAO,CAAC,IAAI,CAAC;IAqDhB;;OAEG;IACG,mBAAmB,CACvB,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,IAAI,CAAC,EAAE,yBAAyB,GAC/B,OAAO,CAAC,IAAI,CAAC;CAKjB"}
@@ -0,0 +1,219 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.Go2Typebox = void 0;
37
+ const child_process_1 = require("child_process");
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ const parser_1 = require("./parser");
41
+ const sorter_1 = require("./sorter");
42
+ const writer_1 = require("./writer");
43
+ const defaultLogger = {
44
+ log: (m) => console.log(m),
45
+ warn: (m) => console.warn(m),
46
+ error: (m, e) => console.error(m, e),
47
+ };
48
+ /** Converts Go struct definitions to TypeBox schemas and writes TypeScript output. */
49
+ class Go2Typebox {
50
+ /**
51
+ * @param config - Optional Prettier command, logger, default log mode, and warning suppression.
52
+ */
53
+ constructor(config) {
54
+ this.typeAliases = new Map();
55
+ this.sliceTypeAliases = new Map();
56
+ /** When true (inside `convertMany`), avoid logging “written” for every file in silent mode. */
57
+ this.convertManyActive = false;
58
+ this.prettierCommand =
59
+ config?.prettierCommand ?? 'npx prettier --write --log-level silent';
60
+ this.logger = config?.logger ?? defaultLogger;
61
+ this.defaultLogMode = config?.logMode ?? 'silent';
62
+ this.defaultSuppressWarnings = config?.suppressWarnings ?? false;
63
+ }
64
+ /** Resolves effective log mode from per-call options or constructor default. */
65
+ effectiveLogMode(opts) {
66
+ return opts?.logMode ?? this.defaultLogMode;
67
+ }
68
+ /** Resolves whether warnings are suppressed for this conversion call. */
69
+ effectiveSuppressWarnings(opts) {
70
+ return opts?.suppressWarnings ?? this.defaultSuppressWarnings;
71
+ }
72
+ /**
73
+ * Runs Prettier on the output file. In silent mode, keeps `--log-level silent` (or adds it);
74
+ * in verbose mode, strips silent so Prettier can print lines like `…ms (unchanged)`.
75
+ */
76
+ runPrettierOnOutput(outputFile, logMode) {
77
+ let cmd = this.prettierCommand.trim();
78
+ const quietPrettier = logMode === 'silent';
79
+ if (!quietPrettier) {
80
+ cmd = cmd.replace(/\s--log-level\s+silent\b/g, '').trim();
81
+ }
82
+ else if (!/\blog-level\b/.test(cmd)) {
83
+ cmd = `${cmd} --log-level silent`;
84
+ }
85
+ (0, child_process_1.execSync)(`${cmd} "${outputFile}"`, {
86
+ stdio: quietPrettier ? ['ignore', 'ignore', 'inherit'] : 'inherit',
87
+ });
88
+ }
89
+ /**
90
+ * Parses one Go file, merges type aliases into instance state, generates TypeBox for structs,
91
+ * writes to `outputFile`, and optionally formats with Prettier.
92
+ *
93
+ * @returns `true` if at least one struct was written, `false` if skipped (no structs).
94
+ */
95
+ async convertFile(inputFile, outputFile, opts) {
96
+ const logMode = this.effectiveLogMode(opts);
97
+ const verbose = logMode === 'verbose';
98
+ const suppressWarnings = this.effectiveSuppressWarnings(opts);
99
+ try {
100
+ const goContent = await fs.promises.readFile(inputFile, 'utf-8');
101
+ if (verbose) {
102
+ this.logger.log(`📖 Reading Go file: ${inputFile}`);
103
+ }
104
+ const fileAliases = (0, parser_1.parseGoTypeAliases)(goContent);
105
+ if (fileAliases.size > 0) {
106
+ for (const [k, v] of fileAliases.entries())
107
+ this.typeAliases.set(k, v);
108
+ }
109
+ const fileSliceAliases = (0, parser_1.parseGoSliceTypeAliases)(goContent);
110
+ if (fileSliceAliases.size > 0) {
111
+ for (const [k, v] of fileSliceAliases.entries()) {
112
+ this.sliceTypeAliases.set(k, v);
113
+ }
114
+ }
115
+ const structs = (0, parser_1.parseGoStructs)(goContent);
116
+ if (verbose) {
117
+ this.logger.log(`🔍 Found struct(s): ${structs.length} — ${structs
118
+ .map((s) => s.name)
119
+ .join(', ')}`);
120
+ }
121
+ if (structs.length === 0) {
122
+ if (fileAliases.size > 0) {
123
+ if (verbose) {
124
+ this.logger.log(`📎 Skipping write (no struct): ${inputFile} — loaded aliases: ${fileAliases.size}`);
125
+ }
126
+ }
127
+ else if (!suppressWarnings) {
128
+ this.logger.warn('⚠️ Go file has no struct with fields');
129
+ }
130
+ return false;
131
+ }
132
+ const structMap = (0, sorter_1.buildStructMap)(structs, {
133
+ sliceTypeAliases: fileSliceAliases,
134
+ typeAliases: this.typeAliases,
135
+ });
136
+ const sortedStructs = (0, sorter_1.topologicalSort)(structMap);
137
+ if (verbose) {
138
+ this.logger.log(`📊 Dependency order: ${sortedStructs
139
+ .map((s) => s.name)
140
+ .join(' -> ')}`);
141
+ }
142
+ const mode = opts?.mode ?? 'overwrite';
143
+ const emptyStructStrategy = opts?.emptyStructStrategy ?? 'object';
144
+ (0, writer_1.writeOutputFile)({
145
+ outputFile,
146
+ sortedStructs,
147
+ structMap,
148
+ typeAliases: this.typeAliases,
149
+ sliceTypeAliases: this.sliceTypeAliases,
150
+ mode,
151
+ emptyStructStrategy,
152
+ warn: suppressWarnings ? () => { } : (m) => this.logger.warn(m),
153
+ });
154
+ const shouldLogWriteNow = verbose || (logMode === 'silent' && !this.convertManyActive);
155
+ if (shouldLogWriteNow) {
156
+ this.logger.log(`✅ Wrote TypeBox to file: ${outputFile}`);
157
+ }
158
+ const formatWithPrettier = opts?.formatWithPrettier ?? true;
159
+ if (formatWithPrettier) {
160
+ this.runPrettierOnOutput(outputFile, logMode);
161
+ if (verbose) {
162
+ this.logger.log('✅ File formatted successfully with Prettier');
163
+ }
164
+ }
165
+ return true;
166
+ }
167
+ catch (error) {
168
+ this.logger.error('❌ Conversion error:', error);
169
+ throw error;
170
+ }
171
+ }
172
+ async convertMany(input, outputFile, opts) {
173
+ const firstMode = opts?.firstMode ?? 'overwrite';
174
+ const nextMode = opts?.nextMode ?? 'append';
175
+ /** Returns sorted `.go` file paths under `dir` (posix-joined). */
176
+ const readDirGoFiles = async (dir) => (await fs.promises.readdir(dir))
177
+ .filter((f) => f.endsWith('.go'))
178
+ .sort((a, b) => a.localeCompare(b))
179
+ .map((f) => path.posix.join(dir, f));
180
+ const inputFiles = Array.isArray(input)
181
+ ? input
182
+ : [
183
+ ...(input.files ?? []),
184
+ ...(input.dirs?.length
185
+ ? (await Promise.all(input.dirs.map((d) => readDirGoFiles(d)))).flat()
186
+ : []),
187
+ ...(input.tailFiles ?? []),
188
+ ];
189
+ const logMode = this.effectiveLogMode(opts);
190
+ this.convertManyActive = true;
191
+ let wroteAny = false;
192
+ try {
193
+ for (let i = 0; i < inputFiles.length; i++) {
194
+ const ok = await this.convertFile(inputFiles[i], outputFile, {
195
+ ...opts,
196
+ mode: i === 0 ? firstMode : nextMode,
197
+ });
198
+ if (ok)
199
+ wroteAny = true;
200
+ }
201
+ if (logMode === 'silent' && wroteAny) {
202
+ this.logger.log(`✅ Wrote TypeBox to file: ${outputFile}`);
203
+ }
204
+ }
205
+ finally {
206
+ this.convertManyActive = false;
207
+ }
208
+ }
209
+ /**
210
+ * Like `convertFile` but resolves `inputFile` and `outputFile` with `path.resolve` (CLI helper).
211
+ */
212
+ async convertFileResolved(inputFile, outputFile, opts) {
213
+ const resolvedInput = path.resolve(inputFile);
214
+ const resolvedOutput = path.resolve(outputFile);
215
+ await this.convertFile(resolvedInput, resolvedOutput, opts);
216
+ }
217
+ }
218
+ exports.Go2Typebox = Go2Typebox;
219
+ //# sourceMappingURL=go2typebox.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"go2typebox.js","sourceRoot":"","sources":["../src/go2typebox.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAAyC;AACzC,uCAAyB;AACzB,2CAA6B;AAC7B,qCAIkB;AAClB,qCAA2D;AAC3D,qCAA2C;AAY3C,MAAM,aAAa,GAAqB;IACtC,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1B,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5B,KAAK,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,GAAG,KAAK,CAAC;QACrB,IAAI,CAAC;YACH,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBAC3C,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC,CAAE,EAAE,UAAU,EAAE;oBAC5D,GAAG,IAAI;oBACP,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ;iBACrC,CAAC,CAAC;gBACH,IAAI,EAAE;oBAAE,QAAQ,GAAG,IAAI,CAAC;YAC1B,CAAC;YAED,IAAI,OAAO,KAAK,QAAQ,IAAI,QAAQ,EAAE,CAAC;gBACrC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,UAAU,EAAE,CAAC,CAAC;YAC5D,CAAC;QACH,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;QACjC,CAAC;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,mBAAmB,CACvB,SAAiB,EACjB,UAAkB,EAClB,IAAgC;QAEhC,MAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAC9C,MAAM,cAAc,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;QAChD,MAAM,IAAI,CAAC,WAAW,CAAC,aAAa,EAAE,cAAc,EAAE,IAAI,CAAC,CAAC;IAC9D,CAAC;CACF;AAjPD,gCAiPC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Public API for go2typebox: Go struct → TypeBox codegen, optional standardization, and RPC prune helpers.
3
+ */
4
+ export { Go2Typebox } from './go2typebox';
5
+ export { collapseRedundantPrefixedSchemaAliases, standardizeTypeboxTypes, unwrapInlineSchemaRefs, } from './standardizeTypeboxTypes';
6
+ export type { StandardizeJsonRpcOptions, StandardizeTypeboxTypesOptions, } from './standardizeTypeboxTypes';
7
+ export { pruneTypeboxFileByRequestResponseRoots, } from './pruneTypeboxFile';
8
+ export type { PruneTypeboxFileOptions } from './pruneTypeboxFile';
9
+ export type { ConvertGoToTypeboxOptions, EmptyStructStrategy, Go2TypeboxConfig, Go2TypeboxLogger, Go2TypeboxLogMode, GoField, GoStruct, WriteMode, WriteMode as Go2TypeboxWriteMode, } from './types';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EACL,sCAAsC,EACtC,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,2BAA2B,CAAC;AACnC,YAAY,EACV,yBAAyB,EACzB,8BAA8B,GAC/B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,sCAAsC,GACvC,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAClE,YAAY,EACV,yBAAyB,EACzB,mBAAmB,EACnB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,OAAO,EACP,QAAQ,EACR,SAAS,EACT,SAAS,IAAI,mBAAmB,GACjC,MAAM,SAAS,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ /**
3
+ * Public API for go2typebox: Go struct → TypeBox codegen, optional standardization, and RPC prune helpers.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.pruneTypeboxFileByRequestResponseRoots = exports.unwrapInlineSchemaRefs = exports.standardizeTypeboxTypes = exports.collapseRedundantPrefixedSchemaAliases = exports.Go2Typebox = void 0;
7
+ var go2typebox_1 = require("./go2typebox");
8
+ Object.defineProperty(exports, "Go2Typebox", { enumerable: true, get: function () { return go2typebox_1.Go2Typebox; } });
9
+ var standardizeTypeboxTypes_1 = require("./standardizeTypeboxTypes");
10
+ Object.defineProperty(exports, "collapseRedundantPrefixedSchemaAliases", { enumerable: true, get: function () { return standardizeTypeboxTypes_1.collapseRedundantPrefixedSchemaAliases; } });
11
+ Object.defineProperty(exports, "standardizeTypeboxTypes", { enumerable: true, get: function () { return standardizeTypeboxTypes_1.standardizeTypeboxTypes; } });
12
+ Object.defineProperty(exports, "unwrapInlineSchemaRefs", { enumerable: true, get: function () { return standardizeTypeboxTypes_1.unwrapInlineSchemaRefs; } });
13
+ var pruneTypeboxFile_1 = require("./pruneTypeboxFile");
14
+ Object.defineProperty(exports, "pruneTypeboxFileByRequestResponseRoots", { enumerable: true, get: function () { return pruneTypeboxFile_1.pruneTypeboxFileByRequestResponseRoots; } });
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AAEH,2CAA0C;AAAjC,wGAAA,UAAU,OAAA;AACnB,qEAImC;AAHjC,iJAAA,sCAAsC,OAAA;AACtC,kIAAA,uBAAuB,OAAA;AACvB,iIAAA,sBAAsB,OAAA;AAMxB,uDAE4B;AAD1B,0IAAA,sCAAsC,OAAA"}
@@ -0,0 +1,10 @@
1
+ import { GoStruct, GoSliceTypeAliasMap } from './types';
2
+ /** Extracts all `type Name struct { … }` blocks from Go source (comments stripped). */
3
+ export declare function parseGoStructs(content: string): GoStruct[];
4
+ /** Parses `type Alias = T` (and `type Alias = *T`) aliases into alias → target type string. */
5
+ export declare function parseGoTypeAliases(content: string): Map<string, string>;
6
+ /**
7
+ * Parses slice type aliases: `type IDs []int`, `type Rows [][]string`, `type List []pkg.Item`.
8
+ */
9
+ export declare function parseGoSliceTypeAliases(content: string): GoSliceTypeAliasMap;
10
+ //# sourceMappingURL=parser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../src/parser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,QAAQ,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AA2CjE,uFAAuF;AACvF,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ,EAAE,CAoB1D;AAED,+FAA+F;AAC/F,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAevE;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,mBAAmB,CAkB5E"}