summaryrefslogtreecommitdiff
path: root/js/main.ts
blob: 027baa3cf025b767cb5790b7265edbf832471ef6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// tslint:disable-next-line:no-reference
/// <reference path="deno.d.ts" />
import * as ts from "typescript";

import { flatbuffers } from "flatbuffers";
import { deno as fbs } from "./msg_generated";
import { assert } from "./util";

// import * as runtime from "./runtime";

const globalEval = eval;
const window = globalEval("this");

let cmdIdCounter = 0;
function assignCmdId(): number {
  // TODO(piscisaureus) Safely re-use so they don't overflow.
  const cmdId = ++cmdIdCounter;
  assert(cmdId < 2 ** 32, "cmdId overflow");
  return cmdId;
}

function startMsg(cmdId: number): ArrayBuffer {
  const builder = new flatbuffers.Builder();
  const msg = fbs.Start.createStart(builder, 0);
  fbs.Base.startBase(builder);
  fbs.Base.addCmdId(builder, cmdId);
  fbs.Base.addMsg(builder, msg);
  fbs.Base.addMsgType(builder, fbs.Any.Start);
  builder.finish(fbs.Base.endBase(builder));
  return typedArrayToArrayBuffer(builder.asUint8Array());
}

window["denoMain"] = () => {
  deno.print(`ts.version: ${ts.version}`);

  // First we send an empty "Start" message to let the privlaged side know we
  // are ready. The response should be a "StartRes" message containing the CLI
  // argv and other info.
  const cmdId = assignCmdId();
  const res = deno.send(startMsg(cmdId));

  // TODO(ry) Remove this conditional once main.rs gets up to speed.
  if (res == null) {
    console.log(`The 'Start' message got a null response.  Normally this would
    be an error but main.rs currently does this."); Exiting without error.`);
    return;
  }

  // Deserialize res into startResMsg.
  const bb = new flatbuffers.ByteBuffer(new Uint8Array(res));
  const base = fbs.Base.getRootAsBase(bb);
  assert(base.cmdId() === cmdId);
  assert(fbs.Any.StartRes === base.msgType());
  const startResMsg = new fbs.StartRes();
  assert(base.msg(startResMsg) != null);

  const cwd = startResMsg.cwd();
  deno.print(`cwd: ${cwd}`);

  const argv: string[] = [];
  for (let i = 0; i < startResMsg.argvLength(); i++) {
    argv.push(startResMsg.argv(i));
  }
  deno.print(`argv ${argv}`);

  /* TODO(ry) Uncomment to test further message passing.
  const inputFn = argv[0];
  const mod = runtime.resolveModule(inputFn, `${cwd}/`);
  mod.compileAndRun();
  */
};

function typedArrayToArrayBuffer(ta: Uint8Array): ArrayBuffer {
  return ta.buffer.slice(
    ta.byteOffset,
    ta.byteOffset + ta.byteLength
  ) as ArrayBuffer;
}