@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.
package/index.d.ts ADDED
@@ -0,0 +1,1272 @@
1
+ /// <reference types="@rbxts/types" />
2
+
3
+ /*
4
+ The public types of netweave, over the Luau runtime in `src`. Names and meanings are the original's.
5
+
6
+ What the original exports and this file leaves out, on purpose:
7
+
8
+ - `nw.internal`, `nw.types.isType`, and every member of `nw.config` but `snapshot` and `describe`.
9
+ They are the library's own seams; a game that reaches for one has left the contract.
10
+ - `Descriptor` and `Encoding`. A schema is opaque here, so there is no record to name.
11
+ - `OptionalPayload`, `ArrayPayload`, `MapPayload`, `StructPayload`, `UnionPayload`, `EnumPayload`.
12
+ Luau needs a type function to project each payload; TypeScript infers them.
13
+
14
+ Where a type here is stricter than the original's, the comment beside it says so.
15
+ */
16
+
17
+ /*
18
+ Nothing below this line is reachable by name, so nothing outside this file can write a value that
19
+ carries one of these keys. That is what makes a brand a brand.
20
+ */
21
+ declare const payload: unique symbol;
22
+ declare const invariant: unique symbol;
23
+ declare const trusted: unique symbol;
24
+ declare const untrusted: unique symbol;
25
+ declare const forbidden: unique symbol;
26
+ declare const policyOf: unique symbol;
27
+ declare const channelClass: unique symbol;
28
+ declare const serverView: unique symbol;
29
+ declare const clientView: unique symbol;
30
+ declare const audienceOf: unique symbol;
31
+
32
+ /* A type no value has, whose only job is to put `M` in the diagnostic. */
33
+ interface Forbidden<M extends string> {
34
+ readonly [forbidden]: M;
35
+ }
36
+
37
+ type Primitive = string | number | boolean;
38
+ type Datatype = Instance | Vector3 | Vector2 | CFrame | Color3 | buffer;
39
+ type AnyType = nw.Type<any>;
40
+ type Simplify<T> = { [K in keyof T]: T[K] };
41
+
42
+ type DeepReadonly<T> = T extends Primitive | Datatype | undefined
43
+ ? T
44
+ : T extends ReadonlyMap<infer K, infer V>
45
+ ? ReadonlyMap<K, DeepReadonly<V>>
46
+ : T extends ReadonlySet<infer E>
47
+ ? ReadonlySet<E>
48
+ : T extends ReadonlyArray<infer E>
49
+ ? ReadonlyArray<DeepReadonly<E>>
50
+ : { readonly [K in keyof T]: DeepReadonly<T[K]> };
51
+
52
+ /*
53
+ Refuses keys outside `K`, even through a variable, where TypeScript's own excess-property check does
54
+ not look. `S` is inferred backwards through a homomorphic mapped type rather than intersected in:
55
+ intersecting turns `maxBytes: "4"` into "not assignable to never", and this keeps "to number".
56
+
57
+ The message is the original's (Channel.luau `permit`): the key, the keys the class takes in `Takes`,
58
+ which is a tuple so that their order is the one written and not a union's, and the key of `Takes`
59
+ the written one is but for case, when there is one. A key of `K` that is not in `Takes` is one the
60
+ spec forbids with its own message.
61
+ */
62
+ type OnlyKeys<S, K, Where extends string, Takes extends readonly string[]> = {
63
+ readonly [P in keyof S]: P extends K
64
+ ? unknown
65
+ : Forbidden<`${Where} has no \`${P & string}\`.${CaseHint<P & string, Takes>} It takes ${Joined<Takes>} — check the spelling, because a key that is ignored looks exactly like one that worked.`>;
66
+ };
67
+
68
+ /* The same for nw.configure, in the words of the original's (Config.luau `refuse`): `Known` is sorted as those are. */
69
+ type KnownKeys<S, Known extends readonly string[], Field extends string> = {
70
+ readonly [P in keyof S]: P extends Known[number]
71
+ ? unknown
72
+ : Forbidden<`nw.configure: no such ${Field} \`${P & string}\`.${CaseHint<P & string, Known>} Known ${Field}s: ${Joined<Known>}`>;
73
+ };
74
+
75
+ /* `a, b, c`. */
76
+ type Joined<L extends readonly string[]> = L extends readonly [infer H extends string, ...infer R extends readonly string[]]
77
+ ? R extends readonly []
78
+ ? H
79
+ : `${H}, ${Joined<R>}`
80
+ : "";
81
+
82
+ /* The first of `L` that is `P` but for case, or never: `timeout` for `timeOut`, `maxBytes` for `maxbytes`. */
83
+ type SameButCase<P extends string, L extends readonly string[]> = L extends readonly [infer H extends string, ...infer R extends readonly string[]]
84
+ ? Lowercase<H> extends Lowercase<P>
85
+ ? H
86
+ : SameButCase<P, R>
87
+ : never;
88
+
89
+ type CaseHint<P extends string, L extends readonly string[]> = [SameButCase<P, L>] extends [never] ? "" : ` Did you mean \`${SameButCase<P, L>}\`?`;
90
+
91
+ type NonEmpty<R, M extends string> = [keyof R] extends [never] ? Forbidden<M> : R;
92
+
93
+ type NotUntrusted<V> = V extends { readonly [untrusted]: true }
94
+ ? Forbidden<"nw.validate is not an untrust. A channel's payload is already checked against its schema; narrow it with a policy instead.">
95
+ : V;
96
+
97
+ /* A handler that returns a Promise has already returned: its `ctx` is recycled before it resumes. */
98
+ type Sync<R> = R extends { andThen: any }
99
+ ? Forbidden<"A handler must not be async. ctx is recycled the moment the handler returns; copy the fields you need and task.spawn the rest.">
100
+ : unknown;
101
+
102
+ type MapKey<K extends AnyType> = [nw.PayloadOf<K>] extends [Primitive | Instance]
103
+ ? K
104
+ : Forbidden<"A map key must be a number, a string, a boolean, an enum or an instance. Anything else decodes to a fresh value nobody can look up; key by an id or a name.">;
105
+
106
+ type OptionalKeys<F extends Record<string, AnyType>> = {
107
+ [K in keyof F]: undefined extends F[K][typeof payload] ? K : never;
108
+ }[keyof F];
109
+
110
+ type StructPayload<F extends Record<string, AnyType>> = Simplify<
111
+ { [K in Exclude<keyof F, OptionalKeys<F>>]: F[K][typeof payload] } & {
112
+ [K in OptionalKeys<F>]?: F[K][typeof payload];
113
+ }
114
+ >;
115
+
116
+ type UnionPayload<B extends Record<string, AnyType>> = {
117
+ [K in keyof B]: { tag: K; value: B[K][typeof payload] };
118
+ }[keyof B];
119
+
120
+ /* What every member of a composition can accept: the intersection of what each one takes. */
121
+ type Accepted<P extends unknown[]> = {
122
+ [I in keyof P]: P[I] extends nw.Configured<infer T> ? (value: T) => void : never;
123
+ }[number] extends (value: infer T) => void
124
+ ? T
125
+ : never;
126
+
127
+ type NoAuthorize =
128
+ Forbidden<"A channel that authorizes is a command or a query. If you need to approve it, it is a command.">;
129
+ type NoBudget = Forbidden<"The server is the sender on this class, so there is nobody to budget.">;
130
+ type NoAudience =
131
+ Forbidden<"Only state, event and replicate have an audience. An inbound channel has one recipient, the server.">;
132
+ type NoReply = Forbidden<"Only a query replies, and only a query waits for a reply.">;
133
+ type NoStore = Forbidden<"Only replicate reads from a store and names a subject.">;
134
+ type MustArrive =
135
+ Forbidden<"This class has to arrive. unreliable would make the class name a promise it does not keep.">;
136
+ type NoData = Forbidden<"A query carries args and returns, not data.">;
137
+
138
+ interface InboundSpec {
139
+ /** Packets a second one player may send. There is no unlimited spelling. */
140
+ readonly rate: number;
141
+ /** How deep the token bucket is. One second's worth when omitted, and never below `rate`. */
142
+ readonly burst?: number;
143
+ /** Tightens the byte ceiling the schema derives. It can never raise it. */
144
+ readonly maxBytes?: number;
145
+ readonly audience?: NoAudience;
146
+ readonly store?: NoStore;
147
+ readonly subject?: NoStore;
148
+ }
149
+
150
+ interface CommandSpec<D extends AnyType> extends InboundSpec {
151
+ readonly data: D;
152
+ /** Who may. Built with `nw.policy`, or several composed with `nw.all`. */
153
+ readonly authorize: nw.Configured<nw.PayloadOf<NoInfer<D>>>;
154
+ readonly unreliable?: MustArrive;
155
+ readonly args?: NoReply;
156
+ readonly returns?: NoReply;
157
+ readonly timeout?: NoReply;
158
+ }
159
+
160
+ interface LooseSpec<D extends AnyType> extends InboundSpec {
161
+ readonly data: D;
162
+ /** Neither arrival nor order is promised. Right for input the next packet supersedes. */
163
+ readonly unreliable?: boolean;
164
+ readonly authorize?: NoAuthorize;
165
+ readonly args?: NoReply;
166
+ readonly returns?: NoReply;
167
+ readonly timeout?: NoReply;
168
+ }
169
+
170
+ interface QuerySpec<A extends AnyType, R extends AnyType> extends InboundSpec {
171
+ readonly args: A;
172
+ readonly returns: undefined extends nw.PayloadOf<R>
173
+ ? Forbidden<"A query cannot return a top-level optional: invoke reports failure as undefined, so the two would be one answer. Wrap it in a struct.">
174
+ : R;
175
+ /** Seconds until the caller gives up. Required, because a request that never resolves is a leaked thread. */
176
+ readonly timeout: number;
177
+ /** Who may. A read is how an exploit finds what to write, so a query is authorized like a command. */
178
+ readonly authorize: nw.Configured<nw.PayloadOf<NoInfer<A>>>;
179
+ readonly unreliable?: MustArrive;
180
+ readonly data?: NoData;
181
+ }
182
+
183
+ interface OutboundSpec {
184
+ readonly rate?: NoBudget;
185
+ readonly burst?: NoBudget;
186
+ readonly maxBytes?: NoBudget;
187
+ readonly authorize?: NoAuthorize;
188
+ readonly args?: NoReply;
189
+ readonly returns?: NoReply;
190
+ readonly timeout?: NoReply;
191
+ }
192
+
193
+ interface PublishSpec<D extends AnyType, S extends nw.Scope> extends OutboundSpec {
194
+ readonly data: D;
195
+ /** Who this reaches, evaluated against the subject it is published for. */
196
+ readonly audience: nw.Audience<S>;
197
+ /** A dropped packet costs one tick of staleness. Payloads over 908 bytes are refused at `send`. */
198
+ readonly unreliable?: boolean;
199
+ readonly store?: NoStore;
200
+ readonly subject?: NoStore;
201
+ }
202
+
203
+ interface ReplicateSpec<U extends AnyType, D extends AnyType, S extends nw.Scope> extends OutboundSpec {
204
+ /** The type of the key. It goes on the wire, because the client keeps one value per subject. */
205
+ readonly subject: U;
206
+ readonly data: D;
207
+ /** Who sees each subject. */
208
+ readonly audience: nw.Audience<S>;
209
+ /** Where the truth lives, and the only way in. */
210
+ readonly store: nw.Store<nw.PayloadOf<NoInfer<U>>, DeepReadonly<nw.PayloadOf<NoInfer<D>>>>;
211
+ readonly unreliable?: MustArrive;
212
+ }
213
+
214
+ /* Every key each class knows, forbidden ones included: those carry their own message. */
215
+ type CommandKeys = keyof CommandSpec<AnyType>;
216
+ type LooseKeys = keyof LooseSpec<AnyType>;
217
+ type QueryKeys = keyof QuerySpec<AnyType, AnyType>;
218
+ type PublishKeys = keyof PublishSpec<AnyType, nw.Scope>;
219
+ type ReplicateKeys = keyof ReplicateSpec<AnyType, AnyType, nw.Scope>;
220
+
221
+ /*
222
+ The keys each class takes, which its refusal of any other lists, in the order of the original's
223
+ `permit`. Written by hand, because a union has no order to print, and so held against the spec in
224
+ tests/types/extra_ok.ts: every key of it that is not forbidden, and no other.
225
+ */
226
+ type CommandTakes = ["data", "rate", "burst", "maxBytes", "authorize"];
227
+ type LooseTakes = ["data", "rate", "burst", "maxBytes", "unreliable"];
228
+ type QueryTakes = ["args", "returns", "rate", "burst", "maxBytes", "timeout", "authorize"];
229
+ type PublishTakes = ["data", "audience", "unreliable"];
230
+ type ReplicateTakes = ["subject", "data", "audience", "store"];
231
+
232
+ /* What nw.configure knows, sorted as the original sorts them, and held against `nw.Settings`, `nw.Rules` and `nw.Limits` there too. */
233
+ type SettingNames = ["contextGuard", "limits", "rules"];
234
+ type RuleNames = ["authorize", "budget", "direction", "handler", "parse", "protocol", "query", "queue", "rateUnbounded", "replicate", "send"];
235
+ type LimitNames = ["baselinesPerClient", "callsInFlight", "pendingPerBatch", "queueCapacity", "repeatsPerDiagnostic", "resyncTicks", "unreliableBytes"];
236
+
237
+ type Published<C extends nw.Class, S extends nw.Scope, T> = nw.Channel<
238
+ C,
239
+ [S] extends ["everyone"] ? nw.Broadcaster<T> : nw.Publisher<T>,
240
+ nw.Listener<T>
241
+ >;
242
+
243
+ // The schema vocabulary (PLAN-M1 D-5) ----------------------------------------------------------------
244
+
245
+ declare const schemaOf: unique symbol;
246
+ declare const fallbackOf: unique symbol;
247
+ declare const unfit: unique symbol;
248
+
249
+ /*
250
+ Carries `D` to rbxts-transformer-netweave and nothing to assignability. `D` is unused, so TypeScript
251
+ relates any two of these: a plain number goes into a `nw.u8<0, 9>`, and a `nw.u8` into a `nw.u16` or
252
+ a `number`. The schema says what is sent; `send` and the receiver check the range, as with `types.*`.
253
+ */
254
+ interface Note<D> {}
255
+
256
+ /* What a type of the vocabulary says about its schema, as a tuple whose first element is the kind. */
257
+ interface Mark<D> {
258
+ readonly [schemaOf]?: Note<D>;
259
+ }
260
+
261
+ /* What `nw.Default` says the absent value reads as. */
262
+ interface Fallback<V> {
263
+ readonly [fallbackOf]?: Note<V>;
264
+ }
265
+
266
+ /* The global types, under names the namespace's own `Vector2`, `Vector3` and `CFrame` do not hide. */
267
+ type GlobalVector2 = Vector2;
268
+ type GlobalVector3 = Vector3;
269
+ type GlobalCFrame = CFrame;
270
+
271
+ /*
272
+ What rbxts-transformer-netweave compares a type with, read off here so that they are the types this
273
+ file means and not whatever another declaration of the same name is.
274
+ */
275
+ interface Known {
276
+ vector2: Vector2;
277
+ vector3: Vector3;
278
+ cframe: CFrame;
279
+ color3: Color3;
280
+ buffer: buffer;
281
+ instance: Instance;
282
+ player: Player;
283
+ classes: keyof Instances;
284
+ array: Array<unknown>;
285
+ readonlyArray: ReadonlyArray<unknown>;
286
+ map: Map<unknown, unknown>;
287
+ readonlyMap: ReadonlyMap<unknown, unknown>;
288
+ set: Set<unknown>;
289
+ readonlySet: ReadonlySet<unknown>;
290
+ }
291
+
292
+ type Width = "u8" | "u16" | "u32" | "u53" | "i8" | "i16" | "i32" | "i53" | "f32" | "f64";
293
+ type Numeric<W extends Width, Min extends number, Max extends number> = number & Mark<[W, Min, Max]>;
294
+
295
+ /*
296
+ The check behind `schema<T>()`: `never` when `T` has a schema, and otherwise one `Unfit` per place that
297
+ has none. It walks `T` as rbxts-transformer-netweave does, and stops 8 levels down, so that a recursive
298
+ type is refused rather than expanded until TypeScript gives up. The depth is what bounds the work an
299
+ editor does for one call.
300
+ */
301
+ interface Unfit<Path extends string, Why extends string> {
302
+ readonly [unfit]: [Path, Why];
303
+ }
304
+
305
+ type Deeper = [1, 2, 3, 4, 5, 6, 7, 8, 9];
306
+ type Limit = 8;
307
+
308
+ type MarkOf<T> = T extends unknown ? (NonNullable<T[typeof schemaOf & keyof T]> extends Note<infer D> ? D : never) : never;
309
+ type KindOf<T> = MarkOf<T> extends [infer K, ...unknown[]] ? K : never;
310
+ type FallbackOf<T> = T extends unknown
311
+ ? NonNullable<T[typeof fallbackOf & keyof T]> extends Note<infer V>
312
+ ? V
313
+ : never
314
+ : never;
315
+
316
+ type IsUnion<T, U = T> = (T extends unknown ? ([U] extends [T] ? false : true) : never) extends false ? false : true;
317
+
318
+ type Prefix<K extends string, U> =
319
+ U extends Unfit<infer P, infer W> ? Unfit<P extends "" ? K : P extends `[${string}` ? `${K}${P}` : `${K}.${P}`, W> : never;
320
+
321
+ type Fit<T, D extends number = 0> = 0 extends 1 & T
322
+ ? Unfit<"", "is any, which has no schema; name the type">
323
+ : unknown extends T
324
+ ? Unfit<"", "is unknown, which has no schema; name the type">
325
+ : [T] extends [never]
326
+ ? Unfit<"", "is never, which has no schema">
327
+ : D extends Limit
328
+ ? Unfit<"", "is nested more than 8 deep, and a schema cannot be recursive">
329
+ : [T] extends [undefined]
330
+ ? Unfit<"", "is undefined alone; a value that may be absent is T | undefined">
331
+ : [T] extends [void]
332
+ ? Unfit<"", "is void, which has no schema">
333
+ : undefined extends T
334
+ ? typeof fallbackOf extends keyof Exclude<T, undefined>
335
+ ? Unfit<"", "has a default, so it is never absent; drop the ? or the | undefined">
336
+ : FitPresent<Exclude<T, undefined>, D>
337
+ : FitPresent<T, D>;
338
+
339
+ type FitPresent<T, D extends number> = typeof fallbackOf extends keyof T
340
+ ? FitDefault<T>
341
+ : [T] extends [boolean]
342
+ ? never
343
+ : [T] extends [string]
344
+ ? FitText<T>
345
+ : [T] extends [number]
346
+ ? FitNumber<T>
347
+ : [T] extends [buffer]
348
+ ? typeof schemaOf extends keyof T
349
+ ? FitBounds<MarkOf<T>>
350
+ : never
351
+ : [T] extends [Color3]
352
+ ? never
353
+ : [T] extends [GlobalVector2 | GlobalVector3 | GlobalCFrame]
354
+ ? FitVector<T>
355
+ : [T] extends [Instance]
356
+ ? IsUnion<T> extends true
357
+ ? Unfit<"", "is a union of instance classes; name a class they share">
358
+ : never
359
+ : [T] extends [(...args: never) => unknown]
360
+ ? Unfit<"", "is a function, which cannot cross the network">
361
+ : [T] extends [ReadonlyArray<infer E>]
362
+ ? FitList<T, E, D>
363
+ : [T] extends [ReadonlyMap<infer K, infer V>]
364
+ ? FitKey<K, "key", D> | Prefix<"value", Fit<V, Deeper[D]>>
365
+ : [T] extends [ReadonlySet<infer E>]
366
+ ? FitKey<E, "element", D>
367
+ : IsUnion<T> extends true
368
+ ? FitUnion<T, D>
369
+ : typeof schemaOf extends keyof T
370
+ ? FitUnion<T, D>
371
+ : [Extract<keyof T, `_nominal_${string}`>] extends [never]
372
+ ? FitStruct<T, D>
373
+ : Unfit<"", "is a Roblox type that netweave has no schema for">;
374
+
375
+ type NotLiteral<V, What extends string> = [V] extends [never]
376
+ ? never
377
+ : number extends V
378
+ ? Unfit<"", `has ${What} that is number; write a number literal`>
379
+ : string extends V
380
+ ? Unfit<"", `has ${What} that is string; write a string literal`>
381
+ : boolean extends V
382
+ ? Unfit<"", `has ${What} that is boolean; write true or false`>
383
+ : IsUnion<V> extends true
384
+ ? Unfit<"", `has ${What} that is a union; write one literal`>
385
+ : never;
386
+
387
+ type FitBounds<M> = M extends [unknown, infer Min, infer Max, ...infer Rest]
388
+ ? [Min] extends [never]
389
+ ? never
390
+ : [Max] extends [never]
391
+ ? M extends ["array", ...unknown[]]
392
+ ? NotLiteral<Min, "a length">
393
+ : Unfit<"", "has a minimum and no maximum; give both bounds">
394
+ : NotLiteral<Min, "a bound"> | NotLiteral<Max, "a bound"> | (Rest extends [infer Step, ...unknown[]] ? NotLiteral<Step, "a step"> : never)
395
+ : never;
396
+
397
+ type FitNumber<T> = typeof schemaOf extends keyof T
398
+ ? KindOf<T> extends Width | "quantized"
399
+ ? FitBounds<MarkOf<T>>
400
+ : Unfit<"", "is a number marked as something else">
401
+ : number extends T
402
+ ? Unfit<"", "is a number without a width; write nw.u8, nw.i16<-300, 300>, nw.f32 or nw.Quantized<0, 1, 0.25>">
403
+ : IsUnion<T> extends true
404
+ ? Unfit<"", "is a union of numbers; use a union of names, which is an enum, or a number with a range">
405
+ : never;
406
+
407
+ type FitTextOptions<O> = [O] extends [never]
408
+ ? never
409
+ : { [K in keyof O]-?: NotLiteral<O[K], `a ${K & string} option`> }[keyof O];
410
+
411
+ type FitText<T> = typeof schemaOf extends keyof T
412
+ ? KindOf<T> extends "string"
413
+ ? FitBounds<MarkOf<T>> | FitTextOptions<MarkOf<T>[3 & keyof MarkOf<T>]>
414
+ : string extends T
415
+ ? Unfit<"", "is an enum of string; its names are string literals">
416
+ : never
417
+ : never;
418
+
419
+ type FitDefault<T> = FallbackOf<T> extends infer V
420
+ ? [T] extends [boolean]
421
+ ? NotLiteral<V, "a default">
422
+ : [T] extends [string]
423
+ ? typeof schemaOf extends keyof T
424
+ ? FitText<T> | NotLiteral<V, "a default">
425
+ : string extends T
426
+ ? NotLiteral<V, "a default">
427
+ : IsUnion<T> extends true
428
+ ? NotLiteral<V, "a default">
429
+ : Unfit<"", "has a default on a literal, which is the only value it can have">
430
+ : [T] extends [number]
431
+ ? typeof schemaOf extends keyof T
432
+ ? FitNumber<T> | NotLiteral<V, "a default">
433
+ : Unfit<"", "has a default on a number without a width or on a literal">
434
+ : Unfit<"", "has a default, which only a number, a string, a boolean or an enum takes">
435
+ : never;
436
+
437
+ type FitVector<T> = IsUnion<T> extends true
438
+ ? Unfit<"", "is a union of datatypes; pick one">
439
+ : typeof schemaOf extends keyof T
440
+ ? MarkOf<T> extends [unknown, infer C]
441
+ ? [C] extends [never]
442
+ ? never
443
+ : typeof schemaOf extends keyof C
444
+ ? KindOf<C> extends Width | "quantized"
445
+ ? Prefix<"component", FitBounds<MarkOf<C>>>
446
+ : Unfit<"component", "is not a number with a width">
447
+ : Unfit<"component", "is not a number with a width; write nw.f32, nw.i16<-2048, 2048> or nw.Quantized<-1, 1, 0.25>">
448
+ : never
449
+ : never;
450
+
451
+ type FitList<T, E, D extends number> = "length" extends keyof T
452
+ ? Unfit<"", "is a tuple, which has no schema; write nw.List<T, 3> for a fixed length">
453
+ :
454
+ | (typeof schemaOf extends keyof T ? FitBounds<MarkOf<T>> : never)
455
+ | (undefined extends E
456
+ ? MarkOf<T> extends ["array", infer Min, infer Max]
457
+ ? [Min] extends [never]
458
+ ? Unfit<"", "holds optionals and has no exact length; write nw.List<T | undefined, 4>">
459
+ : [Max] extends [never]
460
+ ? Prefix<"[]", Fit<E, Deeper[D]>>
461
+ : Unfit<"", "holds optionals and has no exact length; write nw.List<T | undefined, 4>">
462
+ : Unfit<"", "holds optionals and has no exact length; write nw.List<T | undefined, 4>">
463
+ : Prefix<"[]", Fit<E, Deeper[D]>>);
464
+
465
+ type FitKey<K, Where extends string, D extends number> = undefined extends K
466
+ ? Unfit<Where, "may be absent, and a Luau table has no nil key">
467
+ : [K] extends [Primitive | Instance]
468
+ ? Prefix<Where, Fit<K, Deeper[D]>>
469
+ : Unfit<
470
+ Where,
471
+ "is not a number, a string, a boolean, an enum or an instance. Anything else decodes to a fresh value nobody can look up; key by an id or a name."
472
+ >;
473
+
474
+ type FitUnion<T, D extends number> = T extends { tag: infer G; value: infer V }
475
+ ? [Exclude<keyof T, "tag" | "value" | typeof schemaOf>] extends [never]
476
+ ? [G] extends [string]
477
+ ? string extends G
478
+ ? Unfit<"", "has a tag that is string; a tag is a string literal">
479
+ : IsUnion<G> extends true
480
+ ? Unfit<"", "has a tag that is a union; a tag is one string literal">
481
+ : Prefix<G & string, Fit<V, Deeper[D]>>
482
+ : Unfit<"", "has a tag that is not a string literal">
483
+ : Unfit<"", "is one of several objects that are not each { tag, value }; write nw.Union<{ a: A; b: B }>">
484
+ : Unfit<"", "is a union netweave has no schema for: only string literals (an enum) and { tag, value } objects (a union) can be one of several">;
485
+
486
+ type FitStruct<T, D extends number> = string extends keyof T
487
+ ? Unfit<"", "has an index signature; a record of any keys is a Map">
488
+ : number extends keyof T
489
+ ? Unfit<"", "has an index signature; a record of any keys is a Map">
490
+ : [keyof T] extends [never]
491
+ ? Unfit<"", "has no fields, and a struct needs one">
492
+ : [Exclude<keyof T, string>] extends [never]
493
+ ? { [K in keyof T]: Prefix<K & string, Fit<T[K], Deeper[D]>> }[keyof T]
494
+ : Unfit<"", "has a key that is not a name">;
495
+
496
+ type Reported<U> = U extends Unfit<infer P, infer W> ? Forbidden<P extends "" ? `schema<T>: T ${W}` : `schema<T>: ${P} ${W}`> : never;
497
+
498
+ declare namespace nw {
499
+ // Schemas -----------------------------------------------------------------------------------
500
+
501
+ /** What a schema describes. */
502
+ type Kind =
503
+ | "boolean"
504
+ | "number"
505
+ | "string"
506
+ | "buffer"
507
+ | "vector2"
508
+ | "vector3"
509
+ | "cframe"
510
+ | "color3"
511
+ | "instance"
512
+ | "enum"
513
+ | "literal"
514
+ | "optional"
515
+ | "array"
516
+ | "map"
517
+ | "struct"
518
+ | "union";
519
+
520
+ /**
521
+ * A schema whose payload is `T`. Build one with {@link types}; one declaration yields the payload
522
+ * type, the validation and the serialisation.
523
+ *
524
+ * Invariant in `T`: a schema that is missing a field is not a schema for the type that has it.
525
+ */
526
+ interface Type<T> {
527
+ readonly kind: Kind;
528
+ readonly [payload]: T;
529
+ readonly [invariant]: (value: T) => T;
530
+ }
531
+
532
+ /**
533
+ * The payload type of a schema, so that it cannot drift from the wire.
534
+ *
535
+ * @example
536
+ * const Equip = t.struct({ slot: t.u8(0, 9) });
537
+ * type Equip = t.PayloadOf<typeof Equip>;
538
+ */
539
+ type PayloadOf<D extends AnyType> = D[typeof payload];
540
+
541
+ /** A schema usable bare, and callable to bound it: a value range for numbers, a length for buffers. */
542
+ interface Ranged<T> extends Type<T> {
543
+ (min: number, max: number): Type<T>;
544
+ }
545
+
546
+ /** What `t.string` takes after its length. `charset` and `pattern` cannot both be given. */
547
+ type TextOptions = {
548
+ /** The bytes must decode as UTF-8. */
549
+ readonly utf8?: boolean;
550
+ } & (
551
+ | {
552
+ /** A Lua pattern the whole value must match. Refused at declaration when its worst case is unbounded. */
553
+ readonly pattern?: string;
554
+ readonly charset?: undefined;
555
+ }
556
+ | {
557
+ /** A Lua character class, written without the brackets. Linear whatever a client sends. */
558
+ readonly charset?: string;
559
+ readonly pattern?: undefined;
560
+ }
561
+ );
562
+
563
+ /** A string schema, callable to bound the length in bytes and what the bytes may contain. */
564
+ interface Text extends Type<string> {
565
+ (min: number, max: number, options?: TextOptions): Type<string>;
566
+ }
567
+
568
+ /** A vector schema, callable with the schema its components are carried at. */
569
+ interface Componented<T> extends Type<T> {
570
+ (component: Type<number>): Type<T>;
571
+ }
572
+
573
+ interface InstanceOptions {
574
+ /** The container an arrival must be inside. */
575
+ readonly descendantOf?: Instance;
576
+ }
577
+
578
+ /**
579
+ * An instance schema, callable with a class name. Stricter than the original, whose payload stays
580
+ * `Instance`: `t.instance("Sound")` is a `Type<Sound>`.
581
+ */
582
+ interface Classed extends Type<Instance> {
583
+ <N extends keyof Instances>(className: N, options?: InstanceOptions): Type<Instances[N]>;
584
+ }
585
+
586
+ /** The type vocabulary. Every type is bounded, and that is where the byte ceilings come from. */
587
+ interface Types {
588
+ /** A whole number in 0..255. `t.u8(0, 10)` narrows it further. */
589
+ readonly u8: Ranged<number>;
590
+ /** A whole number in 0..65535. */
591
+ readonly u16: Ranged<number>;
592
+ /** A whole number in 0..4294967295. */
593
+ readonly u32: Ranged<number>;
594
+ /** A whole number in 0..2^53: a UserId, a timestamp. Eight bytes bare, narrowed by a range. */
595
+ readonly u53: Ranged<number>;
596
+ /** A whole number in -128..127. */
597
+ readonly i8: Ranged<number>;
598
+ /** A whole number in -32768..32767. */
599
+ readonly i16: Ranged<number>;
600
+ /** A whole number in -2147483648..2147483647. */
601
+ readonly i32: Ranged<number>;
602
+ /** `u53` with a sign. */
603
+ readonly i53: Ranged<number>;
604
+ /** Four bytes, about seven significant digits. A range validates and never narrows the storage. */
605
+ readonly f32: Ranged<number>;
606
+ /** Eight bytes, every finite number. */
607
+ readonly f64: Ranged<number>;
608
+ /**
609
+ * A fraction carried as a count of steps from `min`, in the narrowest storage that holds the
610
+ * count. The value comes back rounded to the nearest step, and the range has to divide into a
611
+ * whole number of them.
612
+ */
613
+ readonly quantized: (min: number, max: number, step: number) => Type<number>;
614
+ /** One bit, shared with the other flags of the struct it is in. */
615
+ readonly boolean: Type<boolean>;
616
+ /** A length-prefixed string. The length is in bytes. */
617
+ readonly string: Text;
618
+ /** A length-prefixed buffer. */
619
+ readonly buffer: Ranged<buffer>;
620
+ /** Two `f32`, or two of whatever you name: `t.vector2(t.i16(-1024, 1024))`. */
621
+ readonly vector2: Componented<GlobalVector2>;
622
+ /** Three `f32`, and unbounded. Name a component to say where the map is. */
623
+ readonly vector3: Componented<GlobalVector3>;
624
+ /** A direction: a magnitude that is not 1 is refused. */
625
+ readonly unitVector3: Componented<GlobalVector3>;
626
+ /** Twenty-four bytes bare. Named, the position is the component's and the rotation is six bytes. */
627
+ readonly cframe: Componented<GlobalCFrame>;
628
+ /** Three bytes. */
629
+ readonly color3: Type<Color3>;
630
+ /** An instance, carried beside the buffer. `t.instance("Sound")` refuses anything else. */
631
+ readonly instance: Classed;
632
+ /** A `Player`. One that arrives is not necessarily still here; `ctx.player` is the sender. */
633
+ readonly player: Type<Player>;
634
+ /** A closed set of names, as keys: `t.enum({ primary: true, secondary: true })`. */
635
+ readonly enum: <V extends Record<string, true>>(
636
+ variants: NonEmpty<V, "An enum needs at least one variant.">,
637
+ ) => Type<keyof V & string>;
638
+ /** One value both sides already know, costing nothing on the wire. */
639
+ readonly literal: <const V extends Primitive>(value: V) => Type<V>;
640
+ readonly optional: {
641
+ /** A value that may be absent, at one bit. */
642
+ <D extends AnyType>(
643
+ inner: D,
644
+ ): undefined extends PayloadOf<D>
645
+ ? Forbidden<"An optional cannot wrap an optional.">
646
+ : Type<PayloadOf<D> | undefined>;
647
+ /** Absent reads as `fallback`, and `fallback` is never sent. Number, string, boolean or enum only. */
648
+ <D extends AnyType>(
649
+ inner: D,
650
+ fallback: [PayloadOf<D>] extends [Primitive]
651
+ ? PayloadOf<NoInfer<D>>
652
+ : Forbidden<"t.optional takes a default only for a number, a string, a boolean or an enum.">,
653
+ ): Type<PayloadOf<D>>;
654
+ };
655
+ readonly array: {
656
+ /** Exactly `length` elements, and no length prefix. The elements may be optional. */
657
+ <D extends AnyType>(element: D, length: number): Type<PayloadOf<D>[]>;
658
+ /** Between `min` and `max` elements; 0..65535 when omitted. */
659
+ <D extends AnyType>(
660
+ element: D,
661
+ min?: number,
662
+ max?: number,
663
+ ): undefined extends PayloadOf<D>
664
+ ? Forbidden<"An array of optionals needs an exact length, because a list with holes has no length Luau agrees on.">
665
+ : Type<PayloadOf<D>[]>;
666
+ };
667
+ /** Key and value pairs. */
668
+ readonly map: <K extends AnyType, V extends AnyType>(
669
+ key: K & MapKey<K>,
670
+ value: V,
671
+ ) => Type<Map<PayloadOf<K>, PayloadOf<V>>>;
672
+ /** A set of values: its count and its entries, and no more. */
673
+ readonly set: <E extends AnyType>(element: E & MapKey<E>) => Type<Set<PayloadOf<E>>>;
674
+ /** A record. Fields are written in name order, so the order they are declared in is free. */
675
+ readonly struct: <F extends Record<string, AnyType>>(
676
+ fields: NonEmpty<F, "A struct needs at least one field.">,
677
+ ) => Type<StructPayload<F>>;
678
+ /** One of several shapes. The payload is `{ tag, value }`, so comparing `tag` narrows `value`. */
679
+ readonly union: <B extends Record<string, AnyType>>(
680
+ branches: NonEmpty<B, "A union needs at least one branch.">,
681
+ ) => Type<UnionPayload<B>>;
682
+ }
683
+
684
+ /** The type vocabulary, usually imported as `t`: `import nw, { types as t } from "@rbxts/netweave"`. */
685
+ const types: Types;
686
+
687
+ /* The same name as a namespace, so that `t.PayloadOf<typeof Schema>` works through the import. */
688
+ namespace types {
689
+ export type Type<T> = nw.Type<T>;
690
+ export type PayloadOf<D extends AnyType> = nw.PayloadOf<D>;
691
+ export type Kind = nw.Kind;
692
+ export type Ranged<T> = nw.Ranged<T>;
693
+ export type Text = nw.Text;
694
+ export type TextOptions = nw.TextOptions;
695
+ export type Componented<T> = nw.Componented<T>;
696
+ export type Classed = nw.Classed;
697
+ export type InstanceOptions = nw.InstanceOptions;
698
+ }
699
+
700
+ // The schema vocabulary ---------------------------------------------------------------------
701
+
702
+ /*
703
+ Payload types that say how they are carried, for `schema<T>()` of `@rbxts/netweave/macros`, which
704
+ rbxts-transformer-netweave compiles to the `types.*` call each one names (PLAN-M1 D-5). A value of
705
+ one is an ordinary value: `{ slot: 3 }` is an `{ slot: nw.u8<0, 9> }`, and the slot is a number.
706
+ Everything else a schema can be is written as TypeScript writes it: `boolean`, `string`, `buffer`,
707
+ `Vector3`, `Color3`, `Instance`, a class such as `Part`, `Player`, a literal, a union of string
708
+ literals, `T | undefined`, `T[]`, `Map`, `Set`, an interface, and `{ tag, value }` objects.
709
+ */
710
+
711
+ /** A whole number in 0..255, carried as `types.u8`; `nw.u8<0, 9>` is `types.u8(0, 9)`. */
712
+ type u8<Min extends number = never, Max extends number = never> = Numeric<"u8", Min, Max>;
713
+ /** A whole number in 0..65535, carried as `types.u16`. */
714
+ type u16<Min extends number = never, Max extends number = never> = Numeric<"u16", Min, Max>;
715
+ /** A whole number in 0..4294967295, carried as `types.u32`. */
716
+ type u32<Min extends number = never, Max extends number = never> = Numeric<"u32", Min, Max>;
717
+ /** A whole number in 0..2^53, carried as `types.u53`. */
718
+ type u53<Min extends number = never, Max extends number = never> = Numeric<"u53", Min, Max>;
719
+ /** A whole number in -128..127, carried as `types.i8`. */
720
+ type i8<Min extends number = never, Max extends number = never> = Numeric<"i8", Min, Max>;
721
+ /** A whole number in -32768..32767, carried as `types.i16`. */
722
+ type i16<Min extends number = never, Max extends number = never> = Numeric<"i16", Min, Max>;
723
+ /** A whole number in -2147483648..2147483647, carried as `types.i32`. */
724
+ type i32<Min extends number = never, Max extends number = never> = Numeric<"i32", Min, Max>;
725
+ /** `nw.u53` with a sign, carried as `types.i53`. */
726
+ type i53<Min extends number = never, Max extends number = never> = Numeric<"i53", Min, Max>;
727
+ /** Four bytes, carried as `types.f32`. A range validates and never narrows the storage. */
728
+ type f32<Min extends number = never, Max extends number = never> = Numeric<"f32", Min, Max>;
729
+ /** Eight bytes, carried as `types.f64`. */
730
+ type f64<Min extends number = never, Max extends number = never> = Numeric<"f64", Min, Max>;
731
+
732
+ /**
733
+ * A fraction carried as a count of steps, `types.quantized(Min, Max, Step)`. A step that is a
734
+ * quotient is written as the number it comes to: `2 / 254` is `0.007874015748031496`, the same double.
735
+ */
736
+ type Quantized<Min extends number, Max extends number, Step extends number> = number &
737
+ Mark<["quantized", Min, Max, Step]>;
738
+
739
+ /** A string of `Min` to `Max` bytes, `types.string(Min, Max, Options)`. A bare `string` is `types.string`. */
740
+ type Str<Min extends number, Max extends number, Options extends TextOptions = never> = string &
741
+ Mark<["string", Min, Max, Options]>;
742
+
743
+ /** A buffer of `Min` to `Max` bytes, `types.buffer(Min, Max)`. A bare `buffer` is `types.buffer`. */
744
+ type Buf<Min extends number, Max extends number> = buffer & Mark<["buffer", Min, Max]>;
745
+
746
+ /** `Vector2` carried at the component `C`, `types.vector2(C)`. Without `C` it is `Vector2`. */
747
+ type Vector2<C extends number = never> = [C] extends [never] ? GlobalVector2 : GlobalVector2 & Mark<["vector2", C]>;
748
+
749
+ /** `Vector3` carried at the component `C`, `types.vector3(C)`. Without `C` it is `Vector3`. */
750
+ type Vector3<C extends number = never> = [C] extends [never] ? GlobalVector3 : GlobalVector3 & Mark<["vector3", C]>;
751
+
752
+ /** A direction, `types.unitVector3`, or `types.unitVector3(C)` with a component. */
753
+ type UnitVector3<C extends number = never> = GlobalVector3 & Mark<["unitVector3", C]>;
754
+
755
+ /** `CFrame` with its position carried at the component `C`, `types.cframe(C)`. Without `C` it is `CFrame`. */
756
+ type CFrame<C extends number = never> = [C] extends [never] ? GlobalCFrame : GlobalCFrame & Mark<["cframe", C]>;
757
+
758
+ /**
759
+ * A list. `nw.List<T, 3>` is exactly three, `types.array(T, 3)`, and the only list whose elements may
760
+ * be optional; `nw.List<T, 0, 8>` is `types.array(T, 0, 8)`. A bare `T[]` is `types.array(T)`.
761
+ */
762
+ type List<T, Min extends number = never, Max extends number = never> = T[] & Mark<["array", Min, Max]>;
763
+
764
+ /**
765
+ * A value that reads as `Value` when it is absent, and is not sent when it is `Value`:
766
+ * `types.optional(T, Value)`. The field takes no `?`, because the payload always has it.
767
+ */
768
+ type Default<T extends Primitive, Value extends T> = T & Fallback<Value>;
769
+
770
+ /** An enum of the names `V`, `types.enum`. Needed only for one name: `"a" | "b"` is an enum already. */
771
+ type Enum<V extends string> = V & Mark<["enum"]>;
772
+
773
+ /**
774
+ * One of the branches of `B`, as the `{ tag, value }` objects `types.union(B)` carries. Needed only for
775
+ * one branch: a union of two or more `{ tag, value }` objects is a union already.
776
+ */
777
+ type Union<B extends object> = {
778
+ [K in keyof B & string]: { tag: K; value: B[K] } & Mark<["union"]>;
779
+ }[keyof B & string];
780
+
781
+ /**
782
+ * `unknown` when `T` has a schema, and otherwise what is wrong with it, as a type no value has. It is
783
+ * the constraint of `schema<T>()`, so that a type without one is refused where it is written.
784
+ */
785
+ type Schemable<T> = [Exclude<Fit<T>, undefined>] extends [never] ? unknown : Reported<Exclude<Fit<T>, undefined>>;
786
+
787
+ // Trust -------------------------------------------------------------------------------------
788
+
789
+ /** The mark `Trusted<T>` carries. Named only so that declaration files can print it. */
790
+ interface TrustedMark {
791
+ readonly [trusted]: true;
792
+ }
793
+
794
+ /** The mark `Untrusted<T>` carries. Named only so that declaration files can print it. */
795
+ interface UntrustedMark {
796
+ readonly [untrusted]: true;
797
+ }
798
+
799
+ /**
800
+ * A value that passed the checks its channel declares. Produced by a `command` handler, a `query`
801
+ * handler and {@link validate}, and by nothing else. Write it on every function that changes
802
+ * authoritative state; the protection is exactly as wide as those annotations.
803
+ *
804
+ * Stricter than the original, which can brand tables only: here `Trusted<number>` is not `number`.
805
+ */
806
+ type Trusted<T> = T extends undefined ? T : T & TrustedMark;
807
+
808
+ /**
809
+ * A value that arrived from a client and fits its schema, and nothing more. It is still a `T`, so
810
+ * reading it, adding to it and printing it work; it does not fit a parameter that wants `Trusted<T>`.
811
+ *
812
+ * Stricter than the original, which can brand tables only.
813
+ */
814
+ type Untrusted<T> = T extends undefined ? T : T & UntrustedMark;
815
+
816
+ /**
817
+ * Checks a value that did not arrive on a channel, such as a DataStore row or an HTTP body. What
818
+ * comes back is a copy holding exactly the keys the schema names. It runs no policy.
819
+ *
820
+ * Stricter than the original: an `Untrusted` payload is refused, because washing one through here
821
+ * would turn "fits the schema" into "was authorized".
822
+ */
823
+ function validate<D extends AnyType, V>(
824
+ schema: D,
825
+ value: V & NotUntrusted<V>,
826
+ ): LuaTuple<[value: Trusted<PayloadOf<D>>, failure: undefined] | [value: undefined, failure: string]>;
827
+
828
+ // Policies ----------------------------------------------------------------------------------
829
+
830
+ /**
831
+ * What a policy and a handler are told about the request. Valid only until the handler returns:
832
+ * the record is reused per player, so copy the fields you need to keep.
833
+ */
834
+ interface Ctx {
835
+ /** The sender. */
836
+ readonly player: Player;
837
+ /** The qualified channel name. */
838
+ readonly channel: string;
839
+ /** Looked up the first time something reads it. */
840
+ readonly character?: Model;
841
+ /** Looked up the first time something reads it. */
842
+ readonly humanoid?: Humanoid;
843
+ /** `os.clock()` when the packet was dispatched. */
844
+ readonly now: number;
845
+ }
846
+
847
+ /** What a check returns: {@link allow} or {@link deny}. A shared record, so never keep one. */
848
+ interface Verdict {
849
+ readonly ok: boolean;
850
+ readonly value: unknown;
851
+ readonly reason?: string;
852
+ }
853
+
854
+ /** The per-request half of a policy. It must not yield. */
855
+ type Check<T> = (ctx: Ctx, payload: T) => Verdict;
856
+
857
+ /**
858
+ * The load-time half of a policy. It runs on both sides, because the declaration does. To reach a
859
+ * server-only module, return a second function as well: `return $tuple(check, stage)`. The stage
860
+ * runs once, on the server, before any packet decodes.
861
+ *
862
+ * `config` is whatever the policy was called with, and an empty table when it was used bare, so
863
+ * annotate it with optional fields.
864
+ */
865
+ type Factory<T> = (config: any) => Check<T> | LuaTuple<[check: Check<T>, stage: () => void]>;
866
+
867
+ /** What `authorize` takes and {@link all} returns. {@link Policy} is one that can also be configured. */
868
+ interface Configured<T> {
869
+ readonly [policyOf]: (payload: T) => void;
870
+ }
871
+
872
+ /** What {@link policy} returns. `authorize` takes it as it is, or called to configure it. */
873
+ interface Policy<T> extends Configured<T> {
874
+ (config: object): Configured<T>;
875
+ }
876
+
877
+ /**
878
+ * Declares a policy: the outer function runs once, the one it returns runs per request. A policy
879
+ * that ignores the payload writes it `unknown` and goes on any channel.
880
+ *
881
+ * Stricter than the original: the payload has to accept what the channel carries.
882
+ *
883
+ * @example
884
+ * const ownsSlot = nw.policy((config: { slots?: number }) => {
885
+ * const slots = config.slots ?? 3;
886
+ * return (_ctx: nw.Ctx, request: Equip) => (request.slot > slots ? nw.deny("no such slot") : nw.allow());
887
+ * });
888
+ */
889
+ function policy<T = unknown>(factory: Factory<T>): Policy<T>;
890
+
891
+ /**
892
+ * Every policy must allow, left to right; the first denial wins. Put the cheap check first.
893
+ *
894
+ * Stricter than the original, whose type lets a composition be configured: the runtime raises on
895
+ * every such call, so configure the members instead.
896
+ */
897
+ function all<P extends [Configured<any>, ...Configured<any>[]]>(...policies: P): Configured<Accepted<P>>;
898
+
899
+ /** Approves the request. With a value, that value is what the next policy and the handler receive. */
900
+ function allow(value?: unknown): Verdict;
901
+
902
+ /** Refuses the request. The reason reaches {@link observe} and is never sent to the client. */
903
+ function deny(reason: string): Verdict;
904
+
905
+ // Audiences and stores ----------------------------------------------------------------------
906
+
907
+ /** Whether an audience is provably every player. Only `everyone` gets `broadcast`. */
908
+ type Scope = "everyone" | "subset";
909
+
910
+ /** Who a server-to-client channel reaches. Build one with {@link audience}. */
911
+ interface Audience<S extends Scope = Scope> {
912
+ readonly scope: S;
913
+ readonly kind: "everyone" | "owner" | "nearby" | "select";
914
+ readonly [audienceOf]: true;
915
+ }
916
+
917
+ const audience: {
918
+ /** Every connected player. The only audience with `broadcast`. */
919
+ readonly everyone: Audience<"everyone">;
920
+ /** The player the published subject belongs to. A player owns itself, a character its player. */
921
+ readonly owner: Audience<"subset">;
922
+ /** Players within `studs` of the subject. */
923
+ readonly nearby: (studs: number) => Audience<"subset">;
924
+ /**
925
+ * The players your function returns for a subject. It runs per publish, and per subject per
926
+ * tick on `replicate`, so return a list you already keep; for a subject it does not know,
927
+ * return an empty one.
928
+ *
929
+ * The subject is whatever the publisher passes. Annotating it is a claim nothing checks.
930
+ */
931
+ readonly select: <U = unknown>(chooser: (subject: U) => ReadonlyArray<Player>) => Audience<"subset">;
932
+ };
933
+
934
+ /**
935
+ * Where the game keeps what `replicate` sends. Anything with these two functions is one; write
936
+ * them as arrow functions, because they are called without `self`.
937
+ */
938
+ interface Store<K = any, V = any> {
939
+ /** Every subject that exists right now. */
940
+ readonly subjects: () => ReadonlyArray<K>;
941
+ /** The current value, or undefined when the subject is gone. */
942
+ readonly read: (subject: K) => V | undefined;
943
+ }
944
+
945
+ const store: {
946
+ readonly of: {
947
+ /** A table the game writes to, read live once a tick. */
948
+ <K, V>(source: ReadonlyMap<K, V>): Store<K, V>;
949
+ <V>(source: Readonly<Record<string, V>>): Store<string, V>;
950
+ };
951
+ /** A Charm atom, or any getter, holding subject to value. */
952
+ readonly charm: <K, V>(getter: () => ReadonlyMap<K, V>) => Store<K, V>;
953
+ /** ReplicaService replicas, read at `Data`. */
954
+ readonly replica: <K, V>(replicas: ReadonlyMap<K, { readonly Data: V }>) => Store<K, V>;
955
+ };
956
+
957
+ // Channels ----------------------------------------------------------------------------------
958
+
959
+ /** A class is a security obligation, not a transport mode. */
960
+ type Class = "command" | "intent" | "signal" | "query" | "state" | "event" | "replicate";
961
+
962
+ /**
963
+ * A declared channel. Opaque, and stricter than the original for it: the record's fields can be
964
+ * read there, and through a mutable alias written.
965
+ */
966
+ interface Channel<C extends Class, S, L> {
967
+ readonly [channelClass]: C;
968
+ readonly [serverView]: S;
969
+ readonly [clientView]: L;
970
+ }
971
+
972
+ /** Any declared channel. */
973
+ interface AnyChannel {
974
+ readonly [channelClass]: Class;
975
+ readonly [serverView]: unknown;
976
+ readonly [clientView]: unknown;
977
+ }
978
+
979
+ /**
980
+ * Client to server, and it changes authoritative state. The handler receives `Trusted<T>`: decoded,
981
+ * inside the declared rate, and approved.
982
+ */
983
+ function command<D extends AnyType, K = unknown>(
984
+ spec: CommandSpec<D> & OnlyKeys<K, CommandKeys, "nw.command", CommandTakes>,
985
+ ): Channel<"command", Inbound<Trusted<PayloadOf<D>>>, Sender<PayloadOf<D>>>;
986
+
987
+ /**
988
+ * Client to server, continuous input the server judges on its own tick. It coalesces: the handler
989
+ * runs at most once per player per tick with the newest value, and the client sends at `rate`
990
+ * however often `send` is called.
991
+ */
992
+ function intent<D extends AnyType, K = unknown>(
993
+ spec: LooseSpec<D> & OnlyKeys<K, LooseKeys, "nw.intent", LooseTakes>,
994
+ ): Channel<"intent", Inbound<PayloadOf<D>>, Sender<PayloadOf<D>>>;
995
+
996
+ /**
997
+ * Client to server, and it carries no authority. The handler receives `Untrusted<T>`, which does
998
+ * not fit a function that wants `Trusted<T>`.
999
+ */
1000
+ function signal<D extends AnyType, K = unknown>(
1001
+ spec: LooseSpec<D> & OnlyKeys<K, LooseKeys, "nw.signal", LooseTakes>,
1002
+ ): Channel<"signal", Inbound<Untrusted<PayloadOf<D>>>, Sender<PayloadOf<D>>>;
1003
+
1004
+ /** A request that expects an answer, authorized like a command. */
1005
+ function query<A extends AnyType, R extends AnyType, K = unknown>(
1006
+ spec: QuerySpec<A, R> & OnlyKeys<K, QueryKeys, "nw.query", QueryTakes>,
1007
+ ): Channel<"query", Handling<Trusted<PayloadOf<A>>, PayloadOf<R>>, Invoker<PayloadOf<A>, PayloadOf<R>>>;
1008
+
1009
+ /** Server to client, the current value of a subject, every time you publish it. */
1010
+ function state<D extends AnyType, S extends Scope, K = unknown>(
1011
+ spec: PublishSpec<D, S> & OnlyKeys<K, PublishKeys, "nw.state", PublishTakes>,
1012
+ ): Published<"state", S, PayloadOf<D>>;
1013
+
1014
+ /** Server to client, something that happened once. */
1015
+ function event<D extends AnyType, S extends Scope, K = unknown>(
1016
+ spec: PublishSpec<D, S> & OnlyKeys<K, PublishKeys, "nw.event", PublishTakes>,
1017
+ ): Published<"event", S, PayloadOf<D>>;
1018
+
1019
+ /**
1020
+ * Server to client, sent as changes against what each client already has. The server never calls
1021
+ * it: `store` is read once a tick, and each client is sent what it is missing.
1022
+ */
1023
+ function replicate<U extends AnyType, D extends AnyType, S extends Scope, K = unknown>(
1024
+ spec: ReplicateSpec<U, D, S> & OnlyKeys<K, ReplicateKeys, "nw.replicate", ReplicateTakes>,
1025
+ ): Channel<"replicate", Nothing, Mirror<PayloadOf<U>, PayloadOf<D>>>;
1026
+
1027
+ // Views -------------------------------------------------------------------------------------
1028
+
1029
+ /** The server side of `command`, `intent` and `signal`. */
1030
+ interface Inbound<out V> {
1031
+ /** Runs per admitted packet. It must not yield, and one channel has one handler. */
1032
+ listen<R>(handler: (ctx: Ctx, value: V) => R & Sync<R>): void;
1033
+ }
1034
+
1035
+ /** The server side of `query`. */
1036
+ interface Handling<out A, in R> {
1037
+ /** Answers the request. It runs on a thread of its own with a context of its own, so it may yield. */
1038
+ handle(handler: (ctx: Ctx, args: A) => DeepReadonly<R>): void;
1039
+ }
1040
+
1041
+ /** The client side of `command`, `intent` and `signal`. */
1042
+ interface Sender<in T> {
1043
+ /** Raises when the value is outside the schema's bounds, before a byte is written. */
1044
+ send(value: DeepReadonly<T>): void;
1045
+ }
1046
+
1047
+ /** The client side of `query`. */
1048
+ interface Invoker<in A, out R> {
1049
+ /** Yields until the answer, a refusal or the timeout. The failure is a code, never the policy's reason. */
1050
+ invoke(
1051
+ args: DeepReadonly<A>,
1052
+ ): LuaTuple<[value: R, failure: undefined] | [value: undefined, failure: string]>;
1053
+ }
1054
+
1055
+ /** The server side of `state` and `event`. */
1056
+ interface Publisher<in T> {
1057
+ /** Sends to the audience of `subject`. */
1058
+ publish(subject: unknown, value: DeepReadonly<T>): void;
1059
+ }
1060
+
1061
+ /** The server side of `state` and `event` when the audience is everyone. */
1062
+ interface Broadcaster<in T> extends Publisher<T> {
1063
+ /** Sends to every player. */
1064
+ broadcast(value: DeepReadonly<T>): void;
1065
+ }
1066
+
1067
+ /** The client side of `state` and `event`. */
1068
+ interface Listener<out T> {
1069
+ listen<R>(handler: (value: T) => R & Sync<R>): void;
1070
+ }
1071
+
1072
+ /** The client side of `replicate`. */
1073
+ interface Mirror<out U, out T> {
1074
+ /**
1075
+ * The whole value, never a patch, and undefined when the subject goes away. The value is this
1076
+ * client's baseline and is frozen; copy it as deep as you write.
1077
+ *
1078
+ * Stricter than the original, whose type leaves out both the undefined and the freezing.
1079
+ */
1080
+ listen<R>(handler: (subject: U, value: DeepReadonly<T> | undefined) => R & Sync<R>): void;
1081
+ }
1082
+
1083
+ /** The server side of `replicate`: nothing, so that nothing can skip the baseline. */
1084
+ interface Nothing {}
1085
+
1086
+ /** What the server may do with each channel of a declaration. */
1087
+ type ServerView<D> = {
1088
+ readonly [K in keyof D]: D[K] extends { readonly [serverView]: infer S } ? S : never;
1089
+ };
1090
+
1091
+ /** What the client may do with each channel of a declaration. */
1092
+ type ClientView<D> = {
1093
+ readonly [K in keyof D]: D[K] extends { readonly [clientView]: infer L } ? L : never;
1094
+ };
1095
+
1096
+ /** What {@link namespace} returns. Name one with `nw.Views<typeof combat.channels>`. */
1097
+ interface Views<D> {
1098
+ readonly name: string;
1099
+ readonly channels: Readonly<D>;
1100
+ readonly server: ServerView<D>;
1101
+ readonly client: ClientView<D>;
1102
+ }
1103
+
1104
+ /**
1105
+ * Declares a namespace and returns its two directional views.
1106
+ *
1107
+ * Every namespace has to be declared on both sides before the first packet moves, because each
1108
+ * channel's wire id depends on every other channel in the program. Two consequences in roblox-ts:
1109
+ *
1110
+ * - Declare in a shared module. One under ServerScriptService or ServerStorage raises.
1111
+ * - An import used only as a type is removed from the output, and the declaration with it. Load
1112
+ * the modules that declare for their effect, `import "shared/net"`, from both sides.
1113
+ */
1114
+ function namespace<D extends Record<string, AnyChannel>>(name: string, channels: D): Views<D>;
1115
+
1116
+ // Rejections --------------------------------------------------------------------------------
1117
+
1118
+ /** How far a packet got before it was refused. */
1119
+ type Stage =
1120
+ | "parse"
1121
+ | "budget"
1122
+ | "authorize"
1123
+ | "handler"
1124
+ | "queue"
1125
+ | "send"
1126
+ | "protocol"
1127
+ | "query"
1128
+ | "direction"
1129
+ | "replicate";
1130
+
1131
+ /** One refusal. The record is reused, so read what you need inside the observer. */
1132
+ interface Rejection {
1133
+ readonly channel: string;
1134
+ /** Absent on the client, and before the sender is known. */
1135
+ readonly player?: Player;
1136
+ readonly stage: Stage;
1137
+ readonly reason: string;
1138
+ readonly bytes: number;
1139
+ }
1140
+
1141
+ /** What {@link observe} takes. */
1142
+ type Observer = (rejection: Rejection) => void;
1143
+
1144
+ /** Receives every refusal, beside what the console prints. Returns a function that detaches it. */
1145
+ function observe(observer: Observer): () => void;
1146
+
1147
+ /** Refusals at one channel and stage, and their payload bytes added up. */
1148
+ interface Tally {
1149
+ readonly count: number;
1150
+ readonly bytes: number;
1151
+ }
1152
+
1153
+ /** What {@link diagnostics} returns, frozen at every level. */
1154
+ interface Diagnostics {
1155
+ /** `os.clock()` when counting last started. */
1156
+ readonly since: number;
1157
+ readonly total: number;
1158
+ /** By qualified channel name, then by stage. */
1159
+ readonly channels: ReadonlyMap<string, ReadonlyMap<Stage, Tally>>;
1160
+ /** Intent sends the client held back to the declared rate, by channel. Not refusals. */
1161
+ readonly paced: ReadonlyMap<string, number>;
1162
+ }
1163
+
1164
+ /** Every refusal since the counters were last reset. Built on read, so call it on a timer. */
1165
+ function diagnostics(): Diagnostics;
1166
+
1167
+ // Settings ----------------------------------------------------------------------------------
1168
+
1169
+ /** What the console does with a report. It never changes what is enforced. */
1170
+ type Severity = "off" | "warn" | "error";
1171
+
1172
+ /** A severity per rule: one per stage, and `rateUnbounded` for a rate no client could reach. */
1173
+ interface Rules {
1174
+ readonly parse?: Severity;
1175
+ readonly budget?: Severity;
1176
+ readonly authorize?: Severity;
1177
+ readonly handler?: Severity;
1178
+ readonly queue?: Severity;
1179
+ readonly send?: Severity;
1180
+ readonly protocol?: Severity;
1181
+ readonly query?: Severity;
1182
+ readonly direction?: Severity;
1183
+ readonly replicate?: Severity;
1184
+ readonly rateUnbounded?: Severity;
1185
+ }
1186
+
1187
+ interface Limits {
1188
+ /** Packets held for a channel whose listener has not attached yet. */
1189
+ readonly queueCapacity?: number;
1190
+ /** Decoded packets held while a batch is read. Server only. */
1191
+ readonly pendingPerBatch?: number;
1192
+ /** The largest unreliable payload that will be sent. Lowerable from 908, never raisable. */
1193
+ readonly unreliableBytes?: number;
1194
+ /** How many times the console prints one channel and stage before it goes quiet. */
1195
+ readonly repeatsPerDiagnostic?: number;
1196
+ /** Unanswered queries one player may hold at once. */
1197
+ readonly callsInFlight?: number;
1198
+ /** Channel and subject pairs one client's replication may hold. */
1199
+ readonly baselinesPerClient?: number;
1200
+ /** Ticks a peer waits between resyncs that are acted on. */
1201
+ readonly resyncTicks?: number;
1202
+ }
1203
+
1204
+ /** What {@link configure} takes. Anything omitted keeps its current value. */
1205
+ interface Settings {
1206
+ readonly rules?: Rules;
1207
+ readonly limits?: Limits;
1208
+ /** The Studio-only check that a `ctx` has not outlived its packet. */
1209
+ readonly contextGuard?: boolean;
1210
+ }
1211
+
1212
+ /** The settings in force, frozen at every level. */
1213
+ interface Snapshot {
1214
+ readonly rules: Readonly<Required<Rules>>;
1215
+ readonly limits: Readonly<Required<Limits>>;
1216
+ readonly contextGuard?: boolean;
1217
+ }
1218
+
1219
+ /** One row of `nw.config.describe()`. */
1220
+ interface Described {
1221
+ readonly rule: string;
1222
+ readonly severity: Severity;
1223
+ readonly default: Severity;
1224
+ /** Whether the rule reports wire data, where "error" can never raise. */
1225
+ readonly wire: boolean;
1226
+ readonly summary: string;
1227
+ }
1228
+
1229
+ /** Sets severities and limits. Call it before declaring channels: limits are read when they are built. */
1230
+ function configure<K = unknown, R = unknown, L = unknown>(
1231
+ settings: {
1232
+ readonly rules?: Rules & KnownKeys<R, RuleNames, "rule">;
1233
+ readonly limits?: Limits & KnownKeys<L, LimitNames, "limit">;
1234
+ readonly contextGuard?: boolean;
1235
+ } & KnownKeys<K, SettingNames, "setting">,
1236
+ ): Snapshot;
1237
+
1238
+ const config: {
1239
+ /** What is in force. */
1240
+ readonly snapshot: () => Snapshot;
1241
+ /** Every rule with its setting, its default and one line on what it reports. */
1242
+ readonly describe: () => Described[];
1243
+ };
1244
+
1245
+ // Protocol ----------------------------------------------------------------------------------
1246
+
1247
+ /** One namespace's own hash, so that a mismatch can be named. */
1248
+ interface NamespaceDigest {
1249
+ readonly name: string;
1250
+ readonly hash: number;
1251
+ }
1252
+
1253
+ /** What both peers must agree on before any packet is meaningful. */
1254
+ interface Protocol {
1255
+ readonly hash: number;
1256
+ readonly count: number;
1257
+ /** Sorted, so the channel with wire id `i + 1` is `names[i]`. */
1258
+ readonly names: ReadonlyArray<string>;
1259
+ readonly namespaces: ReadonlyArray<NamespaceDigest>;
1260
+ }
1261
+
1262
+ /** The agreed protocol. Calling it seals the set: nothing can be declared afterwards. */
1263
+ function protocol(): Protocol;
1264
+
1265
+ /** The text the protocol hash is taken over. Print it on both sides and diff it. Seals the set. */
1266
+ function signature(): string;
1267
+
1268
+ /** Which milestone of netweave this build is. */
1269
+ const milestone: string;
1270
+ }
1271
+
1272
+ export = nw;