Skip to content

Commit 09c603e

Browse files
committed
registerFile
1 parent 2c037b7 commit 09c603e

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/runtime/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export * from "./stdlib/index.js";
1111
export type * from "./stdlib/databaseClient.js";
1212
export type * from "./stdlib/fileAttachment.js";
1313
export {DatabaseClient} from "./stdlib/databaseClient.js";
14-
export {FileAttachment} from "./stdlib/fileAttachment.js";
14+
export {FileAttachment, registerFile} from "./stdlib/fileAttachment.js";
1515

1616
export const runtime = Object.assign(new Runtime({...library, __ojs_runtime: () => runtime}), {fileAttachments});
1717
export const main = (runtime as typeof runtime & {main: Module}).main = runtime.module();

src/runtime/stdlib/fileAttachment.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ export interface FileAttachment {
4747
html(): Promise<Document>;
4848
}
4949

50+
// TODO Enforce that files have been registered; throw error if not found.
5051
export const FileAttachment = (name: string, base = document.baseURI): FileAttachment => {
5152
const href = new URL(name, base).href;
5253
let file = files.get(href);
@@ -57,6 +58,31 @@ export const FileAttachment = (name: string, base = document.baseURI): FileAttac
5758
return file;
5859
};
5960

61+
export interface FileInfo {
62+
path: string;
63+
mimeType?: string;
64+
lastModified?: number;
65+
size?: number;
66+
}
67+
68+
export function registerFile(name: string, info: FileInfo, base: string | URL = location.href) {
69+
const href = new URL(name, base).href;
70+
if (info == null) {
71+
files.delete(href);
72+
} else {
73+
const {path, mimeType, lastModified, size} = info;
74+
const file = new FileAttachmentImpl(
75+
new URL(path, base).href,
76+
name.split("/").pop()!,
77+
mimeType,
78+
lastModified,
79+
size
80+
);
81+
files.set(href, file);
82+
return file;
83+
}
84+
}
85+
6086
async function fetchFile(file: FileAttachment): Promise<Response> {
6187
const response = await fetch(file.href);
6288
if (!response.ok) throw new Error(`Unable to load file: ${file.name}`);

0 commit comments

Comments
 (0)