primdy 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +124 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/runtime/cookies.d.ts +22 -0
- package/dist/runtime/response.d.ts +3 -0
- package/dist/runtime/types.d.ts +18 -0
- package/dist/server/index.js +38 -0
- package/package.json +38 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Primdy
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# Primdy
|
|
2
|
+
|
|
3
|
+
Blazingly fast, file-system routed API framework optimized for [Bun](https://bun.sh).
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
bun add primdy
|
|
9
|
+
# or
|
|
10
|
+
npm install primdy
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quickstart
|
|
14
|
+
|
|
15
|
+
Create a route by adding a `route.ts` file under `src/` (or whatever `src` you configure) and exporting an HTTP method handler:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
// src/route.ts
|
|
19
|
+
export async function GET() {
|
|
20
|
+
return Response.json({ ok: true });
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Start the dev server:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
primdy dev
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
That's it! You can now make a request to `http://localhost:3000/` and expect `{"ok": true}`.
|
|
31
|
+
|
|
32
|
+
## Routing
|
|
33
|
+
|
|
34
|
+
Routes are defined by `route.ts` files. Each exported HTTP method (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`) becomes a handler for that method.
|
|
35
|
+
|
|
36
|
+
The syntax is the same as Next.js's API routes in App Router, with the exception that you return `Response` instead of `NextResponse`:
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
// src/users/[id]/route.ts
|
|
40
|
+
export async function GET(
|
|
41
|
+
request: Request,
|
|
42
|
+
{ params }: { params: { id: string } },
|
|
43
|
+
) {
|
|
44
|
+
return Response.json({ id: params.id });
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Catch-all and optional catch-all segments also produce a `string[]` param instead of a `string`:
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
// src/docs/[...slug]/route.ts
|
|
52
|
+
export async function GET(
|
|
53
|
+
request: Request,
|
|
54
|
+
{ params }: { params: { slug: string[] } },
|
|
55
|
+
) {
|
|
56
|
+
return Response.json({ slug: params.slug });
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Middleware
|
|
61
|
+
|
|
62
|
+
Use a `middleware.ts` or `proxy.ts` file to run code before every route in that directory. Export a `default`, `middleware`, or `proxy` function:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
// src/users/proxy.ts
|
|
66
|
+
export function proxy(request: Request) {
|
|
67
|
+
const auth = request.headers.get("authorization");
|
|
68
|
+
if (!auth) {
|
|
69
|
+
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Helpers
|
|
75
|
+
|
|
76
|
+
For convenience, `primdy` exports few helper functions for creating responses:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import { json, text, redirect } from "primdy";
|
|
80
|
+
|
|
81
|
+
json({ hello: "world" });
|
|
82
|
+
text("hello");
|
|
83
|
+
redirect("/auth");
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Cookies
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { cookies, setCookie, deleteCookie } from "primdy";
|
|
90
|
+
|
|
91
|
+
export async function GET(request: Request) {
|
|
92
|
+
const theme = cookies(request).get("theme")?.value ?? "light";
|
|
93
|
+
const response = Response.json({ theme });
|
|
94
|
+
return setCookie(response, "theme", theme, { path: "/", httpOnly: true });
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Configuration
|
|
99
|
+
|
|
100
|
+
Create a `primdy.config.ts` at your project root:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import type { PrimdyConfig } from "primdy";
|
|
104
|
+
|
|
105
|
+
export default {
|
|
106
|
+
src: "src",
|
|
107
|
+
port: 3000,
|
|
108
|
+
hostname: "localhost",
|
|
109
|
+
node: false,
|
|
110
|
+
} satisfies PrimdyConfig;
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## CLI
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
primdy dev
|
|
117
|
+
primdy build
|
|
118
|
+
primdy start
|
|
119
|
+
primdy analyze
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Production builds
|
|
123
|
+
|
|
124
|
+
In production, you probably want to serve `primdy start` instead of `primdy dev`. Use `primdy build` to bundle your application first!
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function s(n,r){return Response.json(n,r)}function u(n,r){return new Response(n,r)}function a(n,r=307){return Response.redirect(n,r)}function c(n){let r=new Map;if(!n)return r;for(let e of n.split(";")){let t=e.indexOf("=");if(t===-1)continue;let i=e.slice(t+1).trim();try{r.set(e.slice(0,t).trim(),decodeURIComponent(i))}catch{r.set(e.slice(0,t).trim(),i)}}return r}var p=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function d(n,r,e={}){if(!p.test(n))throw Error(`Invalid cookie ${JSON.stringify(n)}`);let t=`${n}=${encodeURIComponent(r)}`;if(e.maxAge!==void 0)t+=`; Max-Age=${e.maxAge}`;if(e.expires)t+=`; Expires=${e.expires.toUTCString()}`;if(e.domain)t+=`; Domain=${e.domain}`;if(e.path)t+=`; Path=${e.path}`;if(e.secure)t+="; Secure";if(e.httpOnly)t+="; HttpOnly";if(e.sameSite)t+=`; SameSite=${e.sameSite[0].toUpperCase()}${e.sameSite.slice(1)}`;return t}function f(n){let r=c(n.headers.get("cookie"));return{get(e){let t=r.get(e);return t===void 0?void 0:{name:e,value:t}},getAll(){return[...r].map(([e,t])=>({name:e,value:t}))}}}function o(n,r,e,t){return n.headers.append("Set-Cookie",d(r,e,t)),n}function l(n,r,e={}){return o(n,r,"",{...e,maxAge:0})}export{f as cookies,l as deleteCookie,s as json,a as redirect,o as setCookie,u as text};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
type CookieOptions = {
|
|
2
|
+
maxAge?: number;
|
|
3
|
+
expires?: Date;
|
|
4
|
+
domain?: string;
|
|
5
|
+
path?: string;
|
|
6
|
+
secure?: boolean;
|
|
7
|
+
httpOnly?: boolean;
|
|
8
|
+
sameSite?: "strict" | "lax" | "none";
|
|
9
|
+
};
|
|
10
|
+
export declare function cookies(request: Request): {
|
|
11
|
+
get(name: string): {
|
|
12
|
+
name: string;
|
|
13
|
+
value: string;
|
|
14
|
+
} | undefined;
|
|
15
|
+
getAll(): {
|
|
16
|
+
name: string;
|
|
17
|
+
value: string;
|
|
18
|
+
}[];
|
|
19
|
+
};
|
|
20
|
+
export declare function setCookie(response: Response, name: string, value: string, options?: CookieOptions): Response;
|
|
21
|
+
export declare function deleteCookie(response: Response, name: string, options?: Omit<CookieOptions, "expires">): Response;
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type HTTPMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
|
|
2
|
+
export type RouteContext<P extends Record<string, string | string[]> = Record<string, string | string[]>> = {
|
|
3
|
+
params: P;
|
|
4
|
+
};
|
|
5
|
+
export type RouteHandler<P extends Record<string, string | string[]> = Record<string, string | string[]>> = (request: Request, context: RouteContext<P>) => Response | Promise<Response>;
|
|
6
|
+
export type RouteModule = Partial<Record<HTTPMethod, RouteHandler>>;
|
|
7
|
+
export type MiddlewareHandler = (request: Request, context: RouteContext) => Response | void | Promise<Response | void>;
|
|
8
|
+
export type MiddlewareModule = {
|
|
9
|
+
default?: MiddlewareHandler;
|
|
10
|
+
middleware?: MiddlewareHandler;
|
|
11
|
+
proxy?: MiddlewareHandler;
|
|
12
|
+
};
|
|
13
|
+
export type PrimdyConfig = {
|
|
14
|
+
src?: string;
|
|
15
|
+
port?: number;
|
|
16
|
+
hostname?: string;
|
|
17
|
+
node?: boolean;
|
|
18
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @bun
|
|
3
|
+
import{access as Nt,readdir as Mt}from"fs/promises";import{join as Ht,resolve as Ft}from"path";class w extends Error{constructor(e,t,i){super(i);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class x extends w{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class H{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new x(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,i);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function F(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}import{EventEmitter as Be}from"events";import q from"child_process";import y from"path";import I from"fs";import d from"process";import{stripVTControlCharacters as Ge}from"util";import{stripVTControlCharacters as Ie}from"util";class V{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((n)=>!n._hidden),i=e._getHelpCommand();if(i&&!i._hidden)t.push(i);if(this.sortSubcommands)t.sort((n,r)=>n.name().localeCompare(r.name()));return t}compareOptions(e,t){let i=(n)=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter((n)=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),r=i.long&&e._findOption(i.long);if(!n&&!r)t.push(i);else if(i.long&&!r)t.push(e.createOption(i.long,i.description));else if(i.short&&!n)t.push(e.createOption(i.short,i.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter((r)=>!r.hidden);t.push(...n)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((i)=>F(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,n)=>Math.max(i,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((i)=>JSON.stringify(i)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let i=`(${t.join(", ")})`;if(e.description)return`${e.description} ${i}`;return i}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((i)=>JSON.stringify(i)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let i=`(${t.join(", ")})`;if(e.description)return`${e.description} ${i}`;return i}return e.description}formatItemList(e,t,i){if(t.length===0)return[];return[i.styleTitle(e),...t,""]}groupItems(e,t,i){let n=new Map;return e.forEach((r)=>{let s=i(r);if(!n.has(s))n.set(s,[])}),t.forEach((r)=>{let s=i(r);if(!n.has(s))n.set(s,[]);n.get(s).push(r)}),n}formatHelp(e,t){let i=t.padWidth(e,t),n=t.helpWidth??80;function r(u,h){return t.formatItem(u,i,h,t)}let s=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],o=t.commandDescription(e);if(o.length>0)s=s.concat([t.boxWrap(t.styleCommandDescription(o),n),""]);let a=t.visibleArguments(e).map((u)=>r(t.styleArgumentTerm(t.argumentTerm(u)),t.styleArgumentDescription(t.argumentDescription(u))));if(s=s.concat(this.formatItemList("Arguments:",a,t)),this.groupItems(e.options,t.visibleOptions(e),(u)=>u.helpGroupHeading??"Options:").forEach((u,h)=>{let A=u.map((C)=>r(t.styleOptionTerm(t.optionTerm(C)),t.styleOptionDescription(t.optionDescription(C))));s=s.concat(this.formatItemList(h,A,t))}),t.showGlobalOptions){let u=t.visibleGlobalOptions(e).map((h)=>r(t.styleOptionTerm(t.optionTerm(h)),t.styleOptionDescription(t.optionDescription(h))));s=s.concat(this.formatItemList("Global Options:",u,t))}return this.groupItems(e.commands,t.visibleCommands(e),(u)=>u.helpGroup()||"Commands:").forEach((u,h)=>{let A=u.map((C)=>r(t.styleSubcommandTerm(t.subcommandTerm(C)),t.styleSubcommandDescription(t.subcommandDescription(C))));s=s.concat(this.formatItemList(h,A,t))}),s.join(`
|
|
4
|
+
`)}displayWidth(e){return Ie(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t==="[command]")return this.styleSubcommandText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleCommandText(t)}).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleSubcommandText(t)}).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,i,n){let s=" ".repeat(2);if(!i)return s+e;let o=e.padEnd(t+e.length-n.displayWidth(e)),a=2,l=(this.helpWidth??80)-t-a-2,u;if(l<this.minWidthToWrap||n.preformatted(i))u=i;else u=n.boxWrap(i,l).replace(/\n/g,`
|
|
5
|
+
`+" ".repeat(t+a));return s+o+" ".repeat(a)+u.replace(/\n/g,`
|
|
6
|
+
${s}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return i.forEach((s)=>{let o=s.match(n);if(o===null){r.push("");return}let a=[o.shift()],c=this.displayWidth(a[0]);o.forEach((l)=>{let u=this.displayWidth(l);if(c+u<=t){a.push(l),c+=u;return}r.push(a.join(""));let h=l.trimStart();a=[h],c=this.displayWidth(h)}),r.push(a.join(""))}),r.join(`
|
|
7
|
+
`)}}class S{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=je(e);if(this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;if(typeof e==="string")t={[e]:!0};return this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new x(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,i);return t},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return ne(this.name().replace(/^no-/,""));return ne(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class L{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((t)=>{if(t.negate)this.negativeOptions.set(t.attributeName(),t);else this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,i)=>{if(this.positiveOptions.has(i))this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,r=n!==void 0?n:!1;return t.negate===(r===e)}}function ne(e){return e.split("-").reduce((t,i)=>t+i[0].toUpperCase()+i.slice(1))}function je(e){let t,i,n=/^-[^-]$/,r=/^--[^-]/,s=e.split(/[ |,]+/).concat("guard");if(n.test(s[0]))t=s.shift();if(r.test(s[0]))i=s.shift();if(!t&&n.test(s[0]))t=s.shift();if(!t&&r.test(s[0]))t=i,i=s.shift();if(s[0].startsWith("-")){let o=s[0],a=`option creation failed due to '${o}' in option flags '${e}'`;if(/^-[^-][^-]/.test(o))throw Error(`${a}
|
|
8
|
+
- a short flag is a single dash and a single character
|
|
9
|
+
- either use a single dash and a single character (for a short flag)
|
|
10
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(n.test(o))throw Error(`${a}
|
|
11
|
+
- too many short flags`);if(r.test(o))throw Error(`${a}
|
|
12
|
+
- too many long flags`);throw Error(`${a}
|
|
13
|
+
- unrecognised flag format`)}if(t===void 0&&i===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:i}}function De(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let i=[];for(let n=0;n<=e.length;n++)i[n]=[n];for(let n=0;n<=t.length;n++)i[0][n]=n;for(let n=1;n<=t.length;n++)for(let r=1;r<=e.length;r++){let s;if(e[r-1]===t[n-1])s=0;else s=1;if(i[r][n]=Math.min(i[r-1][n]+1,i[r][n-1]+1,i[r-1][n-1]+s),r>1&&n>1&&e[r-1]===t[n-2]&&e[r-2]===t[n-1])i[r][n]=Math.min(i[r][n],i[r-2][n-2]+1)}return i[e.length][t.length]}function U(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let i=e.startsWith("--");if(i)e=e.slice(2),t=t.map((o)=>o.slice(2));let n=[],r=3,s=0.4;if(t.forEach((o)=>{if(o.length<=1)return;let a=De(e,o),c=Math.max(e.length,o.length);if((c-a)/c>s){if(a<r)r=a,n=[o];else if(a===r)n.push(o)}}),n.sort((o,a)=>o.localeCompare(a)),i)n=n.map((o)=>`--${o}`);if(n.length>1)return`
|
|
14
|
+
(Did you mean one of ${n.join(", ")}?)`;if(n.length===1)return`
|
|
15
|
+
(Did you mean ${n[0]}?)`;return""}class E extends Be{constructor(e){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(t)=>d.stdout.write(t),writeErr:(t)=>d.stderr.write(t),outputError:(t,i)=>i(t),getOutHelpWidth:()=>d.stdout.isTTY?d.stdout.columns:void 0,getErrHelpWidth:()=>d.stderr.isTTY?d.stderr.columns:void 0,getOutHasColors:()=>se()??(d.stdout.isTTY&&d.stdout.hasColors?.()),getErrHasColors:()=>se()??(d.stderr.isTTY&&d.stderr.hasColors?.()),stripColor:(t)=>Ge(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,i){let n=t,r=i;if(typeof n==="object"&&n!==null)r=n,n=null;r=r||{};let[,s,o]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(s);if(n)a.description(n),a._executableHandler=!0;if(r.isDefault)this._defaultCommandName=a._name;if(a._hidden=!!(r.noHelp||r.hidden),a._executableFile=r.executableFile||null,o)a.arguments(o);if(this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),n)return this;return a}createCommand(e){return new E(e)}createHelp(){return Object.assign(new V,this.configureHelp())}configureHelp(e){if(e===void 0)return this._helpConfiguration;return this._helpConfiguration=e,this}configureOutput(e){if(e===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...e},this}showHelpAfterError(e=!0){if(typeof e!=="string")e=!!e;return this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
|
|
16
|
+
- specify the name in Command constructor or using .name()`);if(t=t||{},t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new H(e,t)}argument(e,t,i,n){let r=this.createArgument(e,t);if(typeof i==="function")r.default(n).argParser(i);else r.default(i);return this.addArgument(r),this}arguments(e){return e.trim().split(/ +/).forEach((t)=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==="boolean"){if(this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let i=e??"help [command]",[,n,r]=i.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(n);if(o.helpOption(!1),r)o.arguments(r);if(s)o.description(s);if(this._addImplicitHelpCommand=!0,this._helpCommand=o,e||t)this._initCommandGroup(o);return this}addHelpCommand(e,t){if(typeof e!=="object")return this.helpCommand(e,t),this;return this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(e,t){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
|
|
17
|
+
Expecting one of '${i.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,i){if(this._exitCallback)this._exitCallback(new w(e,t,i));d.exit(e)}action(e){let t=(i)=>{let n=this.registeredArguments.length,r=i.slice(0,n);if(this._storeOptionsAsProperties)r[n]=this;else r[n]=this.opts();return r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new S(e,t)}_callParseArg(e,t,i,n){try{return e.parseArg(t,i)}catch(r){if(r.code==="commander.invalidArgument"){let s=`${n} ${r.message}`;this.error(s,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let i=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
|
|
18
|
+
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(n)=>[n.name()].concat(n.aliases()),i=t(e).find((n)=>this._findCommand(n));if(i){let n=t(this._findCommand(i)).join("|"),r=t(e).join("|");throw Error(`cannot add command '${r}' as already have command '${n}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.defaultValue!==void 0)this.setOptionValueWithSource(i,e.defaultValue,"default");let n=(r,s,o)=>{if(r==null&&e.presetArg!==void 0)r=e.presetArg;let a=this.getOptionValue(i);if(r!==null&&e.parseArg)r=this._callParseArg(e,r,a,s);else if(r!==null&&e.variadic)r=e._collectValue(r,a);if(r==null)if(e.negate)r=!1;else if(e.isBoolean()||e.optional)r=!0;else r="";this.setOptionValueWithSource(i,r,o)};if(this.on("option:"+t,(r)=>{let s=`error: option '${e.flags}' argument '${r}' is invalid.`;n(r,s,"cli")}),e.envVar)this.on("optionEnv:"+t,(r)=>{let s=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;n(r,s,"env")});return this}_optionEx(e,t,i,n,r){if(typeof t==="object"&&t instanceof S)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(t,i);if(s.makeOptionMandatory(!!e.mandatory),typeof n==="function")s.default(r).argParser(n);else if(n instanceof RegExp){let o=n;n=(a,c)=>{let l=o.exec(a);return l?l[0]:c},s.default(r).argParser(n)}else s.default(n);return this.addOption(s)}option(e,t,i,n){return this._optionEx({},e,t,i,n)}requiredOption(e,t,i,n){return this._optionEx({mandatory:!0},e,t,i,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,i){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((i)=>{if(i.getOptionValueSource(e)!==void 0)t=i.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(d.versions?.electron)t.from="electron";let n=d.execArgv??[];if(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))t.from="eval"}if(e===void 0)e=d.argv;this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":if(d.defaultApp)this._scriptPath=e[1],i=e.slice(2);else i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",i}parse(e,t){this._prepareForParse();let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){this._prepareForParse();let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_prepareForParse(){if(this._savedState===null)this.options.filter((e)=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach((e)=>{let t=e.long.replace(/^--no-/,"--");if(!this._findOption(t))this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
19
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,i){if(I.existsSync(e))return;let n=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${e}' does not exist
|
|
20
|
+
- if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
21
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
22
|
+
- ${n}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let i=[".js",".ts",".tsx",".mjs",".cjs"];function n(l,u){let h=y.resolve(l,u);if(I.existsSync(h))return h;if(i.includes(y.extname(u)))return;let A=i.find((C)=>I.existsSync(`${h}${C}`));if(A)return`${h}${A}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=e._executableFile||`${this._name}-${e._name}`,s=this._executableDir||"";if(this._scriptPath){let l;try{l=I.realpathSync(this._scriptPath)}catch{l=this._scriptPath}s=y.resolve(y.dirname(l),s)}if(s){let l=n(s,r);if(!l&&!e._executableFile&&this._scriptPath){let u=y.basename(this._scriptPath,y.extname(this._scriptPath));if(u!==this._name)l=n(s,`${u}-${e._name}`)}r=l||r}let o=i.includes(y.extname(r)),a;if(d.platform!=="win32")if(o)t.unshift(r),t=re(d.execArgv).concat(t),a=q.spawn(d.argv[0],t,{stdio:"inherit"});else a=q.spawn(r,t,{stdio:"inherit"});else this._checkForMissingExecutable(r,s,e._name),t.unshift(r),t=re(d.execArgv).concat(t),a=q.spawn(d.execPath,t,{stdio:"inherit"});if(!a.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((u)=>{d.on(u,()=>{if(a.killed===!1&&a.exitCode===null)a.kill(u)})});let c=this._exitCallback;a.on("close",(l)=>{if(l=l??1,!c)d.exit(l);else c(new w(l,"commander.executeSubCommandAsync","(close)"))}),a.on("error",(l)=>{if(l.code==="ENOENT")this._checkForMissingExecutable(r,s,e._name);else if(l.code==="EACCES")throw Error(`'${r}' not executable`);if(!c)d.exit(1);else{let u=new w(1,"commander.executeSubCommandAsync","(error)");u.nestedError=l,c(u)}}),this.runningCommand=a}_dispatchSubcommand(e,t,i){let n=this._findCommand(e);if(!n)this.help({error:!0});n._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,n,"preSubcommand"),r=this._chainOrCall(r,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(i));else return n._parseCommand(t,i)}),r}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(i,n,r)=>{let s=n;if(n!==null&&i.parseArg){let o=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;s=this._callParseArg(i,n,r,o)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,n)=>{let r=i.defaultValue;if(i.variadic){if(n<this.args.length){if(r=this.args.slice(n),i.parseArg)r=r.reduce((s,o)=>e(i,o,s),i.defaultValue)}else if(r===void 0)r=[]}else if(n<this.args.length){if(r=this.args[n],i.parseArg)r=e(i,r,i.defaultValue)}t[n]=r}),this.processedArgs=t}_chainOrCall(e,t){if(e?.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let i=e,n=[];if(this._getCommandAndAncestors().reverse().filter((r)=>r._lifeCycleHooks[t]!==void 0).forEach((r)=>{r._lifeCycleHooks[t].forEach((s)=>{n.push({hookedCommand:r,callback:s})})}),t==="postAction")n.reverse();return n.forEach((r)=>{i=this._chainOrCall(i,()=>r.callback(r.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let n=e;if(this._lifeCycleHooks[i]!==void 0)this._lifeCycleHooks[i].forEach((r)=>{n=this._chainOrCall(n,()=>r(this,t))});return n}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{if(i.unknown.length>0)this.unknownOption(i.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let s;if(s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent)s=this._chainOrCall(s,()=>{this.parent.emit(r,e,t)});return s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent?.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else n(),this._processArguments()}else if(this.commands.length)n(),this.help({error:!0});else n(),this._processArguments()}_findCommand(e){if(!e)return;return this.commands.find((t)=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find((t)=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((e)=>{e.options.forEach((t)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((i)=>{let n=i.attributeName();if(this.getOptionValue(n)===void 0)return!1;return this.getOptionValueSource(n)!=="default"});e.filter((i)=>i.conflictsWith.length>0).forEach((i)=>{let n=e.find((r)=>i.conflictsWith.includes(r.attributeName()));if(n)this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],n=t;function r(l){return l.length>1&&l[0]==="-"}let s=(l)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(l))return!1;return!this._getCommandAndAncestors().some((u)=>u.options.map((h)=>h.short).some((h)=>/^-\d$/.test(h)))},o=null,a=null,c=0;while(c<e.length||a){let l=a??e[c++];if(a=null,l==="--"){if(n===i)n.push(l);n.push(...e.slice(c));break}if(o&&(!r(l)||s(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,r(l)){let u=this._findOption(l);if(u){if(u.required){let h=e[c++];if(h===void 0)this.optionMissingArgument(u);this.emit(`option:${u.name()}`,h)}else if(u.optional){let h=null;if(c<e.length&&(!r(e[c])||s(e[c])))h=e[c++];this.emit(`option:${u.name()}`,h)}else this.emit(`option:${u.name()}`);o=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){if(u.required||u.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${u.name()}`,l.slice(2));else this.emit(`option:${u.name()}`),a=`-${l.slice(2)}`;continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),h=this._findOption(l.slice(0,u));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,l.slice(u+1));continue}}if(n===t&&r(l)&&!(this.commands.length===0&&s(l)))n=i;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(l)){t.push(l),i.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){i.push(l,...e.slice(c));break}}if(this._passThroughOptions){n.push(l,...e.slice(c));break}n.push(l)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let n=this.options[i].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
|
|
23
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
24
|
+
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
25
|
+
`),this.outputHelp({error:!0});let i=t||{},n=i.exitCode||1,r=i.code||"commander.error";this._exit(n,r,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in d.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,d.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new L(this.options),t=(i)=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter((i)=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach((i)=>{Object.keys(i.implied).filter((n)=>!t(n)).forEach((n)=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let i=(s)=>{let o=s.attributeName(),a=this.getOptionValue(o),c=this.options.find((u)=>u.negate&&o===u.attributeName()),l=this.options.find((u)=>!u.negate&&o===u.attributeName());if(c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg))return c;return l||s},n=(s)=>{let o=i(s),a=o.attributeName();if(this.getOptionValueSource(a)==="env")return`environment variable '${o.envVar}'`;return`option '${o.flags}'`},r=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],r=this;do{let s=r.createHelp().visibleOptions(r).filter((o)=>o.long).map((o)=>o.long);n=n.concat(s),r=r.parent}while(r&&!r._enablePositionalOptions);t=U(e,n)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",n=e.length,r=this.parent?` for '${this.name()}'`:"",s=e.join(", "),o=`error: too many arguments${r}. Expected ${t} argument${i} but got ${n}: ${s}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach((r)=>{if(n.push(r.name()),r.alias())n.push(r.alias())}),t=U(e,n)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let n=this.createOption(t,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
26
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return this._summary=e,this}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)t=this.commands[this.commands.length-1];if(e===t._name)throw Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((t)=>this.alias(t)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map((i)=>F(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){if(e===void 0)return this._name;return this._name=e,this}helpGroup(e){if(e===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=e,this}commandsGroup(e){if(e===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=e,this}optionsGroup(e){if(e===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=e,this}_initOptionGroup(e){if(this._defaultOptionGroup&&!e.helpGroupHeading)e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){if(this._defaultCommandGroup&&!e.helpGroup())e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=y.basename(e,y.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp(),i=this._getOutputContext(e);t.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=t.formatHelp(this,t);if(i.hasColors)return n;return this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let t=!!e.error,i,n,r;if(t)i=(o)=>this._outputConfiguration.writeErr(o),n=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth();else i=(o)=>this._outputConfiguration.writeOut(o),n=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(o)=>{if(!n)o=this._outputConfiguration.stripColor(o);return i(o)},hasColors:n,helpWidth:r}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let i=this._getOutputContext(e),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach((s)=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation({error:i.error});if(t){if(r=t(r),typeof r!=="string"&&!Buffer.isBuffer(r))throw Error("outputHelp callback must return a string or a Buffer")}if(i.write(r),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",n),this._getCommandAndAncestors().forEach((s)=>s.emit("afterAllHelp",n))}helpOption(e,t){if(typeof e==="boolean"){if(e){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),e||t)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(d.exitCode??0);if(t===0&&e&&typeof e!=="function"&&e.error)t=1;this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
27
|
+
Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,(r)=>{let s;if(typeof t==="function")s=t({error:r.error,command:r.command});else s=t;if(s)r.write(`${s}
|
|
28
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((n)=>t.is(n)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function re(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let i,n="127.0.0.1",r="9229",s;if((s=t.match(/^(--inspect(-brk)?)$/))!==null)i=s[1];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(i=s[1],/^\d+$/.test(s[3]))r=s[3];else n=s[3];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)i=s[1],n=s[3],r=s[4];if(i&&r!=="0")return`${i}=${n}:${parseInt(r)+1}`;return t})}function se(){if(d.env.NO_COLOR||d.env.FORCE_COLOR==="0"||d.env.FORCE_COLOR==="false")return!1;if(d.env.FORCE_COLOR||d.env.CLICOLOR_FORCE!==void 0)return!0;return}var pi=new E;function oe(e,t,i){let n=e.indexOf(t);if(n===-1)return e;let r=t.length,s=0,o="";do o+=e.slice(s,n)+t+i,s=n+r,n=e.indexOf(t,s);while(n!==-1);return o+=e.slice(s),o}function ae(e,t,i,n){let r=0,s="";do{let o=e[n-1]==="\r";s+=e.slice(r,o?n-1:n)+t+(o?`\r
|
|
29
|
+
`:`
|
|
30
|
+
`)+i,r=n+1,n=e.indexOf(`
|
|
31
|
+
`,r)}while(n!==-1);return s+=e.slice(r),s}var le=(e=0)=>(t)=>`\x1B[${t+e}m`,Y=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,z=(e=0)=>(t,i,n)=>`\x1B[${38+e};2;${t};${i};${n}m`,We=(e)=>`\x1B[58;5;${e<90?e-30:e-90+8}m`,p={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:["4:2",24],underlineCurly:["4:3",24],underlineDotted:["4:4",24],underlineDashed:["4:5",24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]},underlineColor:{underlineBlack:["58;5;0",59],underlineRed:["58;5;1",59],underlineGreen:["58;5;2",59],underlineYellow:["58;5;3",59],underlineBlue:["58;5;4",59],underlineMagenta:["58;5;5",59],underlineCyan:["58;5;6",59],underlineWhite:["58;5;7",59],underlineBlackBright:["58;5;8",59],underlineGray:["58;5;8",59],underlineGrey:["58;5;8",59],underlineRedBright:["58;5;9",59],underlineGreenBright:["58;5;10",59],underlineYellowBright:["58;5;11",59],underlineBlueBright:["58;5;12",59],underlineMagentaBright:["58;5;13",59],underlineCyanBright:["58;5;14",59],underlineWhiteBright:["58;5;15",59]}},gi=Object.keys(p.modifier),Le=Object.keys(p.color),Ue=Object.keys(p.bgColor),_i=Object.keys(p.underlineColor),yi=[...Le,...Ue];function qe(){let e=new Map;for(let[t,i]of Object.entries(p)){for(let[n,r]of Object.entries(i))p[n]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},i[n]=p[n],e.set(Number.parseInt(r[0],10),r[1]);Object.defineProperty(p,t,{value:i,enumerable:!1})}return Object.defineProperty(p,"codes",{value:e,enumerable:!1}),p.color.close="\x1B[39m",p.bgColor.close="\x1B[49m",p.underlineColor.close="\x1B[59m",p.color.ansi=le(),p.color.ansi256=Y(),p.color.ansi16m=z(),p.bgColor.ansi=le(10),p.bgColor.ansi256=Y(10),p.bgColor.ansi16m=z(10),p.underlineColor.ansi=We,p.underlineColor.ansi256=Y(20),p.underlineColor.ansi16m=z(20),Object.defineProperties(p,{rgbToAnsi256:{value(t,i,n){if(t===i&&i===n){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(i/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(t){let i=/[\da-f]{6}|[\da-f]{3}/i.exec(t.toString(16));if(!i)return[0,0,0];let[n]=i;if(n.length===3)n=[...n].map((s)=>s+s).join("");let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:(t)=>p.rgbToAnsi256(...p.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let i,n,r;if(t>=232)i=((t-232)*10+8)/255,n=i,r=i;else{t-=16;let a=t%36;i=Math.floor(t/36)/5,n=Math.floor(a/6)/5,r=a%6/5}let s=Math.max(i,n,r)*2;if(s===0)return 30;let o=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(i));if(s===2)o+=60;return o},enumerable:!1},rgbToAnsi:{value:(t,i,n)=>p.ansi256ToAnsi(p.rgbToAnsi256(t,i,n)),enumerable:!1},hexToAnsi:{value:(t)=>p.ansi256ToAnsi(p.hexToAnsi256(t)),enumerable:!1}}),p}var Ye=qe(),_=Ye;import K from"process";import ze from"os";import ue from"tty";function g(e,t=globalThis.Deno?globalThis.Deno.args:K.argv){let i=e.startsWith("-")?"":e.length===1?"-":"--",n=t.indexOf(i+e),r=t.indexOf("--");return n!==-1&&(r===-1||n<r)}var{env:m}=K,j;if(g("no-color")||g("no-colors")||g("color=false")||g("color=never"))j=0;else if(g("color")||g("colors")||g("color=true")||g("color=always"))j=1;function he(){return/^\d+$/.test(m.FORCE_COLOR)}function Ke(){if(!("FORCE_COLOR"in m))return;if(m.FORCE_COLOR==="false")return 0;if(m.FORCE_COLOR==="true"||m.FORCE_COLOR.length===0)return 1;if(!he())return;return Math.min(Number.parseInt(m.FORCE_COLOR,10),3)}function Je(e){if(e===0)return!1;return{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Qe(e,{streamIsTTY:t,sniffFlags:i=!0}={}){let n=Ke();if(n!==void 0)j=n;let r=i?j:n;if(r===0)return 0;if(i){if(g("color=16m")||g("color=full")||g("color=truecolor"))return 3;if(g("color=256"))return 2}if(r!==void 0&&he())return r;if("TF_BUILD"in m&&"AGENT_NAME"in m)return 1;if(e&&!t&&r===void 0)return 0;let s=r||0;if(m.TERM==="dumb")return s;if(K.platform==="win32"){let o=ze.release().split(".");if(Number(o[0])>=10&&Number(o[2])>=10586)return Number(o[2])>=14931?3:2;return 1}if("CI"in m){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((o)=>(o in m)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((o)=>(o in m))||m.CI_NAME==="codeship")return 1;return s}if("TEAMCITY_VERSION"in m)return/^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.test(m.TEAMCITY_VERSION)?1:0;if(m.COLORTERM==="truecolor")return 3;if(m.TERM==="xterm-kitty")return 3;if(m.TERM==="xterm-ghostty")return 3;if(m.TERM==="wezterm")return 3;if("TERM_PROGRAM"in m){let o=Number.parseInt((m.TERM_PROGRAM_VERSION||"").split(".",1)[0],10);switch(m.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(?:color)?$/i.test(m.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(m.TERM))return 1;if("COLORTERM"in m)return 1;return s}function ce(e,t={}){let i=Qe(e,{streamIsTTY:e&&e.isTTY,...t});return Je(i)}var Xe={stdout:ce({isTTY:ue.isatty(1)}),stderr:ce({isTTY:ue.isatty(2)})},de=Xe;var{stdout:pe,stderr:me}=de,R=Symbol("GENERATOR"),k=Symbol("STYLER"),B=Symbol("IS_EMPTY"),D=Symbol("LEVEL"),P=Object.create(null),fe=(e)=>{if(!Number.isSafeInteger(e)||e<0||e>3)throw Error("The `level` should be an integer from 0 to 3")},Ze={enumerable:!0,get(){return this[D]},set(e){fe(e),this[D]=e}},et=(e,t={})=>{if(t.level!==void 0)fe(t.level);let i=pe?pe.level:0;e[D]=t.level===void 0?i:t.level};var tt=(e)=>{let t=(...i)=>i.join(" ");return et(t,e),Object.setPrototypeOf(t,N.prototype),t};function N(e){return tt(e)}Object.setPrototypeOf(N.prototype,Function.prototype);for(let[e,t]of Object.entries(_))P[e]={get(){let i=Q(this,ge(t.open,t.close,this[k]),this[B]);return Object.defineProperty(this,e,{value:i}),i}};P.visible={get(){let e=Q(this,this[k],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var it=(e,t)=>{let i=_[t];if(e==="rgb"){let r=(o,a,c)=>i.ansi(_.rgbToAnsi(o,a,c));return[r,r,(o,a,c)=>i.ansi256(_.rgbToAnsi256(o,a,c)),i.ansi16m]}if(e==="hex"){let r=(o)=>i.ansi(_.hexToAnsi(o));return[r,r,(o)=>i.ansi256(_.hexToAnsi256(o)),(o)=>i.ansi16m(..._.hexToRgb(o))]}let n=(r)=>i.ansi(_.ansi256ToAnsi(r));return[n,n,i.ansi256,i.ansi256]},nt=["rgb","hex","ansi256"];for(let e of nt){let t=e[0].toUpperCase()+e.slice(1);for(let[i,n]of[[e,"color"],["bg"+t,"bgColor"],["underline"+t,"underlineColor"]]){let{close:r}=_[n],s=it(e,n);P[i]={get(){let o=function(a,c,l){let u=s[this.level](a,c,l);return Q(this,ge(u,r,this[k]),this[B])};return Object.defineProperty(this,i,{value:o}),o}}}}var rt=Object.defineProperties(()=>{},{...P,level:{enumerable:!0,get(){return this[R].level},set(e){this[R].level=e}}}),ge=(e,t,i)=>{let n,r;if(i===void 0)n=e,r=t;else n=i.openAll+e,r=t+i.closeAll;return{open:e,close:t,openAll:n,closeAll:r,parent:i}},Q=(e,t,i)=>{let n=(...r)=>{if(r.length===1)return J(n,""+r[0]);if(r.length===2)return J(n,r[0]+" "+r[1]);return J(n,r.join(" "))};return Object.setPrototypeOf(n,rt),n[R]=e[R]??e,n[k]=t,n[B]=i,n},J=(e,t)=>{if(e[R][D]<=0||!t)return e[B]?"":t;let i=e[k];if(i===void 0)return t;let{openAll:n,closeAll:r}=i;if(t.includes("\x1B"))while(i!==void 0)t=oe(t,i.close,i.open),i=i.parent;let s=t.indexOf(`
|
|
32
|
+
`);if(s!==-1)t=ae(t,r,n,s);return n+t+r};Object.defineProperties(N.prototype,{...P,level:Ze});var st=N(),Ti=N({level:me?me.level:0});var f=st;import{mkdir as gt,readFile as _t,rm as yt,writeFile as bt}from"fs/promises";import{basename as Ot,join as b}from"path";import{build as Ct}from"esbuild";import{readdir as ot}from"fs/promises";import{dirname as at,join as lt,relative as ye}from"path";function _e(e){let t=e.replaceAll("\\","/").split("/");if(t.at(-1)!=="route.ts"&&t.at(-1)!=="route.js")return null;t.pop();let i=t.join("/"),n=[];for(let r of t){if(!r||/^\(.+\)$/.test(r))continue;if(/^\[\[\.\.\..+\]\]$/.test(r)){n.push({type:"optionalCatchAll",name:r.slice(5,-2)});continue}if(/^\[\.\.\..+\]$/.test(r)){n.push({type:"catchAll",name:r.slice(4,-1)});continue}if(/^\[.+\]$/.test(r)){n.push({type:"dynamic",name:r.slice(1,-1)});continue}n.push({type:"static",value:r})}return{dir:i,segments:n,pathname:n.length?"/"+n.map((r)=>{if(r.type==="static")return r.value;if(r.type==="dynamic")return`[${r.name}]`;if(r.type==="catchAll")return`[...${r.name}]`;return`[[...${r.name}]]`}).join("/"):"/"}}var ut=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];async function be(e){return ot(e,{recursive:!0,withFileTypes:!0}).catch(()=>[])}function Oe(e){return lt(e.parentPath??e.path,e.name)}async function M(e){let t=[];for(let i of await be(e)){if(!i.isFile())continue;if(i.name!=="route.ts"&&i.name!=="route.js")continue;let n=Oe(i),r=ye(e,n),s=_e(r);if(!s)continue;t.push({id:r.replaceAll("/",":").replace(/\.(ts|js)$/,""),file:n,dir:s.dir,pathname:s.pathname,segments:s.segments,methods:ut})}return t.sort(ct)}async function G(e){let t=[];for(let i of await be(e)){if(!i.isFile())continue;if(!/^(middleware|proxy)\.(ts|js)$/.test(i.name))continue;let n=Oe(i),r=ye(e,at(n)).replaceAll("\\","/");t.push({file:n,dir:r==="."?"":r})}return t.sort((i,n)=>i.dir.length-n.dir.length)}function ct(e,t){let i=(n)=>n.segments.reduce((r,s)=>{if(s.type==="static")return r+1000;if(s.type==="dynamic")return r+100;if(s.type==="catchAll")return r+10;return r},n.segments.length);return i(t)-i(e)}import{mkdir as ht,readFile as dt,writeFile as pt}from"fs/promises";import{join as v,relative as Ce}from"path";async function we(e,t,i=[]){let n=v(e,".primdy");await ht(n,{recursive:!0});let r={version:1,routes:t.map((s)=>({...s,file:Ce(n,s.file).replaceAll("\\","/")})),middleware:i.map((s)=>({...s,file:Ce(n,s.file).replaceAll("\\","/")}))};await pt(v(n,"routes.json"),JSON.stringify(r))}async function Ae(e){let t=v(e,".primdy"),i=v(t,"routes.json"),n=JSON.parse(await dt(i,"utf8"));return{...n,routes:n.routes.map((r)=>({...r,file:v(t,r.file)})),middleware:(n.middleware??[]).map((r)=>({...r,file:v(t,r.file)}))}}import{mkdir as mt,writeFile as ft}from"fs/promises";import{join as xe}from"path";async function Ee(e,t){let i=xe(e,".primdy");await mt(i,{recursive:!0});let r=`export type PrimdyRoute = ${t.map((s)=>`"${s.pathname}"`).join(" | ")||"never"};
|
|
33
|
+
`;await ft(xe(i,"routes.d.ts"),r)}async function Te(e,t){let i=await M(b(e,t)),n=await G(b(e,t)),r=b(e,".primdy");await yt(r,{recursive:!0,force:!0}),await gt(r,{recursive:!0});let s=b(r,"routes"),o=[];for(let[l,u]of i.entries())o.push({...u,file:await ve(u.file,b(s,String(l)))});let a=b(r,"middleware"),c=[];for(let[l,u]of n.entries())c.push({...u,file:await ve(u.file,b(a,String(l)))});return await we(e,o,c),await Ee(e,i),{routes:o,middleware:c}}async function ve(e,t){if((await Ct({entryPoints:[e],outdir:t,bundle:!0,platform:"node",format:"esm",minifyWhitespace:!0,sourcemap:"external",logLevel:"silent"})).errors.length)throw Error(`Failed to build ${e}`);let n=b(t,Ot(e).replace(/\.(ts|js)$/,".js"));return await wt(`${n}.map`),n}async function wt(e){let t=await _t(e,"utf8");await bt(e,JSON.stringify(JSON.parse(t)))}import{access as At}from"fs/promises";import{join as xt}from"path";async function Et(e){for(let t of["primdy.config.ts","primdy.config.js","primdy.config.mjs"]){let i=xt(e,t);try{return await At(i),i}catch{continue}}return null}async function X(e,t={}){let i=await Et(e),r=(i?await import(i).catch(()=>({default:{}})):{default:{}}).default??{};for(let[s,o]of Object.entries(t))if(o!==void 0)r[s]=o;return r}var O={success:(e)=>console.log(`${f.bold.green("\u2713")} ${e}`),info:(e)=>console.log(`${f.bold.cyan("\u2139")} ${e}`),warn:(e)=>console.log(`${f.bold.yellow("\u26A0")} ${e}`),err:(e)=>console.log(`${f.bold.red("\u2717")} ${e}`)},Z=(e)=>{O.success(`Ready in ${Math.round(performance.now()-e)}ms`)};import{createServer as vt}from"http";import{Readable as Me}from"stream";function Se(e,t){let i=t.split("/").filter(Boolean);for(let n of e){let r={},s=0,o=!0;for(let a of n.segments){if(a.type==="static"){if(i[s]!==a.value){o=!1;break}s++;continue}if(a.type==="dynamic"){let l=Re(i[s]);if(l===null){o=!1;break}r[a.name]=l,s++;continue}if(a.type==="catchAll"){if(s>=i.length){o=!1;break}let l=$e(i.slice(s));if(l===null){o=!1;break}r[a.name]=l,s=i.length;continue}let c=$e(i.slice(s));if(c===null){o=!1;break}r[a.name]=c,s=i.length}if(o&&s===i.length)return{route:n,params:r}}return null}function Re(e){try{return decodeURIComponent(e)}catch{return null}}function $e(e){let t=[];for(let i of e){let n=Re(i);if(n===null)return null;t.push(n)}return t}function ke(e,t){return e.filter((i)=>i.dir===""||t.dir===i.dir||t.dir.startsWith(`${i.dir}/`))}var Pe=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];async function Ne(e,t,i=[]){let n=new URL(e.url),r=Se(t,n.pathname);if(!r)return new Response("Not Found",{status:404});for(let c of ke(i,r.route)){let l=await import(c.file),u=l.default??l.middleware??l.proxy;if(typeof u!=="function")continue;let h=await u(e,{params:r.params});if(h)return h}let s=e.method;if(!Pe.includes(s))return new Response("Method Not Allowed",{status:405,headers:{Allow:r.route.methods.join(", ")}});let o=await import(r.route.file),a=o[s];if(typeof a!=="function"){let c=Pe.filter((l)=>typeof o[l]==="function");if(!c.length)return new Response("Method Not Allowed",{status:405});return new Response("Method Not Allowed",{status:405,headers:{Allow:c.join(", ")}})}return a(e,{params:r.params})}function ee(e,t,i,n){let r=performance.now()-n,s=f.dim(e.method),o=f.white(t),a=i>=500?f.red(i):i>=400?f.yellow(i):i>=300?f.cyan(i):f.green(i),c=r<1?f.dim(`${r.toFixed(2)}ms`):r>=100?f.yellow(`${Math.round(r)}ms`):f.dim(`${Math.round(r)}ms`);console.log(`${s} ${o} ${a} took ${c}`)}var Tt=typeof Bun<"u";function $t(e,t){let i=new Headers;for(let r in e.headers){let s=e.headers[r];if(s===void 0)continue;i.set(r,Array.isArray(s)?s.join(", "):s)}let n=e.method!=="GET"&&e.method!=="HEAD";return new Request(`http://${e.headers.host??t}${e.url??"/"}`,{method:e.method,headers:i,body:n?Me.toWeb(e):void 0,duplex:n?"half":void 0})}function te(e,t,i=[]){let n=Tt&&!t.forceNode;async function r(o){let a=performance.now(),c=new URL(o.url);try{let l=await Ne(o,e,i);return ee(o,c.pathname,l.status,a),l}catch(l){console.error(l);let u=new Response("Internal Server Error",{status:500});return ee(o,c.pathname,u.status,a),u}}if(n){let o=Bun.serve({hostname:t.hostname,port:t.port,fetch:r});return console.log(`${f.bold.cyanBright("\u25C6 Primdy Server")}
|
|
34
|
+
- Local: ${o.url}`),o}let s=vt(async(o,a)=>{let c=await r($t(o,t.hostname));a.statusCode=c.status;for(let[u,h]of c.headers)if(u.toLowerCase()!=="set-cookie")a.setHeader(u,h);let l=c.headers.getSetCookie?.();if(l?.length)a.setHeader("set-cookie",l);if(c.body)Me.fromWeb(c.body).pipe(a);else a.end()});return s.listen(t.port,t.hostname,()=>{console.log(`${f.bold.yellowBright("\u25C6 Primdy Server")}
|
|
35
|
+
- Local: http://${t.hostname}:${t.port}/`),O.warn(`Primdy is optimized for Bun, and Node.js compatibility is slower
|
|
36
|
+
Consider migrating your application: https://bun.sh/`)}),s}import{stat as St}from"fs/promises";function Rt(e){if(e<1024)return`${e} B`;return`${(e/1024).toFixed(1)} KB`}async function kt(e){return(await St(e).catch(()=>({size:0}))).size}async function He(e){let t=e.filter((r)=>r.entries.length>0);if(!t.length)return;let i=await Promise.all(t.map((r)=>Promise.all(r.entries.slice().sort((s,o)=>s.label.localeCompare(o.label)).map(async(s)=>({label:s.label,size:await kt(s.file)}))))),n=Math.max(...i.flat().map((r)=>r.label.length));t.forEach((r,s)=>{let o=i[s];console.log(f.bold(r.title)),o.forEach((a,c)=>{let l=c===o.length-1?"\u2514\u2500":"\u251C\u2500",u=f.dim(Rt(a.size).padStart(8));console.log(`${l} ${a.label.padEnd(n+2)}${u}`)})})}var Fe={name:"primdy",version:"0.1.0",description:"Blazingly fast, file-system routed API framework",license:"MIT",type:"module",main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"}},bin:{primdy:"dist/server/index.js"},files:["dist"],scripts:{build:"bun scripts/build.ts",prepublishOnly:"bun run build",test:"bun test"},dependencies:{chalk:"^6.0.0",commander:"^15.0.0",esbuild:"^0.28.2"},devDependencies:{"@types/bun":"^1.4.1",typescript:"^7.0.2"},engines:{bun:">=1.4.0"}};import{spawnSync as Vt}from"child_process";import{fileURLToPath as It}from"url";var jt=typeof process<"u"&&!!process.versions?.bun;if(!jt){if(!(process.argv.includes("--node")||process.argv.includes("-N")||await X(process.cwd()).then((i)=>i.node===!0).catch(()=>!1)))try{let i=It(import.meta.url),n=Vt("bun",[i,...process.argv.slice(2)],{stdio:"inherit",env:process.env});process.exit(n.status??0)}catch{}}var T=new E;T.name("primdy").description("Blazingly fast, file-system routed API framework").version(Fe.version).helpOption("-h, --help","Display help").helpCommand("help","Displays this message.");async function W(e,t={}){let i=Ft(process.cwd(),e),n=await X(i,{port:Number(process.env.PORT)||void 0,hostname:process.env.HOSTNAME,...t}),r=n.src??"src",s=Ht(i,r),o=n.port??3000,a=n.hostname??"localhost";return{cwd:i,config:n,src:r,appPath:s,port:o,hostname:a}}function Ve(e){let t={};if(e.port!==void 0)t.port=Number(e.port);if(e.hostname!==void 0)t.hostname=e.hostname;if(e.node!==void 0)t.node=e.node;return t}async function Dt(e){try{await Nt(e)}catch{return!1}return(await Mt(e,{recursive:!0,withFileTypes:!0}).catch(()=>[])).some((i)=>i.isFile()&&(i.name==="route.ts"||i.name==="route.js"))}async function ie(e){if(await Dt(e))return!0;return O.err(`No application found
|
|
37
|
+
Cannot find ${e}`),!1}T.command("dev").argument("[directory]","Application directory",".").description("Starts the development server.").option("-p, --port <port>","Port to listen on").option("-H, --hostname <hostname>","Hostname to listen on").option("-N, --node","Force the Node.js runtime").action(async(e,t)=>{let i=performance.now(),n=await W(e,Ve(t));if(!await ie(n.appPath))process.exit(1);let r=await M(n.appPath),s=await G(n.appPath);te(r,{port:n.port,hostname:n.hostname,forceNode:n.config.node},s),Z(i)});T.command("build").argument("[directory]","Application directory",".").description("Creates a production build of your application.").action(async(e)=>{let t=performance.now(),i=await W(e);if(!await ie(i.appPath))process.exit(1);try{let{routes:n,middleware:r}=await Te(i.cwd,i.src);await He([{title:"Routes",entries:n.map((a)=>({label:a.pathname,file:a.file}))},{title:"Middleware",entries:r.map((a)=>({label:a.dir?`/${a.dir}`:"/",file:a.file}))}]);let s=performance.now()-t,o=s>=1000?`${(s/1000).toFixed(1)}s`:`${Math.round(s)}ms`;O.success(`Built ${n.length} routes in ${o}`)}catch(n){O.err(n instanceof Error?n.message:String(n)),process.exit(1)}});T.command("start").argument("[directory]","Application directory",".").description("Starts the production server.").option("-p, --port <port>","Port to listen on").option("-H, --hostname <hostname>","Hostname to listen on").option("-N, --node","Force the Node.js runtime").action(async(e,t)=>{let i=performance.now(),n=await W(e,Ve(t));try{let r=await Ae(n.cwd);te(r.routes,{port:n.port,hostname:n.hostname,forceNode:n.config.node},r.middleware),Z(i)}catch{O.err(`No production build found
|
|
38
|
+
Run ${f.bold("primdy build")} to build your application`),process.exit(1)}});T.command("analyze").argument("[directory]","Application directory",".").description("Analyzes application routes.").action(async(e)=>{let t=await W(e);if(!await ie(t.appPath))process.exit(1);let i=await M(t.appPath);for(let n of i)console.log(`${n.pathname} ${n.file}`)});await T.parseAsync();
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "primdy",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Blazingly fast, file-system routed API framework",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"bin": {
|
|
16
|
+
"primdy": "dist/server/index.js"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "bun scripts/build.ts",
|
|
23
|
+
"prepublishOnly": "bun run build",
|
|
24
|
+
"test": "bun test"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"chalk": "^6.0.0",
|
|
28
|
+
"commander": "^15.0.0",
|
|
29
|
+
"esbuild": "^0.28.2"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/bun": "^1.4.1",
|
|
33
|
+
"typescript": "^7.0.2"
|
|
34
|
+
},
|
|
35
|
+
"engines": {
|
|
36
|
+
"bun": ">=1.4.0"
|
|
37
|
+
}
|
|
38
|
+
}
|