summaryrefslogtreecommitdiff
path: root/cli/js2/40_compiler_api.js
blob: 8a2aa759a57f7b873f87ea358155957c103bfc9f (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

// This file contains the runtime APIs which will dispatch work to the internal
// compiler within Deno.
((window) => {
  const util = window.__bootstrap.util;
  const { sendAsync } = window.__bootstrap.dispatchJson;

  function opCompile(request) {
    return sendAsync("op_compile", request);
  }

  function opTranspile(
    request,
  ) {
    return sendAsync("op_transpile", request);
  }

  function checkRelative(specifier) {
    return specifier.match(/^([\.\/\\]|https?:\/{2}|file:\/{2})/)
      ? specifier
      : `./${specifier}`;
  }

  // TODO(bartlomieju): change return type to interface?
  function transpileOnly(
    sources,
    options = {},
  ) {
    util.log("Deno.transpileOnly", { sources: Object.keys(sources), options });
    const payload = {
      sources,
      options: JSON.stringify(options),
    };
    return opTranspile(payload);
  }

  // TODO(bartlomieju): change return type to interface?
  async function compile(
    rootName,
    sources,
    options = {},
  ) {
    const payload = {
      rootName: sources ? rootName : checkRelative(rootName),
      sources,
      options: JSON.stringify(options),
      bundle: false,
    };
    util.log("Deno.compile", {
      rootName: payload.rootName,
      sources: !!sources,
      options,
    });
    const result = await opCompile(payload);
    util.assert(result.emitMap);
    const maybeDiagnostics = result.diagnostics.length === 0
      ? undefined
      : result.diagnostics;

    const emitMap = {};

    for (const [key, emittedSource] of Object.entries(result.emitMap)) {
      emitMap[key] = emittedSource.contents;
    }

    return [maybeDiagnostics, emitMap];
  }

  // TODO(bartlomieju): change return type to interface?
  async function bundle(
    rootName,
    sources,
    options = {},
  ) {
    const payload = {
      rootName: sources ? rootName : checkRelative(rootName),
      sources,
      options: JSON.stringify(options),
      bundle: true,
    };
    util.log("Deno.bundle", {
      rootName: payload.rootName,
      sources: !!sources,
      options,
    });
    const result = await opCompile(payload);
    util.assert(result.output);
    const maybeDiagnostics = result.diagnostics.length === 0
      ? undefined
      : result.diagnostics;
    return [maybeDiagnostics, result.output];
  }

  window.__bootstrap.compilerApi = {
    bundle,
    compile,
    transpileOnly,
  };
})(this);