### Compile Flamework Project (Template Setup) Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/installation.md These commands compile the Flamework project. `npm run build` performs a single compilation, while `npm run watch` starts a continuous watch mode for development. ```bash npm run build # Build your project npm run watch # Start watch mode ``` -------------------------------- ### Initialize Roblox-TS Project for Manual Flamework Setup Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/installation.md This command initializes a new roblox-ts project in your chosen directory. It prompts for setup questions to configure the project structure, preparing it for Flamework integration. ```bash npx roblox-ts init game ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/rbxts-flamework/documentation/blob/master/README.md Installs all necessary project dependencies using Yarn. This command should be run once after cloning the repository. ```shell $ yarn ``` -------------------------------- ### Build Flamework Project Manually (Watch Mode) Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/installation.md This command starts the roblox-ts compiler in watch mode, continuously building your project. It's the final step to enable development with Flamework after manual setup. ```bash npx rbxtsc -w ``` -------------------------------- ### Initialize New Flamework Project with Template Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/installation.md This command initializes a new Flamework project using the official template. It clones the template repository and then installs all necessary Node.js dependencies for immediate use. ```bash npx degit rbxts-flamework/template npm i ``` -------------------------------- ### Install Roblox-TS Locally for Manual Flamework Setup Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/installation.md This command installs `roblox-ts@next` as a development dependency within your project. A local installation is required for Flamework to function correctly, and `@next` is used until v1.2.0 is released. ```bash npm i -D roblox-ts@next ``` -------------------------------- ### Install Core Flamework Packages Manually Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/installation.md These commands install the essential Flamework library and its transformer as development dependencies. Optional modules like components and networking can be added for extended functionality. ```bash npm i -D rbxts-transformer-flamework npm i @flamework/core npm i @flamework/components # Flamework's component system npm i @flamework/networking # Flamework's remote networking module ``` -------------------------------- ### Update Flamework and Roblox-TS Packages (Template Setup) Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/installation.md These commands update core Flamework packages and Roblox-TS dependencies to their latest versions. This ensures compatibility and access to new features after initial template setup. ```bash # Update Flamework npm i rbxts-transformer-flamework@latest @flamework/core@latest @flamework/networking@latest @flamework/components@latest # Update roblox-ts npm i roblox-ts@latest @rbxts/types@latest @rbxts/compiler-types@latest ``` -------------------------------- ### Start Local Development Server Source: https://github.com/rbxts-flamework/documentation/blob/master/README.md Initiates a local development server and automatically opens the website in a browser. Most code changes are reflected live without requiring a server restart, facilitating rapid development. ```shell $ yarn start ``` -------------------------------- ### Ignite Flamework Application (TypeScript) Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/guides/ignition.md Once all necessary modules have been preloaded using `Flamework.addPaths`, the Flamework application can be safely started. This TypeScript snippet demonstrates the simple call to `Flamework.ignite()` which initializes and runs the framework. ```ts Flamework.ignite() ``` -------------------------------- ### Configure default.project.json for Flamework Modules Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/installation.md This JSON snippet updates `default.project.json` to correctly map the `@flamework` Node.js module path. This is essential for Roblox Studio to locate Flamework's runtime components. ```json "node_modules": { "@rbxts": { "$path": "node_modules/@rbxts" }, "@flamework": { "$path": "node_modules/@flamework" } } ``` -------------------------------- ### Configure tsconfig.json for Flamework Plugins Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/installation.md This JSON snippet configures `tsconfig.json` to enable experimental decorators and integrate the `rbxts-transformer-flamework` plugin. These settings are crucial for Flamework's compile-time functionality. ```json "experimentalDecorators": true, "plugins": [ { "transform": "rbxts-transformer-flamework" } ] ``` -------------------------------- ### Preload Flamework Modules (TypeScript) Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/guides/ignition.md Before Flamework can be ignited, its services, controllers, and components must be preloaded. This TypeScript example shows how to use `Flamework.addPaths` to specify directories containing these modules for both server and client-side code, ensuring Flamework can discover them. ```ts // server Flamework.addPaths("src/server/services"); Flamework.addPaths("src/server/components"); Flamework.addPaths("src/shared/components"); // client Flamework.addPaths("src/client/controllers"); Flamework.addPaths("src/client/components"); Flamework.addPaths("src/shared/components"); ``` -------------------------------- ### Update Flamework Packages Manually Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/installation.md These commands update the core Flamework packages (`@flamework/core` and `rbxts-transformer-flamework`) to their latest versions. This is part of the manual update process for existing projects. ```bash npm i @flamework/core@latest npm i -D rbxts-transformer-flamework@latest ``` -------------------------------- ### Use Singletons with Dependency Injection in TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/guides/singletons.md This example shows how Flamework automatically instantiates and manages singletons when they are used for dependency injection. It illustrates applying the @Singleton() decorator to a class and then retrieving an instance using the Dependency macro. ```typescript @Singleton() class MySingleton {} const mySingleton = Dependency(); ``` -------------------------------- ### Define Flamework meta and normal decorators for properties, methods, and classes Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/guides/decorators.md This example shows how to create Flamework's meta and normal decorators for properties, methods, and classes. Normal decorators execute a custom function after application, receiving descriptor and arguments. It also demonstrates applying these decorators to a sample class, showcasing their usage. ```ts // Property Decorators export const FieldDecorator = Modding.createMetaDecorator<[string]>("Property"); export const FieldDecorator = Modding.createDecorator<[string]>("Property", (descriptor, [name]) => { print("Decorated field", descriptor.isStatic, tostring(descriptor.object) + "." + descriptor.property); print("Passed in name:", name); }); // Method Decorators export const MethodDecorator = Modding.createMetaDecorator<[string]>("Method"); export const MethodDecorator = Modding.createDecorator<[string]>("Method", (descriptor, [name]) => { print("Decorated method", descriptor.isStatic, tostring(descriptor.object) + "." + descriptor.property + "()"); print("Passed in name:", name); }); // Class Decorators export const NameDecorator = Modding.createMetaDecorator<[string]>("Class"); export const NameDecorator = Modding.createDecorator<[string]>("Class", (descriptor, [name]) => { print("Decorated object", descriptor.object); print("Passed in name:", name); }); @NameDecorator("Peter") class A { @FieldDecorator("John") public abc = 1; @FieldDecorator("Andrew") @MethodDecorator("Andrew") public method() {} } ``` -------------------------------- ### Registering a handler for Flamework's onBadRequest event Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2021-09-14-flamework-release.md Example of how to register a callback for the onBadRequest global networking event, demonstrating how to access the player, event information, and the argument number that failed type guards for logging or debugging purposes. ```ts Networking.registerNetworkHandler("onBadRequest", (player, event, failedArg) => { print(player, "fired", event.name, "but passed invalid value for argument", failedArg); }); ``` -------------------------------- ### Query Polymorphic Flamework Components using getComponents and getAllComponents (TypeScript) Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/components/scripting-api.md Shows how to fetch components that support generic features or extend a base class using `Components.getComponents(instance)` for specific instances and `Components.getAllComponents(instance)` for all instances. Examples include an `OnInteract` interface and a `BaseEnemy` class. ```TypeScript const components = Dependency(); // A hypothetical OnInteract interface, similar to a lifecycle event. print("interactable components:", components.getComponents(Workspace.MyInteractableItem)); // Getting all components that extend a BaseEnemy class. print("enemies:", components.getAllComponents()); ``` -------------------------------- ### Configure tsconfig.json for Flamework Type Roots Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/installation.md This JSON snippet modifies the `typeRoots` in `tsconfig.json` to include the `@flamework` scope. This ensures that TypeScript can correctly resolve Flamework's type definitions during compilation. ```json "typeRoots": ["node_modules/@rbxts", "node_modules/@flamework"] ``` -------------------------------- ### Implement custom Flamework decorators using Modding API listeners Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/guides/decorators.md This snippet illustrates implementing custom decorators within a Flamework `Service` that implements `OnStart`. It demonstrates retrieving decorated constructors via `Modding.getDecorators` and listening for new decorator applications using `Modding.onListenerAdded`. The example also shows how to access decorator arguments and properties using `Modding.getDecorator` and `Modding.getPropertyDecorators`. ```ts @Service() export class MyDecoratorService implements OnStart { onStart() { // Retrieve all constructors that are using the NameDecorator // You can do whatever you wish with the constructor from here // e.g construct an instance via Flamework's dependency resolution const constructors = Modding.getDecorators(); for (const { object, arguments: args } of constructors) { print(object, "is named", args[0]); } // Listen for new listeners that are using NameDecorator Modding.onListenerAdded((object) => { // Retrieves the arguments from the decorator const decorator = Modding.getDecorator(object); if (decorator) { const [name] = decorator.arguments; print(object, "is the child of", name); } // Retrieves all the FieldDecorators for (const [prop, decorator] of Modding.getPropertyDecorators(object)) { const [name] = decorator.arguments; print(object, "has prop", prop, "with name", name); } }); } } ``` -------------------------------- ### Flamework Components API: Get Components by Type from Instance Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2022-06-09-flamework-release.md Describes the getComponents(instance) API, a new method in the Flamework Components library. This API allows developers to retrieve all components attached to a specific Roblox instance that implement or extend from a given TypeScript type T. ```APIDOC getComponents(instance: Instance): T[] Description: Retrieves all components that implement or extend from type T on the given instance. Parameters: instance: The Roblox Instance to check for components. Returns: An array of components of type T. ``` -------------------------------- ### Apply Middleware to Remote Event Namespaces in TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/networking/namespaces.md This example shows how to configure middleware for specific remote events or entire namespaces when creating the server's global events, allowing for fine-grained control over event processing. ```ts const Events = GlobalEvents.createServer({ middleware: { normalEvent: [middleware0], myCombatEvents: { killPlayer: [middleware1], } } }) ``` -------------------------------- ### General Reflect API Methods Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/reflection.md Overview of standard Reflect API methods for defining, checking, getting, and deleting metadata on objects and properties, following the reflect-metadata proposal. These methods operate on the prototype chain or directly on own properties. ```APIDOC Reflect.defineMetadata(metadataKey: any, metadataValue: any, target: object) Reflect.defineMetadata(metadataKey: any, metadataValue: any, target: object, propertyKey: string | symbol) Reflect.hasMetadata(metadataKey: any, target: object): boolean Reflect.hasMetadata(metadataKey: any, target: object, propertyKey: string | symbol): boolean Reflect.hasOwnMetadata(metadataKey: any, target: object): boolean Reflect.hasOwnMetadata(metadataKey: any, target: object, propertyKey: string | symbol): boolean Reflect.getMetadata(metadataKey: any, target: object): any Reflect.getMetadata(metadataKey: any, target: object, propertyKey: string | symbol): any Reflect.getOwnMetadata(metadataKey: any, target: object): any Reflect.getOwnMetadata(metadataKey: any, target: object, propertyKey: string | symbol): any Reflect.getMetadataKeys(target: object): string[] Reflect.getMetadataKeys(target: object, propertyKey: string | symbol): string[] Reflect.getOwnMetadataKeys(target: object): string[] Reflect.getOwnMetadataKeys(target: object, propertyKey: string | symbol): string[] Reflect.deleteMetadata(metadataKey: any, target: object): boolean Reflect.deleteMetadata(metadataKey: any, target: object, propertyKey: string | symbol): boolean ``` -------------------------------- ### Access Remote Events within Namespaces in TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/networking/namespaces.md This code demonstrates how to access and interact with remote events organized under namespaces, showing examples of firing an event and connecting to an event listener. ```ts Events.myCombatEvents.killPlayer.fire(); Events.mySocialEvents.throwAParty.connect(() => print("Throwing a party!")); ``` -------------------------------- ### Using Flamework Promise-based Remote Functions (Invoke, SetCallback, Predict) Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2021-09-14-flamework-release.md Provides comprehensive examples demonstrating how to interact with Flamework's new promise-based remote functions. It covers invoking functions from both server and client, setting up callbacks to handle incoming function calls, and utilizing prediction for client-side function execution to improve responsiveness. ```ts // server Functions.prompt.invoke(player, "Yes", "No").then((result) => print("player said", result)); Functions.fetchData.setCallback((player, kind) => { return kind === "Coins" ? getPlayerCoins(player) : getPlayerGems(player); }) ``` ```ts // client Functions.fetchData.invoke("Coins").then((result) => print("I have", result, "coins!")); Functions.prompt.setCallback((option1, option2) => { return math.random() < 0.5 ? option1 : option2; }) ``` ```ts // prediction (fire a client function on the client) Functions.prompt.predict("Yes", "No").then((result) => print("I chose", result)); ``` -------------------------------- ### Implement Component Dependencies in Flamework (TypeScript) Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2022-12-19-flamework-release.md This TypeScript example demonstrates how to use dependency injection for components in Flamework. `Component2` depends on `Component1`, ensuring that `Component1` is added first and automatically removed if `Component1` is removed, facilitating inter-component communication and managing their lifecycle. ```ts @Component({ tag: "required!" }) export class Component1 extends BaseComponent { doSomething() { print("I did something!"); } } @Component({ tag: "required!" }) export class Component2 extends BaseComponent extends OnStart { constructor(private component: Component1) { super(); } onStart() { print("Telling dependency to do something"); this.component.doSomething(); } } ``` -------------------------------- ### Specify Singleton Load Order with Metadata in TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/guides/singletons.md This example shows how to define a custom load order for singletons using the "flamework:loadOrder" metadata. The Singleton decorator is extended to accept a SingletonConfig with an optional loadOrder property, which is then applied using Reflect.defineMetadata. ```typescript interface SingletonConfig { loadOrder?: number; } /** * Request the required metadata for lifecycle events and dependency resolution. * @metadata flamework:implements flamework:parameters */ export const Singleton = Modding.createDecorator<[SingletonConfig]>("Class", (descriptor, [config]) => { Reflect.defineMetadata(descriptor.object, "flamework:singleton", true); Reflect.defineMetadata(descriptor.object, "flamework:loadOrder", config.loadOrder); }); ``` -------------------------------- ### Configure Flamework Networking Events (TypeScript) Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2022-12-19-flamework-release.md This TypeScript snippet shows how to apply custom configuration when creating a `Networking.createEvent`. By passing an object, you can modify default behaviors, such as disabling client-side input validation guards for specific events, offering flexibility in networking setup. ```ts const GlobalEvents = Networking.createEvent({}, {}, { disableClientGuards: true }); ``` -------------------------------- ### Flamework Components API: Get All Components by Type Globally Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2022-06-09-flamework-release.md Details the getAllComponents() API, another new addition to the Flamework Components library. This function provides a way to globally retrieve all components across the application that implement or extend from a specified TypeScript type T. ```APIDOC getAllComponents(): T[] Description: Retrieves all components globally that implement or extend from type T. Parameters: None Returns: An array of all components of type T. ``` -------------------------------- ### Component Definition with Generic Type Parameters for Flexible Inheritance Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/components/inheritance.md This example demonstrates how to define a SuperComponent using generic type parameters. This pattern allows child components to add new attributes, narrow existing attributes, or change the instance type when extending. ```typescript interface SuperAttributes { prop1: string, prop2: number, } @Component() class SuperComponent extends BaseComponent {} ``` -------------------------------- ### Nesting User Macros with Metadata Passing in TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/guides/user-macros.md This example illustrates how to nest user macros by passing metadata between them. It defines a BaseMacroMetadata type and shows how baseMacro can be called from newMacro by including and passing down the necessary metadata in the signature. This pattern is recommended for complex macros in libraries. ```ts type BaseMacroMetadata = Modding.GenericMany; /** @metadata macro */ function baseMacro(abc?: BaseMacroMetadata) {} /** @metadata macro */ function newMacro(param: string, macro?: BaseMacroMetadata) { return baseMacro(macro); } ``` -------------------------------- ### Firing Remote Events from the Server Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/networking/remote-events.md Provides examples of how to send RemoteEvents from the server to individual players, groups of players, all players except specified ones, broadcast to all players, or predict a server event using a player as the sender. ```ts // Fire to player(s) Events.event.fire(player, ...args); Events.event.fire([player1, player2], ...args); // Fire to all players except Events.event.except(player, ...args); Events.event.except([player1, player2], ...args); // Broadcast Events.event.broadcast(...args); // Predict, fires server event using player as the sender Events.event.predict(player, ...args); // Shorthand syntax, equivalent to Events.event.fire Events.event(player, ...args); ``` -------------------------------- ### Using Link Metadata in Flamework with TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/metadata.md This example illustrates Flamework's support for link metadata, which allows referencing a symbol or type within the `@metadata` tag. A key caveat is that linked symbols must be exported in packages for TypeScript to find them. ```ts type ConstructorConstraint = new () => defined; /** * @metadata {@link ConstructorConstraint constraint} */ @Decorator() class A { // ERROR! constructor(arg1: string) {} } ``` -------------------------------- ### Handling Errors in Flamework Remote Functions Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/networking/remote-functions.md This example shows how to handle rejections from Remote Function promises using the `.catch()` method. It specifically demonstrates checking the `reason` for a `NetworkingFunctionError.Timeout` to provide specific error feedback, while also catching other general errors. ```ts Events.function.invoke() .then((value) => print("I successfully got", value)) .catch((reason) => { if (reason === NetworkingFunctionError.Timeout) { warn("My request timed out!"); } else { warn("A different error occurred:", reason); } }) ``` -------------------------------- ### Define Random Chance RemoteEvent Middleware Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/networking/middleware.md Example TypeScript function `randomChanceMiddleware` for `Networking.EventMiddleware`. This middleware processes a request based on a given percentage chance. It demonstrates how to use `processNext` to continue the middleware chain or fire listeners, and how to access event metadata. ```ts function randomChanceMiddleware>(chances: number): Networking.EventMiddleware { return (processNext, event) => { print("Loaded middleware for", event.name); return (player, ...args) => { if (math.random() < chances / 100) { processNext(player, ...args); } }; }; } ``` -------------------------------- ### TypeScript Interface: CallerMetadata Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/guides/user-macros.md This TypeScript interface defines the structure of callsite-specific metadata available through Flamework's `Modding.Caller` function. It provides details about the source expression, including its starting line and character, width, a unique identifier, and the actual source text. ```TypeScript interface CallerMetadata { /** * The starting line of the expression. */ line: number; /** * The char at the start of the expression relative to the starting line. */ character: number; /** * The width of the expression. * This includes the width of multiline statements. */ width: number; /** * A unique identifier that can be used to identify exact callsites. * This can be used for hooks. */ uuid: string; /** * The source text for the expression. */ text: string; } ``` -------------------------------- ### Defining a new Promise-based RemoteFunction in Flamework Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2021-09-14-flamework-release.md Illustrates how to define server and client interfaces for a new promise-based remote function using Networking.createFunction in Flamework. This setup allows for type-safe definition of function parameters and return types, including placeholders for server and client middleware. ```ts interface ServerFunctions { myServerFunction(param1: string, param2: number): Instance | undefined; } interface ClientFunctions { myClientFunction(param1: string, param2: number): Instance | undefined; } export const GlobalFunctions = Networking.createFunction({ // server middleware }, { // client middleware }) ``` -------------------------------- ### Invoking Flamework Remote Functions Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/networking/remote-functions.md This example illustrates how to invoke a Remote Function and wait for its response using the `.then()` method. It covers the standard `invoke` method, a shorthand syntax for direct function calls, and the `predict` method for simulating requests. The `player?` parameter indicates it's optional and typically used on the server-side. ```ts // Invoke a function Functions.function.invoke(player?, "my parameter!").then((value) => ...); // Shorthand syntax, equivalent to Functions. Functions.function(player?, "my parameter!").then((value) => ...); // Predict, simulates a request being sent Functions.function.predict(player?, "my parameter!").then((value) => ...); ``` -------------------------------- ### Using Mapped Types with Modding.Many for Type Derivations in TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/guides/user-macros.md This example demonstrates the use of mapped types in conjunction with Modding.Many to generate derived types. It shows how to create an object type where each property corresponds to a member of T, and its value is a Modding.Generic guard for that member. ```ts declare function macro(guardsForEachMember?: Modding.Many<{ [k in keyof T]: Modding.Generic }>); ``` -------------------------------- ### Handling Flamework Remote Functions with setCallback Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/networking/remote-functions.md This snippet demonstrates how to set a callback for a Remote Function using `setCallback`. It shows examples for both normal synchronous functions and asynchronous functions. Flamework allows only one handler per function, and calling `setCallback` multiple times will override previous handlers with a warning. ```ts // With a normal function Functions.function.setCallback((player?, param1) => { print("This is", param1); return math.random(1, 100); }) // With an async function Functions.function.setCallback(async (player?, param1) => { print("This is", param1); return await myAsyncNumberGenerator(1, 100); }) ``` -------------------------------- ### Defining a Basic User Macro in TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/guides/user-macros.md This snippet demonstrates how to define a basic user macro using the "@metadata macro" tag. It shows how to access type parameter metadata (Modding.Generic) and call site information (Modding.CallerMany) within the macro function. The example also includes a call to the defined macro. ```ts /** @metadata macro */ function macro(abc?: Modding.Generic, xyz?: Modding.CallerMany<"line" | "char">) { assert(abc && xyz); print(abc, `${xyz.line}:${xyz.char}`); } macro(); ``` -------------------------------- ### Generating Objects and Tuples with Modding.Many in TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/guides/user-macros.md These examples show how Modding.Many can be used to generate complex data structures like objects and tuples at compile time. It demonstrates defining macro parameters that resolve to an object with specific metadata fields or a tuple of metadata values. ```ts declare function macro(metadata?: Modding.Many<{ a: Modding.Generic, b: Modding.Caller<"uuid"> }>); ``` ```ts declare function macro(metadata?: Modding.Many<[Modding.Generic, Modding.Caller<"uuid">]>); ``` -------------------------------- ### Define Random Chance RemoteFunction Middleware Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/networking/middleware.md Example TypeScript function `randomChanceMiddleware` for `Networking.FunctionMiddleware`. This middleware processes a request based on a given percentage chance, similar to the event middleware. It shows how `processNext` returns a promise and how to handle `Networking.Skip` to cancel a request, ensuring the skip value is propagated. ```ts function randomChanceMiddleware, O>(chances: number): Networking.FunctionMiddleware { return (processNext, event) => { print("Loaded middleware for", event.name); return async (player, ...args) => { if (math.random() < chances / 100) { return processNext(player, ...args); } return Networking.Skip; }; }; } ``` -------------------------------- ### Defining a Flamework User Macro in TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2022-05-15-flamework-release.md This TypeScript code defines a Flamework-style macro named `macro` that demonstrates how to access compile-time metadata. It utilizes `Modding.Generic` to retrieve the ID of a type parameter `T` and `Modding.Caller<"line" | "char">` to get the line and character number of the callsite. The macro asserts the presence of these metadata values and then prints the ID and callsite location. ```typescript /** @metadata macro */ function macro(abc?: Modding.Generic, xyz?: Modding.Caller<"line" | "char">) { assert(abc && xyz); print(abc.id, `${xyz.line}:${xyz.char}`); } macro(); ``` -------------------------------- ### Injecting custom dependencies with Modding.registerDependency Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/guides/dependency-resolution.md Illustrates how to inject custom values into Flamework's dependency resolution using Modding.registerDependency. This API takes a function that returns the value to be injected, called whenever the specified ID is resolved. It must be called prior to ignition. The example also shows how a service consumes these registered dependencies. ```ts // This uses a marker type to prevent type interning. export type Name = string & { _marker?: void }; export type Version = string & { _marker?: void }; Modding.registerDependency((ctor) => tostring(ctor)); Modding.registerDependency(() => "v1.5.2"); ``` ```ts @Service() export class MyService { constructor(private name: Name, private version: Version) { assert(name === "MyService"); assert(version === "v1.5.2"); } } ``` -------------------------------- ### Deploy Website to GitHub Pages Source: https://github.com/rbxts-flamework/documentation/blob/master/README.md Deploys the built static website content to the 'gh-pages' branch of the GitHub repository. This command first builds the website and then pushes the generated content, offering options for SSH or non-SSH authentication. ```shell $ USE_SSH=true yarn deploy ``` ```shell $ GIT_USER= yarn deploy ``` -------------------------------- ### Build Static Website Content Source: https://github.com/rbxts-flamework/documentation/blob/master/README.md Generates the static HTML, CSS, and JavaScript files for the website into the 'build' directory. The output can then be served using any standard static content hosting service. ```shell $ yarn build ``` -------------------------------- ### Flamework Controller with OnRender Lifecycle Event Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/guides/creating-a-singleton.md Demonstrates a minimal Flamework controller, MyController, implementing the OnRender lifecycle. The onRender method is called every frame on the client, printing a message and delta time. This highlights client-side specific lifecycle events. ```ts import { Controller, OnRender } from "@flamework/core"; @Controller() export class MyController implements OnRender { onRender(dt: number) { print("My controller is rendering", dt); } } ``` -------------------------------- ### Flamework Service with OnTick Lifecycle Event Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/guides/creating-a-singleton.md Demonstrates a minimal Flamework service, MyService, implementing the OnTick lifecycle. The onTick method is called every frame on the server, printing a message and delta time. This shows how to subscribe to server-side lifecycle events. ```ts import { Service, OnTick } from "@flamework/core"; @Service() export class MyService implements OnTick { onTick(dt: number) { print("My service is ticking", dt); } } ``` -------------------------------- ### Define Unreliable Remote Event Namespace in TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/networking/namespaces.md This example shows how to mark an entire namespace as unreliable using `UnreliableNamespace` type, ensuring all events within it behave as unreliable remote events. ```ts interface ClientToServerEvents { myUnreliableNamespace: UnreliableNamespace<{ myNamespacedEvent(): void; }>; } type UnreliableNamespace = { [k in keyof T]: Networking.Unreliable }; ``` -------------------------------- ### Configure Flamework Controller for Later Load Order Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/guides/creating-a-singleton.md Shows how to use the loadOrder configuration to make a Flamework controller load later. Setting loadOrder: 2 ensures it initializes after controllers with the default loadOrder of 1. This overrides automatic dependency injection ordering. ```ts @Controller( { loadOrder: 2 // Loads AFTER all other controllers with default loadOrder }) ``` -------------------------------- ### Configure Flamework Networking with createServer/createClient Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/migration.md Flamework 1.0.0 requires individual server and client networking configurations. Replace shared config with `GlobalEvents.createServer({})` and `GlobalEvents.createClient({})`. `createEvent`/`createFunction` no longer accept configuration. ```ts // `createEvent`/`createFunction` no longer accepts configuration. const GlobalEvents = Networking.createEvent(); const Events = GlobalEvents.createServer({ /* server config */ }) const Events = GlobalEvents.createClient({ /* client config */ }) ``` -------------------------------- ### Configure Flamework Controller for Earlier Load Order Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/guides/creating-a-singleton.md Shows how to use the loadOrder configuration to make a Flamework controller load earlier. Setting loadOrder: 0 ensures it initializes before controllers with the default loadOrder of 1. This overrides automatic dependency injection ordering. ```ts @Controller( { loadOrder: 0 // Loads BEFORE all other controllers with default loadOrder }) ``` -------------------------------- ### Preload Modules with Flamework.addPaths Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/guides/utility-macros.md The `Flamework.addPaths` function preloads all modules located under the specified filesystem paths. Paths can be relative to the project directory or the current file (if prefixed with `./`). It also supports glob patterns for preloading entire folders, though relative paths are disabled when using globs. ```TypeScript function Flamework.addPaths(...paths: string[]): void ``` -------------------------------- ### Refactor Networking Event Configuration Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2023-12-18-flamework-release.md This snippet illustrates the refactored approach for configuring networking events in Flamework 1.0. Previously, all middleware and configuration were passed in a single `createEvent` call. Now, `createServer` and `createClient` methods are used separately to configure server and client-specific settings, improving security and future extensibility. ```TypeScript /// Previously const GlobalEvents = Networking.createEvent( { /* server middleware */ }, { /* client middleware */ }, { /* server & client config */ }, ) /// Now const GlobalEvents = Networking.createEvent(); // server/networking.ts const Events = GlobalEvents.createServer({ /* server config */ }) // client/networking.ts const Events = GlobalEvents.createClient({ /* client config */ }) ``` -------------------------------- ### Flamework Runtime Configuration Options Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/guides/configuration.md Details the configurable options within the `flamework.json` file, affecting runtime behavior. ```APIDOC flamework.json: profiling: Defaults: true in studio, otherwise false Description: Enables microprofiler tags and memory categories for Flamework's built-in lifecycle events. logLevel: Defaults: none Valid values: none, verbose Description: Configures the logging level for Flamework. disableDependencyWarnings: Defaults: false Description: Disables warnings emitted by Flamework when using the Dependency macro prior to Flamework.ignite(). ``` -------------------------------- ### Implementing Constructor-Based Dependency Injection in Flamework Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/guides/dependencies.md This snippet demonstrates the preferred method for obtaining singleton references in Flamework using constructor-based dependency injection. Flamework automatically resolves and passes dependencies to the constructor when creating a singleton, ensuring proper load order and facilitating testability and maintainability. ```ts import { OtherService } from "./otherService"; @Service() export class MyService { constructor(private otherService: OtherService) {} method() { print(this.otherService.getName()); } } ``` -------------------------------- ### Handling Inter-Component Dependencies in Flamework Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/components/creating-a-component.md Explains how Flamework supports dependency injection between components attached to the same instance, ensuring dependent components are created only after their dependencies are available. ```ts class MyComponent extends BaseComponent {} // MyOtherComponent will not be created until MyComponent is class MyOtherComponent extends BaseComponent { constructor(private myComponent: MyComponent) {} } ``` -------------------------------- ### Flamework Networking Configuration Interfaces (APIDOC) Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2022-12-19-flamework-release.md These API documentation interfaces, `EventConfiguration` and `FunctionConfiguration`, define the available settings for customizing Flamework's networking behavior. They allow control over server and client input/return validation guards and specify default timeouts for server-to-client and client-to-server requests, enabling fine-tuned network interactions. ```APIDOC export interface EventConfiguration { /** * Disables input validation on the server, allowing any value to pass. * Defaults to `false` */ disableServerGuards: boolean; /** * Disables input validation on the client, allowing any value to pass. * Defaults to `false` */ disableClientGuards: boolean; } export interface FunctionConfiguration { /** * Disables input validation and return validation on the server, allowing any value to pass. * Defaults to `false` */ disableServerGuards: boolean; /** * Disables input validation and return validation on the client, allowing any value to pass. * Defaults to `false` */ disableClientGuards: boolean; /** * The default timeout for requests from the server to the client. * Defaults to `10` */ defaultServerTimeout: number; /** * The default timeout for requests from the client to the server. * Defaults to `30` */ defaultClientTimeout: number; } ``` -------------------------------- ### Flamework Networking Middleware Types Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/networking/middleware.md Documentation for the `Networking.EventMiddleware` and `Networking.FunctionMiddleware` types, which define the expected input and output signatures for custom middlewares in Flamework. ```APIDOC Networking.EventMiddleware I: Defines the inputs your middleware accepts and can't be applied to events that don't satisfy the specified type. Networking.FunctionMiddleware I: Defines the inputs your middleware accepts. O: Defines the output your middleware accepts and can't be applied to functions that don't satisfy the specified type. ``` -------------------------------- ### Specify Custom Attribute Type Guards with TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/components/configuration.md The 'attributes' property allows you to define custom type guards for attributes specified in your Component's attribute interface. This example demonstrates using the '@rbxts/t' package to constrain the 'amount' attribute to a number between 1 and 5. ```ts interface Attributes { amount: number } @Component( { tag: "Example", attributes: { amount: t.numberConstrained( 1, 5 ) } } ) export class ExampleComponent extends BaseComponent implements OnStart {} ``` -------------------------------- ### Declaring a Flamework Component in TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/components/creating-a-component.md Demonstrates how to declare a basic Flamework component by extending `BaseComponent` and implementing `OnStart` for lifecycle events, showcasing constructor dependency injection. ```ts import { OnStart } from "@flamework/core"; import { Component, BaseComponent } from "@flamework/components"; @Component() export class MyComponent extends BaseComponent implements OnStart { constructor(private myDependency: MyDependency) { super(); } onStart() { print(`Wow! I'm attached to ${this.instance.GetFullName()}`); } } ``` -------------------------------- ### Using the Dependency Macro for Singleton Retrieval in Flamework Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/guides/dependencies.md This snippet illustrates how to use the `Dependency` macro to retrieve a singleton reference directly. While convenient for utility functions or Roact components, this method is generally not recommended as it can hinder testing, refactoring, and obfuscate singleton execution order. It may also be removed or restricted in future Flamework versions. ```ts const myDependency = Dependency(); ``` -------------------------------- ### Specifying Instance Type for Flamework Components Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/components/creating-a-component.md Illustrates how to define a custom `Instance` type for a Flamework component, ensuring it's only instantiated on objects matching the specified interface and providing type-safe access to instance properties. ```ts interface MyComponentInstance extends Model { hinge: BasePart & { constraint: HingeConstraint }, } export class MyComponent extends BaseComponent<{}, MyComponentInstance> implements OnStart { onStart() { print(this.instance.hinge.constraint); } } ``` -------------------------------- ### Flamework Transformer Configuration Options Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/guides/configuration.md Details the configurable options for Flamework's transformer within the `tsconfig.json` file, under `rbxts-transformer-flamework`. ```APIDOC tsconfig.json (rbxts-transformer-flamework): noSemanticDiagnostics: Defaults: false Description: Disables Flamework's TypeScript type checking to improve compile times. Can result in instability as Flamework's behavior is undefined when there are outstanding type errors. obfuscation: Defaults: false Description: Enables Flamework's obfuscation which will shorten and randomize internal IDs, networking names and similar. idGenerationMode: Defaults: obfuscated when obfuscation is enabled, otherwise full Valid values: full, obfuscated, short, tiny Description: Controls how Flamework's identifiers are generated. You most likely do not need to change this. Options: full: Mostly unique IDs without any randomization. Game projects: server/services/myService@MyService Packages: @rbxts/my-package:server/services/myService@MyService obfuscated: IDs have no debug information but can include package names. Game projects: aZx Packages: @rbxts/my-package:aZx short / tiny: Similar to obfuscated, except they contain some debug information. The random text is used to guarantee uniqueness. Tiny will not include the file name. Game projects (short): myService@MyService{aZx} Game projects (tiny): MyService{aZx} Packages (short): @rbxts/my-package:myService@MyService{aZx} Packages (tiny): @rbxts/my-package:MyService{aZx} hashPrefix: Defaults: package name Description: Changes the prefix used for IDs generated by packages. ``` -------------------------------- ### Flamework Package Previous Beta Versions Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2023-04-13-flamework-release.md This snippet lists the specific beta versions for core Flamework packages, including @flamework/core, @flamework/networking, @flamework/components, and rbxts-transformer-flamework. These versions are provided for users who may need to revert their dependencies to a known stable state due to issues with newer releases. ```plaintext @flamework/core: 1.0.0-beta.8 @flamework/networking: 1.0.0-beta.9 @flamework/components: 1.0.0-beta.12 rbxts-transformer-flamework: 1.0.0-beta.15 ``` -------------------------------- ### Flamework Configuration for ID Generation Modes Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2022-05-15-flamework-release.md This documentation describes the `idGenerationMode` configuration option within Flamework's `tsconfig`. It details four distinct modes: 'full', 'short', 'tiny', and 'obfuscated', explaining their behavior and recommended use cases. Modes other than 'full' incorporate a unique hash to prevent collisions, making them unsuitable for packages. ```APIDOC "idGenerationMode": "full" - This should always be used for packages. - (prefix:)server/services/subfolder/service1@Service1 "idGenerationMode": "short" - Includes only the file name and declaration name. - (prefix:)service1@Service1\{HASH} "idGenerationMode": "tiny" - Includes only the declaration name. - (prefix:)Service1\{HASH} "idGenerationMode": "obfuscated" - (prefix:)HASH ``` -------------------------------- ### Attaching a Flamework Component using CollectionService Tag Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/components/creating-a-component.md Shows how to configure a Flamework component to be automatically attached to Roblox instances tagged with a specific CollectionService tag by specifying the `tag` property in the `@Component` decorator. ```ts @Component({ tag: "my-cs-tag" }) ``` -------------------------------- ### Flamework Package Versions for Previous Release Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2021-09-14-flamework-release.md Lists the specific package versions for @flamework/core, @flamework/networking, @flamework/components, and rbxts-transformer-flamework. These versions are provided as a reference for reverting packages in case of compatibility issues or problems with the current update. ```text @flamework/core: 1.0.0-beta.0 @flamework/networking: 1.0.0-beta.2 @flamework/components: 1.0.0-beta.3 rbxts-transformer-flamework: 1.0.0-beta.3 ``` -------------------------------- ### Implement Component Instance Guard with TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/components/configuration.md The 'instanceGuard' is similar to 'predicate' but handles instance readiness differently. On the server, it throws an error if the guard fails. On the client, it waits for 'DescendantsAdded' and 'DescendantsRemoving' events until the guard passes, accommodating partial instance loading. Using 'instanceGuard' overrides any automatically generated type guards. ```ts @Component( { tag: "Example", instanceGuard: Flamework.createGuard() } ) export class ExampleComponent extends BaseComponent<{}, Model> implements OnStart {} ``` -------------------------------- ### Converting to the new networking structure in Flamework Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2021-09-14-flamework-release.md Demonstrates the transition from the old global event connection methods to the new event-specific methods for Flamework networking events, showing both the deprecated and new syntax. ```ts // old Events.connect("myEvent", () => {}); Events.predict("myEvent"); // new Events.myEvent.connect(() => {}); Events.myEvent.predict(); ``` -------------------------------- ### Creating Flamework Remote Functions with Networking.createFunction Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/networking/remote-functions.md This snippet demonstrates how to define `ClientToServerFunctions` and `ServerToClientFunctions` interfaces and then use `Networking.createFunction` to generate a global functions object. It also shows how to create separate server and client instances, which is recommended to avoid exposing server configurations. ```ts import { Networking } from "@flamework/networking"; interface ClientToServerFunctions { function(param1: string): number; } interface ServerToClientFunctions { function(param1: string): number; } // Returns an object containing a `server` and `client` field. export const GlobalFunctions = Networking.createFunction(); // It is recommended that you create these in separate server/client files, // which will avoid exposing server configuration (including type guards) to the client. export const ServerFunctions = GlobalFunctions.createServer({ /* server config */ }); export const ClientFunctions = GlobalFunctions.createClient({ /* client config */ }); ``` -------------------------------- ### Implement Disposable Component for Custom Cleanup Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2023-12-18-flamework-release.md This TypeScript class, `DisposableComponent`, extends `BaseComponent` and provides a `Maid` instance for automatic cleanup. It overrides the `destroy` method to ensure the `Maid` is properly disposed, offering a drop-in replacement for components requiring custom cleanup solutions. ```TypeScript export class DisposableComponent extends BaseComponent { protected maid = new Maid(); override destroy() { this.maid.Destroy(); super.destroy(); } } ``` -------------------------------- ### Reverting Flamework Packages to Previous Release Versions Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2021-11-03-flamework-release.md This snippet provides the specific versions for Flamework packages to revert to if issues are encountered with the current update. It lists the core, networking, components, and transformer packages with their respective beta versions, allowing users to roll back to a stable state. ```Text @flamework/core: 1.0.0-beta.1 @flamework/networking: 1.0.0-beta.5 @flamework/components: 1.0.0-beta.4 rbxts-transformer-flamework: 1.0.0-beta.7 ``` -------------------------------- ### Define Flamework Configuration Interface (TypeScript) Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2022-12-19-flamework-release.md This TypeScript interface, `FlameworkConfig`, defines global configuration options for Flamework. It allows setting the logging level for debugging and disabling specific dependency warnings that occur before ignition, providing fine-grained control over the framework's behavior. ```ts export interface FlameworkConfig { /** * Defines what logging level Flamework should use. * This can be useful for debugging issues with ignition. */ logLevel?: "none" | "verbose"; /** * Disables the warnings that occur when you use the `Dependency` macro prior to ignition. * This does not disable warning for using the macro during preloading, as that is always unintended. */ disableDependencyWarnings?: boolean; } ``` -------------------------------- ### Implement and Access Networking Namespaces in Flamework Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2024-01-21-flamework-release.md Shows how to organize networking events using nested namespaces for better structure and isolation. It also demonstrates how to access these namespaced events and apply middleware configurations to them. ```TypeScript interface ClientToServerEvents { normalEvent(): void; myCombatEvents: { killPlayer(): void; revivePlayer(): void; eatPlayer(): void; }, mySocialEvents: { doNotKillPlayer(): void; throwAParty(): void; inviteFriends(): void; }, // Namespaces don't have to be defined in the same file! myRandomNamespace: MyRandomNamespace, } ``` ```TypeScript // You can access namespaces as you might expect, through the `Events` object. Events.myCombatEvents.killPlayer(); Events.mySocialEvents.throwAParty(); ``` ```TypeScript const Events = GlobalEvents.createServer({ middleware: { normalEvent: [middleware0], myCombatEvents: { killPlayer: [middleware1, middleware2], } } }) ``` -------------------------------- ### Define a Minimal Flamework Service in TypeScript Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/introduction.md This TypeScript code snippet demonstrates the minimal boilerplate required to define a service within the Flamework framework. By applying the @Service() decorator to a class, it becomes a discoverable service that can be fetched or optionally integrate with Flamework's lifecycle events. ```typescript @Service() export class MyService {} ``` -------------------------------- ### Register Middleware with GlobalEvents.createServer Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/additional-modules/networking/middleware.md Demonstrates how to apply a custom middleware, such as `randomChanceMiddleware`, to a specific server event (`myServerEvent`) within the `GlobalEvents.createServer` configuration. This registers the middleware to be called for inbound requests before the event's listeners. ```ts export const Events = GlobalEvents.createServer( { // Inbound middleware, called by the receiver prior to firing any connections. middleware: { myServerEvent: [randomChanceMiddleware(50)], } } ); ``` -------------------------------- ### Adding a listener with Modding.addListener Source: https://github.com/rbxts-flamework/documentation/blob/master/docs/modding/guides/listeners.md Demonstrates how to register a class instance as a listener using `Modding.addListener`. Flamework automatically processes `flamework:implements` and `flamework:decorators` metadata. Singletons, components, and custom classes created with `Modding.createDependency` are also automatically added as listeners. ```ts @Decorator() class A implements LifecycleEvent {} Modding.addListener(new A()); ``` -------------------------------- ### Flamework Modding.inspect() Macro API Reference Source: https://github.com/rbxts-flamework/documentation/blob/master/blog/2023-04-13-flamework-release.md Documents the `Modding.inspect()` macro, which allows developers to run a type `T` through Flamework's user macro system in plain code. This enables retrieving type-derived information, such as keys of a type or generated guards for its members. ```TypeScript type MyConstant = typeof myConstant; const myConstant = { a: { value: "default" }, b: { value: 15 }, } as const; const constantMetadata = Modding.inspect<{ keys: (keyof MyConstant)[], guards: { [k in keyof MyConstant]: Modding.Generic }, }>(); ```