Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support typescript #129

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/sum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function sum(a: number, b: number): number {
return a + b;
}
65 changes: 65 additions & 0 deletions docs/typescript.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# TypeScript

[Observable Markdown](./markdown) supports TypeScript — an extension of JavaScript adding types to the language — in fenced code blocks and inline expressions.

`ts` code blocks use [esbuild](https://esbuild.github.io/) to parse TypeScript syntax and discard the type annotations. Inline expressions that fail to parse with JavaScript are likewise passed to esbuild, and replaced with the transform if it succeeds.

Note however that this support is limited to parsing the code and converting it to JavaScript; esbuild does not do any type checking.

TypeScript is also supported in [data loaders](./loaders).

````md
```ts
const message: string = "Hello, world!";
```
````

try this one:

```ts echo
const file: FileAttachment = FileAttachment("javascript/hello.txt");
```

```ts echo
file.text()
```

```ts echo
function add(a: number, b: number): number {
return a + b;
}
```

The resulting function can be called from js cells as well as other ts cells:

```js echo
add(1, 3)
```

```ts echo
add(1 as number, 3)
```

Inline expressions are also converted when they appear to be written in TypeScript:

1 + 2 = ${add(1 as number, 2)}.

```md echo
1 + 2 = ${add(1 as number, 2)}.
```

Syntax errors are shown as expected:

```ts echo
function bad() ::: {
return a + b;
}
```

Imports are transpiled too (here `sum.js` refers to `sum.ts`; by convention, TypeScript files have the `.ts` extension but are imported using `.js`):

```ts echo
import {sum} from "./sum.js";

display(sum(1, 2));
```
6 changes: 4 additions & 2 deletions src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {bundleStyles, rollupClient} from "./rollup.js";
import {searchIndex} from "./search.js";
import {Telemetry} from "./telemetry.js";
import {faint, yellow} from "./tty.js";
import {transpileTypeScript} from "./typescript.js";

export interface BuildOptions {
config: Config;
Expand Down Expand Up @@ -188,7 +189,7 @@ export async function build(
const resolveImportAlias = (path: string): string => {
const hash = getModuleHash(root, path).slice(0, 8);
const ext = extname(path);
return `/${join("_import", dirname(path), basename(path, ext))}.${hash}${ext}`;
return `/${join("_import", dirname(path), basename(path, ext))}.${hash}${ext === "ts" ? "js" : ext}`;
};
for (const path of localImports) {
const sourcePath = join(root, path);
Expand All @@ -198,7 +199,8 @@ export async function build(
}
effects.output.write(`${faint("copy")} ${sourcePath} ${faint("→")} `);
const resolveImport = getModuleResolver(root, path);
const input = await readFile(sourcePath, "utf-8");
let input = await readFile(sourcePath, "utf-8");
if (path.endsWith(".ts")) input = transpileTypeScript(input);
const contents = await transpileModule(input, {
root,
path,
Expand Down
8 changes: 7 additions & 1 deletion src/dataloader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {FileWatchers} from "./fileWatchers.js";
import {getFileHash} from "./javascript/module.js";
import type {Logger, Writer} from "./logger.js";
import {cyan, faint, green, red, yellow} from "./tty.js";
import {getTypeScriptPath} from "./typescript.js";

const runningCommands = new Map<string, Promise<string>>();

Expand Down Expand Up @@ -122,7 +123,12 @@ export class LoaderResolver {

getWatchPath(path: string): string | undefined {
const exactPath = join(this.root, path);
return existsSync(exactPath) ? exactPath : this.find(path)?.path;
if (existsSync(exactPath)) return exactPath;
if (path.endsWith(".js")) {
const tspath = getTypeScriptPath(exactPath);
if (existsSync(tspath)) return tspath;
}
return this.find(path)?.path;
}

watchFiles(path: string, watchPaths: Iterable<string>, callback: (name: string) => void) {
Expand Down
10 changes: 8 additions & 2 deletions src/javascript/module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import {createHash} from "node:crypto";
import {readFileSync, statSync} from "node:fs";
import {existsSync, readFileSync, statSync} from "node:fs";
import {join} from "node:path/posix";
import type {Program} from "acorn";
import {resolvePath} from "../path.js";
import {getTypeScriptPath, transpileTypeScript} from "../typescript.js";
import {findFiles} from "./files.js";
import {findImports} from "./imports.js";
import {parseProgram} from "./parse.js";
Expand Down Expand Up @@ -70,7 +71,11 @@ export function getModuleHash(root: string, path: string): string {
* source root, or undefined if the module does not exist or has invalid syntax.
*/
export function getModuleInfo(root: string, path: string): ModuleInfo | undefined {
const key = join(root, path);
let key = join(root, path);
if (!existsSync(key) && path.endsWith(".js")) {
const tskey = getTypeScriptPath(key);
if (existsSync(tskey)) key = tskey;
}
let mtimeMs: number;
try {
({mtimeMs} = statSync(key));
Expand All @@ -84,6 +89,7 @@ export function getModuleInfo(root: string, path: string): ModuleInfo | undefine
let body: Program;
try {
source = readFileSync(key, "utf-8");
if (key.endsWith(".ts")) source = transpileTypeScript(source);
body = parseProgram(source);
} catch {
moduleInfoCache.delete(key); // delete stale entry
Expand Down
7 changes: 6 additions & 1 deletion src/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {transpileSql} from "./sql.js";
import {transpileTag} from "./tag.js";
import {InvalidThemeError} from "./theme.js";
import {red} from "./tty.js";
import {transpileTypeScript} from "./typescript.js";

export interface MarkdownCode {
id: string;
Expand Down Expand Up @@ -54,6 +55,8 @@ function isFalse(attribute: string | undefined): boolean {
function getLiveSource(content: string, tag: string, attributes: Record<string, string>): string | undefined {
return tag === "js"
? content
: tag === "ts"
? transpileTypeScript(content)
: tag === "tex"
? transpileTag(content, "tex.block", true)
: tag === "html"
Expand Down Expand Up @@ -100,6 +103,7 @@ function makeFenceRenderer(baseRenderer: RenderRule): RenderRule {
if (source != null) {
const id = uniqueCodeId(context, source);
// TODO const sourceLine = context.startLine + context.currentLine;
if (tag === "ts") source = transpileTypeScript(source);
const node = parseJavaScript(source, {path});
context.code.push({id, node});
html += `<div id="cell-${id}" class="observablehq observablehq--block${
Expand Down Expand Up @@ -255,7 +259,8 @@ function makePlaceholderRenderer(): RenderRule {
const id = uniqueCodeId(context, token.content);
try {
// TODO sourceLine: context.startLine + context.currentLine
const node = parseJavaScript(token.content, {path, inline: true});
const input = transpileTypeScript(token.content);
const node = parseJavaScript(input, {path, inline: true});
context.code.push({id, node});
return `<span id="cell-${id}" class="observablehq--loading"></span>`;
} catch (error) {
Expand Down
12 changes: 9 additions & 3 deletions src/preview.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {createHash} from "node:crypto";
import {watch} from "node:fs";
import {existsSync, watch} from "node:fs";
import type {FSWatcher, WatchEventType} from "node:fs";
import {access, constants, readFile} from "node:fs/promises";
import {createServer} from "node:http";
Expand Down Expand Up @@ -30,6 +30,7 @@ import {bundleStyles, rollupClient} from "./rollup.js";
import {searchIndex} from "./search.js";
import {Telemetry} from "./telemetry.js";
import {bold, faint, green, link} from "./tty.js";
import {getTypeScriptPath, transpileTypeScript} from "./typescript.js";

export interface PreviewOptions {
config: Config;
Expand Down Expand Up @@ -111,14 +112,19 @@ export class PreviewServer {
send(req, pathname, {root: join(root, ".observablehq", "cache")}).pipe(res);
} else if (pathname.startsWith("/_import/")) {
const path = pathname.slice("/_import".length);
const filepath = join(root, path);
let filepath = join(root, path);
try {
if (pathname.endsWith(".css")) {
await access(filepath, constants.R_OK);
end(req, res, await bundleStyles({path: filepath}), "text/css");
return;
} else if (pathname.endsWith(".js")) {
const input = await readFile(join(root, path), "utf-8");
if (!existsSync(filepath)) {
const tspath = getTypeScriptPath(filepath);
if (existsSync(tspath)) filepath = tspath;
}
let input = await readFile(filepath, "utf-8");
if (filepath.endsWith(".ts")) input = transpileTypeScript(input);
const output = await transpileModule(input, {root, path});
end(req, res, output, "text/javascript");
return;
Expand Down
19 changes: 19 additions & 0 deletions src/typescript.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {transformSync} from "esbuild";

export function transpileTypeScript(input: string): string {
try {
const js = transformSync(input, {
loader: "ts",
tsconfigRaw: '{"compilerOptions": {"verbatimModuleSyntax": true}}'
}).code;
// preserve the absence of a trailing semi-colon, to display
return input.trim().at(-1) !== ";" ? js.replace(/;[\s\n]*$/, "") : js;
} catch {
return input;
}
}

export function getTypeScriptPath(path: string): string {
if (!path.endsWith(".js")) throw new Error(`expected .js: ${path}`);
return path.slice(0, -".js".length) + ".ts";
}
3 changes: 3 additions & 0 deletions test/input/build/typescript/sum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function sum(a: number, b: number): number {
return a + b;
}
22 changes: 22 additions & 0 deletions test/input/build/typescript/typescript.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
```ts echo
function add(a: number, b: number): number {
return a + b;
}
```

```js echo
add(1, 3)
```

```ts echo
add(1 as number, 3)
```

```ts echo
import {sum} from "./sum.ts";
```

```ts echo
sum(1, 2)
```

3 changes: 3 additions & 0 deletions test/output/build/typescript/_import/sum.fd55756b.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function sum(a, b) {
return a + b;
}
89 changes: 89 additions & 0 deletions test/output/build/typescript/typescript.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preload" as="style" href="https://fonts.googleapis.com/css2?family=Source+Serif+Pro:ital,wght@0,400;0,600;0,700;1,400;1,600;1,700&amp;display=swap" crossorigin>
<link rel="preload" as="style" href="./_observablehq/theme-air,near-midnight.css">
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css2?family=Source+Serif+Pro:ital,wght@0,400;0,600;0,700;1,400;1,600;1,700&amp;display=swap" crossorigin>
<link rel="stylesheet" type="text/css" href="./_observablehq/theme-air,near-midnight.css">
<link rel="modulepreload" href="./_observablehq/client.js">
<link rel="modulepreload" href="./_observablehq/runtime.js">
<link rel="modulepreload" href="./_observablehq/stdlib.js">
<link rel="modulepreload" href="./_import/sum.fd55756b.ts">
<script type="module">

import {define} from "./_observablehq/client.js";

define({id: "fe9e095e", outputs: ["add"], body: () => {
function add(a, b) {
return a + b;
}
return {add};
}});

define({id: "b2e42312", inputs: ["add","display"], body: async (add,display) => {
display(await(
add(1, 3)
))
}});

define({id: "333f7706", inputs: ["add","display"], body: async (add,display) => {
display(await(
add(1, 3)
))
}});

define({id: "c0a82f57", outputs: ["sum"], body: async () => {
const {sum} = await import("./_import/sum.fd55756b.ts");

return {sum};
}});

define({id: "87970c86", inputs: ["sum","display"], body: async (sum,display) => {
display(await(
sum(1, 2)
))
}});

</script>
<input id="observablehq-sidebar-toggle" type="checkbox" title="Toggle sidebar">
<label id="observablehq-sidebar-backdrop" for="observablehq-sidebar-toggle"></label>
<nav id="observablehq-sidebar">
<ol>
<label id="observablehq-sidebar-close" for="observablehq-sidebar-toggle"></label>
<li class="observablehq-link"><a href="./">Home</a></li>
</ol>
<ol>
<li class="observablehq-link observablehq-link-active"><a href="./typescript">Untitled</a></li>
</ol>
</nav>
<script>{/* redacted init script */}</script>
<aside id="observablehq-toc" data-selector="h1:not(:first-of-type), h2:first-child, :not(h1) + h2">
<nav>
</nav>
</aside>
<div id="observablehq-center">
<main id="observablehq-main" class="observablehq">
<div id="cell-fe9e095e" class="observablehq observablehq--block"></div>
<pre data-language="ts"><code class="language-ts"><span class="hljs-keyword">function</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-built_in">number</span> {
<span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<div id="cell-b2e42312" class="observablehq observablehq--block observablehq--loading"></div>
<pre data-language="js"><code class="language-js"><span class="hljs-title function_">add</span>(<span class="hljs-number">1</span>, <span class="hljs-number">3</span>)
</code></pre>
<div id="cell-333f7706" class="observablehq observablehq--block observablehq--loading"></div>
<pre data-language="ts"><code class="language-ts"><span class="hljs-title function_">add</span>(<span class="hljs-number">1</span> <span class="hljs-keyword">as</span> <span class="hljs-built_in">number</span>, <span class="hljs-number">3</span>)
</code></pre>
<div id="cell-c0a82f57" class="observablehq observablehq--block"></div>
<pre data-language="ts"><code class="language-ts"><span class="hljs-keyword">import</span> {sum} <span class="hljs-keyword">from</span> <span class="hljs-string">"./sum.ts"</span>;
</code></pre>
<div id="cell-87970c86" class="observablehq observablehq--block observablehq--loading"></div>
<pre data-language="ts"><code class="language-ts"><span class="hljs-title function_">sum</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
</code></pre>
</main>
<footer id="observablehq-footer">
<nav><a rel="prev" href="./"><span>Home</span></a></nav>
<div>Built with <a href="https://observablehq.com/" target="_blank">Observable</a> on <a title="2024-01-10T16:00:00">Jan 10, 2024</a>.</div>
</footer>
</div>
6 changes: 3 additions & 3 deletions test/output/single-quote-expression.md.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
"body": {
"type": "Literal",
"start": 0,
"end": 4,
"end": 5,
"value": "}\"",
"raw": "'}\"'"
"raw": "\"}\\\"\""
},
"declarations": null,
"references": [],
Expand All @@ -20,7 +20,7 @@
"expression": true,
"async": false,
"inline": true,
"input": "'}\"'"
"input": "\"}\\\"\""
}
}
]
Expand Down
Loading