Skip to content

Commit

Permalink
feat(repl): add @jxa/repl (#3)
Browse files Browse the repository at this point in the history
* feat(repl): add @jxa/repl

* chore(repl): handle empty input

* test(repl): add test
  • Loading branch information
azu authored Jun 25, 2018
1 parent dbf0e97 commit ef4f112
Show file tree
Hide file tree
Showing 13 changed files with 318 additions and 34 deletions.
19 changes: 19 additions & 0 deletions packages/@jxa/repl/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2018 azu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
53 changes: 53 additions & 0 deletions packages/@jxa/repl/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# @jxa/repl

REPL for JXA.

## Install

Install with [npm](https://www.npmjs.com/):

npm install -g @jxa/rep

## Usage

$ npx @jxa/repl
# or
$ npm install -g @jxa/repl
$ jxa-repl
> Application("System Events").currentUser().name();

## Command

### `.clear`

Clear current buffer and history.
It will release defined variables.

## Changelog

See [Releases page](https://github.com/JXA-userland/JXA/releases).

## Reference

- [REPL | Node.js v10.5.0 Documentation](https://nodejs.org/api/repl.html)

## Contributing

Pull requests and stars are always welcome.

For bugs and feature requests, [please create an issue](https://github.com/JXA-userland/JXA/issues).

1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request :D

## Author

- [github/azu](https://github.com/azu)
- [twitter/azu_re](https://twitter.com/azu_re)

## License

MIT © azu
3 changes: 3 additions & 0 deletions packages/@jxa/repl/bin/cmd.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env node
const run = require("../lib/cli.js").run;
run();
65 changes: 65 additions & 0 deletions packages/@jxa/repl/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"name": "@jxa/repl",
"version": "1.0.0",
"description": "REPL for JXA.",
"keywords": [
"cli",
"jxa",
"node.js",
"repl"
],
"homepage": "https://github.com/JXA-userland/JXA/tree/master/packages/@jxa/repl/",
"bugs": {
"url": "https://github.com/JXA-userland/JXA/issues"
},
"license": "MIT",
"author": "azu",
"files": [
"bin/",
"lib/",
"src/"
],
"main": "lib/repl.js",
"types": "lib/repl.d.ts",
"bin": {
"jxa-repl": "./bin/cmd.js"
},
"directories": {
"lib": "lib",
"test": "test"
},
"repository": {
"type": "git",
"url": "https://github.com/JXA-userland/JXA.git"
},
"scripts": {
"build": "cross-env NODE_ENV=production tsc -p .",
"clean": "rimraf lib/",
"prepublish": "npm run --if-present build",
"test": "mocha \"test/**/*.ts\"",
"prettier": "prettier --write \"**/*.{js,jsx,ts,tsx,css}\"",
"watch": "tsc -p . --watch"
},
"prettier": {
"printWidth": 120,
"singleQuote": false,
"tabWidth": 4
},
"dependencies": {
"@jxa/run": "^1.0.3"
},
"devDependencies": {
"@types/mocha": "^5.2.3",
"@types/node": "^10.3.5",
"cross-env": "^5.2.0",
"mocha": "^5.2.0",
"prettier": "^1.7.4",
"rimraf": "^2.6.2",
"ts-node": "^7.0.0",
"ts-node-test-register": "^4.0.0",
"typescript": "^2.9.2"
},
"publishConfig": {
"access": "public"
}
}
6 changes: 6 additions & 0 deletions packages/@jxa/repl/src/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { JXARepl } from "./repl";

export const run = () => {
const repl = new JXARepl();
repl.start();
};
39 changes: 39 additions & 0 deletions packages/@jxa/repl/src/repl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as repl from "repl";
import { runJXACode } from "@jxa/run";
import * as util from "util";

export class JXARepl {
private replServer!: repl.REPLServer;

start() {
this.replServer = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });
const cmdStack: string[] = [];
// ".clear" command
this.replServer.defineCommand("clear", () => {
cmdStack.length = 0;
(this.replServer as any).clearBufferedCommand()
});

function myEval(cmd: string, _context: any, _filename: string, callback: (error: Error | null, cmd?: string) => void) {
if (cmd.length === 0) {
return callback(null);
}
const existCode = cmdStack.join("\n");
let code = existCode + "\n" + cmd;
runJXACode(code).then(output => {
cmdStack.push(cmd);
callback(null, util.inspect(output));
}).catch(error => {
callback(error);
});
}

function myWriter(output: string) {
return output;
}
}

stop() {
this.replServer.close();
}
}
1 change: 1 addition & 0 deletions packages/@jxa/repl/test/mocha.opts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
--require ts-node-test-register
9 changes: 9 additions & 0 deletions packages/@jxa/repl/test/repl-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { JXARepl } from "../src/repl";

describe("@jxa/repl", () => {
it("start and stop", () => {
const repl = new JXARepl();
repl.start();
repl.stop();
});
});
9 changes: 9 additions & 0 deletions packages/@jxa/repl/test/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"declaration": false
},
"include": [
"**/*"
]
}
35 changes: 35 additions & 0 deletions packages/@jxa/repl/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"compilerOptions": {
/* Basic Options */
"module": "commonjs",
"moduleResolution": "node",
"newLine": "LF",
"outDir": "./lib/",
"target": "es5",
"sourceMap": true,
"declaration": true,
"jsx": "preserve",
"lib": [
"es2017",
"dom"
],
/* Strict Type-Checking Options */
"strict": true,
/* Additional Checks */
"noUnusedLocals": true,
/* Report errors on unused locals. */
"noUnusedParameters": true,
/* Report errors on unused parameters. */
"noImplicitReturns": true,
/* Report error when not all code paths in function return a value. */
"noFallthroughCasesInSwitch": true
/* Report errors for fallthrough cases in switch statement. */
},
"include": [
"src/**/*"
],
"exclude": [
".git",
"node_modules"
]
}
18 changes: 15 additions & 3 deletions packages/@jxa/run/src/run.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
const execFile = require("child_process").execFile;
const macosVersion = require("macos-version");

export function runJXACode(jxaCode: string) {
return executeInOsa(jxaCode, []);
}

export function run<R>(jxaCodeFunction: (...args: any[]) => void, ...args: any[]): Promise<R>;
export function run<R, A1>(jxaCodeFunction: (a1: A1) => void, a1: A1): Promise<R>;
export function run<R, A1, A2>(jxaCodeFunction: (a1: A1, a2: A2) => void, a1: A1, a2: A2): Promise<R>;
Expand Down Expand Up @@ -73,8 +77,15 @@ ObjC.import('Foundation');
var args = JSON.parse(ObjC.unwrap($.NSProcessInfo.processInfo.environment.objectForKey("OSA_ARGS")));
var fn = (${jxaCodeFunction.toString()});
var out = fn.apply(null, args);
JSON.stringify(out);
JSON.stringify({ result: out });
`;
return executeInOsa(code, args);
}

/**
* execute the `code` in `osascript`
*/
function executeInOsa(code: string, args: any[]) {
return new Promise((resolve, reject) => {
macosVersion.assertGreaterThanOrEqualTo("10.10");
const child = execFile(
Expand All @@ -99,9 +110,10 @@ JSON.stringify(out);
}

try {
resolve(JSON.parse(stdout.toString()));
const result = JSON.parse(stdout.toString().trim()).result;
resolve(result);
} catch (errorOutput) {
reject(errorOutput);
resolve(stdout.toString().trim());
}
}
);
Expand Down
66 changes: 37 additions & 29 deletions packages/@jxa/run/test/run-test.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,48 @@
import "@jxa/global-type";
import { run } from "../src/run";
import { run, runJXACode } from "../src/run";
import * as assert from "assert";

describe("@jxa/run", () => {
it("script execution", async () => {
const result = await run(name => {
return "Hello there, " + name + "!"
}, "nodejs");
assert.strictEqual(result, "Hello there, nodejs!");
});
it("system access", async () => {
const result = await run(
() =>
Application("System Events")
.currentUser()
.name(),
);
assert.strictEqual(result, process.env.USER);
});
it("multiline", async () => {
const result = await run(function () {
var foo = "bar";
var baz = "foo";
return baz + foo;
describe("#runJXACode", () => {
it("script execution", async () => {
const result = await runJXACode(`const sys = Application("System Events");sys.currentUser().name();`);
assert.strictEqual(result, process.env.USER);
});
assert.strictEqual(result, "foobar");
});
describe("#run", () => {
it("script execution", async () => {
const result = await run(name => {
return "Hello there, " + name + "!"
}, "nodejs");
assert.strictEqual(result, "Hello there, nodejs!");
});
it("system access", async () => {
const result = await run(
() =>
Application("System Events")
.currentUser()
.name()
);
assert.strictEqual(result, process.env.USER);
});
it("multiline", async () => {
const result = await run(function () {
var foo = "bar";
var baz = "foo";
return baz + foo;
});
assert.strictEqual(result, "foobar");
});

it("correct return value", async () => {
const result = await run(() => 123.47);
assert.strictEqual(result, 123.47);
});
it("correct return value", async () => {
const result = await run(() => 123.47);
assert.strictEqual(result, 123.47);
});

it("undefined return", async () => {
const result = await run(() => {
it("undefined return", async () => {
const result = await run(() => {
});
assert.strictEqual(result, undefined);
});
assert.strictEqual(result, undefined);
});
});
Loading

0 comments on commit ef4f112

Please sign in to comment.