@rbxts/netweave 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2064 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Types
6
+
7
+ The type vocabulary. One declaration yields the payload type, the validation, and the
8
+ serialisation — you never write a schema and a type guard that can drift apart.
9
+
10
+ ```lua
11
+ local t = require(Packages.netweave).types
12
+
13
+ local Shot = t.struct({
14
+ origin = t.vector3,
15
+ direction = t.unitVector3,
16
+ seq = t.u16,
17
+ })
18
+ -- Shot : Type<{ origin: Vector3, direction: Vector3, seq: number }>
19
+ ```
20
+
21
+ Constraints live inside the type rather than beside it. `t.f32(-90, 90)` is a pitch, and the
22
+ codec derives both the range check and a narrower encoding from that one expression.
23
+
24
+ :::caution
25
+ Payload inference needs Luau's new type solver. Without it the library still loads and runs,
26
+ but nothing here is checked. See `docs/DESIGN-API.md` §7.
27
+ :::
28
+ ]=]
29
+
30
+ --[[
31
+ A type is inert. It computes nothing and encodes nothing; the codec lowers it to an IR and runs
32
+ the layout passes over that (`PLAN-M1` D-1). Keeping it inert is what creates the layout window
33
+ at all — ByteNet builds closures straight from the schema and so can never see two fields at
34
+ once (`RESEARCH §3.8-N`).
35
+ ]]
36
+
37
+ --[=[
38
+ @type Encoding "u8" | "u16" | "u32" | "u53" | "i8" | "i16" | "i32" | "i53" | "f32" | "f64"
39
+ @within Types
40
+
41
+ Storage width for a number, and the component width of a vector.
42
+
43
+ This is an upper bound, not a promise: a range narrower than the encoding lets the codec store
44
+ fewer bytes and subtract the minimum, so `t.u16(1000, 1255)` occupies one byte on the wire.
45
+ ]=]
46
+ export type Encoding = "u8" | "u16" | "u32" | "u53" | "i8" | "i16" | "i32" | "i53" | "f32" | "f64"
47
+
48
+ --[=[
49
+ @type Kind "boolean" | "number" | "string" | "buffer" | "vector2" | "vector3" | "cframe" | "color3" | "instance" | "enum" | "literal" | "optional" | "array" | "map" | "struct" | "union"
50
+ @within Types
51
+
52
+ What a descriptor describes. The codec dispatches on this.
53
+ ]=]
54
+ export type Kind =
55
+ "boolean"
56
+ | "number"
57
+ | "string"
58
+ | "buffer"
59
+ | "vector2"
60
+ | "vector3"
61
+ | "cframe"
62
+ | "color3"
63
+ | "instance"
64
+ | "enum"
65
+ | "literal"
66
+ | "optional"
67
+ | "array"
68
+ | "map"
69
+ | "struct"
70
+ | "union"
71
+
72
+ --[=[
73
+ @interface Descriptor
74
+ @within Types
75
+ .kind Kind
76
+ .encoding Encoding? -- numbers, and vector components
77
+ .min number? -- value range for numbers, length range for strings, buffers and arrays
78
+ .max number?
79
+ .step number? -- `quantized`: the size of one wire level
80
+ .utf8 boolean? -- `string`: the bytes must decode as UTF-8
81
+ .pattern string? -- `string`: a Lua pattern the whole value must match
82
+ .class string? -- `instance`: the class an arrival must be, or nil for any
83
+ .descendantOf Instance? -- `instance`: the container an arrival must be inside
84
+ .variants { string }? -- `enum`: variant names, sorted. Wire index is the position here
85
+ .literal (string | boolean | number)? -- `literal`: the one value, which costs nothing on the wire
86
+ .default (string | boolean | number)? -- `optional`: what an absent value reads as, and what is not sent
87
+ .unit boolean? -- `vector3`: the magnitude must be 1
88
+ .inner Descriptor? -- `optional`
89
+ .element Descriptor? -- `array`
90
+ .key Descriptor? -- `map`
91
+ .value Descriptor? -- `map`
92
+ .fields { [string]: Descriptor }? -- `struct`
93
+ .branches { [string]: Descriptor }? -- `union`: branch name to schema
94
+ .order { string }? -- `struct`: field names, sorted. Wire order is the order here
95
+
96
+ An untyped type. Most fields are unused by most kinds; the codec reads only the ones its
97
+ `kind` implies.
98
+ ]=]
99
+ export type Descriptor = {
100
+ kind: Kind,
101
+ encoding: Encoding?,
102
+ min: number?,
103
+ max: number?,
104
+ step: number?,
105
+ class: string?,
106
+ descendantOf: Instance?,
107
+ utf8: boolean?,
108
+ pattern: string?,
109
+ variants: { string }?,
110
+ literal: (string | boolean | number)?,
111
+ default: (string | boolean | number)?,
112
+ unit: boolean?,
113
+ inner: Descriptor?,
114
+ element: Descriptor?,
115
+ key: Descriptor?,
116
+ value: Descriptor?,
117
+ fields: { [string]: Descriptor }?,
118
+ branches: { [string]: Descriptor }?,
119
+ order: { string }?,
120
+ }
121
+
122
+ --[=[
123
+ @type Type<T> Descriptor & { __payload: T }
124
+ @within Types
125
+
126
+ A descriptor carrying the payload type it decodes to. `__payload` is a phantom: never assigned
127
+ at runtime, never read at runtime, present so a `type function` can pull `T` back out.
128
+ ]=]
129
+ --[[
130
+ `Descriptor` and `Type<T>` duplicate their fields on purpose, and must stay in sync.
131
+
132
+ Luau refuses a recursive type instantiated at different parameters, so `Type<T>` cannot both be
133
+ generic and refer to itself for its children. Expressing it as `Descriptor & { __payload: T }`
134
+ does compile, but breaks two things verified working in `spike/inference/`: a metatable-wrapped
135
+ table stops being a subtype of the intersection, so `t.u8` is no longer usable where a
136
+ `Type<number>` is expected; and `readproperty` inside a `type function` can no longer see
137
+ through it, so `t.struct` stops inferring. A flat duplicate keeps both.
138
+
139
+ `tests/types_ok.luau` asserts the two stay structurally compatible, so drift is a build break
140
+ rather than a surprise.
141
+ ]]
142
+ export type Type<T> = {
143
+ kind: Kind,
144
+ encoding: Encoding?,
145
+ min: number?,
146
+ max: number?,
147
+ step: number?,
148
+ class: string?,
149
+ descendantOf: Instance?,
150
+ utf8: boolean?,
151
+ pattern: string?,
152
+ variants: { string }?,
153
+ literal: (string | boolean | number)?,
154
+ default: (string | boolean | number)?,
155
+ unit: boolean?,
156
+ inner: Descriptor?,
157
+ element: Descriptor?,
158
+ key: Descriptor?,
159
+ value: Descriptor?,
160
+ fields: { [string]: Descriptor }?,
161
+ branches: { [string]: Descriptor }?,
162
+ order: { string }?,
163
+ __payload: T,
164
+ }
165
+
166
+ --[[
167
+ A callable type's table half.
168
+
169
+ `Ranged<T>`, `Text`, `Componented<T>` and `Classed` are `Type<T> & ((…) -> Type<T>)`: an
170
+ intersection, because that is the only spelling that checks the **types** of the arguments and
171
+ still lets the value be used bare. A `typeof(setmetatable(…))` alias enforced the argument count
172
+ alone, so `t.u8(0, "b")` and `t.instance(5)` were accepted and the wrong storage was declared
173
+ (M4-1; `PLAN-M5` D-1).
174
+
175
+ The cost is this function. To a `type function` an intersection is not a table, so
176
+ `readproperty("__payload")` on one answers nothing — every payload extraction below has to take
177
+ the table half out first. Private, because nothing outside needs the shape; the two other
178
+ modules that read a schema's payload carry their own copy, since a `type function` cannot
179
+ reference an outer local and calling across a `require` needs the name exported.
180
+ ]]
181
+ -- selene: allow(undefined_variable)
182
+ type function carrierOf(ty: type): type
183
+ if not ty:is("intersection") then
184
+ return ty
185
+ end
186
+
187
+ for _, part in ty:components() do
188
+ if part:is("table") and part:readproperty(types.singleton("__payload")) then
189
+ return part
190
+ end
191
+ end
192
+
193
+ return ty
194
+ end
195
+
196
+ --[=[
197
+ @type PayloadOf<T> T
198
+ @within Types
199
+
200
+ Extracts the payload type out of a `Type<T>`.
201
+
202
+ ```lua
203
+ type Shot = t.PayloadOf<typeof(ShotType)>
204
+ ```
205
+ ]=]
206
+ -- selene: allow(undefined_variable)
207
+ export type function PayloadOf(ty)
208
+ ty = carrierOf(ty)
209
+
210
+ --[[ Asked before `readproperty`, which raises its own message on a non-table — `type.readproperty:
211
+ expected self to be either a table, but got number instead` — printed verbatim at the call
212
+ site in a game's declaration file, where nothing about it names netweave or the fix. ]]
213
+ local advice = "PayloadOf takes a netweave type and extracts what it carries: "
214
+ .. "t.PayloadOf<typeof(ShotType)>, where ShotType came from t.struct, t.u8 or t.array. "
215
+ .. "A payload type is what comes out of it, not what goes in."
216
+
217
+ if not ty:is("table") then
218
+ error(advice)
219
+ end
220
+
221
+ local payload = ty:readproperty(types.singleton("__payload"))
222
+
223
+ if not payload then
224
+ error(advice)
225
+ end
226
+
227
+ return payload
228
+ end
229
+
230
+ --[[
231
+ **The Q5 instantiation, which this type function needed and did not have.**
232
+
233
+ `spike/declare/README.md` Q5, measured again by M4's security report: an `export type function`
234
+ that its own module never references does not reduce for a module that requires it. It becomes an
235
+ error type — silently — so `type Shot = t.PayloadOf<typeof(ShotType)>` named nothing, and
236
+ `local wrong: Shot = { origin = "no" }` compiled. Every game function annotated with the alias
237
+ the docstring above prescribes was unchecked.
238
+
239
+ `StructPayload` and `EnumPayload` never had the problem because `t.struct` and `t.enum` name them
240
+ in their own signatures. `PayloadOf` is the one nothing else in this file mentions, and one
241
+ reference is enough. `Trust.luau` carries the same two lines for the same reason.
242
+ ]]
243
+ type _instantiatePayloadOf = PayloadOf<Type<{ probe: boolean }>>
244
+
245
+ --[[
246
+ **The two-parameter seam, and the one-parameter one behind it.**
247
+
248
+ `t.map<K, V>(key: Type<K>, value: Type<V>)` compiled for primitives and failed for the schema
249
+ every replicated-entities game writes first: `t.map(t.u16, Entity)` was `Expected this to be
250
+ exactly 'unknown', but got '{ hp: number }'`, because the solver does not unify a generic
251
+ parameter against a type-function result — `Entity` is a `Type<StructPayload<…>>`, and a `T`
252
+ read out of that is `unknown`, not the struct (M4-1, 중대). Measured next: `t.optional(Entity)`
253
+ and `t.array(Entity)` had the same seam outside a spec literal, so `nw.validate(t.optional(S),
254
+ v)` returned an unbranded `unknown?` and the brand never applied on that path.
255
+
256
+ Reading `__payload` directly is what `t.struct` has always done and what works. Three small
257
+ type functions, one per constructor, each with its own message, rather than `PayloadOf` reused,
258
+ because the message prints verbatim at the call site and has to name the constructor that was
259
+ called. The extraction is spelled out three times because a type function cannot reference an
260
+ outer local — the analyzer refuses it as a syntax error.
261
+ ]]
262
+
263
+ --[=[
264
+ @type OptionalPayload<I, D> I? | I
265
+ @within Types
266
+
267
+ What [Types.optional] carries: the inner type's payload, or nil — and with a default, the
268
+ payload alone, because an absent value reads as the default. Applied for you.
269
+ ]=]
270
+ --[[ A schema built at runtime reaches these through `any`, and `any` carries no `__payload`. It
271
+ stays `any` on the way out rather than being refused: the analyzer has been bypassed on
272
+ purpose, and the runtime `check()` is the guard on that path. ]]
273
+ -- selene: allow(undefined_variable)
274
+ export type function OptionalPayload(inner: type, default: type)
275
+ if inner:is("any") then
276
+ return types.any
277
+ end
278
+
279
+ inner = carrierOf(inner)
280
+
281
+ local advice = "t.optional takes a netweave type, as in t.optional(t.u16) or t.optional(Entity). "
282
+ .. "What was passed carries no payload, so it did not come from t.u8, t.struct, t.enum or "
283
+ .. "another constructor"
284
+
285
+ if not inner:is("table") then
286
+ error(advice)
287
+ end
288
+
289
+ local payload = inner:readproperty(types.singleton("__payload"))
290
+
291
+ if not payload then
292
+ error(advice)
293
+ end
294
+
295
+ --[[ An absent second argument arrives as `unknown` (measured, `spike/additions`), and nil is
296
+ the spelling of "no default" a caller could write out. ]]
297
+ if default:is("unknown") or default:is("nil") then
298
+ return types.unionof(payload :: type, types.singleton(nil))
299
+ end
300
+
301
+ --[[ The default's tag against the payload's, for the primitives the runtime admits: a string
302
+ default on a number field is a diagnostic here rather than a raise at the declaration. A
303
+ singleton's tag is "singleton", so its value's kind is read through it. ]]
304
+ local function primitive(ty: type): string?
305
+ if ty:is("singleton") then
306
+ return type(ty:value())
307
+ end
308
+
309
+ if ty:is("number") or ty:is("string") or ty:is("boolean") then
310
+ return ty.tag
311
+ end
312
+
313
+ if ty:is("union") then
314
+ local kind: string? = nil
315
+
316
+ for _, component in ty:components() do
317
+ local each = primitive(component)
318
+
319
+ if each == nil or (kind ~= nil and each ~= kind) then
320
+ return nil
321
+ end
322
+
323
+ kind = each
324
+ end
325
+
326
+ return kind
327
+ end
328
+
329
+ return nil
330
+ end
331
+
332
+ local wanted = primitive(payload :: type)
333
+ local given = primitive(default)
334
+
335
+ if wanted == nil then
336
+ error(
337
+ "t.optional takes a default only for a number, a string, a boolean or an enum: those are the "
338
+ .. "values two peers can compare, and a table default would be a fresh table on every read"
339
+ )
340
+ end
341
+
342
+ if given ~= wanted then
343
+ error(
344
+ `t.optional was given a default of the wrong kind: this field carries a {wanted}, and the `
345
+ .. `default is a {given or default.tag}`
346
+ )
347
+ end
348
+
349
+ return payload :: type
350
+ end
351
+
352
+ --[=[
353
+ @type ArrayPayload<E> { E }
354
+ @within Types
355
+
356
+ What [Types.array] carries: a list of the element type's payload. Applied for you.
357
+ ]=]
358
+ -- selene: allow(undefined_variable)
359
+ export type function ArrayPayload(element: type)
360
+ if element:is("any") then
361
+ return types.newtable(nil, { index = types.number, readresult = types.any, writeresult = types.any })
362
+ end
363
+
364
+ element = carrierOf(element)
365
+
366
+ local advice = "t.array takes a netweave element type, as in t.array(t.u8) or t.array(Entity, 100). "
367
+ .. "What was passed carries no payload, so it did not come from t.u8, t.struct, t.enum or "
368
+ .. "another constructor"
369
+
370
+ if not element:is("table") then
371
+ error(advice)
372
+ end
373
+
374
+ local payload = element:readproperty(types.singleton("__payload"))
375
+
376
+ if not payload then
377
+ error(advice)
378
+ end
379
+
380
+ return types.newtable(
381
+ nil,
382
+ { index = types.number, readresult = payload :: type, writeresult = payload :: type }
383
+ )
384
+ end
385
+
386
+ --[=[
387
+ @type MapPayload<K, V> { [K]: V }
388
+ @within Types
389
+
390
+ What [Types.map] carries: the key type's payload indexing the value type's. Applied for you.
391
+ ]=]
392
+ -- selene: allow(undefined_variable)
393
+ export type function MapPayload(key, value)
394
+ local advice = "t.map takes two netweave types, a key and a value, as in t.map(t.u16, Entity). "
395
+ .. "One of them carries no payload, so it did not come from t.u16, t.string, t.struct or "
396
+ .. "another constructor"
397
+
398
+ local function payloadOf(carrier: type): type
399
+ if carrier:is("any") then
400
+ return types.any
401
+ end
402
+
403
+ carrier = carrierOf(carrier)
404
+
405
+ if not carrier:is("table") then
406
+ error(advice)
407
+ end
408
+
409
+ local payload = carrier:readproperty(types.singleton("__payload"))
410
+
411
+ if not payload then
412
+ error(advice)
413
+ end
414
+
415
+ return payload
416
+ end
417
+
418
+ local index = payloadOf(key)
419
+ local payload = payloadOf(value)
420
+
421
+ return types.newtable(nil, { index = index, readresult = payload, writeresult = payload })
422
+ end
423
+
424
+ --[=[
425
+ @type StructPayload<F> F
426
+ @within Types
427
+
428
+ Maps a table of types to a table of their payloads. This is what lets [Types.struct] infer its
429
+ own result.
430
+
431
+ Rarely written by hand — `t.struct` applies it for you.
432
+ ]=]
433
+ --[[
434
+ Luau has no mapped types, so without this a heterogeneous struct cannot even be expressed: the
435
+ naive `struct<V>(fields: { [string]: Type<V> })` signature unifies `V` across fields and
436
+ rejects `{ id = t.u8, name = t.string }` outright (`spike/inference/README.md`, Q1 candidate A).
437
+ ]]
438
+ -- selene: allow(undefined_variable)
439
+ export type function StructPayload(fields)
440
+ local result = types.newtable()
441
+
442
+ for key, property in fields:properties() do
443
+ --[[ Through `carrierOf` before the shape test, not after: a callable constructor is an
444
+ intersection and `is("table")` is false for one, so the guard would refuse every
445
+ `t.u8` in a struct (`PLAN-M5` D-1). ]]
446
+ local field = if property.read then carrierOf(property.read) else nil
447
+
448
+ if not field or not field:is("table") then
449
+ error("a struct field is not a netweave type")
450
+ end
451
+
452
+ local payload = field:readproperty(types.singleton("__payload"))
453
+
454
+ if not payload then
455
+ error("a struct field is not a netweave type")
456
+ end
457
+
458
+ result:setproperty(key, payload)
459
+ end
460
+
461
+ return result
462
+ end
463
+
464
+ --[=[
465
+ @type EnumPayload<V> V
466
+ @within Types
467
+
468
+ Turns a set of variant names into a union of string singletons. Applied by [Types.enum].
469
+ ]=]
470
+ --[[
471
+ The variants have to be written as table *keys* because Luau widens `{"a", "b"}` to `{string}`,
472
+ losing exactly the information this exists to preserve.
473
+ ]]
474
+ --[=[
475
+ @type UnionPayload<B> B
476
+ @within Types
477
+
478
+ Turns a table of branch schemas into a **discriminated union** of `{ tag, value }` pairs. Applied
479
+ by [Types.union].
480
+
481
+ `t.union({ move = M, attack = A })` carries
482
+ `{ tag: "move", value: MovePayload } | { tag: "attack", value: AttackPayload }`, so
483
+ `if action.tag == "move" then` narrows `action.value` to the move payload and nothing else.
484
+ ]=]
485
+ --[[
486
+ The `tag`/`value` shape rather than `{ move: M? } | { attack: A? }`, and the reason is narrowing
487
+ rather than taste. Luau narrows a union of tables on a **singleton property**, so comparing `tag`
488
+ against a literal selects one component and its `value` with it. A union of tables distinguished
489
+ by which optional field is present narrows on `if action.move then`, which leaves the other
490
+ branches' fields readable as `nil` — the reader can still write `action.attack` and get no error,
491
+ which is the whole failure the tag exists to prevent.
492
+ ]]
493
+ -- selene: allow(undefined_variable)
494
+ export type function UnionPayload(branches)
495
+ local result = nil
496
+
497
+ for key, property in branches:properties() do
498
+ --[[ `carrierOf` first, for the reason `StructPayload` gives. ]]
499
+ local branch = if property.read then carrierOf(property.read) else nil
500
+
501
+ if not branch or not branch:is("table") then
502
+ error("a union branch is not a netweave type")
503
+ end
504
+
505
+ local payload = branch:readproperty(types.singleton("__payload"))
506
+
507
+ if not payload then
508
+ error("a union branch is not a netweave type")
509
+ end
510
+
511
+ local case = types.newtable()
512
+ case:setproperty(types.singleton("tag"), key)
513
+ case:setproperty(types.singleton("value"), payload)
514
+
515
+ result = if result then types.unionof(result, case) else case
516
+ end
517
+
518
+ if not result then
519
+ error("a union needs at least one branch")
520
+ end
521
+
522
+ return result
523
+ end
524
+
525
+ -- selene: allow(undefined_variable)
526
+ export type function EnumPayload(variants)
527
+ local result = nil
528
+
529
+ for key in variants:properties() do
530
+ result = if result then types.unionof(result, key) else key
531
+ end
532
+
533
+ if not result then
534
+ error("an enum needs at least one variant")
535
+ end
536
+
537
+ return result
538
+ end
539
+
540
+ --[=[
541
+ @type Ranged<T> Type<T>
542
+ @within Types
543
+
544
+ A type that is usable bare and callable to constrain it. Both forms appear in the same
545
+ declaration:
546
+
547
+ ```lua
548
+ seq = t.u16, -- the encoding's full range
549
+ slot = t.u8(0, 2), -- narrowed, and stored in fewer bits
550
+ ```
551
+
552
+ The pair means a **value** range for numbers and a **length** range for strings and buffers.
553
+ ]=]
554
+ export type Ranged<T> = Type<T> & ((min: number, max: number) -> Type<T>)
555
+
556
+ --[=[
557
+ @interface TextOptions
558
+ @within Types
559
+ .utf8 boolean? -- the bytes must decode as UTF-8
560
+ .pattern string? -- a Lua pattern the whole value must match, anchored by netweave
561
+ .charset string? -- a Lua character class every byte must belong to, written without the brackets
562
+
563
+ What [Types.string] accepts after its length bounds.
564
+
565
+ `charset` and `pattern` say the same kind of thing and cannot both be given. `charset = "%w_"`
566
+ is stored as the pattern `[%w_]*`, so two peers declaring it either way agree; it exists
567
+ because a class with one repetition is the one shape of pattern whose cost is linear in the
568
+ value whatever the length, and a peer chooses the length.
569
+ ]=]
570
+ export type TextOptions = {
571
+ utf8: boolean?,
572
+ pattern: string?,
573
+ charset: string?,
574
+ }
575
+
576
+ --[=[
577
+ @type Text Type<string>
578
+ @within Types
579
+
580
+ A string type: callable to bound the length, and to say what the bytes may contain.
581
+
582
+ ```lua
583
+ t.string(1, 20) -- a length, as before
584
+ t.string(1, 20, { utf8 = true }) -- and valid UTF-8
585
+ t.string(1, 20, { charset = "%w_" }) -- and only word characters, at any length
586
+ t.string(1, 20, { pattern = "%a+%d?" }) -- or a shape, when a set is not enough
587
+ ```
588
+
589
+ :::note
590
+ A `pattern` with more than one unbounded item (`*`, `+`, `-`) is refused past a length the
591
+ matcher can afford, because the matcher backtracks and a peer chooses the bytes. A `charset` is
592
+ one class and one repetition, so it is never refused for cost.
593
+ :::
594
+ ]=]
595
+ export type Text = Type<string> & ((min: number, max: number, options: TextOptions?) -> Type<string>)
596
+
597
+ --[=[
598
+ @type Componented<T> Type<T>
599
+ @within Types
600
+
601
+ A vector type, callable with the schema its **components** are carried at.
602
+
603
+ ```lua
604
+ t.vector3 -- three f32, twelve bytes
605
+ t.vector3(t.i16(-2048, 2048)) -- three u16, six
606
+ t.unitVector3(t.quantized(-1, 1, 2 / 254)) -- three u8, three
607
+ ```
608
+ ]=]
609
+ export type Componented<T> = Type<T> & ((component: Type<number>) -> Type<T>)
610
+
611
+ --[=[
612
+ @interface InstanceOptions
613
+ @within Types
614
+ .descendantOf Instance? -- the container an arrival must be inside
615
+
616
+ What [Types.instance] accepts after its class name.
617
+ ]=]
618
+ export type InstanceOptions = {
619
+ descendantOf: Instance?,
620
+ }
621
+
622
+ --[=[
623
+ @type Classed Type<Instance>
624
+ @within Types
625
+
626
+ An instance type, callable with a class name to restrict what may arrive — and with a container
627
+ to restrict where it may have come from.
628
+
629
+ ```lua
630
+ t.instance("Sound")
631
+ t.instance("BasePart", { descendantOf = workspace })
632
+ ```
633
+ ]=]
634
+ export type Classed = Type<Instance> & ((className: string, options: InstanceOptions?) -> Type<Instance>)
635
+
636
+ --[[
637
+ ~~`f32` is `-2^24..2^24` and `f64` is `-2^53..2^53`.~~ **Those were the spans in which each
638
+ encoding represents every *integer* exactly, and using them as the value range refused ordinary
639
+ numbers** (M4 report): bare `t.f32` refused `1e8`, bare `t.f64` refused `1e18`, and
640
+ `t.f32(0, 1e9)` was refused at declaration — with a range the author never wrote appearing in the
641
+ message.
642
+
643
+ The cap did no layout work either. A float is never narrowed (`Ir.lowerNumber`: subtracting a
644
+ lower bound from a float and storing it narrower changes which values are representable), so
645
+ these two numbers only ever validated, and validated the wrong property. What a float range is
646
+ for is the author's own claim about the value — `t.f32(-1, 1)` for a normal, `t.f32(-90, 90)` for
647
+ a pitch — and the encoding's own limit is the largest finite value it can hold.
648
+
649
+ So: the largest finite `f32` and the largest finite double. `inf` is outside both, which is the
650
+ intent — it round-trips, but it is a value no schema means to declare, and NaN was already
651
+ refused because it fails both comparisons.
652
+
653
+ The precision this does *not* promise is now in the docstrings, where the finding says it should
654
+ have been: `f32` carries about seven significant digits, so a number past 2^24 comes back rounded.
655
+ ]]
656
+ local MAX_F32 = 3.4028234663852886e38
657
+ local MAX_F64 = 1.7976931348623157e308
658
+
659
+ local ENCODING_RANGE: { [string]: { min: number, max: number } } = {
660
+ u8 = { min = 0, max = 255 },
661
+ u16 = { min = 0, max = 65535 },
662
+ u32 = { min = 0, max = 4294967295 },
663
+ u53 = { min = 0, max = 2 ^ 53 },
664
+ i8 = { min = -128, max = 127 },
665
+ i16 = { min = -32768, max = 32767 },
666
+ i32 = { min = -2147483648, max = 2147483647 },
667
+ i53 = { min = -(2 ^ 53), max = 2 ^ 53 },
668
+ f32 = { min = -MAX_F32, max = MAX_F32 },
669
+ f64 = { min = -MAX_F64, max = MAX_F64 },
670
+ }
671
+
672
+ --[[ Which encodings carry a fraction. Everything else — every integer encoding, and the *lengths*
673
+ `t.string` and `t.buffer` are ranged by — has to be given whole bounds. ]]
674
+ local FRACTIONAL: { [string]: boolean } = { f32 = true, f64 = true }
675
+
676
+ local MAX_LENGTH = 65535
677
+
678
+ --[[ Declaring a schema is programmer territory, so it throws. Wire data never reaches here. ]]
679
+ local function check(condition: boolean, message: string)
680
+ if not condition then
681
+ error(`[netweave] {message}`, 3)
682
+ end
683
+ end
684
+
685
+ --[[
686
+ Returns `any` on purpose. The new solver does not push a call site's expected type into a
687
+ generic return (`spike/inference/README.md`), so a `descriptor<T>` would infer `Type<unknown>`
688
+ and every constructor would have to cast twice. Each public constructor states its own return
689
+ type instead, which is where the type belongs to be read anyway.
690
+ ]]
691
+ --[[
692
+ Which tables this module built.
693
+
694
+ `isType` was `type(value) == "table" and type(value.kind) == "string"`, so any table with a string
695
+ `kind` passed `t.optional`, `t.array`, `t.map`, `t.struct`, `Channel`'s `requireType` and
696
+ `nw.validate` — and every invariant the constructors enforce was advisory. Measured for five
697
+ shapes (M4 report finding 7): `order = {"a","a"}` double-encodes, a `max` of 2^31 gives a 2 GB
698
+ ceiling that the `maxBytes` policy is then measured against, `variants = {}` lowers to zero bits,
699
+ and `nw.validate(bogus, 5)` minted a `Trusted`.
700
+
701
+ A set rather than a field, because a field can be copied: `table.clone(t.u8)` would carry a
702
+ sentinel across but is not in here. Weak keys, so a schema built inside a function is collectable
703
+ with it, and the membership test is one lookup at declaration time — the wire path never asks.
704
+ ]]
705
+ local constructed: { [any]: true } = setmetatable({}, { __mode = "k" }) :: any
706
+
707
+ local function descriptor(fields: { [string]: any }): any
708
+ local frozen = table.freeze(fields)
709
+ constructed[frozen] = true
710
+
711
+ return frozen
712
+ end
713
+
714
+ --[[ A callable constructor — `t.u8`, `t.string`, `t.vector3`, `t.instance` — is a `setmetatable`
715
+ table rather than a `descriptor`, and is usable bare, so it is registered the same way. ]]
716
+ local function constructor(callable: any): any
717
+ constructed[callable] = true
718
+
719
+ return callable
720
+ end
721
+
722
+ --[[
723
+ Every key is checked to be a string before the sort. A number key reached `table.sort` and
724
+ either sorted in silently — `t.enum({ [1] = true })` accepted with `variants = {1}` while the
725
+ analyzer refused it for a different reason — or, mixed with strings, died in the VM's
726
+ `attempt to compare string < number`, which names neither the constructor nor the key (M4-1).
727
+ ]]
728
+ local function sortedKeys(source: { [string]: any }, what: string): { string }
729
+ local keys = {}
730
+
731
+ for key in source do
732
+ check(
733
+ type(key) == "string",
734
+ `a {what} is named by a string key, and {tostring(key)} is a {typeof(key)}. Write `
735
+ .. `\{ name = ... \}, not \{ ... \} — a list has positions where this needs names`
736
+ )
737
+ table.insert(keys, key)
738
+ end
739
+
740
+ table.sort(keys)
741
+ return table.freeze(keys)
742
+ end
743
+
744
+ --[[
745
+ Bare and callable share one descriptor, so `t.u8` and `t.u8(0, 10)` describe the same kind. The
746
+ constrained form is a fresh frozen copy; nothing is mutated after definition.
747
+ ]]
748
+ --[[
749
+ What `t.string`'s third argument may say, checked at declaration rather than ignored.
750
+
751
+ The report's own row for this asks for it because client strings reach `SetAsync` keys,
752
+ `Instance.Name` and chat, where invalid UTF-8 or a control character surfaces as an error in game
753
+ code with no packet to point at. A length bound cannot say any of that.
754
+
755
+ `pattern` is anchored by netweave rather than by the author, so a pattern that already carries an
756
+ anchor is refused: `"^" .. "^%w+$" .. "$"` matches a literal caret, and silently. Anchoring is the
757
+ whole difference between "the name is word characters" and "the name contains a word character
758
+ somewhere", and the unanchored reading is the one that lets anything through.
759
+ ]]
760
+ local TEXT_OPTIONS: { [string]: boolean } = { utf8 = true, pattern = true, charset = true }
761
+ table.freeze(TEXT_OPTIONS)
762
+
763
+ --[[
764
+ The matcher's worst case for a pattern with k unbounded items is about `max^k` steps, and this
765
+ is the largest product `t.string` admits. 2^16 steps is 0.4 ms measured (`spike/pattern/cost`:
766
+ two items at 256 bytes), which a `rate` can budget; the default `max` of 65,535 with two items
767
+ is 4 × 10^9 steps, 25 seconds, which nothing can. So two unbounded items allow a `max` of 256,
768
+ three allow 40, four allow 16, and one is linear at any length.
769
+ ]]
770
+ local PATTERN_STEPS = 65536
771
+
772
+ --[[
773
+ What the declaration checks, because the matcher does not: Lua 5.3 §6.4.1 says a malformed
774
+ pattern raises *during matching*, and the M4-1 report found the previous check — `string.find`
775
+ against the empty string — reached nothing behind a literal. `"a%b"` was accepted at
776
+ declaration and raised on the receive path, on a peer's string, outside `reject` (G4).
777
+
778
+ So the pattern is walked here by the grammar in that section. Two things are refused that are
779
+ well-formed: a back-reference (`%1`), because it needs a capture the walk would have to track
780
+ and its cost is not the `max^k` bound below; and an anchor at either end, because netweave adds
781
+ its own (see `TEXT_OPTIONS`). A `^` or `$` anywhere else is the literal character, as it is in
782
+ Lua, and `%$` at the end is an escaped dollar, not an anchor — the old check read the last
783
+ character alone and refused it.
784
+
785
+ Returns the count of unbounded items — a single-character class followed by `*`, `+` or `-` —
786
+ which is what the cost rule needs; `?` is bounded and `%b`/`%f` are linear.
787
+ ]]
788
+ local function scanPattern(pattern: string): (string?, number)
789
+ local length = #pattern
790
+ local at = 1
791
+ local depth = 0
792
+ local unbounded = 0
793
+
794
+ --[[ The index of the ']' closing a set that opens at `open`, or nil. A '^' first negates, a
795
+ ']' first (after that) is the literal bracket, and a '%' escapes the character after it. ]]
796
+ local function closeSet(open: number): number?
797
+ local close = open + 1
798
+ if string.sub(pattern, close, close) == "^" then
799
+ close += 1
800
+ end
801
+ if string.sub(pattern, close, close) == "]" then
802
+ close += 1
803
+ end
804
+ while close <= length and string.sub(pattern, close, close) ~= "]" do
805
+ if string.sub(pattern, close, close) == "%" then
806
+ close += 1
807
+ end
808
+ close += 1
809
+ end
810
+ return if close <= length then close else nil
811
+ end
812
+
813
+ if string.sub(pattern, 1, 1) == "^" then
814
+ return "anchor", 0
815
+ end
816
+
817
+ while at <= length do
818
+ local char = string.sub(pattern, at, at)
819
+ local item = true
820
+
821
+ if char == "(" then
822
+ depth += 1
823
+ at += 1
824
+ item = false
825
+ elseif char == ")" then
826
+ if depth == 0 then
827
+ return "a ')' with no '(' before it", 0
828
+ end
829
+ depth -= 1
830
+ at += 1
831
+ item = false
832
+ elseif char == "$" and at == length then
833
+ return "anchor", 0
834
+ elseif char == "%" then
835
+ local next = string.sub(pattern, at + 1, at + 1)
836
+
837
+ if next == "" then
838
+ return "ends in a '%', which has to be followed by a class or the character it escapes", 0
839
+ elseif next == "b" then
840
+ if at + 3 > length then
841
+ return "'%b' needs the two characters it balances, as in %b()", 0
842
+ end
843
+ at += 4
844
+ item = false
845
+ elseif next == "f" then
846
+ if string.sub(pattern, at + 2, at + 2) ~= "[" then
847
+ return "'%f' needs a set after it, as in %f[%w]", 0
848
+ end
849
+ local close = closeSet(at + 2)
850
+ if not close then
851
+ return "a '[' that never closes", 0
852
+ end
853
+ at = close + 1
854
+ item = false
855
+ elseif string.match(next, "%d") then
856
+ return `a back-reference '%{next}', which netweave patterns do not support; spell the repeated text out`,
857
+ 0
858
+ else
859
+ at += 2
860
+ end
861
+ elseif char == "[" then
862
+ local close = closeSet(at)
863
+ if not close then
864
+ return "a '[' that never closes", 0
865
+ end
866
+ at = close + 1
867
+ else
868
+ at += 1
869
+ end
870
+
871
+ if item then
872
+ local quantifier = string.sub(pattern, at, at)
873
+ if quantifier == "*" or quantifier == "+" or quantifier == "-" then
874
+ unbounded += 1
875
+ at += 1
876
+ elseif quantifier == "?" then
877
+ at += 1
878
+ end
879
+ end
880
+ end
881
+
882
+ if depth > 0 then
883
+ return "a '(' that never closes", 0
884
+ end
885
+
886
+ return nil, unbounded
887
+ end
888
+
889
+ --[[ The body of a set, as Lua reads one: a leading `^` negates, a `]` first is literal, `%`
890
+ escapes the next byte, and the first other `]` closes the set. The caller supplies the
891
+ brackets, so a close inside the body is the one thing this has to find. ]]
892
+ local function classProblem(charset: string): string?
893
+ local length = #charset
894
+ local at = if string.sub(charset, 1, 1) == "^" then 2 else 1
895
+
896
+ if string.sub(charset, at, at) == "]" then
897
+ at += 1
898
+ end
899
+
900
+ while at <= length do
901
+ local char = string.sub(charset, at, at)
902
+
903
+ if char == "%" then
904
+ if at == length then
905
+ return "it ends with a lone %, which escapes nothing"
906
+ end
907
+
908
+ at += 2
909
+ elseif char == "]" then
910
+ return "a ] inside it closes the set early, and what follows would sit outside the brackets"
911
+ else
912
+ at += 1
913
+ end
914
+ end
915
+
916
+ return nil
917
+ end
918
+
919
+ local function refineText(constrained: any, options: any)
920
+ if options == nil then
921
+ return
922
+ end
923
+
924
+ check(
925
+ type(options) == "table",
926
+ `t.string's options come as a table: t.string(0, 24, \{ utf8 = true \}). Got {typeof(options)}`
927
+ )
928
+
929
+ for key in options do
930
+ check(
931
+ TEXT_OPTIONS[key] == true,
932
+ `t.string has no option \`{tostring(key)}\`. The three are utf8, pattern and charset — `
933
+ .. `check the spelling, because an option that is ignored looks exactly like one that passed`
934
+ )
935
+ end
936
+
937
+ local wantsUtf8 = options.utf8
938
+
939
+ if wantsUtf8 ~= nil then
940
+ check(type(wantsUtf8) == "boolean", `t.string's \`utf8\` takes a boolean, got {typeof(wantsUtf8)}`)
941
+
942
+ --[[ `false` records nothing. A descriptor that carries the default is a descriptor two peers
943
+ can spell differently and hash differently for no reason. ]]
944
+ constrained.utf8 = wantsUtf8 or nil
945
+ end
946
+
947
+ local pattern = options.pattern
948
+ local charset = options.charset
949
+
950
+ --[[
951
+ A set is a pattern with one class and one repetition, stored as that pattern: the reader,
952
+ the writer and the protocol signature then have one attribute to carry, and a peer that
953
+ spelled the same set as a pattern agrees with one that spelled it as a set. What the option
954
+ adds is the guarantee — a class with `*` is one unbounded item, which the rule below admits
955
+ at any length, so a set can never be refused for cost the way a pattern can (M4-1, the
956
+ matcher-cost finding; `PLAN-M5` phase 5).
957
+ ]]
958
+ if charset ~= nil then
959
+ check(type(charset) == "string", `t.string's \`charset\` takes a string, got {typeof(charset)}`)
960
+ check(
961
+ pattern == nil,
962
+ "t.string takes `charset` or `pattern`, not both: a charset is the pattern [charset]*, so "
963
+ .. "write the set into the pattern if the pattern needs more than a set"
964
+ )
965
+ check(
966
+ charset ~= "",
967
+ "t.string's `charset` is empty, which admits no byte at all. Use a length of 0..0 if that is what you meant"
968
+ )
969
+
970
+ --[[ Two walks: the class walk, for a `]` that would close the set early and leave the rest
971
+ outside it (`"%w]"` between brackets scans as the well-formed set `[%w]` followed by a
972
+ literal bracket, not the set the author wrote), then the pattern walk over the whole
973
+ thing for everything else the grammar refuses. ]]
974
+ local problem = classProblem(charset) or scanPattern(`[{charset}]`)
975
+
976
+ check(
977
+ problem == nil,
978
+ `t.string's \`charset\` "{charset}" is not a Lua character class: {problem or ""}. Write `
979
+ .. `what goes between the brackets — %w_ for word characters, a-z for a range, ^%c for `
980
+ .. `anything but a control character, %] for a bracket`
981
+ )
982
+
983
+ pattern = `[{charset}]*`
984
+ end
985
+
986
+ if pattern ~= nil then
987
+ check(type(pattern) == "string", `t.string's \`pattern\` takes a string, got {typeof(pattern)}`)
988
+ check(
989
+ pattern ~= "",
990
+ "t.string's `pattern` is empty, which matches only an empty string. Use a length of 0..0 if that is what you meant"
991
+ )
992
+
993
+ local problem, unbounded = scanPattern(pattern)
994
+
995
+ check(
996
+ problem ~= "anchor",
997
+ `t.string's \`pattern\` "{pattern}" carries its own anchor, and netweave adds one — the `
998
+ .. `two together match a literal ^ or $. Write the pattern for the whole value and `
999
+ .. `leave the anchors off; a literal dollar at the end is %$`
1000
+ )
1001
+
1002
+ check(
1003
+ problem == nil,
1004
+ `t.string's \`pattern\` "{pattern}" is not a Lua pattern: {problem or ""}. It would raise `
1005
+ .. `on a peer's string rather than refuse it, so it is refused here`
1006
+ )
1007
+
1008
+ --[[ `max` is the length of the value the matcher runs over, and it is the attacker's choice
1009
+ up to that bound. The rule is on the product, so a short field keeps its two `.*`. ]]
1010
+ local max = constrained.max
1011
+ local allowed = math.floor(PATTERN_STEPS ^ (1 / math.max(unbounded, 1)))
1012
+
1013
+ check(
1014
+ unbounded <= 1 or max ^ unbounded <= PATTERN_STEPS,
1015
+ `t.string's \`pattern\` "{pattern}" has {unbounded} unbounded items (*, + or -) over a `
1016
+ .. `value of up to {max} bytes, and the matcher backtracks over every one of them: `
1017
+ .. `about {max}^{unbounded} steps on a hostile string, which is seconds per packet at `
1018
+ .. `the default maximum. `
1019
+ .. `Lower the maximum to {allowed} or fewer for this many items, or rewrite the `
1020
+ .. `pattern so at most one item is unbounded — a character class with a count, `
1021
+ .. `[%w]?[%w]?, or a class instead of '.'`
1022
+ )
1023
+
1024
+ constrained.pattern = pattern
1025
+ end
1026
+ end
1027
+
1028
+ local function ranged(base: { [string]: any }, label: string, refine: ((any, any) -> ())?): any
1029
+ local self = table.clone(base)
1030
+
1031
+ --[[
1032
+ Whole bounds, unless the encoding itself carries a fraction.
1033
+
1034
+ `t.u8(0.5, 2.5)` type-checked, lowered and encoded — and delivered a different number than
1035
+ was sent, with no rejection anywhere: the offset became 0.5, the writer's whole-number test
1036
+ passed on the *value*, `buffer.writeu8(1 - 0.5)` truncated, and the reader added 0.5 back.
1037
+ Sent 1, got 0.5. That is the failure M3 phase 9 closed for fractional values, re-opened one
1038
+ level up by the bound (M4 report).
1039
+
1040
+ The same applies to `t.string` and `t.buffer`, whose range is a **length**: half a byte is
1041
+ not a length, and a fractional one would reach the length prefix.
1042
+ ]]
1043
+ local whole = not FRACTIONAL[base.encoding or ""]
1044
+
1045
+ local callable = setmetatable(
1046
+ self,
1047
+ table.freeze({
1048
+ __call = function(_self: any, min: number, max: number, extra: any): any
1049
+ check(type(min) == "number", `{label} range needs a numeric minimum`)
1050
+ check(type(max) == "number", `{label} range needs a numeric maximum`)
1051
+ check(min <= max, `{label} range has min {min} above max {max}`)
1052
+ check(
1053
+ min >= base.min and max <= base.max,
1054
+ `{label} range {min}..{max} is outside {base.min}..{base.max}`
1055
+ )
1056
+ check(
1057
+ not whole or (min % 1 == 0 and max % 1 == 0),
1058
+ `{label} range {min}..{max} is not whole, and this one counts in whole numbers. `
1059
+ .. `Round the bounds — or use t.f32 or t.f64 if the value really is fractional`
1060
+ )
1061
+
1062
+ local constrained = table.clone(base)
1063
+ constrained.min = min
1064
+ constrained.max = max
1065
+
1066
+ --[[ Only `t.string` takes a third argument, and everything else refuses one rather
1067
+ than dropping it. `t.u8(0, 10, { utf8 = true })` is a mistake with an obvious
1068
+ cause and no symptom, which is the shape this repository keeps finding. ]]
1069
+ if refine then
1070
+ refine(constrained, extra)
1071
+ else
1072
+ check(
1073
+ extra == nil,
1074
+ `{label} takes a minimum and a maximum and nothing after them. Only t.string `
1075
+ .. `has options, and they are utf8 and pattern`
1076
+ )
1077
+ end
1078
+
1079
+ return descriptor(constrained)
1080
+ end,
1081
+ })
1082
+ )
1083
+
1084
+ return constructor(table.freeze(callable))
1085
+ end
1086
+
1087
+ local t = {}
1088
+
1089
+ local function number(encoding: Encoding): any
1090
+ local bounds = ENCODING_RANGE[encoding]
1091
+ return ranged({
1092
+ kind = "number" :: Kind,
1093
+ encoding = encoding,
1094
+ min = bounds.min,
1095
+ max = bounds.max,
1096
+ }, encoding)
1097
+ end
1098
+
1099
+ --[=[
1100
+ @prop u8 Ranged<number>
1101
+ @within Types
1102
+ An integer in `0..255`. `t.u8(0, 10)` narrows it further.
1103
+ ]=]
1104
+ t.u8 = number("u8") :: Ranged<number>
1105
+
1106
+ --[=[
1107
+ @prop u16 Ranged<number>
1108
+ @within Types
1109
+ An integer in `0..65535`.
1110
+ ]=]
1111
+ t.u16 = number("u16") :: Ranged<number>
1112
+
1113
+ --[=[
1114
+ @prop u32 Ranged<number>
1115
+ @within Types
1116
+ An integer in `0..4294967295`.
1117
+ ]=]
1118
+ t.u32 = number("u32") :: Ranged<number>
1119
+
1120
+ --[=[
1121
+ @prop u53 Ranged<number>
1122
+ @within Types
1123
+
1124
+ A whole number in `0..9007199254740992`, which is every integer a Luau double holds exactly.
1125
+
1126
+ ```lua
1127
+ owner = t.u53, -- a UserId
1128
+ stamp = t.u53(0, 2 ^ 42), -- milliseconds, narrowed
1129
+ ```
1130
+
1131
+ Eight bytes bare, and **narrowed like any other integer**: a range whose span fits four bytes or
1132
+ fewer takes that instead, so `t.u53(1, 1000)` is two.
1133
+
1134
+ :::note
1135
+ Before this existed the widest integer was `t.u32` and a `UserId` had to be declared `t.f64` —
1136
+ a float, whose wholeness only the *writer* refused. A peer sending `1.5` on a field a game reads
1137
+ as an id got 1.5 delivered, and `Players:GetPlayerByUserId`, a table key and a datastore write
1138
+ all behave differently for it. This is checked on both sides.
1139
+ :::
1140
+ ]=]
1141
+ t.u53 = number("u53") :: Ranged<number>
1142
+
1143
+ --[=[
1144
+ @prop i8 Ranged<number>
1145
+ @within Types
1146
+ A signed integer in `-128..127`.
1147
+ ]=]
1148
+ t.i8 = number("i8") :: Ranged<number>
1149
+
1150
+ --[=[
1151
+ @prop i16 Ranged<number>
1152
+ @within Types
1153
+ A signed integer in `-32768..32767`.
1154
+ ]=]
1155
+ t.i16 = number("i16") :: Ranged<number>
1156
+
1157
+ --[=[
1158
+ @prop i32 Ranged<number>
1159
+ @within Types
1160
+ A signed integer in `-2147483648..2147483647`.
1161
+ ]=]
1162
+ t.i32 = number("i32") :: Ranged<number>
1163
+
1164
+ --[=[
1165
+ @prop i53 Ranged<number>
1166
+ @within Types
1167
+
1168
+ [Types.u53] with a sign: a whole number in `-9007199254740992..9007199254740992`.
1169
+
1170
+ A balance that can go negative, a signed offset from an epoch, a difference between two ids.
1171
+ Eight bytes bare, and narrowed the same way — `t.i53(-1000, 1000)` is two.
1172
+ ]=]
1173
+ t.i53 = number("i53") :: Ranged<number>
1174
+
1175
+ --[=[
1176
+ @prop f32 Ranged<number>
1177
+ @within Types
1178
+
1179
+ A single-precision float, four bytes, up to ±3.4028235e38.
1180
+
1181
+ A range on a float validates but never narrows the storage — subtracting a lower bound and
1182
+ storing it smaller would change which values are representable, which is not what the schema
1183
+ said.
1184
+
1185
+ :::caution
1186
+ **About seven significant digits.** Every integer up to 16,777,216 is exact and past that they
1187
+ come back rounded: 16777217 arrives as 16777216, silently, because that is what the encoding is.
1188
+ Use `t.f64` where a large number has to be exact, `t.u32` or `t.i32` where it is an integer, or
1189
+ [Types.quantized] where a bounded range needs fewer bytes than either.
1190
+ :::
1191
+ ]=]
1192
+ t.f32 = number("f32") :: Ranged<number>
1193
+
1194
+ --[=[
1195
+ @prop f64 Ranged<number>
1196
+ @within Types
1197
+
1198
+ A double-precision float, eight bytes, up to ±1.7976931348623157e308 — every number Luau has,
1199
+ `inf` and NaN excepted.
1200
+
1201
+ Integers are exact to 2^53, which is every `UserId`, every timestamp in milliseconds and every
1202
+ currency balance a game will hold.
1203
+ ]=]
1204
+ t.f64 = number("f64") :: Ranged<number>
1205
+
1206
+ --[=[
1207
+ @within Types
1208
+ @function quantized
1209
+ @param min number -- the lowest value the field carries
1210
+ @param max number -- the highest
1211
+ @param step number -- the smallest difference the wire keeps
1212
+ @return Type<number>
1213
+
1214
+ A fractional value carried as **the number of steps from `min`** — the one range on a float that
1215
+ narrows the storage.
1216
+
1217
+ ```lua
1218
+ normal = t.quantized(-1, 1, 2 / 254), -- one byte, where t.f32 is four
1219
+ yaw = t.quantized(-180, 180, 0.25), -- 1440 levels, two bytes
1220
+ ```
1221
+
1222
+ `t.f32` costs four bytes whatever range you declare, because subtracting a lower bound from a
1223
+ float and storing it smaller changes which values are representable — so a range on a float
1224
+ validates and nothing more. This is the declaration that says how much precision you actually
1225
+ need, and the layout then spends what that precision costs: one byte up to 256 levels, two up to
1226
+ 65,536, four beyond.
1227
+
1228
+ :::caution
1229
+ **The value comes back rounded to the nearest step**, and that is the trade rather than a defect
1230
+ — it is written into the declaration instead of hidden in the encoding. `t.quantized(-1, 1,
1231
+ 2 / 254)` sent `0.5` returns `0.49606…`. Use `t.f32` where the exact bits matter, or a smaller
1232
+ step where they nearly do.
1233
+ :::
1234
+
1235
+ :::note
1236
+ The range has to divide into a whole number of steps. `t.quantized(0, 100, 3)` is 33.3 of them
1237
+ and is refused here rather than rounded silently, because which end moves is the author's call
1238
+ and not netweave's.
1239
+ :::
1240
+ ]=]
1241
+ function t.quantized(min: number, max: number, step: number, ...: any): Type<number>
1242
+ check(
1243
+ select("#", ...) == 0,
1244
+ `t.quantized takes a minimum, a maximum and a step and nothing after them, got `
1245
+ .. `{select("#", ...) + 3} arguments. An argument that is dropped looks exactly like one `
1246
+ .. `that was applied`
1247
+ )
1248
+ check(type(min) == "number", "quantized needs a numeric minimum")
1249
+ check(type(max) == "number", "quantized needs a numeric maximum")
1250
+ check(type(step) == "number", "quantized needs a numeric step")
1251
+ check(min < max, `quantized range has min {min} at or above max {max}. Put the smaller one first`)
1252
+ check(
1253
+ step > 0,
1254
+ `quantized step {step} is not above zero. The step is how far apart two `
1255
+ .. `neighbouring values are, so it is a positive number smaller than the range`
1256
+ )
1257
+ check(
1258
+ step <= max - min,
1259
+ `quantized step {step} is wider than the {max - min} it divides. One step across the whole `
1260
+ .. `range is the coarsest this gets; anything wider carries no information`
1261
+ )
1262
+
1263
+ local levels = (max - min) / step
1264
+ local whole = math.floor(levels + 0.5)
1265
+
1266
+ --[[ Relative, because `2 / (2 / 254)` is 254.00000000000003 and the declaration that produced it
1267
+ is exactly the one this is for. What it refuses is a range genuinely off a step boundary. ]]
1268
+ check(
1269
+ math.abs(levels - whole) <= 1e-9 * math.max(1, whole),
1270
+ `quantized range {min}..{max} is {levels} steps of {step}, which is not a whole number of `
1271
+ .. `them. Move a bound or change the step so it divides evenly — netweave will not pick `
1272
+ .. `which one for you`
1273
+ )
1274
+
1275
+ check(
1276
+ whole <= 4294967295,
1277
+ `quantized range {min}..{max} in steps of {step} is {whole} levels, past the 4294967295 a `
1278
+ .. `four-byte count holds. Use a larger step, or t.f64 if the value really needs that `
1279
+ .. `much precision`
1280
+ )
1281
+
1282
+ return descriptor({
1283
+ kind = "number" :: Kind,
1284
+ min = min,
1285
+ max = max,
1286
+ step = step,
1287
+ })
1288
+ end
1289
+
1290
+ --[=[
1291
+ @prop boolean Type<boolean>
1292
+ @within Types
1293
+
1294
+ One bit, not one byte. Booleans, optional presence markers and small enum tags share a bitfield
1295
+ per struct, so twelve of these cost two bytes rather than twelve.
1296
+ ]=]
1297
+ t.boolean = descriptor({ kind = "boolean" :: Kind }) :: Type<boolean>
1298
+
1299
+ --[=[
1300
+ @prop string Text
1301
+ @within Types
1302
+
1303
+ A length-prefixed string, up to 65535 bytes. `t.string(0, 64)` bounds the length and shrinks
1304
+ the prefix.
1305
+
1306
+ A third argument says what the bytes may **contain**:
1307
+
1308
+ ```lua
1309
+ name = t.string(1, 20, { utf8 = true, pattern = "[%w_]+" }),
1310
+ ```
1311
+
1312
+ * `utf8` — the bytes decode as UTF-8. Roblox's own text APIs assume this, and invalid bytes
1313
+ surface later as an error in game code with no packet to point at.
1314
+ * `pattern` — a Lua pattern the **whole** value must match. netweave anchors it, so
1315
+ `"[%w_]+"` means the entire string is word characters rather than "contains one".
1316
+
1317
+ Both are checked on the way out *and* on the way in: a value the schema forbids is a raise at
1318
+ the `:send` that wrote it, and a peer's is a refused packet.
1319
+
1320
+ A pattern has a **cost**, and a peer chooses the string it runs over. Lua's matcher backtracks,
1321
+ so a pattern with `k` unbounded items (`*`, `+` or `-`) costs about `max^k` steps on a hostile
1322
+ string: `(.*)@(.*)%.(.*)` over the default 65,535 bytes is 34 seconds per packet, inside any
1323
+ `rate`. `t.string` refuses a pattern whose `max^k` passes 2^16 — two unbounded items need a
1324
+ `max` of 256 or less, three need 40, and one unbounded item is linear at any length. Write the
1325
+ shape with bounded classes where you can: `[%w_]+` is one item and costs nothing.
1326
+
1327
+ :::caution
1328
+ A pattern is a promise about shape, not about safety. It cannot make a string safe to
1329
+ concatenate into a query or a rich-text label — it only means the string is the shape you said.
1330
+ Escaping is still the caller's job.
1331
+ :::
1332
+ ]=]
1333
+ t.string = ranged({
1334
+ kind = "string" :: Kind,
1335
+ min = 0,
1336
+ max = MAX_LENGTH,
1337
+ }, "string", refineText) :: Text
1338
+
1339
+ --[=[
1340
+ @prop buffer Ranged<buffer>
1341
+ @within Types
1342
+ A length-prefixed buffer, up to 65535 bytes.
1343
+ ]=]
1344
+ t.buffer = ranged({
1345
+ kind = "buffer" :: Kind,
1346
+ min = 0,
1347
+ max = MAX_LENGTH,
1348
+ }, "buffer") :: Ranged<buffer>
1349
+
1350
+ --[[
1351
+ A vector, callable with the schema its components are carried at.
1352
+
1353
+ Bare, a vector is three `f32` and **unbounded**: a position of `1e38` on an `intent` passes
1354
+ `parse`, and `t.unitVector3` covers directions only (M4 report). Naming a component schema is
1355
+ how a position says where the map is, and it narrows the storage at the same time, because
1356
+ everything a number type knows is reused per component — a range, a declared minimum subtracted,
1357
+ a quantisation step.
1358
+
1359
+ The component has to be a number and cannot be optional: a vector with two components is not a
1360
+ vector, and there is no bit to spend saying so — a vector opens no scope of its own.
1361
+ ]]
1362
+ local function vectored(base: { [string]: any }, label: string, axes: number): any
1363
+ local self = table.clone(base)
1364
+
1365
+ local callable = setmetatable(
1366
+ self,
1367
+ table.freeze({
1368
+ __call = function(_self: any, component: any, ...: any): any
1369
+ check(
1370
+ select("#", ...) == 0,
1371
+ `{label} takes one component schema and nothing after it, got `
1372
+ .. `{select("#", ...) + 1} arguments. An argument that is dropped looks `
1373
+ .. `exactly like one that was applied`
1374
+ )
1375
+
1376
+ --[[ The kind test rather than `isType`, which is defined further down: what a component
1377
+ has to be is a *number* schema, and asking that directly is both narrower and
1378
+ available here. Since `PLAN-M5` phase 3 a forged table is refused either way —
1379
+ `isType` is a set of what this module built — and this still asks the narrower
1380
+ question. ]]
1381
+ check(
1382
+ type(component) == "table",
1383
+ `{label} needs a netweave type for its components, got {typeof(component)}`
1384
+ )
1385
+ check(
1386
+ component.kind == "number",
1387
+ `{label} carries {axes} numbers, and its component schema is a `
1388
+ .. `{tostring(component.kind)}. Use t.f32, a narrowed integer like `
1389
+ .. `t.i16(-2048, 2048), or t.quantized`
1390
+ )
1391
+
1392
+ --[[
1393
+ A unit vector's components are in [-1, 1] and almost never whole, so a component
1394
+ that is an integer can represent six directions, an unsigned one three, and a
1395
+ range that stops short of ±1 none along that axis. The writer refuses a
1396
+ fractional value in an integer component and the reader's tolerance widens only
1397
+ for a quantised step, so `t.unitVector3(t.u8)` lowered to three bytes and refused
1398
+ almost every honest direction — the `t.array(x, 1.5)` shape one level up (M4-1).
1399
+ ]]
1400
+ if base.unit then
1401
+ local fractional = FRACTIONAL[component.encoding or ""] == true or component.step ~= nil
1402
+ local low = if component.min ~= nil then component.min else -math.huge
1403
+ local high = if component.max ~= nil then component.max else math.huge
1404
+
1405
+ check(
1406
+ fractional,
1407
+ `{label} is a direction, and its components are fractions in -1..1; a `
1408
+ .. `{tostring(component.encoding)} component can hold only whole numbers. `
1409
+ .. `Use t.f32, or t.quantized(-1, 1, 2 / 254) for one byte per axis`
1410
+ )
1411
+ check(
1412
+ low <= -1 and high >= 1,
1413
+ `{label} is a direction, and its components reach -1 and 1; this one covers `
1414
+ .. `{low}..{high}. Declare the component over -1..1 or wider`
1415
+ )
1416
+ end
1417
+
1418
+ local constrained = table.clone(base)
1419
+ constrained.element = component
1420
+ constrained.encoding = nil
1421
+
1422
+ return descriptor(constrained)
1423
+ end,
1424
+ })
1425
+ )
1426
+
1427
+ return constructor(table.freeze(callable))
1428
+ end
1429
+
1430
+ --[=[
1431
+ @prop vector2 Componented<Vector2>
1432
+ @within Types
1433
+
1434
+ Two `f32` components, or two of whatever you name: `t.vector2(t.i16(-1024, 1024))` is four bytes.
1435
+ ]=]
1436
+ t.vector2 =
1437
+ vectored({ kind = "vector2" :: Kind, encoding = "f32" :: Encoding }, "vector2", 2) :: Componented<Vector2>
1438
+
1439
+ --[=[
1440
+ @prop vector3 Componented<Vector3>
1441
+ @within Types
1442
+
1443
+ Three `f32` components — twelve bytes, and **unbounded**.
1444
+
1445
+ ```lua
1446
+ position = t.vector3(t.i16(-2048, 2048)), -- six bytes, and off the map is refused
1447
+ ```
1448
+
1449
+ A component schema is the difference between "a Vector3 arrived" and "a Vector3 inside the world
1450
+ arrived". Bare, `1e38` on an `intent` is a legal position; naming the range makes it a refusal at
1451
+ `parse` with the bounds in the message, and pays for itself in bytes.
1452
+ ]=]
1453
+ t.vector3 =
1454
+ vectored({ kind = "vector3" :: Kind, encoding = "f32" :: Encoding }, "vector3", 3) :: Componented<Vector3>
1455
+
1456
+ --[=[
1457
+ @prop unitVector3 Componented<Vector3>
1458
+ @within Types
1459
+
1460
+ A direction: a `Vector3` validated to unit length on arrival.
1461
+
1462
+ This is the check a shooter would otherwise write by hand in every handler, and forgetting it
1463
+ once is how a client sends a 10,000-stud "direction".
1464
+
1465
+ ```lua
1466
+ direction = t.unitVector3(t.quantized(-1, 1, 2 / 254)), -- three bytes instead of twelve
1467
+ ```
1468
+
1469
+ :::note
1470
+ A quantised direction does not land exactly on the unit sphere, so the length check widens by
1471
+ what the step can move it — `sqrt(3)` half-steps, derived rather than guessed. Naming a component
1472
+ coarse enough to matter is therefore a wider tolerance rather than a refusal, and the coarser the
1473
+ step the less "unit" promises.
1474
+ :::
1475
+ ]=]
1476
+ t.unitVector3 = vectored({
1477
+ kind = "vector3" :: Kind,
1478
+ encoding = "f32" :: Encoding,
1479
+ unit = true,
1480
+ }, "unitVector3", 3) :: Componented<Vector3>
1481
+
1482
+ --[=[
1483
+ @prop cframe Componented<CFrame>
1484
+ @within Types
1485
+
1486
+ Position and rotation: twenty-four bytes bare, and callable with the schema the **position** is
1487
+ carried at, which also makes the rotation compact.
1488
+
1489
+ ```lua
1490
+ pose = t.cframe, -- three f32 and an axis-angle vector, 24 bytes
1491
+ pose = t.cframe(t.i16(-2048, 2048)), -- six bytes of position, six of rotation, two bits
1492
+ ```
1493
+
1494
+ Named, the rotation travels as a quaternion with its largest component dropped: three `i16`
1495
+ and a two-bit index in the enclosing bitfield, against twelve bytes of axis-angle. The rotation
1496
+ comes back within 1e-4 radians of what was sent — five runs of 200,000 random rotations measured
1497
+ 6.1e-5 to 6.4e-5, `spike/additions/f_quaternion.luau` — and the position is whatever the
1498
+ component says, refused off the map like a vector's.
1499
+ ]=]
1500
+ t.cframe = vectored({ kind = "cframe" :: Kind }, "cframe", 3) :: Componented<CFrame>
1501
+
1502
+ --[=[
1503
+ @prop color3 Type<Color3>
1504
+ @within Types
1505
+ Three bytes.
1506
+ ]=]
1507
+ t.color3 = descriptor({ kind = "color3" :: Kind }) :: Type<Color3>
1508
+
1509
+ --[=[
1510
+ @prop instance Classed
1511
+ @within Types
1512
+
1513
+ An instance, carried alongside the buffer rather than in it. `t.instance("Sound")` rejects
1514
+ anything that is not a `Sound`.
1515
+
1516
+ :::note
1517
+ The payload type stays `Instance` even when a class is named — Luau cannot resolve a class-name
1518
+ string to its type, so narrow it yourself if you need the specific class.
1519
+ :::
1520
+ ]=]
1521
+ t.instance = (function(): Classed
1522
+ local base = { kind = "instance" :: Kind }
1523
+ local self = table.clone(base)
1524
+
1525
+ local callable = setmetatable(
1526
+ self,
1527
+ table.freeze({
1528
+ __call = function(_self: any, className: string, options: any, ...: any): Type<Instance>
1529
+ check(
1530
+ select("#", ...) == 0,
1531
+ `t.instance takes a class and an options table and nothing after them, got `
1532
+ .. `{select("#", ...) + 2} arguments. An argument that is dropped looks exactly `
1533
+ .. `like one that was applied`
1534
+ )
1535
+ check(type(className) == "string", "instance class must be a string")
1536
+
1537
+ local constrained = table.clone(base)
1538
+ constrained.class = className
1539
+
1540
+ if options ~= nil then
1541
+ check(
1542
+ type(options) == "table",
1543
+ `t.instance's options come as a table: t.instance("BasePart", `
1544
+ .. `\{ descendantOf = workspace \}). Got {typeof(options)}`
1545
+ )
1546
+
1547
+ for key in options do
1548
+ check(
1549
+ key == "descendantOf",
1550
+ `t.instance has no option \`{tostring(key)}\`. The one is descendantOf — `
1551
+ .. `check the spelling, because an option that is ignored looks exactly `
1552
+ .. `like one that passed`
1553
+ )
1554
+ end
1555
+
1556
+ local root = options.descendantOf
1557
+
1558
+ if root ~= nil then
1559
+ check(
1560
+ typeof(root) == "Instance",
1561
+ `t.instance's \`descendantOf\` takes the container itself, not a name: `
1562
+ .. `t.instance("BasePart", \{ descendantOf = workspace \}). Got `
1563
+ .. `{typeof(root)}`
1564
+ )
1565
+
1566
+ constrained.descendantOf = root
1567
+ end
1568
+ end
1569
+
1570
+ return descriptor(constrained)
1571
+ end,
1572
+ })
1573
+ )
1574
+
1575
+ return (constructor(table.freeze(callable)) :: any) :: Classed
1576
+ end)()
1577
+
1578
+ --[=[
1579
+ @prop player Type<Player>
1580
+ @within Types
1581
+
1582
+ A `Player`, which is [Types.instance] with the payload type Luau cannot get from a class name.
1583
+
1584
+ ```lua
1585
+ target = t.player,
1586
+ ```
1587
+
1588
+ :::caution
1589
+ **A `Player` object that arrives is not necessarily a player who is here.** `IsA("Player")` is
1590
+ still true for someone who left the instant before the packet was written, and the reference the
1591
+ sender used keeps it alive. Where the sender's own identity is what you need, `ctx.player` is the
1592
+ server's answer and cannot be chosen by anybody; this is for naming *another* player, and what
1593
+ makes that name current is the roster, not the type.
1594
+ :::
1595
+ ]=]
1596
+ t.player = descriptor({ kind = "instance" :: Kind, class = "Player" }) :: Type<Player>
1597
+
1598
+ --[=[
1599
+ @within Types
1600
+ @function isType
1601
+ @param value any
1602
+ @return boolean
1603
+ @private
1604
+
1605
+ Whether this module built `value`.
1606
+
1607
+ Not a shape test: a table with a string `kind` used to pass, so every bound, every sorted order
1608
+ and every non-empty enum the constructors check was advisory (M4 report finding 7). `Channel` and
1609
+ `Trust` ask through here rather than repeating the test, because there is only one set.
1610
+ ]=]
1611
+ function t.isType(value: any): boolean
1612
+ return constructed[value] == true
1613
+ end
1614
+
1615
+ local function isType(value: any): boolean
1616
+ return constructed[value] == true
1617
+ end
1618
+
1619
+ --[[
1620
+ A default is checked here, at the declaration, by the bounds the descriptor already carries —
1621
+ not by the codec, which this module cannot require. The kinds are the ones whose `==` is value
1622
+ equality, because the writer decides "is this the default" with it, and a string or a number
1623
+ is also what a default *is* to the game: the value the field has when nobody set it.
1624
+ ]]
1625
+ local INTEGER: { [string]: boolean } = {
1626
+ u8 = true,
1627
+ u16 = true,
1628
+ u32 = true,
1629
+ u53 = true,
1630
+ i8 = true,
1631
+ i16 = true,
1632
+ i32 = true,
1633
+ i53 = true,
1634
+ }
1635
+
1636
+ local function checkDefault(inner: { [string]: any }, default: any)
1637
+ local kind = inner.kind
1638
+ local given = type(default)
1639
+
1640
+ if kind == "number" then
1641
+ check(given == "number", `t.optional's default for a number field is a number, got {given}`)
1642
+ check(
1643
+ default == default and default ~= math.huge and default ~= -math.huge,
1644
+ "t.optional's default is not finite"
1645
+ )
1646
+ check(
1647
+ (inner.min == nil or default >= inner.min) and (inner.max == nil or default <= inner.max),
1648
+ `t.optional's default {default} is outside the field's range {tostring(inner.min)}..{tostring(
1649
+ inner.max
1650
+ )}`
1651
+ )
1652
+ check(
1653
+ not INTEGER[inner.encoding] or default % 1 == 0,
1654
+ `t.optional's default {default} is not whole, and the field is an integer`
1655
+ )
1656
+ elseif kind == "string" then
1657
+ check(given == "string", `t.optional's default for a string field is a string, got {given}`)
1658
+ check(
1659
+ #default >= (inner.min or 0) and #default <= (inner.max or MAX_LENGTH),
1660
+ `t.optional's default is {#default} bytes, outside the field's length {tostring(inner.min)}..{tostring(
1661
+ inner.max
1662
+ )}`
1663
+ )
1664
+ elseif kind == "boolean" then
1665
+ check(given == "boolean", `t.optional's default for a boolean field is a boolean, got {given}`)
1666
+ elseif kind == "enum" then
1667
+ check(
1668
+ given == "string" and table.find(inner.variants, default) ~= nil,
1669
+ `t.optional's default {tostring(default)} is not a variant of the enum`
1670
+ )
1671
+ else
1672
+ error(
1673
+ `[netweave] t.optional takes a default only for a number, a string, a boolean or an enum, `
1674
+ .. `not a {tostring(kind)}: those are the values two peers can compare, and a table `
1675
+ .. `default would be a fresh table on every read`,
1676
+ 3
1677
+ )
1678
+ end
1679
+ end
1680
+
1681
+ --[=[
1682
+ @within Types
1683
+ @function enum
1684
+ @param variants V -- a set: `{ primary = true, secondary = true }`
1685
+ @return Type<EnumPayload<V>>
1686
+
1687
+ A closed set of names, encoded as an index in the enclosing bitfield. Two variants cost one
1688
+ bit; four cost two.
1689
+
1690
+ ```lua
1691
+ weapon = t.enum({ primary = true, secondary = true, melee = true }),
1692
+ -- payload type: "primary" | "secondary" | "melee"
1693
+ ```
1694
+
1695
+ :::note
1696
+ Variants are written as keys rather than as an array because Luau widens `{"a", "b"}` to
1697
+ `{string}`, which would throw away the literal types this exists to give you.
1698
+ :::
1699
+ ]=]
1700
+ --[[
1701
+ Wire index is the position in the sorted name list, never table iteration order. ByteNet derives
1702
+ packet ids from iteration order and the failure mode is that everything decodes as the wrong
1703
+ thing, silently (`docs/WIRE-FORMAT.md` §3).
1704
+ ]]
1705
+ function t.enum<V>(variants: V): Type<EnumPayload<V>>
1706
+ check(type(variants) == "table", "enum variants must be a table")
1707
+
1708
+ local names = sortedKeys(variants :: any, "enum variant")
1709
+ check(#names > 0, "an enum needs at least one variant")
1710
+
1711
+ for _, name in names do
1712
+ check((variants :: any)[name] == true, `enum variant "{name}" must be set to true`)
1713
+ end
1714
+
1715
+ return descriptor({
1716
+ kind = "enum" :: Kind,
1717
+ variants = names,
1718
+ })
1719
+ end
1720
+
1721
+ --[=[
1722
+ @within Types
1723
+ @function literal
1724
+ @param value V -- a string, a boolean or a number
1725
+ @return Type<V>
1726
+
1727
+ One value, known to both sides, costing nothing on the wire.
1728
+
1729
+ ```lua
1730
+ version = t.literal("v3"), -- payload type "v3"
1731
+ ready = t.literal(true), -- payload type true
1732
+ ```
1733
+
1734
+ The writer refuses any other value, the reader hands the constant back, and a change never
1735
+ moves it. It is for versioning a payload, for a `t.union` branch that carries a name and
1736
+ nothing else, and for [Types.set], whose entries are literal `true`. A number literal's payload
1737
+ is `number`, because Luau has no number singletons; the value is still checked on the way out.
1738
+ ]=]
1739
+ function t.literal<V>(value: V & (string | boolean | number)): Type<V>
1740
+ local kind = type(value)
1741
+
1742
+ check(
1743
+ kind == "string" or kind == "boolean" or kind == "number",
1744
+ `t.literal takes a string, a boolean or a number, got {typeof(value)}`
1745
+ )
1746
+ check(
1747
+ kind ~= "number" or (value == value and value ~= math.huge and value ~= -math.huge),
1748
+ "t.literal takes a finite number; NaN and the infinities are not values two peers can agree on"
1749
+ )
1750
+
1751
+ return descriptor({
1752
+ kind = "literal" :: Kind,
1753
+ literal = value,
1754
+ })
1755
+ end
1756
+
1757
+ --[=[
1758
+ @within Types
1759
+ @function optional
1760
+ @param inner I -- a netweave type
1761
+ @param default D? -- what an absent value reads as; a number, a string, a boolean or an enum variant
1762
+ @return Type<OptionalPayload<I, D>>
1763
+
1764
+ A value that may be absent. Presence costs one bit in the enclosing bitfield, not a byte.
1765
+
1766
+ ```lua
1767
+ target = t.optional(t.u16), -- payload number?, nil when absent
1768
+ speed = t.optional(t.u8, 16), -- payload number, 16 when absent, and 16 is never sent
1769
+ ```
1770
+
1771
+ With a default the payload is the inner type alone: the reader hands the default back where
1772
+ the bit is clear, and the writer clears the bit for the default as well as for nil, so the
1773
+ common value costs a bit rather than its bytes. The default is part of the protocol — two peers
1774
+ declaring different ones disagree — and it is a primitive, because a table default would be a
1775
+ fresh table on every read and no two of them equal.
1776
+ ]=]
1777
+ function t.optional<I, D>(inner: I, default: D?): Type<OptionalPayload<I, D>>
1778
+ check(isType(inner), "optional needs a netweave type")
1779
+ check((inner :: any).kind ~= "optional", "optional cannot wrap an optional")
1780
+
1781
+ if default == nil then
1782
+ return descriptor({
1783
+ kind = "optional" :: Kind,
1784
+ inner = inner,
1785
+ })
1786
+ end
1787
+
1788
+ checkDefault(inner :: any, default)
1789
+
1790
+ return descriptor({
1791
+ kind = "optional" :: Kind,
1792
+ inner = inner,
1793
+ default = default,
1794
+ })
1795
+ end
1796
+
1797
+ --[=[
1798
+ @within Types
1799
+ @function array
1800
+ @param element E -- a netweave type
1801
+ @param min number? -- alone, an exact length
1802
+ @param max number?
1803
+ @return Type<ArrayPayload<E>>
1804
+
1805
+ A list.
1806
+
1807
+ ```lua
1808
+ t.array(t.u8) -- 0..65535, length-prefixed
1809
+ t.array(entity, 100) -- exactly 100
1810
+ t.array(t.string, 0, 8) -- at most 8
1811
+ ```
1812
+
1813
+ The exact form is what makes a schema statically sized, and a statically sized packet carries
1814
+ no length prefix at all — the framing guarantee costs it nothing.
1815
+ ]=]
1816
+ function t.array<E>(element: E, min: number?, max: number?): Type<ArrayPayload<E>>
1817
+ check(isType(element), "array needs a netweave element type")
1818
+
1819
+ --[[
1820
+ `{ T? }` with no exact length has no length: `#` on a table with nils is a border, and Luau
1821
+ picks it from how the table was built — `{1, nil, 3}` as a literal is three, filled by
1822
+ assignment it is one. So `{1, 2, nil}` sent two and `{[2] = -5}` sent nothing, with no raise
1823
+ and no report (M4-1). With an exact length nothing is measured, every position is written;
1824
+ without one the honest spellings are a map keyed by index, or a struct.
1825
+ ]]
1826
+ check(
1827
+ (element :: any).kind ~= "optional" or (min ~= nil and (max == nil or max == min)),
1828
+ `t.array(t.optional(...)) needs an exact length, because a list with holes has no length `
1829
+ .. `Luau agrees on. Give it one — t.array(t.optional(t.u8), 4) — or key the entries: `
1830
+ .. `t.map(t.u8, t.u8)`
1831
+ )
1832
+
1833
+ local lower = min or 0
1834
+ local upper = max or (if min then min else MAX_LENGTH)
1835
+
1836
+ check(lower >= 0, `array length {lower} is negative`)
1837
+ check(lower <= upper, `array length range has min {lower} above max {upper}`)
1838
+ check(upper <= MAX_LENGTH, `array length {upper} exceeds {MAX_LENGTH}`)
1839
+
1840
+ --[[ A count is not a range through `ranged`, so it needs the same check separately.
1841
+ `t.array(t.u8, 1.5)` lowered happily and then refused **every** length the game could send:
1842
+ a channel declared, accepted, and unable to carry anything (M4 report). ]]
1843
+ check(
1844
+ lower % 1 == 0 and upper % 1 == 0,
1845
+ `array length {lower}..{upper} is not whole. A length is a count of elements, and a `
1846
+ .. `fractional one is a channel that refuses every list you can build`
1847
+ )
1848
+
1849
+ return descriptor({
1850
+ kind = "array" :: Kind,
1851
+ element = element,
1852
+ min = lower,
1853
+ max = upper,
1854
+ })
1855
+ end
1856
+
1857
+ --[=[
1858
+ @within Types
1859
+ @function map
1860
+ @param key K -- a netweave type the receiver can look a value up by
1861
+ @param value V -- a netweave type
1862
+ @return Type<MapPayload<K, V>>
1863
+
1864
+ A dictionary, length-prefixed and written as key/value pairs.
1865
+ ]=]
1866
+ --[[
1867
+ **What can be a map key, and why the list is this short.**
1868
+
1869
+ A key has to be a value the *receiver* can look one up by. That is a property of how the decoded
1870
+ value behaves as a table index, not of how it serialises:
1871
+
1872
+ * `number`, `string`, `boolean` and `enum` decode to primitives, and two equal ones are the
1873
+ same key. Those work.
1874
+ * `instance` decodes to the reference the sidecar carried, and reference identity is exactly
1875
+ what a map keyed by an instance wants. That works too.
1876
+ * `struct`, `array`, `map` and `buffer` decode to **fresh tables**. Two entries the sender
1877
+ wrote with equal keys arrive as two distinct keys, and the game cannot look up either — it
1878
+ would have to walk the map comparing contents, which is not a map.
1879
+ * `optional` cannot be a key at all: a Lua table has no nil index. The presence bit it adds is
1880
+ dead weight that only a hostile packet can clear, and when it did, the reader raised on
1881
+ `result[nil]` — wire data reaching a Luau error, which is guarantee G4 (M4 report, finding 3).
1882
+ * `vector2`, `vector3`, `color3` and `cframe` are refused for the same reason as tables, but the
1883
+ reason is one this file must not have to know: whether two separately decoded datatypes are
1884
+ the same table key depends on whether the runtime interns them. **A schema is not allowed to
1885
+ depend on that**, so they are out here rather than out on some runtimes.
1886
+
1887
+ A game that wants one of the refused kinds as a key has the same options either way: key by
1888
+ something primitive that names it — an id, a name, an enum — and put the rest in the value.
1889
+ ]]
1890
+ local MAP_KEYS: { [string]: boolean } = {
1891
+ number = true,
1892
+ string = true,
1893
+ boolean = true,
1894
+ enum = true,
1895
+ instance = true,
1896
+ }
1897
+
1898
+ function t.map<K, V>(key: K, value: V): Type<MapPayload<K, V>>
1899
+ check(isType(key), "map needs a netweave key type")
1900
+ check(isType(value), "map needs a netweave value type")
1901
+
1902
+ local keyKind = (key :: any).kind
1903
+
1904
+ check(
1905
+ MAP_KEYS[keyKind] == true,
1906
+ `a map key is {tostring(keyKind)}, and a map key has to be something the receiver can look `
1907
+ .. `it up by. Use t.u16, t.string(0, 32), t.boolean, an enum, or t.instance — a `
1908
+ .. `{tostring(keyKind)} decodes to a fresh value on the other side, so two entries the `
1909
+ .. `sender wrote with equal keys arrive as two keys nothing can index. Key by an id or a `
1910
+ .. `name and put the rest in the value.`
1911
+ )
1912
+
1913
+ return descriptor({
1914
+ kind = "map" :: Kind,
1915
+ key = key,
1916
+ value = value,
1917
+ min = 0,
1918
+ max = MAX_LENGTH,
1919
+ })
1920
+ end
1921
+
1922
+ --[=[
1923
+ @within Types
1924
+ @function set
1925
+ @param element E -- a netweave type the receiver can look an entry up by; the same kinds [Types.map] takes as a key
1926
+ @return Type<MapPayload<E, Type<true>>>
1927
+
1928
+ A set of values, carried as `{ [E]: true }`.
1929
+
1930
+ ```lua
1931
+ unlocked = t.set(t.string(1, 32)), -- payload type { [string]: true }
1932
+ ```
1933
+
1934
+ It is a [Types.map] whose value is [Types.literal] `true`, and that is not sugar: a
1935
+ `t.map(k, t.boolean)` spends a flag byte per entry on a bit that is always set, and a literal
1936
+ costs nothing, so a set is its count and its entries and no more. A change replaces the set
1937
+ whole, as it does a map.
1938
+ ]=]
1939
+ function t.set<E>(element: E): Type<MapPayload<E, Type<true>>>
1940
+ check(isType(element), "set needs a netweave element type")
1941
+
1942
+ local kind = (element :: any).kind
1943
+
1944
+ --[[ The map's own check would refuse the same kinds, in the map's words; a set is what the
1945
+ author wrote, so the refusal says so. ]]
1946
+ check(
1947
+ MAP_KEYS[kind] == true,
1948
+ `a set of {tostring(kind)} cannot be looked up on the other side: an entry that decodes to `
1949
+ .. `a fresh value is an entry nothing can find again. Use t.u16, t.string(0, 32), an enum `
1950
+ .. `or t.instance, and put the rest of the value in a map keyed by it.`
1951
+ )
1952
+
1953
+ return t.map(element, t.literal(true)) :: any
1954
+ end
1955
+
1956
+ --[=[
1957
+ @within Types
1958
+ @function struct
1959
+ @param fields F -- a table of netweave types
1960
+ @return Type<StructPayload<F>>
1961
+
1962
+ A record. The payload type is derived from the fields, so there is nothing to keep in sync.
1963
+
1964
+ ```lua
1965
+ local Entity = t.struct({
1966
+ id = t.u8,
1967
+ position = t.vector3,
1968
+ alive = t.boolean,
1969
+ })
1970
+ -- Type<{ id: number, position: Vector3, alive: boolean }>
1971
+ ```
1972
+ ]=]
1973
+ --[[
1974
+ Fields are encoded in sorted name order, not declaration order. Both peers build the same
1975
+ literal so hash order would usually agree, but "usually" is how ByteNet's id assignment behaves
1976
+ too, and sorting costs nothing at definition time.
1977
+ ]]
1978
+ function t.struct<F>(fields: F): Type<StructPayload<F>>
1979
+ check(type(fields) == "table", "struct fields must be a table")
1980
+
1981
+ local order = sortedKeys(fields :: any, "struct field")
1982
+ check(#order > 0, "a struct needs at least one field")
1983
+
1984
+ for _, name in order do
1985
+ check(isType((fields :: any)[name]), `struct field "{name}" is not a netweave type`)
1986
+ end
1987
+
1988
+ --[[ A copy, frozen. The caller's table was kept by reference, so swapping a field after the
1989
+ declaration changed what a codec built later encoded and what the signature hashed — a
1990
+ schema that is not what was declared, with no message (M4 report, finding 17; the same
1991
+ in `t.union`). ]]
1992
+ return descriptor({
1993
+ kind = "struct" :: Kind,
1994
+ fields = table.freeze(table.clone(fields :: any)),
1995
+ order = order,
1996
+ })
1997
+ end
1998
+
1999
+ --[=[
2000
+ @within Types
2001
+ @function union
2002
+ @param branches B -- branch name to schema
2003
+ @return Type<UnionPayload<B>>
2004
+
2005
+ **One of several shapes, and the wire says which.**
2006
+
2007
+ ```lua
2008
+ local Action = t.union({
2009
+ move = t.struct({ x = t.u8, y = t.u8 }),
2010
+ attack = t.struct({ target = t.u16 }),
2011
+ wait = t.u8,
2012
+ })
2013
+
2014
+ action:listen(function(ctx, value)
2015
+ if value.tag == "move" then
2016
+ print(value.value.x) -- narrowed to the move branch
2017
+ end
2018
+ end)
2019
+ ```
2020
+
2021
+ The payload is `{ tag: "move", value: … } | { tag: "attack", value: … }`, so comparing `tag`
2022
+ against a literal narrows `value` with it.
2023
+
2024
+ Two branches cost **one bit**, three or four cost two, and only the chosen branch's bytes are
2025
+ written. Branches fork the bit budget rather than summing it: a union of two structs each
2026
+ carrying three flags costs `1 + 3` bits, not `1 + 6` — Zap sums, so its variants consume separate
2027
+ bits even though only one can ever be present (`RESEARCH §3.9-Y`, `WIRE-FORMAT.md` §5).
2028
+
2029
+ :::caution
2030
+ **This is what the "one optional field per case" pattern was standing in for**, and the
2031
+ difference is that the pattern cannot say *exactly one*. A struct of optionals lets a peer set
2032
+ two cases at once, or none, and every handler that reads it has to check for both — which is a
2033
+ check that gets written once and forgotten twice.
2034
+ :::
2035
+
2036
+ :::note
2037
+ Adding, removing or renaming a branch changes the wire and the protocol hash, the same as adding
2038
+ an enum variant: the tag is a **position**, so a branch inserted in the middle renumbers the ones
2039
+ after it. Both peers redeploy together, which the handshake enforces rather than hopes for.
2040
+ :::
2041
+ ]=]
2042
+ --[[
2043
+ Branches are encoded in sorted name order for the same reason struct fields and enum variants
2044
+ are: both peers evaluate the same literal, and "hash order usually agrees" is exactly how
2045
+ ByteNet's id assignment behaves.
2046
+ ]]
2047
+ function t.union<B>(branches: B): Type<UnionPayload<B>>
2048
+ check(type(branches) == "table", "union branches must be a table")
2049
+
2050
+ local names = sortedKeys(branches :: any, "union branch")
2051
+ check(#names > 0, "a union needs at least one branch")
2052
+
2053
+ for _, name in names do
2054
+ check(isType((branches :: any)[name]), `union branch "{name}" is not a netweave type`)
2055
+ end
2056
+
2057
+ return descriptor({
2058
+ kind = "union" :: Kind,
2059
+ variants = names,
2060
+ branches = table.freeze(table.clone(branches :: any)),
2061
+ })
2062
+ end
2063
+
2064
+ return table.freeze(t)