typia 9.7.2 → 10.0.0-dev.20251107

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 (116) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +153 -153
  3. package/lib/factories/ProtobufFactory.js +1 -1
  4. package/lib/factories/ProtobufFactory.mjs +1 -1
  5. package/lib/programmers/internal/json_schema_station.d.mts +2 -2
  6. package/lib/programmers/internal/json_schema_station.d.ts +2 -2
  7. package/lib/programmers/llm/LlmApplicationProgrammer.js +5 -1
  8. package/lib/programmers/llm/LlmApplicationProgrammer.js.map +1 -1
  9. package/lib/programmers/llm/LlmApplicationProgrammer.mjs +5 -1
  10. package/lib/programmers/llm/LlmSchemaProgrammer.js +1 -4
  11. package/lib/programmers/llm/LlmSchemaProgrammer.js.map +1 -1
  12. package/lib/programmers/llm/LlmSchemaProgrammer.mjs +1 -35
  13. package/package.json +121 -121
  14. package/src/AssertionGuard.ts +41 -41
  15. package/src/CamelCase.ts +75 -75
  16. package/src/IRandomGenerator.ts +337 -337
  17. package/src/IReadableURLSearchParams.ts +9 -9
  18. package/src/PascalCase.ts +71 -71
  19. package/src/Primitive.ts +90 -90
  20. package/src/Resolved.ts +72 -72
  21. package/src/SnakeCase.ts +127 -127
  22. package/src/TypeGuardError.ts +216 -216
  23. package/src/factories/MetadataCollection.ts +270 -270
  24. package/src/factories/MetadataCommentTagFactory.ts +632 -632
  25. package/src/factories/MetadataFactory.ts +402 -402
  26. package/src/factories/ProtobufFactory.ts +873 -873
  27. package/src/functional.ts +705 -705
  28. package/src/http.ts +972 -972
  29. package/src/internal/_ProtobufReader.ts +188 -188
  30. package/src/internal/_ProtobufSizer.ts +137 -137
  31. package/src/internal/_ProtobufWriter.ts +135 -135
  32. package/src/internal/_jsonStringifyString.ts +42 -42
  33. package/src/json.ts +643 -643
  34. package/src/llm.ts +615 -615
  35. package/src/misc.ts +594 -594
  36. package/src/module.ts +889 -889
  37. package/src/notations.ts +751 -751
  38. package/src/programmers/FeatureProgrammer.ts +605 -605
  39. package/src/programmers/ImportProgrammer.ts +179 -179
  40. package/src/programmers/RandomProgrammer.ts +1195 -1195
  41. package/src/programmers/helpers/ProtobufWire.ts +34 -34
  42. package/src/programmers/internal/check_array_length.ts +43 -43
  43. package/src/programmers/internal/check_bigint.ts +46 -46
  44. package/src/programmers/internal/check_dynamic_key.ts +197 -197
  45. package/src/programmers/internal/check_dynamic_properties.ts +231 -231
  46. package/src/programmers/internal/check_everything.ts +21 -21
  47. package/src/programmers/internal/check_native.ts +23 -23
  48. package/src/programmers/internal/check_number.ts +108 -108
  49. package/src/programmers/internal/check_object.ts +72 -72
  50. package/src/programmers/internal/check_string.ts +46 -46
  51. package/src/programmers/internal/check_template.ts +46 -46
  52. package/src/programmers/internal/check_union_array_like.ts +331 -331
  53. package/src/programmers/internal/decode_union_object.ts +110 -110
  54. package/src/programmers/internal/feature_object_entries.ts +59 -59
  55. package/src/programmers/internal/json_schema_escaped.ts +78 -78
  56. package/src/programmers/internal/json_schema_object.ts +150 -150
  57. package/src/programmers/internal/json_schema_station.ts +2 -2
  58. package/src/programmers/internal/metadata_to_pattern.ts +40 -40
  59. package/src/programmers/internal/postfix_of_tuple.ts +3 -3
  60. package/src/programmers/internal/prune_object_properties.ts +69 -69
  61. package/src/programmers/internal/stringify_dynamic_properties.ts +158 -158
  62. package/src/programmers/internal/stringify_native.ts +5 -5
  63. package/src/programmers/internal/stringify_regular_properties.ts +77 -77
  64. package/src/programmers/internal/template_to_pattern.ts +21 -21
  65. package/src/programmers/internal/wrap_metadata_rest_tuple.ts +21 -21
  66. package/src/programmers/json/JsonStringifyProgrammer.ts +1124 -1124
  67. package/src/programmers/llm/LlmApplicationProgrammer.ts +10 -1
  68. package/src/programmers/llm/LlmSchemaProgrammer.ts +2 -7
  69. package/src/protobuf.ts +820 -820
  70. package/src/reflect.ts +46 -46
  71. package/src/schemas/json/IJsonApplication.ts +77 -77
  72. package/src/schemas/json/IJsonSchemaCollection.ts +212 -212
  73. package/src/schemas/json/IJsonSchemaUnit.ts +263 -263
  74. package/src/schemas/metadata/IMetadataTypeTag.ts +14 -14
  75. package/src/schemas/metadata/Metadata.ts +669 -669
  76. package/src/schemas/metadata/MetadataAliasType.ts +57 -57
  77. package/src/schemas/metadata/MetadataApplication.ts +40 -40
  78. package/src/schemas/metadata/MetadataArray.ts +47 -47
  79. package/src/schemas/metadata/MetadataArrayType.ts +51 -51
  80. package/src/schemas/metadata/MetadataAtomic.ts +85 -85
  81. package/src/schemas/metadata/MetadataEscaped.ts +45 -45
  82. package/src/schemas/metadata/MetadataFunction.ts +45 -45
  83. package/src/schemas/metadata/MetadataObject.ts +46 -46
  84. package/src/schemas/metadata/MetadataObjectType.ts +137 -137
  85. package/src/schemas/metadata/MetadataParameter.ts +52 -52
  86. package/src/schemas/metadata/MetadataProperty.ts +53 -53
  87. package/src/schemas/metadata/MetadataTemplate.ts +78 -78
  88. package/src/schemas/metadata/MetadataTuple.ts +28 -28
  89. package/src/schemas/metadata/MetadataTupleType.ts +61 -61
  90. package/src/tags/Constant.ts +47 -47
  91. package/src/tags/ContentMediaType.ts +27 -27
  92. package/src/tags/Default.ts +52 -52
  93. package/src/tags/Example.ts +56 -56
  94. package/src/tags/Examples.ts +56 -56
  95. package/src/tags/ExclusiveMaximum.ts +44 -44
  96. package/src/tags/ExclusiveMinimum.ts +44 -44
  97. package/src/tags/Format.ts +78 -78
  98. package/src/tags/JsonSchemaPlugin.ts +36 -36
  99. package/src/tags/MaxItems.ts +31 -31
  100. package/src/tags/MaxLength.ts +25 -25
  101. package/src/tags/Maximum.ts +39 -39
  102. package/src/tags/MinItems.ts +31 -31
  103. package/src/tags/MinLength.ts +25 -25
  104. package/src/tags/Minimum.ts +39 -39
  105. package/src/tags/MultipleOf.ts +42 -42
  106. package/src/tags/Pattern.ts +49 -49
  107. package/src/tags/Sequence.ts +37 -37
  108. package/src/tags/TagBase.ts +102 -102
  109. package/src/tags/Type.ts +64 -64
  110. package/src/tags/UniqueItems.ts +34 -34
  111. package/src/tags/internal/FormatCheatSheet.ts +71 -71
  112. package/src/transformers/ITransformOptions.ts +70 -70
  113. package/src/transformers/ImportTransformer.ts +253 -253
  114. package/src/transformers/NoTransformConfigurationError.ts +16 -16
  115. package/src/transformers/features/llm/LlmApplicationTransformer.ts +224 -224
  116. package/src/typings/Equal.ts +18 -18
@@ -1,873 +1,873 @@
1
- import ts from "typescript";
2
-
3
- import { IMetadataTypeTag } from "../schemas/metadata/IMetadataTypeTag";
4
- import { Metadata } from "../schemas/metadata/Metadata";
5
- import { MetadataObjectType } from "../schemas/metadata/MetadataObjectType";
6
- import { MetadataProperty } from "../schemas/metadata/MetadataProperty";
7
- import { IProtobufProperty } from "../schemas/protobuf/IProtobufProperty";
8
- import { IProtobufPropertyType } from "../schemas/protobuf/IProtobufPropertyType";
9
- import { IProtobufSchema } from "../schemas/protobuf/IProtobufSchema";
10
-
11
- import { ProtobufUtil } from "../programmers/helpers/ProtobufUtil";
12
-
13
- import { TransformerError } from "../transformers/TransformerError";
14
-
15
- import { ProtobufAtomic } from "../typings/ProtobufAtomic";
16
- import { ValidationPipe } from "../typings/ValidationPipe";
17
-
18
- import { MetadataCollection } from "./MetadataCollection";
19
- import { MetadataFactory } from "./MetadataFactory";
20
-
21
- export namespace ProtobufFactory {
22
- export interface IProps {
23
- method: string;
24
- checker: ts.TypeChecker;
25
- transformer?: ts.TransformationContext;
26
- collection: MetadataCollection;
27
- type: ts.Type;
28
- }
29
-
30
- /* -----------------------------------------------------------
31
- METADATA COMPOSER
32
- ----------------------------------------------------------- */
33
- export const metadata = (props: IProps): Metadata => {
34
- // COMPOSE METADATA WITH INDIVIDUAL VALIDATIONS
35
- const result: ValidationPipe<Metadata, MetadataFactory.IError> =
36
- MetadataFactory.analyze({
37
- ...props,
38
- transformer: props.transformer,
39
- options: {
40
- escape: false,
41
- constant: true,
42
- absorb: true,
43
- validate: validate(),
44
- },
45
- });
46
- if (result.success === false)
47
- throw TransformerError.from({
48
- code: `typia.protobuf.${props.method}`,
49
- errors: result.errors,
50
- });
51
- return result.data;
52
- };
53
-
54
- /** @internal */
55
- export const emplaceObject = (object: MetadataObjectType): void => {
56
- for (const p of object.properties) emplaceProperty(p);
57
- const properties: IProtobufProperty[] = object.properties
58
- .map((p) => p.of_protobuf_)
59
- .filter((p) => p !== undefined);
60
- const unique: Set<number> = new Set(
61
- properties
62
- .filter((p) => p !== undefined)
63
- .filter((p) => p.fixed === true)
64
- .map((p) => p.union.map((u) => u.index))
65
- .flat(),
66
- );
67
- let index: number = 1;
68
- properties.forEach((schema) => {
69
- if (schema.fixed === true)
70
- index = Math.max(
71
- index,
72
- Math.max(...schema.union.map((u) => u.index)) + 1,
73
- );
74
- else {
75
- for (const u of schema.union) {
76
- while (unique.has(index) === true) ++index;
77
- u.index = index;
78
- unique.add(index);
79
- }
80
- ++index;
81
- }
82
- });
83
- };
84
-
85
- const emplaceProperty = (prop: MetadataProperty): void => {
86
- const union: IProtobufPropertyType[] = [];
87
- for (const native of prop.value.natives)
88
- if (native.name === "Uint8Array")
89
- union.push({
90
- type: "bytes",
91
- index: ProtobufUtil.getSequence(native.tags[0] ?? [])!,
92
- });
93
- union.push(...emplaceAtomic(prop.value).values());
94
- for (const array of prop.value.arrays)
95
- union.push({
96
- type: "array",
97
- array: array.type,
98
- value: emplaceSchema(
99
- array.type.value,
100
- ) as IProtobufSchema.IArray["value"],
101
- index: ProtobufUtil.getSequence(array.tags[0] ?? [])!,
102
- });
103
- for (const obj of prop.value.objects)
104
- if (isDynamicObject(obj.type))
105
- union.push({
106
- type: "map",
107
- map: obj.type,
108
- key: emplaceSchema(
109
- obj.type.properties[0]!.key,
110
- ) as IProtobufSchema.IMap["key"],
111
- value: emplaceSchema(
112
- obj.type.properties[0]!.value,
113
- ) as IProtobufSchema.IMap["value"],
114
- index: ProtobufUtil.getSequence(obj.tags[0] ?? [])!,
115
- });
116
- else
117
- union.push({
118
- type: "object",
119
- object: obj.type,
120
- index: ProtobufUtil.getSequence(obj.tags[0] ?? [])!,
121
- });
122
- for (const map of prop.value.maps)
123
- union.push({
124
- type: "map",
125
- map,
126
- key: emplaceSchema(map.key) as IProtobufSchema.IMap["key"],
127
- value: emplaceSchema(map.value) as IProtobufSchema.IMap["value"],
128
- index: ProtobufUtil.getSequence(map.tags[0] ?? [])!,
129
- });
130
- prop.of_protobuf_ = {
131
- union,
132
- fixed: union.every((p) => p.index !== null),
133
- };
134
- };
135
-
136
- const emplaceSchema = (metadata: Metadata): IProtobufSchema => {
137
- for (const native of metadata.natives)
138
- if (native.name === "Uint8Array")
139
- return {
140
- type: "bytes",
141
- };
142
- const atomic = emplaceAtomic(metadata);
143
- if (atomic.size) return atomic.values().next().value!;
144
- for (const array of metadata.arrays)
145
- return {
146
- type: "array",
147
- array: array.type,
148
- value: emplaceSchema(
149
- array.type.value,
150
- ) as IProtobufSchema.IArray["value"],
151
- };
152
- for (const obj of metadata.objects)
153
- if (isDynamicObject(obj.type))
154
- return {
155
- type: "map",
156
- map: obj.type,
157
- key: emplaceSchema(
158
- obj.type.properties[0]!.key,
159
- ) as IProtobufSchema.IMap["key"],
160
- value: emplaceSchema(
161
- obj.type.properties[0]!.value,
162
- ) as IProtobufSchema.IMap["value"],
163
- };
164
- else
165
- return {
166
- type: "object",
167
- object: obj.type,
168
- };
169
- for (const map of metadata.maps)
170
- return {
171
- type: "map",
172
- map,
173
- key: emplaceSchema(map.key) as IProtobufSchema.IMap["key"],
174
- value: emplaceSchema(map.value) as IProtobufSchema.IMap["value"],
175
- };
176
- throw new Error(
177
- "Error on ProtobufFactory.emplaceSchema(): any type detected.",
178
- );
179
- };
180
-
181
- const emplaceAtomic = (
182
- meta: Metadata,
183
- ): Map<ProtobufAtomic, IProtobufPropertyType> => {
184
- const map: Map<ProtobufAtomic, IProtobufPropertyType> = new Map();
185
-
186
- // CONSTANTS
187
- for (const c of meta.constants)
188
- if (c.type === "boolean")
189
- map.set("bool", {
190
- type: "bool",
191
- index: getSequence(c.values[0]?.tags[0] ?? [])!,
192
- });
193
- else if (c.type === "bigint") {
194
- const init: ProtobufAtomic.BigNumeric = getBigintType(
195
- c.values.map((v) => BigInt(v.value)),
196
- );
197
- for (const value of c.values)
198
- emplaceBigint({
199
- map,
200
- tags: value.tags,
201
- init,
202
- });
203
- } else if (c.type === "number") {
204
- const init: ProtobufAtomic.Numeric = getNumberType(
205
- c.values.map((v) => v.value) as number[],
206
- );
207
- for (const value of c.values)
208
- emplaceNumber({
209
- map,
210
- tags: value.tags,
211
- init,
212
- });
213
- } else if (c.type === "string")
214
- map.set("string", {
215
- type: "string",
216
- index: getSequence(c.values[0]?.tags[0] ?? [])!,
217
- });
218
-
219
- // TEMPLATE
220
- if (meta.templates.length)
221
- map.set("string", {
222
- type: "string",
223
- index: getSequence(meta.templates[0]?.tags[0] ?? [])!,
224
- });
225
-
226
- // ATOMICS
227
- for (const atomic of meta.atomics)
228
- if (atomic.type === "boolean")
229
- map.set("bool", {
230
- type: "bool",
231
- index: getSequence(atomic.tags[0] ?? [])!,
232
- });
233
- else if (atomic.type === "bigint")
234
- emplaceBigint({
235
- map,
236
- tags: atomic.tags,
237
- init: "int64",
238
- });
239
- else if (atomic.type === "number")
240
- emplaceNumber({
241
- map,
242
- tags: atomic.tags,
243
- init: "double",
244
- });
245
- else if (atomic.type === "string")
246
- map.set("string", {
247
- type: "string",
248
- index: getSequence(atomic.tags[0] ?? [])!,
249
- });
250
-
251
- // SORTING FOR VALIDATION REASON
252
- return new Map(
253
- Array.from(map).sort((x, y) => ProtobufUtil.compare(x[0], y[0])),
254
- );
255
- };
256
-
257
- const emplaceBigint = (next: {
258
- map: Map<ProtobufAtomic, IProtobufPropertyType>;
259
- tags: IMetadataTypeTag[][];
260
- init: ProtobufAtomic.BigNumeric;
261
- }): void => {
262
- if (next.tags.length === 0) {
263
- next.map.set(next.init, {
264
- type: "bigint",
265
- name: next.init,
266
- index: null!,
267
- });
268
- return;
269
- }
270
- for (const row of next.tags) {
271
- const value: ProtobufAtomic.BigNumeric =
272
- row.find(
273
- (tag) =>
274
- tag.kind === "type" &&
275
- (tag.value === "int64" || tag.value === "uint64"),
276
- )?.value ?? next.init;
277
- next.map.set(next.init, {
278
- type: "bigint",
279
- name: value,
280
- index: ProtobufUtil.getSequence(row)!,
281
- });
282
- }
283
- };
284
-
285
- const emplaceNumber = (next: {
286
- map: Map<ProtobufAtomic, IProtobufPropertyType>;
287
- tags: IMetadataTypeTag[][];
288
- init: ProtobufAtomic.Numeric;
289
- }): void => {
290
- if (next.tags.length === 0) {
291
- next.map.set(next.init, {
292
- type: "number",
293
- name: next.init,
294
- index: null!,
295
- });
296
- return;
297
- }
298
- for (const row of next.tags) {
299
- const value: ProtobufAtomic.Numeric =
300
- row.find(
301
- (tag) =>
302
- tag.kind === "type" &&
303
- (tag.value === "int32" ||
304
- tag.value === "uint32" ||
305
- tag.value === "int64" ||
306
- tag.value === "uint64" ||
307
- tag.value === "float" ||
308
- tag.value === "double"),
309
- )?.value ?? next.init;
310
- next.map.set(value, {
311
- type: "number",
312
- name: value,
313
- index: ProtobufUtil.getSequence(row)!,
314
- });
315
- }
316
- };
317
-
318
- const getBigintType = (values: bigint[]): ProtobufAtomic.BigNumeric =>
319
- values.some((v) => v < 0) ? "int64" : "uint64";
320
-
321
- const getNumberType = (values: number[]): ProtobufAtomic.Numeric =>
322
- values.every((v) => Math.floor(v) === v)
323
- ? values.every((v) => -2147483648 <= v && v <= 2147483647)
324
- ? "int32"
325
- : "int64"
326
- : "double";
327
-
328
- const getSequence = (tags: IMetadataTypeTag[]): number | null => {
329
- const sequence = tags.find(
330
- (t) =>
331
- t.kind === "sequence" &&
332
- typeof (t.schema as any)?.["x-protobuf-sequence"] === "number",
333
- );
334
- if (sequence === undefined) return null;
335
- const value: number = Number(
336
- (sequence.schema as any)["x-protobuf-sequence"],
337
- );
338
- return Number.isNaN(value) ? null : value;
339
- };
340
-
341
- /* -----------------------------------------------------------
342
- VALIDATORS
343
- ----------------------------------------------------------- */
344
- const validate = () => {
345
- const visited: WeakSet<MetadataObjectType> = new WeakSet();
346
- return (meta: Metadata, explore: MetadataFactory.IExplore): string[] => {
347
- const errors: string[] = [];
348
- const insert = (msg: string) => errors.push(msg);
349
-
350
- if (explore.top === true) {
351
- const onlyObject: boolean =
352
- meta.size() === 1 &&
353
- meta.objects.length === 1 &&
354
- meta.objects[0]!.type.properties.every((p) =>
355
- p.key.isSoleLiteral(),
356
- ) &&
357
- meta.isRequired() === true &&
358
- meta.nullable === false;
359
- if (onlyObject === false)
360
- insert("target type must be a sole and static object type");
361
- }
362
- for (const obj of meta.objects) {
363
- if (visited.has(obj.type)) continue;
364
- visited.add(obj.type);
365
- validateObject({
366
- object: obj.type,
367
- errors,
368
- });
369
- try {
370
- emplaceObject(obj.type);
371
- } catch {}
372
- }
373
-
374
- //----
375
- // NOT SUPPORTED TYPES
376
- //----
377
- const noSupport = (msg: string) => insert(`does not support ${msg}`);
378
-
379
- // PROHIBIT ANY TYPE
380
- if (meta.any) noSupport("any type");
381
- // PROHIBIT FUNCTIONAL TYPE
382
- if (meta.functions.length) noSupport("functional type");
383
- // PROHIBIT TUPLE TYPE
384
- if (meta.tuples.length) noSupport("tuple type");
385
- // PROHIBIT SET TYPE
386
- if (meta.sets.length) noSupport("Set type");
387
- // NATIVE TYPE, BUT NOT Uint8Array
388
- if (meta.natives.length)
389
- for (const native of meta.natives) {
390
- if (native.name === "Uint8Array") continue;
391
-
392
- const instead = BANNED_NATIVE_TYPES.get(native.name);
393
- if (instead === undefined) noSupport(`${native.name} type`);
394
- else noSupport(`${native.name} type. Use ${instead} type instead.`);
395
- }
396
- //----
397
- // ATOMIC CASES
398
- //----
399
- if (meta.atomics.length) {
400
- const numbers = ProtobufUtil.getNumbers(meta);
401
- const bigints = ProtobufUtil.getBigints(meta);
402
-
403
- for (const type of ["int64", "uint64"])
404
- if (numbers.has(type) && bigints.has(type))
405
- insert(
406
- `tags.Type<"${type}"> cannot be used in both number and bigint types. Recommend to remove from number type`,
407
- );
408
- }
409
- //----
410
- // ARRAY CASES
411
- //----
412
- // DO NOT ALLOW MULTI-DIMENSIONAL ARRAY
413
- if (
414
- meta.arrays.length &&
415
- meta.arrays.some((array) => !!array.type.value.arrays.length)
416
- )
417
- noSupport("over two dimensional array type");
418
- // CHILD OF ARRAY TYPE MUST BE REQUIRED
419
- if (
420
- meta.arrays.length &&
421
- meta.arrays.some(
422
- (array) =>
423
- array.type.value.isRequired() === false ||
424
- array.type.value.nullable === true,
425
- )
426
- )
427
- noSupport("optional type in array");
428
- // UNION IN ARRAY
429
- if (
430
- meta.arrays.length &&
431
- meta.arrays.some(
432
- (a) =>
433
- a.type.value.size() > 1 &&
434
- a.type.value.constants.length !== 1 &&
435
- a.type.value.constants[0]?.values.length !== a.type.value.size(),
436
- )
437
- )
438
- noSupport("union type in array");
439
- // DO DYNAMIC OBJECT IN ARRAY
440
- if (
441
- meta.arrays.length &&
442
- meta.arrays.some(
443
- (a) =>
444
- a.type.value.maps.length ||
445
- (a.type.value.objects.length &&
446
- a.type.value.objects.some(
447
- (o) => ProtobufUtil.isStaticObject(o.type) === false,
448
- )),
449
- )
450
- )
451
- noSupport("dynamic object in array");
452
- // UNION WITH ARRAY
453
- if (meta.size() > 1 && meta.arrays.length)
454
- noSupport("union type with array type");
455
- //----
456
- // OBJECT CASES
457
- //----
458
- // EMPTY PROPERTY
459
- if (
460
- meta.objects.length &&
461
- meta.objects.some((obj) => obj.type.properties.length === 0)
462
- )
463
- noSupport("empty object type");
464
- // MULTIPLE DYNAMIC KEY TYPED PROPERTIES
465
- if (
466
- meta.objects.length &&
467
- meta.objects.some(
468
- (obj) =>
469
- obj.type.properties.filter((p) => !p.key.isSoleLiteral()).length >
470
- 1,
471
- )
472
- )
473
- noSupport(
474
- "object type with multiple dynamic key typed properties. Keep only one.",
475
- );
476
- // STATIC AND DYNAMIC PROPERTIES ARE COMPATIBLE
477
- if (
478
- meta.objects.length &&
479
- meta.objects.some(
480
- (obj) =>
481
- obj.type.properties.some((p) => p.key.isSoleLiteral()) &&
482
- obj.type.properties.some((p) => !p.key.isSoleLiteral()),
483
- )
484
- )
485
- noSupport(
486
- "object type with mixed static and dynamic key typed properties. Keep statics or dynamic only.",
487
- );
488
- // DYNAMIC OBJECT, BUT PROPERTY VALUE TYPE IS ARRAY
489
- if (
490
- meta.objects.length &&
491
- isDynamicObject(meta.objects[0]!.type) &&
492
- meta.objects[0]!.type.properties.some((p) => !!p.value.arrays.length)
493
- )
494
- noSupport("dynamic object with array value type");
495
- // UNION WITH DYNAMIC OBJECTTa
496
- if (
497
- meta.size() > 1 &&
498
- meta.objects.length &&
499
- isDynamicObject(meta.objects[0]!.type)
500
- )
501
- noSupport("union type with dynamic object type");
502
- // UNION IN DYNAMIC PROPERTY VALUE
503
- if (
504
- meta.objects.length &&
505
- meta.objects.some(
506
- (obj) =>
507
- isDynamicObject(obj.type) &&
508
- obj.type.properties.some((p) => ProtobufUtil.isUnion(p.value)),
509
- )
510
- )
511
- noSupport("union type in dynamic property");
512
- //----
513
- // MAP CASES
514
- //----
515
- // KEY TYPE IS UNION
516
- if (
517
- meta.maps.length &&
518
- meta.maps.some((m) => ProtobufUtil.isUnion(m.key))
519
- )
520
- noSupport("union key typed map");
521
- // KEY TYPE IS NOT ATOMIC
522
- if (
523
- meta.maps.length &&
524
- meta.maps.some((m) => ProtobufUtil.getAtomics(m.key).size !== 1)
525
- )
526
- noSupport("non-atomic key typed map");
527
- // MAP TYPE, BUT PROPERTY KEY TYPE IS OPTIONAL
528
- if (
529
- meta.maps.length &&
530
- meta.maps.some((m) => m.key.isRequired() === false || m.key.nullable)
531
- )
532
- noSupport("optional key typed map");
533
- // MAP TYPE, BUT VALUE TYPE IS ARRAY
534
- if (meta.maps.length && meta.maps.some((m) => !!m.value.arrays.length))
535
- noSupport("map type with array value type");
536
- // UNION WITH MAP
537
- if (meta.size() > 1 && meta.maps.length)
538
- noSupport("union type with map type");
539
- // UNION IN MAP
540
- if (
541
- meta.maps.length &&
542
- meta.maps.some((m) => ProtobufUtil.isUnion(m.value))
543
- )
544
- noSupport("union type in map value type");
545
- return errors;
546
- };
547
- };
548
-
549
- /* -----------------------------------------------------------
550
- SEQUENE VALIDATOR
551
- ----------------------------------------------------------- */
552
- const validateObject = (next: {
553
- object: MetadataObjectType;
554
- errors: string[];
555
- }): void => {
556
- for (const property of next.object.properties)
557
- validateProperty({
558
- metadata: property.value,
559
- errors: next.errors,
560
- });
561
-
562
- const entire: Map<number, string> = new Map();
563
- const visitProperty = (p: MetadataProperty) => {
564
- const local: Set<number> = new Set();
565
- const tagger = (matrix: IMetadataTypeTag[][]): void => {
566
- matrix.forEach((tags) => {
567
- const value: number | null = ProtobufUtil.getSequence(tags);
568
- if (value !== null) local.add(value);
569
- });
570
- };
571
- for (const c of p.value.constants)
572
- for (const v of c.values) tagger(v.tags);
573
- for (const a of p.value.atomics) tagger(a.tags);
574
- for (const t of p.value.templates) tagger(t.tags);
575
- for (const o of p.value.objects) tagger(o.tags);
576
- for (const a of p.value.arrays) tagger(a.tags);
577
- for (const s of local)
578
- if (entire.has(s))
579
- next.errors.push(
580
- `The Sequence<${s}> tag is duplicated in two properties (${JSON.stringify(entire.get(s))} and ${JSON.stringify(p.key.getSoleLiteral())})`,
581
- );
582
- else entire.set(s, p.key.getSoleLiteral()!);
583
- };
584
- for (const p of next.object.properties) visitProperty(p);
585
- };
586
-
587
- const validateProperty = (next: {
588
- metadata: Metadata;
589
- errors: string[];
590
- }): void => {
591
- let expected: number = 0;
592
- const sequences: Set<number> = new Set();
593
- const add = (value: number): boolean => {
594
- if (sequences.has(value)) return false;
595
- sequences.add(value);
596
- ++expected;
597
- return true;
598
- };
599
-
600
- for (const validator of [
601
- validateBooleanSequence,
602
- validateNumericSequences({
603
- type: "bigint",
604
- default: "int64",
605
- categories: BIGINT_TYPES,
606
- }),
607
- validateNumericSequences({
608
- type: "number",
609
- default: "double",
610
- categories: NUMBER_TYPES,
611
- }),
612
- validateStringSequence,
613
- ])
614
- validator({ metadata: next.metadata, errors: next.errors, add });
615
- for (const array of next.metadata.arrays)
616
- validateInstanceSequence({
617
- type: "array",
618
- tags: array.tags,
619
- errors: next.errors,
620
- add,
621
- });
622
- for (const object of next.metadata.objects)
623
- validateInstanceSequence({
624
- type: "object",
625
- tags: object.tags,
626
- errors: next.errors,
627
- add,
628
- });
629
- for (const map of next.metadata.maps)
630
- validateInstanceSequence({
631
- type: "map",
632
- tags: map.tags,
633
- errors: next.errors,
634
- add,
635
- });
636
- for (const native of next.metadata.natives)
637
- if (native.name === "Uint8Array")
638
- validateInstanceSequence({
639
- type: "Uint8Array",
640
- tags: native.tags,
641
- errors: next.errors,
642
- add,
643
- });
644
- };
645
-
646
- const validateBooleanSequence = (next: {
647
- metadata: Metadata;
648
- errors: string[];
649
- add: (value: number) => boolean;
650
- }): void => {
651
- // PREPARE EMPLACER
652
- const unique: Set<number> = new Set();
653
- let expected: number = 0;
654
- let actual: number = 0;
655
- const emplace = (matrix: IMetadataTypeTag[][]): void => {
656
- for (const tags of matrix)
657
- for (const tag of tags) {
658
- const sequence = ProtobufUtil.getSequence([tag]);
659
- if (sequence !== null) {
660
- unique.add(sequence);
661
- ++actual;
662
- }
663
- ++expected;
664
- }
665
- };
666
-
667
- // GATHER SEQUENCE TAGS
668
- for (const atomic of next.metadata.atomics)
669
- if (atomic.type === "boolean") emplace(atomic.tags);
670
- for (const constant of next.metadata.constants)
671
- if (constant.type === "boolean")
672
- for (const value of constant.values) emplace(value.tags);
673
-
674
- // PREDICATE
675
- if (unique.size && actual !== expected)
676
- next.errors.push(
677
- `The sequence tag must be declared in every union type members`,
678
- );
679
- else if (unique.size > 1)
680
- next.errors.push(
681
- `The sequence tag value must be the same in boolean type (including literal types)`,
682
- );
683
- else if (unique.size === 1) {
684
- const value: number = unique.values().next().value!;
685
- if (next.add(value) === false)
686
- next.errors.push(
687
- `The sequence tag value ${value} in boolean type is duplicated with other types`,
688
- );
689
- }
690
- };
691
-
692
- const validateNumericSequences =
693
- (config: {
694
- type: "number" | "bigint";
695
- default: string;
696
- categories: Set<string>;
697
- }) =>
698
- (next: {
699
- metadata: Metadata;
700
- errors: string[];
701
- add: (value: number) => boolean;
702
- }): void => {
703
- // FIND TYPE CATEGORIES
704
- const categories: Set<string> = new Set();
705
- const getType = (tags: IMetadataTypeTag[]): string => {
706
- const found: IMetadataTypeTag | undefined = tags.find(
707
- (t) => t.kind === "type" && config.categories.has(t.value),
708
- );
709
- return found?.value ?? config.default;
710
- };
711
- const exploreCategory = (matrix: IMetadataTypeTag[][]): void => {
712
- for (const tags of matrix) categories.add(getType(tags));
713
- };
714
- for (const atomic of next.metadata.atomics)
715
- if (atomic.type === config.type) exploreCategory(atomic.tags);
716
- for (const constant of next.metadata.constants)
717
- if (constant.type === config.type)
718
- for (const value of constant.values) exploreCategory(value.tags);
719
-
720
- // ITERATE TYPE CATEGORIES
721
- for (const category of categories) {
722
- const unique: Set<number> = new Set();
723
- let expected: number = 0;
724
- let actual: number = 0;
725
- const emplace = (tags: IMetadataTypeTag[]): void => {
726
- const sequence: number | null = ProtobufUtil.getSequence(tags);
727
- if (sequence !== null) {
728
- unique.add(sequence);
729
- ++actual;
730
- }
731
- ++expected;
732
- };
733
-
734
- for (const atomic of next.metadata.atomics)
735
- if (atomic.type === config.type)
736
- for (const tags of atomic.tags)
737
- if (getType(tags) === category) emplace(tags);
738
- for (const constant of next.metadata.constants)
739
- if (constant.type === config.type)
740
- for (const value of constant.values)
741
- for (const tags of value.tags)
742
- if (getType(tags) === category) emplace(tags);
743
-
744
- if (unique.size && actual !== expected) {
745
- next.errors.push(
746
- `The sequence tag must be declared in every union type members`,
747
- );
748
- } else if (unique.size > 1)
749
- next.errors.push(
750
- `The sequence tag value must be the same in ${config.type} type (including literal types)`,
751
- );
752
- else if (unique.size === 1) {
753
- const value: number = unique.values().next().value!;
754
- if (next.add(value) === false)
755
- next.errors.push(
756
- `The sequence tag value ${value} in ${config.type} type is duplicated with other types`,
757
- );
758
- }
759
- }
760
- };
761
-
762
- const validateStringSequence = (next: {
763
- metadata: Metadata;
764
- errors: string[];
765
- add: (value: number) => boolean;
766
- }): void => {
767
- const unique: Set<number> = new Set();
768
- let expected: number = 0;
769
- let actual: number = 0;
770
- const emplace = (matrix: IMetadataTypeTag[][]): void => {
771
- for (const tags of matrix)
772
- for (const tag of tags) {
773
- const sequence = ProtobufUtil.getSequence([tag]);
774
- if (sequence !== null) {
775
- unique.add(sequence);
776
- ++actual;
777
- }
778
- ++expected;
779
- }
780
- };
781
- for (const atomic of next.metadata.atomics)
782
- if (atomic.type === "string") emplace(atomic.tags);
783
- for (const constant of next.metadata.constants)
784
- if (constant.type === "string")
785
- for (const value of constant.values) emplace(value.tags);
786
- for (const template of next.metadata.templates) emplace(template.tags);
787
-
788
- if (unique.size && actual !== expected)
789
- next.errors.push(
790
- `The sequence tag must be declared in every union type members`,
791
- );
792
- else if (unique.size > 1)
793
- next.errors.push(
794
- `The sequence tag value must be the same in string types including literal and template types`,
795
- );
796
- else if (unique.size === 1) {
797
- const value: number = unique.values().next().value!;
798
- if (next.add(value) === false)
799
- next.errors.push(
800
- `The sequence tag value ${value} in string type is duplicated with other types`,
801
- );
802
- }
803
- };
804
-
805
- const validateInstanceSequence = (next: {
806
- type: "array" | "object" | "map" | "Uint8Array";
807
- tags: IMetadataTypeTag[][];
808
- errors: string[];
809
- add: (value: number) => boolean;
810
- }): void => {
811
- const unique: Set<number> = new Set();
812
- let count: number = 0;
813
- for (const tags of next.tags) {
814
- const value: number | null = ProtobufUtil.getSequence(tags);
815
- if (value === null) continue;
816
- unique.add(value);
817
- ++count;
818
- }
819
- if (unique.size && count !== next.tags.length)
820
- next.errors.push(
821
- `The sequence tag must be declared in every union type members`,
822
- );
823
- else if (unique.size > 1)
824
- next.errors.push(
825
- `The sequence tag value must be the same in ${next.type === "array" ? "an array" : "object"} type.`,
826
- );
827
- else if (unique.size === 1) {
828
- const value: number = unique.values().next().value!;
829
- if (next.add(value) === false)
830
- next.errors.push(
831
- `The sequence tag value ${value} in ${next.type} type is duplicated with other types`,
832
- );
833
- }
834
- };
835
- }
836
-
837
- const isDynamicObject = (obj: MetadataObjectType): boolean =>
838
- obj.properties[0]!.key.isSoleLiteral() === false;
839
-
840
- const BANNED_NATIVE_TYPES: Map<string, string | null> = new Map([
841
- ["Date", "string"],
842
- ["Boolean", "boolean"],
843
- ["BigInt", "bigint"],
844
- ["Number", "number"],
845
- ["String", "string"],
846
- ...[
847
- "Buffer",
848
- "Uint8ClampedArray",
849
- "Uint16Array",
850
- "Uint32Array",
851
- "BigUint64Array",
852
- "Int8Array",
853
- "Int16Array",
854
- "Int32Array",
855
- "BigInt64Array",
856
- "Float32Array",
857
- "Float64Array",
858
- "DataView",
859
- "ArrayBuffer",
860
- "SharedArrayBuffer",
861
- ].map((name) => [name, "Uint8Array"] as const),
862
- ["WeakSet", "Array"],
863
- ["WeakMap", "Map"],
864
- ]);
865
- const NUMBER_TYPES: Set<string> = new Set([
866
- "int32",
867
- "uint32",
868
- "int64",
869
- "uint64",
870
- "float",
871
- "double",
872
- ]);
873
- const BIGINT_TYPES = new Set(["int64", "uint64"]);
1
+ import ts from "typescript";
2
+
3
+ import { IMetadataTypeTag } from "../schemas/metadata/IMetadataTypeTag";
4
+ import { Metadata } from "../schemas/metadata/Metadata";
5
+ import { MetadataObjectType } from "../schemas/metadata/MetadataObjectType";
6
+ import { MetadataProperty } from "../schemas/metadata/MetadataProperty";
7
+ import { IProtobufProperty } from "../schemas/protobuf/IProtobufProperty";
8
+ import { IProtobufPropertyType } from "../schemas/protobuf/IProtobufPropertyType";
9
+ import { IProtobufSchema } from "../schemas/protobuf/IProtobufSchema";
10
+
11
+ import { ProtobufUtil } from "../programmers/helpers/ProtobufUtil";
12
+
13
+ import { TransformerError } from "../transformers/TransformerError";
14
+
15
+ import { ProtobufAtomic } from "../typings/ProtobufAtomic";
16
+ import { ValidationPipe } from "../typings/ValidationPipe";
17
+
18
+ import { MetadataCollection } from "./MetadataCollection";
19
+ import { MetadataFactory } from "./MetadataFactory";
20
+
21
+ export namespace ProtobufFactory {
22
+ export interface IProps {
23
+ method: string;
24
+ checker: ts.TypeChecker;
25
+ transformer?: ts.TransformationContext;
26
+ collection: MetadataCollection;
27
+ type: ts.Type;
28
+ }
29
+
30
+ /* -----------------------------------------------------------
31
+ METADATA COMPOSER
32
+ ----------------------------------------------------------- */
33
+ export const metadata = (props: IProps): Metadata => {
34
+ // COMPOSE METADATA WITH INDIVIDUAL VALIDATIONS
35
+ const result: ValidationPipe<Metadata, MetadataFactory.IError> =
36
+ MetadataFactory.analyze({
37
+ ...props,
38
+ transformer: props.transformer,
39
+ options: {
40
+ escape: false,
41
+ constant: true,
42
+ absorb: true,
43
+ validate: validate(),
44
+ },
45
+ });
46
+ if (result.success === false)
47
+ throw TransformerError.from({
48
+ code: `typia.protobuf.${props.method}`,
49
+ errors: result.errors,
50
+ });
51
+ return result.data;
52
+ };
53
+
54
+ /** @internal */
55
+ export const emplaceObject = (object: MetadataObjectType): void => {
56
+ for (const p of object.properties) emplaceProperty(p);
57
+ const properties: IProtobufProperty[] = object.properties
58
+ .map((p) => p.of_protobuf_)
59
+ .filter((p) => p !== undefined);
60
+ const unique: Set<number> = new Set(
61
+ properties
62
+ .filter((p) => p !== undefined)
63
+ .filter((p) => p.fixed === true)
64
+ .map((p) => p.union.map((u) => u.index))
65
+ .flat(),
66
+ );
67
+ let index: number = 1;
68
+ properties.forEach((schema) => {
69
+ if (schema.fixed === true)
70
+ index = Math.max(
71
+ index,
72
+ Math.max(...schema.union.map((u) => u.index)) + 1,
73
+ );
74
+ else {
75
+ for (const u of schema.union) {
76
+ while (unique.has(index) === true) ++index;
77
+ u.index = index;
78
+ unique.add(index);
79
+ }
80
+ ++index;
81
+ }
82
+ });
83
+ };
84
+
85
+ const emplaceProperty = (prop: MetadataProperty): void => {
86
+ const union: IProtobufPropertyType[] = [];
87
+ for (const native of prop.value.natives)
88
+ if (native.name === "Uint8Array")
89
+ union.push({
90
+ type: "bytes",
91
+ index: ProtobufUtil.getSequence(native.tags[0] ?? [])!,
92
+ });
93
+ union.push(...emplaceAtomic(prop.value).values());
94
+ for (const array of prop.value.arrays)
95
+ union.push({
96
+ type: "array",
97
+ array: array.type,
98
+ value: emplaceSchema(
99
+ array.type.value,
100
+ ) as IProtobufSchema.IArray["value"],
101
+ index: ProtobufUtil.getSequence(array.tags[0] ?? [])!,
102
+ });
103
+ for (const obj of prop.value.objects)
104
+ if (isDynamicObject(obj.type))
105
+ union.push({
106
+ type: "map",
107
+ map: obj.type,
108
+ key: emplaceSchema(
109
+ obj.type.properties[0]!.key,
110
+ ) as IProtobufSchema.IMap["key"],
111
+ value: emplaceSchema(
112
+ obj.type.properties[0]!.value,
113
+ ) as IProtobufSchema.IMap["value"],
114
+ index: ProtobufUtil.getSequence(obj.tags[0] ?? [])!,
115
+ });
116
+ else
117
+ union.push({
118
+ type: "object",
119
+ object: obj.type,
120
+ index: ProtobufUtil.getSequence(obj.tags[0] ?? [])!,
121
+ });
122
+ for (const map of prop.value.maps)
123
+ union.push({
124
+ type: "map",
125
+ map,
126
+ key: emplaceSchema(map.key) as IProtobufSchema.IMap["key"],
127
+ value: emplaceSchema(map.value) as IProtobufSchema.IMap["value"],
128
+ index: ProtobufUtil.getSequence(map.tags[0] ?? [])!,
129
+ });
130
+ prop.of_protobuf_ = {
131
+ union,
132
+ fixed: union.every((p) => p.index !== null),
133
+ };
134
+ };
135
+
136
+ const emplaceSchema = (metadata: Metadata): IProtobufSchema => {
137
+ for (const native of metadata.natives)
138
+ if (native.name === "Uint8Array")
139
+ return {
140
+ type: "bytes",
141
+ };
142
+ const atomic = emplaceAtomic(metadata);
143
+ if (atomic.size) return atomic.values().next().value!;
144
+ for (const array of metadata.arrays)
145
+ return {
146
+ type: "array",
147
+ array: array.type,
148
+ value: emplaceSchema(
149
+ array.type.value,
150
+ ) as IProtobufSchema.IArray["value"],
151
+ };
152
+ for (const obj of metadata.objects)
153
+ if (isDynamicObject(obj.type))
154
+ return {
155
+ type: "map",
156
+ map: obj.type,
157
+ key: emplaceSchema(
158
+ obj.type.properties[0]!.key,
159
+ ) as IProtobufSchema.IMap["key"],
160
+ value: emplaceSchema(
161
+ obj.type.properties[0]!.value,
162
+ ) as IProtobufSchema.IMap["value"],
163
+ };
164
+ else
165
+ return {
166
+ type: "object",
167
+ object: obj.type,
168
+ };
169
+ for (const map of metadata.maps)
170
+ return {
171
+ type: "map",
172
+ map,
173
+ key: emplaceSchema(map.key) as IProtobufSchema.IMap["key"],
174
+ value: emplaceSchema(map.value) as IProtobufSchema.IMap["value"],
175
+ };
176
+ throw new Error(
177
+ "Error on ProtobufFactory.emplaceSchema(): any type detected.",
178
+ );
179
+ };
180
+
181
+ const emplaceAtomic = (
182
+ meta: Metadata,
183
+ ): Map<ProtobufAtomic, IProtobufPropertyType> => {
184
+ const map: Map<ProtobufAtomic, IProtobufPropertyType> = new Map();
185
+
186
+ // CONSTANTS
187
+ for (const c of meta.constants)
188
+ if (c.type === "boolean")
189
+ map.set("bool", {
190
+ type: "bool",
191
+ index: getSequence(c.values[0]?.tags[0] ?? [])!,
192
+ });
193
+ else if (c.type === "bigint") {
194
+ const init: ProtobufAtomic.BigNumeric = getBigintType(
195
+ c.values.map((v) => BigInt(v.value)),
196
+ );
197
+ for (const value of c.values)
198
+ emplaceBigint({
199
+ map,
200
+ tags: value.tags,
201
+ init,
202
+ });
203
+ } else if (c.type === "number") {
204
+ const init: ProtobufAtomic.Numeric = getNumberType(
205
+ c.values.map((v) => v.value) as number[],
206
+ );
207
+ for (const value of c.values)
208
+ emplaceNumber({
209
+ map,
210
+ tags: value.tags,
211
+ init,
212
+ });
213
+ } else if (c.type === "string")
214
+ map.set("string", {
215
+ type: "string",
216
+ index: getSequence(c.values[0]?.tags[0] ?? [])!,
217
+ });
218
+
219
+ // TEMPLATE
220
+ if (meta.templates.length)
221
+ map.set("string", {
222
+ type: "string",
223
+ index: getSequence(meta.templates[0]?.tags[0] ?? [])!,
224
+ });
225
+
226
+ // ATOMICS
227
+ for (const atomic of meta.atomics)
228
+ if (atomic.type === "boolean")
229
+ map.set("bool", {
230
+ type: "bool",
231
+ index: getSequence(atomic.tags[0] ?? [])!,
232
+ });
233
+ else if (atomic.type === "bigint")
234
+ emplaceBigint({
235
+ map,
236
+ tags: atomic.tags,
237
+ init: "int64",
238
+ });
239
+ else if (atomic.type === "number")
240
+ emplaceNumber({
241
+ map,
242
+ tags: atomic.tags,
243
+ init: "double",
244
+ });
245
+ else if (atomic.type === "string")
246
+ map.set("string", {
247
+ type: "string",
248
+ index: getSequence(atomic.tags[0] ?? [])!,
249
+ });
250
+
251
+ // SORTING FOR VALIDATION REASON
252
+ return new Map(
253
+ Array.from(map).sort((x, y) => ProtobufUtil.compare(x[0], y[0])),
254
+ );
255
+ };
256
+
257
+ const emplaceBigint = (next: {
258
+ map: Map<ProtobufAtomic, IProtobufPropertyType>;
259
+ tags: IMetadataTypeTag[][];
260
+ init: ProtobufAtomic.BigNumeric;
261
+ }): void => {
262
+ if (next.tags.length === 0) {
263
+ next.map.set(next.init, {
264
+ type: "bigint",
265
+ name: next.init,
266
+ index: null!,
267
+ });
268
+ return;
269
+ }
270
+ for (const row of next.tags) {
271
+ const value: ProtobufAtomic.BigNumeric =
272
+ row.find(
273
+ (tag) =>
274
+ tag.kind === "type" &&
275
+ (tag.value === "int64" || tag.value === "uint64"),
276
+ )?.value ?? next.init;
277
+ next.map.set(next.init, {
278
+ type: "bigint",
279
+ name: value,
280
+ index: ProtobufUtil.getSequence(row)!,
281
+ });
282
+ }
283
+ };
284
+
285
+ const emplaceNumber = (next: {
286
+ map: Map<ProtobufAtomic, IProtobufPropertyType>;
287
+ tags: IMetadataTypeTag[][];
288
+ init: ProtobufAtomic.Numeric;
289
+ }): void => {
290
+ if (next.tags.length === 0) {
291
+ next.map.set(next.init, {
292
+ type: "number",
293
+ name: next.init,
294
+ index: null!,
295
+ });
296
+ return;
297
+ }
298
+ for (const row of next.tags) {
299
+ const value: ProtobufAtomic.Numeric =
300
+ row.find(
301
+ (tag) =>
302
+ tag.kind === "type" &&
303
+ (tag.value === "int32" ||
304
+ tag.value === "uint32" ||
305
+ tag.value === "int64" ||
306
+ tag.value === "uint64" ||
307
+ tag.value === "float" ||
308
+ tag.value === "double"),
309
+ )?.value ?? next.init;
310
+ next.map.set(value, {
311
+ type: "number",
312
+ name: value,
313
+ index: ProtobufUtil.getSequence(row)!,
314
+ });
315
+ }
316
+ };
317
+
318
+ const getBigintType = (values: bigint[]): ProtobufAtomic.BigNumeric =>
319
+ values.some((v) => v < 0) ? "int64" : "uint64";
320
+
321
+ const getNumberType = (values: number[]): ProtobufAtomic.Numeric =>
322
+ values.every((v) => Math.floor(v) === v)
323
+ ? values.every((v) => -2147483648 <= v && v <= 2147483647)
324
+ ? "int32"
325
+ : "int64"
326
+ : "double";
327
+
328
+ const getSequence = (tags: IMetadataTypeTag[]): number | null => {
329
+ const sequence = tags.find(
330
+ (t) =>
331
+ t.kind === "sequence" &&
332
+ typeof (t.schema as any)?.["x-protobuf-sequence"] === "number",
333
+ );
334
+ if (sequence === undefined) return null;
335
+ const value: number = Number(
336
+ (sequence.schema as any)["x-protobuf-sequence"],
337
+ );
338
+ return Number.isNaN(value) ? null : value;
339
+ };
340
+
341
+ /* -----------------------------------------------------------
342
+ VALIDATORS
343
+ ----------------------------------------------------------- */
344
+ const validate = () => {
345
+ const visited: WeakSet<MetadataObjectType> = new WeakSet();
346
+ return (meta: Metadata, explore: MetadataFactory.IExplore): string[] => {
347
+ const errors: string[] = [];
348
+ const insert = (msg: string) => errors.push(msg);
349
+
350
+ if (explore.top === true) {
351
+ const onlyObject: boolean =
352
+ meta.size() === 1 &&
353
+ meta.objects.length === 1 &&
354
+ meta.objects[0]!.type.properties.every((p) =>
355
+ p.key.isSoleLiteral(),
356
+ ) &&
357
+ meta.isRequired() === true &&
358
+ meta.nullable === false;
359
+ if (onlyObject === false)
360
+ insert("target type must be a sole and static object type");
361
+ }
362
+ for (const obj of meta.objects) {
363
+ if (visited.has(obj.type)) continue;
364
+ visited.add(obj.type);
365
+ validateObject({
366
+ object: obj.type,
367
+ errors,
368
+ });
369
+ try {
370
+ emplaceObject(obj.type);
371
+ } catch {}
372
+ }
373
+
374
+ //----
375
+ // NOT SUPPORTED TYPES
376
+ //----
377
+ const noSupport = (msg: string) => insert(`does not support ${msg}`);
378
+
379
+ // PROHIBIT ANY TYPE
380
+ if (meta.any) noSupport("any type");
381
+ // PROHIBIT FUNCTIONAL TYPE
382
+ if (meta.functions.length) noSupport("functional type");
383
+ // PROHIBIT TUPLE TYPE
384
+ if (meta.tuples.length) noSupport("tuple type");
385
+ // PROHIBIT SET TYPE
386
+ if (meta.sets.length) noSupport("Set type");
387
+ // NATIVE TYPE, BUT NOT Uint8Array
388
+ if (meta.natives.length)
389
+ for (const native of meta.natives) {
390
+ if (native.name === "Uint8Array") continue;
391
+
392
+ const instead = BANNED_NATIVE_TYPES.get(native.name);
393
+ if (instead === undefined) noSupport(`${native.name} type`);
394
+ else noSupport(`${native.name} type. Use ${instead} type instead.`);
395
+ }
396
+ //----
397
+ // ATOMIC CASES
398
+ //----
399
+ if (meta.atomics.length) {
400
+ const numbers = ProtobufUtil.getNumbers(meta);
401
+ const bigints = ProtobufUtil.getBigints(meta);
402
+
403
+ for (const type of ["int64", "uint64"])
404
+ if (numbers.has(type) && bigints.has(type))
405
+ insert(
406
+ `tags.Type<"${type}"> cannot be used in both number and bigint types. Recommend to remove from number type`,
407
+ );
408
+ }
409
+ //----
410
+ // ARRAY CASES
411
+ //----
412
+ // DO NOT ALLOW MULTI-DIMENSIONAL ARRAY
413
+ if (
414
+ meta.arrays.length &&
415
+ meta.arrays.some((array) => !!array.type.value.arrays.length)
416
+ )
417
+ noSupport("over two dimensional array type");
418
+ // CHILD OF ARRAY TYPE MUST BE REQUIRED
419
+ if (
420
+ meta.arrays.length &&
421
+ meta.arrays.some(
422
+ (array) =>
423
+ array.type.value.isRequired() === false ||
424
+ array.type.value.nullable === true,
425
+ )
426
+ )
427
+ noSupport("optional type in array");
428
+ // UNION IN ARRAY
429
+ if (
430
+ meta.arrays.length &&
431
+ meta.arrays.some(
432
+ (a) =>
433
+ a.type.value.size() > 1 &&
434
+ a.type.value.constants.length !== 1 &&
435
+ a.type.value.constants[0]?.values.length !== a.type.value.size(),
436
+ )
437
+ )
438
+ noSupport("union type in array");
439
+ // DO DYNAMIC OBJECT IN ARRAY
440
+ if (
441
+ meta.arrays.length &&
442
+ meta.arrays.some(
443
+ (a) =>
444
+ a.type.value.maps.length ||
445
+ (a.type.value.objects.length &&
446
+ a.type.value.objects.some(
447
+ (o) => ProtobufUtil.isStaticObject(o.type) === false,
448
+ )),
449
+ )
450
+ )
451
+ noSupport("dynamic object in array");
452
+ // UNION WITH ARRAY
453
+ if (meta.size() > 1 && meta.arrays.length)
454
+ noSupport("union type with array type");
455
+ //----
456
+ // OBJECT CASES
457
+ //----
458
+ // EMPTY PROPERTY
459
+ if (
460
+ meta.objects.length &&
461
+ meta.objects.some((obj) => obj.type.properties.length === 0)
462
+ )
463
+ noSupport("empty object type");
464
+ // MULTIPLE DYNAMIC KEY TYPED PROPERTIES
465
+ if (
466
+ meta.objects.length &&
467
+ meta.objects.some(
468
+ (obj) =>
469
+ obj.type.properties.filter((p) => !p.key.isSoleLiteral()).length >
470
+ 1,
471
+ )
472
+ )
473
+ noSupport(
474
+ "object type with multiple dynamic key typed properties. Keep only one.",
475
+ );
476
+ // STATIC AND DYNAMIC PROPERTIES ARE COMPATIBLE
477
+ if (
478
+ meta.objects.length &&
479
+ meta.objects.some(
480
+ (obj) =>
481
+ obj.type.properties.some((p) => p.key.isSoleLiteral()) &&
482
+ obj.type.properties.some((p) => !p.key.isSoleLiteral()),
483
+ )
484
+ )
485
+ noSupport(
486
+ "object type with mixed static and dynamic key typed properties. Keep statics or dynamic only.",
487
+ );
488
+ // DYNAMIC OBJECT, BUT PROPERTY VALUE TYPE IS ARRAY
489
+ if (
490
+ meta.objects.length &&
491
+ isDynamicObject(meta.objects[0]!.type) &&
492
+ meta.objects[0]!.type.properties.some((p) => !!p.value.arrays.length)
493
+ )
494
+ noSupport("dynamic object with array value type");
495
+ // UNION WITH DYNAMIC OBJECTTa
496
+ if (
497
+ meta.size() > 1 &&
498
+ meta.objects.length &&
499
+ isDynamicObject(meta.objects[0]!.type)
500
+ )
501
+ noSupport("union type with dynamic object type");
502
+ // UNION IN DYNAMIC PROPERTY VALUE
503
+ if (
504
+ meta.objects.length &&
505
+ meta.objects.some(
506
+ (obj) =>
507
+ isDynamicObject(obj.type) &&
508
+ obj.type.properties.some((p) => ProtobufUtil.isUnion(p.value)),
509
+ )
510
+ )
511
+ noSupport("union type in dynamic property");
512
+ //----
513
+ // MAP CASES
514
+ //----
515
+ // KEY TYPE IS UNION
516
+ if (
517
+ meta.maps.length &&
518
+ meta.maps.some((m) => ProtobufUtil.isUnion(m.key))
519
+ )
520
+ noSupport("union key typed map");
521
+ // KEY TYPE IS NOT ATOMIC
522
+ if (
523
+ meta.maps.length &&
524
+ meta.maps.some((m) => ProtobufUtil.getAtomics(m.key).size !== 1)
525
+ )
526
+ noSupport("non-atomic key typed map");
527
+ // MAP TYPE, BUT PROPERTY KEY TYPE IS OPTIONAL
528
+ if (
529
+ meta.maps.length &&
530
+ meta.maps.some((m) => m.key.isRequired() === false || m.key.nullable)
531
+ )
532
+ noSupport("optional key typed map");
533
+ // MAP TYPE, BUT VALUE TYPE IS ARRAY
534
+ if (meta.maps.length && meta.maps.some((m) => !!m.value.arrays.length))
535
+ noSupport("map type with array value type");
536
+ // UNION WITH MAP
537
+ if (meta.size() > 1 && meta.maps.length)
538
+ noSupport("union type with map type");
539
+ // UNION IN MAP
540
+ if (
541
+ meta.maps.length &&
542
+ meta.maps.some((m) => ProtobufUtil.isUnion(m.value))
543
+ )
544
+ noSupport("union type in map value type");
545
+ return errors;
546
+ };
547
+ };
548
+
549
+ /* -----------------------------------------------------------
550
+ SEQUENCE VALIDATOR
551
+ ----------------------------------------------------------- */
552
+ const validateObject = (next: {
553
+ object: MetadataObjectType;
554
+ errors: string[];
555
+ }): void => {
556
+ for (const property of next.object.properties)
557
+ validateProperty({
558
+ metadata: property.value,
559
+ errors: next.errors,
560
+ });
561
+
562
+ const entire: Map<number, string> = new Map();
563
+ const visitProperty = (p: MetadataProperty) => {
564
+ const local: Set<number> = new Set();
565
+ const tagger = (matrix: IMetadataTypeTag[][]): void => {
566
+ matrix.forEach((tags) => {
567
+ const value: number | null = ProtobufUtil.getSequence(tags);
568
+ if (value !== null) local.add(value);
569
+ });
570
+ };
571
+ for (const c of p.value.constants)
572
+ for (const v of c.values) tagger(v.tags);
573
+ for (const a of p.value.atomics) tagger(a.tags);
574
+ for (const t of p.value.templates) tagger(t.tags);
575
+ for (const o of p.value.objects) tagger(o.tags);
576
+ for (const a of p.value.arrays) tagger(a.tags);
577
+ for (const s of local)
578
+ if (entire.has(s))
579
+ next.errors.push(
580
+ `The Sequence<${s}> tag is duplicated in two properties (${JSON.stringify(entire.get(s))} and ${JSON.stringify(p.key.getSoleLiteral())})`,
581
+ );
582
+ else entire.set(s, p.key.getSoleLiteral()!);
583
+ };
584
+ for (const p of next.object.properties) visitProperty(p);
585
+ };
586
+
587
+ const validateProperty = (next: {
588
+ metadata: Metadata;
589
+ errors: string[];
590
+ }): void => {
591
+ let expected: number = 0;
592
+ const sequences: Set<number> = new Set();
593
+ const add = (value: number): boolean => {
594
+ if (sequences.has(value)) return false;
595
+ sequences.add(value);
596
+ ++expected;
597
+ return true;
598
+ };
599
+
600
+ for (const validator of [
601
+ validateBooleanSequence,
602
+ validateNumericSequences({
603
+ type: "bigint",
604
+ default: "int64",
605
+ categories: BIGINT_TYPES,
606
+ }),
607
+ validateNumericSequences({
608
+ type: "number",
609
+ default: "double",
610
+ categories: NUMBER_TYPES,
611
+ }),
612
+ validateStringSequence,
613
+ ])
614
+ validator({ metadata: next.metadata, errors: next.errors, add });
615
+ for (const array of next.metadata.arrays)
616
+ validateInstanceSequence({
617
+ type: "array",
618
+ tags: array.tags,
619
+ errors: next.errors,
620
+ add,
621
+ });
622
+ for (const object of next.metadata.objects)
623
+ validateInstanceSequence({
624
+ type: "object",
625
+ tags: object.tags,
626
+ errors: next.errors,
627
+ add,
628
+ });
629
+ for (const map of next.metadata.maps)
630
+ validateInstanceSequence({
631
+ type: "map",
632
+ tags: map.tags,
633
+ errors: next.errors,
634
+ add,
635
+ });
636
+ for (const native of next.metadata.natives)
637
+ if (native.name === "Uint8Array")
638
+ validateInstanceSequence({
639
+ type: "Uint8Array",
640
+ tags: native.tags,
641
+ errors: next.errors,
642
+ add,
643
+ });
644
+ };
645
+
646
+ const validateBooleanSequence = (next: {
647
+ metadata: Metadata;
648
+ errors: string[];
649
+ add: (value: number) => boolean;
650
+ }): void => {
651
+ // PREPARE EMPLACER
652
+ const unique: Set<number> = new Set();
653
+ let expected: number = 0;
654
+ let actual: number = 0;
655
+ const emplace = (matrix: IMetadataTypeTag[][]): void => {
656
+ for (const tags of matrix)
657
+ for (const tag of tags) {
658
+ const sequence = ProtobufUtil.getSequence([tag]);
659
+ if (sequence !== null) {
660
+ unique.add(sequence);
661
+ ++actual;
662
+ }
663
+ ++expected;
664
+ }
665
+ };
666
+
667
+ // GATHER SEQUENCE TAGS
668
+ for (const atomic of next.metadata.atomics)
669
+ if (atomic.type === "boolean") emplace(atomic.tags);
670
+ for (const constant of next.metadata.constants)
671
+ if (constant.type === "boolean")
672
+ for (const value of constant.values) emplace(value.tags);
673
+
674
+ // PREDICATE
675
+ if (unique.size && actual !== expected)
676
+ next.errors.push(
677
+ `The sequence tag must be declared in every union type members`,
678
+ );
679
+ else if (unique.size > 1)
680
+ next.errors.push(
681
+ `The sequence tag value must be the same in boolean type (including literal types)`,
682
+ );
683
+ else if (unique.size === 1) {
684
+ const value: number = unique.values().next().value!;
685
+ if (next.add(value) === false)
686
+ next.errors.push(
687
+ `The sequence tag value ${value} in boolean type is duplicated with other types`,
688
+ );
689
+ }
690
+ };
691
+
692
+ const validateNumericSequences =
693
+ (config: {
694
+ type: "number" | "bigint";
695
+ default: string;
696
+ categories: Set<string>;
697
+ }) =>
698
+ (next: {
699
+ metadata: Metadata;
700
+ errors: string[];
701
+ add: (value: number) => boolean;
702
+ }): void => {
703
+ // FIND TYPE CATEGORIES
704
+ const categories: Set<string> = new Set();
705
+ const getType = (tags: IMetadataTypeTag[]): string => {
706
+ const found: IMetadataTypeTag | undefined = tags.find(
707
+ (t) => t.kind === "type" && config.categories.has(t.value),
708
+ );
709
+ return found?.value ?? config.default;
710
+ };
711
+ const exploreCategory = (matrix: IMetadataTypeTag[][]): void => {
712
+ for (const tags of matrix) categories.add(getType(tags));
713
+ };
714
+ for (const atomic of next.metadata.atomics)
715
+ if (atomic.type === config.type) exploreCategory(atomic.tags);
716
+ for (const constant of next.metadata.constants)
717
+ if (constant.type === config.type)
718
+ for (const value of constant.values) exploreCategory(value.tags);
719
+
720
+ // ITERATE TYPE CATEGORIES
721
+ for (const category of categories) {
722
+ const unique: Set<number> = new Set();
723
+ let expected: number = 0;
724
+ let actual: number = 0;
725
+ const emplace = (tags: IMetadataTypeTag[]): void => {
726
+ const sequence: number | null = ProtobufUtil.getSequence(tags);
727
+ if (sequence !== null) {
728
+ unique.add(sequence);
729
+ ++actual;
730
+ }
731
+ ++expected;
732
+ };
733
+
734
+ for (const atomic of next.metadata.atomics)
735
+ if (atomic.type === config.type)
736
+ for (const tags of atomic.tags)
737
+ if (getType(tags) === category) emplace(tags);
738
+ for (const constant of next.metadata.constants)
739
+ if (constant.type === config.type)
740
+ for (const value of constant.values)
741
+ for (const tags of value.tags)
742
+ if (getType(tags) === category) emplace(tags);
743
+
744
+ if (unique.size && actual !== expected) {
745
+ next.errors.push(
746
+ `The sequence tag must be declared in every union type members`,
747
+ );
748
+ } else if (unique.size > 1)
749
+ next.errors.push(
750
+ `The sequence tag value must be the same in ${config.type} type (including literal types)`,
751
+ );
752
+ else if (unique.size === 1) {
753
+ const value: number = unique.values().next().value!;
754
+ if (next.add(value) === false)
755
+ next.errors.push(
756
+ `The sequence tag value ${value} in ${config.type} type is duplicated with other types`,
757
+ );
758
+ }
759
+ }
760
+ };
761
+
762
+ const validateStringSequence = (next: {
763
+ metadata: Metadata;
764
+ errors: string[];
765
+ add: (value: number) => boolean;
766
+ }): void => {
767
+ const unique: Set<number> = new Set();
768
+ let expected: number = 0;
769
+ let actual: number = 0;
770
+ const emplace = (matrix: IMetadataTypeTag[][]): void => {
771
+ for (const tags of matrix)
772
+ for (const tag of tags) {
773
+ const sequence = ProtobufUtil.getSequence([tag]);
774
+ if (sequence !== null) {
775
+ unique.add(sequence);
776
+ ++actual;
777
+ }
778
+ ++expected;
779
+ }
780
+ };
781
+ for (const atomic of next.metadata.atomics)
782
+ if (atomic.type === "string") emplace(atomic.tags);
783
+ for (const constant of next.metadata.constants)
784
+ if (constant.type === "string")
785
+ for (const value of constant.values) emplace(value.tags);
786
+ for (const template of next.metadata.templates) emplace(template.tags);
787
+
788
+ if (unique.size && actual !== expected)
789
+ next.errors.push(
790
+ `The sequence tag must be declared in every union type members`,
791
+ );
792
+ else if (unique.size > 1)
793
+ next.errors.push(
794
+ `The sequence tag value must be the same in string types including literal and template types`,
795
+ );
796
+ else if (unique.size === 1) {
797
+ const value: number = unique.values().next().value!;
798
+ if (next.add(value) === false)
799
+ next.errors.push(
800
+ `The sequence tag value ${value} in string type is duplicated with other types`,
801
+ );
802
+ }
803
+ };
804
+
805
+ const validateInstanceSequence = (next: {
806
+ type: "array" | "object" | "map" | "Uint8Array";
807
+ tags: IMetadataTypeTag[][];
808
+ errors: string[];
809
+ add: (value: number) => boolean;
810
+ }): void => {
811
+ const unique: Set<number> = new Set();
812
+ let count: number = 0;
813
+ for (const tags of next.tags) {
814
+ const value: number | null = ProtobufUtil.getSequence(tags);
815
+ if (value === null) continue;
816
+ unique.add(value);
817
+ ++count;
818
+ }
819
+ if (unique.size && count !== next.tags.length)
820
+ next.errors.push(
821
+ `The sequence tag must be declared in every union type members`,
822
+ );
823
+ else if (unique.size > 1)
824
+ next.errors.push(
825
+ `The sequence tag value must be the same in ${next.type === "array" ? "an array" : "object"} type.`,
826
+ );
827
+ else if (unique.size === 1) {
828
+ const value: number = unique.values().next().value!;
829
+ if (next.add(value) === false)
830
+ next.errors.push(
831
+ `The sequence tag value ${value} in ${next.type} type is duplicated with other types`,
832
+ );
833
+ }
834
+ };
835
+ }
836
+
837
+ const isDynamicObject = (obj: MetadataObjectType): boolean =>
838
+ obj.properties[0]!.key.isSoleLiteral() === false;
839
+
840
+ const BANNED_NATIVE_TYPES: Map<string, string | null> = new Map([
841
+ ["Date", "string"],
842
+ ["Boolean", "boolean"],
843
+ ["BigInt", "bigint"],
844
+ ["Number", "number"],
845
+ ["String", "string"],
846
+ ...[
847
+ "Buffer",
848
+ "Uint8ClampedArray",
849
+ "Uint16Array",
850
+ "Uint32Array",
851
+ "BigUint64Array",
852
+ "Int8Array",
853
+ "Int16Array",
854
+ "Int32Array",
855
+ "BigInt64Array",
856
+ "Float32Array",
857
+ "Float64Array",
858
+ "DataView",
859
+ "ArrayBuffer",
860
+ "SharedArrayBuffer",
861
+ ].map((name) => [name, "Uint8Array"] as const),
862
+ ["WeakSet", "Array"],
863
+ ["WeakMap", "Map"],
864
+ ]);
865
+ const NUMBER_TYPES: Set<string> = new Set([
866
+ "int32",
867
+ "uint32",
868
+ "int64",
869
+ "uint64",
870
+ "float",
871
+ "double",
872
+ ]);
873
+ const BIGINT_TYPES = new Set(["int64", "uint64"]);