Skip to content

Commit

Permalink
Add better logging and error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Peterclark1996 committed Aug 21, 2024
1 parent 2d270c1 commit 57de628
Show file tree
Hide file tree
Showing 7 changed files with 76 additions and 29 deletions.
2 changes: 1 addition & 1 deletion packages/create-s2ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "create-s2ts",
"version": "0.3.1",
"version": "0.3.2",
"description": "A tool to scaffold a s2ts project",
"main": "dist/index.js",
"bin": {
Expand Down
2 changes: 1 addition & 1 deletion packages/s2ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "s2ts",
"version": "0.3.1",
"version": "0.3.2",
"description": "A tool to automatically compile counter-strike TS files (.vts files)",
"main": "dist/index.js",
"bin": {
Expand Down
38 changes: 23 additions & 15 deletions packages/s2ts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { compileToVtsc } from "./logic/compile"
import { transpileFromTypeScript } from "./logic/transpile"
import { bundleImports } from "./logic/rollup"
import { VtsFile } from "./types/file"
import { logger } from "./log"

export const s2tsVersion = "0.0.0"

Expand All @@ -17,7 +18,7 @@ export const start = (specifiedPath: string | undefined) => {
const watchDir = standardisePath(path.join(projectDir, "./scripts"))

if (!watchDir.includes(sourcePathPart)) {
console.error(
logger.error(
`The current path '${watchDir}' was expected to contain '${sourcePathPart}' but it did not. Check if you are running in the correct folder.`
)
return
Expand All @@ -31,33 +32,40 @@ export const start = (specifiedPath: string | undefined) => {
.watch(watchDir, { persistent: true })
.on("add", filePath => processFileAtPath({ project: projectDir, file: filePath }))
.on("change", filePath => processFileAtPath({ project: projectDir, file: filePath }))
.on("error", error => console.error(`Watcher error: ${error}`))
.on("error", error => logger.error(`Watcher error: ${error}`))

console.log(`Watching for file changes in ${watchDir}`)
logger.info(`Watching for file changes in ${watchDir}`)
}

const processFileAtPath = async (pathFor: { project: string; file: string }) => {
if (!pathFor.file.endsWith(".vts") && !pathFor.file.endsWith(".ts")) return

const standardFilePath = standardisePath(pathFor.file)

const compiledBuffer = await processFileData(pathFor.project, {
name: path.basename(standardFilePath),
path: standardFilePath,
content: readFileSync(standardFilePath).toString("utf-8")
})
try {
const compiledBuffer = await processFileData(pathFor.project, {
name: path.basename(standardFilePath),
path: standardFilePath,
content: readFileSync(standardFilePath).toString("utf-8")
})

const outputFilePath = standardFilePath.replace(".vts", ".vts_c").replace(".ts", ".vts_c").replace(sourcePathPart, targetPathPart)
mkdirSync(path.dirname(outputFilePath), { recursive: true })
writeFileSync(outputFilePath, compiledBuffer)
if (!compiledBuffer) return

const now = new Date()
console.log(`${now.toLocaleTimeString()} Compiled: ${path.basename(outputFilePath)}`)
const outputFilePath = standardFilePath.replace(".vts", ".vts_c").replace(".ts", ".vts_c").replace(sourcePathPart, targetPathPart)
mkdirSync(path.dirname(outputFilePath), { recursive: true })
writeFileSync(outputFilePath, compiledBuffer)

logger.info(`Compiled: ${path.basename(outputFilePath)}`)
} catch (error) {
logger.error(`Error in s2ts: ${error}`)
}
}

export const processFileData = async (pathForProject: string, file: VtsFile) => {
const transpiledData = transpileFromTypeScript(file.content)
const bundledData = await bundleImports(pathForProject, { ...file, content: transpiledData })
const transpiledResult = transpileFromTypeScript(file)
if (!transpiledResult.success) return

const bundledData = await bundleImports(pathForProject, { ...file, content: transpiledResult.output })
const bundledDataWithVersion = addS2tsVersion(bundledData)
return compileToVtsc(bundledDataWithVersion)
}
Expand Down
10 changes: 10 additions & 0 deletions packages/s2ts/src/log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export const logger = {
info: (message: string) => {
const now = new Date()
console.log(`${now.toLocaleTimeString()} ${message}`)
},
error: (message: string) => {
const now = new Date()
console.error(`${now.toLocaleTimeString()} ${message}`)
}
}
17 changes: 13 additions & 4 deletions packages/s2ts/src/logic/rollup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,17 @@ export const bundleImports = async (pathForProject: string, file: VtsFile): Prom

return null
},
load: (id: string) => {
if (id === file.name) return file.content
if (fs.existsSync(id)) return transpileFromTypeScript(fs.readFileSync(id, "utf-8"))
load: (path: string) => {
if (path === file.name) return file.content
if (fs.existsSync(path)) {
const transpiledResult = transpileFromTypeScript({
name: path,
path,
content: fs.readFileSync(path, "utf-8")
})

if (transpiledResult.success) return transpiledResult.output
}

return null
}
Expand All @@ -44,7 +52,8 @@ export const bundleImports = async (pathForProject: string, file: VtsFile): Prom
virtualPlugin,
typescript({
module: "ESNext",
target: "ES2015"
target: "ES2015",
outputToFilesystem: false
})
],
external: ["cspointscript"],
Expand Down
30 changes: 25 additions & 5 deletions packages/s2ts/src/logic/transpile.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,34 @@
import { ModuleKind, ScriptTarget, transpileModule } from "typescript"
import { ModuleKind, ScriptTarget, transpileModule, flattenDiagnosticMessageText } from "typescript"
import { VtsFile } from "../types/file"
import { logger } from "../log"

export const transpileFromTypeScript = (source: string): string => {
const result = transpileModule(source, {
export const transpileFromTypeScript = (file: VtsFile): { output: string; success: boolean } => {
const result = transpileModule(file.content, {
compilerOptions: {
module: ModuleKind.ESNext,
target: ScriptTarget.ES2015,
removeComments: true,
esModuleInterop: false,
allowSyntheticDefaultImports: false
}
},
reportDiagnostics: true
})
return result.outputText

if (result.diagnostics && result.diagnostics.length > 0) {
result.diagnostics.forEach(diagnostic => {
const message = flattenDiagnosticMessageText(diagnostic.messageText, "\n")
const now = new Date()
if (diagnostic.file && diagnostic.start !== undefined) {
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start)
logger.error(`Error in ${file.path} (${line + 1},${character + 1}): ${message}`)
} else {
logger.error(`Error in ${file.path}: ${message}`)
}
})
}

return {
output: result.outputText,
success: !result.diagnostics || result.diagnostics.length === 0
}
}
6 changes: 3 additions & 3 deletions packages/s2ts/tests/compile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ test("I can compile a vts file and get a correctly formed vts_c file", async ()
const content = readFileSync(sourcePath).toString("utf-8")

const actualBuffer = await processFileData(".", { name: "test.ts", path: "./test.ts", content })
const actual = actualBuffer.toString("utf-8")
const actual = actualBuffer?.toString("utf-8")

const expectedPath = path.join(__dirname, "/resource/test.vts_c")
const expected = readFileSync(expectedPath).toString("utf-8")
Expand All @@ -20,7 +20,7 @@ test("I can compile a vts typescript file and get a correctly formed vts_c javas
const content = readFileSync(sourcePath).toString("utf-8")

const actualBuffer = await processFileData(".", { name: "test.ts", path: "./test.ts", content })
const actual = actualBuffer.toString("utf-8")
const actual = actualBuffer?.toString("utf-8")

const expectedPath = path.join(__dirname, "/resource/test_withTypes.vts_c")
const expected = readFileSync(expectedPath).toString("utf-8")
Expand All @@ -33,7 +33,7 @@ test("I can compile a vts file and see the s2ts version in the header of the vts
const content = readFileSync(sourcePath).toString("utf-8")

const actualBuffer = await processFileData(".", { name: "test.ts", path: "./test.ts", content })
const actual = actualBuffer.toString("utf-8")
const actual = actualBuffer?.toString("utf-8")

expect(actual).toContain("// s2ts v0.0.0")
})

0 comments on commit 57de628

Please sign in to comment.