some fixes
Browse filesFiles changed (9)
- app/actions/projects.ts-32
- app/api/ask/route.ts+31-12
- app/api/me/projects/[namespace]/[repoId]/commits/[commitId]/promote/route.ts+21-17
- app/api/me/projects/[namespace]/[repoId]/images/route.ts+16-12
- app/api/me/projects/[namespace]/[repoId]/route.ts+7-41
- app/api/me/projects/route.ts+3-8
- app/api/proxy/route.ts+2-8
- components/editor/preview/index.tsx+1
- hooks/useAi.ts+5-2
18 unmodified lines19202122232425262728293031323334353637383940414243444546474849505152535455565718 unmodified lines};}// await dbConnect();// const projects = await Project.find({// user_id: user?.id,// })// .sort({ _createdAt: -1 })// .limit(100)// .lean();// if (!projects) {// return {// ok: true,// isEmpty: true,// projects: [],// };// }// const mappedProjects = []// for (const project of projects) {// const space = await spaceInfo({// name: project.space_id,// accessToken: user.token as string,// additionalFields: ["author", "cardData"],// });// if (!space.private) {// mappedProjects.push({// ...project,// name: space.name,// cardData: space.cardData,// });// }// }const projects = [];// get user spaces from Hugging Facefor await (const space of listSpaces({accessToken: user.token as string,additionalFields: ["author", "cardData"],18 unmodified lines1920212223242518 unmodified lines};}const projects = [];for await (const space of listSpaces({accessToken: user.token as string,additionalFields: ["author", "cardData"],
102 unmodified lines10310410510610710810911022 unmodified lines133134135136137138139137 unmodified lines27727827928028128217 unmodified lines30030130230330430530674 unmodified lines38138238338438538638738838939039139239339439571 unmodified lines467468469470471472473474475476477478479480481102 unmodified linesrewrittenPrompt = await rewritePrompt(prompt, enhancedSettings, { token, billTo }, selectedModel.value, selectedProvider);}console.log(rewrittenPrompt);try {const encoder = new TextEncoder();const stream = new TransformStream();22 unmodified lines},{role: "user",content: `${rewritePrompt}${redesignMarkdown ? `\n\nHere is my current design as a markdown:\n\n${redesignMarkdown}\n\nNow, please create a new design based on this markdown. Use the images in the markdown.` : ""}`},],max_tokens: selectedProvider.max_tokens,137 unmodified linesconst client = new InferenceClient(token);const selectedProvider = await getBestProvider(selectedModel.value, provider)try {17 unmodified linescontent: `${selectedElementHtml? `\n\nYou have to update ONLY the following element, NOTHING ELSE: \n\n\`\`\`html\n${selectedElementHtml}\n\`\`\``: ""}. Current pages: ${pages?.map((p: Page) => `- ${p.path} \n${p.html}`).join("\n")}. ${files?.length > 0 ? `Current images: ${files?.map((f: string) => `- ${f}`).join("\n")}.` : ""}`,},74 unmodified linespageHtml = `${replaceBlock}\n${pageHtml}`;updatedLines.push([1, replaceBlock.split("\n").length]);} else {const blockPosition = pageHtml.indexOf(searchBlock);if (blockPosition !== -1) {const beforeText = pageHtml.substring(0, blockPosition);const startLineNumber = beforeText.split("\n").length;const replaceLines = replaceBlock.split("\n").length;const endLineNumber = startLineNumber + replaceLines - 1;updatedLines.push([startLineNumber, endLineNumber]);pageHtml = pageHtml.replace(searchBlock, replaceBlock);}}71 unmodified linesnewHtml = `${replaceBlock}\n${newHtml}`;updatedLines.push([1, replaceBlock.split("\n").length]);} else {const blockPosition = newHtml.indexOf(searchBlock);if (blockPosition !== -1) {const beforeText = newHtml.substring(0, blockPosition);const startLineNumber = beforeText.split("\n").length;const replaceLines = replaceBlock.split("\n").length;const endLineNumber = startLineNumber + replaceLines - 1;updatedLines.push([startLineNumber, endLineNumber]);newHtml = newHtml.replace(searchBlock, replaceBlock);}}102 unmodified lines10310410510610710822 unmodified lines131132133134135136137137 unmodified lines27527627727827928028128228328428528628728828929029129229329429517 unmodified lines31331431531631731831974 unmodified lines39439539639739839940040140240340440540640740840941041171 unmodified lines483484485486487488489490491492493494495496497498499500102 unmodified linesrewrittenPrompt = await rewritePrompt(prompt, enhancedSettings, { token, billTo }, selectedModel.value, selectedProvider);}try {const encoder = new TextEncoder();const stream = new TransformStream();22 unmodified lines},{role: "user",content: `${rewrittenPrompt}${redesignMarkdown ? `\n\nHere is my current design as a markdown:\n\n${redesignMarkdown}\n\nNow, please create a new design based on this markdown. Use the images in the markdown.` : ""}`},],max_tokens: selectedProvider.max_tokens,137 unmodified linesconst client = new InferenceClient(token);// Helper function to escape regex special charactersconst escapeRegExp = (string: string) => {return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');};// Helper function to create flexible HTML regex that handles varying spacesconst createFlexibleHtmlRegex = (searchBlock: string) => {let searchRegex = escapeRegExp(searchBlock).replace(/\s+/g, '\\s*') // Allow any amount of whitespace where there are spaces.replace(/>\s*</g, '>\\s*<') // Allow spaces between HTML tags.replace(/\s*>/g, '\\s*>'); // Allow spaces before closing >return new RegExp(searchRegex, 'g');};const selectedProvider = await getBestProvider(selectedModel.value, provider)try {17 unmodified linescontent: `${selectedElementHtml? `\n\nYou have to update ONLY the following element, NOTHING ELSE: \n\n\`\`\`html\n${selectedElementHtml}\n\`\`\` Could be in multiple pages, if so, update all the pages.`: ""}. Current pages: ${pages?.map((p: Page) => `- ${p.path} \n${p.html}`).join("\n")}. ${files?.length > 0 ? `Current images: ${files?.map((f: string) => `- ${f}`).join("\n")}.` : ""}`,},74 unmodified linespageHtml = `${replaceBlock}\n${pageHtml}`;updatedLines.push([1, replaceBlock.split("\n").length]);} else {const regex = createFlexibleHtmlRegex(searchBlock);const match = regex.exec(pageHtml);if (match) {const matchedText = match[0];const beforeText = pageHtml.substring(0, match.index);const startLineNumber = beforeText.split("\n").length;const replaceLines = replaceBlock.split("\n").length;const endLineNumber = startLineNumber + replaceLines - 1;updatedLines.push([startLineNumber, endLineNumber]);pageHtml = pageHtml.replace(matchedText, replaceBlock);}}71 unmodified linesnewHtml = `${replaceBlock}\n${newHtml}`;updatedLines.push([1, replaceBlock.split("\n").length]);} else {const regex = createFlexibleHtmlRegex(searchBlock);const match = regex.exec(newHtml);if (match) {const matchedText = match[0];const beforeText = newHtml.substring(0, match.index);const startLineNumber = beforeText.split("\n").length;const replaceLines = replaceBlock.split("\n").length;const endLineNumber = startLineNumber + replaceLines - 1;updatedLines.push([startLineNumber, endLineNumber]);newHtml = newHtml.replace(matchedText, replaceBlock);}}
12345678911 unmodified lines2122232425262728293031323334353637383940414243444546474867 unmodified lines116117118119120121122import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, listFiles, uploadFiles } from "@huggingface/hub";import { isAuthenticated } from "@/lib/auth";import Project from "@/models/Project";import dbConnect from "@/lib/mongodb";export async function POST(req: NextRequest,11 unmodified linesreturn NextResponse.json({ message: "Unauthorized" }, { status: 401 });}await dbConnect();const param = await params;const { namespace, repoId, commitId } = param;const project = await Project.findOne({user_id: user.id,space_id: `${namespace}/${repoId}`,}).lean();if (!project) {return NextResponse.json({ ok: false, error: "Project not found" },{ status: 404 });}try {const repo: RepoDesignation = {type: "space",name: `${namespace}/${repoId}`,};// Fetch files from the specific commitconst files: File[] = [];const allowedExtensions = ["html", "md", "css", "js", "json", "txt"];67 unmodified lines);} catch (error: any) {console.error("Error promoting version:", error);// Handle specific HuggingFace API errorsif (error.statusCode === 404) {123456711 unmodified lines192021222324252627282930313233343536373839404142434445464748495051525367 unmodified lines121122123124125126import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, listFiles, spaceInfo, uploadFiles } from "@huggingface/hub";import { isAuthenticated } from "@/lib/auth";export async function POST(req: NextRequest,11 unmodified linesreturn NextResponse.json({ message: "Unauthorized" }, { status: 401 });}const param = await params;const { namespace, repoId, commitId } = param;try {const repo: RepoDesignation = {type: "space",name: `${namespace}/${repoId}`,};const space = await spaceInfo({name: `${namespace}/${repoId}`,accessToken: user.token as string,additionalFields: ["author"],});if (!space || space.sdk !== "static") {return NextResponse.json({ ok: false, error: "Space is not a static space." },{ status: 404 });}if (space.author !== user.name) {return NextResponse.json({ ok: false, error: "Space does not belong to the authenticated user." },{ status: 403 });}// Fetch files from the specific commitconst files: File[] = [];const allowedExtensions = ["html", "md", "css", "js", "json", "txt"];67 unmodified lines);} catch (error: any) {// Handle specific HuggingFace API errorsif (error.statusCode === 404) {
1234510 unmodified lines161718192021222324252627282930313233343536373839import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, uploadFiles } from "@huggingface/hub";import { isAuthenticated } from "@/lib/auth";import Project from "@/models/Project";10 unmodified linesreturn NextResponse.json({ message: "Unauthorized" }, { status: 401 });}await dbConnect();const param = await params;const { namespace, repoId } = param;const project = await Project.findOne({user_id: user.id,space_id: `${namespace}/${repoId}`,}).lean();if (!project) {return NextResponse.json({ok: false,error: "Project not found",},{ status: 404 });}// Parse the FormData to get the imagesconst formData = await req.formData();1234510 unmodified lines16171819202122232425262728293031323334353637383940414243import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, spaceInfo, uploadFiles } from "@huggingface/hub";import { isAuthenticated } from "@/lib/auth";import Project from "@/models/Project";10 unmodified linesreturn NextResponse.json({ message: "Unauthorized" }, { status: 401 });}const param = await params;const { namespace, repoId } = param;const space = await spaceInfo({name: `${namespace}/${repoId}`,accessToken: user.token as string,additionalFields: ["author"],});if (!space || space.sdk !== "static") {return NextResponse.json({ ok: false, error: "Space is not a static space." },{ status: 404 });}if (space.author !== user.name) {return NextResponse.json({ ok: false, error: "Space does not belong to the authenticated user." },{ status: 403 });}// Parse the FormData to get the imagesconst formData = await req.formData();
1234567896 unmodified lines1617181920212223242526272829303132333435363731 unmodified lines697071727374757677787914 unmodified lines94959697989910010110210310410510610710810911011111211311411511686 unmodified lines2032042052062072082092102112125 unmodified lines218219220221222223224225226227import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, spaceInfo, uploadFiles, listFiles, deleteRepo, listCommits } from "@huggingface/hub";import { isAuthenticated } from "@/lib/auth";import Project from "@/models/Project";import dbConnect from "@/lib/mongodb";import { Commit, Page } from "@/types";export async function DELETE(6 unmodified linesreturn NextResponse.json({ message: "Unauthorized" }, { status: 401 });}await dbConnect();const param = await params;const { namespace, repoId } = param;const project = await Project.findOne({user_id: user.id,space_id: `${namespace}/${repoId}`,}).lean();if (!project) {return NextResponse.json({ ok: false, error: "Project not found" },{ status: 404 });}try {const space = await spaceInfo({name: `${namespace}/${repoId}`,31 unmodified linesrepo,accessToken: user.token as string,});await Project.deleteOne({user_id: user.id,space_id: `${namespace}/${repoId}`,});return NextResponse.json({ ok: true }, { status: 200 });} catch (error: any) {14 unmodified linesreturn NextResponse.json({ message: "Unauthorized" }, { status: 401 });}await dbConnect();const param = await params;const { namespace, repoId } = param;const project = await Project.findOne({user_id: user.id,space_id: `${namespace}/${repoId}`,}).lean();if (!project) {return NextResponse.json({ok: false,error: "Project not found",},{ status: 404 });}try {const space = await spaceInfo({name: namespace + "/" + repoId,86 unmodified lines{ status: 404 });}return NextResponse.json({project,pages: htmlFiles,files,commits,5 unmodified lines// eslint-disable-next-line @typescript-eslint/no-explicit-any} catch (error: any) {if (error.statusCode === 404) {await Project.deleteOne({user_id: user.id,space_id: `${namespace}/${repoId}`,});return NextResponse.json({ error: "Space not found", ok: false },{ status: 404 }12345676 unmodified lines14151617181920212231 unmodified lines5455565758596014 unmodified lines75767778798081828386 unmodified lines1701711721731741751761771781791801811825 unmodified lines188189190191192193import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, spaceInfo, listFiles, deleteRepo, listCommits } from "@huggingface/hub";import { isAuthenticated } from "@/lib/auth";import { Commit, Page } from "@/types";export async function DELETE(6 unmodified linesreturn NextResponse.json({ message: "Unauthorized" }, { status: 401 });}const param = await params;const { namespace, repoId } = param;try {const space = await spaceInfo({name: `${namespace}/${repoId}`,31 unmodified linesrepo,accessToken: user.token as string,});return NextResponse.json({ ok: true }, { status: 200 });} catch (error: any) {14 unmodified linesreturn NextResponse.json({ message: "Unauthorized" }, { status: 401 });}const param = await params;const { namespace, repoId } = param;try {const space = await spaceInfo({name: namespace + "/" + repoId,86 unmodified lines{ status: 404 });}return NextResponse.json({project: {id: space.id,space_id: space.name,_updatedAt: space.updatedAt,},pages: htmlFiles,files,commits,5 unmodified lines// eslint-disable-next-line @typescript-eslint/no-explicit-any} catch (error: any) {if (error.statusCode === 404) {return NextResponse.json({ error: "Space not found", ok: false },{ status: 404 }
1 unmodified line234567895 unmodified lines1516171819202148 unmodified lines7071727374757677787911 unmodified lines919293949596971 unmodified lineimport { RepoDesignation, createRepo, listCommits, uploadFiles } from "@huggingface/hub";import { isAuthenticated } from "@/lib/auth";import Project from "@/models/Project";import dbConnect from "@/lib/mongodb";import { Commit, Page } from "@/types";import { COLORS } from "@/lib/utils";5 unmodified linesreturn NextResponse.json({ message: "Unauthorized" }, { status: 401 });}await dbConnect();const { title: titleFromRequest, pages, prompt } = await req.json();const title = titleFromRequest ?? "DeepSite Project";48 unmodified lines});const path = repoUrl.split("/").slice(-2).join("/");const project = await Project.create({user_id: user.id,space_id: path,});const commits: Commit[] = [];for await (const commit of listCommits({ repo, accessToken: user.token as string })) {11 unmodified linesfiles,pages,commits,project,}return NextResponse.json({ space: newProject, path, ok: true }, { status: 201 });1 unmodified line2345675 unmodified lines13141516171848 unmodified lines67686970717211 unmodified lines8485868788899091921 unmodified lineimport { RepoDesignation, createRepo, listCommits, uploadFiles } from "@huggingface/hub";import { isAuthenticated } from "@/lib/auth";import { Commit, Page } from "@/types";import { COLORS } from "@/lib/utils";5 unmodified linesreturn NextResponse.json({ message: "Unauthorized" }, { status: 401 });}const { title: titleFromRequest, pages, prompt } = await req.json();const title = titleFromRequest ?? "DeepSite Project";48 unmodified lines});const path = repoUrl.split("/").slice(-2).join("/");const commits: Commit[] = [];for await (const commit of listCommits({ repo, accessToken: user.token as string })) {11 unmodified linesfiles,pages,commits,project: {}}return NextResponse.json({ space: newProject, path, ok: true }, { status: 201 });
79 unmodified lines80818283848586878889909192936 unmodified lines10010110210310410510610710810924 unmodified lines13413513613713813914054 unmodified lines19519619719819920020120220320420520620720879 unmodified lines<script>// Add event listeners and communicate with parentdocument.addEventListener('DOMContentLoaded', function() {console.log('DOM loaded, setting up communication');let hoveredElement = null;let isEditModeEnabled = false;document.addEventListener('mouseover', function(event) {if (event.target !== document.body && event.target !== document.documentElement) {hoveredElement = event.target;console.log('Element hovered:', event.target.tagName, 'Edit mode:', isEditModeEnabled);const rect = event.target.getBoundingClientRect();const message = {6 unmodified lineswidth: rect.width,height: rect.height},element: event.target.outerHTML.substring(0, 200)}};console.log('Sending message to parent:', message);parent.postMessage(message, '*');}});24 unmodified lineswidth: rect.width,height: rect.height},element: event.target.outerHTML.substring(0, 200)}}, '*');} else {54 unmodified lines// Listen for messages from parentwindow.addEventListener('message', function(event) {console.log('Iframe received message from parent:', event.data);if (event.data.type === 'ENABLE_EDIT_MODE') {console.log('Enabling edit mode');isEditModeEnabled = true;document.body.style.userSelect = 'none';document.body.style.pointerEvents = 'auto';} else if (event.data.type === 'DISABLE_EDIT_MODE') {console.log('Disabling edit mode');isEditModeEnabled = false;document.body.style.userSelect = '';document.body.style.pointerEvents = '';79 unmodified lines8081828384858687888990916 unmodified lines989910010110210310410510624 unmodified lines13113213313413513613754 unmodified lines19219319419519619719819920020120279 unmodified lines<script>// Add event listeners and communicate with parentdocument.addEventListener('DOMContentLoaded', function() {let hoveredElement = null;let isEditModeEnabled = false;document.addEventListener('mouseover', function(event) {if (event.target !== document.body && event.target !== document.documentElement) {hoveredElement = event.target;const rect = event.target.getBoundingClientRect();const message = {6 unmodified lineswidth: rect.width,height: rect.height},element: event.target.outerHTML}};parent.postMessage(message, '*');}});24 unmodified lineswidth: rect.width,height: rect.height},element: event.target.outerHTML}}, '*');} else {54 unmodified lines// Listen for messages from parentwindow.addEventListener('message', function(event) {if (event.data.type === 'ENABLE_EDIT_MODE') {isEditModeEnabled = true;document.body.style.userSelect = 'none';document.body.style.pointerEvents = 'auto';} else if (event.data.type === 'DISABLE_EDIT_MODE') {isEditModeEnabled = false;document.body.style.userSelect = '';document.body.style.pointerEvents = '';
91 unmodified lines92939495969791 unmodified linesconst mockElement = {tagName: data.tagName,getBoundingClientRect: () => data.rect,};setSelectedElement(mockElement as any);setIsEditableModeEnabled(false);91 unmodified lines9293949596979891 unmodified linesconst mockElement = {tagName: data.tagName,getBoundingClientRect: () => data.rect,outerHTML: data.element,};setSelectedElement(mockElement as any);setIsEditableModeEnabled(false);
249 unmodified lines2502512522532542559 unmodified lines26526626726826927027139 unmodified lines311312313314315316317249 unmodified linesconst callAiFollowUp = async (prompt: string, enhancedSettings?: EnhancedSettings) => {if (isAiWorking) return;if (!prompt.trim()) return;setIsAiWorking(true);9 unmodified linespreviousPrompts: prompts,model,pages,selectedElementHtml: selectedElement,files: selectedFiles,repoId: project?.space_id}),39 unmodified linessetIsEditableModeEnabled(false);if (audio.current) audio.current.play();if (iframe) {iframe.src = iframe.src;}return { success: true, html: res.html, updatedLines: res.updatedLines };249 unmodified lines2502512522532542552569 unmodified lines26626726826927027127239 unmodified lines312313314315316317318319320249 unmodified linesconst callAiFollowUp = async (prompt: string, enhancedSettings?: EnhancedSettings) => {if (isAiWorking) return;if (!prompt.trim()) return;setIsAiWorking(true);9 unmodified linespreviousPrompts: prompts,model,pages,selectedElementHtml: selectedElement?.outerHTML,files: selectedFiles,repoId: project?.space_id}),39 unmodified linessetIsEditableModeEnabled(false);if (audio.current) audio.current.play();if (iframe) {setTimeout(() => {iframe.src = iframe.src;}, 500);}return { success: true, html: res.html, updatedLines: res.updatedLines };
app/actions/projects.ts-32
app/api/ask/route.ts+31-12
app/api/me/projects/[namespace]/[repoId]/commits/[commitId]/promote/route.ts+21-17
app/api/me/projects/[namespace]/[repoId]/images/route.ts+16-12
app/api/me/projects/[namespace]/[repoId]/route.ts+7-41
app/api/me/projects/route.ts+3-8
app/api/proxy/route.ts+2-8
components/editor/preview/index.tsx+1
hooks/useAi.ts+5-2