-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathlesson-files.ts
More file actions
177 lines (129 loc) · 4.2 KB
/
lesson-files.ts
File metadata and controls
177 lines (129 loc) · 4.2 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import type { Files, FilesRefList, Lesson } from '@tutorialkit/types';
import { newTask, type Task } from './tasks.js';
import { wait } from './utils/promises.js';
type InvalidationResult =
| {
type: 'template' | 'files' | 'solution';
files: Files;
}
| { type: 'none' };
export class LessonFilesFetcher {
private _map = new Map<string, Files>();
private _templateLoadTask?: Task<Files>;
private _templateLoaded: string | undefined;
constructor(private _basePathname: string = '/') {
if (!this._basePathname.endsWith('/')) {
this._basePathname = this._basePathname + '/';
}
}
async invalidate(filesRef: string): Promise<InvalidationResult> {
if (!this._map.has(filesRef)) {
return { type: 'none' };
}
const type = getTypeFromFilesRef(filesRef);
let files: Files;
if (this._templateLoaded === filesRef) {
files = await this._fetchTemplate(filesRef).promise;
} else {
files = await this._fetchFiles(filesRef);
}
return {
type,
files,
};
}
async getLessonTemplate(lesson: Lesson): Promise<Files> {
const templateName = typeof lesson.data.template === 'string' ? lesson.data.template : lesson.data.template?.name;
const templatePathname = `template-${templateName}.json`;
if (this._map.has(templatePathname)) {
return this._map.get(templatePathname)!;
}
if (this._templateLoadTask && this._templateLoaded === templatePathname) {
return this._templateLoadTask.promise;
}
const task = this._fetchTemplate(templatePathname);
return task.promise;
}
getLessonFiles(lesson: Lesson): Promise<Files> {
return this._getFilesFromFilesRefList(lesson.files);
}
getLessonSolution(lesson: Lesson): Promise<Files> {
return this._getFilesFromFilesRefList(lesson.solution);
}
private _fetchTemplate(templatePathname: string) {
this._templateLoadTask?.cancel();
const task = newTask(async (signal) => {
const response = await fetch(`${this._basePathname}${templatePathname}`, { signal });
if (!response.ok) {
throw new Error(`Failed to fetch: status ${response.status}`);
}
const body = convertToFiles(await response.json());
this._map.set(templatePathname, body);
signal.throwIfAborted();
return body;
});
this._templateLoadTask = task;
this._templateLoaded = templatePathname;
return task;
}
private async _getFilesFromFilesRefList(filesRefList: FilesRefList): Promise<Files> {
// the ref does not have any content
if (filesRefList[1].length === 0) {
return {};
}
const pathname = filesRefList[0];
if (this._map.has(pathname)) {
return this._map.get(pathname)!;
}
const promise = this._fetchFiles(pathname);
return promise;
}
private async _fetchFiles(pathname: string): Promise<Files> {
let retry = 2;
while (true) {
try {
const response = await fetch(`${this._basePathname}${pathname}`);
if (!response.ok) {
throw new Error(`Failed to fetch ${pathname}: ${response.status} ${response.statusText}`);
}
const body = convertToFiles(await response.json());
this._map.set(pathname, body);
return body;
} catch (error) {
if (retry <= 0) {
console.error(`Failed to fetch ${pathname} after 3 attempts.`);
console.error(error);
return {};
}
}
retry -= 1;
await wait(1000);
}
}
}
function convertToFiles(json: Record<string, string | { base64: string }>): Files {
const result: Files = {};
if (typeof json !== 'object') {
return result;
}
for (const property in json) {
const value = json[property];
let transformedValue;
if (typeof value === 'object') {
transformedValue = Uint8Array.from(atob(value.base64), (char) => char.charCodeAt(0));
} else {
transformedValue = value;
}
result[property] = transformedValue;
}
return result;
}
function getTypeFromFilesRef(filesRef: string): 'template' | 'files' | 'solution' {
if (filesRef.startsWith('template-')) {
return 'template';
}
if (filesRef.endsWith('files.json')) {
return 'files';
}
return 'solution';
}