@w3kits-com/plugin-opendesign 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- (globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,70904,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"BailoutToCSR",{enumerable:!0,get:function(){return a}});let r=e.r(40594);function a({reason:e,children:t}){if("u"<typeof window)throw Object.defineProperty(new r.BailoutToCSRError(e),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return t}},12171,(e,t,n)=>{"use strict";function r(e){return e.split("/").map(e=>encodeURIComponent(e)).join("/")}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"encodeURIPath",{enumerable:!0,get:function(){return r}})},18456,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"PreloadChunks",{enumerable:!0,get:function(){return l}});let r=e.r(17580),a=e.r(19101),i=e.r(45891),o=e.r(12171),s=e.r(36114);function l({moduleIds:e}){if("u">typeof window)return null;let t=i.workAsyncStorage.getStore();if(void 0===t)return null;let n=[];if(t.reactLoadableManifest&&e){let r=t.reactLoadableManifest;for(let t of e){if(!r[t])continue;let e=r[t].files;n.push(...e)}}if(0===n.length)return null;let d=(0,s.getAssetTokenQuery)();return(0,r.jsx)(r.Fragment,{children:n.map(e=>{let n=`${t.assetPrefix}/_next/${(0,o.encodeURIPath)(e)}${d}`;return e.endsWith(".css")?(0,r.jsx)("link",{precedence:"dynamic",href:n,rel:"stylesheet",as:"style",nonce:t.nonce},e):((0,a.preload)(n,{as:"script",fetchPriority:"low",nonce:t.nonce}),null)})})}},21950,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return d}});let r=e.r(17580),a=e.r(62174),i=e.r(70904),o=e.r(18456);function s(e){return{default:e&&"default"in e?e.default:e}}let l={loader:()=>Promise.resolve(s(()=>null)),loading:null,ssr:!0},d=function(e){let t={...l,...e},n=(0,a.lazy)(()=>t.loader().then(s)),d=t.loading;function c(e){let s=d?(0,r.jsx)(d,{isLoading:!0,pastDelay:!0,error:null}):null,l=!t.ssr||!!t.loading,c=l?a.Suspense:a.Fragment,u=t.ssr?(0,r.jsxs)(r.Fragment,{children:["u"<typeof window?(0,r.jsx)(o.PreloadChunks,{moduleIds:t.modules}):null,(0,r.jsx)(n,{...e})]}):(0,r.jsx)(i.BailoutToCSR,{reason:"next/dynamic",children:(0,r.jsx)(n,{...e})});return(0,r.jsx)(c,{...l?{fallback:s}:{},children:u})}return c.displayName="LoadableComponent",c}},8726,(e,t,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return a}});let r=e.r(81258)._(e.r(21950));function a(e,t){let n={};"function"==typeof e&&(n.loader=e);let a={...n,...t};return(0,r.default)({...a,modules:a.loadableGenerated?.modules})}("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),t.exports=n.default)},13903,e=>{"use strict";var t=e.i(17580),n=e.i(8726);let r=new TextEncoder;new TextDecoder;let a=0,i=new Map;function o(){return window.parent&&window.parent!==window?window.parent:null}async function s(e){let t;(t=window).__w3kitsBridgeListenerInstalled||(t.__w3kitsBridgeListenerInstalled=!0,window.addEventListener("message",e=>{let t=e.data;if(!t||"W3KITS_RESPONSE"!==t.type||"string"!=typeof t.requestId)return;let n=i.get(t.requestId);n&&(i.delete(t.requestId),clearTimeout(n.timeout),n.resolve(t))}));let n=o();if(!n)throw Error("W3Kits runtime is only available inside the W3Kits plugin iframe.");let r=(a+=1,`opendesign_${Date.now().toString(36)}_${a.toString(36)}`),s=await new Promise((t,a)=>{let o=setTimeout(()=>{i.delete(r),a(Error("W3Kits runtime request timed out."))},3e4);i.set(r,{resolve:t,reject:a,timeout:o}),n.postMessage({version:1,...e,requestId:r},"*")});if(!s.ok)throw Error(s.error?.message||s.error?.code||"W3Kits runtime request failed.");return s.data}async function l(e){try{let t=await s({type:"W3KITS_RUNTIME_FS_READ",path:e});if(t.bodyBase64)return function(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}(t.bodyBase64);return r.encode(t.body??"")}catch(e){if(e instanceof Error&&/not found/i.test(e.message))return null;throw e}}async function d(e,t,n={}){let a="string"==typeof t?r.encode(t):t;return(await s({type:"W3KITS_RUNTIME_FS_WRITE",path:e,bodyBase64:function(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}(a),contentType:n.contentType,expectedEtag:n.expectedEtag})).metadata}async function c(e="/workspace"){return(await s({type:"W3KITS_RUNTIME_FS_LIST",path:e})).entries??[]}async function u(){return s({type:"W3KITS_RUNTIME_FS_SYNC"})}var p=new TextEncoder,f=new TextDecoder,h=class extends Error{constructor(e,t){super(t),this.code=e,this.name="BrowserVfsError"}code};function w(e){let t=e.trim();if(!t)throw new h("invalid_path","Workspace path is required");if("/"===t)return"/";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))throw new h("invalid_path","Workspace path must not be a URL");if(t.includes("\\"))throw new h("invalid_path","Workspace path must use forward slashes");let n=t.split("/").filter(Boolean);if(0===n.length)throw new h("invalid_path","Workspace path is required");for(let e of n){if("."===e||".."===e)throw new h("path_traversal","Workspace path must not traverse directories");if(!/^[A-Za-z0-9._@=,+~ -]+$/.test(e))throw new h("invalid_path","Workspace path contains unsupported characters")}return"/"+n.join("/")}function y(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}async function m(e){let t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e);try{let e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,"0")).join("")}catch{let t=0x811c9dc5;for(let n of e)t^=n,t=Math.imul(t,0x1000193)>>>0;return t.toString(16).padStart(8,"0")}}function g(e,t,n={}){return m(t).then(r=>{let a=new Date().toISOString();return{path:e,size:t.byteLength,etag:r,revision:a+"-"+r.slice(0,12),updatedAt:a,...n.contentType?{contentType:n.contentType}:{}}})}function b(e,t){let n=new Set,r="/"===t?"/":t.replace(/\/$/,"");for(let t of e){if(!y(t.path,r))continue;let e="/"===r?t.path.slice(1):t.path.slice(r.length+1),[a]=e.split("/");a&&e.includes("/")&&n.add(("/"===r?"":r)+"/"+a)}let a=new Date(0).toISOString();return Array.from(n,e=>({kind:"directory",path:e,size:0,etag:"",revision:"",updatedAt:a})).sort((e,t)=>e.path.localeCompare(t.path))}var x=class{files=new Map;async stat(e){return this.files.get(w(e))?.metadata??null}async readFile(e){let t=this.files.get(w(e));return t?new Uint8Array(t.body):null}async writeFile(e,t,n={}){let r=w(e);if("/"===r)throw new h("invalid_path","Workspace file path must not be root");let a=new Uint8Array(t),i=await g(r,a,n);return this.files.set(r,{body:a,metadata:i}),i}async deleteFile(e){return this.files.delete(w(e))}async listFiles(e="/"){let t=w(e),n=Array.from(this.files.values(),e=>({...e.metadata,kind:"file"})),r=n.filter(e=>{if(!y(e.path,t))return!1;let n="/"===t?e.path.slice(1):e.path.slice(t.length+1);return n.length>0&&!n.includes("/")});return[...b(n,t),...r].sort((e,t)=>e.path.localeCompare(t.path))}async clear(){this.files.clear()}},v=class e{constructor(e){this.root=e}root;index=null;static async create(t={}){let n=t.globalScope??globalThis,r=n.navigator?.storage?.getDirectory;if("function"!=typeof r)throw new h("opfs_unavailable","OPFS is not available");let a=await r.call(n.navigator.storage);return new e(await a.getDirectoryHandle(t.namespace??"default",{create:!0}))}async filesDirectory(){return this.root.getDirectoryHandle("files",{create:!0})}async readIndex(){if(this.index)return this.index;try{let e=await this.root.getFileHandle("index.json"),t=await e.getFile(),n=f.decode(await t.arrayBuffer()),r=JSON.parse(n);this.index=new Map(r.map(e=>[e.path,e]))}catch{this.index=new Map}return this.index}async writeIndex(){let e=await this.readIndex(),t=await this.root.getFileHandle("index.json",{create:!0}),n=await t.createWritable();await n.write(p.encode(JSON.stringify(Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))))),await n.close()}fileName(e){return encodeURIComponent(e)}async stat(e){return(await this.readIndex()).get(w(e))??null}async readFile(e){let t=w(e);if(!(await this.readIndex()).has(t))return null;try{let e=await (await this.filesDirectory()).getFileHandle(this.fileName(t)),n=await e.getFile();return new Uint8Array(await n.arrayBuffer())}catch{return null}}async writeFile(e,t,n={}){let r=w(e);if("/"===r)throw new h("invalid_path","Workspace file path must not be root");let a=new Uint8Array(t),i=await g(r,a,n),o=await (await this.filesDirectory()).getFileHandle(this.fileName(r),{create:!0}),s=await o.createWritable();return await s.write(a),await s.close(),(await this.readIndex()).set(r,i),await this.writeIndex(),i}async deleteFile(e){let t=w(e);return!!(await this.readIndex()).delete(t)&&(await (await this.filesDirectory()).removeEntry?.(this.fileName(t)),await this.writeIndex(),!0)}async listFiles(e="/"){let t=w(e),n=Array.from((await this.readIndex()).values(),e=>({...e,kind:"file"})),r=n.filter(e=>{if(!y(e.path,t))return!1;let n="/"===t?e.path.slice(1):e.path.slice(t.length+1);return n.length>0&&!n.includes("/")});return[...b(n,t),...r].sort((e,t)=>e.path.localeCompare(t.path))}async clear(){for(let e of Array.from((await this.readIndex()).keys()))await (await this.filesDirectory()).removeEntry?.(this.fileName(e));this.index=new Map,await this.writeIndex()}};function S(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??new h("indexeddb_error","IndexedDB request failed"))})}var k=class e{constructor(e){this.db=e}db;static async create(t={}){let n=(t.globalScope??globalThis).indexedDB;if("function"!=typeof n?.open)throw new h("indexeddb_unavailable","IndexedDB is not available");let r=n.open("w3kits-browser-vfs:"+(t.namespace??"default"),1);return r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains("files")||e.createObjectStore("files",{keyPath:"path"})},new e(await S(r))}store(e){let t=this.db.transaction("files",e);return{store:t.objectStore("files"),done:new Promise((e,n)=>{t.oncomplete=()=>e(),t.onabort=()=>n(t.error??new h("indexeddb_aborted","IndexedDB transaction aborted")),t.onerror=()=>n(t.error??new h("indexeddb_error","IndexedDB transaction failed"))})}}async stat(e){let{store:t}=this.store("readonly"),n=await S(t.get(w(e)));return n?.metadata??null}async readFile(e){let{store:t}=this.store("readonly"),n=await S(t.get(w(e)));return n?new Uint8Array(n.body):null}async writeFile(e,t,n={}){let r=w(e);if("/"===r)throw new h("invalid_path","Workspace file path must not be root");let a=new Uint8Array(t),i=await g(r,a,n),{store:o,done:s}=this.store("readwrite"),l=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);return await S(o.put({path:r,body:l,metadata:i})),await s,i}async deleteFile(e){let t=w(e);if(!await this.stat(t))return!1;let{store:n,done:r}=this.store("readwrite");return await S(n.delete(t)),await r,!0}async listFiles(e="/"){let t=w(e),{store:n}=this.store("readonly"),r=(await S(n.getAll())).map(e=>({...e.metadata,kind:"file"})),a=r.filter(e=>{if(!y(e.path,t))return!1;let n="/"===t?e.path.slice(1):e.path.slice(t.length+1);return n.length>0&&!n.includes("/")});return[...b(r,t),...a].sort((e,t)=>e.path.localeCompare(t.path))}async clear(){let{store:e,done:t}=this.store("readwrite");await S(e.clear()),await t}};async function T(e={}){if(function(e=globalThis){return"function"==typeof e.navigator?.storage?.getDirectory}(e.globalScope??globalThis))try{return await v.create(e)}catch{}if(function(e=globalThis){return"function"==typeof e.indexedDB?.open}(e.globalScope??globalThis))try{return await k.create(e)}catch{}return new x}async function _(e,t){let n=[];for(let r of t){if("file"===r.kind){n.push(r);continue}n.push(...await _(e,await e.listFiles(r.path)))}return n.sort((e,t)=>e.path.localeCompare(t.path))}let j=async function e(t={}){return function(e=new x){let t=new Set;return{readFile:async t=>e.readFile(t),async readText(t){let n=await e.readFile(t);return n?f.decode(n):null},async writeFile(n,r,a){let i=await e.writeFile(n,"string"==typeof r?p.encode(r):r,a);return t.add(i.path),i},async deleteFile(n){let r=w(n),a=await e.deleteFile(r);return a&&t.add(r),a},stat:t=>e.stat(t),listFiles:t=>e.listFiles(t),dirtyPaths:()=>Array.from(t).sort(),markClean(e){if(!e)return void t.clear();for(let n of e)t.delete(w(n))},async exportSnapshot(){let t=await e.listFiles("/"),n=await _(e,t),r=[];for(let t of n){let n=await e.readFile(t.path);n&&r.push({path:t.path,contentBase64:function(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}(n),...t.contentType?{contentType:t.contentType}:{},updatedAt:t.updatedAt})}return p.encode(JSON.stringify({version:1,files:r}))},async importSnapshot(n,r={}){let a=JSON.parse("string"==typeof n?n:f.decode(n));if(1!==a.version||!Array.isArray(a.files))throw new h("invalid_snapshot","Unsupported workspace snapshot");for(let n of(await e.clear(),t.clear(),a.files)){let a=await e.writeFile(n.path,function(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}(n.contentBase64),n.contentType?{contentType:n.contentType}:{});r.markDirty&&t.add(a.path)}}}}(await T(t))}({namespace:"opendesign-w3kits-web-mode-v1"});function I(e){return"/workspace"+(e.startsWith("/")?e:"/"+e)}function A(e){return"/workspace"===e?"/":e.startsWith("/workspace/")?e.slice(10):e.startsWith("/")?e:"/"+e}function E(e){return{...e,path:I(e.path)}}async function O(){return j}async function W(e){let t=await O(),n=await t.readFile(A(e));if(n)return n;let r=await l(I(A(e)));return r&&await t.writeFile(A(e),r),r}async function P(e){let t=await W(e);return t?new TextDecoder().decode(t):null}async function U(e,t,n={}){return(await O()).writeFile(A(e),t,n)}async function F(e="/"){let t=await O(),n=await t.listFiles(A(e));if(n.length)return n.map(E);let r=await c(I(A(e))).catch(()=>[]);for(let e of r){if("file"!==e.kind)continue;let n=await l(e.path).catch(()=>null);n&&await t.writeFile(A(e.path),n,e.contentType?{contentType:e.contentType}:{})}return r}async function N(){let e=await O(),t=0,n=[];for(let r of e.dirtyPaths()){let a=await e.readFile(r);if(!a)continue;let i=await e.stat(r);try{await d(I(r),a,i?.contentType?{contentType:i.contentType}:{}),t+=1}catch(e){n.push({path:r,error:e instanceof Error?e.message:"upload_failed"})}}if(n.length>0)return{uploaded:t,deleted:0,retained:n.length,unauthenticated:!1,errors:n};let r=await u();return r.unauthenticated||0!==r.errors.length||e.markClean(),{...r,uploaded:t+r.uploaded}}var R=e.i(92180);let C="/workspace/projects/index.json",D=[],B="https://w3kits.com/api/ai/openai/v1",M="opendesign",K=null;function L(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json"}})}function q(e,t=200,n="text/plain;charset=utf-8"){return new Response(e,{status:t,headers:{"content-type":n}})}function J(){try{return new URL(B).origin}catch{return"https://w3kits.com"}}async function z(){let e=Date.now();if(K&&K.expiresAt-e>3e4)return K.value;let t=await function(e,t=1e4){if(window.parent===window)return Promise.reject(Error("W3Kits runtime bridge is unavailable."));let n="opendesign-"+Date.now()+"-"+Math.random().toString(36).slice(2),r=J();return new Promise((a,i)=>{let o=window.setTimeout(()=>{window.removeEventListener("message",s),i(Error("W3Kits runtime bridge timed out."))},t),s=e=>{if(e.source!==window.parent||e.origin!==r)return;let t=e.data;t?.type==="W3KITS_RESPONSE"&&t.requestId===n&&(window.clearTimeout(o),window.removeEventListener("message",s),t.ok?a(t.data):i(Error("string"==typeof t.error?.message?t.error.message:"string"==typeof t.error?.code?t.error.code:"W3Kits runtime bridge failed.")))};window.addEventListener("message",s),window.parent.postMessage({...e,version:1,requestId:n},r)})}({type:"W3KITS_RUNTIME_SESSION_REQUEST",pluginId:M,origin:window.location.origin});return K={value:t,expiresAt:e+1e3*Math.max(30,t.expiresIn-30)},t}async function H(){let e=await z(),t={"content-type":"application/json","x-w3kits-runtime-session":e.token,"x-w3kits-plugin-id":e.pluginId||M,"x-w3kits-plugin-version":e.pluginVersion};for(let[n,r]of Object.entries(e.identityHeaders||{}))"string"==typeof r&&r&&(t[n]=r);return e.packageName&&(t["x-w3kits-plugin-package"]=e.packageName),e.packageIntegrity&&(t["x-w3kits-plugin-integrity"]=e.packageIntegrity),t}function G(e,t){return"event: "+e+"\ndata: "+JSON.stringify(t)+"\n\n"}async function $(e,t){let n=await P(e);if(!n)return t;try{return JSON.parse(n)}catch{return t}}async function Z(e,t){await U(e,JSON.stringify(t,null,2),{contentType:"application/json"})}function Q(e){return{id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt,skillId:e.skillId,designSystemId:e.designSystemId,...e.pendingPrompt?{pendingPrompt:e.pendingPrompt}:{},...e.metadata?{metadata:e.metadata}:{}}}function V(e){return"/workspace/projects/"+e}function X(e,t){let n=t.replace(/^\/+/,"");return V(e)+"/files/"+n}async function Y(){return $(C,[])}async function ee(e){await Z(C,e)}async function et(e,t){let n=t.pathname.split("/").filter(Boolean),r=await Y();if("GET"===e.method&&2===n.length)return L({projects:r.map(Q)});if("POST"===e.method&&2===n.length){let t=await e.json().catch(()=>({})),n=Date.now(),a={id:t.id||(0,R.randomUUID)(),name:"string"==typeof t.name&&t.name.trim()?t.name.trim():"Untitled design",createdAt:n,updatedAt:n,skillId:t.skillId??null,designSystemId:t.designSystemId??null,pendingPrompt:"string"==typeof t.pendingPrompt?t.pendingPrompt:void 0,metadata:t.metadata};return await ee([a,...r.filter(e=>e.id!==a.id)]),await Z(V(a.id)+"/project.json",a),await U(X(a.id,"DESIGN.md"),"# "+a.name+"\n",{contentType:"text/markdown;charset=utf-8"}),L({project:Q(a),conversationId:(0,R.randomUUID)()})}let a=n[2];if(!a)return L({error:"not_found"},404);let i=r.find(e=>e.id===a);if(!i)return L({error:"project_not_found"},404);if("GET"===e.method&&3===n.length)return L({project:Q(i)});if("PATCH"===e.method&&3===n.length){let t=await e.json().catch(()=>({})),n={...i,...t,id:i.id,updatedAt:Date.now()};return await ee(r.map(e=>e.id===i.id?n:e)),await Z(V(i.id)+"/project.json",n),L({project:Q(n)})}if("GET"===e.method&&"files"===n[3])return L({files:(await F(V(a)+"/files")).filter(e=>"file"===e.kind).map(e=>({name:e.path.split("/").pop()||e.path,path:e.path.replace(V(a)+"/files/",""),kind:"file",size:e.size??0}))});if("POST"===e.method&&"files"===n[3]){let t=await e.json().catch(()=>({})),n=t.path||t.name||"untitled.txt";return await U(X(a,n),t.content??"",{contentType:"text/plain;charset=utf-8"}),L({ok:!0})}if("GET"===e.method&&"raw"===n[3]){let e=decodeURIComponent(n.slice(4).join("/")),t=await P(X(a,e));return null==t?q("Not found",404):q(t,200,en(e))}return L({error:"unsupported_in_w3kits_web_mode"},404)}function en(e){return e.endsWith(".html")?"text/html;charset=utf-8":e.endsWith(".css")?"text/css;charset=utf-8":e.endsWith(".js")||e.endsWith(".mjs")?"application/javascript;charset=utf-8":e.endsWith(".json")?"application/json":e.endsWith(".md")?"text/markdown;charset=utf-8":e.endsWith(".svg")?"image/svg+xml":e.endsWith(".png")?"image/png":e.endsWith(".jpg")||e.endsWith(".jpeg")?"image/jpeg":e.endsWith(".webp")?"image/webp":"text/plain;charset=utf-8"}async function er(e,t){let n;if("GET"!==e.method)return L({error:"method_not_allowed"},405);let r=t.pathname.split("/").filter(Boolean),a=r[1];try{n=decodeURIComponent(r.slice(2).join("/"))}catch{return q("Not found",404)}if(n=function(e){if(!e||e.includes("\\")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))return null;let t=e.split("/");return t.some(e=>!e||"."===e||".."===e)?null:t.join("/")}(n)??"",!a||!n)return q("Not found",404);for(let e of[X(a,".od/artifacts/"+n),V(a)+"/.od/artifacts/"+n,X(a,n)]){let t=await W(e);if(t)return new Response(t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),{status:200,headers:{"content-type":en(n)}})}return q("Not found",404)}async function ea(e){if("POST"!==e.method)return L({error:"method_not_allowed"},405);let t=await e.json().catch(()=>({})),n=[...t.systemPrompt?[{role:"system",content:t.systemPrompt}]:[],...(t.messages??[]).map(e=>({role:e.role,content:e.content}))],r=(t.baseUrl||B).replace(/\/+$/,""),a=await fetch(r+"/chat/completions",{method:"POST",credentials:"include",headers:await H(),body:JSON.stringify({model:t.model||"gpt-4o-mini",messages:n,stream:!0,...t.maxTokens?{max_tokens:t.maxTokens}:{}})});if(401===a.status&&function(){try{window.parent?.postMessage({type:"W3KITS_AUTH_REQUIRED",version:1,pluginId:M,reason:"ai_request"},J())}catch{}}(),!a.ok||!a.body)return q(G("error",{message:await a.text().catch(()=>"")||"OpenAI proxy failed ("+a.status+")"}),200,"text/event-stream;charset=utf-8");let i=new TextDecoder,o=new TextEncoder;return new Response(new ReadableStream({async start(e){let t=a.body.getReader(),n="",r="";try{for(;;){let{value:a,done:s}=await t.read();if(s)break;for(n+=i.decode(a,{stream:!0});;){let t=n.match(/\r?\n\r?\n/);if(!t||void 0===t.index)break;let a=n.slice(0,t.index);for(let i of(n=n.slice(t.index+t[0].length),a.split(/\r?\n/))){if(!i.startsWith("data:"))continue;let t=i.slice(5).trim();if(!t||"[DONE]"===t)continue;let n=JSON.parse(t),a=n.choices?.[0]?.delta?.content??"";a&&(r+=a,e.enqueue(o.encode(G("delta",{delta:a}))))}}}e.enqueue(o.encode(G("end",{text:r}))),e.close()}catch(t){e.enqueue(o.encode(G("error",{message:t instanceof Error?t.message:"OpenAI stream failed"}))),e.close()}}}),{headers:{"content-type":"text/event-stream;charset=utf-8"}})}async function ei(e){let t=new URL(e.url);return"/api/health"===t.pathname?L({ok:!0,mode:"w3kits-web"}):"/api/active"===t.pathname?L({ok:!0}):"/api/app-config"===t.pathname?L({config:{onboardingCompleted:!0}}):"/api/agents"===t.pathname?L({agents:[]}):"/api/skills"===t.pathname?L({skills:D}):"/api/design-templates"===t.pathname?L({designTemplates:[]}):"/api/design-systems"===t.pathname?L({designSystems:[]}):"/api/templates"===t.pathname?L({templates:[]}):"/api/prompt-templates"===t.pathname?L({promptTemplates:[]}):"/api/version"===t.pathname?L({version:"w3kits-web"}):"/api/proxy/openai/stream"===t.pathname?ea(e):"/api/w3kits/sync"===t.pathname&&"POST"===e.method?L(await N()):t.pathname.startsWith("/api/projects")?et(e,t):t.pathname.startsWith("/artifacts/")?er(e,t):fetch(e)}let eo=!1,es="open-design:config",el="https://w3kits.com/api/ai/openai/v1",ed="w3kits-plugin-user",ec="gpt-4o-mini";function eu(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function ep(e={}){return{...e,mode:"api",apiProtocol:"openai",apiKey:e.apiKey||ed,baseUrl:e.baseUrl||el,model:e.model||ec,apiProviderBaseUrl:null,onboardingCompleted:!0,apiProtocolConfigs:{...e.apiProtocolConfigs??{},openai:{apiKey:e.apiKey||ed,baseUrl:e.baseUrl||el,model:e.model||ec,apiProviderBaseUrl:null}}}}async function ef(){try{let e=window.localStorage.getItem(es);await d("/workspace/config/open-design.json",e||JSON.stringify(ep()),{contentType:"application/json"})}catch{}}async function eh(e){let t=e.ports[0],n=e.data;if(t&&n?.type==="W3KITS_DAEMON_REQUEST"&&n.request?.url)try{let e=await ei(new Request(n.request.url,{method:n.request.method||"GET",headers:n.request.headers||[],body:function(e){if(!e)return;let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}(n.request.bodyBase64)}));t.postMessage({status:e.status,headers:Array.from(e.headers.entries()),bodyBase64:eu(new Uint8Array(await e.arrayBuffer()))})}catch(e){t.postMessage({status:500,headers:[["content-type","application/json"]],bodyBase64:eu(new TextEncoder().encode(JSON.stringify({error:e instanceof Error?e.message:"w3kits_daemon_error"})))})}}let ew=!1,ey=(0,n.default)(()=>e.A(37491).then(e=>e.App),{loadableGenerated:{modules:[76768]},ssr:!1,loading:()=>(0,t.jsx)("div",{className:"od-loading-shell",children:"Loading Open Design…"})});e.s(["ClientApp",0,function(){if(!ew&&o()){ew=!0;try{let e=window.localStorage.getItem(es),t=e?JSON.parse(e):{},n=ep(t);window.localStorage.setItem(es,JSON.stringify(n))}catch{}if(!eo&&o()){let e;eo=!0,e=window.fetch.bind(window),window.fetch=async(t,n)=>{let r=new Request(t,n),a=new URL(r.url);return a.origin===window.location.origin&&(a.pathname.startsWith("/api/")||a.pathname.startsWith("/artifacts/"))?ei(r):e(t,n)}}"serviceWorker"in navigator&&(navigator.serviceWorker.addEventListener("message",e=>{eh(e)}),navigator.serviceWorker.register("/w3kits-daemon-sw.js",{scope:"/"}).catch(()=>void 0)),ef()}return(0,t.jsx)(ey,{})}],13903)},37491,e=>{e.v(t=>Promise.all(["static/chunks/0jzvy---_kh9r.js"].map(t=>e.l(t))).then(()=>t(76768)))}]);
@@ -1,77 +0,0 @@
1
- const REQUEST_TIMEOUT_MS = 30000;
2
-
3
- function bytesToBase64(bytes) {
4
- let binary = '';
5
- const chunkSize = 0x8000;
6
- for (let index = 0; index < bytes.length; index += chunkSize) {
7
- binary += String.fromCharCode(...bytes.subarray(index, index + chunkSize));
8
- }
9
- return btoa(binary);
10
- }
11
-
12
- function base64ToBytes(value) {
13
- const binary = atob(value || '');
14
- const bytes = new Uint8Array(binary.length);
15
- for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
16
- return bytes;
17
- }
18
-
19
- async function requestPayload(request) {
20
- const body = request.method === 'GET' || request.method === 'HEAD'
21
- ? undefined
22
- : bytesToBase64(new Uint8Array(await request.arrayBuffer()));
23
- return {
24
- type: 'W3KITS_DAEMON_REQUEST',
25
- request: {
26
- url: request.url,
27
- method: request.method,
28
- headers: Array.from(request.headers.entries()),
29
- bodyBase64: body,
30
- },
31
- };
32
- }
33
-
34
- async function targetClient(event) {
35
- if (event.clientId) {
36
- const client = await self.clients.get(event.clientId);
37
- if (client) return client;
38
- }
39
- const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
40
- return clients[0] || null;
41
- }
42
-
43
- async function relayToClient(event) {
44
- const client = await targetClient(event);
45
- if (!client) return new Response(JSON.stringify({ error: 'w3kits_client_unavailable' }), { status: 503, headers: { 'content-type': 'application/json' } });
46
-
47
- const message = await requestPayload(event.request);
48
- const channel = new MessageChannel();
49
- const response = await new Promise((resolve) => {
50
- const timeout = setTimeout(() => resolve({ status: 504, headers: [['content-type', 'application/json']], bodyBase64: bytesToBase64(new TextEncoder().encode(JSON.stringify({ error: 'w3kits_daemon_timeout' }))) }), REQUEST_TIMEOUT_MS);
51
- channel.port1.onmessage = (reply) => {
52
- clearTimeout(timeout);
53
- resolve(reply.data || {});
54
- };
55
- client.postMessage(message, [channel.port2]);
56
- });
57
-
58
- return new Response(base64ToBytes(response.bodyBase64), {
59
- status: response.status || 200,
60
- headers: response.headers || [],
61
- });
62
- }
63
-
64
- self.addEventListener('install', (event) => {
65
- event.waitUntil(self.skipWaiting());
66
- });
67
-
68
- self.addEventListener('activate', (event) => {
69
- event.waitUntil(self.clients.claim());
70
- });
71
-
72
- self.addEventListener('fetch', (event) => {
73
- const url = new URL(event.request.url);
74
- if (url.origin !== self.location.origin) return;
75
- if (!url.pathname.startsWith('/api/') && !url.pathname.startsWith('/artifacts/')) return;
76
- event.respondWith(relayToClient(event));
77
- });