Skip to content

Implement Float Property Truncation Fix plugin and fix finalizeBuild being consumed #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion dist/Plugins/AllPlugins.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import type { DashFile } from '../Core/DashFile';
import type { Dash } from '../Dash';
import { Plugin } from './Plugin';
import { TCompilerPluginFactory } from './TCompilerPluginFactory';
import { jsonStringifyWithFloatFix } from './BuiltIn/FloatPropertyTruncationFix';
import { JsRuntime } from '../Common/JsRuntime';
declare const availableHooks: readonly ["buildStart", "buildEnd", "include", "ignore", "transformPath", "read", "load", "registerAliases", "require", "transform", "finalizeBuild", "beforeFileUnlinked"];
export declare type THookType = typeof availableHooks[number];
export declare type THookType = (typeof availableHooks)[number];
export declare class AllPlugins {
protected dash: Dash<any>;
protected pluginRuntime: JsRuntime;
Expand Down Expand Up @@ -39,6 +40,7 @@ export declare class AllPlugins {
unlinkOutputFiles: (filePaths: string[]) => Promise<void>;
hasComMojangDirectory: boolean;
compileFiles: (filePaths: string[], virtual?: boolean) => Promise<void>;
jsonStringifyWithFloatFix: typeof jsonStringifyWithFloatFix;
};
runBuildStartHooks(): Promise<void>;
runIncludeHooks(): Promise<(string | [string, {
Expand Down
2 changes: 1 addition & 1 deletion dist/Plugins/BuiltIn/Components/Plugins.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ interface IOpts {
fileType: string;
getComponentObjects: (fileContent: any) => [string, any][];
}
export declare function createCustomComponentPlugin({ fileType, getComponentObjects, }: IOpts): TCompilerPluginFactory<{
export declare function createCustomComponentPlugin({ fileType, getComponentObjects }: IOpts): TCompilerPluginFactory<{
v1CompatMode?: boolean;
}>;
export declare const CustomEntityComponentPlugin: TCompilerPluginFactory<{
Expand Down
6 changes: 6 additions & 0 deletions dist/Plugins/BuiltIn/FloatPropertyTruncationFix.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { TCompilerPluginFactory } from '../TCompilerPluginFactory';
export declare function jsonStringifyWithFloatFix(json: Object, matches: {
pathGlob: string;
apply?: (path: string, traversedObjects: any[]) => boolean;
}[], spacing?: any): string;
export declare const FloatPropertyTruncationFix: TCompilerPluginFactory;
1,983 changes: 1,127 additions & 856 deletions dist/dash-compiler.bundled.es.js

Large diffs are not rendered by default.

237 changes: 101 additions & 136 deletions dist/dash-compiler.es.js

Large diffs are not rendered by default.

23 changes: 9 additions & 14 deletions dist/dash-compiler.umd.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@bridge-editor/dash-compiler",
"version": "0.12.0",
"version": "0.13.0-beta",
"description": "A fast compiler for Minecraft Add-Ons",
"scripts": {
"build:types": "tsc --project tsconfig.json",
Expand All @@ -27,6 +27,10 @@
{
"name": "Thomas Orsbourne",
"email": "[email protected]"
},
{
"name": "Outer Cloud",
"email": "[email protected]"
}
],
"license": "MIT",
Expand All @@ -51,4 +55,4 @@
"vite": "^2.6.13",
"vitest": "^0.22.1"
}
}
}
6 changes: 0 additions & 6 deletions src/Core/TransformFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,6 @@ export class FileTransformer {

if (writeData !== undefined && writeData !== null) {
if (!isWritableData(writeData)) {
this.dash.console.warn(
`File "${
file.filePath
}" was not in a writable format: "${typeof writeData}". Trying to JSON.stringify(...) it...`,
writeData
)
writeData = JSON.stringify(writeData)
}
}
Expand Down
3 changes: 3 additions & 0 deletions src/Plugins/AllPlugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { RewriteForPackaging } from './BuiltIn/RewriteForPackaging'
import { ContentsFilePlugin } from './BuiltIn/ContentsFile'
import { FormatVersionCorrection } from './BuiltIn/FormatVersionCorrection'
import { GeneratorScriptsPlugin } from './BuiltIn/GeneratorScripts/Plugin'
import { FloatPropertyTruncationFix, jsonStringifyWithFloatFix } from './BuiltIn/FloatPropertyTruncationFix'
import { JsRuntime } from '../Common/JsRuntime'

const builtInPlugins: Record<string, TCompilerPluginFactory<any>> = {
Expand All @@ -29,6 +30,7 @@ const builtInPlugins: Record<string, TCompilerPluginFactory<any>> = {
contentsFile: ContentsFilePlugin,
formatVersionCorrection: FormatVersionCorrection,
generatorScripts: GeneratorScriptsPlugin,
floatPropertyTruncationFix: FloatPropertyTruncationFix,
}

const availableHooks = [
Expand Down Expand Up @@ -244,6 +246,7 @@ export class AllPlugins {
*/
hasComMojangDirectory: this.dash.fileSystem !== this.dash.outputFileSystem,
compileFiles: (filePaths: string[], virtual = true) => this.dash.compileAdditionalFiles(filePaths, virtual),
jsonStringifyWithFloatFix,
}
}

Expand Down
6 changes: 0 additions & 6 deletions src/Plugins/BuiltIn/Commands/Plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,12 +193,6 @@ export const CustomCommandsPlugin: TCompilerPluginFactory<{
if (isCommand(filePath) && fileContent) {
return (<Command>fileContent).toString()
}
// Make sure JSON files are transformed back into a format that we can write to disk
else if (
loadCommandsFor(filePath) &&
typeof fileContent !== 'string'
)
return JSON.stringify(fileContent, null, '\t')
},
}
}
112 changes: 112 additions & 0 deletions src/Plugins/BuiltIn/FloatPropertyTruncationFix.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { isMatch } from '@bridge-editor/common-utils'
import { TCompilerPluginFactory } from '../TCompilerPluginFactory'

/**
* @example
* jsonStringifyWithFloatFix(fileContent, [
* {
* pathGlob: 'minecraft:entity/description/properties/*╱value',
* apply(path, traversedObjects) {
* if (traversedObjects.length === 0) return false
*
* if (traversedObjects[traversedObjects.length - 1].type !== 'float') return false
*
* return true
* },
* },
* {
* pathGlob: 'minecraft:entity/description/properties/*╱range/*',
* apply(path, traversedObjects) {
* if (traversedObjects.length < 2) return false
*
* if (traversedObjects[traversedObjects.length - 2].type !== 'float') return false
*
* return true
* },
* },
* ])
* @param json The JSON object that will be stringified
* @param matches A list of objects describing where the float fix should be applied. pathGlob is a glob matcher string of the path traversed inside the JSON object. Traversed objects is a list of parent objects in the order that the replacer has traversed down.
* @param spacing The spacing to use. Pass null for minimal whitespace
* @returns The stringified JSON
*/
export function jsonStringifyWithFloatFix(json: Object, matches: { pathGlob: string; apply?: (path: string, traversedObjects: any[]) => boolean }[], spacing: any = '\t') {
let traversedKeys: string[] = []
let traversedObjects: any[] = []
return JSON.stringify(
json,
function (key, value) {
if (key !== '') {
traversedKeys.push(key)
traversedObjects.push(this)
}

if (typeof value !== 'object') {
const path = traversedKeys.join('/')
const matcherTraversedObjects = [...traversedObjects]

console.log(path)

traversedKeys.pop()
traversedObjects.pop()

if (typeof value === 'number') {
for (const matcher of matches) {
console.log(path, matcher.pathGlob, isMatch(path, matcher.pathGlob))

if (isMatch(path, matcher.pathGlob) && (!matcher.apply || matcher.apply(path, matcherTraversedObjects))) {
let result = value.toString()

return `$___dash___floatPropertyTruncationFix___THIS IS AUTO GENERATED AND I HATE IT___${result.includes('.') ? result : result + '.0'}`
}
}
}

return value
} else {
return value
}
},
spacing
).replaceAll(/"\$___dash___floatPropertyTruncationFix___THIS IS AUTO GENERATED AND I HATE IT___([0-9]|\.|-)+"/g, value => {
return value.substring(80, value.length - 1)
})
}

/*
Fixes the issue where stringified JSON will truncate floats which minecraft expects to be in entity float properties
*/
export const FloatPropertyTruncationFix: TCompilerPluginFactory = ({ fileType }) => {
return {
finalizeBuild(filePath, fileContent) {
if (fileType?.getId(filePath) !== 'entity') return

if (!filePath.endsWith('player.json')) return fileContent

if (typeof fileContent === 'string') return fileContent

return jsonStringifyWithFloatFix(fileContent, [
{
pathGlob: 'minecraft:entity/description/properties/*/value',
apply(path, traversedObjects) {
if (traversedObjects.length === 0) return false

if (traversedObjects[traversedObjects.length - 1].type !== 'float') return false

return true
},
},
{
pathGlob: 'minecraft:entity/description/properties/*/range/*',
apply(path, traversedObjects) {
if (traversedObjects.length < 2) return false

if (traversedObjects[traversedObjects.length - 2].type !== 'float') return false

return true
},
},
])
},
}
}
6 changes: 0 additions & 6 deletions src/Plugins/BuiltIn/Molang.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,12 +176,6 @@ export const MolangPlugin: TCompilerPluginFactory<{
}
},

finalizeBuild(filePath, fileContent) {
// Make sure JSON files are transformed back into a format that we can write to disk
if (loadMolangFrom(filePath) && typeof fileContent !== 'string')
return JSON.stringify(fileContent, null, '\t')
},

buildEnd() {
astTransformers = []
},
Expand Down