sveltekit-remote-fn-plugin
Version:
A Vite plugin for SvelteKit remote functions
37 lines (34 loc) • 9.31 kB
JavaScript
(function(b,S){typeof exports=="object"&&typeof module<"u"?module.exports=S():typeof define=="function"&&define.amd?define(S):(b=typeof globalThis<"u"?globalThis:b||self,b.SvelteKitRemoteFnPlugin=S())})(this,function(){"use strict";var b=typeof document<"u"?document.currentScript:null;function S(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var E={exports:{}},c=E.exports={},v,g;function R(){throw new Error("setTimeout has not been defined")}function j(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?v=setTimeout:v=R}catch{v=R}try{typeof clearTimeout=="function"?g=clearTimeout:g=j}catch{g=j}})();function L(t){if(v===setTimeout)return setTimeout(t,0);if((v===R||!v)&&setTimeout)return v=setTimeout,setTimeout(t,0);try{return v(t,0)}catch{try{return v.call(null,t,0)}catch{return v.call(this,t,0)}}}function O(t){if(g===clearTimeout)return clearTimeout(t);if((g===j||!g)&&clearTimeout)return g=clearTimeout,clearTimeout(t);try{return g(t)}catch{try{return g.call(null,t)}catch{return g.call(this,t)}}}var y=[],C=!1,p,F=-1;function q(){!C||!p||(C=!1,p.length?y=p.concat(y):F=-1,y.length&&$())}function $(){if(!C){var t=L(q);C=!0;for(var e=y.length;e;){for(p=y,y=[];++F<e;)p&&p[F].run();F=-1,e=y.length}p=null,C=!1,O(t)}}c.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];y.push(new _(t,e)),y.length===1&&!C&&L($)};function _(t,e){this.fun=t,this.array=e}_.prototype.run=function(){this.fun.apply(null,this.array)},c.title="browser",c.browser=!0,c.env={},c.argv=[],c.version="",c.versions={};function w(){}c.on=w,c.addListener=w,c.once=w,c.off=w,c.removeListener=w,c.removeAllListeners=w,c.emit=w,c.prependListener=w,c.prependOnceListener=w,c.listeners=function(t){return[]},c.binding=function(t){throw new Error("process.binding is not supported")},c.cwd=function(){return"/"},c.chdir=function(t){throw new Error("process.chdir is not supported")},c.umask=function(){return 0};var z=E.exports;const H=S(z);function m(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}function x(t,e){for(var r="",n=0,i=-1,s=0,o,l=0;l<=t.length;++l){if(l<t.length)o=t.charCodeAt(l);else{if(o===47)break;o=47}if(o===47){if(!(i===l-1||s===1))if(i!==l-1&&s===2){if(r.length<2||n!==2||r.charCodeAt(r.length-1)!==46||r.charCodeAt(r.length-2)!==46){if(r.length>2){var a=r.lastIndexOf("/");if(a!==r.length-1){a===-1?(r="",n=0):(r=r.slice(0,a),n=r.length-1-r.lastIndexOf("/")),i=l,s=0;continue}}else if(r.length===2||r.length===1){r="",n=0,i=l,s=0;continue}}e&&(r.length>0?r+="/..":r="..",n=2)}else r.length>0?r+="/"+t.slice(i+1,l):r=t.slice(i+1,l),n=l-i-1;i=l,s=0}else o===46&&s!==-1?++s:s=-1}return r}function B(t,e){var r=e.dir||e.root,n=e.base||(e.name||"")+(e.ext||"");return r?r===e.root?r+n:r+t+n:n}var T={resolve:function(){for(var e="",r=!1,n,i=arguments.length-1;i>=-1&&!r;i--){var s;i>=0?s=arguments[i]:(n===void 0&&(n=H.cwd()),s=n),m(s),s.length!==0&&(e=s+"/"+e,r=s.charCodeAt(0)===47)}return e=x(e,!r),r?e.length>0?"/"+e:"/":e.length>0?e:"."},normalize:function(e){if(m(e),e.length===0)return".";var r=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47;return e=x(e,!r),e.length===0&&!r&&(e="."),e.length>0&&n&&(e+="/"),r?"/"+e:e},isAbsolute:function(e){return m(e),e.length>0&&e.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var e,r=0;r<arguments.length;++r){var n=arguments[r];m(n),n.length>0&&(e===void 0?e=n:e+="/"+n)}return e===void 0?".":T.normalize(e)},relative:function(e,r){if(m(e),m(r),e===r||(e=T.resolve(e),r=T.resolve(r),e===r))return"";for(var n=1;n<e.length&&e.charCodeAt(n)===47;++n);for(var i=e.length,s=i-n,o=1;o<r.length&&r.charCodeAt(o)===47;++o);for(var l=r.length,a=l-o,d=s<a?s:a,f=-1,u=0;u<=d;++u){if(u===d){if(a>d){if(r.charCodeAt(o+u)===47)return r.slice(o+u+1);if(u===0)return r.slice(o+u)}else s>d&&(e.charCodeAt(n+u)===47?f=u:u===0&&(f=0));break}var U=e.charCodeAt(n+u),M=r.charCodeAt(o+u);if(U!==M)break;U===47&&(f=u)}var P="";for(u=n+f+1;u<=i;++u)(u===i||e.charCodeAt(u)===47)&&(P.length===0?P+="..":P+="/..");return P.length>0?P+r.slice(o+f):(o+=f,r.charCodeAt(o)===47&&++o,r.slice(o))},_makeLong:function(e){return e},dirname:function(e){if(m(e),e.length===0)return".";for(var r=e.charCodeAt(0),n=r===47,i=-1,s=!0,o=e.length-1;o>=1;--o)if(r=e.charCodeAt(o),r===47){if(!s){i=o;break}}else s=!1;return i===-1?n?"/":".":n&&i===1?"//":e.slice(0,i)},basename:function(e,r){if(r!==void 0&&typeof r!="string")throw new TypeError('"ext" argument must be a string');m(e);var n=0,i=-1,s=!0,o;if(r!==void 0&&r.length>0&&r.length<=e.length){if(r.length===e.length&&r===e)return"";var l=r.length-1,a=-1;for(o=e.length-1;o>=0;--o){var d=e.charCodeAt(o);if(d===47){if(!s){n=o+1;break}}else a===-1&&(s=!1,a=o+1),l>=0&&(d===r.charCodeAt(l)?--l===-1&&(i=o):(l=-1,i=a))}return n===i?i=a:i===-1&&(i=e.length),e.slice(n,i)}else{for(o=e.length-1;o>=0;--o)if(e.charCodeAt(o)===47){if(!s){n=o+1;break}}else i===-1&&(s=!1,i=o+1);return i===-1?"":e.slice(n,i)}},extname:function(e){m(e);for(var r=-1,n=0,i=-1,s=!0,o=0,l=e.length-1;l>=0;--l){var a=e.charCodeAt(l);if(a===47){if(!s){n=l+1;break}continue}i===-1&&(s=!1,i=l+1),a===46?r===-1?r=l:o!==1&&(o=1):r!==-1&&(o=-1)}return r===-1||i===-1||o===0||o===1&&r===i-1&&r===n+1?"":e.slice(r,i)},format:function(e){if(e===null||typeof e!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return B("/",e)},parse:function(e){m(e);var r={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return r;var n=e.charCodeAt(0),i=n===47,s;i?(r.root="/",s=1):s=0;for(var o=-1,l=0,a=-1,d=!0,f=e.length-1,u=0;f>=s;--f){if(n=e.charCodeAt(f),n===47){if(!d){l=f+1;break}continue}a===-1&&(d=!1,a=f+1),n===46?o===-1?o=f:u!==1&&(u=1):o!==-1&&(u=-1)}return o===-1||a===-1||u===0||u===1&&o===a-1&&o===l+1?a!==-1&&(l===0&&i?r.base=r.name=e.slice(1,a):r.base=r.name=e.slice(l,a)):(l===0&&i?(r.name=e.slice(1,o),r.base=e.slice(1,a)):(r.name=e.slice(l,o),r.base=e.slice(l,a)),r.ext=e.slice(o,a)),l>0?r.dir=e.slice(0,l-1):i&&(r.dir="/"),r},sep:"/",delimiter:":",win32:null,posix:null};T.posix=T;var h=T,J=null,A=J;const W=h.dirname(new URL(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:b&&b.src||new URL("index.js",document.baseURI).href).pathname),D={serverFunctionsDir:h.join(W,"..","src","lib","server","functions"),outputDir:h.join(W,"..","src","lib"),apiPrefix:"/api/v1"};function N(t,e,r){const n=`
import { post } from '@sveltejs/kit/server';
${t.map(i=>`
export async function ${i}(...args: any[]) {
try {
const response = await post('${r.apiPrefix}/${i}', { args });
if (!response.ok) {
throw new Error(\`HTTP error! status: \${response.status}\`);
}
return await response.json();
} catch (error) {
console.error(\`Error calling ${i}:\`, error);
throw error;
}
}`).join(`
`)}
`;A.writeFileSync(e,n)}function Q(t,e,r){t.forEach(n=>{const i=h.join(e,"routes",r.apiPrefix.slice(1),n);A.existsSync(i)||A.mkdirSync(i,{recursive:!0});const s=`
import { ${n} } from '$lib/server/functions/${n}.server';
export async function POST({ request }) {
const { args } = await request.json();
try {
const result = await ${n}(...args);
return new Response(JSON.stringify(result), {
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
console.error(\`Error in ${n}:\`, error);
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
`;A.writeFileSync(h.join(i,"+server.ts"),s)})}function k(t={}){const e={...D,...t},r=A.readdirSync(e.serverFunctionsDir),n=[];r.forEach(s=>{if(s.endsWith(".server.ts")){const o=h.join(e.serverFunctionsDir,s),a=A.readFileSync(o,"utf-8").match(/export\s+async?\s+function\s+(\w+)/g);a&&a.forEach(d=>{const f=d.split(" ").pop();f&&n.push(f)})}});const i=h.join(e.outputDir,"server.ts");N(n,i,e),Q(n,e.outputDir,e),console.log("Remote functions and routes generated successfully!")}function K(t={}){let e;return{name:"sveltekit-remote-fn",apply(r,{command:n}){var i;return n==="build"&&!((i=r.build)!=null&&i.ssr)},configResolved(r){console.log("BuildStart Config: ",r),e=r},buildStart(){console.log("BuildStart Config: ",t),k(t)},handleHotUpdate({file:r}){const n=h.relative(e.root,r);if(console.log("HandleHotUpdate RelativePath: ",n),n.startsWith(t.serverFunctionsDir||D.serverFunctionsDir)&&r.endsWith(".server.ts"))return console.log("Server function file changed, regenerating remote functions..."),k(t),[]},configureServer(r){const n=r.watcher;n.on("add",i=>{const s=h.relative(e.root,i);console.log("WatcherOn Add RelativePath: ",s),s.startsWith(t.serverFunctionsDir||D.serverFunctionsDir)&&i.endsWith(".server.ts")&&(console.log("New server function file added, regenerating remote functions..."),k(t))}),n.on("unlink",i=>{const s=h.relative(e.root,i);console.log("WatcherOn Unlink RelativePath: ",s),s.startsWith(t.serverFunctionsDir||D.serverFunctionsDir)&&i.endsWith(".server.ts")&&(console.log("Server function file removed, regenerating remote functions..."),k(t))})}}}return K});