@mt-tl/tl 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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -0
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +47 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/codegen/gen-types.d.ts +10 -0
  8. package/dist/codegen/gen-types.d.ts.map +1 -0
  9. package/dist/codegen/gen-types.js +190 -0
  10. package/dist/codegen/gen-types.js.map +1 -0
  11. package/dist/index.d.ts +13 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +21 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/logger.d.ts +63 -0
  16. package/dist/logger.d.ts.map +1 -0
  17. package/dist/logger.js +147 -0
  18. package/dist/logger.js.map +1 -0
  19. package/dist/migrate.d.ts +37 -0
  20. package/dist/migrate.d.ts.map +1 -0
  21. package/dist/migrate.js +84 -0
  22. package/dist/migrate.js.map +1 -0
  23. package/dist/rpc.d.ts +74 -0
  24. package/dist/rpc.d.ts.map +1 -0
  25. package/dist/rpc.js +2 -0
  26. package/dist/rpc.js.map +1 -0
  27. package/dist/tl/crc32.d.ts +2 -0
  28. package/dist/tl/crc32.d.ts.map +1 -0
  29. package/dist/tl/crc32.js +42 -0
  30. package/dist/tl/crc32.js.map +1 -0
  31. package/dist/tl/ir.d.ts +68 -0
  32. package/dist/tl/ir.d.ts.map +1 -0
  33. package/dist/tl/ir.js +63 -0
  34. package/dist/tl/ir.js.map +1 -0
  35. package/dist/tl/parser.d.ts +22 -0
  36. package/dist/tl/parser.d.ts.map +1 -0
  37. package/dist/tl/parser.js +122 -0
  38. package/dist/tl/parser.js.map +1 -0
  39. package/dist/tl/value.d.ts +26 -0
  40. package/dist/tl/value.d.ts.map +1 -0
  41. package/dist/tl/value.js +44 -0
  42. package/dist/tl/value.js.map +1 -0
  43. package/dist/tools/freeze-layer.d.ts +26 -0
  44. package/dist/tools/freeze-layer.d.ts.map +1 -0
  45. package/dist/tools/freeze-layer.js +86 -0
  46. package/dist/tools/freeze-layer.js.map +1 -0
  47. package/dist/wire.d.ts +12 -0
  48. package/dist/wire.d.ts.map +1 -0
  49. package/dist/wire.js +50 -0
  50. package/dist/wire.js.map +1 -0
  51. package/package.json +76 -0
  52. package/schema/scheme_0_protocol.tl +150 -0
  53. package/src/cli.ts +48 -0
  54. package/src/codegen/gen-types.ts +203 -0
  55. package/src/index.ts +22 -0
  56. package/src/logger.ts +210 -0
  57. package/src/migrate.ts +101 -0
  58. package/src/rpc.ts +70 -0
  59. package/src/tl/crc32.ts +44 -0
  60. package/src/tl/ir.ts +105 -0
  61. package/src/tl/parser.ts +144 -0
  62. package/src/tl/value.ts +60 -0
  63. package/src/tools/freeze-layer.ts +108 -0
  64. package/src/wire.ts +54 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joe Beretta
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,40 @@
1
+ # @mt-tl/tl
2
+
3
+ TL (Type Language) tooling for MTProto, used alongside `@mt-tl/server`: a `.tl`
4
+ parser/IR, a generic wire codec, value↔JSON helpers, schema-version migrations, a
5
+ **TypeScript type generator**, layer freezing, and the bundled MTProto **protocol**
6
+ schema.
7
+
8
+ ```bash
9
+ npm install -D @mt-tl/tl
10
+ ```
11
+
12
+ Most apps use it for two things:
13
+
14
+ ## 1. Generate types from your `.tl`
15
+
16
+ ```bash
17
+ npx mtproto-tl gen-types ./schema ./src/generated/schema.ts
18
+ ```
19
+
20
+ Emits one interface per constructor, a union per type, and the `RpcMethods` map
21
+ you pass to `createServer<RpcMethods>()`.
22
+
23
+ ## 2. Freeze a layer when you ship one
24
+
25
+ ```bash
26
+ npx mtproto-tl freeze ./schema ./schema/layers 205
27
+ ```
28
+
29
+ Writes `scheme_205.json` (loaded for layered encoding) + a `.tl` mirror.
30
+
31
+ ## Library API
32
+
33
+ Also exports the building blocks the server uses: `parseSchemaDir`,
34
+ `generateSchemaTs` / `writeSchemaTs`, `freezeLayer`, `MigrationRegistry`,
35
+ `toJson` / `fromJson`, the RPC envelope types, and `protocolSchemaDir` (absolute
36
+ path to the bundled protocol schema).
37
+
38
+ ## License
39
+
40
+ MIT
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js ADDED
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env node
2
+ import { writeSchemaTs } from './codegen/gen-types.js';
3
+ import { freezeLayer } from './tools/freeze-layer.js';
4
+ const USAGE = `mtproto-tl — TL tooling
5
+
6
+ Usage:
7
+ mtproto-tl gen-types <schemaDir> <outFile>
8
+ Generate TypeScript types (RpcMethods + interfaces) from a .tl schema.
9
+
10
+ mtproto-tl freeze <schemaDir> <outDir> <layer>
11
+ Freeze the current schema into a per-layer snapshot (scheme_<layer>.json + .tl).
12
+ `;
13
+ function fail(msg) {
14
+ console.error(msg + '\n\n' + USAGE);
15
+ process.exit(1);
16
+ }
17
+ const [cmd, ...args] = process.argv.slice(2);
18
+ switch (cmd) {
19
+ case 'gen-types': {
20
+ const [schemaDir, outFile] = args;
21
+ if (!schemaDir || !outFile)
22
+ fail('gen-types requires <schemaDir> <outFile>');
23
+ writeSchemaTs(schemaDir, outFile);
24
+ break;
25
+ }
26
+ case 'freeze': {
27
+ const [schemaDir, outDir, layerStr] = args;
28
+ if (!schemaDir || !outDir || !layerStr)
29
+ fail('freeze requires <schemaDir> <outDir> <layer>');
30
+ const layer = Number(layerStr);
31
+ if (!Number.isInteger(layer))
32
+ fail(`freeze: <layer> must be an integer, got "${layerStr}"`);
33
+ const res = freezeLayer(schemaDir, outDir, layer);
34
+ console.log(`Froze layer ${layer}: ${res.constructors} constructors, ${res.methods} methods → ${res.out}`);
35
+ if (res.crcWarnings)
36
+ console.warn(` (${res.crcWarnings} CRC warnings)`);
37
+ break;
38
+ }
39
+ case undefined:
40
+ case '-h':
41
+ case '--help':
42
+ console.log(USAGE);
43
+ break;
44
+ default:
45
+ fail(`unknown command: ${cmd}`);
46
+ }
47
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAA;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAErD,MAAM,KAAK,GAAG;;;;;;;;CAQb,CAAA;AAED,SAAS,IAAI,CAAC,GAAW;IACrB,OAAO,CAAC,KAAK,CAAC,GAAG,GAAG,MAAM,GAAG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AK,QAAQ;QACT,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QAClB,MAAK;IACT;QACI,IAAI,CAAC,oBAAoB,GAAG,EAAE,CAAC,CAAA;AACvC,CAAC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Generates TypeScript types from the `.tl` schema in `dir`: one interface per
3
+ * constructor, a union per type, and the `RpcMethods` map (method → params/result)
4
+ * you pass to `createServer<RpcMethods>()`. Returns the source as a string; see
5
+ * {@link writeSchemaTs} to write it to a file. Run via your app's `gen:types` script.
6
+ */
7
+ export declare function generateSchemaTs(dir?: string): string;
8
+ /** Generates types for the schema in `schemaDir` and writes them to `outPath`. */
9
+ export declare function writeSchemaTs(schemaDir: string, outPath: string): void;
10
+ //# sourceMappingURL=gen-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gen-types.d.ts","sourceRoot":"","sources":["../../src/codegen/gen-types.ts"],"names":[],"mappings":"AA8EA;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,GAAE,MAAyB,GAAG,MAAM,CA4FvE;AASD,kFAAkF;AAClF,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAItE"}
@@ -0,0 +1,190 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { parseSchemaDir } from '../tl/parser.js';
5
+ import { protocolSchemaDir as bundledSchemaDir } from '../index.js';
6
+ /**
7
+ * Generates `generated/schema.ts` — TypeScript types for the **newest** layer:
8
+ * one interface per constructor, a union alias per TL type, and an `RpcMethods`
9
+ * map (method name → { params; result }) for typed worker handlers.
10
+ *
11
+ * Types only (no runtime). Field shapes are the post-`fromJson` values workers
12
+ * receive: long→bigint, bytes/int128/int256→Buffer, Vector<T>→T[], flags.N?T→
13
+ * optional. Run `yarn gen:types` after editing the schema.
14
+ *
15
+ * yarn workspace @mt-tl/tl run gen:types
16
+ */
17
+ const SPECIAL_TYPES = new Set(['Object', 'X', 'Bool', 'Vector t', 'true', '#']);
18
+ function tsName(name) {
19
+ return name
20
+ .split('.')
21
+ .map(s => (s ? s.charAt(0).toUpperCase() + s.slice(1) : s))
22
+ .join('');
23
+ }
24
+ function mapType(t, known) {
25
+ switch (t.kind) {
26
+ case 'int':
27
+ case 'double':
28
+ case 'flags':
29
+ return 'number';
30
+ case 'long':
31
+ return 'bigint';
32
+ case 'bytes':
33
+ case 'int128':
34
+ case 'int256':
35
+ return 'Buffer';
36
+ case 'string':
37
+ return 'string';
38
+ case 'bool':
39
+ return 'boolean';
40
+ case 'true':
41
+ return 'true';
42
+ case 'vector':
43
+ return `${wrapUnion(mapType(t.inner, known))}[]`;
44
+ case 'object':
45
+ return 'unknown';
46
+ case 'flag':
47
+ return mapType(t.inner, known);
48
+ case 'boxed':
49
+ case 'bare': {
50
+ const n = tsName(t.name);
51
+ return known.has(n) ? n : 'unknown';
52
+ }
53
+ }
54
+ }
55
+ function wrapUnion(t) {
56
+ return t.includes('|') ? `(${t})` : t;
57
+ }
58
+ function fieldLines(def, known) {
59
+ const out = [];
60
+ for (const p of def.params) {
61
+ if (p.type.kind === 'flags')
62
+ continue; // internal bitmask
63
+ const prop = /^[A-Za-z_$][\w$]*$/.test(p.name) ? p.name : JSON.stringify(p.name);
64
+ if (p.type.kind === 'flag') {
65
+ out.push(` ${prop}?: ${mapType(p.type.inner, known)}`);
66
+ }
67
+ else {
68
+ out.push(` ${prop}: ${mapType(p.type, known)}`);
69
+ }
70
+ }
71
+ return out;
72
+ }
73
+ /**
74
+ * Generates TypeScript types from the `.tl` schema in `dir`: one interface per
75
+ * constructor, a union per type, and the `RpcMethods` map (method → params/result)
76
+ * you pass to `createServer<RpcMethods>()`. Returns the source as a string; see
77
+ * {@link writeSchemaTs} to write it to a file. Run via your app's `gen:types` script.
78
+ */
79
+ export function generateSchemaTs(dir = bundledSchemaDir) {
80
+ const { defs } = parseSchemaDir(dir);
81
+ const ctors = defs.filter(d => d.kind === 'constructor');
82
+ const methods = defs.filter(d => d.kind === 'method');
83
+ // Type groups (union of constructors), excluding special types.
84
+ const typeGroups = new Map();
85
+ for (const d of ctors) {
86
+ if (SPECIAL_TYPES.has(d.type))
87
+ continue;
88
+ const g = typeGroups.get(d.type) ?? [];
89
+ g.push(d);
90
+ typeGroups.set(d.type, g);
91
+ }
92
+ // A TL type is a UNION of its constructors, emitted under the bare type name.
93
+ // The one exception: a type with a single constructor whose name equals the
94
+ // type name (e.g. `error` = Error) — there the lone interface IS the type, so
95
+ // no union alias is needed.
96
+ const unions = new Map();
97
+ for (const [type, group] of typeGroups) {
98
+ const name = tsName(type);
99
+ const soleSelfNamed = group.length === 1 && tsName(group[0].name) === name;
100
+ if (soleSelfNamed)
101
+ continue;
102
+ unions.set(name, group);
103
+ }
104
+ const unionNames = new Set(unions.keys());
105
+ // A constructor's interface name. When it would take a name a union already
106
+ // owns (the type's "primary" constructor — e.g. `user` in type `User`), suffix
107
+ // it with `_` so the union keeps the bare name: `User = User_ | UserEmpty | …`.
108
+ const ctorIface = (d) => {
109
+ const base = tsName(d.name);
110
+ return unionNames.has(base) ? `${base}_` : base;
111
+ };
112
+ // Interface def per constructor name (dedup; first wins).
113
+ const ctorByTs = new Map();
114
+ for (const d of ctors) {
115
+ const name = ctorIface(d);
116
+ if (!ctorByTs.has(name))
117
+ ctorByTs.set(name, d);
118
+ }
119
+ const known = new Set([...ctorByTs.keys(), ...unionNames]);
120
+ const lines = [
121
+ '// AUTO-GENERATED by `yarn gen:types`. Do not edit by hand.',
122
+ '// Types for the newest schema layer (post-fromJson shapes).',
123
+ '/* eslint-disable */',
124
+ '',
125
+ ];
126
+ // Constructor interfaces (sorted).
127
+ for (const name of [...ctorByTs.keys()].sort()) {
128
+ const def = ctorByTs.get(name);
129
+ const fields = fieldLines(def, known);
130
+ lines.push(`export interface ${name} {`);
131
+ lines.push(` _: ${JSON.stringify(def.name)}`);
132
+ lines.push(...fields);
133
+ lines.push('}', '');
134
+ }
135
+ // Type unions (sorted).
136
+ for (const name of [...unions.keys()].sort()) {
137
+ const members = [...new Set(unions.get(name).map(d => ctorIface(d)))];
138
+ lines.push(`export type ${name} = ${members.join(' | ')}`, '');
139
+ }
140
+ // RpcMethods map (sorted by method name; dedup by name — first wins).
141
+ lines.push('export interface RpcMethods {');
142
+ const seenMethods = new Set();
143
+ for (const m of [...methods].sort((a, b) => a.name.localeCompare(b.name))) {
144
+ if (seenMethods.has(m.name))
145
+ continue;
146
+ seenMethods.add(m.name);
147
+ const paramsName = `${tsName(m.name)}Params`;
148
+ const result = resultType(m.type, known);
149
+ lines.push(` ${JSON.stringify(m.name)}: { params: ${paramsName}; result: ${result} }`);
150
+ }
151
+ lines.push('}', '');
152
+ // Method params interfaces (sorted).
153
+ const seenParams = new Set();
154
+ for (const m of [...methods].sort((a, b) => a.name.localeCompare(b.name))) {
155
+ const paramsName = `${tsName(m.name)}Params`;
156
+ if (seenParams.has(paramsName))
157
+ continue;
158
+ seenParams.add(paramsName);
159
+ lines.push(`export interface ${paramsName} {`);
160
+ lines.push(...fieldLines(m, known));
161
+ lines.push('}', '');
162
+ }
163
+ return lines.join('\n');
164
+ }
165
+ function resultType(type, known) {
166
+ if (type === 'Bool')
167
+ return 'boolean';
168
+ if (type === 'Object' || type === 'X')
169
+ return 'unknown';
170
+ const n = tsName(type);
171
+ return known.has(n) ? n : 'unknown';
172
+ }
173
+ /** Generates types for the schema in `schemaDir` and writes them to `outPath`. */
174
+ export function writeSchemaTs(schemaDir, outPath) {
175
+ mkdirSync(dirname(outPath), { recursive: true });
176
+ writeFileSync(outPath, generateSchemaTs(schemaDir));
177
+ console.log(`Generated -> ${outPath}`);
178
+ }
179
+ // CLI: `tsx gen-types.ts <schemaDir> <outPath>` (apps wrap this in their own
180
+ // `gen:types` script pointing at their schema). No bundled default — the
181
+ // framework no longer ships business types.
182
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
183
+ const [schemaDir, outPath] = process.argv.slice(2);
184
+ if (!schemaDir || !outPath) {
185
+ console.error('usage: gen-types <schemaDir> <outPath>');
186
+ process.exit(1);
187
+ }
188
+ writeSchemaTs(schemaDir, outPath);
189
+ }
190
+ //# sourceMappingURL=gen-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gen-types.js","sourceRoot":"","sources":["../../src/codegen/gen-types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAClD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAChD,OAAO,EAAE,iBAAiB,IAAI,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAGnE;;;;;;;;;;GAUG;AAEH,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC,CAAA;AAE/E,SAAS,MAAM,CAAC,IAAY;IACxB,OAAO,IAAI;SACN,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SAC1D,IAAI,CAAC,EAAE,CAAC,CAAA;AACjB,CAAC;AAED,SAAS,OAAO,CAAC,CAAS,EAAE,KAAkB;IAC1C,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;QACb,KAAK,KAAK,CAAC;QACX,KAAK,QAAQ,CAAC;QACd,KAAK,OAAO;YACR,OAAO,QAAQ,CAAA;QACnB,KAAK,MAAM;YACP,OA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,CAAC,CAAC,CAAA;IACnB,CAAC;IACD,aAAa,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA;AACrC,CAAC"}
@@ -0,0 +1,13 @@
1
+ export * from './tl/ir.js';
2
+ export * from './tl/value.js';
3
+ export * from './tl/parser.js';
4
+ export * from './tl/crc32.js';
5
+ export * from './rpc.js';
6
+ export * from './wire.js';
7
+ export * from './migrate.js';
8
+ export * from './logger.js';
9
+ export { generateSchemaTs, writeSchemaTs } from './codegen/gen-types.js';
10
+ export { freezeLayer, type FreezeResult } from './tools/freeze-layer.js';
11
+ /** Absolute path to the bundled MTProto protocol `.tl` schema directory. */
12
+ export declare const protocolSchemaDir: string;
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,cAAc,YAAY,CAAA;AAC1B,cAAc,eAAe,CAAA;AAC7B,cAAc,gBAAgB,CAAA;AAC9B,cAAc,eAAe,CAAA;AAC7B,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA;AACzB,cAAc,cAAc,CAAA;AAG5B,cAAc,aAAa,CAAA;AAG3B,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAA;AACxE,OAAO,EAAE,WAAW,EAAE,KAAK,YAAY,EAAE,MAAM,yBAAyB,CAAA;AAKxE,4EAA4E;AAC5E,eAAO,MAAM,iBAAiB,QAAuD,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,21 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ export * from './tl/ir.js';
3
+ export * from './tl/value.js';
4
+ export * from './tl/parser.js';
5
+ export * from './tl/crc32.js';
6
+ export * from './rpc.js';
7
+ export * from './wire.js';
8
+ export * from './migrate.js';
9
+ // Shared structured logger — the server engine, the handler layer, and your app
10
+ // import it for one consistent log style (see docs/guide/observability.md).
11
+ export * from './logger.js';
12
+ // Codegen + layer tooling — consumers generate TS types and freeze layer
13
+ // snapshots from THEIR `.tl` schema.
14
+ export { generateSchemaTs, writeSchemaTs } from './codegen/gen-types.js';
15
+ export { freezeLayer } from './tools/freeze-layer.js';
16
+ // @mt-tl/tl ships only the fixed MTProto **protocol** schema; business `.tl`
17
+ // lives in the consumer app. This is the protocol-only default; apps pass their
18
+ // own schema dir to the gateway.
19
+ /** Absolute path to the bundled MTProto protocol `.tl` schema directory. */
20
+ export const protocolSchemaDir = fileURLToPath(new URL('../schema', import.meta.url));
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAExC,cAAc,YAAY,CAAA;AAC1B,cAAc,eAAe,CAAA;AAC7B,cAAc,gBAAgB,CAAA;AAC9B,cAAc,eAAe,CAAA;AAC7B,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA;AACzB,cAAc,cAAc,CAAA;AAC5B,gFAAgF;AAChF,4EAA4E;AAC5E,cAAc,aAAa,CAAA;AAC3B,yEAAyE;AACzE,qCAAqC;AACrC,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAA;AACxE,OAAO,EAAE,WAAW,EAAqB,MAAM,yBAAyB,CAAA;AAExE,6EAA6E;AAC7E,gFAAgF;AAChF,iCAAiC;AACjC,4EAA4E;AAC5E,MAAM,CAAC,MAAM,iBAAiB,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,WAAW,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA"}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * A tiny dependency-free structured logger, shared across the MTProto packages
3
+ * (the server engine, the handler layer, and your app — import it for one
4
+ * consistent log style). Levels gate output; fields are key/value context.
5
+ *
6
+ * - `LOG_LEVEL` sets the threshold (`trace`<`debug`<`info`<`warn`<`error`<`silent`).
7
+ * - `LOG_FORMAT=json` emits one JSON object per line (ship to a log pipeline);
8
+ * anything else is a readable line for local dev.
9
+ * - `LOG_ERROR_STACK=true|false` forces whether `Error.stack` is serialized
10
+ * (default: on for `pretty`, off for `json` — prod opts in).
11
+ * - `pretty` output is ANSI-colored when stdout is a TTY (dim keys, colored
12
+ * level) for readability; honors `NO_COLOR` / `FORCE_COLOR`.
13
+ * - Tests default to `silent` (set `LOG_LEVEL` to override).
14
+ *
15
+ * Levels, by convention across this codebase:
16
+ * - `trace` — byte/hex protocol firehose (every recv, framing headers, decrypt).
17
+ * - `debug` — useful protocol events (decoded method, salt re-send, handshake step).
18
+ * - `info` — request/response one-liners + lifecycle links/unlinks (sockets,
19
+ * sessions, auth keys, users) + update deliveries.
20
+ * - `warn` — recoverable anomalies (decode failure, unknown method, integrity
21
+ * rejection, insecure config).
22
+ * - `error` — a request that failed or an update that could not be delivered.
23
+ */
24
+ export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'silent';
25
+ export type Fields = Record<string, unknown>;
26
+ export interface Logger {
27
+ /** Byte/hex protocol firehose — guard heavy field building with {@link isLevelEnabled}. */
28
+ trace(msg: string, fields?: Fields): void;
29
+ debug(msg: string, fields?: Fields): void;
30
+ info(msg: string, fields?: Fields): void;
31
+ warn(msg: string, fields?: Fields): void;
32
+ error(msg: string, fields?: Fields): void;
33
+ /** Returns a logger that merges `bindings` into every line (e.g. a scope/conn id). */
34
+ child(bindings: Fields): Logger;
35
+ /** True when a message at `level` would be emitted — guard expensive field building. */
36
+ isLevelEnabled(level: LogLevel): boolean;
37
+ /** The active threshold level. */
38
+ readonly level: LogLevel;
39
+ }
40
+ export interface LoggerOptions {
41
+ level?: LogLevel;
42
+ /** 'json' for machine-readable lines, 'pretty' for humans. */
43
+ format?: 'json' | 'pretty';
44
+ name?: string;
45
+ bindings?: Fields;
46
+ /**
47
+ * Include `Error.stack` when serializing an Error field. Default: `true` for
48
+ * `pretty` (dev), `false` for `json` (prod opts in). `LOG_ERROR_STACK` overrides.
49
+ */
50
+ errorStack?: boolean;
51
+ /**
52
+ * ANSI-color the `pretty` output (dim keys, colored level). Default: auto — on
53
+ * when stdout is a TTY and `NO_COLOR` is unset (off when a custom `write` is
54
+ * given). Never colors `json`.
55
+ */
56
+ color?: boolean;
57
+ /** Sink (defaults to stdout/stderr by level). Override in tests. */
58
+ write?: (line: string) => void;
59
+ }
60
+ export declare function createLogger(options?: LoggerOptions): Logger;
61
+ /** A logger that drops everything (explicit opt-out in tests/embedders). */
62
+ export declare const noopLogger: Logger;
63
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,CAAA;AAW/E,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAE5C,MAAM,WAAW,MAAM;IACnB,2FAA2F;IAC3F,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACzC,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACzC,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACxC,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACxC,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACzC,sFAAsF;IACtF,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAA;IAC/B,wFAAwF;IACxF,cAAc,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAA;IACxC,kCAAkC;IAClC,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAA;CAC3B;AAED,MAAM,WAAW,aAAa;IAC1B,KAAK,CAAC,EAAE,QAAQ,CAAA;IAChB,8DAA8D;IAC9D,MAAM,CAAC,EAAE,MAAM,GAAG,QAAQ,CAAA;IAC1B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB;;;;OAIG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,oEAAoE;IACpE,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;CACjC;AAkED,wBAAgB,YAAY,CAAC,OAAO,GAAE,aAAkB,GAAG,MAAM,CAsDhE;AASD,4EAA4E;AAC5E,eAAO,MAAM,UAAU,EAAE,MASxB,CAAA"}
package/dist/logger.js ADDED
@@ -0,0 +1,147 @@
1
+ const ORDER = {
2
+ trace: 5,
3
+ debug: 10,
4
+ info: 20,
5
+ warn: 30,
6
+ error: 40,
7
+ silent: 99,
8
+ };
9
+ function defaultLevel() {
10
+ const env = process.env.LOG_LEVEL;
11
+ if (env && env in ORDER)
12
+ return env;
13
+ if (process.env.VITEST || process.env.NODE_ENV === 'test')
14
+ return 'silent';
15
+ return 'info';
16
+ }
17
+ function defaultFormat() {
18
+ return process.env.LOG_FORMAT === 'json' ? 'json' : 'pretty';
19
+ }
20
+ function defaultErrorStack(format) {
21
+ const env = process.env.LOG_ERROR_STACK;
22
+ if (env === 'true' || env === '1')
23
+ return true;
24
+ if (env === 'false' || env === '0')
25
+ return false;
26
+ return format === 'pretty';
27
+ }
28
+ function defaultColor(format) {
29
+ if (format === 'json')
30
+ return false;
31
+ if (process.env.NO_COLOR !== undefined)
32
+ return false;
33
+ if (process.env.FORCE_COLOR)
34
+ return true;
35
+ return !!process.stdout.isTTY;
36
+ }
37
+ // ANSI styling for the pretty (TTY) format.
38
+ const RESET = '\x1b[0m';
39
+ const DIM = '\x1b[2m';
40
+ const BOLD = '\x1b[1m';
41
+ const GRAY = '\x1b[90m';
42
+ const LEVEL_COLOR = {
43
+ trace: '\x1b[90m', // gray
44
+ debug: '\x1b[36m', // cyan
45
+ info: '\x1b[32m', // green
46
+ warn: '\x1b[33m', // yellow
47
+ error: '\x1b[31m', // red
48
+ };
49
+ function makeSerialize(errorStack) {
50
+ return function serialize(value) {
51
+ if (value instanceof Error) {
52
+ const base = { name: value.name, message: value.message };
53
+ if (errorStack && value.stack)
54
+ base.stack = value.stack;
55
+ return base;
56
+ }
57
+ if (typeof value === 'bigint')
58
+ return value.toString();
59
+ return value;
60
+ };
61
+ }
62
+ function prettyFields(fields, serialize, color) {
63
+ const parts = [];
64
+ for (const [k, v] of Object.entries(fields)) {
65
+ const sv = serialize(v);
66
+ const val = typeof sv === 'object' && sv !== null ? JSON.stringify(sv) : String(sv);
67
+ // Dim the key so the eye separates key from value; values stay bright.
68
+ parts.push(color ? `${DIM}${k}=${RESET}${val}` : `${k}=${val}`);
69
+ }
70
+ if (!parts.length)
71
+ return '';
72
+ // Wider gap between fields when colored (the TTY view we optimize for reading).
73
+ const sep = color ? ' ' : ' ';
74
+ return sep + parts.join(sep);
75
+ }
76
+ export function createLogger(options = {}) {
77
+ const level = options.level ?? defaultLevel();
78
+ const format = options.format ?? defaultFormat();
79
+ const errorStack = options.errorStack ?? defaultErrorStack(format);
80
+ // A custom sink (tests/embedders) gets no color unless explicitly asked.
81
+ const color = options.color ?? (options.write ? false : defaultColor(format));
82
+ const name = options.name;
83
+ const bindings = options.bindings ?? {};
84
+ const threshold = ORDER[level];
85
+ const serialize = makeSerialize(errorStack);
86
+ const emit = (lvl, msg, fields) => {
87
+ if (ORDER[lvl] < threshold)
88
+ return;
89
+ const merged = { ...bindings, ...(fields ?? {}) };
90
+ const write = options.write ?? (lvl === 'error' || lvl === 'warn' ? errLine : outLine);
91
+ if (format === 'json') {
92
+ const obj = { time: new Date().toISOString(), level: lvl, ...(name ? { name } : {}), msg };
93
+ for (const [k, v] of Object.entries(merged))
94
+ obj[k] = serialize(v);
95
+ write(JSON.stringify(obj));
96
+ }
97
+ else {
98
+ const ts = new Date().toISOString().slice(11, 23);
99
+ const lvlText = lvl.toUpperCase().padEnd(5);
100
+ if (color) {
101
+ const tag = name ? ` ${DIM}[${name}]${RESET}` : '';
102
+ write(`${GRAY}${ts}${RESET} ${LEVEL_COLOR[lvl]}${lvlText}${RESET}${tag} ${BOLD}${msg}${RESET}` +
103
+ prettyFields(merged, serialize, true));
104
+ }
105
+ else {
106
+ const tag = name ? ` [${name}]` : '';
107
+ write(`${ts} ${lvlText}${tag} ${msg}` + prettyFields(merged, serialize, false));
108
+ }
109
+ }
110
+ };
111
+ return {
112
+ level,
113
+ trace: (msg, fields) => emit('trace', msg, fields),
114
+ debug: (msg, fields) => emit('debug', msg, fields),
115
+ info: (msg, fields) => emit('info', msg, fields),
116
+ warn: (msg, fields) => emit('warn', msg, fields),
117
+ error: (msg, fields) => emit('error', msg, fields),
118
+ isLevelEnabled: lvl => ORDER[lvl] >= threshold,
119
+ child: extra => createLogger({
120
+ ...options,
121
+ level,
122
+ format,
123
+ errorStack,
124
+ color,
125
+ name,
126
+ bindings: { ...bindings, ...extra },
127
+ }),
128
+ };
129
+ }
130
+ function outLine(line) {
131
+ process.stdout.write(line + '\n');
132
+ }
133
+ function errLine(line) {
134
+ process.stderr.write(line + '\n');
135
+ }
136
+ /** A logger that drops everything (explicit opt-out in tests/embedders). */
137
+ export const noopLogger = {
138
+ level: 'silent',
139
+ trace() { },
140
+ debug() { },
141
+ info() { },
142
+ warn() { },
143
+ error() { },
144
+ isLevelEnabled: () => false,
145
+ child: () => noopLogger,
146
+ };
147
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.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,EAAE,GAAG,QAAQ,EAAE,GAAG,KAAK,EAAE;SACtC,CAAC;KACT,CAAA;AACL,CAAC;AAED,SAAS,OAAO,CAAC,IAAY;IACzB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC,CAAA;AACrC,CAAC;AACD,SAAS,OAAO,CAAC,IAAY;IACzB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC,CAAA;AACrC,CAAC;AAED,4EAA4E;AAC5E,MAAM,CAAC,MAAM,UAAU,GAAW;IAC9B,KAAK,EAAE,QAAQ;IACf,KAAK,KAAI,CAAC;IACV,KAAK,KAAI,CAAC;IACV,IAAI,KAAI,CAAC;IACT,IAAI,KAAI,CAAC;IACT,KAAK,KAAI,CAAC;IACV,cAAc,EAAE,GAAG,EAAE,CAAC,KAAK;IAC3B,KAAK,EAAE,GAAG,EAAE,CAAC,UAAU;CAC1B,CAAA"}
@@ -0,0 +1,37 @@
1
+ import type { TlValue } from './tl/value.js';
2
+ /**
3
+ * One rung of a predicate's migration ladder. `up` maps THIS version's shape to
4
+ * the NEXT version's; `down` maps the next version back to this one. The newest
5
+ * (canonical) rung has neither.
6
+ */
7
+ export interface MigrationRung {
8
+ /** Layer this shape was introduced. */
9
+ since: number;
10
+ up?: (obj: Record<string, unknown>) => Record<string, unknown>;
11
+ down?: (obj: Record<string, unknown>) => Record<string, unknown>;
12
+ }
13
+ /**
14
+ * Per-predicate migration ladders. The gateway normalizes inbound values to the
15
+ * canonical (newest) shape (`up`) before forwarding, and renders canonical values
16
+ * down to a client's layer (`down`) before encoding — so workers only ever see
17
+ * the canonical shape. Scales to N versions: one rung per version; adding a
18
+ * version appends a rung and never touches the others.
19
+ *
20
+ * Only non-additively-changed predicates need a ladder; everything else is
21
+ * handled by decode-union + layered-encode with no rungs (identity here).
22
+ */
23
+ export declare class MigrationRegistry {
24
+ private byPredicate;
25
+ /** Register a predicate's ladder (rungs in any order; sorted by `since`). */
26
+ register(predicate: string, rungs: MigrationRung[]): this;
27
+ has(predicate: string): boolean;
28
+ get size(): number;
29
+ /** Normalize a value decoded at `fromLayer` up to the canonical shape. */
30
+ up(value: TlValue, fromLayer: number): TlValue;
31
+ /** Render a canonical value down to `toLayer`'s shape. */
32
+ down(value: TlValue, toLayer: number): TlValue;
33
+ private recurse;
34
+ private upObject;
35
+ private downObject;
36
+ }
37
+ //# sourceMappingURL=migrate.d.ts.map