Add more instance types

This commit is contained in:
evil bocchi
2025-04-06 20:11:44 +08:00
parent 6b84f78743
commit b673375f30
7 changed files with 338 additions and 25 deletions
-1
View File
@@ -12,7 +12,6 @@ This transformer automatically converts constructor-style instance creation (`ne
- 🔍 Full TypeScript type safety - 🔍 Full TypeScript type safety
- ⚡ Zero runtime overhead (transforms at compile-time) - ⚡ Zero runtime overhead (transforms at compile-time)
- 🔄 Supports all creatable Roblox instance types - 🔄 Supports all creatable Roblox instance types
- 📦 Easy to install and use
## Installation ## Installation
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "rbxts-transformer-instances", "name": "rbxts-transformer-instances",
"version": "1.0.0", "version": "1.0.1",
"description": "Enable the use of instance constructors, reducing boilerplate.", "description": "Enable the use of instance constructors, reducing boilerplate.",
"main": "out/index.js", "main": "out/index.js",
"author": "evilbocchi", "author": "evilbocchi",
+29 -4
View File
@@ -128,6 +128,26 @@ declare const CreatableInstancesWithConstructors: CreatableInstancesWithConstruc
return content; return content;
} }
/**
* Generate the instance-classes.ts file content
* @param {string[]} classNames List of creatable instance class names
* @returns {string} The content for the instance-classes.ts file
*/
function generateInstanceClassesFile(classNames) {
return `/**
* This file is auto-generated by the generate-instance-classes script.
* Do not modify manually.
*/
/**
* Array of all creatable Roblox instance class names
* Used by the transformer to identify constructor calls
*/
export const CREATABLE_INSTANCES = [
${classNames.map(name => `"${name}"`).join(",\n ")}
];`;
}
/** /**
* Main function * Main function
*/ */
@@ -135,12 +155,17 @@ function main() {
const classNames = getCreatableInstanceNames(); const classNames = getCreatableInstanceNames();
console.log(`Found ${classNames.length} creatable instance types`); console.log(`Found ${classNames.length} creatable instance types`);
// Generate and write declarations file
const declarationsContent = generateDeclarations(classNames); const declarationsContent = generateDeclarations(classNames);
const outputPath = path.join(__dirname, '..', 'index.d.ts'); const declarationsPath = path.join(__dirname, '..', 'index.d.ts');
fs.writeFileSync(declarationsPath, declarationsContent, 'utf-8');
console.log(`Successfully generated declarations in ${declarationsPath}`);
// Write to file // Generate and write instance-classes.ts
fs.writeFileSync(outputPath, declarationsContent, 'utf-8'); const instanceClassesContent = generateInstanceClassesFile(classNames);
console.log(`Successfully generated declarations in ${outputPath}`); const instanceClassesPath = path.join(__dirname, '..', 'src', 'instance-classes.ts');
fs.writeFileSync(instanceClassesPath, instanceClassesContent, 'utf-8');
console.log(`Successfully generated instance classes in ${instanceClassesPath}`);
console.log('Example declarations:'); console.log('Example declarations:');
const examples = classNames.slice(0, 5); const examples = classNames.slice(0, 5);
+301
View File
@@ -0,0 +1,301 @@
/**
* This file is auto-generated by the generate-instance-classes script.
* Do not modify manually.
*/
/**
* Array of all creatable Roblox instance class names
* Used by the transformer to identify constructor calls
*/
export const CREATABLE_INSTANCES = [
"Accessory",
"AccessoryDescription",
"Accoutrement",
"Actor",
"AdGui",
"AdPortal",
"AirController",
"AlignOrientation",
"AlignPosition",
"AngularVelocity",
"Animation",
"AnimationConstraint",
"AnimationController",
"AnimationRigData",
"Animator",
"Annotation",
"ArcHandles",
"Atmosphere",
"AtmosphereSensor",
"Attachment",
"AudioAnalyzer",
"AudioChannelMixer",
"AudioChannelSplitter",
"AudioChorus",
"AudioCompressor",
"AudioDeviceInput",
"AudioDeviceOutput",
"AudioDistortion",
"AudioEcho",
"AudioEmitter",
"AudioEqualizer",
"AudioFader",
"AudioFilter",
"AudioFlanger",
"AudioLimiter",
"AudioListener",
"AudioPitchShifter",
"AudioPlayer",
"AudioReverb",
"AudioSearchParams",
"AudioTextToSpeech",
"AuroraScript",
"Backpack",
"BallSocketConstraint",
"Beam",
"BillboardGui",
"BindableEvent",
"BindableFunction",
"BlockMesh",
"BloomEffect",
"BlurEffect",
"BodyAngularVelocity",
"BodyColors",
"BodyForce",
"BodyGyro",
"BodyPartDescription",
"BodyPosition",
"BodyThrust",
"BodyVelocity",
"Bone",
"BoolValue",
"BoxHandleAdornment",
"Breakpoint",
"BrickColorValue",
"BubbleChatMessageProperties",
"BuoyancySensor",
"CFrameValue",
"Camera",
"CanvasGroup",
"CharacterMesh",
"ChorusSoundEffect",
"ClickDetector",
"ClimbController",
"Clouds",
"Color3Value",
"ColorCorrectionEffect",
"ColorGradingEffect",
"CompressorSoundEffect",
"ConeHandleAdornment",
"Configuration",
"ControllerManager",
"ControllerPartSensor",
"CornerWedgePart",
"CurveAnimation",
"CustomLog",
"CylinderHandleAdornment",
"CylinderMesh",
"CylindricalConstraint",
"DataStoreGetOptions",
"DataStoreIncrementOptions",
"DataStoreOptions",
"DataStoreSetOptions",
"Decal",
"DepthOfFieldEffect",
"Dialog",
"DialogChoice",
"DistortionSoundEffect",
"DoubleConstrainedValue",
"DragDetector",
"Dragger",
"EchoSoundEffect",
"EqualizerSoundEffect",
"EulerRotationCurve",
"ExperienceInviteOptions",
"ExplorerFilter",
"Explosion",
"FaceControls",
"FileMesh",
"Fire",
"FlangeSoundEffect",
"FloatCurve",
"FloorWire",
"FluidForceSensor",
"Folder",
"ForceField",
"Frame",
"GetTextBoundsParams",
"Glue",
"GroundController",
"Handles",
"HapticEffect",
"Hat",
"HiddenSurfaceRemovalAsset",
"Highlight",
"HingeConstraint",
"Hole",
"Humanoid",
"HumanoidController",
"HumanoidDescription",
"HumanoidRigDescription",
"IKControl",
"ImageButton",
"ImageHandleAdornment",
"ImageLabel",
"InputAction",
"InputBinding",
"InputContext",
"IntConstrainedValue",
"IntValue",
"InternalSyncItem",
"IntersectOperation",
"Keyframe",
"KeyframeMarker",
"KeyframeSequence",
"LineForce",
"LineHandleAdornment",
"LinearVelocity",
"LocalScript",
"LocalizationTable",
"ManualGlue",
"ManualWeld",
"MarkerCurve",
"MaterialVariant",
"MeshPart",
"Model",
"ModuleScript",
"Motor",
"Motor6D",
"MotorFeature",
"NegateOperation",
"NoCollisionConstraint",
"Noise",
"NumberPose",
"NumberValue",
"ObjectValue",
"OperationGraph",
"Pants",
"Part",
"PartOperation",
"ParticleEmitter",
"Path2D",
"PathfindingLink",
"PathfindingModifier",
"PitchShiftSoundEffect",
"Plane",
"PlaneConstraint",
"PluginCapabilities",
"PointLight",
"Pose",
"PrismaticConstraint",
"ProximityPrompt",
"RTAnimationTracker",
"RayValue",
"RelativeGui",
"RemoteEvent",
"RemoteFunction",
"ReverbSoundEffect",
"RigidConstraint",
"RocketPropulsion",
"RodConstraint",
"RopeConstraint",
"Rotate",
"RotateP",
"RotateV",
"RotationCurve",
"ScreenGui",
"Script",
"ScrollingFrame",
"Seat",
"SelectionBox",
"SelectionPartLasso",
"SelectionPointLasso",
"SelectionSphere",
"Shirt",
"ShirtGraphic",
"SkateboardController",
"SkateboardPlatform",
"Sky",
"Smoke",
"Snap",
"Sound",
"SoundGroup",
"Sparkles",
"SpawnLocation",
"SpecialMesh",
"SphereHandleAdornment",
"SpotLight",
"SpringConstraint",
"StarterGear",
"StringValue",
"StudioAttachment",
"StudioCallout",
"StyleDerive",
"StyleLink",
"StyleRule",
"StyleSheet",
"SunRaysEffect",
"SurfaceAppearance",
"SurfaceGui",
"SurfaceLight",
"SurfaceSelection",
"SwimController",
"Team",
"TeleportOptions",
"TerrainDetail",
"TerrainRegion",
"TextBox",
"TextButton",
"TextChannel",
"TextChatCommand",
"TextChatMessageProperties",
"TextLabel",
"Texture",
"Tool",
"Torque",
"TorsionSpringConstraint",
"TrackerStreamAnimation",
"Trail",
"TremoloSoundEffect",
"TrussPart",
"UIAspectRatioConstraint",
"UICorner",
"UIDragDetector",
"UIFlexItem",
"UIGradient",
"UIGridLayout",
"UIListLayout",
"UIPadding",
"UIPageLayout",
"UIScale",
"UISizeConstraint",
"UIStroke",
"UITableLayout",
"UITextSizeConstraint",
"UnionOperation",
"UniversalConstraint",
"UnreliableRemoteEvent",
"Vector3Curve",
"Vector3Value",
"VectorForce",
"VehicleController",
"VehicleSeat",
"VelocityMotor",
"VideoDeviceInput",
"VideoDisplay",
"VideoFrame",
"VideoPlayer",
"ViewportFrame",
"VisualizationMode",
"VisualizationModeCategory",
"WedgePart",
"Weld",
"WeldConstraint",
"Wire",
"WireframeHandleAdornment",
"WorkspaceAnnotation",
"WorldModel",
"WrapDeformer",
"WrapLayer",
"WrapTarget"
];
+7 -13
View File
@@ -1,4 +1,5 @@
import ts from "typescript"; import ts from "typescript";
import { CREATABLE_INSTANCES } from "./instance-classes";
/** /**
* This is the transformer's configuration, the values are passed from the tsconfig. * This is the transformer's configuration, the values are passed from the tsconfig.
@@ -35,22 +36,15 @@ function visitExpression(context: TransformContext, node: ts.Expression): ts.Exp
// Check for new expressions (new Part()) // Check for new expressions (new Part())
if (ts.isNewExpression(node)) { if (ts.isNewExpression(node)) {
const { expression, arguments: args } = node; const { expression, arguments: args } = node;
// Check if it's a simple identifier (e.g., Part, not Something.Part) // Check if it's a simple identifier (e.g., Part, not Something.Part)
if (ts.isIdentifier(expression)) { if (ts.isIdentifier(expression)) {
const className = expression.text; const className = expression.text;
// Check if it's an Instance-derived class (assuming basic Roblox classes for now) // Use the imported list of creatable instances
const instanceClasses = [ if (CREATABLE_INSTANCES.includes(className)) {
"Part", "Model", "Folder", "Script", "LocalScript", "ModuleScript",
"Frame", "TextLabel", "TextButton", "ImageLabel", "ImageButton",
"Sound", "Animation", "BoolValue", "StringValue", "NumberValue",
// Add more Roblox classes as needed
];
if (instanceClasses.includes(className)) {
const { factory } = context; const { factory } = context;
// Create new Instance("ClassName") expression // Create new Instance("ClassName") expression
return factory.createNewExpression( return factory.createNewExpression(
factory.createIdentifier("Instance"), factory.createIdentifier("Instance"),
@@ -77,7 +71,7 @@ function visitNode(context: TransformContext, node: ts.Node): ts.Node | ts.Node[
return context.transform(node); return context.transform(node);
} }
export default function(program: ts.Program, config: TransformerConfig = { _: undefined }) { export default function (program: ts.Program, config: TransformerConfig = { _: undefined }) {
return (context: ts.TransformationContext) => { return (context: ts.TransformationContext) => {
const transformContext = new TransformContext(program, context, config); const transformContext = new TransformContext(program, context, config);
return (file: ts.SourceFile) => { return (file: ts.SourceFile) => {
View File
-6
View File
@@ -1,6 +0,0 @@
/// <reference path="index.d.ts" />
type hi = CreatableInstancesWithConstructors;
new Frame()
new Part().Name = "hi";