@upstart.gg/sdk 0.0.93 → 0.0.94
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/dist/node/cli/api.js +1 -1
- package/dist/node/cli/api.js.map +1 -1
- package/dist/node/cli/commands/login/cmd-login.js +1 -1
- package/dist/node/cli/commands/login/cmd-login.js.map +1 -1
- package/dist/node/cli/commands/publish/cmd-publish.js +10 -10
- package/dist/node/cli/commands/publish/cmd-publish.js.map +1 -1
- package/dist/node/cli/commands/publish/uploader.js +1 -1
- package/dist/node/cli/commands/publish/uploader.js.map +1 -1
- package/dist/node/cli/is-logged-in.js +2 -2
- package/dist/node/cli/is-logged-in.js.map +1 -1
- package/dist/node/cli/program.js +1 -1
- package/dist/node/cli/program.js.map +1 -1
- package/dist/node/shared/config.js +2 -2
- package/dist/node/shared/config.js.map +1 -1
- package/dist/node/shared/logger.js +1 -1
- package/dist/node/shared/logger.js.map +1 -1
- package/dist/shared/bricks/manifests/all-manifests.js +1 -1
- package/dist/shared/bricks/manifests/button.manifest.js +1 -1
- package/dist/shared/bricks/manifests/card.manifest.js +1 -1
- package/dist/shared/bricks/manifests/container.manifest.js +1 -1
- package/dist/shared/bricks/manifests/header.manifest.js +1 -1
- package/dist/shared/bricks/manifests/hero.manifest.js +1 -1
- package/dist/shared/bricks/manifests/image.manifest.js +1 -1
- package/dist/shared/bricks/manifests/images-gallery.manifest.js +1 -1
- package/dist/shared/bricks/manifests/text.manifest.js +1 -1
- package/dist/shared/bricks/props/_docs-common-styles.js +1 -1
- package/dist/shared/bricks.js +1 -1
- package/dist/shared/{chunk-U5WW6K7W.js → chunk-6I4PY5WS.js} +1 -1
- package/dist/shared/{chunk-ERSFH7XA.js → chunk-EFJQECVB.js} +1 -1
- package/dist/shared/{chunk-4FLI7C3B.js → chunk-GDLXGNMG.js} +1 -1
- package/dist/shared/{chunk-BXEKJXEP.js → chunk-HW5TY2QW.js} +1 -1
- package/dist/shared/{chunk-RHRJYPU3.js → chunk-LUJOZWSF.js} +1 -1
- package/dist/shared/{chunk-QCQH5WLN.js → chunk-NFU5BF6G.js} +1 -1
- package/dist/shared/{chunk-SWGSHUTE.js → chunk-NUJO6EYU.js} +1 -1
- package/dist/shared/{chunk-V2NS45PF.js → chunk-QRBMK5UX.js} +1 -1
- package/dist/shared/{chunk-6MEWEGNA.js → chunk-TQ23UATQ.js} +1 -1
- package/dist/shared/{chunk-IKAMZM4I.js → chunk-XEQ2XZLQ.js} +1 -1
- package/dist/shared/chunk-YLAVY3GS.js +3 -0
- package/dist/shared/page.js +1 -1
- package/dist/shared/template.js +1 -1
- package/package.json +4 -7
- package/dist/shared/chunk-S64XUCWM.js +0 -3
package/dist/node/cli/api.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*! Upstart.gg - Copyright (C) 2024 Flippable - https://github.com/upstart-gg/upstart/blob/main/LICENSE */
|
|
2
2
|
|
|
3
|
-
import{createLogger as T}from"vite";var g="0.0.
|
|
3
|
+
import{createLogger as T}from"vite";var g="0.0.94";import i from"chalk";function h(e,t,o=!1){let s=T(e==="debug"?"info":e,{prefix:"[upstart]",allowClearScreen:t});return o&&s.info(i.hex("#7270c6").bold(`\u{1F680} Upstart v${g}
|
|
4
4
|
`)),{...s,success:(r,n)=>s.info(i.green(r),n),error:(r,n)=>s.error(i.red(r),n),warn:(r,n)=>s.warn(i.yellow(r),n),warnOnce:(r,n)=>s.warnOnce(i.yellow(r),n),debug:(r,n)=>{e==="debug"&&s.info(i.gray(r),n)}}}var p=h();var m="upstart-cli";var w=process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID??"50000000-0000-0000-0000-000000000001",d=process.env.PUBLIC_UPSTART_API_BASE_URL??"https://api.upstart.gg",A=process.env.PUBLIC_UPSTART_EDITOR_BASE_URL??"https://upstart.gg";import E from"conf";import c from"node:path";import _ from"node:crypto";import a from"node:fs";import{fileURLToPath as L}from"node:url";import z from"chalk";var R=L(new URL(".",import.meta.url)),x=S(),u=new E({projectName:m,encryptionKey:x,clearInvalidConfig:!0});function O(){let e=R;for(;e!==c.parse(e).root;){let t=c.join(e,"node_modules");if(a.existsSync(t))return t;e=c.dirname(e)}return null}function S(){let e=O();if(!e)throw new Error("Could not find nearest node_modules directory.");let t=c.join(e,".enpage-tmp");a.existsSync(t)||a.mkdirSync(t,{recursive:!0,mode:448});let o=c.join(t,".enpage-key");if(!a.existsSync(o)){let r=_.randomBytes(32).toString("hex");return a.writeFileSync(o,r,{mode:384}),r}return a.readFileSync(o,"utf8")}async function J(e,t,o={}){u.get("access_token")&&(o.Authorization=`Bearer ${u.get("access_token")}`);let s=await fetch(l(e),{method:"POST",headers:{"Content-Type":t instanceof URLSearchParams?"application/x-www-form-urlencoded":"application/json",...o},body:t instanceof URLSearchParams?t:JSON.stringify(t)}).catch(r=>{p.error(`Fatal Error requesting API: ${r.message} (${r.cause.code})`),p.error("Please check your internet connection and try again, or retry later."),process.exit(1)});return y(s)}async function K(e,t={}){u.get("access_token")&&(t.Authorization=`Bearer ${u.get("access_token")}`);let o=await fetch(l(e),{headers:t,method:"GET"}).catch(s=>{p.error(`Fatal Error requesting API: ${s.message} (${s.cause.code})`),p.error("Please check your internet connection and try again, or retry later."),process.exit(1)});return y(o)}function l(e){let t=new URL(d.endsWith("/")?d:`${d}/`);return new URL(e,t)}async function y(e){let t=e.headers.get("content-type")?.startsWith("application/json")?await e.json():await e.text();return e.ok?{isSuccess:!0,isError:!1,status:e.status,statusText:e.statusText,data:t}:{isSuccess:!1,isError:!0,status:e.status,statusText:e.statusText,data:t}}export{K as get,J as post};
|
|
5
5
|
//# sourceMappingURL=api.js.map
|
package/dist/node/cli/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/node/shared/logger.ts","../../../package.json","../../../src/node/cli/constants.ts","../../../src/node/cli/store.ts","../../../src/node/cli/api.ts"],"sourcesContent":["import {\n createLogger as createLoggerBase,\n type LogLevel,\n type LogOptions,\n type Logger as BaseLogger,\n} from \"vite\";\nimport { version } from \"../../../package.json\";\nimport chalk from \"chalk\";\n\ntype UpstartLoggerLevel = LogLevel | \"debug\";\n\nexport function createLogger(level?: UpstartLoggerLevel, allowClearScreen?: boolean, showVersion = false) {\n // vite logger does not support \"debug\" level\n const logger = createLoggerBase(level === \"debug\" ? \"info\" : level, {\n prefix: \"[upstart]\",\n allowClearScreen,\n });\n\n if (showVersion) {\n logger.info(chalk.hex(\"#7270c6\").bold(`🚀 Upstart v${version}\\n`));\n }\n\n return {\n ...logger,\n success: (message: string, options?: LogOptions) => logger.info(chalk.green(message), options),\n error: (message: string, options?: LogOptions) => logger.error(chalk.red(message), options),\n warn: (message: string, options?: LogOptions) => logger.warn(chalk.yellow(message), options),\n warnOnce: (message: string, options?: LogOptions) => logger.warnOnce(chalk.yellow(message), options),\n debug: (message: string, options?: LogOptions) => {\n if (level === \"debug\") {\n logger.info(chalk.gray(message), options);\n }\n },\n };\n}\n\nexport const logger = createLogger();\n\nexport type Logger = BaseLogger & {\n success: (message: string, options?: LogOptions) => void;\n debug: (message: string, options?: LogOptions) => void;\n};\n","{\n \"name\": \"@upstart.gg/sdk\",\n \"version\": \"0.0.93\",\n \"type\": \"module\",\n \"files\": [\n \"dist\",\n \"env.d.ts\"\n ],\n \"sideEffects\": false,\n \"exports\": {\n \".\": {\n \"import\": \"./dist/shared/index.js\",\n \"types\": \"./dist/shared/index.d.ts\"\n },\n \"./shared/*\": {\n \"types\": \"./dist/shared/*.d.ts\",\n \"import\": \"./dist/shared/*.js\"\n },\n \"./builder/*\": {\n \"import\": \"./dist/node/builder/*.js\"\n },\n \"./cli/*\": {\n \"import\": \"./dist/node/cli/*.js\"\n },\n \"./env.d.ts\": {\n \"types\": \"./env.d.ts\",\n \"require\": \"./env.d.ts\",\n \"import\": \"./env.d.ts\"\n },\n \"./*\": {\n \"types\": \"./dist/shared/*.d.ts\",\n \"import\": \"./dist/shared/*.js\"\n }\n },\n \"bin\": {\n \"enpage\": \"dist/node/cli/program.js\"\n },\n \"dependencies\": {\n \"@date-fns/utc\": \"1.2.0\",\n \"@headlessui/react\": \"2.1.2\",\n \"@inquirer/prompts\": \"5.3.8\",\n \"@radix-ui/react-context-menu\": \"2.2.2\",\n \"@radix-ui/react-toggle-group\": \"1.1.0\",\n \"@radix-ui/themes\": \"3.1.4\",\n \"@sinclair/typebox\": \"0.33.7\",\n \"@upstart.gg/style-system\": \"workspace:*\",\n \"ajv\": \"8.17.1\",\n \"ajv-formats\": \"3.0.1\",\n \"chalk\": \"5.3.0\",\n \"chroma-js\": \"3.1.2\",\n \"commander\": \"12.1.0\",\n \"conf\": \"13.0.1\",\n \"date-fns\": \"3.6.0\",\n \"debug\": \"4.3.6\",\n \"fast-glob\": \"3.3.2\",\n \"form-data\": \"4.0.0\",\n \"get-port\": \"7.1.0\",\n \"htmlparser2\": \"9.1.0\",\n \"http-errors-enhanced\": \"2.0.8\",\n \"immer\": \"10.1.1\",\n \"import-meta-resolve\": \"4.1.0\",\n \"lodash-es\": \"4.17.21\",\n \"nanoid\": \"5.0.7\",\n \"open\": \"10.1.0\",\n \"ora\": \"8.1.0\",\n \"p-queue\": \"8.0.1\",\n \"react-hotkeys-hook\": \"4.5.1\",\n \"react-icons\": \"5.3.0\",\n \"react-selecto\": \"1.26.3\",\n \"rollup-plugin-strip-banner\": \"3.1.0\",\n \"usehooks-ts\": \"3.1.0\",\n \"zundo\": \"2.3.0\",\n \"zustand\": \"4.5.5\"\n },\n \"peerDependencies\": {\n \"@upstart.gg/style-system\": \"workspace:*\",\n \"react\": \"18.3.0-canary-3d9b20132-20240124\",\n \"react-dom\": \"18.3.0-canary-3d9b20132-20240124\"\n },\n \"devDependencies\": {\n \"@cloudflare/workers-types\": \"4.20240806.0\",\n \"@types/chroma-js\": \"2.4.4\",\n \"@types/cli-progress\": \"3.11.6\",\n \"@types/debug\": \"4.1.12\",\n \"@types/express\": \"^4.17.21\",\n \"@types/lodash-es\": \"4.17.12\",\n \"@types/node\": \"^20.14.10\",\n \"@types/react\": \"18.3.3\",\n \"@types/react-dom\": \"^18.3.0\",\n \"@types/sortablejs\": \"1.15.8\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"concurrently\": \"8.2.2\",\n \"express\": \"^4.21.2\",\n \"rimraf\": \"6.0.1\",\n \"tsup\": \"8.2.4\",\n \"vite\": \"5.4.6\",\n \"vite-plugin-dts\": \"4.2.1\",\n \"vite-plugin-image-optimizer\": \"1.1.8\",\n \"vite-plugin-inspect\": \"0.8.7\",\n \"vite-plugin-virtual\": \"0.3.0\",\n \"vite-tsconfig-paths\": \"5.0.1\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"build:types\": \"tsc --emitDeclarationOnly --declaration --declarationMap\",\n \"dev\": \"NODE_OPTIONS='--max-old-space-size=12384' tsup --watch\",\n \"sizetest\": \"pnpm build && du -sh dist\",\n \"lint\": \"biome check --write . && tsc --noEmit\",\n \"ci:lint\": \"tsc --noEmit\",\n \"test\": \"vitest\",\n \"prepare\": \"node ./scripts/prepare.cjs\",\n \"gen-ia-docs\": \"tsx scripts/generate-ia-docs.ts\"\n },\n \"author\": \"Matthias Etienne\",\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","export const CLI_PROJECT_NAME = \"upstart-cli\";\nexport const CLI_LOGIN_POLL_INTERVAL = 5000; // seconds\nexport const CLI_LOGIN_CLIENT_ID =\n process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID ?? \"50000000-0000-0000-0000-000000000001\";\n\nexport const API_BASE_URL = process.env.PUBLIC_UPSTART_API_BASE_URL ?? \"https://api.upstart.gg\";\nexport const EDITOR_BASE_URL = process.env.PUBLIC_UPSTART_EDITOR_BASE_URL ?? \"https://upstart.gg\";\nexport const DEFAULT_UPLOAD_MAX_CONCURRENCY = 10;\n\nexport const OAUTH_ENDPOINT_DEVICE_CODE = \"oauth/devicecode\";\nexport const OAUTH_ENDPOINT_TOKEN = \"oauth/token\";\nexport const OAUTH_ENDPOINT_USER_INFO = \"oauth/userinfo\";\n\nexport const API_ENDPOINT_REGISTER_TEMPLATE = \"v1/templates\";\n","import type { CredentialsStore } from \"./types\";\nimport { CLI_PROJECT_NAME, OAUTH_ENDPOINT_USER_INFO } from \"./constants\";\nimport Conf from \"conf\";\nimport path from \"node:path\";\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { getPackageManager } from \"./utils\";\nimport chalk from \"chalk\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\nconst key = getKey();\nconst accessStore = new Conf<CredentialsStore>({\n projectName: CLI_PROJECT_NAME,\n encryptionKey: key,\n clearInvalidConfig: true,\n});\n\n/**\n * Get access token or throw error if not found\n */\nexport function getTokenOrThrow() {\n const token = accessStore.get(\"access_token\");\n if (!token) {\n const pkgCmd = getPackageManager();\n throw new Error(\n `Access token not found. Please run ${chalk.cyan(`${pkgCmd} run enpage:login`)} to authenticate.`,\n );\n }\n return token;\n}\n\nfunction findNearestNodeModules(): string | null {\n let currentDir = __dirname;\n while (currentDir !== path.parse(currentDir).root) {\n const nodeModulesPath = path.join(currentDir, \"node_modules\");\n if (fs.existsSync(nodeModulesPath)) {\n return nodeModulesPath;\n }\n currentDir = path.dirname(currentDir);\n }\n return null;\n}\n\nfunction getKey() {\n const nodeModulesPath = findNearestNodeModules();\n if (!nodeModulesPath) {\n throw new Error(\"Could not find nearest node_modules directory.\");\n }\n const tmpSecureStoreDir = path.join(nodeModulesPath, \".enpage-tmp\");\n if (!fs.existsSync(tmpSecureStoreDir)) {\n fs.mkdirSync(tmpSecureStoreDir, { recursive: true, mode: 0o700 });\n }\n const keyPath = path.join(tmpSecureStoreDir, \".enpage-key\");\n if (!fs.existsSync(keyPath)) {\n const key = crypto.randomBytes(32).toString(\"hex\");\n fs.writeFileSync(keyPath, key, { mode: 0o600 });\n return key;\n }\n const key = fs.readFileSync(keyPath, \"utf8\");\n return key;\n}\n\nexport { accessStore };\n","import { logger } from \"../shared/logger\";\nimport { API_BASE_URL } from \"./constants\";\nimport { accessStore } from \"./store\";\n\ntype SuccessResponseWrapper<T> = {\n isSuccess: true;\n isError: false;\n status: number;\n statusText: string;\n data: T;\n};\n\ntype ErrorResponseWrapper<E> = {\n isSuccess: false;\n isError: true;\n status: number;\n statusText: string;\n data: E;\n};\n\ntype ResponseWrapper<T, E> = SuccessResponseWrapper<T> | ErrorResponseWrapper<E>;\n\ntype CommonResponseType = {\n success: boolean;\n};\n\n/**\n *\n * @param pathOrUrl\n * @param data\n * @returns\n */\nexport async function post<\n ResponseType extends CommonResponseType = CommonResponseType,\n ErrorType = { error: string; error_description?: string },\n>(path: string, data: Record<string, unknown> | URLSearchParams, headers: Record<string, string> = {}) {\n if (accessStore.get(\"access_token\")) {\n headers.Authorization = `Bearer ${accessStore.get(\"access_token\")}`;\n }\n const response = await fetch(toURL(path), {\n method: \"POST\",\n headers: {\n \"Content-Type\":\n data instanceof URLSearchParams ? \"application/x-www-form-urlencoded\" : \"application/json\",\n ...headers,\n },\n body: data instanceof URLSearchParams ? data : JSON.stringify(data),\n }).catch((error) => {\n logger.error(`Fatal Error requesting API: ${error.message} (${error.cause.code})`);\n logger.error(`Please check your internet connection and try again, or retry later.`);\n process.exit(1);\n });\n\n return formatResponse<ResponseType, ErrorType>(response);\n}\n\nexport async function get<ResponseType = unknown, ErrorType = { error: string; error_description?: string }>(\n path: string,\n headers: Record<string, string> = {},\n) {\n if (accessStore.get(\"access_token\")) {\n headers.Authorization = `Bearer ${accessStore.get(\"access_token\")}`;\n }\n const response = await fetch(toURL(path), { headers, method: \"GET\" }).catch((error) => {\n logger.error(`Fatal Error requesting API: ${error.message} (${error.cause.code})`);\n logger.error(`Please check your internet connection and try again, or retry later.`);\n process.exit(1);\n });\n return formatResponse<ResponseType, ErrorType>(response);\n}\n\nfunction toURL(path: string) {\n const apiBaseURL = new URL(API_BASE_URL.endsWith(\"/\") ? API_BASE_URL : `${API_BASE_URL}/`);\n return new URL(path, apiBaseURL);\n}\n\nasync function formatResponse<SuccessType, ErrorType>(\n response: Response,\n): Promise<ResponseWrapper<SuccessType, ErrorType>> {\n const data = response.headers.get(\"content-type\")?.startsWith(\"application/json\")\n ? ((await response.json()) as ResponseType)\n : ((await response.text()) as ResponseType);\n\n if (response.ok) {\n return {\n isSuccess: true,\n isError: false,\n status: response.status,\n statusText: response.statusText,\n data: data as SuccessType,\n };\n } else {\n return {\n isSuccess: false,\n isError: true,\n status: response.status,\n statusText: response.statusText,\n data: data as ErrorType,\n };\n }\n}\n"],"mappings":";;AAAA,OACE,gBAAgBA,MAIX,OCHL,IAAAC,EAAW,SDKb,OAAOC,MAAW,QAIX,SAASC,EAAaC,EAA4BC,EAA4BC,EAAc,GAAO,CAExG,IAAMC,EAASC,EAAiBJ,IAAU,QAAU,OAASA,EAAO,CAClE,OAAQ,YACR,iBAAAC,CACF,CAAC,EAED,OAAIC,GACFC,EAAO,KAAKL,EAAM,IAAI,SAAS,EAAE,KAAK,sBAAeO,CAAO;AAAA,CAAI,CAAC,EAG5D,CACL,GAAGF,EACH,QAAS,CAACG,EAAiBC,IAAyBJ,EAAO,KAAKL,EAAM,MAAMQ,CAAO,EAAGC,CAAO,EAC7F,MAAO,CAACD,EAAiBC,IAAyBJ,EAAO,MAAML,EAAM,IAAIQ,CAAO,EAAGC,CAAO,EAC1F,KAAM,CAACD,EAAiBC,IAAyBJ,EAAO,KAAKL,EAAM,OAAOQ,CAAO,EAAGC,CAAO,EAC3F,SAAU,CAACD,EAAiBC,IAAyBJ,EAAO,SAASL,EAAM,OAAOQ,CAAO,EAAGC,CAAO,EACnG,MAAO,CAACD,EAAiBC,IAAyB,CAC5CP,IAAU,SACZG,EAAO,KAAKL,EAAM,KAAKQ,CAAO,EAAGC,CAAO,CAE5C,CACF,CACF,CAEO,IAAMJ,EAASJ,EAAa,EEpC5B,IAAMS,EAAmB,cAEzB,IAAMC,EACX,QAAQ,IAAI,gCAAkC,uCAEnCC,EAAe,QAA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OAAQG,EAAS,OACjB,WAAYA,EAAS,WACrB,KAAMH,CACR,CAEJ","names":["createLoggerBase","version","chalk","createLogger","level","allowClearScreen","showVersion","logger","createLoggerBase","version","message","options","CLI_PROJECT_NAME","CLI_LOGIN_CLIENT_ID","API_BASE_URL","EDITOR_BASE_URL","Conf","path","crypto","fs","fileURLToPath","chalk","__dirname","fileURLToPath","key","getKey","accessStore","Conf","CLI_PROJECT_NAME","findNearestNodeModules","currentDir","__dirname","path","nodeModulesPath","fs","getKey","tmpSecureStoreDir","keyPath","key","crypto","post","path","data","headers","accessStore","response","toURL","error","logger","formatResponse","get","apiBaseURL","API_BASE_URL"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/node/shared/logger.ts","../../../package.json","../../../src/node/cli/constants.ts","../../../src/node/cli/store.ts","../../../src/node/cli/api.ts"],"sourcesContent":["import {\n createLogger as createLoggerBase,\n type LogLevel,\n type LogOptions,\n type Logger as BaseLogger,\n} from \"vite\";\nimport { version } from \"../../../package.json\";\nimport chalk from \"chalk\";\n\ntype UpstartLoggerLevel = LogLevel | \"debug\";\n\nexport function createLogger(level?: UpstartLoggerLevel, allowClearScreen?: boolean, showVersion = false) {\n // vite logger does not support \"debug\" level\n const logger = createLoggerBase(level === \"debug\" ? \"info\" : level, {\n prefix: \"[upstart]\",\n allowClearScreen,\n });\n\n if (showVersion) {\n logger.info(chalk.hex(\"#7270c6\").bold(`🚀 Upstart v${version}\\n`));\n }\n\n return {\n ...logger,\n success: (message: string, options?: LogOptions) => logger.info(chalk.green(message), options),\n error: (message: string, options?: LogOptions) => logger.error(chalk.red(message), options),\n warn: (message: string, options?: LogOptions) => logger.warn(chalk.yellow(message), options),\n warnOnce: (message: string, options?: LogOptions) => logger.warnOnce(chalk.yellow(message), options),\n debug: (message: string, options?: LogOptions) => {\n if (level === \"debug\") {\n logger.info(chalk.gray(message), options);\n }\n },\n };\n}\n\nexport const logger = createLogger();\n\nexport type Logger = BaseLogger & {\n success: (message: string, options?: LogOptions) => void;\n debug: (message: string, options?: LogOptions) => void;\n};\n","{\n \"name\": \"@upstart.gg/sdk\",\n \"version\": \"0.0.94\",\n \"type\": \"module\",\n \"files\": [\n \"dist\",\n \"env.d.ts\"\n ],\n \"sideEffects\": false,\n \"exports\": {\n \".\": {\n \"import\": \"./dist/shared/index.js\",\n \"types\": \"./dist/shared/index.d.ts\"\n },\n \"./shared/*\": {\n \"types\": \"./dist/shared/*.d.ts\",\n \"import\": \"./dist/shared/*.js\"\n },\n \"./builder/*\": {\n \"import\": \"./dist/node/builder/*.js\"\n },\n \"./cli/*\": {\n \"import\": \"./dist/node/cli/*.js\"\n },\n \"./env.d.ts\": {\n \"types\": \"./env.d.ts\",\n \"require\": \"./env.d.ts\",\n \"import\": \"./env.d.ts\"\n },\n \"./*\": {\n \"types\": \"./dist/shared/*.d.ts\",\n \"import\": \"./dist/shared/*.js\"\n }\n },\n \"dependencies\": {\n \"@date-fns/utc\": \"1.2.0\",\n \"@headlessui/react\": \"2.2.1\",\n \"@inquirer/prompts\": \"5.3.8\",\n \"@radix-ui/react-context-menu\": \"2.2.2\",\n \"@radix-ui/react-toggle-group\": \"1.1.0\",\n \"@radix-ui/themes\": \"3.1.4\",\n \"@sinclair/typebox\": \"0.33.7\",\n \"@upstart.gg/style-system\": \"workspace:*\",\n \"ajv\": \"8.17.1\",\n \"ajv-formats\": \"3.0.1\",\n \"chalk\": \"5.3.0\",\n \"chroma-js\": \"3.1.2\",\n \"commander\": \"12.1.0\",\n \"conf\": \"13.0.1\",\n \"date-fns\": \"3.6.0\",\n \"debug\": \"4.3.6\",\n \"fast-glob\": \"3.3.2\",\n \"form-data\": \"4.0.0\",\n \"get-port\": \"7.1.0\",\n \"htmlparser2\": \"9.1.0\",\n \"http-errors-enhanced\": \"2.0.8\",\n \"immer\": \"10.1.1\",\n \"import-meta-resolve\": \"4.1.0\",\n \"lodash-es\": \"4.17.21\",\n \"nanoid\": \"5.0.7\",\n \"open\": \"10.1.0\",\n \"ora\": \"8.1.0\",\n \"p-queue\": \"8.0.1\",\n \"react-hotkeys-hook\": \"4.5.1\",\n \"react-icons\": \"5.3.0\",\n \"react-selecto\": \"1.26.3\",\n \"rollup-plugin-strip-banner\": \"3.1.0\",\n \"usehooks-ts\": \"3.1.0\",\n \"zundo\": \"2.3.0\",\n \"zustand\": \"4.5.5\"\n },\n \"peerDependencies\": {\n \"@upstart.gg/style-system\": \"workspace:*\",\n \"react\": \"18.3.0-canary-3d9b20132-20240124\",\n \"react-dom\": \"18.3.0-canary-3d9b20132-20240124\"\n },\n \"devDependencies\": {\n \"@cloudflare/workers-types\": \"4.20240806.0\",\n \"@types/chroma-js\": \"2.4.4\",\n \"@types/cli-progress\": \"3.11.6\",\n \"@types/debug\": \"4.1.12\",\n \"@types/express\": \"^4.17.21\",\n \"@types/lodash-es\": \"4.17.12\",\n \"@types/node\": \"^20.14.10\",\n \"@types/react\": \"18.3.3\",\n \"@types/react-dom\": \"^18.3.0\",\n \"@types/sortablejs\": \"1.15.8\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"concurrently\": \"8.2.2\",\n \"express\": \"^4.21.2\",\n \"rimraf\": \"6.0.1\",\n \"tsup\": \"8.2.4\",\n \"vite\": \"5.4.6\",\n \"vite-plugin-dts\": \"4.2.1\",\n \"vite-plugin-image-optimizer\": \"1.1.8\",\n \"vite-plugin-inspect\": \"0.8.7\",\n \"vite-plugin-virtual\": \"0.3.0\",\n \"vite-tsconfig-paths\": \"5.0.1\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"build:types\": \"tsc --emitDeclarationOnly --declaration --declarationMap\",\n \"dev\": \"NODE_OPTIONS='--max-old-space-size=12384' tsup --watch\",\n \"sizetest\": \"pnpm build && du -sh dist\",\n \"lint\": \"biome check --write . && tsc --noEmit\",\n \"ci:lint\": \"tsc --noEmit\",\n \"test\": \"vitest\",\n \"gen-ia-docs\": \"tsx scripts/generate-ia-docs.ts\"\n },\n \"author\": \"Matthias Etienne\",\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","export const CLI_PROJECT_NAME = \"upstart-cli\";\nexport const CLI_LOGIN_POLL_INTERVAL = 5000; // seconds\nexport const CLI_LOGIN_CLIENT_ID =\n process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID ?? \"50000000-0000-0000-0000-000000000001\";\n\nexport const API_BASE_URL = process.env.PUBLIC_UPSTART_API_BASE_URL ?? \"https://api.upstart.gg\";\nexport const EDITOR_BASE_URL = process.env.PUBLIC_UPSTART_EDITOR_BASE_URL ?? \"https://upstart.gg\";\nexport const DEFAULT_UPLOAD_MAX_CONCURRENCY = 10;\n\nexport const OAUTH_ENDPOINT_DEVICE_CODE = \"oauth/devicecode\";\nexport const OAUTH_ENDPOINT_TOKEN = \"oauth/token\";\nexport const OAUTH_ENDPOINT_USER_INFO = \"oauth/userinfo\";\n\nexport const API_ENDPOINT_REGISTER_TEMPLATE = \"v1/templates\";\n","import type { CredentialsStore } from \"./types\";\nimport { CLI_PROJECT_NAME, OAUTH_ENDPOINT_USER_INFO } from \"./constants\";\nimport Conf from \"conf\";\nimport path from \"node:path\";\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { getPackageManager } from \"./utils\";\nimport chalk from \"chalk\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\nconst key = getKey();\nconst accessStore = new Conf<CredentialsStore>({\n projectName: CLI_PROJECT_NAME,\n encryptionKey: key,\n clearInvalidConfig: true,\n});\n\n/**\n * Get access token or throw error if not found\n */\nexport function getTokenOrThrow() {\n const token = accessStore.get(\"access_token\");\n if (!token) {\n const pkgCmd = getPackageManager();\n throw new Error(\n `Access token not found. Please run ${chalk.cyan(`${pkgCmd} run enpage:login`)} to authenticate.`,\n );\n }\n return token;\n}\n\nfunction findNearestNodeModules(): string | null {\n let currentDir = __dirname;\n while (currentDir !== path.parse(currentDir).root) {\n const nodeModulesPath = path.join(currentDir, \"node_modules\");\n if (fs.existsSync(nodeModulesPath)) {\n return nodeModulesPath;\n }\n currentDir = path.dirname(currentDir);\n }\n return null;\n}\n\nfunction getKey() {\n const nodeModulesPath = findNearestNodeModules();\n if (!nodeModulesPath) {\n throw new Error(\"Could not find nearest node_modules directory.\");\n }\n const tmpSecureStoreDir = path.join(nodeModulesPath, \".enpage-tmp\");\n if (!fs.existsSync(tmpSecureStoreDir)) {\n fs.mkdirSync(tmpSecureStoreDir, { recursive: true, mode: 0o700 });\n }\n const keyPath = path.join(tmpSecureStoreDir, \".enpage-key\");\n if (!fs.existsSync(keyPath)) {\n const key = crypto.randomBytes(32).toString(\"hex\");\n fs.writeFileSync(keyPath, key, { mode: 0o600 });\n return key;\n }\n const key = fs.readFileSync(keyPath, \"utf8\");\n return key;\n}\n\nexport { accessStore };\n","import { logger } from \"../shared/logger\";\nimport { API_BASE_URL } from \"./constants\";\nimport { accessStore } from \"./store\";\n\ntype SuccessResponseWrapper<T> = {\n isSuccess: true;\n isError: false;\n status: number;\n statusText: string;\n data: T;\n};\n\ntype ErrorResponseWrapper<E> = {\n isSuccess: false;\n isError: true;\n status: number;\n statusText: string;\n data: E;\n};\n\ntype ResponseWrapper<T, E> = SuccessResponseWrapper<T> | ErrorResponseWrapper<E>;\n\ntype CommonResponseType = {\n success: boolean;\n};\n\n/**\n *\n * @param pathOrUrl\n * @param data\n * @returns\n */\nexport async function post<\n ResponseType extends CommonResponseType = CommonResponseType,\n ErrorType = { error: string; error_description?: string },\n>(path: string, data: Record<string, unknown> | URLSearchParams, headers: Record<string, string> = {}) {\n if (accessStore.get(\"access_token\")) {\n headers.Authorization = `Bearer ${accessStore.get(\"access_token\")}`;\n }\n const response = await fetch(toURL(path), {\n method: \"POST\",\n headers: {\n \"Content-Type\":\n data instanceof URLSearchParams ? \"application/x-www-form-urlencoded\" : \"application/json\",\n ...headers,\n },\n body: data instanceof URLSearchParams ? data : JSON.stringify(data),\n }).catch((error) => {\n logger.error(`Fatal Error requesting API: ${error.message} (${error.cause.code})`);\n logger.error(`Please check your internet connection and try again, or retry later.`);\n process.exit(1);\n });\n\n return formatResponse<ResponseType, ErrorType>(response);\n}\n\nexport async function get<ResponseType = unknown, ErrorType = { error: string; error_description?: string }>(\n path: string,\n headers: Record<string, string> = {},\n) {\n if (accessStore.get(\"access_token\")) {\n headers.Authorization = `Bearer ${accessStore.get(\"access_token\")}`;\n }\n const response = await fetch(toURL(path), { headers, method: \"GET\" }).catch((error) => {\n logger.error(`Fatal Error requesting API: ${error.message} (${error.cause.code})`);\n logger.error(`Please check your internet connection and try again, or retry later.`);\n process.exit(1);\n });\n return formatResponse<ResponseType, ErrorType>(response);\n}\n\nfunction toURL(path: string) {\n const apiBaseURL = new URL(API_BASE_URL.endsWith(\"/\") ? API_BASE_URL : `${API_BASE_URL}/`);\n return new URL(path, apiBaseURL);\n}\n\nasync function formatResponse<SuccessType, ErrorType>(\n response: Response,\n): Promise<ResponseWrapper<SuccessType, ErrorType>> {\n const data = response.headers.get(\"content-type\")?.startsWith(\"application/json\")\n ? ((await response.json()) as ResponseType)\n : ((await response.text()) as ResponseType);\n\n if (response.ok) {\n return {\n isSuccess: true,\n isError: false,\n status: response.status,\n statusText: response.statusText,\n data: data as SuccessType,\n };\n } else {\n return {\n isSuccess: false,\n isError: true,\n status: response.status,\n statusText: response.statusText,\n data: data as ErrorType,\n };\n }\n}\n"],"mappings":";;AAAA,OACE,gBAAgBA,MAIX,OCHL,IAAAC,EAAW,SDKb,OAAOC,MAAW,QAIX,SAASC,EAAaC,EAA4BC,EAA4BC,EAAc,GAAO,CAExG,IAAMC,EAASC,EAAiBJ,IAAU,QAAU,OAASA,EAAO,CAClE,OAAQ,YACR,iBAAAC,CACF,CAAC,EAED,OAAIC,GACFC,EAAO,KAAKL,EAAM,IAAI,SAAS,EAAE,KAAK,sBAAeO,CAAO;AAAA,CAAI,CAAC,EAG5D,CACL,GAAGF,EACH,QAAS,CAACG,EAAiBC,IAAyBJ,EAAO,KAAKL,EAAM,MAAMQ,CAAO,E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AAK,CAAC,CAChB,CAAC,EACD,OAAOC,EAAwCJ,CAAQ,CACzD,CAEA,SAASC,EAAML,EAAc,CAC3B,IAAMU,EAAa,IAAI,IAAIC,EAAa,SAAS,GAAG,EAAIA,EAAe,GAAGA,CAAY,GAAG,EACzF,OAAO,IAAI,IAAIX,EAAMU,CAAU,CACjC,CAEA,eAAeF,EACbJ,EACkD,CAClD,IAAMH,EAAOG,EAAS,QAAQ,IAAI,cAAc,GAAG,WAAW,kBAAkB,EAC1E,MAAMA,EAAS,KAAK,EACpB,MAAMA,EAAS,KAAK,EAE1B,OAAIA,EAAS,GACJ,CACL,UAAW,GACX,QAAS,GACT,OAAQA,EAAS,OACjB,WAAYA,EAAS,WACrB,KAAMH,CACR,EAEO,CACL,UAAW,GACX,QAAS,GACT,OAAQG,EAAS,OACjB,WAAYA,EAAS,WACrB,KAAMH,CACR,CAEJ","names":["createLoggerBase","version","chalk","createLogger","level","allowClearScreen","showVersion","logger","createLoggerBase","version","message","options","CLI_PROJECT_NAME","CLI_LOGIN_CLIENT_ID","API_BASE_URL","EDITOR_BASE_URL","Conf","path","crypto","fs","fileURLToPath","chalk","__dirname","fileURLToPath","key","getKey","accessStore","Conf","CLI_PROJECT_NAME","findNearestNodeModules","currentDir","__dirname","path","nodeModulesPath","fs","getKey","tmpSecureStoreDir","keyPath","key","crypto","post","path","data","headers","accessStore","response","toURL","error","logger","formatResponse","get","apiBaseURL","API_BASE_URL"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*! Upstart.gg - Copyright (C) 2024 Flippable - https://github.com/upstart-gg/upstart/blob/main/LICENSE */
|
|
2
2
|
|
|
3
|
-
import U from"chalk";import{confirm as N}from"@inquirer/prompts";import b from"open";var y="upstart-cli";var g=process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID??"50000000-0000-0000-0000-000000000001",u=process.env.PUBLIC_UPSTART_API_BASE_URL??"https://api.upstart.gg",j=process.env.PUBLIC_UPSTART_EDITOR_BASE_URL??"https://upstart.gg";var _="oauth/devicecode",T="oauth/token";import{createLogger as L}from"vite";var h="0.0.
|
|
3
|
+
import U from"chalk";import{confirm as N}from"@inquirer/prompts";import b from"open";var y="upstart-cli";var g=process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID??"50000000-0000-0000-0000-000000000001",u=process.env.PUBLIC_UPSTART_API_BASE_URL??"https://api.upstart.gg",j=process.env.PUBLIC_UPSTART_EDITOR_BASE_URL??"https://upstart.gg";var _="oauth/devicecode",T="oauth/token";import{createLogger as L}from"vite";var h="0.0.94";import i from"chalk";function x(t,e,n=!1){let s=L(t==="debug"?"info":t,{prefix:"[upstart]",allowClearScreen:e});return n&&s.info(i.hex("#7270c6").bold(`\u{1F680} Upstart v${h}
|
|
4
4
|
`)),{...s,success:(r,o)=>s.info(i.green(r),o),error:(r,o)=>s.error(i.red(r),o),warn:(r,o)=>s.warn(i.yellow(r),o),warnOnce:(r,o)=>s.warnOnce(i.yellow(r),o),debug:(r,o)=>{t==="debug"&&s.info(i.gray(r),o)}}}var m=x();import R from"conf";import c from"node:path";import O from"node:crypto";import a from"node:fs";import{fileURLToPath as v}from"node:url";import Q from"chalk";var k=v(new URL(".",import.meta.url)),w=P(),p=new R({projectName:y,encryptionKey:w,clearInvalidConfig:!0});function S(){let t=k;for(;t!==c.parse(t).root;){let e=c.join(t,"node_modules");if(a.existsSync(e))return e;t=c.dirname(t)}return null}function P(){let t=S();if(!t)throw new Error("Could not find nearest node_modules directory.");let e=c.join(t,".enpage-tmp");a.existsSync(e)||a.mkdirSync(e,{recursive:!0,mode:448});let n=c.join(e,".enpage-key");if(!a.existsSync(n)){let r=O.randomBytes(32).toString("hex");return a.writeFileSync(n,r,{mode:384}),r}return a.readFileSync(n,"utf8")}async function l(t,e,n={}){p.get("access_token")&&(n.Authorization=`Bearer ${p.get("access_token")}`);let s=await fetch(C(t),{method:"POST",headers:{"Content-Type":e instanceof URLSearchParams?"application/x-www-form-urlencoded":"application/json",...n},body:e instanceof URLSearchParams?e:JSON.stringify(e)}).catch(r=>{m.error(`Fatal Error requesting API: ${r.message} (${r.cause.code})`),m.error("Please check your internet connection and try again, or retry later."),process.exit(1)});return I(s)}function C(t){let e=new URL(u.endsWith("/")?u:`${u}/`);return new URL(t,e)}async function I(t){let e=t.headers.get("content-type")?.startsWith("application/json")?await t.json():await t.text();return t.ok?{isSuccess:!0,isError:!1,status:t.status,statusText:t.statusText,data:e}:{isSuccess:!1,isError:!0,status:t.status,statusText:t.statusText,data:e}}async function A(t,e){for(;;){let n=new URLSearchParams({grant_type:"device_code",device_code:t,client_id:g}),s=await l(T,n),{data:r,isSuccess:o}=s;if(o)return r;if(r.error==="authorization_pending")await new Promise(f=>setTimeout(f,5e3));else return e.error(`Error while polling for login: ${r.error_description??r.error}`),!1}}async function de({options:t,logger:e}){e.info(`Logging in to Enpage...
|
|
5
5
|
`);let{isError:n,data:s}=await l(_,{client_id:g,scope:"profile,templates:publish"});n&&(e.error("Failed to get device code. Please try again."),e.error(`Error: ${s.error_description??s.error}`),process.exit(1));let{verification_uri:r,device_code:o}=s;await N({message:"Would you like to open the login page in your browser?",default:!0}).catch(D=>{process.exit(0)})?b(r):e.info(`
|
|
6
6
|
Please visit the following URL to login:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/node/cli/commands/login/cmd-login.ts","../../../../../src/node/cli/constants.ts","../../../../../src/node/shared/logger.ts","../../../../../package.json","../../../../../src/node/cli/store.ts","../../../../../src/node/cli/api.ts"],"sourcesContent":["import chalk from \"chalk\";\nimport { confirm } from \"@inquirer/prompts\";\nimport open from \"open\";\nimport { CLI_LOGIN_CLIENT_ID, OAUTH_ENDPOINT_DEVICE_CODE, OAUTH_ENDPOINT_TOKEN } from \"../../constants\";\nimport { post } from \"../../api\";\nimport type { Logger } from \"~/node/shared/logger\";\nimport type { CommandArgOpts, CommonOptions } from \"../../types\";\nimport { accessStore } from \"../../store\";\n\nexport async function pollForLogin(deviceCode: string, logger: Logger) {\n while (true) {\n const body = new URLSearchParams({\n grant_type: \"device_code\",\n device_code: deviceCode,\n client_id: CLI_LOGIN_CLIENT_ID,\n });\n const tokenResponse = await post<DeviceCodeTokenSuccessResponse, DeviceCodeTokenErrorResponse>(\n OAUTH_ENDPOINT_TOKEN,\n body,\n );\n const { data, isSuccess } = tokenResponse;\n\n if (isSuccess) {\n return data;\n }\n\n if (data.error === \"authorization_pending\") {\n await new Promise((resolve) => setTimeout(resolve, 5000));\n } else {\n // other error handling\n logger.error(`Error while polling for login: ${data.error_description ?? data.error}`);\n return false;\n }\n }\n}\n\nexport async function login({ options, logger }: CommandArgOpts<CommonOptions>) {\n logger.info(`Logging in to Enpage...\\n`);\n\n const { isError, data } = await post<DeviceCodeResponse>(OAUTH_ENDPOINT_DEVICE_CODE, {\n client_id: CLI_LOGIN_CLIENT_ID,\n scope: \"profile,templates:publish\",\n });\n\n if (isError) {\n logger.error(\"Failed to get device code. Please try again.\");\n logger.error(`Error: ${data.error_description ?? data.error}`);\n process.exit(1);\n }\n\n const { verification_uri, device_code } = data;\n\n const confirmed = await confirm({\n message: `Would you like to open the login page in your browser?`,\n default: true,\n }).catch((e) => {\n process.exit(0);\n });\n\n if (confirmed) {\n open(verification_uri);\n } else {\n logger.info(`\\nPlease visit the following URL to login:\\n ${verification_uri}\\n`);\n }\n\n logger.info(chalk.gray(\"\\nWaiting for login...\\n\"));\n\n const loginData = await pollForLogin(device_code, logger);\n\n if (!loginData) {\n logger.error(\"Login failed. Please try again.\");\n process.exit(1);\n }\n\n // Store the access token info\n accessStore.set({\n ...loginData,\n ...(loginData.expires_in ? { expires_at: Date.now() + loginData.expires_in * 1000 } : {}),\n });\n\n logger.info(\"Login successful!\\n\");\n process.exitCode = 0;\n}\n\ntype DeviceCodeResponse = {\n success: true;\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string; // Optional as per RFC 8628\n expires_in: number;\n interval?: number; // Optional as per RFC 8628\n};\n\n// Union type for the response\n\ntype DeviceCodeTokenSuccessResponse = {\n success: true;\n access_token: string;\n token_type: string;\n expires_in?: number;\n refresh_token?: string;\n scope?: string;\n};\n\n// Error response type for token request\ntype DeviceCodeTokenErrorResponse = {\n error: \"authorization_pending\" | \"slow_down\" | \"access_denied\" | \"expired_token\" | string;\n error_description?: string;\n error_uri?: string;\n};\n","export const CLI_PROJECT_NAME = \"upstart-cli\";\nexport const CLI_LOGIN_POLL_INTERVAL = 5000; // seconds\nexport const CLI_LOGIN_CLIENT_ID =\n process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID ?? \"50000000-0000-0000-0000-000000000001\";\n\nexport const API_BASE_URL = process.env.PUBLIC_UPSTART_API_BASE_URL ?? \"https://api.upstart.gg\";\nexport const EDITOR_BASE_URL = process.env.PUBLIC_UPSTART_EDITOR_BASE_URL ?? \"https://upstart.gg\";\nexport const DEFAULT_UPLOAD_MAX_CONCURRENCY = 10;\n\nexport const OAUTH_ENDPOINT_DEVICE_CODE = \"oauth/devicecode\";\nexport const OAUTH_ENDPOINT_TOKEN = \"oauth/token\";\nexport const OAUTH_ENDPOINT_USER_INFO = \"oauth/userinfo\";\n\nexport const API_ENDPOINT_REGISTER_TEMPLATE = \"v1/templates\";\n","import {\n createLogger as createLoggerBase,\n type LogLevel,\n type LogOptions,\n type Logger as BaseLogger,\n} from \"vite\";\nimport { version } from \"../../../package.json\";\nimport chalk from \"chalk\";\n\ntype UpstartLoggerLevel = LogLevel | \"debug\";\n\nexport function createLogger(level?: UpstartLoggerLevel, allowClearScreen?: boolean, showVersion = false) {\n // vite logger does not support \"debug\" level\n const logger = createLoggerBase(level === \"debug\" ? \"info\" : level, {\n prefix: \"[upstart]\",\n allowClearScreen,\n });\n\n if (showVersion) {\n logger.info(chalk.hex(\"#7270c6\").bold(`🚀 Upstart v${version}\\n`));\n }\n\n return {\n ...logger,\n success: (message: string, options?: LogOptions) => logger.info(chalk.green(message), options),\n error: (message: string, options?: LogOptions) => logger.error(chalk.red(message), options),\n warn: (message: string, options?: LogOptions) => logger.warn(chalk.yellow(message), options),\n warnOnce: (message: string, options?: LogOptions) => logger.warnOnce(chalk.yellow(message), options),\n debug: (message: string, options?: LogOptions) => {\n if (level === \"debug\") {\n logger.info(chalk.gray(message), options);\n }\n },\n };\n}\n\nexport const logger = createLogger();\n\nexport type Logger = BaseLogger & {\n success: (message: string, options?: LogOptions) => void;\n debug: (message: string, options?: LogOptions) => void;\n};\n","{\n \"name\": \"@upstart.gg/sdk\",\n \"version\": \"0.0.93\",\n \"type\": \"module\",\n \"files\": [\n \"dist\",\n \"env.d.ts\"\n ],\n \"sideEffects\": false,\n \"exports\": {\n \".\": {\n \"import\": \"./dist/shared/index.js\",\n \"types\": \"./dist/shared/index.d.ts\"\n },\n \"./shared/*\": {\n \"types\": \"./dist/shared/*.d.ts\",\n \"import\": \"./dist/shared/*.js\"\n },\n \"./builder/*\": {\n \"import\": \"./dist/node/builder/*.js\"\n },\n \"./cli/*\": {\n \"import\": \"./dist/node/cli/*.js\"\n },\n \"./env.d.ts\": {\n \"types\": \"./env.d.ts\",\n \"require\": \"./env.d.ts\",\n \"import\": \"./env.d.ts\"\n },\n \"./*\": {\n \"types\": \"./dist/shared/*.d.ts\",\n \"import\": \"./dist/shared/*.js\"\n }\n },\n \"bin\": {\n \"enpage\": \"dist/node/cli/program.js\"\n },\n \"dependencies\": {\n \"@date-fns/utc\": \"1.2.0\",\n \"@headlessui/react\": \"2.1.2\",\n \"@inquirer/prompts\": \"5.3.8\",\n \"@radix-ui/react-context-menu\": \"2.2.2\",\n \"@radix-ui/react-toggle-group\": \"1.1.0\",\n \"@radix-ui/themes\": \"3.1.4\",\n \"@sinclair/typebox\": \"0.33.7\",\n \"@upstart.gg/style-system\": \"workspace:*\",\n \"ajv\": \"8.17.1\",\n \"ajv-formats\": \"3.0.1\",\n \"chalk\": \"5.3.0\",\n \"chroma-js\": \"3.1.2\",\n \"commander\": \"12.1.0\",\n \"conf\": \"13.0.1\",\n \"date-fns\": \"3.6.0\",\n \"debug\": \"4.3.6\",\n \"fast-glob\": \"3.3.2\",\n \"form-data\": \"4.0.0\",\n \"get-port\": \"7.1.0\",\n \"htmlparser2\": \"9.1.0\",\n \"http-errors-enhanced\": \"2.0.8\",\n \"immer\": \"10.1.1\",\n \"import-meta-resolve\": \"4.1.0\",\n \"lodash-es\": \"4.17.21\",\n \"nanoid\": \"5.0.7\",\n \"open\": \"10.1.0\",\n \"ora\": \"8.1.0\",\n \"p-queue\": \"8.0.1\",\n \"react-hotkeys-hook\": \"4.5.1\",\n \"react-icons\": \"5.3.0\",\n \"react-selecto\": \"1.26.3\",\n \"rollup-plugin-strip-banner\": \"3.1.0\",\n \"usehooks-ts\": \"3.1.0\",\n \"zundo\": \"2.3.0\",\n \"zustand\": \"4.5.5\"\n },\n \"peerDependencies\": {\n \"@upstart.gg/style-system\": \"workspace:*\",\n \"react\": \"18.3.0-canary-3d9b20132-20240124\",\n \"react-dom\": \"18.3.0-canary-3d9b20132-20240124\"\n },\n \"devDependencies\": {\n \"@cloudflare/workers-types\": \"4.20240806.0\",\n \"@types/chroma-js\": \"2.4.4\",\n \"@types/cli-progress\": \"3.11.6\",\n \"@types/debug\": \"4.1.12\",\n \"@types/express\": \"^4.17.21\",\n \"@types/lodash-es\": \"4.17.12\",\n \"@types/node\": \"^20.14.10\",\n \"@types/react\": \"18.3.3\",\n \"@types/react-dom\": \"^18.3.0\",\n \"@types/sortablejs\": \"1.15.8\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"concurrently\": \"8.2.2\",\n \"express\": \"^4.21.2\",\n \"rimraf\": \"6.0.1\",\n \"tsup\": \"8.2.4\",\n \"vite\": \"5.4.6\",\n \"vite-plugin-dts\": \"4.2.1\",\n \"vite-plugin-image-optimizer\": \"1.1.8\",\n \"vite-plugin-inspect\": \"0.8.7\",\n \"vite-plugin-virtual\": \"0.3.0\",\n \"vite-tsconfig-paths\": \"5.0.1\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"build:types\": \"tsc --emitDeclarationOnly --declaration --declarationMap\",\n \"dev\": \"NODE_OPTIONS='--max-old-space-size=12384' tsup --watch\",\n \"sizetest\": \"pnpm build && du -sh dist\",\n \"lint\": \"biome check --write . && tsc --noEmit\",\n \"ci:lint\": \"tsc --noEmit\",\n \"test\": \"vitest\",\n \"prepare\": \"node ./scripts/prepare.cjs\",\n \"gen-ia-docs\": \"tsx scripts/generate-ia-docs.ts\"\n },\n \"author\": \"Matthias Etienne\",\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","import type { CredentialsStore } from \"./types\";\nimport { CLI_PROJECT_NAME, OAUTH_ENDPOINT_USER_INFO } from \"./constants\";\nimport Conf from \"conf\";\nimport path from \"node:path\";\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { getPackageManager } from \"./utils\";\nimport chalk from \"chalk\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\nconst key = getKey();\nconst accessStore = new Conf<CredentialsStore>({\n projectName: CLI_PROJECT_NAME,\n encryptionKey: key,\n clearInvalidConfig: true,\n});\n\n/**\n * Get access token or throw error if not found\n */\nexport function getTokenOrThrow() {\n const token = accessStore.get(\"access_token\");\n if (!token) {\n const pkgCmd = getPackageManager();\n throw new Error(\n `Access token not found. Please run ${chalk.cyan(`${pkgCmd} run enpage:login`)} to authenticate.`,\n );\n }\n return token;\n}\n\nfunction findNearestNodeModules(): string | null {\n let currentDir = __dirname;\n while (currentDir !== path.parse(currentDir).root) {\n const nodeModulesPath = path.join(currentDir, \"node_modules\");\n if (fs.existsSync(nodeModulesPath)) {\n return nodeModulesPath;\n }\n currentDir = path.dirname(currentDir);\n }\n return null;\n}\n\nfunction getKey() {\n const nodeModulesPath = findNearestNodeModules();\n if (!nodeModulesPath) {\n throw new Error(\"Could not find nearest node_modules directory.\");\n }\n const tmpSecureStoreDir = path.join(nodeModulesPath, \".enpage-tmp\");\n if (!fs.existsSync(tmpSecureStoreDir)) {\n fs.mkdirSync(tmpSecureStoreDir, { recursive: true, mode: 0o700 });\n }\n const keyPath = path.join(tmpSecureStoreDir, \".enpage-key\");\n if (!fs.existsSync(keyPath)) {\n const key = crypto.randomBytes(32).toString(\"hex\");\n fs.writeFileSync(keyPath, key, { mode: 0o600 });\n return key;\n }\n const key = fs.readFileSync(keyPath, \"utf8\");\n return key;\n}\n\nexport { accessStore };\n","import { logger } from \"../shared/logger\";\nimport { API_BASE_URL } from \"./constants\";\nimport { accessStore } from \"./store\";\n\ntype SuccessResponseWrapper<T> = {\n isSuccess: true;\n isError: false;\n status: number;\n statusText: string;\n data: T;\n};\n\ntype ErrorResponseWrapper<E> = {\n isSuccess: false;\n isError: true;\n status: number;\n statusText: string;\n data: E;\n};\n\ntype ResponseWrapper<T, E> = SuccessResponseWrapper<T> | ErrorResponseWrapper<E>;\n\ntype CommonResponseType = {\n success: boolean;\n};\n\n/**\n *\n * @param pathOrUrl\n * @param data\n * @returns\n */\nexport async function post<\n ResponseType extends CommonResponseType = CommonResponseType,\n ErrorType = { error: string; error_description?: string },\n>(path: string, data: Record<string, unknown> | URLSearchParams, headers: Record<string, string> = {}) {\n if (accessStore.get(\"access_token\")) {\n headers.Authorization = `Bearer ${accessStore.get(\"access_token\")}`;\n }\n const response = await fetch(toURL(path), {\n method: \"POST\",\n headers: {\n \"Content-Type\":\n data instanceof URLSearchParams ? \"application/x-www-form-urlencoded\" : \"application/json\",\n ...headers,\n },\n body: data instanceof URLSearchParams ? data : JSON.stringify(data),\n }).catch((error) => {\n logger.error(`Fatal Error requesting API: ${error.message} (${error.cause.code})`);\n logger.error(`Please check your internet connection and try again, or retry later.`);\n process.exit(1);\n });\n\n return formatResponse<ResponseType, ErrorType>(response);\n}\n\nexport async function get<ResponseType = unknown, ErrorType = { error: string; error_description?: string }>(\n path: string,\n headers: Record<string, string> = {},\n) {\n if (accessStore.get(\"access_token\")) {\n headers.Authorization = `Bearer ${accessStore.get(\"access_token\")}`;\n }\n const response = await fetch(toURL(path), { headers, method: \"GET\" }).catch((error) => {\n logger.error(`Fatal Error requesting API: ${error.message} (${error.cause.code})`);\n logger.error(`Please check your internet connection and try again, or retry later.`);\n process.exit(1);\n });\n return formatResponse<ResponseType, ErrorType>(response);\n}\n\nfunction toURL(path: string) {\n const apiBaseURL = new URL(API_BASE_URL.endsWith(\"/\") ? API_BASE_URL : `${API_BASE_URL}/`);\n return new URL(path, apiBaseURL);\n}\n\nasync function formatResponse<SuccessType, ErrorType>(\n response: Response,\n): Promise<ResponseWrapper<SuccessType, ErrorType>> {\n const data = response.headers.get(\"content-type\")?.startsWith(\"application/json\")\n ? ((await response.json()) as ResponseType)\n : ((await response.text()) as ResponseType);\n\n if (response.ok) {\n return {\n isSuccess: true,\n isError: false,\n status: response.status,\n statusText: response.statusText,\n data: data as SuccessType,\n };\n } else {\n return {\n isSuccess: false,\n isError: true,\n status: response.status,\n statusText: response.statusText,\n data: data as ErrorType,\n };\n }\n}\n"],"mappings":";;AAAA,OAAOA,MAAW,QAClB,OAAS,WAAAC,MAAe,oBACxB,OAAOC,MAAU,OCFV,IAAMC,EAAmB,cAEzB,IAAMC,EACX,QAAQ,IAAI,gCAAkC,uCAEnCC,EAAe,QAAQ,IAAI,6BAA+B,yBAC1DC,EAAkB,QAAQ,IAAI,gCAAkC,qBAGtE,IAAMC,EAA6B,mBAC7BC,EAAuB,cCVpC,OACE,gBAAgBC,MAIX,OCHL,IAAAC,EAAW,SDKb,OAAOC,MAAW,QAIX,SAASC,EAAaC,EAA4BC,EAA4BC,EAAc,GAAO,CAExG,IAAMC,EAASC,EAAiBJ,IAAU,QAAU,OAASA,EAAO,CAClE,OAAQ,YACR,iBAAAC,CACF,CAAC,EAED,OAAIC,GACFC,EAAO,KAAKL,EAAM,IAAI,SAAS,EAAE,KAAK,sBAAeO,CAAO;AAAA,CAAI,CAAC,EAG5D,CACL,GAAGF,EACH,QAAS,CAACG,EAAiBC,IAAyBJ,EAAO,KAAKL,EAAM,MAAMQ,CAAO,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Y,KAAK,IAAI,EAAIA,EAAU,WAAa,GAAK,EAAI,CAAC,CACzF,CAAC,EAEDnB,EAAO,KAAK;AAAA,CAAqB,EACjC,QAAQ,SAAW,CACrB","names":["chalk","confirm","open","CLI_PROJECT_NAME","CLI_LOGIN_CLIENT_ID","API_BASE_URL","EDITOR_BASE_URL","OAUTH_ENDPOINT_DEVICE_CODE","OAUTH_ENDPOINT_TOKEN","createLoggerBase","version","chalk","createLogger","level","allowClearScreen","showVersion","logger","createLoggerBase","version","message","options","Conf","path","crypto","fs","fileURLToPath","chalk","__dirname","fileURLToPath","key","getKey","accessStore","Conf","CLI_PROJECT_NAME","findNearestNodeModules","currentDir","__dirname","path","nodeModulesPath","fs","getKey","tmpSecureStoreDir","keyPath","key","crypto","post","path","data","headers","accessStore","response","toURL","error","logger","formatResponse","toURL","path","apiBaseURL","API_BASE_URL","formatResponse","response","data","pollForLogin","deviceCode","logger","body","CLI_LOGIN_CLIENT_ID","tokenResponse","post","OAUTH_ENDPOINT_TOKEN","data","isSuccess","resolve","login","options","isError","OAUTH_ENDPOINT_DEVICE_CODE","verification_uri","device_code","confirm","e","open","chalk","loginData","accessStore"]}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/node/cli/commands/login/cmd-login.ts","../../../../../src/node/cli/constants.ts","../../../../../src/node/shared/logger.ts","../../../../../package.json","../../../../../src/node/cli/store.ts","../../../../../src/node/cli/api.ts"],"sourcesContent":["import chalk from \"chalk\";\nimport { confirm } from \"@inquirer/prompts\";\nimport open from \"open\";\nimport { CLI_LOGIN_CLIENT_ID, OAUTH_ENDPOINT_DEVICE_CODE, OAUTH_ENDPOINT_TOKEN } from \"../../constants\";\nimport { post } from \"../../api\";\nimport type { Logger } from \"~/node/shared/logger\";\nimport type { CommandArgOpts, CommonOptions } from \"../../types\";\nimport { accessStore } from \"../../store\";\n\nexport async function pollForLogin(deviceCode: string, logger: Logger) {\n while (true) {\n const body = new URLSearchParams({\n grant_type: \"device_code\",\n device_code: deviceCode,\n client_id: CLI_LOGIN_CLIENT_ID,\n });\n const tokenResponse = await post<DeviceCodeTokenSuccessResponse, DeviceCodeTokenErrorResponse>(\n OAUTH_ENDPOINT_TOKEN,\n body,\n );\n const { data, isSuccess } = tokenResponse;\n\n if (isSuccess) {\n return data;\n }\n\n if (data.error === \"authorization_pending\") {\n await new Promise((resolve) => setTimeout(resolve, 5000));\n } else {\n // other error handling\n logger.error(`Error while polling for login: ${data.error_description ?? data.error}`);\n return false;\n }\n }\n}\n\nexport async function login({ options, logger }: CommandArgOpts<CommonOptions>) {\n logger.info(`Logging in to Enpage...\\n`);\n\n const { isError, data } = await post<DeviceCodeResponse>(OAUTH_ENDPOINT_DEVICE_CODE, {\n client_id: CLI_LOGIN_CLIENT_ID,\n scope: \"profile,templates:publish\",\n });\n\n if (isError) {\n logger.error(\"Failed to get device code. Please try again.\");\n logger.error(`Error: ${data.error_description ?? data.error}`);\n process.exit(1);\n }\n\n const { verification_uri, device_code } = data;\n\n const confirmed = await confirm({\n message: `Would you like to open the login page in your browser?`,\n default: true,\n }).catch((e) => {\n process.exit(0);\n });\n\n if (confirmed) {\n open(verification_uri);\n } else {\n logger.info(`\\nPlease visit the following URL to login:\\n ${verification_uri}\\n`);\n }\n\n logger.info(chalk.gray(\"\\nWaiting for login...\\n\"));\n\n const loginData = await pollForLogin(device_code, logger);\n\n if (!loginData) {\n logger.error(\"Login failed. Please try again.\");\n process.exit(1);\n }\n\n // Store the access token info\n accessStore.set({\n ...loginData,\n ...(loginData.expires_in ? { expires_at: Date.now() + loginData.expires_in * 1000 } : {}),\n });\n\n logger.info(\"Login successful!\\n\");\n process.exitCode = 0;\n}\n\ntype DeviceCodeResponse = {\n success: true;\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string; // Optional as per RFC 8628\n expires_in: number;\n interval?: number; // Optional as per RFC 8628\n};\n\n// Union type for the response\n\ntype DeviceCodeTokenSuccessResponse = {\n success: true;\n access_token: string;\n token_type: string;\n expires_in?: number;\n refresh_token?: string;\n scope?: string;\n};\n\n// Error response type for token request\ntype DeviceCodeTokenErrorResponse = {\n error: \"authorization_pending\" | \"slow_down\" | \"access_denied\" | \"expired_token\" | string;\n error_description?: string;\n error_uri?: string;\n};\n","export const CLI_PROJECT_NAME = \"upstart-cli\";\nexport const CLI_LOGIN_POLL_INTERVAL = 5000; // seconds\nexport const CLI_LOGIN_CLIENT_ID =\n process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID ?? \"50000000-0000-0000-0000-000000000001\";\n\nexport const API_BASE_URL = process.env.PUBLIC_UPSTART_API_BASE_URL ?? \"https://api.upstart.gg\";\nexport const EDITOR_BASE_URL = process.env.PUBLIC_UPSTART_EDITOR_BASE_URL ?? \"https://upstart.gg\";\nexport const DEFAULT_UPLOAD_MAX_CONCURRENCY = 10;\n\nexport const OAUTH_ENDPOINT_DEVICE_CODE = \"oauth/devicecode\";\nexport const OAUTH_ENDPOINT_TOKEN = \"oauth/token\";\nexport const OAUTH_ENDPOINT_USER_INFO = \"oauth/userinfo\";\n\nexport const API_ENDPOINT_REGISTER_TEMPLATE = \"v1/templates\";\n","import {\n createLogger as createLoggerBase,\n type LogLevel,\n type LogOptions,\n type Logger as BaseLogger,\n} from \"vite\";\nimport { version } from \"../../../package.json\";\nimport chalk from \"chalk\";\n\ntype UpstartLoggerLevel = LogLevel | \"debug\";\n\nexport function createLogger(level?: UpstartLoggerLevel, allowClearScreen?: boolean, showVersion = false) {\n // vite logger does not support \"debug\" level\n const logger = createLoggerBase(level === \"debug\" ? \"info\" : level, {\n prefix: \"[upstart]\",\n allowClearScreen,\n });\n\n if (showVersion) {\n logger.info(chalk.hex(\"#7270c6\").bold(`🚀 Upstart v${version}\\n`));\n }\n\n return {\n ...logger,\n success: (message: string, options?: LogOptions) => logger.info(chalk.green(message), options),\n error: (message: string, options?: LogOptions) => logger.error(chalk.red(message), options),\n warn: (message: string, options?: LogOptions) => logger.warn(chalk.yellow(message), options),\n warnOnce: (message: string, options?: LogOptions) => logger.warnOnce(chalk.yellow(message), options),\n debug: (message: string, options?: LogOptions) => {\n if (level === \"debug\") {\n logger.info(chalk.gray(message), options);\n }\n },\n };\n}\n\nexport const logger = createLogger();\n\nexport type Logger = BaseLogger & {\n success: (message: string, options?: LogOptions) => void;\n debug: (message: string, options?: LogOptions) => void;\n};\n","{\n \"name\": \"@upstart.gg/sdk\",\n \"version\": \"0.0.94\",\n \"type\": \"module\",\n \"files\": [\n \"dist\",\n \"env.d.ts\"\n ],\n \"sideEffects\": false,\n \"exports\": {\n \".\": {\n \"import\": \"./dist/shared/index.js\",\n \"types\": \"./dist/shared/index.d.ts\"\n },\n \"./shared/*\": {\n \"types\": \"./dist/shared/*.d.ts\",\n \"import\": \"./dist/shared/*.js\"\n },\n \"./builder/*\": {\n \"import\": \"./dist/node/builder/*.js\"\n },\n \"./cli/*\": {\n \"import\": \"./dist/node/cli/*.js\"\n },\n \"./env.d.ts\": {\n \"types\": \"./env.d.ts\",\n \"require\": \"./env.d.ts\",\n \"import\": \"./env.d.ts\"\n },\n \"./*\": {\n \"types\": \"./dist/shared/*.d.ts\",\n \"import\": \"./dist/shared/*.js\"\n }\n },\n \"dependencies\": {\n \"@date-fns/utc\": \"1.2.0\",\n \"@headlessui/react\": \"2.2.1\",\n \"@inquirer/prompts\": \"5.3.8\",\n \"@radix-ui/react-context-menu\": \"2.2.2\",\n \"@radix-ui/react-toggle-group\": \"1.1.0\",\n \"@radix-ui/themes\": \"3.1.4\",\n \"@sinclair/typebox\": \"0.33.7\",\n \"@upstart.gg/style-system\": \"workspace:*\",\n \"ajv\": \"8.17.1\",\n \"ajv-formats\": \"3.0.1\",\n \"chalk\": \"5.3.0\",\n \"chroma-js\": \"3.1.2\",\n \"commander\": \"12.1.0\",\n \"conf\": \"13.0.1\",\n \"date-fns\": \"3.6.0\",\n \"debug\": \"4.3.6\",\n \"fast-glob\": \"3.3.2\",\n \"form-data\": \"4.0.0\",\n \"get-port\": \"7.1.0\",\n \"htmlparser2\": \"9.1.0\",\n \"http-errors-enhanced\": \"2.0.8\",\n \"immer\": \"10.1.1\",\n \"import-meta-resolve\": \"4.1.0\",\n \"lodash-es\": \"4.17.21\",\n \"nanoid\": \"5.0.7\",\n \"open\": \"10.1.0\",\n \"ora\": \"8.1.0\",\n \"p-queue\": \"8.0.1\",\n \"react-hotkeys-hook\": \"4.5.1\",\n \"react-icons\": \"5.3.0\",\n \"react-selecto\": \"1.26.3\",\n \"rollup-plugin-strip-banner\": \"3.1.0\",\n \"usehooks-ts\": \"3.1.0\",\n \"zundo\": \"2.3.0\",\n \"zustand\": \"4.5.5\"\n },\n \"peerDependencies\": {\n \"@upstart.gg/style-system\": \"workspace:*\",\n \"react\": \"18.3.0-canary-3d9b20132-20240124\",\n \"react-dom\": \"18.3.0-canary-3d9b20132-20240124\"\n },\n \"devDependencies\": {\n \"@cloudflare/workers-types\": \"4.20240806.0\",\n \"@types/chroma-js\": \"2.4.4\",\n \"@types/cli-progress\": \"3.11.6\",\n \"@types/debug\": \"4.1.12\",\n \"@types/express\": \"^4.17.21\",\n \"@types/lodash-es\": \"4.17.12\",\n \"@types/node\": \"^20.14.10\",\n \"@types/react\": \"18.3.3\",\n \"@types/react-dom\": \"^18.3.0\",\n \"@types/sortablejs\": \"1.15.8\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"concurrently\": \"8.2.2\",\n \"express\": \"^4.21.2\",\n \"rimraf\": \"6.0.1\",\n \"tsup\": \"8.2.4\",\n \"vite\": \"5.4.6\",\n \"vite-plugin-dts\": \"4.2.1\",\n \"vite-plugin-image-optimizer\": \"1.1.8\",\n \"vite-plugin-inspect\": \"0.8.7\",\n \"vite-plugin-virtual\": \"0.3.0\",\n \"vite-tsconfig-paths\": \"5.0.1\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"build:types\": \"tsc --emitDeclarationOnly --declaration --declarationMap\",\n \"dev\": \"NODE_OPTIONS='--max-old-space-size=12384' tsup --watch\",\n \"sizetest\": \"pnpm build && du -sh dist\",\n \"lint\": \"biome check --write . && tsc --noEmit\",\n \"ci:lint\": \"tsc --noEmit\",\n \"test\": \"vitest\",\n \"gen-ia-docs\": \"tsx scripts/generate-ia-docs.ts\"\n },\n \"author\": \"Matthias Etienne\",\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","import type { CredentialsStore } from \"./types\";\nimport { CLI_PROJECT_NAME, OAUTH_ENDPOINT_USER_INFO } from \"./constants\";\nimport Conf from \"conf\";\nimport path from \"node:path\";\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { getPackageManager } from \"./utils\";\nimport chalk from \"chalk\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\nconst key = getKey();\nconst accessStore = new Conf<CredentialsStore>({\n projectName: CLI_PROJECT_NAME,\n encryptionKey: key,\n clearInvalidConfig: true,\n});\n\n/**\n * Get access token or throw error if not found\n */\nexport function getTokenOrThrow() {\n const token = accessStore.get(\"access_token\");\n if (!token) {\n const pkgCmd = getPackageManager();\n throw new Error(\n `Access token not found. Please run ${chalk.cyan(`${pkgCmd} run enpage:login`)} to authenticate.`,\n );\n }\n return token;\n}\n\nfunction findNearestNodeModules(): string | null {\n let currentDir = __dirname;\n while (currentDir !== path.parse(currentDir).root) {\n const nodeModulesPath = path.join(currentDir, \"node_modules\");\n if (fs.existsSync(nodeModulesPath)) {\n return nodeModulesPath;\n }\n currentDir = path.dirname(currentDir);\n }\n return null;\n}\n\nfunction getKey() {\n const nodeModulesPath = findNearestNodeModules();\n if (!nodeModulesPath) {\n throw new Error(\"Could not find nearest node_modules directory.\");\n }\n const tmpSecureStoreDir = path.join(nodeModulesPath, \".enpage-tmp\");\n if (!fs.existsSync(tmpSecureStoreDir)) {\n fs.mkdirSync(tmpSecureStoreDir, { recursive: true, mode: 0o700 });\n }\n const keyPath = path.join(tmpSecureStoreDir, \".enpage-key\");\n if (!fs.existsSync(keyPath)) {\n const key = crypto.randomBytes(32).toString(\"hex\");\n fs.writeFileSync(keyPath, key, { mode: 0o600 });\n return key;\n }\n const key = fs.readFileSync(keyPath, \"utf8\");\n return key;\n}\n\nexport { accessStore };\n","import { logger } from \"../shared/logger\";\nimport { API_BASE_URL } from \"./constants\";\nimport { accessStore } from \"./store\";\n\ntype SuccessResponseWrapper<T> = {\n isSuccess: true;\n isError: false;\n status: number;\n statusText: string;\n data: T;\n};\n\ntype ErrorResponseWrapper<E> = {\n isSuccess: false;\n isError: true;\n status: number;\n statusText: string;\n data: E;\n};\n\ntype ResponseWrapper<T, E> = SuccessResponseWrapper<T> | ErrorResponseWrapper<E>;\n\ntype CommonResponseType = {\n success: boolean;\n};\n\n/**\n *\n * @param pathOrUrl\n * @param data\n * @returns\n */\nexport async function post<\n ResponseType extends CommonResponseType = CommonResponseType,\n ErrorType = { error: string; error_description?: string },\n>(path: string, data: Record<string, unknown> | URLSearchParams, headers: Record<string, string> = {}) {\n if (accessStore.get(\"access_token\")) {\n headers.Authorization = `Bearer ${accessStore.get(\"access_token\")}`;\n }\n const response = await fetch(toURL(path), {\n method: \"POST\",\n headers: {\n \"Content-Type\":\n data instanceof URLSearchParams ? \"application/x-www-form-urlencoded\" : \"application/json\",\n ...headers,\n },\n body: data instanceof URLSearchParams ? data : JSON.stringify(data),\n }).catch((error) => {\n logger.error(`Fatal Error requesting API: ${error.message} (${error.cause.code})`);\n logger.error(`Please check your internet connection and try again, or retry later.`);\n process.exit(1);\n });\n\n return formatResponse<ResponseType, ErrorType>(response);\n}\n\nexport async function get<ResponseType = unknown, ErrorType = { error: string; error_description?: string }>(\n path: string,\n headers: Record<string, string> = {},\n) {\n if (accessStore.get(\"access_token\")) {\n headers.Authorization = `Bearer ${accessStore.get(\"access_token\")}`;\n }\n const response = await fetch(toURL(path), { headers, method: \"GET\" }).catch((error) => {\n logger.error(`Fatal Error requesting API: ${error.message} (${error.cause.code})`);\n logger.error(`Please check your internet connection and try again, or retry later.`);\n process.exit(1);\n });\n return formatResponse<ResponseType, ErrorType>(response);\n}\n\nfunction toURL(path: string) {\n const apiBaseURL = new URL(API_BASE_URL.endsWith(\"/\") ? API_BASE_URL : `${API_BASE_URL}/`);\n return new URL(path, apiBaseURL);\n}\n\nasync function formatResponse<SuccessType, ErrorType>(\n response: Response,\n): Promise<ResponseWrapper<SuccessType, ErrorType>> {\n const data = response.headers.get(\"content-type\")?.startsWith(\"application/json\")\n ? ((await response.json()) as ResponseType)\n : ((await response.text()) as ResponseType);\n\n if (response.ok) {\n return {\n isSuccess: true,\n isError: false,\n status: response.status,\n statusText: response.statusText,\n data: data as SuccessType,\n };\n } else {\n return {\n isSuccess: false,\n isError: true,\n status: response.status,\n statusText: response.statusText,\n data: data as ErrorType,\n };\n }\n}\n"],"mappings":";;AAAA,OAAOA,MAAW,QAClB,OAAS,WAAAC,MAAe,oBACxB,OAAOC,MAAU,OCFV,IAAMC,EAAmB,cAEzB,IAAMC,EACX,QAAQ,IAAI,gCAAkC,uCAEnCC,EAAe,QAAQ,IAAI,6BAA+B,yBAC1DC,EAAkB,QAAQ,IAAI,gCAAkC,qBAGtE,IAAMC,EAA6B,mBAC7BC,EAAuB,cCVpC,OACE,gBAAgBC,MAIX,OCHL,IAAAC,EAAW,SDKb,OAAOC,MAAW,QAIX,SAASC,EAAaC,EAA4BC,EAA4BC,EAAc,GAAO,CAExG,IAAMC,EAASC,EAAiBJ,IAAU,QAAU,OAASA,EAAO,CAClE,OAAQ,YACR,iBAAAC,CACF,CAAC,EAED,OAAIC,GACFC,EAAO,KAAKL,EAAM,IAAI,SAAS,EAAE,KAAK,sBAAeO,CAAO;AAAA,CAAI,CAAC,EAG5D,CACL,GAAGF,EACH,QAAS,CAACG,EAAiBC,IAAyBJ,EAAO,KAAKL,EAAM,MAAMQ,CAAO,EAAGC,CAAO,EAC7F,MAAO,CAACD,EAAiBC,IAAyBJ,EAAO,MAAML,EAAM,IAAIQ,CAAO,EAAGC,CAAO,EAC1F,KAAM,CAACD,EAAiBC,IAAyBJ,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m","open","CLI_PROJECT_NAME","CLI_LOGIN_CLIENT_ID","API_BASE_URL","EDITOR_BASE_URL","OAUTH_ENDPOINT_DEVICE_CODE","OAUTH_ENDPOINT_TOKEN","createLoggerBase","version","chalk","createLogger","level","allowClearScreen","showVersion","logger","createLoggerBase","version","message","options","Conf","path","crypto","fs","fileURLToPath","chalk","__dirname","fileURLToPath","key","getKey","accessStore","Conf","CLI_PROJECT_NAME","findNearestNodeModules","currentDir","__dirname","path","nodeModulesPath","fs","getKey","tmpSecureStoreDir","keyPath","key","crypto","post","path","data","headers","accessStore","response","toURL","error","logger","formatResponse","toURL","path","apiBaseURL","API_BASE_URL","formatResponse","response","data","pollForLogin","deviceCode","logger","body","CLI_LOGIN_CLIENT_ID","tokenResponse","post","OAUTH_ENDPOINT_TOKEN","data","isSuccess","resolve","login","options","isError","OAUTH_ENDPOINT_DEVICE_CODE","verification_uri","device_code","confirm","e","open","chalk","loginData","accessStore"]}
|
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
/*! Upstart.gg - Copyright (C) 2024 Flippable - https://github.com/upstart-gg/upstart/blob/main/LICENSE */
|
|
2
2
|
|
|
3
|
-
var me=Object.defineProperty;var x=(e,t)=>()=>(e&&(t=e(e=0)),t);var fe=(e,t)=>{for(var r in t)me(e,r,{get:t[r],enumerable:!0})};function D(){let e;if(process.env.npm_config_user_agent){let t=process.env.npm_config_user_agent.split(" ")[0];e=t.slice(0,t.lastIndexOf("/"))}return e||(console.log("Warning: could not detect package manager"),e="npm"),e}function q(e){return`[${e.error}]${e.error_description?`: ${e.error_description}`:""}`}var W=x(()=>{"use strict"});var J,dt,P,gt,X,Y,K,b=x(()=>{"use strict";J="upstart-cli",dt=process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID??"50000000-0000-0000-0000-000000000001",P=process.env.PUBLIC_UPSTART_API_BASE_URL??"https://api.upstart.gg",gt=process.env.PUBLIC_UPSTART_EDITOR_BASE_URL??"https://upstart.gg",X=10,Y="oauth/userinfo",K="v1/templates"});import ye from"conf";import C from"node:path";import he from"node:crypto";import R from"node:fs";import{fileURLToPath as Se}from"node:url";import Ee from"chalk";function V(){let e=f.get("access_token");if(!e){let t=D();throw new Error(`Access token not found. Please run ${Ee.cyan(`${t} run enpage:login`)} to authenticate.`)}return e}function we(){let e=Te;for(;e!==C.parse(e).root;){let t=C.join(e,"node_modules");if(R.existsSync(t))return t;e=C.dirname(e)}return null}function _e(){let e=we();if(!e)throw new Error("Could not find nearest node_modules directory.");let t=C.join(e,".enpage-tmp");R.existsSync(t)||R.mkdirSync(t,{recursive:!0,mode:448});let r=C.join(t,".enpage-key");if(!R.existsSync(r)){let o=he.randomBytes(32).toString("hex");return R.writeFileSync(r,o,{mode:384}),o}return R.readFileSync(r,"utf8")}var Te,Pe,f,F=x(()=>{"use strict";b();W();Te=Se(new URL(".",import.meta.url)),Pe=_e(),f=new ye({projectName:J,encryptionKey:Pe,clearInvalidConfig:!0})});var Z,Q=x(()=>{Z="0.0.
|
|
4
|
-
`)),{...s,success:(o,n)=>s.info(k.green(o),n),error:(o,n)=>s.error(k.red(o),n),warn:(o,n)=>s.warn(k.yellow(o),n),warnOnce:(o,n)=>s.warnOnce(k.yellow(o),n),debug:(o,n)=>{e==="debug"&&s.info(k.gray(o),n)}}}var g,G=x(()=>{"use strict";Q();g=Re()});var oe={};fe(oe,{get:()=>De,post:()=>v});async function v(e,t,r={}){f.get("access_token")&&(r.Authorization=`Bearer ${f.get("access_token")}`);let s=await fetch(re(e),{method:"POST",headers:{"Content-Type":t instanceof URLSearchParams?"application/x-www-form-urlencoded":"application/json",...r},body:t instanceof URLSearchParams?t:JSON.stringify(t)}).catch(o=>{g.error(`Fatal Error requesting API: ${o.message} (${o.cause.code})`),g.error("Please check your internet connection and try again, or retry later."),process.exit(1)});return se(s)}async function De(e,t={}){f.get("access_token")&&(t.Authorization=`Bearer ${f.get("access_token")}`);let r=await fetch(re(e),{headers:t,method:"GET"}).catch(s=>{g.error(`Fatal Error requesting API: ${s.message} (${s.cause.code})`),g.error("Please check your internet connection and try again, or retry later."),process.exit(1)});return se(r)}function re(e){let t=new URL(P.endsWith("/")?P:`${P}/`);return new URL(e,t)}async function se(e){let t=e.headers.get("content-type")?.startsWith("application/json")?await e.json():await e.text();return e.ok?{isSuccess:!0,isError:!1,status:e.status,statusText:e.statusText,data:t}:{isSuccess:!1,isError:!0,status:e.status,statusText:e.statusText,data:t}}var z=x(()=>{"use strict";G();b();F()});W();F();import{resolve as y}from"node:path";import{existsSync as
|
|
3
|
+
var me=Object.defineProperty;var x=(e,t)=>()=>(e&&(t=e(e=0)),t);var fe=(e,t)=>{for(var r in t)me(e,r,{get:t[r],enumerable:!0})};function D(){let e;if(process.env.npm_config_user_agent){let t=process.env.npm_config_user_agent.split(" ")[0];e=t.slice(0,t.lastIndexOf("/"))}return e||(console.log("Warning: could not detect package manager"),e="npm"),e}function q(e){return`[${e.error}]${e.error_description?`: ${e.error_description}`:""}`}var W=x(()=>{"use strict"});var J,dt,P,gt,X,Y,K,b=x(()=>{"use strict";J="upstart-cli",dt=process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID??"50000000-0000-0000-0000-000000000001",P=process.env.PUBLIC_UPSTART_API_BASE_URL??"https://api.upstart.gg",gt=process.env.PUBLIC_UPSTART_EDITOR_BASE_URL??"https://upstart.gg",X=10,Y="oauth/userinfo",K="v1/templates"});import ye from"conf";import C from"node:path";import he from"node:crypto";import R from"node:fs";import{fileURLToPath as Se}from"node:url";import Ee from"chalk";function V(){let e=f.get("access_token");if(!e){let t=D();throw new Error(`Access token not found. Please run ${Ee.cyan(`${t} run enpage:login`)} to authenticate.`)}return e}function we(){let e=Te;for(;e!==C.parse(e).root;){let t=C.join(e,"node_modules");if(R.existsSync(t))return t;e=C.dirname(e)}return null}function _e(){let e=we();if(!e)throw new Error("Could not find nearest node_modules directory.");let t=C.join(e,".enpage-tmp");R.existsSync(t)||R.mkdirSync(t,{recursive:!0,mode:448});let r=C.join(t,".enpage-key");if(!R.existsSync(r)){let o=he.randomBytes(32).toString("hex");return R.writeFileSync(r,o,{mode:384}),o}return R.readFileSync(r,"utf8")}var Te,Pe,f,F=x(()=>{"use strict";b();W();Te=Se(new URL(".",import.meta.url)),Pe=_e(),f=new ye({projectName:J,encryptionKey:Pe,clearInvalidConfig:!0})});var Z,Q=x(()=>{Z="0.0.94"});import{createLogger as be}from"vite";import k from"chalk";function Re(e,t,r=!1){let s=be(e==="debug"?"info":e,{prefix:"[upstart]",allowClearScreen:t});return r&&s.info(k.hex("#7270c6").bold(`\u{1F680} Upstart v${Z}
|
|
4
|
+
`)),{...s,success:(o,n)=>s.info(k.green(o),n),error:(o,n)=>s.error(k.red(o),n),warn:(o,n)=>s.warn(k.yellow(o),n),warnOnce:(o,n)=>s.warnOnce(k.yellow(o),n),debug:(o,n)=>{e==="debug"&&s.info(k.gray(o),n)}}}var g,G=x(()=>{"use strict";Q();g=Re()});var oe={};fe(oe,{get:()=>De,post:()=>v});async function v(e,t,r={}){f.get("access_token")&&(r.Authorization=`Bearer ${f.get("access_token")}`);let s=await fetch(re(e),{method:"POST",headers:{"Content-Type":t instanceof URLSearchParams?"application/x-www-form-urlencoded":"application/json",...r},body:t instanceof URLSearchParams?t:JSON.stringify(t)}).catch(o=>{g.error(`Fatal Error requesting API: ${o.message} (${o.cause.code})`),g.error("Please check your internet connection and try again, or retry later."),process.exit(1)});return se(s)}async function De(e,t={}){f.get("access_token")&&(t.Authorization=`Bearer ${f.get("access_token")}`);let r=await fetch(re(e),{headers:t,method:"GET"}).catch(s=>{g.error(`Fatal Error requesting API: ${s.message} (${s.cause.code})`),g.error("Please check your internet connection and try again, or retry later."),process.exit(1)});return se(r)}function re(e){let t=new URL(P.endsWith("/")?P:`${P}/`);return new URL(e,t)}async function se(e){let t=e.headers.get("content-type")?.startsWith("application/json")?await e.json():await e.text();return e.ok?{isSuccess:!0,isError:!1,status:e.status,statusText:e.statusText,data:t}:{isSuccess:!1,isError:!0,status:e.status,statusText:e.statusText,data:t}}var z=x(()=>{"use strict";G();b();F()});W();F();import{resolve as y}from"node:path";import{existsSync as j,readFileSync as it,writeFileSync as at}from"node:fs";import E from"chalk";b();G();import I from"node:path";import N from"node:fs";import Fe from"node:crypto";import Ge from"fast-glob";import ie from"node:http";import Be from"node:https";import{pipeline as Me}from"node:stream";import ne from"chalk";import ze from"form-data";import*as B from"node:fs";var ke=/[<>"|?*\n\r\t\f\x00-\x1F]/,Ae=/(?:^|\/)[*]{2}($|\/)/,$e=248,Le=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Oe=e=>typeof e=="string"&&e.length<=$e&&!ke.test(e),Ue=e=>e.split(/\r\n?|\n/);var Ce=e=>Le(e)&&Array.isArray(e.patterns)&&Array.isArray(e.sections);var M=(e,t={})=>{let r=t.path;if(Ce(e))return e;Oe(e)&&B.existsSync(e)&&(r=e,e=B.readFileSync(e,"utf8"));let s=Ue(e),o=new Map,n={sections:[],patterns:[]},c={name:"default",patterns:[]},i=null;for(let a of s){let p=a.trim();if(p.startsWith("#")){let[,u]=/^#+\s*(.*)\s*$/.exec(p)||[];if(i){o.delete(i.name),i.comment=i.comment?`${i.comment}
|
|
5
5
|
${p}`:p,i.name=u?`${i.name.trim()}
|
|
6
|
-
${u.trim()}`:i.name.trim(),o.set(i.name.toLowerCase().trim(),i);continue}c={name:u?.trim()||"",comment:p,patterns:[]},o.set(c.name.toLowerCase(),c),n.sections.push(c),i=c;continue}p!==""&&(c.patterns.push(p),n.patterns.push(p)),i=null}return(t.dedupe===!0||t.unique===!0)&&(n=ee(n,{...t,format:!1})),n.path=r,n.input=Buffer.from(e),n.format=a=>
|
|
6
|
+
${u.trim()}`:i.name.trim(),o.set(i.name.toLowerCase().trim(),i);continue}c={name:u?.trim()||"",comment:p,patterns:[]},o.set(c.name.toLowerCase(),c),n.sections.push(c),i=c;continue}p!==""&&(c.patterns.push(p),n.patterns.push(p)),i=null}return(t.dedupe===!0||t.unique===!0)&&(n=ee(n,{...t,format:!1})),n.path=r,n.input=Buffer.from(e),n.format=a=>je(n,{...t,...a}),n.dedupe=a=>ee(n,{...t,...a}),n.globs=a=>Ie(n,{path:r,...t,...a}),n};var ee=(e,t)=>{let r=M(e,{...t,dedupe:!1}),s=new Map,o={sections:[],patterns:[]},n;for(let c of r.sections){let{name:i="",comment:a,patterns:p}=c,u=i.trim().toLowerCase();for(let m of p)o.patterns.includes(m)||o.patterns.push(m);i&&s.has(u)?(n=s.get(u),n.patterns=[...n.patterns,...p]):(n={name:i,comment:a,patterns:p},o.sections.push(n),s.set(u,n))}for(let c of o.sections)c.patterns=[...new Set(c.patterns)];return o},ve=e=>{if(Ae.test(e))return e;let t=!1;return e.startsWith("/")?(e=e.slice(1),t=!0):e.slice(1,e.length-1).includes("/")&&(t=!0),e+=e.endsWith("/")?"**/":"/**",t?e:`**/${e}`},Ie=(e,t={})=>{let r=M(e,t),s=[],o=0,n=r.patterns.concat(t.ignore||[]).concat((t.unignore||[]).map(i=>i.startsWith("!")?i:`!${i}`)),c=(i,a)=>{let p=s[s.length-1],u=i?"unignore":"ignore";p&&p.type===u?p.patterns.includes(a)||p.patterns.push(a):(s.push({type:u,path:t.path||null,patterns:[a],index:o}),o++)};for(let i of n){let a="";i.startsWith("!")&&(i=i.slice(1),a="!"),c(a,i.startsWith("/")?i.slice(1):i),c(a,ve(i))}return s},Ne=(e={name:"",patterns:[]})=>{let t=[e.comment||""];return e.patterns?.length&&(t.push(e.patterns.join(`
|
|
7
7
|
`)),t.push("")),t.join(`
|
|
8
|
-
`)},
|
|
9
|
-
`)};var te=M;z();import We from"p-queue";import He from"ora";import{customAlphabet as qe}from"nanoid";var A=class extends Error{constructor(r,s,o){super(`${r}: ${s}`);this.error=r;this.error_description=s;this.filename=o;this.name="UploadError"}},Je={maxDataSize:12*1024*1024,retryAttempts:2,retryDelay:1e3},Xe=new ie.Agent({keepAlive:!0,maxSockets:10,keepAliveMsecs:3e3});async function Ye(e){let t=I.join(e,".gitignore"),s=
|
|
8
|
+
`)},je=(e,t={})=>{let r=M(e,t),s=t.formatSection||Ne,o=r.sections||r,n=[];for(let c of[].concat(o))n.push(s(c));return n.join(`
|
|
9
|
+
`)};var te=M;z();import We from"p-queue";import He from"ora";import{customAlphabet as qe}from"nanoid";var A=class extends Error{constructor(r,s,o){super(`${r}: ${s}`);this.error=r;this.error_description=s;this.filename=o;this.name="UploadError"}},Je={maxDataSize:12*1024*1024,retryAttempts:2,retryDelay:1e3},Xe=new ie.Agent({keepAlive:!0,maxSockets:10,keepAliveMsecs:3e3});async function Ye(e){let t=I.join(e,".gitignore"),s=N.existsSync(t)?te(N.readFileSync(t,"utf-8")).patterns:[];return Ge("**/*",{cwd:e,onlyFiles:!0,dot:!0,absolute:!0,ignore:["node_modules/**",".cache/**","**/.DS_Store",".gitignore",".env",".env.*",".git/**","dist/**",...s]})}async function Ke(e,t,r,s,o,n,c){let i=async a=>{try{return await Ve(e,t,r,s,o,n,c)}catch(p){if(a<c.retryAttempts)return g.warn(`Retrying upload for ${t} (attempt ${a+1})`),await new Promise(u=>setTimeout(u,c.retryDelay)),i(a+1);throw p}};return i(0)}async function Ve(e,t,r,s,o,n,c){return new Promise((i,a)=>{let p=N.statSync(e),u=I.basename(e),m=Date.now(),h=new ze({maxDataSize:c.maxDataSize}),$=N.createReadStream(e),L=0,w=l=>{L+=l.length};$.on("data",w),h.append("file",$,{filename:u,knownLength:p.size});let _={agent:Xe,method:"POST",headers:{authorization:`Bearer ${n}`,"x-upstart-template-file-path":t,"x-upstart-template-id":s,...h.getHeaders()}},T=(r.startsWith("https")?Be:ie).request(r,_,l=>{let S="";l.on("data",O=>{S+=O}),l.on("end",()=>{let O=Date.now(),ge={fileName:u,fileSize:p.size,uploadDuration:O-m,statusCode:l.statusCode??0,serverResponse:S};if(l.statusCode&&l.statusCode>=200&&l.statusCode<300)o.text=`Uploaded ${t}`,i(ge);else{let U;if(l.headers["content-type"]?.startsWith("application/json")){let H=JSON.parse(S);U=new A(H.error||"unknown_error",H.error_description||"Unknown error occurred",t)}else U=new A("unknown_error",S||"Unknown error occurred",t);o.fail(`Failed to upload ${t} [${U.error}] ${U.error_description}`),a(U)}})});T.on("error",l=>{a(new A("request_error",l.message,t))}),Me(h,T,l=>{l&&a(new A("pipeline_error",`Pipeline failed for ${u}: ${l.message}`,t))})})}function Qe(e,t,r){r.length>0?(g.error(ne.red(`Failed to upload ${r.length} files:`)),r.forEach(s=>{let o=s.reason;g.error(`- ${o.filename}: ${o.error_description} (${o.error})`)})):g.info(ne.green(`Uploaded ${t.length} files successfully for template ${e}.
|
|
10
10
|
`))}async function ae(e,t,r,s=!1,o={}){let n={...Je,...o},c=new We({concurrency:X}),i=await Ye(t),a=i.length,p={},u=et(),m=0;for(let d of i){let T=I.relative(t,d),l=await Ze(d);p[T]=l}s&&(g.info(`Dry run mode enabled. Skipping upload.
|
|
11
|
-
`),g.info("The following files would have been uploaded:"),i.forEach(d=>g.info(`- ${d}`)),process.exit(0));let h=He(`Uploading ${a} files...`).start(),$=i.map(d=>{let T=I.resolve(t,d),l=I.relative(t,d),S=`${P}/v1/templates/${e}/upload/${u}`;return c.add(async()=>{let O=await Ke(T,l,S,e,h,r,n);return m++,O})}),L=await Promise.allSettled($);h.stop();let w=L.filter(d=>d.status==="fulfilled"),_=L.filter(d=>d.status==="rejected");if(Qe(e,w.map(d=>d.value),_),!_.length&&w.length){let d=`${P}/v1/templates/${e}/upload/${u}/finalize`,l=await v(d,{signatures:p});if(l.isError)return g.error(`Failed to finalize upload: ${l.data.error_description} (${l.data.error})`),{filesCount:a,uploadedFiles:w.map(S=>S.value),failedFiles:[],success:!1}}return{filesCount:a,uploadedFiles:w.map(d=>d.value),failedFiles:_,success:_.length===0}}async function Ze(e){let t=await Fe.subtle.digest("SHA-1",
|
|
11
|
+
`),g.info("The following files would have been uploaded:"),i.forEach(d=>g.info(`- ${d}`)),process.exit(0));let h=He(`Uploading ${a} files...`).start(),$=i.map(d=>{let T=I.resolve(t,d),l=I.relative(t,d),S=`${P}/v1/templates/${e}/upload/${u}`;return c.add(async()=>{let O=await Ke(T,l,S,e,h,r,n);return m++,O})}),L=await Promise.allSettled($);h.stop();let w=L.filter(d=>d.status==="fulfilled"),_=L.filter(d=>d.status==="rejected");if(Qe(e,w.map(d=>d.value),_),!_.length&&w.length){let d=`${P}/v1/templates/${e}/upload/${u}/finalize`,l=await v(d,{signatures:p});if(l.isError)return g.error(`Failed to finalize upload: ${l.data.error_description} (${l.data.error})`),{filesCount:a,uploadedFiles:w.map(S=>S.value),failedFiles:[],success:!1}}return{filesCount:a,uploadedFiles:w.map(d=>d.value),failedFiles:_,success:_.length===0}}async function Ze(e){let t=await Fe.subtle.digest("SHA-1",N.readFileSync(e));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}function et(){let e=qe("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",5),t=new Date,r=t.getUTCFullYear(),s=(t.getUTCMonth()+1).toString().padStart(2,"0"),o=t.getUTCDate().toString().padStart(2,"0"),n=t.getUTCHours().toString().padStart(2,"0"),c=t.getUTCMinutes().toString().padStart(2,"0"),i=t.getUTCSeconds().toString().padStart(2,"0");return`${r}${s}${o}${n}${c}${i}_${e()}`}z();b();import de from"node:path";G();import tt from"node:fs";import{readFile as rt}from"node:fs/promises";import st from"fast-glob";import{basename as ce,dirname as ot,extname as nt}from"node:path";async function pe(e,t=g){tt.existsSync(e)||(t.error(`\u{1F534} No enpage.config.js found!
|
|
12
12
|
Your project must have an enpage.config.js file in the root directory.
|
|
13
13
|
|
|
14
14
|
`),process.exit(1));let r=await import(e),s=ot(e),o={},n=await st(["README.enpage.md","README.enpage.*.md"],{cwd:s,onlyFiles:!0,absolute:!0,caseSensitiveMatch:!1});for(let c of n){let i=ce(c,".md"),a=nt(i),p=(a===".enpage"?"en":a.substring(1)).toLowerCase();t.debug(`Found template readme file (${p}): ${ce(c)}`),o[p]=await rt(c,"utf-8")}return r.manifest&&(r.manifest.readme=o),r}function le(e,t){for(let r in e.datasources)if((e.datasources[r].provider==="json-object"||e.datasources[r].provider==="json-array")&&!e.datasources[r].sampleData)throw t.error(`\u{1F534} Error: Datasource "${r}" is missing sample data - nothing will be rendered during development! Please check your enpage.config.js file and add a "sampleData" key to your ${r} datasource.`),new Error(`Missing sample data for datasource "${r}"`);return e}b();F();async function ue(e=!1){let t=f.get("access_token"),r=f.get("expires_at");if(!t)return!1;if(r&&r<Date.now())return console.log("Seems like your token expired..."),!1;if(!e)return!0;let{get:s}=await Promise.resolve().then(()=>(z(),oe)),{isSuccess:o}=await s(Y);return o}async function hr({options:e,args:t,logger:r}){if(!await ue(!0)){let m=D();r.error(` ${E.redBright("Error")}: User token not found. Please run ${E.cyan(`${m} run enpage:login`)} to authenticate or set the ${E.cyan("ENPAGE_API_TOKEN")} environment variable.
|
|
15
|
-
`),process.exit(1)}let s=t.length?de.isAbsolute(t[0])?t[0]:y(process.cwd(),t[0]):process.cwd();
|
|
16
|
-
`),process.exit(1));let o=t.length>1?de.isAbsolute(t[1])?t[1]:y(process.cwd(),t[1]):y(s,"dist");
|
|
15
|
+
`),process.exit(1)}let s=t.length?de.isAbsolute(t[0])?t[0]:y(process.cwd(),t[0]):process.cwd();j(s)||(r.error(` Template directory not found: ${s}. Aborting.
|
|
16
|
+
`),process.exit(1));let o=t.length>1?de.isAbsolute(t[1])?t[1]:y(process.cwd(),t[1]):y(s,"dist");j(o)||(r.error(` Dist directory not found: ${o}.
|
|
17
17
|
Please run 'build' before publishing. Aborting.
|
|
18
|
-
`),process.exit(1)),
|
|
18
|
+
`),process.exit(1)),j(y(s,"enpage.config.js"))||(r.error(` ${E.redBright("Error")}: file enpage.config.js not found in ${s}. Aborting.
|
|
19
19
|
`),process.exit(1));let n=await pe(y(s,"enpage.config.js"),r);le(n,r);let c=V(),i=ct(s);i||(r.error(` ${E.redBright("Error")}: package.json file not found in ${s}. Aborting.
|
|
20
20
|
`),process.exit(1));let a=await pt(i);if(a||(r.error(` ${E.redBright("Error")}: cannot read/parse package.json file in ${s}. Aborting.
|
|
21
21
|
`),process.exit(1)),!a.enpage?.id){let{data:m,isError:h,status:$}=await v(K,{manifest:n.manifest});h&&(r.error(` ${E.redBright("Error")}: Cannot register template: ${q(m)}
|
|
@@ -24,7 +24,7 @@ Your project must have an enpage.config.js file in the root directory.
|
|
|
24
24
|
`),(await ae(p,s,c,e.dryRun)).success||(r.error(`
|
|
25
25
|
Upload failed. See details above.
|
|
26
26
|
`),process.exit(1)),r.success(`Template ${p} published.
|
|
27
|
-
`)}function ct(e){return
|
|
27
|
+
`)}function ct(e){return j(y(e,"package.json"))?y(e,"package.json"):j(y(e,"template-package.json"))?y(e,"template-package.json"):!1}function pt(e){try{return JSON.parse(it(e,"utf-8"))}catch{return null}}export{hr as publish};
|
|
28
28
|
/*!
|
|
29
29
|
* parse-gitignore <https://github.com/jonschlinkert/parse-gitignore>
|
|
30
30
|
* Copyright (c) 2015-present, Jon Schlinkert.
|