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

relative fetch and FileAttachments #193

Merged
merged 9 commits into from
Nov 17, 2023
Merged
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
2 changes: 1 addition & 1 deletion public/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ export function define(cell) {
v.define(outputs.length ? `cell ${id}` : null, inputs, body);
variables.push(v);
for (const o of outputs) variables.push(main.define(o, [`cell ${id}`], (exports) => exports[o]));
for (const f of files) attachedFiles.set(f.name, {url: `/_file${(new URL(f.name, location)).pathname}`, mimeType: f.mimeType}); // prettier-ignore
for (const f of files) attachedFiles.set(f.name, {url: f.path, mimeType: f.mimeType});
for (const d of databases) databaseTokens.set(d.name, d);
}

Expand Down
21 changes: 21 additions & 0 deletions src/files.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import {type Stats} from "node:fs";
import {mkdir, readdir, stat} from "node:fs/promises";
import {dirname, extname, join, normalize, relative} from "node:path";
import mime from "mime";
import {isNodeError} from "./error.js";
import type {FileReference} from "./javascript.js";
import {relativeUrl} from "./url.js";

// A path is local if it doesn’t go outside the the root.
export function getLocalPath(sourcePath: string, name: string): string | null {
Expand All @@ -11,6 +14,24 @@ export function getLocalPath(sourcePath: string, name: string): string | null {
return path;
}

export function fileReference(name: string, root: string): FileReference {
mbostock marked this conversation as resolved.
Show resolved Hide resolved
return {
name,
mimeType: mime.getType(name),
path: normalizeRelativePath(relativeUrl(root, "/_file/" + dirname(root) + "/" + name))
mbostock marked this conversation as resolved.
Show resolved Hide resolved
};
}

function normalizeRelativePath(path) {
const parts = path.split("/").filter((d) => d !== ".");
for (let r = 1; r < parts.length; ) {
if (parts[r] === ".." && parts[r - 1] !== "..") parts.splice(--r, 2);
else ++r;
}
if (parts[0] !== "..") parts.unshift(".");
return parts.join("/");
}

export async function* visitMarkdownFiles(root: string): AsyncGenerator<string> {
for await (const file of visitFiles(root)) {
if (extname(file) !== ".md") continue;
Expand Down
6 changes: 4 additions & 2 deletions src/javascript.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {type Node, type Options, Parser, tokTypes} from "acorn";
import mime from "mime";
import {fileReference} from "./files.js";
import {findAwaits} from "./javascript/awaits.js";
import {findDeclarations} from "./javascript/declarations.js";
import {findFeatures} from "./javascript/features.js";
Expand All @@ -17,6 +17,8 @@ export interface DatabaseReference {
export interface FileReference {
name: string;
mimeType: string | null;
/** The relative path from the document to the file in _file */
path: string;
}

export interface ImportReference {
Expand Down Expand Up @@ -63,7 +65,7 @@ export function transpileJavaScript(input: string, options: ParseOptions): Trans
.map((f): DatabaseReference => ({name: f.name}));
const files = node.features
.filter((f) => f.type === "FileAttachment")
.map((f): FileReference => ({name: f.name, mimeType: mime.getType(f.name)}));
.map(({name}) => fileReference(name, sourcePath));
const inputs = Array.from(new Set<string>(node.references.map((r) => r.name)));
const output = new Sourcemap(input);
trim(output, input);
Expand Down
8 changes: 6 additions & 2 deletions src/javascript/fetches.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import {dirname, join} from "node:path";
import {simple} from "acorn-walk";
import {isLocalFetch} from "./features.js";
import {relativeUrl} from "../url.js";
import {getStringLiteralValue, isLocalFetch} from "./features.js";

export function rewriteFetches(output, rootNode, sourcePath) {
simple(rootNode.body, {
CallExpression(node) {
if (isLocalFetch(node, rootNode.references, sourcePath)) {
output.insertLeft(node.arguments[0].start + 3, "_file/");
const arg = node.arguments[0];
const value = relativeUrl(sourcePath, "/_file/" + join(dirname(sourcePath), getStringLiteralValue(arg)));
output.replaceLeft(arg.start, arg.end, JSON.stringify(value));
Comment on lines -8 to +12
Copy link
Contributor Author

@Fil Fil Nov 17, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this also fixes a bug where fetch rewrites didn't work for files in subdirectories:

If you had this in javascript/files.md:

fetch("../file.csv")

it would have been compiled to fetch(".._file//file.csv") 👎

(with this PR it becomes fetch("../_file/file.csv") 👍); tested in input/build/files/

}
}
});
Expand Down
8 changes: 4 additions & 4 deletions src/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ import {type RuleCore} from "markdown-it/lib/parser_core.js";
import {type RuleInline} from "markdown-it/lib/parser_inline.js";
import {type RenderRule, type default as Renderer} from "markdown-it/lib/renderer.js";
import MarkdownItAnchor from "markdown-it-anchor";
import mime from "mime";
import {getLocalPath} from "./files.js";
import {fileReference, getLocalPath} from "./files.js";
import {computeHash} from "./hash.js";
import {parseInfo} from "./info.js";
import {type FileReference, type ImportReference, type Transpile, transpileJavaScript} from "./javascript.js";
import {transpileTag} from "./tag.js";
import {relativeUrl} from "./url.js";

export interface ReadMarkdownResult {
contents: string;
Expand Down Expand Up @@ -329,8 +329,8 @@ function normalizePieceHtml(html: string, root: string, sourcePath: string, cont
const href = element.getAttribute("href")!;
const path = getLocalPath(sourcePath, href);
if (path) {
context.files.push({name: href, mimeType: mime.getType(href)});
element.setAttribute("href", `/_file/${path}`);
context.files.push(fileReference(href, sourcePath));
element.setAttribute("href", relativeUrl(sourcePath, `/_file/${path}`));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rewriting <link href> was not tested; now tested in input/build/files/

}
}
return isSingleElement(document) ? String(document) : `<span>${document}</span>`;
Expand Down
12 changes: 6 additions & 6 deletions src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,15 +207,15 @@ function footer(path: string, options?: Pick<Config, "pages" | "title">): string
: `<nav>${
!link.prev
? ""
: `<a rel="prev" href="${escapeDoubleQuoted(prettyPath(link.prev.path))}"><span>${escapeData(
link.prev.name
)}</span></a>`
: `<a rel="prev" href="${escapeDoubleQuoted(
relativeUrl(path, prettyPath(link.prev.path))
)}"><span>${escapeData(link.prev.name)}</span></a>`
}${
!link.next
? ""
: `<a rel="next" href="${escapeDoubleQuoted(prettyPath(link.next.path))}"><span>${escapeData(
link.next.name
)}</span></a>`
: `<a rel="next" href="${escapeDoubleQuoted(
relativeUrl(path, prettyPath(link.next.path))
)}"><span>${escapeData(link.next.name)}</span></a>`
}</nav>\n`
}<div>© ${new Date().getUTCFullYear()} Observable, Inc.</div>
</footer>`;
Expand Down
1 change: 1 addition & 0 deletions test/input/build/files/custom-styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a { color: pink; }
2 changes: 2 additions & 0 deletions test/input/build/files/file-top.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Hello,world
1,2
18 changes: 18 additions & 0 deletions test/input/build/files/files.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<link rel=stylesheet href="custom-styles.css" />
<link rel=stylesheet href="subsection/additional-styles.css" />

```js
fetch("./file-top.csv")
```

```js
fetch("./subsection/file-sub.csv")
```

```js
FileAttachment("file-top.csv")
```

```js
FileAttachment("subsection/file-sub.csv")
```
1 change: 1 addition & 0 deletions test/input/build/files/subsection/additional-styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a { color: green; }
2 changes: 2 additions & 0 deletions test/input/build/files/subsection/file-sub.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Bonjour,monde
1,2
18 changes: 18 additions & 0 deletions test/input/build/files/subsection/subfiles.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<link rel=stylesheet href="../custom-styles.css" />
<link rel=stylesheet href="additional-styles.css" />

```js
fetch("../file-top.csv")
```

```js
fetch("./file-sub.csv")
```

```js
FileAttachment("../file-top.csv")
```

```js
FileAttachment("file-sub.csv")
```
2 changes: 1 addition & 1 deletion test/output/build/config/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ <h1 id="index" tabindex="-1"><a class="observablehq-header-anchor" href="#index"
</ul>
</main>
<footer id="observablehq-footer">
<nav><a rel="next" href="/one"><span>One&#60;Two</span></a></nav>
<nav><a rel="next" href="./one"><span>One&#60;Two</span></a></nav>
<div>© 2023 Observable, Inc.</div>
</footer>
</div>
2 changes: 1 addition & 1 deletion test/output/build/config/one.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
<h1 id="one" tabindex="-1"><a class="observablehq-header-anchor" href="#one">One</a></h1>
</main>
<footer id="observablehq-footer">
<nav><a rel="prev" href="/"><span>Index</span></a><a rel="next" href="/sub/two"><span>Two</span></a></nav>
<nav><a rel="prev" href="./"><span>Index</span></a><a rel="next" href="./sub/two"><span>Two</span></a></nav>
<div>© 2023 Observable, Inc.</div>
</footer>
</div>
2 changes: 1 addition & 1 deletion test/output/build/config/sub/two.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
<h1 id="two" tabindex="-1"><a class="observablehq-header-anchor" href="#two">Two</a></h1>
</main>
<footer id="observablehq-footer">
<nav><a rel="prev" href="/one"><span>One&#60;Two</span></a></nav>
<nav><a rel="prev" href="../one"><span>One&#60;Two</span></a></nav>
<div>© 2023 Observable, Inc.</div>
</footer>
</div>
1 change: 1 addition & 0 deletions test/output/build/files/_file/custom-styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a { color: pink; }
2 changes: 2 additions & 0 deletions test/output/build/files/_file/file-top.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Hello,world
1,2
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a { color: green; }
2 changes: 2 additions & 0 deletions test/output/build/files/_file/subsection/file-sub.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Bonjour,monde
1,2
60 changes: 60 additions & 0 deletions test/output/build/files/files.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<!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="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&display=swap">
<link rel="stylesheet" type="text/css" href="./_observablehq/style.css">
<link rel="modulepreload" href="./_observablehq/runtime.js">
<script type="module">

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

define({id: "a7808707", inputs: ["display"], files: [{"name":"./file-top.csv","mimeType":"text/csv","path":"./_file/file-top.csv"}], body: (display) => {
display((
fetch("./_file/file-top.csv")
))
}});
define({id: "03b99abc", inputs: ["display"], files: [{"name":"./subsection/file-sub.csv","mimeType":"text/csv","path":"./_file/subsection/file-sub.csv"}], body: (display) => {
display((
fetch("./_file/subsection/file-sub.csv")
))
}});
define({id: "10037545", inputs: ["FileAttachment","display"], files: [{"name":"file-top.csv","mimeType":"text/csv","path":"./_file/file-top.csv"}], body: (FileAttachment,display) => {
display((
FileAttachment("file-top.csv")
))
}});
define({id: "453a8147", inputs: ["FileAttachment","display"], files: [{"name":"subsection/file-sub.csv","mimeType":"text/csv","path":"./_file/subsection/file-sub.csv"}], body: (FileAttachment,display) => {
display((
FileAttachment("subsection/file-sub.csv")
))
}});

</script>
<input id="observablehq-sidebar-toggle" type="checkbox">
<nav id="observablehq-sidebar">
<ol>
<li class="observablehq-link observablehq-link-active"><a href="./files">Untitled</a></li>
<li class="observablehq-link"><a href="./subsection/subfiles">Untitled</a></li>
</ol>
</nav>
<script>{
const toggle = document.querySelector("#observablehq-sidebar-toggle");
const initialState = localStorage.getItem("observablehq-sidebar");
if (initialState) toggle.checked = initialState === "true";
else toggle.indeterminate = true;
}</script>
<div id="observablehq-center">
<main id="observablehq-main" class="observablehq">
<span><link rel="stylesheet" href="./_file/custom-styles.css">
<link rel="stylesheet" href="./_file/subsection/additional-styles.css">
</span><div id="cell-a7808707" class="observablehq observablehq--block"></div>
<div id="cell-03b99abc" class="observablehq observablehq--block"></div>
<div id="cell-10037545" class="observablehq observablehq--block"></div>
<div id="cell-453a8147" class="observablehq observablehq--block"></div>
</main>
<footer id="observablehq-footer">
<nav><a rel="next" href="./subsection/subfiles"><span>Untitled</span></a></nav>
<div>© 2023 Observable, Inc.</div>
</footer>
</div>
60 changes: 60 additions & 0 deletions test/output/build/files/subsection/subfiles.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<!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="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&display=swap">
<link rel="stylesheet" type="text/css" href="../_observablehq/style.css">
<link rel="modulepreload" href="../_observablehq/runtime.js">
<script type="module">

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

define({id: "62f1fd0c", inputs: ["display"], files: [{"name":"../file-top.csv","mimeType":"text/csv","path":"../_file/file-top.csv"}], body: (display) => {
display((
fetch("../_file/file-top.csv")
))
}});
define({id: "94d347ec", inputs: ["display"], files: [{"name":"./file-sub.csv","mimeType":"text/csv","path":"../_file/subsection/file-sub.csv"}], body: (display) => {
display((
fetch("../_file/subsection/file-sub.csv")
))
}});
define({id: "ef9a31ef", inputs: ["FileAttachment","display"], files: [{"name":"../file-top.csv","mimeType":"text/csv","path":"../_file/file-top.csv"}], body: (FileAttachment,display) => {
display((
FileAttachment("../file-top.csv")
))
}});
define({id: "834ecf9f", inputs: ["FileAttachment","display"], files: [{"name":"file-sub.csv","mimeType":"text/csv","path":"../_file/subsection/file-sub.csv"}], body: (FileAttachment,display) => {
display((
FileAttachment("file-sub.csv")
))
}});

</script>
<input id="observablehq-sidebar-toggle" type="checkbox">
<nav id="observablehq-sidebar">
<ol>
<li class="observablehq-link"><a href="../files">Untitled</a></li>
<li class="observablehq-link observablehq-link-active"><a href="./subfiles">Untitled</a></li>
</ol>
</nav>
<script>{
const toggle = document.querySelector("#observablehq-sidebar-toggle");
const initialState = localStorage.getItem("observablehq-sidebar");
if (initialState) toggle.checked = initialState === "true";
else toggle.indeterminate = true;
}</script>
<div id="observablehq-center">
<main id="observablehq-main" class="observablehq">
<span><link rel="stylesheet" href="../_file/custom-styles.css">
<link rel="stylesheet" href="../_file/subsection/additional-styles.css">
</span><div id="cell-62f1fd0c" class="observablehq observablehq--block"></div>
<div id="cell-94d347ec" class="observablehq observablehq--block"></div>
<div id="cell-ef9a31ef" class="observablehq observablehq--block"></div>
<div id="cell-834ecf9f" class="observablehq observablehq--block"></div>
</main>
<footer id="observablehq-footer">
<nav><a rel="prev" href="../files"><span>Untitled</span></a></nav>
<div>© 2023 Observable, Inc.</div>
</footer>
</div>
6 changes: 3 additions & 3 deletions test/output/build/multi/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

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

define({id: "1bcb5df5", inputs: ["FileAttachment"], outputs: ["f1"], files: [{"name":"file1.csv","mimeType":"text/csv"}], body: (FileAttachment) => {
define({id: "1bcb5df5", inputs: ["FileAttachment"], outputs: ["f1"], files: [{"name":"file1.csv","mimeType":"text/csv","path":"./_file/file1.csv"}], body: (FileAttachment) => {
const f1 = FileAttachment("file1.csv").csv();
return {f1};
}});
Expand All @@ -19,7 +19,7 @@
Input.table(f1)
))
}});
define({id: "aaa5c01d", outputs: ["f2"], files: [{"name":"./file2.csv","mimeType":"text/csv"}], body: () => {
define({id: "aaa5c01d", outputs: ["f2"], files: [{"name":"./file2.csv","mimeType":"text/csv","path":"./_file/file2.csv"}], body: () => {
const f2 = fetch("./_file/file2.csv");
return {f2};
}});
Expand All @@ -46,7 +46,7 @@ <h1 id="multi-test" tabindex="-1"><a class="observablehq-header-anchor" href="#m
<div id="cell-aaa5c01d" class="observablehq observablehq--block"></div>
</main>
<footer id="observablehq-footer">
<nav><a rel="prev" href="/subsection/"><span>Sub-Section</span></a></nav>
<nav><a rel="prev" href="./subsection/"><span>Sub-Section</span></a></nav>
<div>© 2023 Observable, Inc.</div>
</footer>
</div>
2 changes: 1 addition & 1 deletion test/output/build/multi/subsection/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ <h1 id="sub-section" tabindex="-1"><a class="observablehq-header-anchor" href="#
<p>This is a sub-section of the multi-section page.</p>
</main>
<footer id="observablehq-footer">
<nav><a rel="next" href="/"><span>Multi test</span></a></nav>
<nav><a rel="next" href="../"><span>Multi test</span></a></nav>
<div>© 2023 Observable, Inc.</div>
</footer>
</div>
2 changes: 1 addition & 1 deletion test/output/build/simple/simple.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

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

define({id: "115586ff", inputs: ["FileAttachment"], outputs: ["result"], files: [{"name":"data.txt","mimeType":"text/plain"}], body: (FileAttachment) => {
define({id: "115586ff", inputs: ["FileAttachment"], outputs: ["result"], files: [{"name":"data.txt","mimeType":"text/plain","path":"./_file/data.txt"}], body: (FileAttachment) => {
let result = FileAttachment("data.txt").text();
return {result};
}});
Expand Down
Loading