diff --git a/README.md b/README.md index 76022a2..5904765 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,8 @@

+SketchForge projects can be saved as native editable `.skf` packages and opened later on another browser or device. Unlike STL/OBJ mesh exports, `.skf` preserves shapes, sketches, groups and boolean operands, exact CAD data where available, imported sources, workspace settings, and undo/redo history. See [the `.skf` project format documentation](docs/SKF_PROJECT_FORMAT.md). + ![SketchForge editor showing a selected box on the workplane](docs/media/sketchforge-editor-v0.6.png) ## Why SketchForge diff --git a/apps/web/src/app/api/local-download/route.ts b/apps/web/src/app/api/local-download/route.ts index fd09f49..84360ae 100644 --- a/apps/web/src/app/api/local-download/route.ts +++ b/apps/web/src/app/api/local-download/route.ts @@ -5,7 +5,8 @@ import { NextResponse } from "next/server"; export const revalidate = false; const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]); -const MAX_LOCAL_DOWNLOAD_BYTES = 25 * 1024 * 1024; +const MAX_TEXT_DOWNLOAD_BYTES = 25 * 1024 * 1024; +const MAX_BINARY_DOWNLOAD_BYTES = 512 * 1024 * 1024; function safeFileName(filename: string) { const base = path.basename(filename).replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_").trim(); @@ -40,28 +41,51 @@ export async function POST(request: Request) { return NextResponse.json({ error: "Local folder downloads are only available from this localhost app" }, { status: 403 }); } - const body = (await request.json()) as { content?: unknown; filename?: unknown; folder?: unknown }; - if (typeof body.content !== "string" || typeof body.filename !== "string" || typeof body.folder !== "string") { - return NextResponse.json({ error: "Invalid download request" }, { status: 400 }); + const contentType = request.headers.get("content-type") ?? ""; + let filename: string; + let folder: string; + let content: string | Buffer; + if (contentType.toLowerCase().startsWith("multipart/form-data")) { + const formData = await request.formData(); + const file = formData.get("file"); + const requestedName = formData.get("filename"); + const requestedFolder = formData.get("folder"); + if (!(file instanceof Blob) || typeof requestedName !== "string" || typeof requestedFolder !== "string") { + return NextResponse.json({ error: "Invalid binary download request" }, { status: 400 }); + } + if (file.size > MAX_BINARY_DOWNLOAD_BYTES) { + return NextResponse.json({ error: "File is too large for local folder download" }, { status: 413 }); + } + filename = requestedName; + folder = requestedFolder; + content = Buffer.from(await file.arrayBuffer()); + } else { + const body = (await request.json()) as { content?: unknown; filename?: unknown; folder?: unknown }; + if (typeof body.content !== "string" || typeof body.filename !== "string" || typeof body.folder !== "string") { + return NextResponse.json({ error: "Invalid download request" }, { status: 400 }); + } + if (Buffer.byteLength(body.content, "utf8") > MAX_TEXT_DOWNLOAD_BYTES) { + return NextResponse.json({ error: "File is too large for local folder download" }, { status: 413 }); + } + filename = body.filename; + folder = body.folder; + content = body.content; } - if (Buffer.byteLength(body.content, "utf8") > MAX_LOCAL_DOWNLOAD_BYTES) { - return NextResponse.json({ error: "File is too large for local folder download" }, { status: 413 }); - } - - const trimmedFolder = body.folder.trim(); + const trimmedFolder = folder.trim(); if (!trimmedFolder) { return NextResponse.json({ error: "Choose a folder first" }, { status: 400 }); } const targetDirectory = path.resolve(path.isAbsolute(trimmedFolder) ? trimmedFolder : path.join(process.cwd(), trimmedFolder)); await fs.mkdir(targetDirectory, { recursive: true }); - const targetPath = path.resolve(targetDirectory, safeFileName(body.filename)); + const targetPath = path.resolve(targetDirectory, safeFileName(filename)); const relativeTarget = path.relative(targetDirectory, targetPath); if (relativeTarget.startsWith("..") || path.isAbsolute(relativeTarget)) { return NextResponse.json({ error: "Invalid file path" }, { status: 400 }); } - await fs.writeFile(targetPath, body.content, "utf8"); + if (typeof content === "string") await fs.writeFile(targetPath, content, "utf8"); + else await fs.writeFile(targetPath, content); return NextResponse.json({ path: targetPath }); } catch (error) { diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 4f76b80..20a2bdf 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -1965,6 +1965,441 @@ button { background: #eef8fc; } +.top-action-heading { + display: grid; + gap: 2px; +} + +.top-action-heading > span { + color: #6b7f91; + font-size: 11px; + font-weight: 700; +} + +.top-action-panel.export-action-panel, +.top-action-panel.import-action-panel { + width: min(440px, calc(100vw - 28px)); + overflow: hidden; + border-color: #d8e1e8; + border-radius: 12px; + box-shadow: 0 18px 55px rgba(19, 37, 55, 0.24); +} + +.export-action-panel header, +.import-action-panel header { + height: 52px; + padding: 0 12px 0 15px; + background: #fff; +} + +.import-action-panel .top-action-body { + padding: 14px; + background: #f7f9fb; +} + +.export-dialog-body { + display: grid; + max-height: calc(100vh - var(--editor-toolbar-height) - 96px); + overflow-y: auto; + background: #f7f9fb; +} + +.export-setting-section { + display: grid; + gap: 8px; + padding: 12px 14px; + background: #fff; + border-bottom: 1px solid #e5ebf0; +} + +.export-file-section { + grid-template-columns: 72px minmax(0, 1fr); + align-items: center; +} + +.export-file-section label, +.export-section-heading strong { + color: #20384d; + font-size: 13px; + font-weight: 800; +} + +.export-file-input-wrap { + display: flex; + min-width: 0; + overflow: hidden; + background: #f7f9fb; + border: 1px solid #d9e2e9; + border-radius: 6px; +} + +.export-file-input-wrap:focus-within { + background: #fff; + border-color: #10a8d0; + box-shadow: 0 0 0 2px rgba(16, 168, 208, 0.12); +} + +.export-file-input { + min-width: 0; + flex: 1; + height: 32px; + padding: 0 2px 0 10px; + color: #263e52; + font: inherit; + font-size: 12px; + font-weight: 750; + background: transparent; + border: 0; + outline: 0; +} + +.export-file-input-wrap > span { + display: inline-flex; + flex: none; + align-items: center; + padding: 0 9px 0 4px; + color: #6d8090; + font-size: 11px; + font-weight: 800; + text-transform: lowercase; +} + +.export-section-heading { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 14px; +} + +.export-section-heading > div { + display: grid; + gap: 3px; +} + +.export-section-heading > div > span { + color: #718494; + font-size: 11px; + font-weight: 650; +} + +.export-scope-badge { + flex: none; + padding: 4px 8px; + color: #137897; + font-size: 10px; + font-weight: 850; + text-transform: uppercase; + background: #eaf9fd; + border: 1px solid #c5edf7; + border-radius: 999px; +} + +.export-format-slider { + position: relative; + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + height: 38px; + padding: 3px; + overflow: hidden; + background: #edf2f5; + border: 1px solid #dbe4eb; + border-radius: 8px; +} + +.export-format-slider::before { + position: absolute; + top: 3px; + bottom: 3px; + left: 3px; + width: calc((100% - 6px) / 5); + content: ""; + background: #fff; + border: 1px solid #a9dce9; + border-radius: 6px; + box-shadow: 0 2px 7px rgba(27, 65, 89, 0.12); + transition: transform 180ms ease; +} + +.export-format-slider[data-format="obj"]::before { + transform: translateX(100%); +} + +.export-format-slider[data-format="step"]::before { + transform: translateX(200%); +} + +.export-format-slider[data-format="svg"]::before { + transform: translateX(300%); +} + +.export-format-slider[data-format="skf"]::before { + transform: translateX(400%); +} + +.export-format-slider button { + position: relative; + z-index: 1; + min-width: 0; + padding: 0 5px; + color: #6f8291; + font-size: 11px; + font-weight: 850; + letter-spacing: 0.02em; + background: transparent; + border: 0; + border-radius: 6px; + cursor: pointer; + transition: color 160ms ease; +} + +.export-format-slider button:hover { + color: #22546a; +} + +.export-format-slider button[aria-checked="true"] { + color: #087f9f; +} + +.skf-history-section { + gap: 9px; +} + +.skf-history-range-control { + position: relative; + height: 26px; +} + +.skf-history-range-control::before, +.skf-history-range-control::after { + position: absolute; + top: 10px; + left: 9px; + height: 6px; + content: ""; + border-radius: 999px; +} + +.skf-history-range-control::before { + right: 9px; + background: #dbe5eb; + box-shadow: inset 0 1px 2px rgba(40, 65, 82, 0.12); +} + +.skf-history-range-control::after { + width: 0; + background: linear-gradient(90deg, #22b9dc, #079bc2); + transition: width 140ms ease; +} + +.skf-history-range-control[data-limit="100"]::after { + width: calc(33.333333% - 6px); +} + +.skf-history-range-control[data-limit="50"]::after { + width: calc(66.666667% - 12px); +} + +.skf-history-range-control[data-limit="30"]::after { + width: calc(100% - 18px); +} + +.skf-history-range { + position: absolute; + inset: 0; + z-index: 1; + width: 100%; + height: 26px; + margin: 0; + appearance: none; + background: transparent; + border: 0; + cursor: grab; +} + +.skf-history-range:active { + cursor: grabbing; +} + +.skf-history-range:focus { + outline: 0; +} + +.skf-history-range::-webkit-slider-runnable-track { + height: 6px; + background: transparent; +} + +.skf-history-range::-webkit-slider-thumb { + width: 18px; + height: 18px; + margin-top: -6px; + appearance: none; + background: #fff; + border: 2px solid #0ba4ca; + border-radius: 50%; + box-shadow: 0 2px 6px rgba(22, 82, 108, 0.25); +} + +.skf-history-range::-moz-range-track { + height: 6px; + background: transparent; +} + +.skf-history-range::-moz-range-thumb { + width: 14px; + height: 14px; + background: #fff; + border: 2px solid #0ba4ca; + border-radius: 50%; + box-shadow: 0 2px 6px rgba(22, 82, 108, 0.25); +} + +.skf-history-range:focus-visible::-webkit-slider-thumb { + box-shadow: 0 0 0 4px rgba(11, 164, 202, 0.17), 0 2px 6px rgba(22, 82, 108, 0.25); +} + +.skf-history-range:focus-visible::-moz-range-thumb { + box-shadow: 0 0 0 4px rgba(11, 164, 202, 0.17), 0 2px 6px rgba(22, 82, 108, 0.25); +} + +.skf-history-range-labels { + position: relative; + height: 14px; + margin-top: -3px; +} + +.skf-history-range-labels span { + position: absolute; + top: 0; + color: #718494; + font-size: 10px; + font-weight: 750; + transform: translateX(-50%); + transition: color 140ms ease; +} + +.skf-history-range-labels span:first-child { + left: 0; + transform: none; +} + +.skf-history-range-labels span:nth-child(2) { + left: calc(33.333333% + 3px); +} + +.skf-history-range-labels span:nth-child(3) { + left: calc(66.666667% - 3px); +} + +.skf-history-range-labels span:last-child { + right: 0; + transform: none; +} + +.skf-history-range-labels span.active { + color: #087f9f; + font-weight: 850; +} + +.export-format-summary { + display: grid; + gap: 5px; + margin: 10px 14px; + padding: 9px 11px; + background: #eef4f7; + border: 1px solid #dde7ed; + border-radius: 7px; +} + +.export-format-summary > div { + display: flex; + align-items: baseline; + gap: 8px; +} + +.export-format-summary strong { + color: #1f3c52; + font-size: 12px; + font-weight: 850; +} + +.export-format-summary span, +.export-format-summary p { + margin: 0; + color: #627789; + font-size: 11px; + font-weight: 700; + line-height: 1.4; +} + +.export-dialog-footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 10px; + padding: 10px 14px 12px; + background: #fff; + border-top: 1px solid #e2e9ee; +} + +.export-dialog-footer > div { + display: flex; + justify-content: flex-end; + gap: 9px; +} + +.export-dialog-footer button { + display: inline-flex; + min-width: 78px; + min-height: 34px; + align-items: center; + justify-content: center; + gap: 7px; + padding: 0 13px; + border-radius: 6px; + cursor: pointer; + font-size: 12px; + font-weight: 850; +} + +.export-dialog-footer .export-primary-button { + min-width: 118px; + color: #fff; + background: linear-gradient(180deg, #14b4dc, #0799c1); + border: 1px solid #078daf; + box-shadow: 0 5px 14px rgba(4, 145, 183, 0.22); +} + +.export-dialog-footer .export-primary-button:hover:not(:disabled) { + background: linear-gradient(180deg, #0eadd4, #058db2); +} + +.export-dialog-footer .export-primary-button:disabled { + cursor: not-allowed; + opacity: 0.55; +} + +.export-primary-button svg { + width: 16px; + height: 16px; +} + +@media (max-width: 560px) { + .top-action-panel.export-action-panel, + .top-action-panel.import-action-panel { + right: 10px; + width: calc(100vw - 20px); + } + + .export-file-section { + grid-template-columns: 1fr; + } + + .export-dialog-footer { + align-items: flex-end; + } +} + .top-action-body { display: grid; gap: 10px; @@ -1999,6 +2434,65 @@ button { background: #eef8fc; } +.top-action-body .open-skf-project-button { + display: grid; + grid-template-columns: 38px minmax(0, 1fr); + min-height: 66px; + justify-content: stretch; + padding: 10px 12px; + color: #173b5a; + background: #fff; + border-color: #cfe2eb; + border-radius: 8px; + text-align: left; +} + +.open-skf-project-button > span:last-child { + display: grid; + gap: 3px; +} + +.open-skf-project-button strong, +.open-skf-project-button small { + display: block; +} + +.open-skf-project-button small { + color: #667d8e; + font-size: 11px; + font-weight: 700; + line-height: 1.35; +} + +.open-skf-project-icon { + display: grid; + width: 34px; + height: 34px; + place-items: center; + color: #087f9f; + background: #eaf9fd; + border: 1px solid #c5edf7; + border-radius: 8px; +} + +.import-kind-divider { + display: flex; + align-items: center; + gap: 9px; + color: #7a8c9a; + font-size: 10px; + font-weight: 800; + text-transform: uppercase; +} + +.import-kind-divider::before, +.import-kind-divider::after { + height: 1px; + flex: 1; + content: ""; + background: #dfe7ed; +} + .top-action-body button svg, .top-action-body button .vector-toolbar-sprite-icon, .top-action-body button .toolbar-command-icon { @@ -2013,16 +2507,16 @@ button { align-content: center; justify-items: center; gap: 8px; - padding: 17px 14px; + padding: 20px 14px; color: #244057; - background: linear-gradient(180deg, rgba(255, 255, 255, 0.86), rgba(244, 248, 251, 0.96)); - border: 1.5px dashed rgba(93, 124, 150, 0.62); - border-radius: 5px; + background: #fff; + border: 1.5px dashed #b8cbd8; + border-radius: 8px; text-align: center; } .top-action-body .import-drop-zone:hover { - background: #fff; + background: #fafeff; border-color: rgba(0, 159, 227, 0.76); box-shadow: inset 0 0 0 1px rgba(0, 159, 227, 0.12), 0 4px 14px rgba(30, 50, 70, 0.1); } diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index e1fca10..99aedb4 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -5,9 +5,11 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor"; import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory"; import { createLocalId } from "@/lib/localIds"; +import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets"; +import { importSkfProject } from "@/lib/skfProject"; import { importExtensionSupported } from "@/lib/stlImport"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; -import type { GridSize, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; +import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; type AppView = "dashboard" | "editor"; type ViewMode = "grid" | "list"; @@ -26,6 +28,7 @@ type DashboardProject = { revision?: number; workspace?: WorkplaneWorkspaceSettings; snapGrid?: GridSize; + placementElevation?: number; }; type StoredDashboardProject = Partial & { @@ -37,6 +40,7 @@ type ProjectShapeCacheEntry = { shapes: WorkplaneShape[]; history: EditorHistoryEntry[]; historyIndex: number; + assets: ProjectAsset[]; }; type ProjectShapeRecord = { @@ -45,6 +49,7 @@ type ProjectShapeRecord = { shapes: WorkplaneShape[]; history?: EditorHistoryEntry[]; historyIndex?: number; + assets?: ProjectAsset[]; updatedAt: number; }; @@ -69,6 +74,7 @@ function projectShapeCacheEntry( shapes: WorkplaneShape[], history?: EditorHistoryEntry[], historyIndex?: number, + assets: ProjectAsset[] = [], ): ProjectShapeCacheEntry { const hydrated = hydrateEditorHistoryState(shapes, history, historyIndex); return { @@ -76,6 +82,7 @@ function projectShapeCacheEntry( shapes: hydrated.entries[hydrated.index]?.shapes ?? shapes, history: hydrated.entries, historyIndex: hydrated.index, + assets: dedupeProjectAssets(assets), }; } @@ -187,6 +194,7 @@ function readStoredProjects() { revision, workspace: normalizeWorkspaceSettings(project.workspace), snapGrid: normalizeSnapGrid(project.snapGrid), + placementElevation: typeof project.placementElevation === "number" && Number.isFinite(project.placementElevation) ? project.placementElevation : 0, }; }); return { projects, legacyShapes }; @@ -217,6 +225,7 @@ function mergeProjectForStorage(project: DashboardProject, storedProject?: Dashb updatedAt: Math.max(project.updatedAt, storedProject.updatedAt), workspace: project.workspace ?? storedProject.workspace, snapGrid: project.snapGrid ?? storedProject.snapGrid, + placementElevation: project.placementElevation ?? storedProject.placementElevation, }; } @@ -233,6 +242,7 @@ function projectForStorage(project: DashboardProject): DashboardProject { revision: project.revision, workspace: normalizeWorkspaceSettings(project.workspace), snapGrid: normalizeSnapGrid(project.snapGrid), + placementElevation: typeof project.placementElevation === "number" && Number.isFinite(project.placementElevation) ? project.placementElevation : 0, }; } @@ -254,6 +264,7 @@ function newProject(name: string, index: number, shapeCount = 0): DashboardProje revision: now, workspace: DEFAULT_WORKPLANE_WORKSPACE, snapGrid: DEFAULT_SNAP_GRID, + placementElevation: 0, }; } @@ -370,7 +381,7 @@ export default function Home() { .then((record) => { if (canceled) return; const revision = activeProject.revision ?? record?.revision ?? Date.now(); - const entry = projectShapeCacheEntry(revision, record?.shapes ?? [], record?.history, record?.historyIndex); + const entry = projectShapeCacheEntry(revision, record?.shapes ?? [], record?.history, record?.historyIndex, record?.assets); setProjectShapesById((current) => ({ ...current, [activeProjectId]: entry, @@ -471,10 +482,11 @@ export default function Home() { shapes: WorkplaneShape[]; history: EditorHistoryEntry[]; historyIndex: number; + assets: ProjectAsset[]; }) => { const revision = Math.max(Date.now(), nextProjectRevisionRef.current + 1); nextProjectRevisionRef.current = revision; - const entry = projectShapeCacheEntry(revision, snapshot.shapes, snapshot.history, snapshot.historyIndex); + const entry = projectShapeCacheEntry(revision, snapshot.shapes, snapshot.history, snapshot.historyIndex, snapshot.assets); setProjectShapesById((current) => { const existing = current[snapshot.projectId]; if (existing && existing.revision > revision) { @@ -512,25 +524,29 @@ export default function Home() { }); }, []); - const updateProjectWorkspace = useCallback((snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => { + const updateProjectWorkspace = useCallback((snapshot: { projectId: string; workspace: WorkplaneWorkspaceSettings; snap: GridSize; placementElevation?: number }) => { const version = Date.now(); const workspace = normalizeWorkspaceSettings(snapshot.workspace); const snapGrid = normalizeSnapGrid(snapshot.snap); - const nextFingerprint = workplaneSettingsFingerprint(workspace, snapGrid); + const placementElevation = typeof snapshot.placementElevation === "number" && Number.isFinite(snapshot.placementElevation) + ? snapshot.placementElevation + : 0; + const nextFingerprint = `${workplaneSettingsFingerprint(workspace, snapGrid)}:${placementElevation}`; setProjects((current) => { let changed = false; const next = current.map((project) => { if (project.id !== snapshot.projectId) return project; - const currentFingerprint = workplaneSettingsFingerprint( + const currentFingerprint = `${workplaneSettingsFingerprint( normalizeWorkspaceSettings(project.workspace), normalizeSnapGrid(project.snapGrid), - ); + )}:${project.placementElevation ?? 0}`; if (currentFingerprint === nextFingerprint) return project; changed = true; return { ...project, workspace, snapGrid, + placementElevation, updatedAt: version, }; }); @@ -551,34 +567,119 @@ export default function Home() { openEditor(project.id, { allowMissingFromStorage: true }); }; - const importFileFromDashboard = useCallback( - async (file: File) => { - const isSvg = /\.svg$/i.test(file.name) || file.type === "image/svg+xml"; - if (!isSvg && !importExtensionSupported(file.name)) { - setDashboardNotice("Unsupported file type. Use STL or SVG."); + const openSkfProjectFromFile = useCallback(async (file: File) => { + setDashboardNotice(`Validating ${file.name} before opening it as a new project`); + try { + const restored = await importSkfProject(await file.arrayBuffer()); + const now = Date.now(); + const project: DashboardProject = { + ...newProject(restored.projectName, projects.length, restored.shapes.length), + createdAt: restored.createdAt, + updatedAt: now, + revision: now, + workspace: restored.workspace, + snapGrid: restored.snapGrid, + placementElevation: restored.placementElevation, + }; + const entry = projectShapeCacheEntry(now, restored.shapes, restored.history, restored.historyIndex, restored.assets); + await saveProjectShapes(project.id, entry); + setProjectShapesById((current) => ({ ...current, [project.id]: entry })); + setProjects((current) => [project, ...current]); + setDashboardNotice(`Opened ${file.name} as a new editable local project`); + openEditor(project.id, { allowMissingFromStorage: true }); + return { ok: true, message: `Opened ${file.name} as a new editable local project` }; + } catch (error) { + const message = error instanceof Error ? error.message : "Could not open SketchForge project"; + setDashboardNotice(message); + return { ok: false, message }; + } + }, [projects.length]); + + const importFilesFromDashboard = useCallback( + async (files: File[]) => { + if (!files.length) return; + const projectFiles = files.filter((file) => /\.skf$/i.test(file.name)); + if (projectFiles.length) { + if (files.length !== 1) { + setDashboardNotice("Open one .skf project at a time; import STL, STEP, and SVG geometry separately"); + return; + } + await openSkfProjectFromFile(projectFiles[0]); + return; + } + const importedShapes: WorkplaneShape[] = []; + const importedAssets: ProjectAsset[] = []; + const importedFileNames: string[] = []; + const failures: Array<{ fileName: string; reason: string }> = []; + + for (let index = 0; index < files.length; index += 1) { + const file = files[index]; + const sourceFormat = sourceFormatForFileName(file.name) ?? (file.type === "image/svg+xml" ? "svg" : null); + const isSvg = sourceFormat === "svg"; + const isStep = sourceFormat === "step"; + if (!sourceFormat || sourceFormat === "obj" || (!isSvg && !isStep && !importExtensionSupported(file.name))) { + failures.push({ fileName: file.name, reason: "Unsupported file type" }); + continue; + } + + setDashboardNotice(`Importing ${index + 1} of ${files.length}: ${file.name}`); + try { + const bytes = new Uint8Array(await file.arrayBuffer()); + const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer; + const parsedShape = isStep + ? await import("@/lib/stepImport").then(({ importedShapeFromStep }) => importedShapeFromStep(file.name, buffer)) + : isSvg + ? importedShapeFromSvg(file.name, new TextDecoder().decode(bytes)) + : importedShapeFromStl(file.name, buffer); + const asset = await projectAssetFromBytes(file.name, sourceFormat, bytes, file.type); + importedShapes.push(attachProjectAsset(parsedShape, asset.id)); + importedAssets.push(asset); + importedFileNames.push(file.name); + } catch (error) { + failures.push({ + fileName: file.name, + reason: error instanceof Error ? error.message : "Could not read file", + }); + } + } + + const failureDetails = failures + .slice(0, 3) + .map((failure) => `${failure.fileName}: ${failure.reason}`) + .join("; "); + const remainingFailureCount = Math.max(0, failures.length - 3); + const failureSummary = failures.length + ? ` Failed: ${failureDetails}${remainingFailureCount ? `; plus ${remainingFailureCount} more` : ""}` + : ""; + + if (!importedShapes.length) { + setDashboardNotice(files.length === 1 && failures[0] ? failures[0].reason : `Could not import any of the ${files.length} selected files.${failureSummary}`); return; } try { - const shape = isSvg - ? importedShapeFromSvg(file.name, await file.text()) - : importedShapeFromStl(file.name, await file.arrayBuffer()); - const project = newProject(projectNameFromFileName(file.name), projects.length, 1); + const projectName = importedShapes.length === 1 + ? projectNameFromFileName(importedFileNames[0]) + : `Imported design (${importedShapes.length} files)`; + const project = newProject(projectName, projects.length, importedShapes.length); const revision = project.revision ?? project.updatedAt; - const entry = projectShapeCacheEntry(revision, [shape]); + const entry = projectShapeCacheEntry(revision, importedShapes, undefined, undefined, dedupeProjectAssets(importedAssets)); await saveProjectShapes(project.id, entry); setProjectShapesById((current) => ({ ...current, [project.id]: entry, })); - setDashboardNotice(`Imported ${file.name}`); + const successSummary = importedShapes.length === 1 && files.length === 1 + ? `Imported ${files[0].name}` + : `Imported ${importedShapes.length} of ${files.length} files`; + setDashboardNotice(`${successSummary}.${failureSummary}`.trim()); setProjects((current) => [project, ...current]); openEditor(project.id, { allowMissingFromStorage: true }); } catch (error) { - setDashboardNotice(error instanceof Error ? error.message : `Could not import ${file.name}`); + setDashboardNotice(error instanceof Error ? error.message : "Could not create a project for the imported files"); } }, - [projects.length], + [openSkfProjectFromFile, projects.length], ); const openLatestProject = () => { @@ -653,11 +754,12 @@ export default function Home() { ref={dashboardImportInputRef} className="hidden-file-input" type="file" - accept=".stl,.svg,image/svg+xml" + multiple + accept=".skf,.stl,.step,.stp,.svg,image/svg+xml" onChange={(event) => { - const file = event.currentTarget.files?.[0]; - if (file) { - void importFileFromDashboard(file); + const files = event.currentTarget.files ? Array.from(event.currentTarget.files) : []; + if (files.length) { + void importFilesFromDashboard(files); } event.currentTarget.value = ""; }} @@ -697,17 +799,22 @@ export default function Home() { {editorStarted && canRenderEditor ? (
@@ -858,7 +965,7 @@ function Dashboard({ - Import STL/SVG + Open SKF or import geometry {panel === "import" ? (
+ +
or add geometry
- - -

STEP keeps boxes, cylinders, spheres and cones as exact CAD geometry (OpenCascade). Other shapes are skipped.

+
+
+ +
+ setExportName(event.target.value)} + onFocus={(event) => event.currentTarget.select()} + onKeyDown={(event) => { + if (event.key === "Enter" && (shapeCount > 0 || exportFormat === "skf") && !stepExporting && !skfExporting) runSelectedExport(); + }} + /> + .{exportFormat} +
+
+ +
+
+
+ Format +
+ {exportFormat === "skf" ? "Full project" : `${shapeCount} ${scopeLabel}`} +
+
+ {(["stl", "obj", "step", "svg", "skf"] as const).map((format) => ( + + ))} +
+
+ + {exportFormat === "skf" ? ( +
+
+
+ Saved action history + Choose how many recent undo actions travel with the project +
+
+
+ setSkfHistoryLimit(skfHistoryLimits[Number(event.currentTarget.value)] ?? "unlimited")} + /> +
+ +
+ ) : null} + +
+
+ {selectedExport.label} + {selectedExport.description} +
+

{selectedExport.note}

+
+ +
+
+ +
+
) : null} {panel === "tips" ? ( diff --git a/apps/web/src/lib/editorHistory.ts b/apps/web/src/lib/editorHistory.ts index d9fe890..31ee3f4 100644 --- a/apps/web/src/lib/editorHistory.ts +++ b/apps/web/src/lib/editorHistory.ts @@ -1,8 +1,9 @@ import type { WorkplaneShape } from "@/types/sketchforge"; import { canonicalizeShape, serializeShapesForSync } from "@/lib/workplaneShapes"; -export const MAX_EDITOR_HISTORY_ENTRIES = 100; +export const MAX_EDITOR_HISTORY_ENTRIES = 5000; export const MAX_EDITOR_HISTORY_BYTES = 64 * 1024 * 1024; +export type EditorHistoryExportLimit = "unlimited" | 100 | 50 | 30; export type EditorHistoryEntry = { shapes: WorkplaneShape[]; @@ -105,3 +106,18 @@ export function hydrateEditorHistoryState( return { entries: [fallback], index: 0 }; } } + +export function editorHistoryForExport( + entries: EditorHistoryEntry[], + requestedIndex: number, + limit: EditorHistoryExportLimit, +): EditorHistoryState { + if (entries.length === 0) return { entries: [], index: 0 }; + const index = Math.min(Math.max(0, requestedIndex), entries.length - 1); + if (limit === "unlimited") return { entries, index }; + const start = Math.max(0, index - limit); + return { + entries: entries.slice(start, index + 1), + index: index - start, + }; +} diff --git a/apps/web/src/lib/exportNames.ts b/apps/web/src/lib/exportNames.ts index 04a956a..463e85c 100644 --- a/apps/web/src/lib/exportNames.ts +++ b/apps/web/src/lib/exportNames.ts @@ -1,4 +1,4 @@ -export type ProjectExportFormat = "stl" | "obj" | "step"; +export type ProjectExportFormat = "stl" | "obj" | "step" | "svg" | "skf"; export function projectExportFileName(projectName: string, format: ProjectExportFormat) { const safeProjectName = projectName diff --git a/apps/web/src/lib/projectAssets.ts b/apps/web/src/lib/projectAssets.ts new file mode 100644 index 0000000..04a178e --- /dev/null +++ b/apps/web/src/lib/projectAssets.ts @@ -0,0 +1,93 @@ +import type { ProjectAsset, ProjectAssetSourceFormat, WorkplaneShape } from "@/types/sketchforge"; + +function exactArrayBuffer(bytes: Uint8Array) { + return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer; +} + +export async function sha256Hex(bytes: Uint8Array) { + if (!globalThis.crypto?.subtle) { + throw new Error("Secure hashing is unavailable in this browser"); + } + const digest = await globalThis.crypto.subtle.digest("SHA-256", exactArrayBuffer(bytes)); + return Array.from(new Uint8Array(digest), (value) => value.toString(16).padStart(2, "0")).join(""); +} + +export function sourceFormatForFileName(fileName: string): ProjectAssetSourceFormat | null { + const extension = fileName.split(".").pop()?.toLowerCase(); + if (extension === "stl" || extension === "obj" || extension === "svg") return extension; + if (extension === "step" || extension === "stp") return "step"; + return null; +} + +export function defaultMediaTypeForSource(format: ProjectAssetSourceFormat) { + if (format === "svg") return "image/svg+xml"; + if (format === "step") return "application/step"; + if (format === "obj") return "model/obj"; + return "model/stl"; +} + +export async function projectAssetFromBytes( + name: string, + sourceFormat: ProjectAssetSourceFormat, + bytes: Uint8Array, + mediaType = defaultMediaTypeForSource(sourceFormat), +): Promise { + const stableBytes = new Uint8Array(bytes); + const sha256 = await sha256Hex(stableBytes); + return { + id: `asset-${sha256.slice(0, 32)}`, + name: name.trim() || `Imported ${sourceFormat.toUpperCase()}`, + mediaType: mediaType.trim() || defaultMediaTypeForSource(sourceFormat), + sourceFormat, + bytes: stableBytes, + byteLength: stableBytes.byteLength, + sha256, + }; +} + +export async function projectAssetFromFile(file: File, sourceFormat = sourceFormatForFileName(file.name)) { + if (!sourceFormat) throw new Error("Unsupported project asset type"); + const bytes = new Uint8Array(await file.arrayBuffer()); + return projectAssetFromBytes(file.name, sourceFormat, bytes, file.type); +} + +export function normalizeProjectAsset(value: ProjectAsset): ProjectAsset { + const candidate = value.bytes as Uint8Array | ArrayBuffer | number[]; + const bytes = candidate instanceof Uint8Array + ? new Uint8Array(candidate) + : candidate instanceof ArrayBuffer + ? new Uint8Array(candidate.slice(0)) + : new Uint8Array(Array.isArray(candidate) ? candidate : []); + return { ...value, bytes, byteLength: bytes.byteLength }; +} + +export function dedupeProjectAssets(assets: ProjectAsset[]) { + const byHash = new Map(); + assets.forEach((asset) => { + const normalized = normalizeProjectAsset(asset); + if (!byHash.has(normalized.sha256)) byHash.set(normalized.sha256, normalized); + }); + return [...byHash.values()].sort((a, b) => a.id.localeCompare(b.id)); +} + +export function attachProjectAsset(shape: WorkplaneShape, assetId: string): WorkplaneShape { + if (!shape.importedMesh) return shape; + return { + ...shape, + importedMesh: { + ...shape.importedMesh, + assetId, + }, + }; +} + +export function projectAssetIdsInShapes(shapes: WorkplaneShape[]) { + const ids = new Set(); + const visit = (shape: WorkplaneShape) => { + if (shape.importedMesh?.assetId) ids.add(shape.importedMesh.assetId); + shape.groupedShapes?.forEach(visit); + shape.edgeTreatmentHistory?.forEach((entry) => visit(entry.before)); + }; + shapes.forEach(visit); + return ids; +} diff --git a/apps/web/src/lib/shapeCatalog.ts b/apps/web/src/lib/shapeCatalog.ts index b7dd387..b779309 100644 --- a/apps/web/src/lib/shapeCatalog.ts +++ b/apps/web/src/lib/shapeCatalog.ts @@ -53,6 +53,7 @@ export function sceneShape(shape: Partial & Pick["sourceFormat"]; +}; + +export type SkfShapeNodeV1 = { + nodeId: string; + objectId: string; + objectType: "native" | "imported" | "group" | "sketch"; + workplaneId: string; + definition: Record; + importedMesh?: SkfImportedMeshReferenceV1; + groupedShapeNodeIds?: string[]; + edgeTreatmentHistory?: Array<{ + id: string; + createdAt: number; + feature: Record; + appliedFrame?: Record; + beforeNodeId: string; + }>; + cadBrepAssetId?: string; +}; + +export type SkfStateV1 = { + id: string; + rootNodeIds: string[]; + nodes: SkfShapeNodeV1[]; +}; + +export type SkfFeatureV1 = { + id: string; + type: string; + outputObjectId: string; + inputObjectIds: string[]; + dependsOnFeatureIds: string[]; + parameters?: Record; +}; + +export type SkfProjectDocumentV1 = { + schema: typeof SKF_SCHEMA_ID; + formatVersion: 1; + minimumReaderVersion: number; + createdWithVersion: string; + metadata: { + projectId?: string; + projectName: string; + units: string; + createdAt: string; + modifiedAt: string; + }; + assets: SkfAssetRecordV1[]; + sceneStateId: string; + states: SkfStateV1[]; + history: { + entries: Array<{ stateId: string; selectedObjectIds: string[] }>; + index: number; + }; + sketches: Array<{ id: string; nodeId: string; objectId: string; extrusionDepth: number }>; + features: SkfFeatureV1[]; + groups: Array<{ id: string; nodeId: string; objectId: string; memberNodeIds: string[]; operation: string }>; + workplanes: Array<{ id: string; kind: "base" | "offset"; elevation: number }>; + exactCad: Array<{ nodeId: string; objectId: string; brepAssetId?: string; importedStepAssetId?: string }>; + editor: { + workspace: WorkplaneWorkspaceSettings; + snapGrid: GridSize; + selectedWorkplaneId: string; + placementElevation: number; + }; +}; + +export type SkfProjectExportInput = { + projectId?: string | null; + projectName: string; + createdAt: number; + modifiedAt: number; + shapes: WorkplaneShape[]; + history: EditorHistoryEntry[]; + historyIndex: number; + assets: ProjectAsset[]; + workspace: WorkplaneWorkspaceSettings; + snapGrid: GridSize; + placementElevation: number; +}; + +export type SkfRestoredProject = { + sourceProjectId?: string; + projectName: string; + createdAt: number; + modifiedAt: number; + shapes: WorkplaneShape[]; + history: EditorHistoryEntry[]; + historyIndex: number; + assets: ProjectAsset[]; + workspace: WorkplaneWorkspaceSettings; + snapGrid: GridSize; + placementElevation: number; + migratedFromVersion?: number; +}; + +export type SkfSourceImporter = (asset: ProjectAsset) => Promise>; + +export type ImportSkfOptions = { + sourceImporter?: SkfSourceImporter; +}; + +type ArchiveFiles = Record; + +function exactArrayBuffer(bytes: Uint8Array) { + return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer; +} + +function finiteNumber(value: unknown, label: string) { + if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`${label} must be a finite number`); + return value; +} + +function safeTimestamp(value: number, fallback: number) { + return Number.isFinite(value) && value > 0 ? value : fallback; +} + +function safeIsoTimestamp(value: number, fallback: number) { + return new Date(safeTimestamp(value, fallback)).toISOString(); +} + +function parseIsoTimestamp(value: unknown, label: string) { + if (typeof value !== "string") throw new Error(`${label} is missing`); + const parsed = Date.parse(value); + if (!Number.isFinite(parsed)) throw new Error(`${label} is invalid`); + return parsed; +} + +function safeNodeToken(value: string) { + return encodeURIComponent(value).replace(/%/g, "~"); +} + +function safeArchivePath(path: string) { + return Boolean(path) + && !path.startsWith("/") + && !path.startsWith("\\") + && !/^[a-z]:/i.test(path) + && !path.includes("\\") + && path.split("/").every((part) => part && part !== "." && part !== ".."); +} + +function extensionForAsset(kind: SkfAssetKind, mediaType: string, sourceFormat?: ProjectAssetSourceFormat) { + if (kind === "source" && sourceFormat) return sourceFormat === "step" ? "step" : sourceFormat; + if (kind === "derived-mesh") return "skfmesh"; + if (kind === "brep") return "brep"; + if (mediaType.includes("png")) return "png"; + if (mediaType.includes("jpeg")) return "jpg"; + if (mediaType.includes("webp")) return "webp"; + if (mediaType.includes("svg")) return "svg"; + if (mediaType.includes("gif")) return "gif"; + return "bin"; +} + +function encodeMeshCache(mesh: NonNullable) { + if (mesh.positions.length > SKF_LIMITS.meshNumbers || (mesh.normals?.length ?? 0) > SKF_LIMITS.meshNumbers) { + throw new Error("Imported mesh is too large for a SketchForge project file"); + } + const normalLength = mesh.normals?.length ?? 0; + const bytes = new Uint8Array(16 + (mesh.positions.length + normalLength) * 8); + bytes.set(strToU8("SKFMSH1\0"), 0); + const view = new DataView(bytes.buffer); + view.setUint32(8, mesh.positions.length, true); + view.setUint32(12, normalLength, true); + let offset = 16; + for (const value of mesh.positions) { + if (!Number.isFinite(value)) throw new Error("Imported mesh contains an invalid coordinate"); + view.setFloat64(offset, value, true); + offset += 8; + } + for (const value of mesh.normals ?? []) { + if (!Number.isFinite(value)) throw new Error("Imported mesh contains an invalid normal"); + view.setFloat64(offset, value, true); + offset += 8; + } + return bytes; +} + +function decodeMeshCache(bytes: Uint8Array) { + if (bytes.byteLength < 16 || strFromU8(bytes.subarray(0, 8)) !== "SKFMSH1\0") { + throw new Error("A derived mesh asset has an invalid header"); + } + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const positionLength = view.getUint32(8, true); + const normalLength = view.getUint32(12, true); + if (positionLength > SKF_LIMITS.meshNumbers || normalLength > SKF_LIMITS.meshNumbers) { + throw new Error("A derived mesh asset exceeds the supported coordinate limit"); + } + const expected = 16 + (positionLength + normalLength) * 8; + if (expected !== bytes.byteLength) throw new Error("A derived mesh asset is truncated or malformed"); + const positions = new Array(positionLength); + const normals = normalLength ? new Array(normalLength) : undefined; + let offset = 16; + for (let index = 0; index < positionLength; index += 1) { + positions[index] = view.getFloat64(offset, true); + offset += 8; + } + for (let index = 0; index < normalLength; index += 1) { + (normals as number[])[index] = view.getFloat64(offset, true); + offset += 8; + } + return { positions, normals }; +} + +function decodeDataUrl(dataUrl: string) { + const match = dataUrl.match(/^data:([^;,]+)?(;base64)?,([\s\S]*)$/); + if (!match) throw new Error("Embedded image has an invalid data URL"); + const mediaType = match[1] || "application/octet-stream"; + if (match[2]) { + const binary = globalThis.atob(match[3].replace(/\s/g, "")); + const bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index); + return { mediaType, bytes }; + } + return { mediaType, bytes: strToU8(decodeURIComponent(match[3])) }; +} + +function bytesToDataUrl(bytes: Uint8Array, mediaType: string) { + let binary = ""; + for (let offset = 0; offset < bytes.length; offset += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(offset, Math.min(bytes.length, offset + 0x8000))); + } + return `data:${mediaType};base64,${globalThis.btoa(binary)}`; +} + +class SkfArchiveBuilder { + readonly files: ArchiveFiles = {}; + readonly assets: SkfAssetRecordV1[] = []; + readonly sourceIdMap = new Map(); + private readonly recordByKindAndHash = new Map(); + + async addAsset( + kind: SkfAssetKind, + bytes: Uint8Array, + mediaType: string, + options: { fileName?: string; sourceFormat?: ProjectAssetSourceFormat } = {}, + ) { + if (bytes.byteLength > SKF_LIMITS.assetBytes) throw new Error(`${options.fileName ?? kind} exceeds the per-asset size limit`); + const sha256 = await sha256Hex(bytes); + const key = `${kind}:${sha256}`; + const existing = this.recordByKindAndHash.get(key); + if (existing) return existing; + const extension = extensionForAsset(kind, mediaType, options.sourceFormat); + const id = `${kind}-${sha256.slice(0, 32)}`; + const path = `assets/${kind}/${sha256}.${extension}`; + const record: SkfAssetRecordV1 = { + id, + kind, + path, + mediaType, + byteLength: bytes.byteLength, + sha256, + ...(options.fileName ? { fileName: options.fileName } : {}), + ...(options.sourceFormat ? { sourceFormat: options.sourceFormat } : {}), + }; + this.files[path] = bytes; + this.assets.push(record); + this.recordByKindAndHash.set(key, record); + return record; + } + + async addSources(assets: ProjectAsset[], referencedIds: Set) { + const normalized = assets + .filter((asset) => referencedIds.has(asset.id)) + .map(normalizeProjectAsset) + .sort((a, b) => a.id.localeCompare(b.id)); + for (const asset of normalized) { + const record = await this.addAsset("source", asset.bytes, asset.mediaType, { + fileName: asset.name, + sourceFormat: asset.sourceFormat, + }); + this.sourceIdMap.set(asset.id, record.id); + } + } +} + +function assertUniqueRuntimeObjectIds(shapes: WorkplaneShape[], stateLabel: string) { + const ids = new Set(); + const visit = (shape: WorkplaneShape) => { + if (!shape.id || ids.has(shape.id)) throw new Error(`${stateLabel} contains duplicate object ID '${shape.id || "(empty)"}'`); + ids.add(shape.id); + shape.groupedShapes?.forEach(visit); + }; + shapes.forEach(visit); +} + +function referencedSourceAssetIds(states: WorkplaneShape[][]) { + const ids = new Set(); + const visit = (shape: WorkplaneShape) => { + if (shape.importedMesh?.assetId) ids.add(shape.importedMesh.assetId); + shape.groupedShapes?.forEach(visit); + shape.edgeTreatmentHistory?.forEach((entry) => visit(entry.before)); + }; + states.flat().forEach(visit); + return ids; +} + +async function serializeShapeNode( + shape: WorkplaneShape, + nodeId: string, + nodes: SkfShapeNodeV1[], + builder: SkfArchiveBuilder, + sourceAssetsByArchiveId: Map, +): Promise { + const { + importedMesh, + groupedShapes, + edgeTreatmentHistory, + cadBrep, + imagePlate, + sketchProfile, + ...baseDefinition + } = canonicalizeShape(shape); + const definition: Record = { ...baseDefinition }; + + if (imagePlate) { + const { dataUrl, ...plateDefinition } = imagePlate; + const decoded = decodeDataUrl(dataUrl); + const asset = await builder.addAsset("image", decoded.bytes, decoded.mediaType, { fileName: `${shape.name}-image` }); + definition.imagePlate = { ...plateDefinition, assetId: asset.id }; + } + + if (sketchProfile) { + const images = await Promise.all((sketchProfile.images ?? []).map(async (image) => { + const { dataUrl, ...imageDefinition } = image; + const decoded = decodeDataUrl(dataUrl); + const asset = await builder.addAsset("image", decoded.bytes, decoded.mediaType, { fileName: image.name }); + return { ...imageDefinition, assetId: asset.id }; + })); + definition.sketchProfile = { + points: sketchProfile.points, + segments: sketchProfile.segments, + ...(images.length ? { images } : {}), + }; + } + + let importedReference: SkfImportedMeshReferenceV1 | undefined; + if (importedMesh) { + const archiveSourceId = importedMesh.assetId ? builder.sourceIdMap.get(importedMesh.assetId) : undefined; + const archiveSource = archiveSourceId ? sourceAssetsByArchiveId.get(archiveSourceId) : undefined; + const canRegenerate = Boolean( + archiveSource + && importedMesh.sourceFormat !== "json" + && archiveSource?.sourceFormat === importedMesh.sourceFormat, + ); + let meshAssetId: string | undefined; + let brepStepAssetId: string | undefined; + if (!canRegenerate) { + meshAssetId = (await builder.addAsset("derived-mesh", encodeMeshCache(importedMesh), "application/vnd.sketchforge.mesh")).id; + if (importedMesh.brepStep) { + brepStepAssetId = (await builder.addAsset("brep", strToU8(importedMesh.brepStep), "application/step")).id; + } + } + importedReference = { + ...(canRegenerate && archiveSourceId ? { sourceAssetId: archiveSourceId } : {}), + ...(meshAssetId ? { meshAssetId } : {}), + ...(brepStepAssetId ? { brepStepAssetId } : {}), + baseWidth: importedMesh.baseWidth, + baseDepth: importedMesh.baseDepth, + baseHeight: importedMesh.baseHeight, + triangleCount: importedMesh.triangleCount, + sourceFormat: importedMesh.sourceFormat, + }; + } + + let cadBrepAssetId: string | undefined; + if (cadBrep) cadBrepAssetId = (await builder.addAsset("brep", strToU8(cadBrep), "application/vnd.sketchforge.brep")).id; + + const groupedShapeNodeIds: string[] = []; + for (const child of groupedShapes ?? []) { + const childNodeId = `${nodeId}/group/${safeNodeToken(child.id)}`; + groupedShapeNodeIds.push(await serializeShapeNode(child, childNodeId, nodes, builder, sourceAssetsByArchiveId)); + } + + const serializedEdgeHistory: NonNullable = []; + for (const entry of edgeTreatmentHistory ?? []) { + const beforeNodeId = `${nodeId}/edge/${safeNodeToken(entry.id)}/before`; + await serializeShapeNode(entry.before, beforeNodeId, nodes, builder, sourceAssetsByArchiveId); + serializedEdgeHistory.push({ + id: entry.id, + createdAt: entry.createdAt, + feature: { ...entry.feature }, + ...(entry.appliedFrame ? { appliedFrame: { ...entry.appliedFrame } } : {}), + beforeNodeId, + }); + } + + const objectType = groupedShapeNodeIds.length + ? "group" + : importedReference + ? "imported" + : shape.kind === "sketch" + ? "sketch" + : "native"; + nodes.push({ + nodeId, + objectId: shape.id, + objectType, + workplaneId: "base", + definition, + ...(importedReference ? { importedMesh: importedReference } : {}), + ...(groupedShapeNodeIds.length ? { groupedShapeNodeIds } : {}), + ...(serializedEdgeHistory.length ? { edgeTreatmentHistory: serializedEdgeHistory } : {}), + ...(cadBrepAssetId ? { cadBrepAssetId } : {}), + }); + return nodeId; +} + +async function serializeState( + id: string, + shapes: WorkplaneShape[], + builder: SkfArchiveBuilder, + sourceAssetsByArchiveId: Map, +): Promise { + assertUniqueRuntimeObjectIds(shapes, id); + const nodes: SkfShapeNodeV1[] = []; + const rootNodeIds: string[] = []; + for (const shape of shapes) { + const nodeId = `${id}/object/${safeNodeToken(shape.id)}`; + rootNodeIds.push(await serializeShapeNode(shape, nodeId, nodes, builder, sourceAssetsByArchiveId)); + } + nodes.sort((a, b) => a.nodeId.localeCompare(b.nodeId)); + return { id, rootNodeIds, nodes }; +} + +function nodeGroupOperation(node: SkfShapeNodeV1, nodeById: Map) { + if (node.definition.groupOperation === "intersection") return "boolean-intersection"; + const children = (node.groupedShapeNodeIds ?? []).map((id) => nodeById.get(id)).filter(Boolean) as SkfShapeNodeV1[]; + const hasHole = children.some((child) => child.definition.hole === true); + const hasSolid = children.some((child) => child.definition.hole !== true); + return hasHole && hasSolid ? "boolean-subtraction" : "group"; +} + +function activeProjectIndexes(state: SkfStateV1) { + const nodeById = new Map(state.nodes.map((node) => [node.nodeId, node])); + const features: SkfFeatureV1[] = []; + const groups: SkfProjectDocumentV1["groups"] = []; + const sketches: SkfProjectDocumentV1["sketches"] = []; + const exactCad: SkfProjectDocumentV1["exactCad"] = []; + const lastFeatureByNode = new Map(); + const visited = new Set(); + + const visit = (nodeId: string) => { + if (visited.has(nodeId)) return; + visited.add(nodeId); + const node = nodeById.get(nodeId); + if (!node) return; + (node.groupedShapeNodeIds ?? []).forEach(visit); + let previous: string | undefined; + if (node.definition.sketchProfile && node.definition.kind === "sketch") { + const featureId = `feature/${safeNodeToken(node.nodeId)}/sketch-extrusion`; + features.push({ + id: featureId, + type: "sketch-extrusion", + outputObjectId: node.objectId, + inputObjectIds: [], + dependsOnFeatureIds: [], + parameters: { depth: node.definition.height, direction: "positive-y", mode: "create" }, + }); + sketches.push({ id: `sketch/${safeNodeToken(node.objectId)}`, nodeId: node.nodeId, objectId: node.objectId, extrusionDepth: Number(node.definition.height) }); + previous = featureId; + } + if (node.groupedShapeNodeIds?.length) { + const operation = nodeGroupOperation(node, nodeById); + const featureId = `feature/${safeNodeToken(node.nodeId)}/${operation}`; + const dependencies = node.groupedShapeNodeIds.flatMap((childId) => { + const dependency = lastFeatureByNode.get(childId); + return dependency ? [dependency] : []; + }); + features.push({ + id: featureId, + type: operation, + outputObjectId: node.objectId, + inputObjectIds: node.groupedShapeNodeIds.map((childId) => nodeById.get(childId)?.objectId ?? ""), + dependsOnFeatureIds: dependencies, + }); + groups.push({ + id: `group/${safeNodeToken(node.objectId)}`, + nodeId: node.nodeId, + objectId: node.objectId, + memberNodeIds: [...node.groupedShapeNodeIds], + operation, + }); + previous = featureId; + } + const treatments = Array.isArray(node.definition.edgeTreatments) ? node.definition.edgeTreatments as Array> : []; + treatments.forEach((treatment, index) => { + const type = treatment.kind === "fillet" ? "fillet" : "chamfer"; + const featureId = `feature/${safeNodeToken(node.nodeId)}/${type}/${index}`; + features.push({ + id: featureId, + type, + outputObjectId: node.objectId, + inputObjectIds: [node.objectId], + dependsOnFeatureIds: previous ? [previous] : [], + parameters: { ...treatment }, + }); + previous = featureId; + }); + if (node.definition.mirrorX || node.definition.mirrorY || node.definition.mirrorZ) { + const featureId = `feature/${safeNodeToken(node.nodeId)}/mirror`; + features.push({ + id: featureId, + type: "mirror", + outputObjectId: node.objectId, + inputObjectIds: [node.objectId], + dependsOnFeatureIds: previous ? [previous] : [], + parameters: { x: Boolean(node.definition.mirrorX), y: Boolean(node.definition.mirrorY), z: Boolean(node.definition.mirrorZ) }, + }); + previous = featureId; + } + if (previous) lastFeatureByNode.set(node.nodeId, previous); + if (node.cadBrepAssetId || node.importedMesh?.sourceAssetId && node.importedMesh.sourceFormat === "step") { + exactCad.push({ + nodeId: node.nodeId, + objectId: node.objectId, + ...(node.cadBrepAssetId ? { brepAssetId: node.cadBrepAssetId } : {}), + ...(node.importedMesh?.sourceAssetId && node.importedMesh.sourceFormat === "step" ? { importedStepAssetId: node.importedMesh.sourceAssetId } : {}), + }); + } + }; + state.rootNodeIds.forEach(visit); + return { features, groups, sketches, exactCad }; +} + +function zipAsync(files: AsyncZippable) { + return new Promise((resolve, reject) => { + zip(files, { level: 6, mtime: new Date("1980-01-01T00:00:00.000Z") }, (error, data) => { + if (error) reject(error); + else resolve(data); + }); + }); +} + +function unzipAsync(bytes: Uint8Array) { + return new Promise((resolve, reject) => { + unzip(bytes, (error, files) => { + if (error) reject(error); + else resolve(files); + }); + }); +} + +export async function exportSkfProject(input: SkfProjectExportInput) { + const hydrated = hydrateEditorHistoryState(input.shapes, input.history, input.historyIndex); + if (hydrated.entries.length > SKF_LIMITS.states) throw new Error("Project has too many undo states for the .skf format"); + const builder = new SkfArchiveBuilder(); + const stateShapes = hydrated.entries.map((entry) => entry.shapes); + await builder.addSources(input.assets, referencedSourceAssetIds(stateShapes)); + const sourceAssetsByArchiveId = new Map(builder.assets.filter((asset) => asset.kind === "source").map((asset) => [asset.id, asset])); + const states: SkfStateV1[] = []; + const stateIdByFingerprint = new Map(); + const historyEntries: SkfProjectDocumentV1["history"]["entries"] = []; + + for (const entry of hydrated.entries) { + let stateId = stateIdByFingerprint.get(entry.fingerprint); + if (!stateId) { + stateId = `state-${states.length + 1}`; + states.push(await serializeState(stateId, entry.shapes, builder, sourceAssetsByArchiveId)); + stateIdByFingerprint.set(entry.fingerprint, stateId); + } + historyEntries.push({ stateId, selectedObjectIds: [...entry.selectedIds] }); + } + + const sceneStateId = historyEntries[hydrated.index]?.stateId; + const activeState = states.find((state) => state.id === sceneStateId); + if (!activeState) throw new Error("Could not identify the active project state"); + const indexes = activeProjectIndexes(activeState); + const now = Date.now(); + const placementElevation = Number.isFinite(input.placementElevation) ? input.placementElevation : 0; + const selectedWorkplaneId = Math.abs(placementElevation) < 1e-9 ? "workplane-base" : "workplane-active"; + const document: SkfProjectDocumentV1 = { + schema: SKF_SCHEMA_ID, + formatVersion: SKF_FORMAT_VERSION, + minimumReaderVersion: SKF_MINIMUM_READER_VERSION, + createdWithVersion: SKF_CREATED_WITH_VERSION, + metadata: { + ...(input.projectId ? { projectId: input.projectId } : {}), + projectName: input.projectName.trim() || "SketchForge design", + units: normalizeWorkspaceSettings(input.workspace).units, + createdAt: safeIsoTimestamp(input.createdAt, now), + modifiedAt: safeIsoTimestamp(input.modifiedAt, now), + }, + assets: builder.assets.sort((a, b) => a.id.localeCompare(b.id)), + sceneStateId, + states, + history: { entries: historyEntries, index: hydrated.index }, + sketches: indexes.sketches, + features: indexes.features, + groups: indexes.groups, + workplanes: [ + { id: "workplane-base", kind: "base", elevation: 0 }, + ...(selectedWorkplaneId === "workplane-active" ? [{ id: "workplane-active" as const, kind: "offset" as const, elevation: placementElevation }] : []), + ], + exactCad: indexes.exactCad, + editor: { + workspace: normalizeWorkspaceSettings(input.workspace), + snapGrid: normalizeSnapGrid(input.snapGrid), + selectedWorkplaneId, + placementElevation, + }, + }; + builder.files["project.json"] = strToU8(`${JSON.stringify(document, null, 2)}\n`); + return zipAsync(Object.fromEntries(Object.entries(builder.files).sort(([a], [b]) => a.localeCompare(b)))); +} + +function inspectZipBeforeExpansion(bytes: Uint8Array) { + if (bytes.byteLength > SKF_LIMITS.archiveBytes) throw new Error(".skf file exceeds the 512 MB archive limit"); + if (bytes.byteLength < 22) throw new Error(".skf file is not a valid package"); + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let eocd = -1; + const minimum = Math.max(0, bytes.byteLength - 65_557); + for (let offset = bytes.byteLength - 22; offset >= minimum; offset -= 1) { + if (view.getUint32(offset, true) === 0x06054b50) { + eocd = offset; + break; + } + } + if (eocd < 0) throw new Error(".skf package is missing its ZIP directory"); + const entryCount = view.getUint16(eocd + 10, true); + const centralSize = view.getUint32(eocd + 12, true); + const centralOffset = view.getUint32(eocd + 16, true); + if (entryCount === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff) { + throw new Error("ZIP64 .skf packages are not supported"); + } + if (entryCount === 0 || entryCount > SKF_LIMITS.entries) throw new Error(".skf package has an invalid number of files"); + if (centralOffset + centralSize > bytes.byteLength) throw new Error(".skf package directory is truncated"); + let offset = centralOffset; + let expandedBytes = 0; + let hasProject = false; + const names = new Set(); + for (let index = 0; index < entryCount; index += 1) { + if (offset + 46 > bytes.byteLength || view.getUint32(offset, true) !== 0x02014b50) throw new Error(".skf package directory is malformed"); + const flags = view.getUint16(offset + 8, true); + const method = view.getUint16(offset + 10, true); + const expanded = view.getUint32(offset + 24, true); + const nameLength = view.getUint16(offset + 28, true); + const extraLength = view.getUint16(offset + 30, true); + const commentLength = view.getUint16(offset + 32, true); + const end = offset + 46 + nameLength + extraLength + commentLength; + if (end > bytes.byteLength) throw new Error(".skf package directory entry is truncated"); + if (flags & 1) throw new Error("Encrypted .skf packages are not supported"); + if (method !== 0 && method !== 8) throw new Error(".skf package uses an unsupported compression method"); + const name = strFromU8(bytes.subarray(offset + 46, offset + 46 + nameLength)); + if (!safeArchivePath(name) || names.has(name)) throw new Error(".skf package contains an unsafe or duplicate file path"); + names.add(name); + if (expanded > SKF_LIMITS.assetBytes && name !== "project.json") throw new Error(`Asset '${name}' exceeds the expansion limit`); + if (name === "project.json") { + hasProject = true; + if (expanded > SKF_LIMITS.projectJsonBytes) throw new Error("project.json exceeds the supported size limit"); + } + expandedBytes += expanded; + if (expandedBytes > SKF_LIMITS.expandedBytes) throw new Error(".skf package expands beyond the 1 GB safety limit"); + offset = end; + } + if (!hasProject) throw new Error(".skf package is missing project.json"); +} + +function objectRecord(value: unknown, label: string): Record { + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object`); + return value as Record; +} + +function stringValue(value: unknown, label: string) { + if (typeof value !== "string" || !value.trim()) throw new Error(`${label} must be a non-empty string`); + return value; +} + +function stringArray(value: unknown, label: string) { + if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || !entry)) throw new Error(`${label} must be a string array`); + return value as string[]; +} + +function validateSketchProfile(value: unknown, label: string) { + const profile = objectRecord(value, label); + if (!Array.isArray(profile.points) || !Array.isArray(profile.segments)) throw new Error(`${label} is missing points or segments`); + const pointIds = new Set(); + profile.points.forEach((rawPoint, index) => { + const point = objectRecord(rawPoint, `${label}.points[${index}]`); + const id = stringValue(point.id, `${label}.points[${index}].id`); + if (pointIds.has(id)) throw new Error(`${label} contains duplicate point ID '${id}'`); + pointIds.add(id); + finiteNumber(point.x, `${label}.points[${index}].x`); + finiteNumber(point.z, `${label}.points[${index}].z`); + }); + const segmentIds = new Set(); + profile.segments.forEach((rawSegment, index) => { + const segment = objectRecord(rawSegment, `${label}.segments[${index}]`); + const id = stringValue(segment.id, `${label}.segments[${index}].id`); + if (segmentIds.has(id)) throw new Error(`${label} contains duplicate segment ID '${id}'`); + segmentIds.add(id); + const startId = stringValue(segment.startId, `${label}.segments[${index}].startId`); + const endId = stringValue(segment.endId, `${label}.segments[${index}].endId`); + if (!pointIds.has(startId) || !pointIds.has(endId)) throw new Error(`${label} contains a segment with a missing point reference`); + }); +} + +function validateShapeDefinition(definition: Record, label: string) { + const id = stringValue(definition.id, `${label}.id`); + stringValue(definition.name, `${label}.name`); + const kind = stringValue(definition.kind, `${label}.kind`); + if (!SHAPE_KINDS.has(kind)) throw new Error(`${label} has unknown shape type '${kind}'`); + stringValue(definition.color, `${label}.color`); + ["x", "z", "size", "width", "depth", "height", "rotation"].forEach((field) => finiteNumber(definition[field], `${label}.${field}`)); + if ((definition.width as number) <= 0 || (definition.depth as number) <= 0 || (definition.height as number) <= 0) { + throw new Error(`${label} has non-positive dimensions`); + } + if ([definition.width, definition.depth, definition.height].some((value) => Math.abs(value as number) > 1e9)) { + throw new Error(`${label} dimensions exceed the supported range`); + } + if (definition.importedMesh || definition.groupedShapes || definition.edgeTreatmentHistory || definition.cadBrep) { + throw new Error(`${label} contains inline package-only geometry fields`); + } + if (definition.sketchProfile) validateSketchProfile(definition.sketchProfile, `${label}.sketchProfile`); + return id; +} + +function validateFeatureGraph(features: unknown, activeObjectIds: Set) { + if (!Array.isArray(features) || features.length > SKF_LIMITS.features) throw new Error("features is invalid or too large"); + const byId = new Map>(); + features.forEach((rawFeature, index) => { + const feature = objectRecord(rawFeature, `features[${index}]`); + const id = stringValue(feature.id, `features[${index}].id`); + if (byId.has(id)) throw new Error(`Duplicate feature ID '${id}'`); + const type = stringValue(feature.type, `features[${index}].type`); + if (!FEATURE_TYPES.has(type)) throw new Error(`Unknown operation type '${type}'`); + const output = stringValue(feature.outputObjectId, `features[${index}].outputObjectId`); + if (!activeObjectIds.has(output)) throw new Error(`Feature '${id}' references missing output object '${output}'`); + stringArray(feature.inputObjectIds, `features[${index}].inputObjectIds`).forEach((input) => { + if (!activeObjectIds.has(input)) throw new Error(`Feature '${id}' references missing input object '${input}'`); + }); + stringArray(feature.dependsOnFeatureIds, `features[${index}].dependsOnFeatureIds`); + byId.set(id, feature); + }); + byId.forEach((feature, id) => { + (feature.dependsOnFeatureIds as string[]).forEach((dependency) => { + if (!byId.has(dependency)) throw new Error(`Feature '${id}' references missing dependency '${dependency}'`); + }); + }); + const visiting = new Set(); + const visited = new Set(); + const visit = (id: string) => { + if (visiting.has(id)) throw new Error(`Cyclic feature dependency detected at '${id}'`); + if (visited.has(id)) return; + visiting.add(id); + ((byId.get(id)?.dependsOnFeatureIds as string[] | undefined) ?? []).forEach(visit); + visiting.delete(id); + visited.add(id); + }; + byId.forEach((_feature, id) => visit(id)); +} + +async function validateDocumentAndAssets(raw: unknown, files: ArchiveFiles) { + const document = objectRecord(raw, "project.json") as unknown as SkfProjectDocumentV1; + if (document.schema !== SKF_SCHEMA_ID) throw new Error("This file is not a SketchForge project"); + if (!Number.isInteger(document.formatVersion)) throw new Error("SketchForge formatVersion is missing"); + if (document.formatVersion > SKF_FORMAT_VERSION) { + throw new Error(`This project uses .skf format ${document.formatVersion}, which requires a newer SketchForge version`); + } + if (document.formatVersion < SKF_FORMAT_VERSION) throw new Error(`Packaged .skf format ${document.formatVersion} requires migration support that is not available`); + if (!Number.isInteger(document.minimumReaderVersion) || document.minimumReaderVersion > SKF_FORMAT_VERSION) { + throw new Error("This project requires a newer SketchForge reader and was not opened"); + } + const metadata = objectRecord(document.metadata, "metadata"); + stringValue(metadata.projectName, "metadata.projectName"); + parseIsoTimestamp(metadata.createdAt, "metadata.createdAt"); + parseIsoTimestamp(metadata.modifiedAt, "metadata.modifiedAt"); + if (!Array.isArray(document.assets) || !Array.isArray(document.states) || !Array.isArray(document.history?.entries)) { + throw new Error("project.json is missing assets, states, or history"); + } + if (document.states.length === 0 || document.states.length > SKF_LIMITS.states) throw new Error("Project contains an invalid number of states"); + + const assetById = new Map(); + const assetPaths = new Set(); + for (let index = 0; index < document.assets.length; index += 1) { + const asset = document.assets[index]; + const id = stringValue(asset?.id, `assets[${index}].id`); + if (assetById.has(id)) throw new Error(`Duplicate asset ID '${id}'`); + if (!asset || !["source", "derived-mesh", "brep", "image"].includes(asset.kind)) throw new Error(`Asset '${id}' has an unknown type`); + if (!safeArchivePath(asset.path) || assetPaths.has(asset.path)) throw new Error(`Asset '${id}' has an unsafe or duplicate path`); + assetPaths.add(asset.path); + const bytes = files[asset.path]; + if (!bytes) throw new Error(`Missing asset '${asset.path}'`); + if (bytes.byteLength !== asset.byteLength) throw new Error(`Asset '${asset.path}' has an invalid size`); + const hash = await sha256Hex(bytes); + if (hash !== asset.sha256) throw new Error(`Asset '${asset.path}' failed its integrity check`); + if (asset.kind === "source" && !["stl", "obj", "svg", "step"].includes(asset.sourceFormat ?? "")) { + throw new Error(`Source asset '${id}' has an unknown source format`); + } + assetById.set(id, asset); + } + + const stateById = new Map(); + const activeObjectIds = new Set(); + for (let stateIndex = 0; stateIndex < document.states.length; stateIndex += 1) { + const state = document.states[stateIndex]; + const stateId = stringValue(state?.id, `states[${stateIndex}].id`); + if (stateById.has(stateId)) throw new Error(`Duplicate state ID '${stateId}'`); + if (!Array.isArray(state.nodes) || state.nodes.length > SKF_LIMITS.objectsPerState) throw new Error(`State '${stateId}' has too many objects`); + const nodeById = new Map(); + state.nodes.forEach((node, nodeIndex) => { + const nodeId = stringValue(node?.nodeId, `states[${stateIndex}].nodes[${nodeIndex}].nodeId`); + if (nodeById.has(nodeId)) throw new Error(`State '${stateId}' contains duplicate node ID '${nodeId}'`); + const definition = objectRecord(node.definition, `node '${nodeId}'.definition`); + const objectId = validateShapeDefinition(definition, `node '${nodeId}'`); + if (node.objectId !== objectId) throw new Error(`Node '${nodeId}' objectId does not match its shape definition`); + if (node.importedMesh) { + const source = node.importedMesh.sourceAssetId ? assetById.get(node.importedMesh.sourceAssetId) : undefined; + const mesh = node.importedMesh.meshAssetId ? assetById.get(node.importedMesh.meshAssetId) : undefined; + if (!source && !mesh) throw new Error(`Imported object '${objectId}' is missing its source or mesh asset`); + if (source && source.kind !== "source" || mesh && mesh.kind !== "derived-mesh") throw new Error(`Imported object '${objectId}' has an invalid asset reference`); + if (node.importedMesh.brepStepAssetId && assetById.get(node.importedMesh.brepStepAssetId)?.kind !== "brep") throw new Error(`Imported object '${objectId}' has a missing STEP B-Rep asset`); + ["baseWidth", "baseDepth", "baseHeight", "triangleCount"].forEach((field) => finiteNumber(node.importedMesh?.[field as keyof SkfImportedMeshReferenceV1], `object '${objectId}'.${field}`)); + } + if (node.cadBrepAssetId && assetById.get(node.cadBrepAssetId)?.kind !== "brep") throw new Error(`Object '${objectId}' has a missing exact B-Rep asset`); + nodeById.set(nodeId, node); + }); + const roots = stringArray(state.rootNodeIds, `state '${stateId}'.rootNodeIds`); + const visiting = new Set(); + const visited = new Set(); + const primaryObjectIds = new Set(); + const walk = (nodeId: string, primary: boolean) => { + if (visiting.has(nodeId)) throw new Error(`Cyclic group or history reference detected at '${nodeId}'`); + if (visited.has(`${primary ? "primary" : "history"}:${nodeId}`)) return; + const node = nodeById.get(nodeId); + if (!node) throw new Error(`State '${stateId}' references missing node '${nodeId}'`); + visiting.add(nodeId); + if (primary) { + if (primaryObjectIds.has(node.objectId)) throw new Error(`State '${stateId}' contains duplicate object ID '${node.objectId}'`); + primaryObjectIds.add(node.objectId); + } + (node.groupedShapeNodeIds ?? []).forEach((child) => walk(child, primary)); + (node.edgeTreatmentHistory ?? []).forEach((entry) => walk(entry.beforeNodeId, false)); + visiting.delete(nodeId); + visited.add(`${primary ? "primary" : "history"}:${nodeId}`); + }; + roots.forEach((root) => walk(root, true)); + if (stateId === document.sceneStateId) primaryObjectIds.forEach((id) => activeObjectIds.add(id)); + stateById.set(stateId, state); + } + if (!stateById.has(document.sceneStateId)) throw new Error("Active scene state is missing"); + if (!Number.isInteger(document.history.index) || document.history.index < 0 || document.history.index >= document.history.entries.length) { + throw new Error("Undo history index is invalid"); + } + document.history.entries.forEach((entry, index) => { + if (!stateById.has(entry.stateId)) throw new Error(`History entry ${index} references missing state '${entry.stateId}'`); + stringArray(entry.selectedObjectIds, `history.entries[${index}].selectedObjectIds`); + }); + if (document.history.entries[document.history.index]?.stateId !== document.sceneStateId) throw new Error("Active scene and undo history index do not match"); + validateFeatureGraph(document.features, activeObjectIds); + const editor = objectRecord(document.editor, "editor"); + finiteNumber(editor.placementElevation, "editor.placementElevation"); + return { document, assetById, stateById }; +} + +async function defaultSourceImporter(asset: ProjectAsset) { + if (asset.sourceFormat === "stl") return importedShapeFromStl(asset.name, exactArrayBuffer(asset.bytes)).importedMesh as NonNullable; + if (asset.sourceFormat === "svg") return importedShapeFromSvg(asset.name, strFromU8(asset.bytes)).importedMesh as NonNullable; + if (asset.sourceFormat === "step") { + const { importedShapeFromStep } = await import("@/lib/stepImport"); + return (await importedShapeFromStep(asset.name, exactArrayBuffer(asset.bytes))).importedMesh as NonNullable; + } + throw new Error(`SketchForge cannot reconstruct ${asset.sourceFormat.toUpperCase()} source assets yet`); +} + +async function restoreShapeFromNode( + nodeId: string, + nodeById: Map, + assetById: Map, + files: ArchiveFiles, + runtimeAssetByArchiveId: Map, + sourceMeshCache: Map>>, + sourceImporter: SkfSourceImporter, + restoring = new Set(), +): Promise { + if (restoring.has(nodeId)) throw new Error(`Cyclic shape dependency detected at '${nodeId}'`); + const node = nodeById.get(nodeId); + if (!node) throw new Error(`Missing shape node '${nodeId}'`); + restoring.add(nodeId); + const definition = { ...node.definition } as Record; + const serializedPlate = definition.imagePlate as (Record & { assetId?: string }) | undefined; + if (serializedPlate?.assetId) { + const record = assetById.get(serializedPlate.assetId); + if (!record || record.kind !== "image") throw new Error(`Object '${node.objectId}' has a missing image asset`); + const { assetId: _assetId, ...plate } = serializedPlate; + definition.imagePlate = { ...plate, dataUrl: bytesToDataUrl(files[record.path], record.mediaType) }; + } + const serializedProfile = definition.sketchProfile as (Record & { images?: Array & { assetId?: string }> }) | undefined; + if (serializedProfile?.images) { + definition.sketchProfile = { + ...serializedProfile, + images: serializedProfile.images.map((image) => { + const record = image.assetId ? assetById.get(image.assetId) : undefined; + if (!record || record.kind !== "image") throw new Error(`Sketch '${node.objectId}' has a missing image asset`); + const { assetId: _assetId, ...rest } = image; + return { ...rest, dataUrl: bytesToDataUrl(files[record.path], record.mediaType) }; + }), + }; + } + + let importedMesh: WorkplaneShape["importedMesh"]; + if (node.importedMesh?.sourceAssetId) { + const sourceAsset = runtimeAssetByArchiveId.get(node.importedMesh.sourceAssetId); + if (!sourceAsset) throw new Error(`Object '${node.objectId}' is missing its imported source asset`); + let promise = sourceMeshCache.get(sourceAsset.id); + if (!promise) { + promise = sourceImporter(sourceAsset); + sourceMeshCache.set(sourceAsset.id, promise); + } + const regenerated = await promise; + importedMesh = { ...regenerated, assetId: sourceAsset.id }; + } else if (node.importedMesh?.meshAssetId) { + const meshRecord = assetById.get(node.importedMesh.meshAssetId); + if (!meshRecord) throw new Error(`Object '${node.objectId}' is missing its derived mesh`); + const decoded = decodeMeshCache(files[meshRecord.path]); + const brepRecord = node.importedMesh.brepStepAssetId ? assetById.get(node.importedMesh.brepStepAssetId) : undefined; + importedMesh = { + ...decoded, + baseWidth: node.importedMesh.baseWidth, + baseDepth: node.importedMesh.baseDepth, + baseHeight: node.importedMesh.baseHeight, + triangleCount: node.importedMesh.triangleCount, + sourceFormat: node.importedMesh.sourceFormat, + ...(brepRecord ? { brepStep: strFromU8(files[brepRecord.path]) } : {}), + }; + } + + const groupedShapes = node.groupedShapeNodeIds?.length + ? await Promise.all(node.groupedShapeNodeIds.map((childId) => restoreShapeFromNode(childId, nodeById, assetById, files, runtimeAssetByArchiveId, sourceMeshCache, sourceImporter, new Set(restoring)))) + : undefined; + const edgeTreatmentHistory = node.edgeTreatmentHistory?.length + ? await Promise.all(node.edgeTreatmentHistory.map(async (entry) => ({ + id: entry.id, + createdAt: entry.createdAt, + feature: entry.feature as NonNullable[number]["feature"], + before: await restoreShapeFromNode(entry.beforeNodeId, nodeById, assetById, files, runtimeAssetByArchiveId, sourceMeshCache, sourceImporter, new Set(restoring)), + ...(entry.appliedFrame ? { appliedFrame: entry.appliedFrame as NonNullable[number]["appliedFrame"] } : {}), + }))) + : undefined; + const cadBrepRecord = node.cadBrepAssetId ? assetById.get(node.cadBrepAssetId) : undefined; + restoring.delete(nodeId); + return canonicalizeShape({ + ...(definition as WorkplaneShape), + ...(importedMesh ? { importedMesh } : {}), + ...(groupedShapes ? { groupedShapes } : {}), + ...(edgeTreatmentHistory ? { edgeTreatmentHistory } : {}), + ...(cadBrepRecord ? { cadBrep: strFromU8(files[cadBrepRecord.path]) } : {}), + }); +} + +async function restoreV1(document: SkfProjectDocumentV1, assetById: Map, stateById: Map, files: ArchiveFiles, options: ImportSkfOptions) { + const runtimeAssetByArchiveId = new Map(); + for (const record of document.assets.filter((asset) => asset.kind === "source")) { + const bytes = new Uint8Array(files[record.path]); + const asset: ProjectAsset = normalizeProjectAsset({ + id: record.id, + name: record.fileName ?? `Imported ${record.sourceFormat?.toUpperCase() ?? "asset"}`, + mediaType: record.mediaType, + sourceFormat: record.sourceFormat as ProjectAssetSourceFormat, + bytes, + byteLength: bytes.byteLength, + sha256: record.sha256, + }); + runtimeAssetByArchiveId.set(record.id, asset); + } + const sourceMeshCache = new Map>>(); + const sourceImporter = options.sourceImporter ?? defaultSourceImporter; + const restoredStates = new Map(); + for (const state of document.states) { + const nodeById = new Map(state.nodes.map((node) => [node.nodeId, node])); + const shapes = await Promise.all(state.rootNodeIds.map((nodeId) => restoreShapeFromNode( + nodeId, + nodeById, + assetById, + files, + runtimeAssetByArchiveId, + sourceMeshCache, + sourceImporter, + ))); + restoredStates.set(state.id, shapes); + } + const history = document.history.entries.map((entry) => editorHistoryEntry(restoredStates.get(entry.stateId) ?? [], entry.selectedObjectIds)); + const shapes = restoredStates.get(document.sceneStateId) ?? []; + const hydrated = hydrateEditorHistoryState(shapes, history, document.history.index); + if (hydrated.entries.length !== history.length || hydrated.index !== document.history.index) throw new Error("Undo history could not be restored without data loss"); + return { + sourceProjectId: document.metadata.projectId, + projectName: document.metadata.projectName, + createdAt: parseIsoTimestamp(document.metadata.createdAt, "metadata.createdAt"), + modifiedAt: parseIsoTimestamp(document.metadata.modifiedAt, "metadata.modifiedAt"), + shapes: hydrated.entries[hydrated.index]?.shapes ?? shapes, + history: hydrated.entries, + historyIndex: hydrated.index, + assets: [...runtimeAssetByArchiveId.values()], + workspace: normalizeWorkspaceSettings(document.editor.workspace), + snapGrid: normalizeSnapGrid(document.editor.snapGrid), + placementElevation: document.editor.placementElevation, + } satisfies SkfRestoredProject; +} + +function migrateV0(raw: Record): SkfRestoredProject { + const project = objectRecord(raw.project, "project"); + const shapes = Array.isArray(raw.shapes) ? raw.shapes as WorkplaneShape[] : []; + assertUniqueRuntimeObjectIds(shapes, "Legacy project"); + shapes.forEach((shape, index) => validateLegacyRuntimeShape(shape, `shapes[${index}]`)); + const historyRaw = Array.isArray(raw.history) ? raw.history as EditorHistoryEntry[] : undefined; + const requestedIndex = typeof raw.historyIndex === "number" ? raw.historyIndex : undefined; + const hydrated = hydrateEditorHistoryState(shapes.map(canonicalizeShape), historyRaw, requestedIndex); + const now = Date.now(); + return { + sourceProjectId: typeof project.id === "string" ? project.id : undefined, + projectName: typeof project.name === "string" && project.name.trim() ? project.name : "Imported SketchForge project", + createdAt: safeTimestamp(typeof project.createdAt === "number" ? project.createdAt : now, now), + modifiedAt: safeTimestamp(typeof project.modifiedAt === "number" ? project.modifiedAt : now, now), + shapes: hydrated.entries[hydrated.index]?.shapes ?? shapes, + history: hydrated.entries, + historyIndex: hydrated.index, + assets: [], + workspace: normalizeWorkspaceSettings(raw.workspace), + snapGrid: normalizeSnapGrid(raw.snapGrid), + placementElevation: typeof raw.placementElevation === "number" && Number.isFinite(raw.placementElevation) ? raw.placementElevation : 0, + migratedFromVersion: 0, + }; +} + +function validateLegacyRuntimeShape(shape: WorkplaneShape, label: string) { + const definition = { ...shape } as Record; + const importedMesh = definition.importedMesh; + const groupedShapes = definition.groupedShapes; + const edgeHistory = definition.edgeTreatmentHistory; + const cadBrep = definition.cadBrep; + delete definition.importedMesh; + delete definition.groupedShapes; + delete definition.edgeTreatmentHistory; + delete definition.cadBrep; + validateShapeDefinition(definition, label); + if (importedMesh) { + const mesh = objectRecord(importedMesh, `${label}.importedMesh`); + if (!Array.isArray(mesh.positions) || mesh.positions.length > SKF_LIMITS.meshNumbers || mesh.positions.some((value) => typeof value !== "number" || !Number.isFinite(value))) { + throw new Error(`${label}.importedMesh has invalid positions`); + } + } + if (Array.isArray(groupedShapes)) groupedShapes.forEach((child, index) => validateLegacyRuntimeShape(child as WorkplaneShape, `${label}.groupedShapes[${index}]`)); + if (Array.isArray(edgeHistory)) edgeHistory.forEach((entry, index) => validateLegacyRuntimeShape((entry as { before: WorkplaneShape }).before, `${label}.edgeTreatmentHistory[${index}].before`)); + if (cadBrep !== undefined && typeof cadBrep !== "string") throw new Error(`${label}.cadBrep is invalid`); +} + +export async function importSkfProject(input: ArrayBuffer | Uint8Array, options: ImportSkfOptions = {}): Promise { + const bytes = input instanceof Uint8Array ? new Uint8Array(input) : new Uint8Array(input.slice(0)); + if (!bytes.byteLength) throw new Error(".skf file is empty"); + const prefix = strFromU8(bytes.subarray(0, Math.min(bytes.length, 64))).trimStart(); + if (prefix.startsWith("{")) { + if (bytes.byteLength > SKF_LIMITS.projectJsonBytes) throw new Error("Legacy .skf JSON exceeds the supported size limit"); + let raw: unknown; + try { + raw = JSON.parse(strFromU8(bytes)); + } catch { + throw new Error("Legacy .skf JSON is malformed"); + } + const document = objectRecord(raw, "Legacy .skf project"); + if (document.schema !== SKF_SCHEMA_ID) throw new Error("This file is not a SketchForge project"); + if (document.formatVersion === 0) return migrateV0(document); + if (typeof document.formatVersion === "number" && document.formatVersion > SKF_FORMAT_VERSION) { + throw new Error(`This project uses .skf format ${document.formatVersion}, which requires a newer SketchForge version`); + } + throw new Error("This legacy .skf version is not supported"); + } + + inspectZipBeforeExpansion(bytes); + let files: ArchiveFiles; + try { + files = await unzipAsync(bytes); + } catch (error) { + throw new Error(`Could not expand .skf package: ${error instanceof Error ? error.message : "corrupt ZIP data"}`); + } + let raw: unknown; + try { + raw = JSON.parse(strFromU8(files["project.json"])); + } catch { + throw new Error("project.json is malformed"); + } + const validated = await validateDocumentAndAssets(raw, files); + return restoreV1(validated.document, validated.assetById, validated.stateById, files, options); +} diff --git a/apps/web/src/lib/svgExport.ts b/apps/web/src/lib/svgExport.ts new file mode 100644 index 0000000..95bc492 --- /dev/null +++ b/apps/web/src/lib/svgExport.ts @@ -0,0 +1,67 @@ +export type SvgProjectionPolygon = ReadonlyArray; + +export type SvgProjectionLayer = { + name: string; + color: string; + polygons: ReadonlyArray; +}; + +function xmlEscape(value: string) { + return value + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +function svgNumber(value: number) { + const rounded = Math.abs(value) < 1e-9 ? 0 : Number(value.toFixed(6)); + return String(rounded); +} + +function safeFillColor(value: string) { + return /^(?:#[0-9a-f]{3,8}|(?:rgb|hsl)a?\([^<>]+\))$/i.test(value.trim()) ? value.trim() : "#0098c7"; +} + +export function toSvgProjection(layers: ReadonlyArray, title = "SketchForge design") { + const cleanLayers = layers.flatMap((layer) => { + const polygons = layer.polygons.filter( + (polygon) => polygon.length >= 3 && polygon.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y)), + ); + return polygons.length ? [{ ...layer, polygons }] : []; + }); + let pointCount = 0; + let minX = Number.POSITIVE_INFINITY; + let minY = Number.POSITIVE_INFINITY; + let maxX = Number.NEGATIVE_INFINITY; + let maxY = Number.NEGATIVE_INFINITY; + cleanLayers.forEach((layer) => layer.polygons.forEach((polygon) => polygon.forEach(([x, y]) => { + pointCount += 1; + minX = Math.min(minX, x); + minY = Math.min(minY, y); + maxX = Math.max(maxX, x); + maxY = Math.max(maxY, y); + }))); + if (!pointCount) throw new Error("SVG projection contains no readable contours"); + + const width = maxX - minX; + const height = maxY - minY; + if (width <= 0 || height <= 0) throw new Error("SVG projection does not enclose a visible area"); + + const body = cleanLayers.map((layer) => { + const pathData = layer.polygons + .map((polygon) => polygon.map(([x, y], index) => `${index === 0 ? "M" : "L"}${svgNumber(x)} ${svgNumber(y)}`).join(" ") + " Z") + .join(" "); + return ` `; + }); + + return [ + '', + ``, + ` ${xmlEscape(title)}`, + " Top-view vector projection exported by SketchForge", + ...body, + "", + ].join("\n"); +} diff --git a/apps/web/src/lib/svgImport.ts b/apps/web/src/lib/svgImport.ts index 3b515d2..e0b9b4c 100644 --- a/apps/web/src/lib/svgImport.ts +++ b/apps/web/src/lib/svgImport.ts @@ -18,6 +18,9 @@ type SvgPathStyle = { fill?: string; fillOpacity?: number; opacity?: number; + stroke?: string; + strokeOpacity?: number; + strokeWidth?: number; visibility?: string; }; @@ -54,13 +57,34 @@ function attributeValues(source: string, name: string) { return values; } +const SVG_DOCUMENT_TYPE_PATTERN = /]*>/gi; +const SVG_11_DOCUMENT_TYPE_PATTERN = /^$/i; + +function svgDocumentTypes(source: string) { + return source.match(SVG_DOCUMENT_TYPE_PATTERN) ?? []; +} + +export function normalizeSvgDocumentType(source: string) { + return source.replace(SVG_DOCUMENT_TYPE_PATTERN, ""); +} + export function validateSvgSourcePreflight(source: string) { if (!source.trim()) throw new Error("SVG file is empty"); if (sourceByteLength(source) > MAX_SVG_BYTES) { throw new Error(`SVG is too large. The maximum supported size is ${MAX_SVG_BYTES / 1024 / 1024} MB`); } - if (/ !SVG_11_DOCUMENT_TYPE_PATTERN.test(declaration))) { + throw new Error("Only the standard SVG 1.1 document type is supported"); + } + + if (/\b(?:width|height|viewBox|d)\s*=\s*(["'])[^"']*\bNaN\b[^"']*\1/i.test(source)) { + throw new Error("SVG contains invalid NaN geometry. In Tinkercad, make sure the workplane intersects the model before exporting the cross-section"); } const xmlElementCount = source.match(/<[a-z][^!?/\s>]*/gi)?.length ?? 0; @@ -122,6 +146,10 @@ function fillAlpha(fill: string | undefined) { return Number.parseFloat(functional); } +function strokeAlpha(stroke: string | undefined) { + return stroke ? fillAlpha(stroke) : 0; +} + function elementStyleValue(element: Element, property: string) { const style = (element as Element & { style?: CSSStyleDeclaration }).style; const fromStyle = style?.getPropertyValue(property); @@ -143,15 +171,55 @@ function elementOrAncestorSuppressesRendering(element: Element | null | undefine return false; } -function pathIsFilledAndVisible(path: THREE.ShapePath) { +function pathStyleAndNode(path: THREE.ShapePath) { const userData = (path as THREE.ShapePath & { userData?: { style?: SvgPathStyle; node?: Element } }).userData; - const style = userData?.style ?? {}; + return { style: userData?.style ?? {}, node: userData?.node }; +} + +function pathIsVisible(path: THREE.ShapePath) { + const { style, node } = pathStyleAndNode(path); const visibility = style.visibility?.trim().toLowerCase(); if (visibility === "hidden" || visibility === "collapse") return false; if (numericStyleValue(style.opacity) <= MIN_VISIBLE_ALPHA) return false; + return !elementOrAncestorSuppressesRendering(node); +} + +function pathHasVisibleFill(path: THREE.ShapePath) { + if (!pathIsVisible(path)) return false; + const { style } = pathStyleAndNode(path); if (numericStyleValue(style.fillOpacity) <= MIN_VISIBLE_ALPHA) return false; - if (fillAlpha(style.fill) <= MIN_VISIBLE_ALPHA) return false; - return !elementOrAncestorSuppressesRendering(userData?.node); + return fillAlpha(style.fill) > MIN_VISIBLE_ALPHA; +} + +function pathHasVisibleStroke(path: THREE.ShapePath) { + if (!pathIsVisible(path)) return false; + const { style } = pathStyleAndNode(path); + if (numericStyleValue(style.strokeOpacity) <= MIN_VISIBLE_ALPHA) return false; + if (numericStyleValue(style.strokeWidth, 0) <= MIN_VISIBLE_ALPHA) return false; + return strokeAlpha(style.stroke) > MIN_VISIBLE_ALPHA; +} + +function subPathIsClosed(path: THREE.Path) { + const points = path.getPoints(SVG_CURVE_SEGMENTS); + if (points.length < 3) return false; + if (path.autoClose) return true; + const extent = points.reduce((largest, point) => Math.max(largest, Math.abs(point.x), Math.abs(point.y)), 1); + const tolerance = extent * 1e-9; + return points[0].distanceToSquared(points[points.length - 1]) <= tolerance * tolerance; +} + +function extrusionProfileFromPath(path: THREE.ShapePath) { + if (pathHasVisibleFill(path)) return path; + if (!pathHasVisibleStroke(path)) return null; + const closedSubPaths = path.subPaths.filter(subPathIsClosed); + if (!closedSubPaths.length) return null; + + const profile = new THREE.ShapePath(); + profile.color.copy(path.color); + profile.subPaths.push(...closedSubPaths); + const userData = (path as THREE.ShapePath & { userData?: { style?: SvgPathStyle; node?: Element } }).userData; + (profile as THREE.ShapePath & { userData?: { style?: SvgPathStyle; node?: Element } }).userData = userData; + return profile; } function cleanRingPoints(points: THREE.Vector2[]) { @@ -422,10 +490,15 @@ export function validateClosedSolidTriangleSoup(positions: readonly number[], la } export function buildSvgExtrusionFromPaths(paths: readonly THREE.ShapePath[]) { - const visiblePaths = paths.filter(pathIsFilledAndVisible); - if (!visiblePaths.length) throw new Error("SVG has no readable visible filled paths"); + const profilePaths = paths.map(extrusionProfileFromPath).filter((path): path is THREE.ShapePath => Boolean(path)); + if (!profilePaths.length) { + if (paths.some(pathHasVisibleStroke)) { + throw new Error("SVG contains only open strokes. Close the paths or convert the strokes to filled outlines before importing"); + } + throw new Error("SVG has no readable visible filled or closed-stroke paths"); + } - const sourceShapes = visiblePaths.flatMap((path) => SVGLoader.createShapes(path)); + const sourceShapes = profilePaths.flatMap((path) => SVGLoader.createShapes(path)); const shapes = composeNestedRings(sourceShapes); const rawPositions: number[] = []; const acceptedAnalyses: TriangleSoupAnalysis[] = []; @@ -485,7 +558,7 @@ export function buildSvgExtrusionFromPaths(paths: readonly THREE.ShapePath[]) { export function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape { validateSvgSourcePreflight(source); - const parsed = svgLoader.parse(normalizeSvgUseReferences(source)); + const parsed = svgLoader.parse(normalizeSvgUseReferences(normalizeSvgDocumentType(source))); const parsedXml = parsed.xml as unknown as XMLDocument | Element; const root = "documentElement" in parsedXml ? parsedXml.documentElement : parsedXml; if (root.localName !== "svg" || root.querySelector("parsererror")) { diff --git a/apps/web/src/lib/workplaneShapes.ts b/apps/web/src/lib/workplaneShapes.ts index 9161b3b..9a4fe20 100644 --- a/apps/web/src/lib/workplaneShapes.ts +++ b/apps/web/src/lib/workplaneShapes.ts @@ -188,6 +188,7 @@ export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) { a.groupedBaseWidth === b.groupedBaseWidth && a.groupedBaseDepth === b.groupedBaseDepth && a.groupedBaseHeight === b.groupedBaseHeight && + a.groupOperation === b.groupOperation && a.locked === b.locked && a.hidden === b.hidden ); diff --git a/apps/web/src/types/sketchforge.ts b/apps/web/src/types/sketchforge.ts index 09303ef..938d95b 100644 --- a/apps/web/src/types/sketchforge.ts +++ b/apps/web/src/types/sketchforge.ts @@ -27,6 +27,18 @@ export type ShapeAsset = { hole?: boolean; }; +export type ProjectAssetSourceFormat = "stl" | "obj" | "svg" | "step"; + +export type ProjectAsset = { + id: string; + name: string; + mediaType: string; + sourceFormat: ProjectAssetSourceFormat; + bytes: Uint8Array; + byteLength: number; + sha256: string; +}; + export type GridSize = "Off" | "0.1 mm" | "0.25 mm" | "0.5 mm" | "1.0 mm" | "2.0 mm" | "5.0 mm" | "Brick"; export type MeasurementAccuracy = 1 | 2 | 3; @@ -179,6 +191,9 @@ export type WorkplaneShape = { baseHeight: number; triangleCount: number; sourceFormat: "stl" | "obj" | "svg" | "json" | "step"; + // Stable reference to the original imported file in the project's shared + // asset table. Copies and grouped operands reuse this reference. + assetId?: string; // Exact OpenCascade B-Rep of the body (single-shape STEP text) in the same // local frame as `positions`. Set only for STEP imports; lets the exporter // re-emit the original analytic geometry instead of the tessellation. @@ -203,6 +218,7 @@ export type WorkplaneShape = { groupedBaseWidth?: number; groupedBaseDepth?: number; groupedBaseHeight?: number; + groupOperation?: "group" | "intersection"; locked?: boolean; hidden?: boolean; }; diff --git a/docs/SKF_PROJECT_FORMAT.md b/docs/SKF_PROJECT_FORMAT.md new file mode 100644 index 0000000..a803b17 --- /dev/null +++ b/docs/SKF_PROJECT_FORMAT.md @@ -0,0 +1,73 @@ +# SketchForge project files (`.skf`) + +`.skf` is SketchForge's native, editable project format. It is an additional backup, transfer, and sharing mechanism; IndexedDB autosave remains the normal local persistence system, and STL, OBJ, STEP, and SVG remain geometry exports. + +## Architecture decision + +SketchForge uses a packaged container (format option B). A `.skf` file is a ZIP archive containing `project.json` and deduplicated files below `assets/`. + +This was selected over pure JSON because imported STL/STEP data and exact B-Rep can be large, Base64 would add size and parsing overhead, and an archive lets SketchForge validate and hash each asset independently. The editable model is still JSON and can be inspected by opening `project.json` from the package. + +## Version 1 layout + +```text +project.skf +├── project.json +└── assets/ + ├── source/ Original imported STL, SVG, or STEP files + ├── derived-mesh/ Exact caches for baked operations or legacy imports + ├── brep/ Exact STEP/B-Rep payloads + └── image/ Deduplicated sketch/reference images +``` + +`project.json` contains these top-level sections: + +- `schema`, `formatVersion`, `minimumReaderVersion`, and `createdWithVersion` +- `metadata`: project name, source project ID, units, and timestamps +- `assets`: path, type, byte length, SHA-256, source format, and media type +- `states`: explicit root node IDs and editable object graphs for the active scene and undo/redo states +- `history`: ordered state references, selection per state, and current undo/redo index +- `sketches`: sketch/extrusion indexes +- `features`: supported group, subtraction, intersection, mirror, sketch-extrusion, fillet, and chamfer operations used by the active project +- `groups`: explicit parent/member references and operation type +- `workplanes`: base and selected offset workplanes +- `exactCad`: objects with exact B-Rep or imported STEP sources +- `editor`: workspace dimensions, units, snap grid, and selected workplane elevation + +Object nodes keep stable SketchForge object IDs. Groups refer to child node IDs instead of array positions. Fillet/chamfer history refers to explicit “before” nodes. Feature dependencies are explicit and checked for cycles. + +## What is preserved + +- All current native shape kinds and their editable parameters +- Position, rotation, dimensions, mirrors, colour, solid/hole role, visibility, and lock state +- Nested groups, boolean operands, subtraction results, and intersection metadata +- Sketch points, lines, Bezier/smooth handles, disjoint profiles, reference images, and extrusion depth +- Imported STL, SVG, and STEP sources, stored once and reused by instances +- Exact imported STEP data, current exact CAD B-Rep, display edges, chamfer/fillet settings, and reversible edge-treatment history +- Undo and redo states according to the export choice: Unlimited, 100, 50, or 30 recent actions. Unlimited means every state still retained by the editor, including available redo states. +- Workspace units, grid/snap settings, dimensions, and active offset workplane + +Native primitives are regenerated from definitions and do not receive mesh assets. Source-backed STL, SVG, and STEP objects are regenerated from their original asset. Derived mesh assets are written only when the current editor has genuinely baked geometry (for example a boolean or edge treatment), or when an older local project no longer has its original imported source. + +## Opening safely + +SketchForge inspects ZIP metadata before expansion and validates the entire project before changing local state. It rejects unsafe paths, encrypted or unsupported compression, excessive expansion, malformed shapes/sketches, duplicate IDs, missing assets, hash mismatches, invalid transforms, unknown shape or operation types, cyclic groups/features, and unsupported versions. + +Opening a valid `.skf` creates a new local project. It does not overwrite the project that is currently open. The imported project is then saved through the existing dashboard, thumbnail, IndexedDB, history, and editor lifecycle. + +Current safety limits are 512 MB compressed, 1 GB expanded, 256 MB per asset, 32 MB for `project.json`, 4,096 archive entries, 100,000 object nodes per state, and 5,001 distinct states. The live editor retains at most 5,000 history entries and 64 MB of serialized history, so Unlimited means all history currently available inside those safety limits. + +## Compatibility and migrations + +The current format is version 1. Readers refuse a higher `formatVersion` or `minimumReaderVersion` instead of partially loading it. The importer also contains an explicit migration for the documented version 0 pure-JSON prototype and preserves its object IDs and valid history. + +Future schema changes should add a version-to-version migration, run validation after every migration, and never mutate the user's original file. + +## Current limitations + +- Projects created before source-asset tracking cannot recover the exact original STL/SVG file. Their existing normalized editable mesh is preserved as a deduplicated legacy cache and is identified by the absence of a source asset. +- SketchForge currently bakes the displayed result of booleans and edge treatments. `.skf` preserves the operands, group hierarchy, feature metadata, reversible history, exact B-Rep where available, and a derived-result cache; it does not add a new live parametric feature editor that the application does not yet have. +- The current workplane system stores a base plane plus numeric offset. It does not expose persistent associative face-workplane references, so `.skf` cannot preserve an association that the editor itself does not model. +- Geometric sketch constraints and dimensions are not yet part of SketchForge's sketch data model. Existing points, segments, curve handles, profiles, and extrusion depth are preserved exactly. +- Camera position is intentionally omitted because the current project persistence system does not own it. It can be added as optional editor state in a compatible future version. +- OBJ is currently an export format, not an import format. An OBJ source-asset record is reserved in the schema for future import support. diff --git a/package-lock.json b/package-lock.json index 57e84de..04c395b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,6 +13,7 @@ "@types/three": "^0.184.1", "brepjs": "^18.118.0", "clsx": "^2.1.1", + "fflate": "^0.8.2", "lucide-react": "^0.511.0", "manifold-3d": "^3.5.0", "next": "^15.3.2", diff --git a/package.json b/package.json index e593d15..773f4d3 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "@types/three": "^0.184.1", "brepjs": "^18.118.0", "clsx": "^2.1.1", + "fflate": "^0.8.2", "lucide-react": "^0.511.0", "manifold-3d": "^3.5.0", "next": "^15.3.2", diff --git a/tests/unit/editorHistory.test.ts b/tests/unit/editorHistory.test.ts index a198032..a83e03d 100644 --- a/tests/unit/editorHistory.test.ts +++ b/tests/unit/editorHistory.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { appendEditorHistorySnapshot, boundedEditorHistory, editorHistoryEntry, hydrateEditorHistoryState, projectShapesFingerprint } from "@/lib/editorHistory"; +import { appendEditorHistorySnapshot, boundedEditorHistory, editorHistoryEntry, editorHistoryForExport, hydrateEditorHistoryState, projectShapesFingerprint } from "@/lib/editorHistory"; import type { WorkplaneShape } from "@/types/sketchforge"; function box(overrides: Partial = {}): WorkplaneShape { @@ -107,4 +107,18 @@ describe("editor history snapshots", () => { expect(restored.entries).toHaveLength(1); expect(restored.entries[0].shapes[0].x).toBe(9); }); + + it("selects all history or the requested number of recent undo actions for project export", () => { + const entries = Array.from({ length: 140 }, (_, x) => editorHistoryEntry([box({ x })], [])); + + const unlimited = editorHistoryForExport(entries, 120, "unlimited"); + expect(unlimited.entries).toBe(entries); + expect(unlimited.index).toBe(120); + + const lastThirty = editorHistoryForExport(entries, 120, 30); + expect(lastThirty.entries).toHaveLength(31); + expect(lastThirty.index).toBe(30); + expect(lastThirty.entries[0].shapes[0].x).toBe(90); + expect(lastThirty.entries[30].shapes[0].x).toBe(120); + }); }); diff --git a/tests/unit/exportNames.test.ts b/tests/unit/exportNames.test.ts index b5aaf9c..b49b3a3 100644 --- a/tests/unit/exportNames.test.ts +++ b/tests/unit/exportNames.test.ts @@ -6,6 +6,8 @@ describe("project export filenames", () => { expect(projectExportFileName("Gearbox Prototype", "stl")).toBe("Gearbox Prototype.stl"); expect(projectExportFileName("Gearbox Prototype", "obj")).toBe("Gearbox Prototype.obj"); expect(projectExportFileName("Gearbox Prototype", "step")).toBe("Gearbox Prototype.step"); + expect(projectExportFileName("Gearbox Prototype", "svg")).toBe("Gearbox Prototype.svg"); + expect(projectExportFileName("Gearbox Prototype", "skf")).toBe("Gearbox Prototype.skf"); }); it("removes filesystem-reserved characters without discarding the project name", () => { diff --git a/tests/unit/skfProject.test.ts b/tests/unit/skfProject.test.ts new file mode 100644 index 0000000..4fa2e69 --- /dev/null +++ b/tests/unit/skfProject.test.ts @@ -0,0 +1,342 @@ +import { describe, expect, it } from "vitest"; +import { strFromU8, strToU8, unzipSync, zipSync } from "fflate"; +import { editorHistoryEntry } from "@/lib/editorHistory"; +import { projectAssetFromBytes } from "@/lib/projectAssets"; +import { canonicalizeShape } from "@/lib/workplaneShapes"; +import { + exportSkfProject, + importSkfProject, + SKF_FORMAT_VERSION, + SKF_SCHEMA_ID, + type SkfProjectDocumentV1, + type SkfProjectExportInput, +} from "@/lib/skfProject"; +import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings"; +import type { ShapeKind, WorkplaneShape } from "@/types/sketchforge"; + +function shape(kind: ShapeKind, id = `${kind}-1`, overrides: Partial = {}): WorkplaneShape { + return { + id, + name: kind, + kind, + color: "#12a4cc", + x: 1, + z: 2, + elevation: 3, + size: 20, + width: 20, + depth: 18, + height: 16, + rotation: 15, + rotationX: 5, + rotationZ: 10, + locked: false, + hidden: false, + ...overrides, + }; +} + +function input(shapes: WorkplaneShape[], overrides: Partial = {}): SkfProjectExportInput { + const history = [editorHistoryEntry(shapes, [])]; + return { + projectId: "project-original", + projectName: "Round trip", + createdAt: 1_700_000_000_000, + modifiedAt: 1_700_000_100_000, + shapes, + history, + historyIndex: 0, + assets: [], + workspace: DEFAULT_WORKPLANE_WORKSPACE, + snapGrid: DEFAULT_SNAP_GRID, + placementElevation: 12.5, + ...overrides, + }; +} + +function packageDocument(bytes: Uint8Array) { + const files = unzipSync(bytes); + return { files, document: JSON.parse(strFromU8(files["project.json"])) as SkfProjectDocumentV1 }; +} + +function mutateProject(bytes: Uint8Array, mutate: (document: SkfProjectDocumentV1) => void) { + const files = unzipSync(bytes); + const document = JSON.parse(strFromU8(files["project.json"])) as SkfProjectDocumentV1; + mutate(document); + files["project.json"] = strToU8(JSON.stringify(document)); + return zipSync(files); +} + +describe("SketchForge .skf project packages", () => { + it("round-trips every supported native shape kind and editable properties", async () => { + const nativeKinds: ShapeKind[] = [ + "box", "cylinder", "sphere", "sketch", "scribble", "cone", "pyramid", "roof", "text", "roundRoof", + "halfSphere", "torus", "tube", "ring", "wedge", "polygon", "icosahedron", + ]; + const shapes = nativeKinds.map((kind, index) => shape(kind, `${kind}-${index}`, { + hole: index === 2, + locked: index === 3, + hidden: index === 4, + mirrorX: index === 5, + sides: index + 3, + text: kind === "text" ? "Editable" : undefined, + sketchProfile: kind === "sketch" ? { + points: [ + { id: "p1", x: 0, z: 0 }, + { id: "p2", x: 10, z: 0 }, + { id: "p3", x: 10, z: 10 }, + ], + segments: [ + { id: "s1", startId: "p1", endId: "p2", kind: "line" }, + { id: "s2", startId: "p2", endId: "p3", kind: "bezier" }, + { id: "s3", startId: "p3", endId: "p1", kind: "line" }, + ], + } : undefined, + })); + + const exported = await exportSkfProject(input(shapes)); + const { document } = packageDocument(exported); + const restored = await importSkfProject(exported); + + expect(restored.projectName).toBe("Round trip"); + expect(restored.sourceProjectId).toBe("project-original"); + expect(JSON.stringify(restored.shapes)).toBe(JSON.stringify(shapes.map(canonicalizeShape))); + expect(restored.workspace).toEqual(DEFAULT_WORKPLANE_WORKSPACE); + expect(restored.snapGrid).toBe(DEFAULT_SNAP_GRID); + expect(restored.placementElevation).toBe(12.5); + expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(0); + }); + + it("preserves nested groups, holes, intersection metadata, edge history, B-Rep, and undo/redo", async () => { + const solid = shape("box", "solid", { x: 0 }); + const hole = shape("cylinder", "hole", { hole: true, color: "#b8c2cc", x: 4 }); + const group = shape("mesh", "group", { + name: "Intersection", + groupOperation: "intersection", + groupedBaseWidth: 30, + groupedBaseDepth: 30, + groupedBaseHeight: 20, + groupedShapes: [solid, hole], + importedMesh: { + positions: [0, 0, 0, 2, 0, 0, 0, 2, 0], + normals: [0, 0, 1, 0, 0, 1, 0, 0, 1], + baseWidth: 2, + baseDepth: 1, + baseHeight: 2, + triangleCount: 1, + sourceFormat: "json", + }, + cadBrep: "BREP exact payload", + edgeTreatments: [{ kind: "fillet", amount: 1.25, edgeCount: 3 }], + edgeTreatmentHistory: [{ + id: "edge-history-1", + createdAt: 1_700_000_050_000, + feature: { kind: "fillet", amount: 1.25, edgeCount: 3 }, + before: shape("box", "group", { width: 30, depth: 30, height: 20 }), + }], + }); + const before = editorHistoryEntry([solid, hole], ["solid", "hole"]); + const after = editorHistoryEntry([group], ["group"]); + const exported = await exportSkfProject(input([group], { history: [before, after], historyIndex: 1 })); + const { document } = packageDocument(exported); + + expect(document.groups[0].operation).toBe("boolean-intersection"); + expect(document.features.some((feature) => feature.type === "fillet")).toBe(true); + expect(document.exactCad).toHaveLength(1); + + const restored = await importSkfProject(exported); + expect(restored.history).toHaveLength(2); + expect(restored.historyIndex).toBe(1); + expect(restored.shapes[0].groupedShapes).toEqual([solid, hole]); + expect(restored.shapes[0].groupOperation).toBe("intersection"); + expect(restored.shapes[0].cadBrep).toBe("BREP exact payload"); + expect(restored.shapes[0].edgeTreatmentHistory?.[0].before.kind).toBe("box"); + }); + + it("stores one original source asset for repeated imported instances and regenerates it once", async () => { + const sourceBytes = strToU8("solid source"); + const asset = await projectAssetFromBytes("shared.stl", "stl", sourceBytes); + const importedMesh: NonNullable = { + positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], + baseWidth: 1, + baseDepth: 1, + baseHeight: 1, + triangleCount: 1, + sourceFormat: "stl", + assetId: asset.id, + }; + const instances = [ + shape("mesh", "instance-a", { importedMesh, x: 0 }), + shape("mesh", "instance-b", { importedMesh, x: 30 }), + ]; + const exported = await exportSkfProject(input(instances, { assets: [asset] })); + const { document } = packageDocument(exported); + let importCalls = 0; + const restored = await importSkfProject(exported, { + sourceImporter: async () => { + importCalls += 1; + return { ...importedMesh, assetId: undefined }; + }, + }); + + expect(document.assets.filter((entry) => entry.kind === "source")).toHaveLength(1); + expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(0); + expect(restored.assets).toHaveLength(1); + expect(restored.shapes[0].importedMesh?.assetId).toBe(restored.shapes[1].importedMesh?.assetId); + expect(importCalls).toBe(1); + }); + + it.each(["svg", "step"] as const)("stores and restores original %s sources", async (sourceFormat) => { + const asset = await projectAssetFromBytes(`source.${sourceFormat}`, sourceFormat, strToU8(`${sourceFormat} source`)); + const importedMesh: NonNullable = { + positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], + baseWidth: 1, + baseDepth: 1, + baseHeight: 1, + triangleCount: 1, + sourceFormat, + assetId: asset.id, + ...(sourceFormat === "step" ? { brepStep: "exact STEP" } : {}), + }; + const exported = await exportSkfProject(input([shape("mesh", `${sourceFormat}-object`, { importedMesh })], { assets: [asset] })); + const { document } = packageDocument(exported); + const restored = await importSkfProject(exported, { sourceImporter: async () => importedMesh }); + + expect(document.assets.filter((entry) => entry.kind === "source")).toHaveLength(1); + expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(0); + expect(restored.assets[0].sourceFormat).toBe(sourceFormat); + expect(restored.shapes[0].importedMesh?.sourceFormat).toBe(sourceFormat); + if (sourceFormat === "step") expect(document.exactCad[0].importedStepAssetId).toBeTruthy(); + }); + + it("deduplicates and restores reference images stored in sketches and image plates", async () => { + const dataUrl = "data:image/png;base64,AAECAwQ="; + const imageShape = shape("sketch", "sketch-images", { + imagePlate: { dataUrl, mimeType: "image/png", pixelWidth: 2, pixelHeight: 2 }, + sketchProfile: { + points: [ + { id: "p1", x: 0, z: 0 }, + { id: "p2", x: 10, z: 0 }, + { id: "p3", x: 0, z: 10 }, + ], + segments: [ + { id: "s1", startId: "p1", endId: "p2" }, + { id: "s2", startId: "p2", endId: "p3" }, + { id: "s3", startId: "p3", endId: "p1" }, + ], + images: [{ + id: "image-1", + name: "Reference", + dataUrl, + mimeType: "image/png", + pixelWidth: 2, + pixelHeight: 2, + x: 0, + z: 0, + width: 10, + depth: 10, + }], + }, + }); + const exported = await exportSkfProject(input([imageShape])); + const { document } = packageDocument(exported); + const restored = await importSkfProject(exported); + + expect(document.assets.filter((entry) => entry.kind === "image")).toHaveLength(1); + expect(restored.shapes[0].imagePlate?.dataUrl).toBe(dataUrl); + expect(restored.shapes[0].sketchProfile?.images?.[0].dataUrl).toBe(dataUrl); + }); + + it("deduplicates derived geometry when legacy imported objects share one mesh", async () => { + const mesh = { + positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], + baseWidth: 1, + baseDepth: 1, + baseHeight: 1, + triangleCount: 1, + sourceFormat: "json" as const, + }; + const exported = await exportSkfProject(input([ + shape("mesh", "legacy-a", { importedMesh: mesh }), + shape("mesh", "legacy-b", { importedMesh: mesh }), + ])); + const { document } = packageDocument(exported); + const restored = await importSkfProject(exported); + + expect(document.assets.filter((entry) => entry.kind === "derived-mesh")).toHaveLength(1); + expect(restored.shapes[0].importedMesh?.positions).toEqual(mesh.positions); + expect(restored.shapes[1].importedMesh?.positions).toEqual(mesh.positions); + }); + + it("migrates the documented v0 JSON project without changing IDs", async () => { + const box = shape("box", "legacy-box"); + const legacy = strToU8(JSON.stringify({ + schema: SKF_SCHEMA_ID, + formatVersion: 0, + project: { id: "legacy-project", name: "Legacy", createdAt: 100, modifiedAt: 200 }, + shapes: [box], + workspace: DEFAULT_WORKPLANE_WORKSPACE, + snapGrid: "0.5 mm", + })); + + const restored = await importSkfProject(legacy); + + expect(restored.migratedFromVersion).toBe(0); + expect(restored.sourceProjectId).toBe("legacy-project"); + expect(restored.shapes[0].id).toBe("legacy-box"); + expect(restored.snapGrid).toBe("0.5 mm"); + }); + + it("rejects unsupported future versions before restoring any state", async () => { + const exported = await exportSkfProject(input([shape("box")])); + const future = mutateProject(exported, (document) => { + (document as { formatVersion: number }).formatVersion = SKF_FORMAT_VERSION + 1; + }); + + await expect(importSkfProject(future)).rejects.toThrow("requires a newer SketchForge version"); + }); + + it("rejects missing references, duplicate IDs, cyclic groups, unknown operations, and corrupt assets", async () => { + const twoShapes = await exportSkfProject(input([shape("box", "one"), shape("box", "two")])); + const missing = mutateProject(twoShapes, (document) => { + document.states[0].rootNodeIds[0] = "missing-node"; + }); + await expect(importSkfProject(missing)).rejects.toThrow("missing node"); + + const duplicate = mutateProject(twoShapes, (document) => { + const [first, second] = document.states[0].nodes; + second.objectId = first.objectId; + second.definition.id = first.objectId; + }); + await expect(importSkfProject(duplicate)).rejects.toThrow("duplicate object ID"); + + const grouped = await exportSkfProject(input([shape("mesh", "group-cycle", { + groupedShapes: [shape("box", "child-a"), shape("box", "child-b")], + })])); + const cyclic = mutateProject(grouped, (document) => { + const root = document.states[0].nodes.find((node) => node.objectId === "group-cycle")!; + root.groupedShapeNodeIds = [root.nodeId]; + }); + await expect(importSkfProject(cyclic)).rejects.toThrow("Cyclic group"); + + const unknownOperation = mutateProject(grouped, (document) => { + document.features[0].type = "unsupported-operation"; + }); + await expect(importSkfProject(unknownOperation)).rejects.toThrow("Unknown operation type"); + + const legacyMesh = await exportSkfProject(input([shape("mesh", "mesh", { + importedMesh: { + positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], + baseWidth: 1, + baseDepth: 1, + baseHeight: 1, + triangleCount: 1, + sourceFormat: "json", + }, + })])); + const { files, document } = packageDocument(legacyMesh); + const asset = document.assets.find((entry) => entry.kind === "derived-mesh")!; + files[asset.path][20] ^= 0xff; + await expect(importSkfProject(zipSync(files))).rejects.toThrow("integrity check"); + }); +}); diff --git a/tests/unit/svgExport.test.ts b/tests/unit/svgExport.test.ts new file mode 100644 index 0000000..814b07e --- /dev/null +++ b/tests/unit/svgExport.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { toSvgProjection } from "@/lib/svgExport"; + +describe("SVG projection export", () => { + it("writes an SVG 1.1 document with millimeter dimensions and even-odd contours", () => { + const svg = toSvgProjection([ + { + name: "Plate & ring", + color: "#d41721", + polygons: [ + [[-5, -3], [5, -3], [5, 3], [-5, 3]], + [[-2, -1], [-2, 1], [2, 1], [2, -1]], + ], + }, + ], "Fixture "); + + expect(svg).toContain('version="1.1"'); + expect(svg).toContain('width="10mm" height="6mm" viewBox="-5 -3 10 6"'); + expect(svg).toContain('fill-rule="evenodd"'); + expect(svg).toContain('data-name="Plate & ring"'); + expect(svg).toContain("Fixture <top>"); + expect(svg.match(/M/g)).toHaveLength(2); + }); + + it("rejects empty and zero-area projections", () => { + expect(() => toSvgProjection([])).toThrow(/no readable contours/i); + expect(() => toSvgProjection([{ name: "Line", color: "bad", polygons: [[[0, 0], [1, 0], [2, 0]]] }])).toThrow(/visible area/i); + }); +}); diff --git a/tests/unit/svgImport.test.ts b/tests/unit/svgImport.test.ts index 533fa64..b61f14c 100644 --- a/tests/unit/svgImport.test.ts +++ b/tests/unit/svgImport.test.ts @@ -4,12 +4,13 @@ import { MAX_SVG_GEOMETRY_ELEMENTS, analyzeTriangleSoup, buildSvgExtrusionFromPaths, + normalizeSvgDocumentType, normalizeSvgUseReferences, validateClosedSolidTriangleSoup, validateSvgSourcePreflight, } from "@/lib/svgImport"; -function shapePath(points: Array<[number, number]>, options: { closed?: boolean; fill?: string; fillOpacity?: number; opacity?: number } = {}) { +function shapePath(points: Array<[number, number]>, options: { closed?: boolean; fill?: string; fillOpacity?: number; opacity?: number; stroke?: string; strokeOpacity?: number; strokeWidth?: number } = {}) { const path = new THREE.ShapePath(); path.moveTo(points[0][0], points[0][1]); for (const [x, y] of points.slice(1)) path.lineTo(x, y); @@ -19,6 +20,9 @@ function shapePath(points: Array<[number, number]>, options: { closed?: boolean; fill: options.fill ?? "#000", fillOpacity: options.fillOpacity ?? 1, opacity: options.opacity ?? 1, + stroke: options.stroke, + strokeOpacity: options.strokeOpacity ?? 1, + strokeWidth: options.strokeWidth ?? 1, visibility: "visible", }, }; @@ -50,11 +54,25 @@ function geometryPositions(geometry: THREE.BufferGeometry) { } describe("SVG source preflight", () => { - it("rejects XML entities and external references", () => { - expect(() => validateSvgSourcePreflight(']>')).toThrow(/document types and entities/i); + it("accepts and removes the standard SVG 1.1 document type", () => { + const source = ` + +`; + expect(() => validateSvgSourcePreflight(source)).not.toThrow(); + expect(normalizeSvgDocumentType(source)).not.toMatch(/ { + expect(() => validateSvgSourcePreflight(']>')).toThrow(/entities/i); + expect(() => validateSvgSourcePreflight('')).toThrow(/only the standard SVG 1\.1 document type/i); expect(() => validateSvgSourcePreflight('')).toThrow(/external references/i); }); + it("reports malformed Tinkercad cross-section geometry", () => { + expect(() => validateSvgSourcePreflight('')).toThrow(/workplane intersects the model/i); + }); + it("rejects excessive geometry before SVGLoader runs", () => { const source = `${"".repeat(MAX_SVG_GEOMETRY_ELEMENTS + 1)}`; expect(() => validateSvgSourcePreflight(source)).toThrow(/too many geometry elements/i); @@ -85,10 +103,28 @@ describe("SVG path extrusion", () => { }); it("ignores non-filled and fully transparent paths", () => { - expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "none" })])).toThrow(/no readable visible filled paths/i); - expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { opacity: 0 })])).toThrow(/no readable visible filled paths/i); - expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fillOpacity: 0 })])).toThrow(/no readable visible filled paths/i); - expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "#00000000" })])).toThrow(/no readable visible filled paths/i); + expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "none" })])).toThrow(/no readable visible/i); + expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { opacity: 0 })])).toThrow(/no readable visible/i); + expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fillOpacity: 0 })])).toThrow(/no readable visible/i); + expect(() => buildSvgExtrusionFromPaths([rectangle(0, 0, 10, 10, { fill: "#00000000" })])).toThrow(/no readable visible/i); + }); + + it("imports a closed Tinkercad-style stroke as an extrusion profile", () => { + const tinkercadOutline = shapePath([[0, 0], [10, 0], [10, 6], [0, 6], [0, 0]], { + closed: false, + fill: "none", + stroke: "rgb(255,0,0)", + strokeWidth: 0.001, + }); + const result = buildSvgExtrusionFromPaths([tinkercadOutline]); + expect(result.analysis.width).toBeCloseTo(10); + expect(result.analysis.depth).toBeCloseTo(6); + expect(result.analysis.volume).toBeCloseTo(240); + }); + + it("explains how to fix an open stroke-only SVG", () => { + const openStroke = shapePath([[0, 0], [10, 0], [5, 5]], { closed: false, fill: "none", stroke: "#000", strokeWidth: 1 }); + expect(() => buildSvgExtrusionFromPaths([openStroke])).toThrow(/only open strokes/i); }); it("imports open filled contours when they enclose usable area and skips lines", () => {