36 lines
1.4 KiB
TypeScript
36 lines
1.4 KiB
TypeScript
import { type Project, clone, validateProject } from '../engine/schema.ts';
|
|
import { defaultProject } from '../engine/templates.ts';
|
|
import { loadDraft } from './persistence.ts';
|
|
|
|
export interface EditorStartupOptions { initialProject?: Project; browserOnly?: boolean; }
|
|
export async function loadEditorProject(
|
|
options: EditorStartupOptions = {},
|
|
dependencies: { request: typeof fetch; draft: () => Promise<Project | null> } = { request: fetch, draft: loadDraft },
|
|
) {
|
|
if (!options.browserOnly) {
|
|
try {
|
|
const response = await dependencies.request('/api/status', { signal: AbortSignal.timeout(1800) });
|
|
if (response.ok) {
|
|
const status = await response.json();
|
|
if (status.forma) {
|
|
const response = await dependencies.request('/api/project');
|
|
if (!response.ok) throw Error('Project unavailable');
|
|
const { project } = await response.json();
|
|
validateProject(project);
|
|
return { project: project as Project, status, restored: false };
|
|
}
|
|
}
|
|
} catch {}
|
|
}
|
|
try {
|
|
const project = await dependencies.draft();
|
|
if (project) {
|
|
validateProject(project);
|
|
return { project, status: null, restored: true };
|
|
}
|
|
} catch {}
|
|
const project = clone(options.initialProject || defaultProject());
|
|
validateProject(project);
|
|
return { project, status: null, restored: false };
|
|
}
|