rpc4next 0.3.4 → 0.3.6

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.
Files changed (59) hide show
  1. package/dist/rpc/cli/index.js +6 -4
  2. package/dist/rpc/client/http-method.js +1 -88
  3. package/dist/rpc/client/index.js +1 -6
  4. package/dist/rpc/client/match.js +1 -30
  5. package/dist/rpc/client/rpc.js +1 -99
  6. package/dist/rpc/client/types.js +0 -2
  7. package/dist/rpc/client/url.js +1 -57
  8. package/dist/rpc/client/utils.js +1 -31
  9. package/dist/rpc/lib/constants.js +1 -9
  10. package/dist/rpc/lib/content-type-types.js +0 -2
  11. package/dist/rpc/lib/http-request-headers-types.js +0 -2
  12. package/dist/rpc/lib/http-response-headers-types.js +0 -2
  13. package/dist/rpc/lib/http-status-code-types.js +0 -2
  14. package/dist/rpc/lib/types.js +0 -2
  15. package/dist/rpc/server/create-handler.js +1 -10
  16. package/dist/rpc/server/create-route-context.js +1 -25
  17. package/dist/rpc/server/index.js +1 -5
  18. package/dist/rpc/server/route-handler-factory.js +1 -68
  19. package/dist/rpc/server/route-types.js +0 -2
  20. package/dist/rpc/server/search-params-to-object.js +1 -18
  21. package/dist/rpc/server/types.js +0 -2
  22. package/dist/rpc/server/validators/validator-utils.js +1 -31
  23. package/dist/rpc/server/validators/zod/index.js +1 -5
  24. package/dist/rpc/server/validators/zod/zod-validator.js +1 -53
  25. package/package.json +6 -2
  26. package/dist/index.js +0 -18
  27. package/dist/rpc/cli/cli-handler.d.ts +0 -2
  28. package/dist/rpc/cli/cli-handler.js +0 -48
  29. package/dist/rpc/cli/cli.d.ts +0 -2
  30. package/dist/rpc/cli/cli.js +0 -32
  31. package/dist/rpc/cli/constants.d.ts +0 -7
  32. package/dist/rpc/cli/constants.js +0 -9
  33. package/dist/rpc/cli/core/alias.d.ts +0 -1
  34. package/dist/rpc/cli/core/alias.js +0 -16
  35. package/dist/rpc/cli/core/cache.d.ts +0 -14
  36. package/dist/rpc/cli/core/cache.js +0 -30
  37. package/dist/rpc/cli/core/constants.d.ts +0 -11
  38. package/dist/rpc/cli/core/constants.js +0 -19
  39. package/dist/rpc/cli/core/generate-path-structure.d.ts +0 -7
  40. package/dist/rpc/cli/core/generate-path-structure.js +0 -30
  41. package/dist/rpc/cli/core/path-utils.d.ts +0 -3
  42. package/dist/rpc/cli/core/path-utils.js +0 -24
  43. package/dist/rpc/cli/core/route-scanner.d.ts +0 -28
  44. package/dist/rpc/cli/core/route-scanner.js +0 -192
  45. package/dist/rpc/cli/core/scan-utils.d.ts +0 -19
  46. package/dist/rpc/cli/core/scan-utils.js +0 -44
  47. package/dist/rpc/cli/core/type-utils.d.ts +0 -6
  48. package/dist/rpc/cli/core/type-utils.js +0 -26
  49. package/dist/rpc/cli/debounce.d.ts +0 -1
  50. package/dist/rpc/cli/debounce.js +0 -43
  51. package/dist/rpc/cli/generator.d.ts +0 -7
  52. package/dist/rpc/cli/generator.js +0 -28
  53. package/dist/rpc/cli/index.d.ts +0 -2
  54. package/dist/rpc/cli/logger.d.ts +0 -3
  55. package/dist/rpc/cli/logger.js +0 -31
  56. package/dist/rpc/cli/types.d.ts +0 -21
  57. package/dist/rpc/cli/types.js +0 -2
  58. package/dist/rpc/cli/watcher.d.ts +0 -2
  59. package/dist/rpc/cli/watcher.js +0 -67
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- const cli_1 = require("./cli");
5
- (0, cli_1.runCli)(process.argv);
2
+ import{Command as Wt}from"commander";import $t from"path";var R=["page.tsx","route.ts"],w=0,$=1,Y=1,M=20,W="\u2192";import U from"path";var et=(t,r)=>{let e=P(U.relative(U.dirname(t),r)).replace(/\.tsx?$/,"");return e.startsWith("../")||(e="./"+e),e},P=t=>t.replace(/\\/g,"/"),C=t=>U.relative(process.cwd(),t);import _t from"fs";import Yt from"path";var rt=["Query","OptionalQuery"],L=" ",g=`
3
+ `,S=";",H=";",j="Endpoint",X="QueryKey",K="OptionalQueryKey",Q="ParamsKey",ot=[j,K,Q,X],nt="rpc4next/client";import ht from"fs";import b from"path";import G from"path";var T=new Map,N=new Map,st=(t,r)=>{let e=G.resolve(r);[...t.keys()].forEach(o=>{let n=G.resolve(o);(n===e||e.startsWith(n+G.sep))&&t.delete(o)})},it=t=>{st(T,t)},at=t=>{st(N,t)};import vt from"fs";import bt from"crypto";var pt=(t,r)=>{let e=bt.createHash("md5").update(`${t}::${r}`).digest("hex").slice(0,16);return`${r}_${e}`};var I=(t,r)=>!t||!r?"":`Record<${t}, ${r}>`,O=t=>t.length===0||t.some(({name:r,type:e})=>!r||!e)?"":`{ ${t.map(({name:r,type:e})=>`"${r}": ${e}`).join(`${H} `)}${t.length>1?H:""} }`,D=(t,r,e)=>!t||!r?"":e?`import type { ${t} as ${e} } from "${r}"${S}`:`import type { ${t} } from "${r}"${S}`;var ct=(t,r,e,o)=>{let n=vt.readFileSync(r,"utf8"),i=e(n);if(!i)return;let s=et(t,r),p=pt(s,i);return{importName:p,importPath:s,importStatement:D(i,s,p),type:o(i,p)}},mt=(t,r)=>ct(t,r,e=>rt.find(o=>new RegExp(`export (interface ${o} ?{|type ${o} ?=)`).test(e)),(e,o)=>e==="Query"?I(X,o):I(K,o)),lt=(t,r,e)=>ct(t,r,o=>[e].find(n=>new RegExp(`export (async )?(function ${n} ?\\(|const ${n} ?=|\\{[^}]*\\b${n}\\b[^}]*\\} ?=|const \\{[^}]*\\b${n}\\b[^}]*\\} ?=|\\{[^}]*\\b${n}\\b[^}]*\\} from)`).test(o)),(o,n)=>O([{name:`$${o.toLowerCase()}`,type:`typeof ${n}`}]));import{HTTP_METHODS as Ft}from"next/dist/server/web/http";var ut="_____",ft="___",gt="_",k=Ft.filter(t=>t!=="OPTIONS"),ne=k.map(t=>`$${t.toLowerCase()}`);var Et=new Set(R),Tt=t=>{if(T.has(t))return T.get(t);let r=ht.readdirSync(t,{withFileTypes:!0});for(let e of r){let{name:o}=e,n=b.join(t,o);if(o==="node_modules"||o.startsWith("_")||o.startsWith("(.)")||o.startsWith("(..)")||o.startsWith("(...)"))return T.set(t,!1),!1;if(e.isFile()&&Et.has(o))return T.set(t,!0),!0;if(e.isDirectory()&&Tt(n))return T.set(t,!0),!0}return T.set(t,!1),!1},wt=(t,{isDynamic:r,isCatchAll:e,isOptionalCatchAll:o})=>{let n=t;return r&&(n=n.replace(/^\[+|\]+$/g,"")),(e||o)&&(n=n.replace(/^\.{3}/,"")),{paramName:n,keyName:`${o?ut:e?ft:r?gt:""}${n}`}},V=(t,r,e="",o=[])=>{if(N.has(r))return N.get(r);let n=e,i=e+L,s=[],p=[],a=[],m=[],c=[...o],x=ht.readdirSync(r,{withFileTypes:!0}).filter(y=>{if(y.isDirectory()){let _=b.join(r,y.name);return Tt(_)}return Et.has(y.name)}).sort();for(let y of x){let _=P(b.join(r,y.name));if(y.isDirectory()){let l=y.name,h=l.startsWith("(")&&l.endsWith(")"),u=l.startsWith("@"),f=l.startsWith("[[...")&&l.endsWith("]]"),E=l.startsWith("[...")&&l.endsWith("]"),d=l.startsWith("[")&&l.endsWith("]"),{paramName:At,keyName:Rt}=wt(l,{isDynamic:d,isCatchAll:E,isOptionalCatchAll:f}),Lt=d||E||f?[...c,{paramName:At,routeType:{isDynamic:d,isCatchAll:E,isOptionalCatchAll:f,isGroup:h,isParallel:u}}]:c,J=h||u,{pathStructure:Z,imports:Ot,paramsTypes:Dt}=V(t,_,J?n:i,Lt);if(p.push(...Ot),m.push(...Dt),J){let tt=Z.match(/^\s*\{([\s\S]*)\}\s*$/);tt&&s.push(`${i}${tt[1].trim()}`)}else s.push(`${i}"${Rt}": ${Z}`)}else{let l=mt(t,_);if(l){let{importStatement:h,importPath:u,type:f}=l;p.push({statement:h,path:u}),a.push(f)}if(k.forEach(h=>{let u=lt(t,_,h);if(u){let{importStatement:f,importPath:E,type:d}=u;p.push({statement:f,path:E}),a.push(d)}}),a.push(j),c.length>0){let h=c.map(({paramName:f,routeType:E})=>{let d=E.isCatchAll?"string[]":E.isOptionalCatchAll?"string[] | undefined":"string";return{name:f,type:d}}),u=O(h);m.push({paramsType:u,dirPath:b.dirname(_)}),a.push(I(Q,u))}}}let A=a.join(" & "),F=s.length>0?`{${g}${s.join(`,${g}`)}${g}${n}}`:"",z={pathStructure:A&&F?`${A} & ${F}`:A||F,imports:p,paramsTypes:m};return N.set(r,z),z};var yt=(t,r)=>{let{pathStructure:e,imports:o,paramsTypes:n}=V(t,r),i=`export type PathStructure = ${e}${S}`,s=o.length?`${o.sort((c,x)=>c.path.localeCompare(x.path,void 0,{numeric:!0})).map(c=>c.statement).join(g)}`:"",p=ot.filter(c=>e.includes(c)),a=D(p.join(" ,"),nt),m=n.map(({paramsType:c,dirPath:x})=>({paramsType:`export type Params = ${c}${S}`,dirPath:x}));return{pathStructure:`${a}${g}${s}${g}${g}${i}`,paramsTypes:m}};import v from"chalk";var q=(t,r,e="\u2192",o=24)=>t.padEnd(o)+` ${e} ${r}`,B=(t=0)=>L.repeat(t),dt=()=>({info:(t,r={})=>{let{indentLevel:e=0,event:o}=r,n=o?`${v.cyan(`[${o}]`)} `:"";console.log(`${B(e)}${n}${t}`)},success:(t,r={})=>{let{indentLevel:e=0}=r;console.log(`${B(e)}${v.green("\u2713")} ${t}`)},error:(t,r={})=>{let{indentLevel:e=0}=r;console.error(`${B(e)}${v.red("\u2717")} ${v.red(t)}`)}});var Pt=({baseDir:t,outputPath:r,paramsFileName:e,logger:o})=>{o.info("Generating types...",{event:"generate"});let{pathStructure:n,paramsTypes:i}=yt(r,t);_t.writeFileSync(r,n),o.success(q("Path structure type",C(r),W,M),{indentLevel:Y}),e&&(i.forEach(({paramsType:s,dirPath:p})=>{let a=Yt.join(p,e);_t.writeFileSync(a,s)}),o.success(q("Params types",e,W,M),{indentLevel:Y}))};import Mt from"chokidar";var St=(t,r)=>{let e=null,o=!1,n=null,i=async(...s)=>{o=!0;try{await t(...s)}finally{if(o=!1,n){let p=n;n=null,i(...p)}}};return(...s)=>{e&&clearTimeout(e),e=setTimeout(()=>{if(o){n=s;return}i(...s)},r)}};var xt=(t,r,e)=>{e.info(`${C(t)}`,{event:"watch"});let o=a=>R.some(m=>a.endsWith(m)),n=new Set,i=St(()=>{n.forEach(a=>{it(a),at(a)}),n.clear(),r()},300),s=Mt.watch(t,{ignoreInitial:!0,ignored:(a,m)=>!!m?.isFile()&&!o(a)});s.on("ready",()=>{i(),s.on("all",(a,m)=>{if(o(m)){let c=C(m);e.info(c,{event:a}),n.add(m),i()}})}),s.on("error",a=>{a instanceof Error?e.error(`Watcher error: ${a.message}`):e.error(`Unknown watcher error: ${String(a)}`)});let p=()=>{s.close().then(()=>{e.info("Watcher closed.",{event:"watch"})}).catch(a=>{e.error(`Failed to close watcher: ${a.message}`)})};process.on("SIGINT",p),process.on("SIGTERM",p)};var Ct=(t,r,e,o)=>{try{return Pt({baseDir:t,outputPath:r,paramsFileName:e,logger:o}),w}catch(n){return n instanceof Error?o.error(`Failed to generate: ${n.message}`):o.error(`Unknown error occurred during generate: ${String(n)}`),$}},Nt=(t,r,e,o)=>{let n=P($t.resolve(t)),i=P($t.resolve(r)),s=typeof e.paramsFile=="string"?e.paramsFile:null;return e.paramsFile!==void 0&&!s?(o.error("Error: --params-file requires a filename."),$):e.watch?(xt(n,()=>{Ct(n,i,s,o)},o),w):Ct(n,i,s,o)};var It=(t,r=dt())=>{let e=new Wt;e.description("Generate RPC client type definitions based on the Next.js path structure.").argument("<baseDir>","Base directory containing Next.js paths for type generation").argument("<outputPath>","Output path for the generated type definitions").option("-w, --watch","Watch mode: regenerate on file changes").option("-p, --params-file [filename]","Generate params types file with specified filename").action(async(o,n,i)=>{try{let s=await Nt(o,n,i,r);i.watch||process.exit(s)}catch(s){r.error(`Unexpected error occurred:${s instanceof Error?s.message:String(s)}`),process.exit($)}}),e.parse(t)};It(process.argv);
4
+ /*!
5
+ * Inspired by pathpida (https://github.com/aspida/pathpida),
6
+ * especially the design and UX of its CLI.
7
+ */
@@ -1,88 +1 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
- Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.httpMethod = void 0;
24
- const url_1 = require("./url");
25
- const utils_1 = require("./utils");
26
- const normalizeHeaders = (headers) => {
27
- const result = {};
28
- if (!headers)
29
- return result;
30
- if (headers instanceof Headers) {
31
- headers.forEach((value, key) => {
32
- result[key.toLowerCase()] = value;
33
- });
34
- return result;
35
- }
36
- if (Array.isArray(headers)) {
37
- headers.forEach(([key, value]) => {
38
- result[key.toLowerCase()] = value;
39
- });
40
- return result;
41
- }
42
- Object.entries(headers).forEach(([key, value]) => {
43
- result[key.toLowerCase()] = value;
44
- });
45
- return result;
46
- };
47
- const httpMethod = (key, paths, params, dynamicKeys, defaultOptions) => {
48
- return (methodParam, options) => __awaiter(void 0, void 0, void 0, function* () {
49
- var _a, _b, _c;
50
- let methodParamBody = undefined;
51
- let methodParamContentType = undefined;
52
- if ((_a = methodParam === null || methodParam === void 0 ? void 0 : methodParam.body) === null || _a === void 0 ? void 0 : _a.json) {
53
- methodParamContentType = "application/json";
54
- methodParamBody = JSON.stringify(methodParam.body.json);
55
- }
56
- const methodParamHeaders = (_b = methodParam === null || methodParam === void 0 ? void 0 : methodParam.requestHeaders) === null || _b === void 0 ? void 0 : _b.headers;
57
- const methodParamCookies = (_c = methodParam === null || methodParam === void 0 ? void 0 : methodParam.requestHeaders) === null || _c === void 0 ? void 0 : _c.cookies;
58
- const urlObj = (0, url_1.createUrl)([...paths], params, dynamicKeys)(methodParam === null || methodParam === void 0 ? void 0 : methodParam.url);
59
- const method = key.replace(/^\$/, "").toUpperCase();
60
- const customFetch = (options === null || options === void 0 ? void 0 : options.fetch) || defaultOptions.fetch || fetch;
61
- const defaultInit = defaultOptions.init || {};
62
- const innerInit = (options === null || options === void 0 ? void 0 : options.init) || {};
63
- const defaultHeaders = normalizeHeaders(defaultInit.headers);
64
- const innerHeaders = normalizeHeaders(methodParamHeaders ? methodParamHeaders : innerInit.headers);
65
- const mergedHeaders = Object.assign(Object.assign({}, defaultHeaders), innerHeaders);
66
- if (methodParamContentType) {
67
- mergedHeaders["content-type"] = methodParamContentType;
68
- }
69
- if (methodParamCookies) {
70
- mergedHeaders["cookie"] = Object.entries(methodParamCookies)
71
- .map(([key, value]) => `${key}=${value}`)
72
- .join("; ");
73
- }
74
- const { headers: _defaultHeaders } = defaultInit, defaultInitWithoutHeaders = __rest(defaultInit, ["headers"]);
75
- const { headers: _innerHeaders } = innerInit, innerInitWithoutHeaders = __rest(innerInit, ["headers"]);
76
- const mergedInit = (0, utils_1.deepMerge)(defaultInitWithoutHeaders, innerInitWithoutHeaders);
77
- mergedInit.method = method;
78
- if (Object.keys(mergedHeaders).length > 0) {
79
- mergedInit.headers = mergedHeaders;
80
- }
81
- if (methodParamBody) {
82
- mergedInit.body = methodParamBody;
83
- }
84
- const response = yield customFetch(urlObj.path, mergedInit);
85
- return response;
86
- });
87
- };
88
- exports.httpMethod = httpMethod;
1
+ import{createUrl as q}from"./url";import{deepMerge as T}from"./utils";const l=t=>{const e={};return t?t instanceof Headers?(t.forEach((n,r)=>{e[r.toLowerCase()]=n}),e):Array.isArray(t)?(t.forEach(([n,r])=>{e[n.toLowerCase()]=r}),e):(Object.entries(t).forEach(([n,r])=>{e[n.toLowerCase()]=r}),e):e},F=(t,e,n,r,c)=>async(s,p)=>{let d,a;s?.body?.json&&(a="application/json",d=JSON.stringify(s.body.json));const g=s?.requestHeaders?.headers,f=s?.requestHeaders?.cookies,m=q([...e],n,r)(s?.url),h=t.replace(/^\$/,"").toUpperCase(),H=p?.fetch??c.fetch??fetch,u=c.init??{},y=p?.init??{},O=l(u.headers),C=l(g??y.headers),o={...O,...C};a&&(o["content-type"]=a),f&&(o.cookie=Object.entries(f).map(([j,R])=>`${j}=${R}`).join("; "));const{headers:k,...b}=u,{headers:w,...I}=y,i=T(b,I);return i.method=h,Object.keys(o).length>0&&(i.headers=o),d&&(i.body=d),await H(m.path,i)};export{F as httpMethod};
@@ -1,6 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createRpcHelper = exports.createRpcClient = void 0;
4
- var rpc_1 = require("./rpc");
5
- Object.defineProperty(exports, "createRpcClient", { enumerable: true, get: function () { return rpc_1.createRpcClient; } });
6
- Object.defineProperty(exports, "createRpcHelper", { enumerable: true, get: function () { return rpc_1.createRpcHelper; } });
1
+ import{createRpcClient as p,createRpcHelper as t}from"./rpc";export{p as createRpcClient,t as createRpcHelper};
@@ -1,30 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.matchPath = void 0;
4
- const url_1 = require("./url");
5
- const utils_1 = require("./utils");
6
- const matchPath = (paths, dynamicKeys) => {
7
- return (path) => {
8
- const basePath = `/${paths.slice(1).join("/")}`;
9
- const regexPattern = (0, url_1.replaceDynamicSegments)(basePath, {
10
- optionalCatchAll: "(?:/(.*))?",
11
- catchAll: "/([^/]+(?:/[^/]+)*)",
12
- dynamic: "/([^/]+)",
13
- });
14
- // Add optional trailing slash
15
- const match = new RegExp(`^${regexPattern}/?$`).exec(path);
16
- if (!match)
17
- return null;
18
- return dynamicKeys.reduce((acc, key, index) => {
19
- const paramKey = key.replace(/^_+/, "");
20
- const matchValue = match[index + 1];
21
- const paramValue = (0, utils_1.isCatchAllOrOptional)(key)
22
- ? matchValue === undefined || matchValue === ""
23
- ? undefined
24
- : matchValue.split("/").filter(Boolean).map(decodeURIComponent)
25
- : decodeURIComponent(matchValue);
26
- return Object.assign(Object.assign({}, acc), { [paramKey]: paramValue });
27
- }, {});
28
- };
29
- };
30
- exports.matchPath = matchPath;
1
+ import{replaceDynamicSegments as d}from"./url";import{isCatchAllOrOptional as u}from"./utils";const f=(r,o)=>a=>{const c=`/${r.slice(1).join("/")}`,i=d(c,{optionalCatchAll:"(?:/(.*))?",catchAll:"/([^/]+(?:/[^/]+)*)",dynamic:"/([^/]+)"}),n=new RegExp(`^${i}/?$`).exec(a);return n?o.reduce((l,t,s)=>{const m=t.replace(/^_+/,""),e=n[s+1],p=u(t)?e===void 0||e===""?void 0:e.split("/").filter(Boolean).map(decodeURIComponent):decodeURIComponent(e);return{...l,[m]:p}},{}):null};export{f as matchPath};
@@ -1,103 +1,5 @@
1
- "use strict";
2
1
  /*!
3
2
  * Inspired by the design of Hono (https://github.com/honojs/hono)
4
3
  * and pathpida (https://github.com/aspida/pathpida)
5
4
  * particularly their routing structures and developer experience.
6
- */
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.createRpcHelper = exports.createRpcClient = exports.createRpcProxy = void 0;
9
- const http_method_1 = require("./http-method");
10
- const match_1 = require("./match");
11
- const url_1 = require("./url");
12
- const utils_1 = require("./utils");
13
- const createRpcProxy = (options, paths = [], params = {}, dynamicKeys = []) => {
14
- const proxy = new Proxy((value) => {
15
- const pathKey = paths.at(-1);
16
- const paramKey = dynamicKeys.at(-1);
17
- if (value === undefined) {
18
- throw new Error(`An argument is required when calling the function for paramKey: ${paramKey}`);
19
- }
20
- if (pathKey && paramKey && (0, utils_1.isDynamic)(pathKey)) {
21
- // Treat as a dynamic parameter
22
- return (0, exports.createRpcProxy)(options, [...paths], Object.assign(Object.assign({}, params), { [paramKey]: value }), dynamicKeys);
23
- }
24
- throw new Error(`paramKey: ${pathKey} is not a dynamic parameter and cannot be called as a function`);
25
- }, {
26
- get: (_, key) => {
27
- if (key === "$url") {
28
- return (0, url_1.createUrl)([...paths], params, dynamicKeys);
29
- }
30
- if (key === "$match") {
31
- return (0, match_1.matchPath)([...paths], dynamicKeys);
32
- }
33
- if ((0, utils_1.isHttpMethod)(key)) {
34
- return (0, http_method_1.httpMethod)(key, [...paths], params, dynamicKeys, Object.assign({}, options));
35
- }
36
- if ((0, utils_1.isDynamic)(key)) {
37
- // Treat as a dynamic parameter
38
- return (0, exports.createRpcProxy)(options, [...paths, key], params, [
39
- ...dynamicKeys,
40
- key,
41
- ]);
42
- }
43
- return (0, exports.createRpcProxy)(options, [...paths, key], params, dynamicKeys);
44
- },
45
- });
46
- return proxy;
47
- };
48
- exports.createRpcProxy = createRpcProxy;
49
- /**
50
- * Creates an RPC client proxy for making HTTP requests with a strongly typed API.
51
- *
52
- * @template T - The type defining the RPC endpoint structure.
53
- * @param baseUrl - The base URL for the RPC client. This URL will be used as the root for all generated endpoint URLs.
54
- * @param options - (Optional) Client options to customize the behavior of the RPC client. These options may include a custom fetch function and default request initialization options.
55
- * @returns An object that enables you to dynamically build endpoint URLs and execute HTTP requests (such as GET, POST, DELETE, etc.) with full type support.
56
- *
57
- * @example
58
- * ```ts
59
- * import { createRpcClient } from "./rpc";
60
- * import type { PathStructure } from "./types";
61
- *
62
- * // Create an RPC client with a base URL
63
- * const client = createRpcClient<PathStructure>("http://localhost:3000");
64
- *
65
- * // Generate a URL for a dynamic endpoint
66
- * const urlResult = client.fuga._foo("test").$url();
67
- * console.log(urlResult.path); // "http://localhost:3000/fuga/test"
68
- * console.log(urlResult.relativePath); // "/fuga/test"
69
- * console.log(urlResult.pathname); // "/fuga/[foo]"
70
- * console.log(urlResult.params); // { foo: "test" }
71
- *
72
- * // Execute a GET request on an endpoint
73
- * const response = await client.api.hoge._foo("test").$get();
74
- * console.log(await response.json()); // Expected response: { method: "get" }
75
- * ```
76
- *
77
- * The above example demonstrates how to generate URLs with dynamic segments and how to execute HTTP requests.
78
- */
79
- const createRpcClient = (baseUrl, options = {}) => (0, exports.createRpcProxy)(options, [baseUrl]);
80
- exports.createRpcClient = createRpcClient;
81
- /**
82
- * Creates an RPC helper proxy for dynamic path matching based on a given endpoint structure.
83
- *
84
- * @template T - The type defining the RPC endpoint structure.
85
- *
86
- * @returns An object that provides dynamic RPC helper methods for the defined endpoints.
87
- *
88
- * @example
89
- * ```ts
90
- * // Create the RPC helper
91
- * const rpcHelper = createRpcHelper<PathStructure>();
92
- *
93
- * // Use the $match method to extract dynamic parameters from a URL path
94
- * const match = rpcHelper.fuga._foo.$match("/fuga/test");
95
- * // Expected output: { foo: "test" }
96
- *
97
- * // If the path does not match, it returns null
98
- * const noMatch = rpcHelper.fuga._foo.$match("/hoge/test");
99
- * // Expected output: null
100
- * ```
101
- */
102
- const createRpcHelper = () => (0, exports.createRpcProxy)({}, ["/"]);
103
- exports.createRpcHelper = createRpcHelper;
5
+ */import{httpMethod as m}from"./http-method";import{matchPath as f}from"./match";import{createUrl as p}from"./url";import{isDynamic as u,isHttpMethod as P}from"./utils";const i=(e,t=[],o={},n=[])=>new Proxy(c=>{const r=t.at(-1),a=n.at(-1);if(c===void 0)throw new Error(`An argument is required when calling the function for paramKey: ${a}`);if(r&&a&&u(r))return i(e,[...t],{...o,[a]:c},n);throw new Error(`paramKey: ${r} is not a dynamic parameter and cannot be called as a function`)},{get:(c,r)=>r==="$url"?p([...t],o,n):r==="$match"?f([...t],n):P(r)?m(r,[...t],o,n,{...e}):u(r)?i(e,[...t,r],o,[...n,r]):i(e,[...t,r],o,n)}),w=(e,t={})=>i(t,[e]),T=()=>i({},["/"]);export{w as createRpcClient,T as createRpcHelper,i as createRpcProxy};
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,57 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createUrl = exports.replaceDynamicSegments = exports.buildUrlSuffix = void 0;
4
- const buildUrlSuffix = (url) => {
5
- if (!url)
6
- return "";
7
- const query = url.query
8
- ? "?" + new URLSearchParams(url.query).toString()
9
- : "";
10
- const hash = url.hash ? `#${url.hash}` : "";
11
- return query + hash;
12
- };
13
- exports.buildUrlSuffix = buildUrlSuffix;
14
- const replaceDynamicSegments = (basePath, replacements) => basePath
15
- // optionalCatchAll
16
- .replace(/\/_{5}(\w+)/g, replacements.optionalCatchAll)
17
- // catchAll
18
- .replace(/\/_{3}(\w+)/g, replacements.catchAll)
19
- // dynamic
20
- .replace(/\/_(\w+)/g, replacements.dynamic);
21
- exports.replaceDynamicSegments = replaceDynamicSegments;
22
- const createUrl = (paths, params, dynamicKeys) => {
23
- const baseUrl = paths.shift();
24
- const basePath = `/${paths.join("/")}`;
25
- const dynamicPath = dynamicKeys.reduce((acc, key) => {
26
- const param = params[key];
27
- if (Array.isArray(param)) {
28
- return acc.replace(`/${key}`, `/${param.map(encodeURIComponent).join("/")}`);
29
- }
30
- if (param === undefined) {
31
- return acc.replace(`/${key}`, "");
32
- }
33
- return acc.replace(`/${key}`, `/${encodeURIComponent(param)}`);
34
- }, basePath);
35
- return (url) => {
36
- const relativePath = `${dynamicPath}${(0, exports.buildUrlSuffix)(url)}`;
37
- const pathname = (0, exports.replaceDynamicSegments)(basePath, {
38
- optionalCatchAll: "/[[...$1]]",
39
- catchAll: "/[...$1]",
40
- dynamic: "/[$1]",
41
- });
42
- const cleanedParams = {};
43
- for (const key in params) {
44
- const cleanedKey = key.replace(/^_+/, "");
45
- cleanedParams[cleanedKey] = params[key];
46
- }
47
- return {
48
- pathname,
49
- params: cleanedParams,
50
- path: baseUrl
51
- ? `${baseUrl.replace(/\/$/, "")}${relativePath}`
52
- : relativePath,
53
- relativePath,
54
- };
55
- };
56
- };
57
- exports.createUrl = createUrl;
1
+ const m=t=>{if(!t)return"";const n=t.query?"?"+new URLSearchParams(t.query).toString():"",c=t.hash?`#${t.hash}`:"";return n+c},u=(t,n)=>t.replace(/\/_{5}(\w+)/g,n.optionalCatchAll).replace(/\/_{3}(\w+)/g,n.catchAll).replace(/\/_(\w+)/g,n.dynamic),$=(t,n,c)=>{const s=t.shift(),o=`/${t.join("/")}`,p=c.reduce((a,r)=>{const e=n[r];return Array.isArray(e)?a.replace(`/${r}`,`/${e.map(encodeURIComponent).join("/")}`):e===void 0?a.replace(`/${r}`,""):a.replace(`/${r}`,`/${encodeURIComponent(e)}`)},o);return a=>{const r=`${p}${m(a)}`,e=u(o,{optionalCatchAll:"/[[...$1]]",catchAll:"/[...$1]",dynamic:"/[$1]"}),i={};for(const l in n){const h=l.replace(/^_+/,"");i[h]=n[l]}return{pathname:e,params:i,path:s?`${s.replace(/\/$/,"")}${r}`:r,relativePath:r}}};export{m as buildUrlSuffix,$ as createUrl,u as replaceDynamicSegments};
@@ -1,31 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deepMerge = exports.isHttpMethod = exports.isCatchAllOrOptional = exports.isDynamic = void 0;
4
- const constants_1 = require("../lib/constants");
5
- const isDynamic = (key) => key.startsWith(constants_1.DYNAMIC_PREFIX);
6
- exports.isDynamic = isDynamic;
7
- const isCatchAllOrOptional = (key) => key.startsWith(constants_1.CATCH_ALL_PREFIX) || key.startsWith(constants_1.OPTIONAL_CATCH_ALL_PREFIX);
8
- exports.isCatchAllOrOptional = isCatchAllOrOptional;
9
- const httpMethods = new Set(constants_1.HTTP_METHOD_FUNC_KEYS);
10
- const isHttpMethod = (value) => httpMethods.has(value);
11
- exports.isHttpMethod = isHttpMethod;
12
- const isPlainObject = (value) => {
13
- return typeof value === "object" && value !== null && !Array.isArray(value);
14
- };
15
- const deepMerge = (target, source) => {
16
- const result = Object.assign({}, target);
17
- for (const key in source) {
18
- if (Object.prototype.hasOwnProperty.call(source, key)) {
19
- const targetValue = target[key];
20
- const sourceValue = source[key];
21
- if (isPlainObject(targetValue) && isPlainObject(sourceValue)) {
22
- result[key] = (0, exports.deepMerge)(targetValue, sourceValue);
23
- }
24
- else {
25
- result[key] = sourceValue;
26
- }
27
- }
28
- }
29
- return result;
30
- };
31
- exports.deepMerge = deepMerge;
1
+ import{DYNAMIC_PREFIX as i,CATCH_ALL_PREFIX as a,OPTIONAL_CATCH_ALL_PREFIX as p,HTTP_METHOD_FUNC_KEYS as u}from"../lib/constants";const T=t=>t.startsWith(i),l=t=>t.startsWith(a)||t.startsWith(p),y=new Set(u),A=t=>y.has(t),c=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),d=(t,n)=>{const s={...t};for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e)){const r=t[e],o=n[e];c(r)&&c(o)?s[e]=d(r,o):s[e]=o}return s};export{d as deepMerge,l as isCatchAllOrOptional,T as isDynamic,A as isHttpMethod};
@@ -1,9 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HTTP_METHOD_FUNC_KEYS = exports.HTTP_METHODS_EXCLUDE_OPTIONS = exports.DYNAMIC_PREFIX = exports.CATCH_ALL_PREFIX = exports.OPTIONAL_CATCH_ALL_PREFIX = void 0;
4
- const http_1 = require("next/dist/server/web/http");
5
- exports.OPTIONAL_CATCH_ALL_PREFIX = "_____";
6
- exports.CATCH_ALL_PREFIX = "___";
7
- exports.DYNAMIC_PREFIX = "_";
8
- exports.HTTP_METHODS_EXCLUDE_OPTIONS = http_1.HTTP_METHODS.filter((method) => method !== "OPTIONS");
9
- exports.HTTP_METHOD_FUNC_KEYS = exports.HTTP_METHODS_EXCLUDE_OPTIONS.map((method) => `$${method.toLowerCase()}`);
1
+ import{HTTP_METHODS as o}from"next/dist/server/web/http";const e="_____",r="___",E="_",t=o.filter(_=>_!=="OPTIONS"),O=t.map(_=>`$${_.toLowerCase()}`);export{r as CATCH_ALL_PREFIX,E as DYNAMIC_PREFIX,t as HTTP_METHODS_EXCLUDE_OPTIONS,O as HTTP_METHOD_FUNC_KEYS,e as OPTIONAL_CATCH_ALL_PREFIX};
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,10 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createHandler = void 0;
4
- // I want to use currying so that the return value can be inferred.
5
- const createHandler = () => {
6
- return (handler) => {
7
- return handler;
8
- };
9
- };
10
- exports.createHandler = createHandler;
1
+ const a=()=>e=>e;export{a as createHandler};
@@ -1,25 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createRouteContext = void 0;
4
- const server_1 = require("next/server");
5
- const search_params_to_object_1 = require("./search-params-to-object");
6
- const createRouteContext = (req, segmentData) => {
7
- const validationResults = {};
8
- return {
9
- req: Object.assign(req, {
10
- query: () => (0, search_params_to_object_1.searchParamsToObject)(req.nextUrl.searchParams),
11
- params: () => segmentData.params,
12
- valid: (target) => {
13
- return validationResults[target];
14
- },
15
- addValidatedData: (target, value) => {
16
- validationResults[target] = value;
17
- },
18
- }),
19
- body: (data, init) => new server_1.NextResponse(data, init),
20
- json: (data, init) => server_1.NextResponse.json(data, init),
21
- text: (data, init) => new server_1.NextResponse(data, Object.assign(Object.assign({}, init), { headers: Object.assign({ "Content-Type": "text/plain" }, init === null || init === void 0 ? void 0 : init.headers) })),
22
- redirect: (url, init) => server_1.NextResponse.redirect(url, init),
23
- };
24
- };
25
- exports.createRouteContext = createRouteContext;
1
+ import{NextResponse as a}from"next/server";import{searchParamsToObject as p}from"./search-params-to-object";const d=(s,o)=>{const n={};return{req:Object.assign(s,{query:()=>p(s.nextUrl.searchParams),params:()=>o.params,valid:t=>n[t],addValidatedData:(t,e)=>{n[t]=e}}),body:(t,e)=>new a(t,e),json:(t,e)=>a.json(t,e),text:(t,e)=>new a(t,{...e,headers:{"Content-Type":"text/plain",...e?.headers}}),redirect:(t,e)=>a.redirect(t,e)}};export{d as createRouteContext};
@@ -1,5 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.routeHandlerFactory = void 0;
4
- var route_handler_factory_1 = require("./route-handler-factory");
5
- Object.defineProperty(exports, "routeHandlerFactory", { enumerable: true, get: function () { return route_handler_factory_1.routeHandlerFactory; } });
1
+ import{routeHandlerFactory as p}from"./route-handler-factory";export{p as routeHandlerFactory};
@@ -1,71 +1,4 @@
1
- "use strict";
2
1
  /*!
3
2
  * Inspired by Hono (https://github.com/honojs/hono),
4
3
  * particularly its routing design and handler interface.
5
- */
6
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
- return new (P || (P = Promise))(function (resolve, reject) {
9
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
- step((generator = generator.apply(thisArg, _arguments || [])).next());
13
- });
14
- };
15
- Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.routeHandlerFactory = void 0;
17
- const create_route_context_1 = require("./create-route-context");
18
- const composeHandlersWithError = (handlers, onError) => {
19
- return (req, segmentData) => __awaiter(void 0, void 0, void 0, function* () {
20
- const routeContext = (0, create_route_context_1.createRouteContext)(req, segmentData);
21
- try {
22
- for (const handler of handlers) {
23
- const result = yield handler(routeContext);
24
- if (result instanceof Response) {
25
- return result;
26
- }
27
- }
28
- throw new Error("No handler returned a response");
29
- }
30
- catch (error) {
31
- return yield onError(error, routeContext);
32
- }
33
- });
34
- };
35
- /**
36
- * A factory function that creates route handlers for various HTTP methods (GET, POST, etc.).
37
- *
38
- * Optionally accepts a global error handler that will be used if any route handler throws.
39
- *
40
- * Example usage:
41
- * ```ts
42
- * const createRouteHandler = routeHandlerFactory((err, rc) => rc.text("error", {status : 400}));
43
- * export const { POST } = createRouteHandler<{ params: ..., query: ... }>().post((rc) => rc.json({success: true}));
44
- * ```
45
- *
46
- * @template TOnErrorResponse Type of the response returned by the error handler (optional)
47
- * @param onError Optional global error handler. If not provided, errors will be re-thrown.
48
- * @returns An object with methods (`get`, `post`, `put`, etc.) to define route handlers for each HTTP method
49
- */
50
- const routeHandlerFactory = (onError) => () => {
51
- const defineRouteForMethod = (method) => {
52
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
53
- return ((...handlers) => {
54
- const resolvedOnError = onError !== null && onError !== void 0 ? onError : ((error, _) => {
55
- throw error;
56
- });
57
- const routeHandler = composeHandlersWithError(handlers, resolvedOnError);
58
- return { [method]: routeHandler };
59
- });
60
- };
61
- return {
62
- get: defineRouteForMethod("GET"),
63
- post: defineRouteForMethod("POST"),
64
- put: defineRouteForMethod("PUT"),
65
- delete: defineRouteForMethod("DELETE"),
66
- patch: defineRouteForMethod("PATCH"),
67
- head: defineRouteForMethod("HEAD"),
68
- options: defineRouteForMethod("OPTIONS"),
69
- };
70
- };
71
- exports.routeHandlerFactory = routeHandlerFactory;
4
+ */import{createRouteContext as d}from"./create-route-context";const i=(o,e)=>async(n,s)=>{const a=d(n,s);try{for(const r of o){const t=await r(a);if(t instanceof Response)return t}throw new Error("No handler returned a response")}catch(r){return await e(r,a)}},T=o=>()=>{const e=n=>(...s)=>{const r=i(s,o??((t,p)=>{throw t}));return{[n]:r}};return{get:e("GET"),post:e("POST"),put:e("PUT"),delete:e("DELETE"),patch:e("PATCH"),head:e("HEAD"),options:e("OPTIONS")}};export{T as routeHandlerFactory};
@@ -1,4 +1,3 @@
1
- "use strict";
2
1
  /*!
3
2
  * Portions of this code are based on the Hono project (https://github.com/honojs/hono),
4
3
  * originally created by Yusuke Wada (https://github.com/yusukebe) and developed with
@@ -7,4 +6,3 @@
7
6
  * Original copyright belongs to Yusuke Wada and the Hono project contributors.
8
7
  * Hono is licensed under the MIT License.
9
8
  */
10
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,18 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.searchParamsToObject = void 0;
4
- const searchParamsToObject = (searchParams) => {
5
- const params = {};
6
- searchParams.forEach((value, key) => {
7
- if (key in params) {
8
- params[key] = Array.isArray(params[key])
9
- ? [...params[key], value]
10
- : [params[key], value];
11
- }
12
- else {
13
- params[key] = value;
14
- }
15
- });
16
- return params;
17
- };
18
- exports.searchParamsToObject = searchParamsToObject;
1
+ const a=t=>{const r={};return t.forEach((n,s)=>{s in r?r[s]=Array.isArray(r[s])?[...r[s],n]:[r[s],n]:r[s]=n}),r};export{a as searchParamsToObject};
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,31 +1 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.getCookiesObject = exports.getHeadersObject = void 0;
13
- const headers_1 = require("next/headers");
14
- const getHeadersObject = () => __awaiter(void 0, void 0, void 0, function* () {
15
- const headersList = yield (0, headers_1.headers)();
16
- const headersObj = {};
17
- for (const [key, value] of headersList.entries()) {
18
- headersObj[key] = value;
19
- }
20
- return headersObj;
21
- });
22
- exports.getHeadersObject = getHeadersObject;
23
- const getCookiesObject = () => __awaiter(void 0, void 0, void 0, function* () {
24
- const cookiesList = yield (0, headers_1.cookies)();
25
- const cookiesObj = {};
26
- for (const cookie of cookiesList.getAll()) {
27
- cookiesObj[cookie.name] = cookie.value;
28
- }
29
- return cookiesObj;
30
- });
31
- exports.getCookiesObject = getCookiesObject;
1
+ import{cookies as r,headers as c}from"next/headers";const i=async()=>{const t=await c(),e={};for(const[o,s]of t.entries())e[o]=s;return e},a=async()=>{const t=await r(),e={};for(const o of t.getAll())e[o.name]=o.value;return e};export{a as getCookiesObject,i as getHeadersObject};
@@ -1,5 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.zodValidator = void 0;
4
- var zod_validator_1 = require("./zod-validator");
5
- Object.defineProperty(exports, "zodValidator", { enumerable: true, get: function () { return zod_validator_1.zodValidator; } });
1
+ import{zodValidator as a}from"./zod-validator";export{a as zodValidator};