3

I am trying to make use of the new JavaScript Automation feature in OS X (10.11) to script an application that does not offer a dictionary. I have an AppleScript that interacts with that application using raw Apple Events, like so:

tell application "Bookends"
  return «event ToySSQLS» "authors REGEX 'Johnson' "
end tell

Now my question is: how do I translate this to JavaScript? I cannot find any information on the Javascript OSA API to send and receive raw Apple events.

One possible workaround might be to call a piece of AppleScript through the shell, but I would prefer to work with a "real" API.

Community
  • 1
  • 1
Panyasan
  • 88
  • 6

1 Answers1

1

You can at least do something faster than a shell script call by using OSAKit in a couple of helper functions:

// evalOSA :: String -> String -> IO String
function evalOSA(strLang, strCode) {

    var oScript = ($.OSAScript || (
            ObjC.import('OSAKit'),
            $.OSAScript))
        .alloc.initWithSourceLanguage(
            strCode, $.OSALanguage.languageForName(strLang)
        ),
        error = $(),
        blnCompiled = oScript.compileAndReturnError(error),
        oDesc = blnCompiled ? (
            oScript.executeAndReturnError(error)
        ) : undefined;

    return oDesc ? (
        oDesc.stringValue.js
    ) : error.js.NSLocalizedDescription.js;
}

// eventCode :: String -> String
function eventCode(strCode) {
    return 'tell application "Bookends" to «event ToyS' +
        strCode + '»';
}

which then allow you to write functions like:

// sqlMatchIDs :: String -> [String]
function sqlMatchIDs(strClause) {
    // SELECT clause without the leading SELECT keyword
    var strResult = evalOSA(
        '', eventCode('SQLS') +
        ' "' + strClause + '"'
    );

    return strResult.indexOf('\r') !== -1 ? (
        strResult.split('\r')
    ) : (strResult ? [strResult] : []);
}

and calls like

sqlMatchIDs("authors like '%Harrington%'")

Fuller set of examples here: JavaScript wrappers for Bookends functions

houthakker
  • 688
  • 5
  • 13