y-lohse / inkjs

A javascript port of inkle's ink scripting language.
http://www.inklestudios.com/ink/
MIT License
507 stars 104 forks source link

What's the correct syntax for Compiler with JSON file handler? #1054

Closed Liquidream closed 7 months ago

Liquidream commented 7 months ago

Hi there,

I'm trying to use the JSON File Handler to dynamically compile several linked ink scripts using Typescript, but I think I'm missing something on how to use the handler correctly.

The code I've got is something like this (simplified for illustration purposes)

private inkStory: InstanceType<typeof Story>
private inkCompiler: InstanceType<typeof Compiler>
private inkJsonFileHandler: InstanceType<typeof JsonFileHandler>

// Setup Ink content/JSON Handler
const jsonInkPackage: Record<string, string> = {
   "_main.ink":   "INCLUDE script1.ink\n INCLUDE script2.ink ",
   "script1.ink": "=== chapter_1 \n example text here...",
   "script2.ink": "=== chapter_2 \n example text here...",
}
const jsonFileHandler = new JsonFileHandler(jsonInkPackage)

// Setup Compiler
const inkCompiler = new Compiler(null, {
   errorHandler: (msg, type) => {
        if (type == ErrorType.Warning) console.warn(msg)
        else console.error(msg)
  },
  countAllVisits: true,                 // Note: I'm specifying all params, else get TS type warning for the param?
  fileHandler: jsonFileHandler,
  pluginNames: [],
  sourceFilename: null,
})

// Compile the story
try {
  inkStory = inkCompiler.Compile()
  // DEBUG: To check compiled story contains all data..
  const jsonBytecode = inkStory.ToJson()
  console.log(jsonBytecode)
} catch (err) {
  console.error(err)
}

The trouble is, I don't know what to pass as the first parameter to Compiler() (string that normally has the ink script), as now all the content is in the jsonFileHandler object.

I've tried passing empty strings and null (as above), but it seems that just compiles an empty story and doesn't trigger the JSON file handler.

Any guidance given would be much appreciated, thanks! 🤓

smwhr commented 7 months ago

You should pass the main ink file as usual, and all other file via the json dictionnary (note that this is the same behaviour for the classic PosixHandler : you pass the main file and the PosixHandler look for the additional INCLUDEd files on disk)

Alternatively, you can pass "INCLUDE main.ink"

Liquidream commented 7 months ago

Thank you, @smwhr 🙌 As soom as I started reading your comment, I realised what I was missing/doing wrong. It's all working perfectly now, thank you ❤️