@upstart.gg/sdk 0.0.92 → 0.0.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/node/cli/api.js +2 -1
  2. package/dist/node/cli/api.js.map +1 -0
  3. package/dist/node/cli/commands/build/cmd-build.js +1 -0
  4. package/dist/node/cli/commands/build/cmd-build.js.map +1 -0
  5. package/dist/node/cli/commands/login/cmd-login.js +2 -1
  6. package/dist/node/cli/commands/login/cmd-login.js.map +1 -0
  7. package/dist/node/cli/commands/logout/cmd-logout.js +1 -0
  8. package/dist/node/cli/commands/logout/cmd-logout.js.map +1 -0
  9. package/dist/node/cli/commands/publish/cmd-publish.js +12 -11
  10. package/dist/node/cli/commands/publish/cmd-publish.js.map +1 -0
  11. package/dist/node/cli/commands/publish/parse-gitignore.js +1 -0
  12. package/dist/node/cli/commands/publish/parse-gitignore.js.map +1 -0
  13. package/dist/node/cli/commands/publish/uploader.js +2 -1
  14. package/dist/node/cli/commands/publish/uploader.js.map +1 -0
  15. package/dist/node/cli/constants.js +1 -0
  16. package/dist/node/cli/constants.js.map +1 -0
  17. package/dist/node/cli/is-logged-in.js +2 -1
  18. package/dist/node/cli/is-logged-in.js.map +1 -0
  19. package/dist/node/cli/program.js +3 -2
  20. package/dist/node/cli/program.js.map +1 -0
  21. package/dist/node/cli/store.js +1 -0
  22. package/dist/node/cli/store.js.map +1 -0
  23. package/dist/node/cli/types.js +1 -0
  24. package/dist/node/cli/types.js.map +1 -0
  25. package/dist/node/cli/utils.js +1 -0
  26. package/dist/node/cli/utils.js.map +1 -0
  27. package/dist/node/shared/config.d.ts.map +1 -1
  28. package/dist/node/shared/config.js +5 -4
  29. package/dist/node/shared/config.js.map +1 -0
  30. package/dist/node/shared/logger.js +2 -1
  31. package/dist/node/shared/logger.js.map +1 -0
  32. package/dist/shared/bricks/manifests/all-manifests.js +1 -1
  33. package/dist/shared/bricks/manifests/button.manifest.js +1 -1
  34. package/dist/shared/bricks/manifests/card.manifest.js +1 -1
  35. package/dist/shared/bricks/manifests/container.manifest.js +1 -1
  36. package/dist/shared/bricks/manifests/header.manifest.js +1 -1
  37. package/dist/shared/bricks/manifests/hero.manifest.js +1 -1
  38. package/dist/shared/bricks/manifests/image.manifest.js +1 -1
  39. package/dist/shared/bricks/manifests/images-gallery.manifest.js +1 -1
  40. package/dist/shared/bricks/manifests/text.manifest.js +1 -1
  41. package/dist/shared/bricks/props/_docs-common-styles.js +1 -1
  42. package/dist/shared/bricks.js +1 -1
  43. package/dist/shared/{chunk-GDLXGNMG.js → chunk-4FLI7C3B.js} +1 -1
  44. package/dist/shared/chunk-6LDLGZUM.js +3 -0
  45. package/dist/shared/{chunk-TQ23UATQ.js → chunk-6MEWEGNA.js} +1 -1
  46. package/dist/shared/{chunk-HW5TY2QW.js → chunk-BXEKJXEP.js} +1 -1
  47. package/dist/shared/{chunk-EFJQECVB.js → chunk-ERSFH7XA.js} +1 -1
  48. package/dist/shared/{chunk-XEQ2XZLQ.js → chunk-IKAMZM4I.js} +1 -1
  49. package/dist/shared/{chunk-NFU5BF6G.js → chunk-QCQH5WLN.js} +1 -1
  50. package/dist/shared/{chunk-CP2GSNLX.js → chunk-RHRJYPU3.js} +1 -1
  51. package/dist/shared/chunk-S64XUCWM.js +3 -0
  52. package/dist/shared/{chunk-NUJO6EYU.js → chunk-SWGSHUTE.js} +1 -1
  53. package/dist/shared/{chunk-6I4PY5WS.js → chunk-U5WW6K7W.js} +1 -1
  54. package/dist/shared/{chunk-QRBMK5UX.js → chunk-V2NS45PF.js} +1 -1
  55. package/dist/shared/chunk-YY6DANZF.js +3 -0
  56. package/dist/shared/datasources/external/json/schema.d.ts +6 -0
  57. package/dist/shared/datasources/external/json/schema.d.ts.map +1 -0
  58. package/dist/shared/datasources/schemas.d.ts +640 -16
  59. package/dist/shared/datasources/schemas.d.ts.map +1 -1
  60. package/dist/shared/datasources/schemas.js +1 -1
  61. package/dist/shared/datasources/types.d.ts +1316 -40
  62. package/dist/shared/datasources/types.d.ts.map +1 -1
  63. package/dist/shared/datasources/types.js +1 -1
  64. package/dist/shared/datasources.d.ts +1 -53
  65. package/dist/shared/datasources.d.ts.map +1 -1
  66. package/dist/shared/datasources.js +1 -1
  67. package/dist/shared/page.d.ts +1914 -12
  68. package/dist/shared/page.d.ts.map +1 -1
  69. package/dist/shared/page.js +1 -1
  70. package/dist/shared/template.d.ts +637 -4
  71. package/dist/shared/template.d.ts.map +1 -1
  72. package/dist/shared/template.js +1 -1
  73. package/package.json +3 -3
  74. package/dist/shared/chunk-7XRTVY2Z.js +0 -3
  75. package/dist/shared/chunk-HC4I5B3L.js +0 -3
  76. package/dist/shared/chunk-YLAVY3GS.js +0 -3
@@ -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.92";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}
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.93";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:
@@ -9,3 +9,4 @@ Please visit the following URL to login:
9
9
  Waiting for login...
10
10
  `));let d=await A(o,e);d||(e.error("Login failed. Please try again."),process.exit(1)),p.set({...d,...d.expires_in?{expires_at:Date.now()+d.expires_in*1e3}:{}}),e.info(`Login successful!
11
11
  `),process.exitCode=0}export{de as login,A as pollForLogin};
12
+ //# sourceMappingURL=cmd-login.js.map
@@ -0,0 +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,EAAGC,CAAO,EAC7F,MAAO,CAACD,EAAiBC,IAAyBJ,EAAO,MAAML,EAAM,IAAIQ,CAAO,EAAGC,CAAO,EAC1F,KAAM,CAACD,EAAiBC,IAAyBJ,EAAO,KAAKL,E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T_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"]}
@@ -2,3 +2,4 @@
2
2
 
3
3
  var i="upstart-cli";var d=process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID??"50000000-0000-0000-0000-000000000001",I=process.env.PUBLIC_UPSTART_API_BASE_URL??"https://api.upstart.gg",O=process.env.PUBLIC_UPSTART_EDITOR_BASE_URL??"https://upstart.gg";import p from"conf";import n from"node:path";import _ from"node:crypto";import e from"node:fs";import{fileURLToPath as a}from"node:url";import U from"chalk";var m=a(new URL(".",import.meta.url)),u=f(),c=new p({projectName:i,encryptionKey:u,clearInvalidConfig:!0});function E(){let o=m;for(;o!==n.parse(o).root;){let t=n.join(o,"node_modules");if(e.existsSync(t))return t;o=n.dirname(o)}return null}function f(){let o=E();if(!o)throw new Error("Could not find nearest node_modules directory.");let t=n.join(o,".enpage-tmp");e.existsSync(t)||e.mkdirSync(t,{recursive:!0,mode:448});let r=n.join(t,".enpage-key");if(!e.existsSync(r)){let s=_.randomBytes(32).toString("hex");return e.writeFileSync(r,s,{mode:384}),s}return e.readFileSync(r,"utf8")}async function h({options:o,logger:t}){t.info("Logging out fom Enpage..."),c.clear(),t.info(`Done.
4
4
  `),process.exit(0)}export{h as logout};
5
+ //# sourceMappingURL=cmd-logout.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/node/cli/constants.ts","../../../../../src/node/cli/store.ts","../../../../../src/node/cli/commands/logout/cmd-logout.ts"],"sourcesContent":["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 type { CommandArgOpts, CommonOptions } from \"../../types\";\nimport { accessStore } from \"../../store\";\n\nexport async function logout({ options, logger }: CommandArgOpts<CommonOptions>) {\n logger.info(`Logging out fom Enpage...`);\n\n accessStore.clear();\n\n logger.info(\"Done.\\n\");\n process.exit(0);\n}\n"],"mappings":";;AAAO,IAAMA,EAAmB,cAEzB,IAAMC,EACX,QAAQ,IAAI,gCAAkC,uCAEnCC,EAAe,QAAQ,IAAI,6BAA+B,yBAC1DC,EAAkB,QAAQ,IAAI,gCAAkC,qBCJ7E,OAAOC,MAAU,OACjB,OAAOC,MAAU,YACjB,OAAOC,MAAY,cACnB,OAAOC,MAAQ,UACf,OAAS,iBAAAC,MAAqB,WAE9B,OAAOC,MAAW,QAElB,IAAMC,EAAYC,EAAc,IAAI,IAAI,IAAK,YAAY,GAAG,CAAC,EACvDC,EAAMC,EAAO,EACbC,EAAc,IAAIC,EAAuB,CAC7C,YAAaC,EACb,cAAeJ,EACf,mBAAoB,EACtB,CAAC,EAgBD,SAASK,GAAwC,CAC/C,IAAIC,EAAaC,EACjB,KAAOD,IAAeE,EAAK,MAAMF,CAAU,EAAE,MAAM,CACjD,IAAMG,EAAkBD,EAAK,KAAKF,EAAY,cAAc,EAC5D,GAAII,EAAG,WAAWD,CAAe,EAC/B,OAAOA,EAETH,EAAaE,EAAK,QAAQF,CAAU,CACtC,CACA,OAAO,IACT,CAEA,SAASK,GAAS,CAChB,IAAMF,EAAkBJ,EAAuB,EAC/C,GAAI,CAACI,EACH,MAAM,IAAI,MAAM,gDAAgD,EAElE,IAAMG,EAAoBJ,EAAK,KAAKC,EAAiB,aAAa,EAC7DC,EAAG,WAAWE,CAAiB,GAClCF,EAAG,UAAUE,EAAmB,CAAE,UAAW,GAAM,KAAM,GAAM,CAAC,EAElE,IAAMC,EAAUL,EAAK,KAAKI,EAAmB,aAAa,EAC1D,GAAI,CAACF,EAAG,WAAWG,CAAO,EAAG,CAC3B,IAAMC,EAAMC,EAAO,YAAY,EAAE,EAAE,SAAS,KAAK,EACjD,OAAAL,EAAG,cAAcG,EAASC,EAAK,CAAE,KAAM,GAAM,CAAC,EACvCA,CACT,CAEA,OADYJ,EAAG,aAAaG,EAAS,MAAM,CAE7C,CC1DA,eAAsBG,EAAO,CAAE,QAAAC,EAAS,OAAAC,CAAO,EAAkC,CAC/EA,EAAO,KAAK,2BAA2B,EAEvCC,EAAY,MAAM,EAElBD,EAAO,KAAK;AAAA,CAAS,EACrB,QAAQ,KAAK,CAAC,CAChB","names":["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","logout","options","logger","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.92"});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}
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.93"});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 N,readFileSync as it,writeFileSync as at}from"node:fs";import E from"chalk";b();G();import I from"node:path";import j 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=>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(`
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=>Ne(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},je=(e={name:"",patterns:[]})=>{let t=[e.comment||""];return e.patterns?.length&&(t.push(e.patterns.join(`
7
7
  `)),t.push("")),t.join(`
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}.
8
+ `)},Ne=(e,t={})=>{let r=M(e,t),s=t.formatSection||je,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=j.existsSync(t)?te(j.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=j.statSync(e),u=I.basename(e),m=Date.now(),h=new ze({maxDataSize:c.maxDataSize}),$=j.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",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!
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",j.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
- `),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"&&!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();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}.
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();N(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");N(o)||(r.error(` Dist directory not found: ${o}.
17
17
  Please run 'build' before publishing. Aborting.
18
- `),process.exit(1)),j(y(s,"enpage.config.js"))||(r.error(` ${E.redBright("Error")}: file enpage.config.js not found in ${s}. Aborting.
18
+ `),process.exit(1)),N(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 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};
27
+ `)}function ct(e){return N(y(e,"package.json"))?y(e,"package.json"):N(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.
@@ -32,3 +32,4 @@ Upload failed. See details above.
32
32
  *
33
33
  * Converted to typescript by Matthias E. <matthias@upstart.gg>
34
34
  */
35
+ //# sourceMappingURL=cmd-publish.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/node/cli/utils.ts","../../../../../src/node/cli/constants.ts","../../../../../src/node/cli/store.ts","../../../../../package.json","../../../../../src/node/shared/logger.ts","../../../../../src/node/cli/api.ts","../../../../../src/node/cli/commands/publish/cmd-publish.ts","../../../../../src/node/cli/commands/publish/uploader.ts","../../../../../src/node/cli/commands/publish/parse-gitignore.ts","../../../../../src/node/shared/config.ts","../../../../../src/node/cli/is-logged-in.ts"],"sourcesContent":["export function getPackageManager() {\n // Detect package manager\n let packageManager: string | undefined;\n if (process.env.npm_config_user_agent) {\n const pmPart = process.env.npm_config_user_agent.split(\" \")[0];\n packageManager = pmPart.slice(0, pmPart.lastIndexOf(\"/\"));\n }\n\n // Display message\n if (!packageManager) {\n console.log(\"Warning: could not detect package manager\");\n packageManager = \"npm\";\n }\n\n return packageManager;\n}\n\nexport function formatAPIError(error: { error: string; error_description?: string }) {\n return `[${error.error}]${error.error_description ? `: ${error.error_description}` : \"\"}`;\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","{\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 {\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","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","import { resolve } from \"node:path\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport chalk from \"chalk\";\nimport type { CommandArgOpts } from \"../../types\";\nimport { formatAPIError, getPackageManager } from \"../../utils\";\nimport { getTokenOrThrow } from \"../../store\";\nimport { uploadTemplate } from \"./uploader\";\nimport path from \"node:path\";\nimport { post } from \"../../api\";\nimport { API_ENDPOINT_REGISTER_TEMPLATE } from \"../../constants\";\nimport { loadConfigFromJsFile, validateTemplateConfig } from \"~/node/shared/config\";\nimport { isLoggedIn } from \"../../is-logged-in\";\n\nexport async function publish({ options, args, logger }: CommandArgOpts) {\n // check if user is logged in\n if (!(await isLoggedIn(true))) {\n const pkgCmd = getPackageManager();\n logger.error(\n ` ${chalk.redBright(\"Error\")}: User token not found. Please run ${chalk.cyan(`${pkgCmd} run enpage:login`)} to authenticate or set the ${chalk.cyan(\"ENPAGE_API_TOKEN\")} environment variable.\\n`,\n );\n process.exit(1);\n }\n\n const templateDir = args.length\n ? path.isAbsolute(args[0])\n ? args[0]\n : resolve(process.cwd(), args[0])\n : process.cwd();\n\n if (!existsSync(templateDir)) {\n logger.error(` Template directory not found: ${templateDir}. Aborting.\\n`);\n process.exit(1);\n }\n\n const distDir =\n args.length > 1\n ? path.isAbsolute(args[1])\n ? args[1]\n : resolve(process.cwd(), args[1])\n : resolve(templateDir, \"dist\");\n\n if (!existsSync(distDir)) {\n logger.error(\n ` Dist directory not found: ${distDir}.\\n Please run 'build' before publishing. Aborting.\\n`,\n );\n process.exit(1);\n }\n\n // check if enpage.config.js and package.json exist in the current directory\n // if not, exit with an error\n if (!existsSync(resolve(templateDir, \"enpage.config.js\"))) {\n logger.error(\n ` ${chalk.redBright(\"Error\")}: file enpage.config.js not found in ${templateDir}. Aborting.\\n`,\n );\n process.exit(1);\n }\n\n // load manifest from both enpage.config.js and package.json\n // manifest.json is used to store the template ID for future updates\n const config = await loadConfigFromJsFile(resolve(templateDir, \"enpage.config.js\"), logger);\n\n validateTemplateConfig(config, logger);\n\n const token = getTokenOrThrow();\n const pkgLocation = getPackageLocation(templateDir);\n\n if (!pkgLocation) {\n logger.error(` ${chalk.redBright(\"Error\")}: package.json file not found in ${templateDir}. Aborting.\\n`);\n process.exit(1);\n }\n\n // load package.json to get the template ID (if it exists)\n const pkg = await getPackageJsonContents(pkgLocation);\n\n if (!pkg) {\n logger.error(\n ` ${chalk.redBright(\"Error\")}: cannot read/parse package.json file in ${templateDir}. Aborting.\\n`,\n );\n process.exit(1);\n }\n\n if (!pkg.enpage?.id) {\n // call API to create a new template\n const { data, isError, status } = await post<{ success: true; template: { id: string } }>(\n API_ENDPOINT_REGISTER_TEMPLATE,\n {\n manifest: config.manifest,\n },\n );\n if (isError) {\n logger.error(` ${chalk.redBright(\"Error\")}: Cannot register template: ${formatAPIError(data)}\\n`);\n process.exit(1);\n }\n pkg.enpage ??= {};\n pkg.enpage.id = data.template.id;\n\n // save the template ID to package.json\n try {\n if (!options.dryRun) writeFileSync(pkgLocation, JSON.stringify(pkg, null, 2));\n } catch (e) {\n logger.error(\n ` ${chalk.redBright(\"Error\")}: Cannot update template id in package.json file located in ${templateDir}. Aborting.\\n`,\n );\n process.exit(1);\n }\n }\n\n const templateId = pkg.enpage.id;\n\n // submit template to Enpage\n logger.info(`Submitting template to Enpage...\\n`);\n\n const uploadResults = await uploadTemplate(templateId, templateDir, token, options.dryRun);\n\n if (!uploadResults.success) {\n logger.error(\"\\nUpload failed. See details above.\\n\");\n process.exit(1);\n }\n\n logger.success(`Template ${templateId} published.\\n`);\n}\n\nfunction getPackageLocation(templateDir: string) {\n return existsSync(resolve(templateDir, \"package.json\"))\n ? resolve(templateDir, \"package.json\")\n : existsSync(resolve(templateDir, \"template-package.json\"))\n ? resolve(templateDir, \"template-package.json\")\n : false;\n}\n\nfunction getPackageJsonContents(pkgJsonPath: string) {\n try {\n return JSON.parse(readFileSync(pkgJsonPath, \"utf-8\"));\n } catch (e) {\n return null;\n }\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport crypto from \"node:crypto\";\nimport fg from \"fast-glob\";\nimport { API_BASE_URL, DEFAULT_UPLOAD_MAX_CONCURRENCY } from \"../../constants\";\nimport http from \"node:http\";\nimport https from \"node:https\";\nimport { pipeline } from \"node:stream\";\nimport type { GenericApiError } from \"../../types\";\nimport { logger } from \"~/node/shared/logger\";\nimport chalk from \"chalk\";\nimport FormData from \"form-data\";\nimport parseGitIgnore from \"./parse-gitignore\";\nimport PQueue from \"p-queue\";\nimport ora from \"ora\";\nimport { customAlphabet } from \"nanoid\";\nimport { post } from \"../../api\";\n\ninterface UploadStats {\n fileName: string;\n fileSize: number;\n uploadDuration: number;\n statusCode: number;\n serverResponse: string;\n}\n\nclass UploadError extends Error implements GenericApiError {\n constructor(\n public error: string,\n public error_description: string,\n public filename: string,\n ) {\n super(`${error}: ${error_description}`);\n this.name = \"UploadError\";\n }\n}\n\ninterface UploadConfig {\n maxDataSize: number;\n retryAttempts: number;\n retryDelay: number;\n}\n\nconst defaultConfig: UploadConfig = {\n maxDataSize: 12 * 1024 * 1024, // 12MB\n retryAttempts: 2,\n retryDelay: 1000,\n};\n\nconst agent = new http.Agent({\n keepAlive: true,\n maxSockets: 10,\n keepAliveMsecs: 3000, // Keep connections open for 3 seconds\n});\n\nasync function discoverFiles(templateDir: string): Promise<string[]> {\n const gitignore = path.join(templateDir, \".gitignore\");\n const gitignoreExists = fs.existsSync(gitignore);\n const gitignored = gitignoreExists ? parseGitIgnore(fs.readFileSync(gitignore, \"utf-8\")).patterns : [];\n\n return fg(\"**/*\", {\n cwd: templateDir,\n onlyFiles: true,\n dot: true,\n absolute: true,\n ignore: [\n \"node_modules/**\",\n \".cache/**\",\n \"**/.DS_Store\",\n \".gitignore\",\n \".env\",\n \".env.*\",\n \".git/**\",\n \"dist/**\",\n ...gitignored,\n ],\n });\n}\n\nasync function uploadFile(\n filePath: string,\n relativePath: string,\n uploadUrl: string,\n templateId: string,\n spinner: ReturnType<typeof ora>,\n token: string,\n config: UploadConfig,\n): Promise<UploadStats> {\n const uploadWithRetry = async (attempt: number): Promise<UploadStats> => {\n try {\n return await performUpload(filePath, relativePath, uploadUrl, templateId, spinner, token, config);\n } catch (error) {\n if (attempt < config.retryAttempts) {\n logger.warn(`Retrying upload for ${relativePath} (attempt ${attempt + 1})`);\n await new Promise((resolve) => setTimeout(resolve, config.retryDelay));\n return uploadWithRetry(attempt + 1);\n }\n throw error;\n }\n };\n\n return uploadWithRetry(0);\n}\n\nasync function performUpload(\n filePath: string,\n relativePath: string,\n uploadUrl: string,\n templateId: string,\n spinner: ReturnType<typeof ora>,\n token: string,\n config: UploadConfig,\n): Promise<UploadStats> {\n return new Promise<UploadStats>((resolve, reject) => {\n const stats = fs.statSync(filePath);\n const fileName = path.basename(filePath);\n const startTime = Date.now();\n\n const form = new FormData({\n maxDataSize: config.maxDataSize,\n });\n const fileStream = fs.createReadStream(filePath);\n let totalUploaded = 0;\n\n const updateProgress = (chunk: Buffer | string) => {\n totalUploaded += chunk.length;\n };\n\n fileStream.on(\"data\", updateProgress);\n form.append(\"file\", fileStream, {\n filename: fileName,\n knownLength: stats.size,\n });\n\n const options: https.RequestOptions = {\n agent,\n method: \"POST\",\n headers: {\n authorization: `Bearer ${token}`,\n \"x-upstart-template-file-path\": relativePath,\n \"x-upstart-template-id\": templateId,\n ...form.getHeaders(),\n },\n };\n\n const protocol = uploadUrl.startsWith(\"https\") ? https : http;\n const req = protocol.request(uploadUrl, options, (res) => {\n let responseBody = \"\";\n res.on(\"data\", (chunk) => {\n responseBody += chunk;\n });\n\n res.on(\"end\", () => {\n const endTime = Date.now();\n const uploadStats: UploadStats = {\n fileName,\n fileSize: stats.size,\n uploadDuration: endTime - startTime,\n statusCode: res.statusCode ?? 0,\n serverResponse: responseBody,\n };\n\n if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {\n spinner.text = `Uploaded ${relativePath}`;\n resolve(uploadStats);\n } else {\n let errorObject: UploadError;\n if (res.headers[\"content-type\"]?.startsWith(\"application/json\")) {\n const parsedError = JSON.parse(responseBody);\n errorObject = new UploadError(\n parsedError.error || \"unknown_error\",\n parsedError.error_description || \"Unknown error occurred\",\n relativePath,\n );\n } else {\n errorObject = new UploadError(\n \"unknown_error\",\n responseBody || \"Unknown error occurred\",\n relativePath,\n );\n }\n\n spinner.fail(\n `Failed to upload ${relativePath} [${errorObject.error}] ${errorObject.error_description}`,\n );\n\n reject(errorObject);\n }\n });\n });\n\n req.on(\"error\", (error) => {\n reject(new UploadError(\"request_error\", error.message, relativePath));\n });\n\n pipeline(form, req, (err) => {\n if (err) {\n reject(\n new UploadError(\"pipeline_error\", `Pipeline failed for ${fileName}: ${err.message}`, relativePath),\n );\n }\n });\n });\n}\n\nfunction reportUploadStatistics(\n templateId: string,\n uploadedFiles: UploadStats[],\n failedFiles: PromiseRejectedResult[],\n) {\n if (failedFiles.length > 0) {\n logger.error(chalk.red(`Failed to upload ${failedFiles.length} files:`));\n failedFiles.forEach((failure) => {\n const error = failure.reason as UploadError;\n logger.error(`- ${error.filename}: ${error.error_description} (${error.error})`);\n });\n } else {\n logger.info(\n chalk.green(`Uploaded ${uploadedFiles.length} files successfully for template ${templateId}.\\n`),\n );\n }\n}\n\nexport async function uploadTemplate(\n templateId: string,\n templateDir: string,\n token: string,\n dryRun = false,\n config: Partial<UploadConfig> = {},\n) {\n const fullConfig = { ...defaultConfig, ...config };\n const queue = new PQueue({ concurrency: DEFAULT_UPLOAD_MAX_CONCURRENCY });\n const files = await discoverFiles(templateDir);\n const filesCount = files.length;\n const signatures: Record<string, string> = {};\n // generate a upload id\n const uploadId = generateUploadId();\n let completedUploads = 0;\n\n // compute signatures\n for (const file of files) {\n const relativePath = path.relative(templateDir, file);\n const md5 = await sha1sum(file);\n signatures[relativePath] = md5;\n }\n\n if (dryRun) {\n logger.info(\"Dry run mode enabled. Skipping upload.\\n\");\n logger.info(\"The following files would have been uploaded:\");\n files.forEach((file) => logger.info(`- ${file}`));\n process.exit(0);\n }\n\n const spinner = ora(`Uploading ${filesCount} files...`).start();\n\n // upload files\n const uploadPromises = files.map((file) => {\n const fullPath = path.resolve(templateDir, file);\n const relativePath = path.relative(templateDir, file);\n const url = `${API_BASE_URL}/v1/templates/${templateId}/upload/${uploadId}`;\n return queue.add(async () => {\n const result = await uploadFile(fullPath, relativePath, url, templateId, spinner, token, fullConfig);\n completedUploads++;\n return result;\n });\n });\n\n const results = await Promise.allSettled(uploadPromises);\n spinner.stop();\n\n const uploadedFiles = results.filter(\n (result): result is PromiseFulfilledResult<UploadStats> => result.status === \"fulfilled\",\n );\n\n const failedFiles = results.filter(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n\n reportUploadStatistics(\n templateId,\n uploadedFiles.map((r) => r.value),\n failedFiles,\n );\n\n // finalize upload\n if (!failedFiles.length && uploadedFiles.length) {\n const finalizeUrl = `${API_BASE_URL}/v1/templates/${templateId}/upload/${uploadId}/finalize`;\n const finalizePayload = {\n signatures,\n };\n\n const finalizeResponse = await post(finalizeUrl, finalizePayload);\n\n if (finalizeResponse.isError) {\n logger.error(\n `Failed to finalize upload: ${finalizeResponse.data.error_description} (${finalizeResponse.data.error})`,\n );\n return {\n filesCount,\n uploadedFiles: uploadedFiles.map((r) => r.value),\n failedFiles: [],\n success: false,\n };\n }\n }\n\n return {\n filesCount,\n uploadedFiles: uploadedFiles.map((r) => r.value),\n failedFiles,\n success: failedFiles.length === 0,\n };\n}\n\nasync function sha1sum(filePath: string): Promise<string> {\n const hash = await crypto.subtle.digest(\"SHA-1\", fs.readFileSync(filePath));\n // convert arrayBuffer to hex\n return Array.from(new Uint8Array(hash))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nfunction generateUploadId(): string {\n const randomId = customAlphabet(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\", 5);\n const now = new Date();\n const year = now.getUTCFullYear();\n const month = (now.getUTCMonth() + 1).toString().padStart(2, \"0\");\n const day = now.getUTCDate().toString().padStart(2, \"0\");\n const hours = now.getUTCHours().toString().padStart(2, \"0\");\n const minutes = now.getUTCMinutes().toString().padStart(2, \"0\");\n const seconds = now.getUTCSeconds().toString().padStart(2, \"0\");\n return `${year}${month}${day}${hours}${minutes}${seconds}_${randomId()}`;\n}\n","/*!\n * parse-gitignore <https://github.com/jonschlinkert/parse-gitignore>\n * Copyright (c) 2015-present, Jon Schlinkert.\n * Released under the MIT License.\n *\n * Converted to typescript by Matthias E. <matthias@upstart.gg>\n */\n\nimport * as fs from \"node:fs\";\n\n// eslint-disable-next-line no-control-regex\nconst INVALID_PATH_CHARS_REGEX = /[<>\"|?*\\n\\r\\t\\f\\x00-\\x1F]/;\nconst GLOBSTAR_REGEX = /(?:^|\\/)[*]{2}($|\\/)/;\nconst MAX_PATH_LENGTH = 260 - 12;\n\ninterface ParseOptions {\n path?: string;\n dedupe?: boolean;\n unique?: boolean;\n ignore?: string[];\n unignore?: string[];\n format?: boolean;\n formatSection?: (section: Section) => string;\n}\n\ninterface Section {\n name: string;\n comment?: string;\n patterns: string[];\n}\n\ninterface ParsedGitignore {\n sections: Section[];\n patterns: string[];\n path?: string;\n input: Buffer;\n format: (opts?: ParseOptions) => string;\n dedupe: (opts?: ParseOptions) => ParsedGitignore;\n globs: (opts?: ParseOptions) => GlobResult[];\n}\n\ninterface GlobResult {\n type: \"ignore\" | \"unignore\";\n path: string | null;\n patterns: string[];\n index: number;\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n v !== null && typeof v === \"object\" && !Array.isArray(v);\n\nconst isValidPath = (input: unknown): input is string =>\n typeof input === \"string\" && input.length <= MAX_PATH_LENGTH && !INVALID_PATH_CHARS_REGEX.test(input);\n\nconst split = (str: string): string[] => str.split(/\\r\\n?|\\n/);\nconst isComment = (str: string): boolean => str.startsWith(\"#\");\nconst isParsed = (input: unknown): input is ParsedGitignore =>\n isObject(input) && Array.isArray(input.patterns) && Array.isArray(input.sections);\n\nconst patterns = (input: string): string[] =>\n split(input)\n .map((l) => l.trim())\n .filter((line) => line !== \"\" && !isComment(line));\n\nconst parse = (input: string | ParsedGitignore, options: ParseOptions = {}): ParsedGitignore => {\n let filepath = options.path;\n\n if (isParsed(input)) return input;\n if (isValidPath(input) && fs.existsSync(input)) {\n filepath = input;\n input = fs.readFileSync(input, \"utf8\");\n }\n\n const lines = split(input);\n const names = new Map<string, Section>();\n\n let parsed: ParsedGitignore = { sections: [], patterns: [] } as unknown as ParsedGitignore;\n let section: Section = { name: \"default\", patterns: [] };\n let prev: Section | null = null;\n\n for (const line of lines) {\n const value = line.trim();\n\n if (value.startsWith(\"#\")) {\n const [, name] = /^#+\\s*(.*)\\s*$/.exec(value) || [];\n\n if (prev) {\n names.delete(prev.name);\n prev.comment = prev.comment ? `${prev.comment}\\n${value}` : value;\n prev.name = name ? `${prev.name.trim()}\\n${name.trim()}` : prev.name.trim();\n names.set(prev.name.toLowerCase().trim(), prev);\n continue;\n }\n\n section = { name: name?.trim() || \"\", comment: value, patterns: [] };\n names.set(section.name.toLowerCase(), section);\n parsed.sections.push(section);\n prev = section;\n continue;\n }\n\n if (value !== \"\") {\n section.patterns.push(value);\n parsed.patterns.push(value);\n }\n\n prev = null;\n }\n\n if (options.dedupe === true || options.unique === true) {\n parsed = dedupe(parsed, { ...options, format: false });\n }\n\n parsed.path = filepath;\n parsed.input = Buffer.from(input);\n parsed.format = (opts?: ParseOptions) => format(parsed, { ...options, ...opts });\n parsed.dedupe = (opts?: ParseOptions) => dedupe(parsed, { ...options, ...opts });\n parsed.globs = (opts?: ParseOptions) => globs(parsed, { path: filepath, ...options, ...opts });\n return parsed;\n};\n\nconst parseFile = (filepath: string, options?: ParseOptions): ParsedGitignore =>\n parse(fs.readFileSync(filepath, \"utf8\"), options);\n\nconst dedupe = (input: string | ParsedGitignore, options: ParseOptions): ParsedGitignore => {\n const parsed = parse(input, { ...options, dedupe: false });\n\n const names = new Map<string, Section>();\n const res: ParsedGitignore = { sections: [], patterns: [] } as unknown as ParsedGitignore;\n let current: Section;\n\n // first, combine duplicate sections\n for (const section of parsed.sections) {\n const { name = \"\", comment, patterns } = section;\n const key = name.trim().toLowerCase();\n\n for (const pattern of patterns) {\n if (!res.patterns.includes(pattern)) {\n res.patterns.push(pattern);\n }\n }\n\n if (name && names.has(key)) {\n current = names.get(key)!;\n current.patterns = [...current.patterns, ...patterns];\n } else {\n current = { name, comment, patterns };\n res.sections.push(current);\n names.set(key, current);\n }\n }\n\n // next, de-dupe patterns in each section\n for (const section of res.sections) {\n section.patterns = [...new Set(section.patterns)];\n }\n\n return res;\n};\n\nconst glob = (pattern: string): string => {\n // Return if a glob pattern has already been specified for sub-directories\n if (GLOBSTAR_REGEX.test(pattern)) {\n return pattern;\n }\n\n // If there is a separator at the beginning or middle (or both) of the pattern,\n // then the pattern is relative to the directory level of the particular .gitignore\n // file itself. Otherwise the pattern may also match at any level below the\n // .gitignore level. relative paths only\n let relative = false;\n if (pattern.startsWith(\"/\")) {\n pattern = pattern.slice(1);\n relative = true;\n } else if (pattern.slice(1, pattern.length - 1).includes(\"/\")) {\n relative = true;\n }\n\n // If there is a separator at the end of the pattern then the pattern will only match directories.\n pattern += pattern.endsWith(\"/\") ? \"**/\" : \"/**\";\n\n // If not relative, the pattern can match any files and directories.\n return relative ? pattern : `**/${pattern}`;\n};\n\nconst globs = (input: string | ParsedGitignore, options: ParseOptions = {}): GlobResult[] => {\n const parsed = parse(input, options);\n const result: GlobResult[] = [];\n let index = 0;\n\n const globPatterns = parsed.patterns\n .concat(options.ignore || [])\n .concat((options.unignore || []).map((p) => (!p.startsWith(\"!\") ? `!${p}` : p)));\n\n const push = (prefix: string, pattern: string) => {\n const prev = result[result.length - 1];\n const type = prefix ? \"unignore\" : \"ignore\";\n\n if (prev && prev.type === type) {\n if (!prev.patterns.includes(pattern)) {\n prev.patterns.push(pattern);\n }\n } else {\n result.push({ type, path: options.path || null, patterns: [pattern], index });\n index++;\n }\n };\n\n for (let pattern of globPatterns) {\n let prefix = \"\";\n\n // An optional prefix \"!\" which negates the pattern; any matching file excluded by\n // a previous pattern will become included again\n if (pattern.startsWith(\"!\")) {\n pattern = pattern.slice(1);\n prefix = \"!\";\n }\n\n // add the raw pattern to the results\n push(prefix, pattern.startsWith(\"/\") ? pattern.slice(1) : pattern);\n\n // add the glob pattern to the results\n push(prefix, glob(pattern));\n }\n\n return result;\n};\n\n/**\n * Formats a .gitignore section\n */\nconst formatSection = (section: Section = { name: \"\", patterns: [] }): string => {\n const output = [section.comment || \"\"];\n\n if (section.patterns?.length) {\n output.push(section.patterns.join(\"\\n\"));\n output.push(\"\");\n }\n\n return output.join(\"\\n\");\n};\n\n/**\n * Format a .gitignore file from the given input or object from `.parse()`.\n * @param {String | ParsedGitignore} input File path or contents.\n * @param {ParseOptions} options\n * @return {String} Returns formatted string.\n * @api public\n */\nconst format = (input: string | ParsedGitignore, options: ParseOptions = {}): string => {\n const parsed = parse(input, options);\n\n const fn = options.formatSection || formatSection;\n const sections = parsed.sections || parsed;\n const output: string[] = [];\n\n for (const section of ([] as Section[]).concat(sections)) {\n output.push(fn(section));\n }\n\n return output.join(\"\\n\");\n};\n\nexport {\n parse,\n parseFile,\n dedupe,\n format,\n globs,\n formatSection,\n patterns,\n type ParseOptions,\n type Section,\n type ParsedGitignore,\n type GlobResult,\n};\n\nexport default parse;\n","import { manifestSchema } from \"~/shared/manifest\";\nimport fs from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport fg from \"fast-glob\";\nimport { type Logger, logger as defaultLogger } from \"./logger\";\nimport { basename, dirname, extname } from \"node:path\";\nimport type { TemplateConfig } from \"~/shared/template\";\n\nexport async function loadConfigFromJsFile(\n configPath: string,\n logger = defaultLogger,\n): Promise<TemplateConfig> {\n if (!fs.existsSync(configPath)) {\n logger.error(\n \"🔴 No enpage.config.js found!\\nYour project must have an enpage.config.js file in the root directory.\\n\\n\",\n );\n process.exit(1);\n }\n const config = (await import(configPath)) as TemplateConfig;\n\n // Parse the readme files fro the same directory as the config file\n const readmePath = dirname(configPath);\n const readme: Record<string, string> = {};\n const readmeFiles = await fg([\"README.enpage.md\", \"README.enpage.*.md\"], {\n cwd: readmePath,\n onlyFiles: true,\n absolute: true,\n caseSensitiveMatch: false,\n });\n\n for (const file of readmeFiles) {\n const base = basename(file, \".md\");\n const ext = extname(base);\n const language = (ext === \".enpage\" ? \"en\" : ext.substring(1)).toLowerCase();\n logger.debug(`Found template readme file (${language}): ${basename(file)}`);\n readme[language] = await readFile(file, \"utf-8\");\n }\n\n if (config.manifest) {\n config.manifest.readme = readme;\n }\n\n return config;\n}\n\nexport function loadConfigFromManifestFile(manifestPath: string, logger: Logger): TemplateConfig {\n if (!fs.existsSync(manifestPath)) {\n logger.error(\"🔴 No enpage.manifest.json found!\\nYou may want to 'build' your template.\\n\\n\");\n process.exit(1);\n }\n return JSON.parse(fs.readFileSync(manifestPath, \"utf-8\"));\n}\n\nexport function validateTemplateConfig(config: TemplateConfig, logger: Logger) {\n for (const key in config.datasources) {\n if (\n (config.datasources[key].provider === \"json-object\" ||\n config.datasources[key].provider === \"json-array\") &&\n !config.datasources[key].sampleData\n ) {\n logger.error(\n `🔴 Error: Datasource \"${key}\" is missing sample data - nothing will be rendered during development! Please check your enpage.config.js file and add a \"sampleData\" key to your ${key} datasource.`,\n );\n throw new Error(`Missing sample data for datasource \"${key}\"`);\n }\n }\n\n // Todo: replace validation from zod to ajv\n // const validated = manifestSchema.safeParse(config.manifest);\n // if (!validated.success) {\n // logger.error(`🔴 Error: template manifest is invalid. Check your call to defineManifest().\\n`);\n // const err = fromError(validated.error);\n // logger.error(`Hint: ${err.toString()}\\n\\n`);\n // process.exit(1);\n // }\n\n return config;\n}\n","import { OAUTH_ENDPOINT_USER_INFO } from \"./constants\";\nimport { accessStore } from \"./store\";\n\nexport async function isLoggedIn(checkRemote = false): Promise<boolean> {\n const token = accessStore.get(\"access_token\");\n const expiration = accessStore.get(\"expires_at\");\n\n if (!token) {\n return false;\n }\n\n if (expiration && expiration < Date.now()) {\n console.log(\"Seems like your token expired...\");\n return false;\n }\n\n if (!checkRemote) {\n return true;\n }\n\n // Check if token is valid\n\n // import dynamically \"./api\" to avoid circular dependency\n const { get } = await import(\"./api\");\n const { isSuccess } = await get(OAUTH_ENDPOINT_USER_INFO);\n\n return isSuccess;\n}\n"],"mappings":";;gIAAO,SAASA,GAAoB,CAElC,IAAIC,EACJ,GAAI,QAAQ,IAAI,sBAAuB,CACrC,IAAMC,EAAS,QAAQ,IAAI,sBAAsB,MAAM,GAAG,EAAE,CAAC,EAC7DD,EAAiBC,EAAO,MAAM,EAAGA,EAAO,YAAY,GAAG,CAAC,CAC1D,CAGA,OAAKD,IACH,QAAQ,IAAI,2CAA2C,EACvDA,EAAiB,OAGZA,CACT,CAEO,SAASE,EAAeC,EAAsD,CACnF,MAAO,IAAIA,EAAM,KAAK,IAAIA,EAAM,kBAAoB,KAAKA,EAAM,iBAAiB,GAAK,EAAE,EACzF,CAnBA,IAAAC,EAAAC,EAAA,oBCAA,IAAaC,EAEAC,GAGAC,EACAC,GACAC,EAIAC,EAEAC,EAbbC,EAAAC,EAAA,kBAAaR,EAAmB,cAEnBC,GACX,QAAQ,IAAI,gCAAkC,uCAEnCC,EAAe,QAAQ,IAAI,6BAA+B,yBAC1DC,GAAkB,QAAQ,IAAI,gCAAkC,qBAChEC,EAAiC,GA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CAEA,SAASa,GAAuBU,EAAqB,CACnD,GAAI,CACF,OAAO,KAAK,MAAMC,GAAaD,EAAa,OAAO,CAAC,CACtD,MAAY,CACV,OAAO,IACT,CACF","names":["getPackageManager","packageManager","pmPart","formatAPIError","error","init_utils","__esmMin","CLI_PROJECT_NAME","CLI_LOGIN_CLIENT_ID","API_BASE_URL","EDITOR_BASE_URL","DEFAULT_UPLOAD_MAX_CONCURRENCY","OAUTH_ENDPOINT_USER_INFO","API_ENDPOINT_REGISTER_TEMPLATE","init_constants","__esmMin","Conf","path","crypto","fs","fileURLToPath","chalk","getTokenOrThrow","token","accessStore","pkgCmd","getPackageManager","findNearestNodeModules","currentDir","__dirname","nodeModulesPath","getKey","tmpSecureStoreDir","keyPath","key","init_store","__esmMin","init_constants","init_utils","CLI_PROJECT_NAME","version","init_package","__esmMin","createLoggerBase","chalk","createLogger","level","allowClearScreen","showVersion","logger","version","message","options","init_logger","__esmMin","init_package","api_exports","__export","get","post","path","data","headers","accessStore","response","toURL","error","logger","formatResponse","apiBaseURL","API_BASE_URL","init_api","__esmMin","init_logger","init_constants","init_store","init_utils","init_store","resolve","existsSync","readFileSync","writeFileSync","chalk","init_constants","init_logger","path","fs","crypto","fg","http","https","pipeline","chalk","FormData","fs","INVALID_PATH_CHARS_REGEX","GLOBSTAR_REGEX","MAX_PATH_LENGTH","isObject","v","isValidPath","input","split","str","isParsed","input","isObject","parse","input","options","filepath","isParsed","isValidPath","lines","split","names","parsed","section","prev","line","value","name","dedupe","opts","format","globs","dedupe","input","options","parsed","parse","names","res","current","section","name","comment","patterns","key","pattern","glob","GLOBSTAR_REGEX","relative","globs","result","index","globPatterns","p","push","prefix","prev","type","formatSection","output","format","fn","sections","parse_gitignore_default","parse","init_api","PQueue","ora","customAlphabet","UploadError","error","error_description","filename","defaultConfig","agent","http","discoverFiles","templateDir","gitignore","path","gitignored","fs","parse_gitignore_default","fg","uploadFile","filePath","relativePath","uploadUrl","templateId","spinner","token","config","uploadWithRetry","attempt","performUpload","logger","resolve","reject","stats","fileName","startTime","form","FormData","fileStream","totalUploaded","updateProgress","chunk","options","req","https","res","responseBody","endTime","uploadStats","errorObject","parsedError","pipeline","err","reportUploadStatistics","uploadedFiles","failedFiles","chalk","failure","uploadTemplate","dryRun","fullConfig","queue","DEFAULT_UPLOAD_MAX_CONCURRENCY","files","filesCount","signatures","uploadId","generateUploadId","completedUploads","file","md5","sha1sum","uploadPromises","fullPath","url","API_BASE_URL","result","results","r","finalizeUrl","finalizeResponse","post","hash","crypto","b","randomId","now","year","month","day","hours","minutes","seconds","init_api","init_constants","path","init_logger","fs","readFile","fg","basename","dirname","extname","loadConfigFromJsFile","configPath","logger","config","readmePath","readme","readmeFiles","file","base","ext","language","validateTemplateConfig","config","logger","key","init_constants","init_store","isLoggedIn","checkRemote","token","accessStore","expiration","get","isSuccess","OAUTH_ENDPOINT_USER_INFO","publish","options","args","logger","isLoggedIn","pkgCmd","getPackageManager","chalk","templateDir","path","resolve","existsSync","distDir","config","loadConfigFromJsFile","validateTemplateConfig","token","getTokenOrThrow","pkgLocation","getPackageLocation","pkg","getPackageJsonContents","data","isError","status","post","API_ENDPOINT_REGISTER_TEMPLATE","formatAPIError","writeFileSync","templateId","uploadTemplate","pkgJsonPath","readFileSync"]}
@@ -13,3 +13,4 @@ ${g.trim()}`:s.name.trim(),a.set(s.name.toLowerCase().trim(),s);continue}o={name
13
13
  *
14
14
  * Converted to typescript by Matthias E. <matthias@upstart.gg>
15
15
  */
16
+ //# sourceMappingURL=parse-gitignore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/node/cli/commands/publish/parse-gitignore.ts"],"sourcesContent":["/*!\n * parse-gitignore <https://github.com/jonschlinkert/parse-gitignore>\n * Copyright (c) 2015-present, Jon Schlinkert.\n * Released under the MIT License.\n *\n * Converted to typescript by Matthias E. <matthias@upstart.gg>\n */\n\nimport * as fs from \"node:fs\";\n\n// eslint-disable-next-line no-control-regex\nconst INVALID_PATH_CHARS_REGEX = /[<>\"|?*\\n\\r\\t\\f\\x00-\\x1F]/;\nconst GLOBSTAR_REGEX = /(?:^|\\/)[*]{2}($|\\/)/;\nconst MAX_PATH_LENGTH = 260 - 12;\n\ninterface ParseOptions {\n path?: string;\n dedupe?: boolean;\n unique?: boolean;\n ignore?: string[];\n unignore?: string[];\n format?: boolean;\n formatSection?: (section: Section) => string;\n}\n\ninterface Section {\n name: string;\n comment?: string;\n patterns: string[];\n}\n\ninterface ParsedGitignore {\n sections: Section[];\n patterns: string[];\n path?: string;\n input: Buffer;\n format: (opts?: ParseOptions) => string;\n dedupe: (opts?: ParseOptions) => ParsedGitignore;\n globs: (opts?: ParseOptions) => GlobResult[];\n}\n\ninterface GlobResult {\n type: \"ignore\" | \"unignore\";\n path: string | null;\n patterns: string[];\n index: number;\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n v !== null && typeof v === \"object\" && !Array.isArray(v);\n\nconst isValidPath = (input: unknown): input is string =>\n typeof input === \"string\" && input.length <= MAX_PATH_LENGTH && !INVALID_PATH_CHARS_REGEX.test(input);\n\nconst split = (str: string): string[] => str.split(/\\r\\n?|\\n/);\nconst isComment = (str: string): boolean => str.startsWith(\"#\");\nconst isParsed = (input: unknown): input is ParsedGitignore =>\n isObject(input) && Array.isArray(input.patterns) && Array.isArray(input.sections);\n\nconst patterns = (input: string): string[] =>\n split(input)\n .map((l) => l.trim())\n .filter((line) => line !== \"\" && !isComment(line));\n\nconst parse = (input: string | ParsedGitignore, options: ParseOptions = {}): ParsedGitignore => {\n let filepath = options.path;\n\n if (isParsed(input)) return input;\n if (isValidPath(input) && fs.existsSync(input)) {\n filepath = input;\n input = fs.readFileSync(input, \"utf8\");\n }\n\n const lines = split(input);\n const names = new Map<string, Section>();\n\n let parsed: ParsedGitignore = { sections: [], patterns: [] } as unknown as ParsedGitignore;\n let section: Section = { name: \"default\", patterns: [] };\n let prev: Section | null = null;\n\n for (const line of lines) {\n const value = line.trim();\n\n if (value.startsWith(\"#\")) {\n const [, name] = /^#+\\s*(.*)\\s*$/.exec(value) || [];\n\n if (prev) {\n names.delete(prev.name);\n prev.comment = prev.comment ? `${prev.comment}\\n${value}` : value;\n prev.name = name ? `${prev.name.trim()}\\n${name.trim()}` : prev.name.trim();\n names.set(prev.name.toLowerCase().trim(), prev);\n continue;\n }\n\n section = { name: name?.trim() || \"\", comment: value, patterns: [] };\n names.set(section.name.toLowerCase(), section);\n parsed.sections.push(section);\n prev = section;\n continue;\n }\n\n if (value !== \"\") {\n section.patterns.push(value);\n parsed.patterns.push(value);\n }\n\n prev = null;\n }\n\n if (options.dedupe === true || options.unique === true) {\n parsed = dedupe(parsed, { ...options, format: false });\n }\n\n parsed.path = filepath;\n parsed.input = Buffer.from(input);\n parsed.format = (opts?: ParseOptions) => format(parsed, { ...options, ...opts });\n parsed.dedupe = (opts?: ParseOptions) => dedupe(parsed, { ...options, ...opts });\n parsed.globs = (opts?: ParseOptions) => globs(parsed, { path: filepath, ...options, ...opts });\n return parsed;\n};\n\nconst parseFile = (filepath: string, options?: ParseOptions): ParsedGitignore =>\n parse(fs.readFileSync(filepath, \"utf8\"), options);\n\nconst dedupe = (input: string | ParsedGitignore, options: ParseOptions): ParsedGitignore => {\n const parsed = parse(input, { ...options, dedupe: false });\n\n const names = new Map<string, Section>();\n const res: ParsedGitignore = { sections: [], patterns: [] } as unknown as ParsedGitignore;\n let current: Section;\n\n // first, combine duplicate sections\n for (const section of parsed.sections) {\n const { name = \"\", comment, patterns } = section;\n const key = name.trim().toLowerCase();\n\n for (const pattern of patterns) {\n if (!res.patterns.includes(pattern)) {\n res.patterns.push(pattern);\n }\n }\n\n if (name && names.has(key)) {\n current = names.get(key)!;\n current.patterns = [...current.patterns, ...patterns];\n } else {\n current = { name, comment, patterns };\n res.sections.push(current);\n names.set(key, current);\n }\n }\n\n // next, de-dupe patterns in each section\n for (const section of res.sections) {\n section.patterns = [...new Set(section.patterns)];\n }\n\n return res;\n};\n\nconst glob = (pattern: string): string => {\n // Return if a glob pattern has already been specified for sub-directories\n if (GLOBSTAR_REGEX.test(pattern)) {\n return pattern;\n }\n\n // If there is a separator at the beginning or middle (or both) of the pattern,\n // then the pattern is relative to the directory level of the particular .gitignore\n // file itself. Otherwise the pattern may also match at any level below the\n // .gitignore level. relative paths only\n let relative = false;\n if (pattern.startsWith(\"/\")) {\n pattern = pattern.slice(1);\n relative = true;\n } else if (pattern.slice(1, pattern.length - 1).includes(\"/\")) {\n relative = true;\n }\n\n // If there is a separator at the end of the pattern then the pattern will only match directories.\n pattern += pattern.endsWith(\"/\") ? \"**/\" : \"/**\";\n\n // If not relative, the pattern can match any files and directories.\n return relative ? pattern : `**/${pattern}`;\n};\n\nconst globs = (input: string | ParsedGitignore, options: ParseOptions = {}): GlobResult[] => {\n const parsed = parse(input, options);\n const result: GlobResult[] = [];\n let index = 0;\n\n const globPatterns = parsed.patterns\n .concat(options.ignore || [])\n .concat((options.unignore || []).map((p) => (!p.startsWith(\"!\") ? `!${p}` : p)));\n\n const push = (prefix: string, pattern: string) => {\n const prev = result[result.length - 1];\n const type = prefix ? \"unignore\" : \"ignore\";\n\n if (prev && prev.type === type) {\n if (!prev.patterns.includes(pattern)) {\n prev.patterns.push(pattern);\n }\n } else {\n result.push({ type, path: options.path || null, patterns: [pattern], index });\n index++;\n }\n };\n\n for (let pattern of globPatterns) {\n let prefix = \"\";\n\n // An optional prefix \"!\" which negates the pattern; any matching file excluded by\n // a previous pattern will become included again\n if (pattern.startsWith(\"!\")) {\n pattern = pattern.slice(1);\n prefix = \"!\";\n }\n\n // add the raw pattern to the results\n push(prefix, pattern.startsWith(\"/\") ? pattern.slice(1) : pattern);\n\n // add the glob pattern to the results\n push(prefix, glob(pattern));\n }\n\n return result;\n};\n\n/**\n * Formats a .gitignore section\n */\nconst formatSection = (section: Section = { name: \"\", patterns: [] }): string => {\n const output = [section.comment || \"\"];\n\n if (section.patterns?.length) {\n output.push(section.patterns.join(\"\\n\"));\n output.push(\"\");\n }\n\n return output.join(\"\\n\");\n};\n\n/**\n * Format a .gitignore file from the given input or object from `.parse()`.\n * @param {String | ParsedGitignore} input File path or contents.\n * @param {ParseOptions} options\n * @return {String} Returns formatted string.\n * @api public\n */\nconst format = (input: string | ParsedGitignore, options: ParseOptions = {}): string => {\n const parsed = parse(input, options);\n\n const fn = options.formatSection || formatSection;\n const sections = parsed.sections || parsed;\n const output: string[] = [];\n\n for (const section of ([] as Section[]).concat(sections)) {\n output.push(fn(section));\n }\n\n return output.join(\"\\n\");\n};\n\nexport {\n parse,\n parseFile,\n dedupe,\n format,\n globs,\n formatSection,\n patterns,\n type ParseOptions,\n type Section,\n type ParsedGitignore,\n type GlobResult,\n};\n\nexport default parse;\n"],"mappings":";;AAQA,UAAYA,MAAQ,UAGpB,IAAMC,EAA2B,4BAC3BC,EAAiB,uBACjBC,EAAkB,IAmClBC,EAAYC,GAChBA,IAAM,MAAQ,OAAOA,GAAM,UAAY,CAAC,MAAM,QAAQA,CAAC,EAEnDC,EAAeC,GACnB,OAAOA,GAAU,UAAYA,EAAM,QAAUJ,GAAmB,CAACF,EAAyB,KAAKM,CAAK,EAEhGC,EAASC,GAA0BA,EAAI,MAAM,UAAU,EACvDC,EAAaD,GAAyBA,EAAI,WAAW,GAAG,EACxDE,EAAYJ,GAChBH,EAASG,CAAK,GAAK,MAAM,QAAQA,EAAM,QAAQ,GAAK,MAAM,QAAQA,EAAM,QAAQ,EAE5EK,EAAYL,GAChBC,EAAMD,CAAK,EACR,IAAKM,GAAMA,EAAE,KAAK,CAAC,EACnB,OAAQC,GAASA,IAAS,IAAM,CAACJ,EAAUI,CAAI,CAAC,EAE/CC,EAAQ,CAACR,EAAiCS,EAAwB,CAAC,IAAuB,CAC9F,IAAIC,EAAWD,EAAQ,KAEvB,GAAIL,EAASJ,CAAK,EAAG,OAAOA,EACxBD,EAAYC,CAAK,GAAQ,aAAWA,CAAK,IAC3CU,EAAWV,EACXA,EAAW,eAAaA,EAAO,MAAM,GAGvC,IAAMW,EAA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K;AAAA,CAAI,CAAC,EACvCwB,EAAO,KAAK,EAAE,GAGTA,EAAO,KAAK;AAAA,CAAI,CACzB,EASMlB,EAAS,CAACpB,EAAiCS,EAAwB,CAAC,IAAc,CACtF,IAAMI,EAASL,EAAMR,EAAOS,CAAO,EAE7B8B,EAAK9B,EAAQ,eAAiB4B,EAC9BG,EAAW3B,EAAO,UAAYA,EAC9ByB,EAAmB,CAAC,EAE1B,QAAWxB,IAAY,CAAC,EAAgB,OAAO0B,CAAQ,EACrDF,EAAO,KAAKC,EAAGzB,CAAO,CAAC,EAGzB,OAAOwB,EAAO,KAAK;AAAA,CAAI,CACzB,EAgBA,IAAOG,EAAQC","names":["fs","INVALID_PATH_CHARS_REGEX","GLOBSTAR_REGEX","MAX_PATH_LENGTH","isObject","v","isValidPath","input","split","str","isComment","isParsed","patterns","l","line","parse","options","filepath","lines","names","parsed","section","prev","value","name","dedupe","opts","format","globs","parseFile","res","current","comment","key","pattern","glob","relative","result","index","globPatterns","p","push","prefix","type","formatSection","output","fn","sections","parse_gitignore_default","parse"]}
@@ -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 L from"node:path";import b from"node:fs";import ge from"node:crypto";import me from"fast-glob";var I="upstart-cli";var Oe=process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID??"50000000-0000-0000-0000-000000000001",y=process.env.PUBLIC_UPSTART_API_BASE_URL??"https://api.upstart.gg",Ae=process.env.PUBLIC_UPSTART_EDITOR_BASE_URL??"https://upstart.gg",N=10;import B from"node:http";import fe from"node:https";import{pipeline as ye}from"node:stream";import{createLogger as q}from"vite";var D="0.0.92";import _ from"chalk";function H(e,t,n=!1){let i=q(e==="debug"?"info":e,{prefix:"[upstart]",allowClearScreen:t});return n&&i.info(_.hex("#7270c6").bold(`\u{1F680} Upstart v${D}
3
+ import L from"node:path";import b from"node:fs";import ge from"node:crypto";import me from"fast-glob";var I="upstart-cli";var Oe=process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID??"50000000-0000-0000-0000-000000000001",y=process.env.PUBLIC_UPSTART_API_BASE_URL??"https://api.upstart.gg",Ae=process.env.PUBLIC_UPSTART_EDITOR_BASE_URL??"https://upstart.gg",N=10;import B from"node:http";import fe from"node:https";import{pipeline as ye}from"node:stream";import{createLogger as q}from"vite";var D="0.0.93";import _ from"chalk";function H(e,t,n=!1){let i=q(e==="debug"?"info":e,{prefix:"[upstart]",allowClearScreen:t});return n&&i.info(_.hex("#7270c6").bold(`\u{1F680} Upstart v${D}
4
4
  `)),{...i,success:(r,s)=>i.info(_.green(r),s),error:(r,s)=>i.error(_.red(r),s),warn:(r,s)=>i.warn(_.yellow(r),s),warnOnce:(r,s)=>i.warnOnce(_.yellow(r),s),debug:(r,s)=>{e==="debug"&&i.info(_.gray(r),s)}}}var g=H();import z from"chalk";import he from"form-data";import*as C from"node:fs";var X=/[<>"|?*\n\r\t\f\x00-\x1F]/,J=/(?:^|\/)[*]{2}($|\/)/,V=248,K=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Y=e=>typeof e=="string"&&e.length<=V&&!X.test(e),Q=e=>e.split(/\r\n?|\n/);var Z=e=>K(e)&&Array.isArray(e.patterns)&&Array.isArray(e.sections);var k=(e,t={})=>{let n=t.path;if(Z(e))return e;Y(e)&&C.existsSync(e)&&(n=e,e=C.readFileSync(e,"utf8"));let i=Q(e),r=new Map,s={sections:[],patterns:[]},c={name:"default",patterns:[]},o=null;for(let a of i){let p=a.trim();if(p.startsWith("#")){let[,u]=/^#+\s*(.*)\s*$/.exec(p)||[];if(o){r.delete(o.name),o.comment=o.comment?`${o.comment}
5
5
  ${p}`:p,o.name=u?`${o.name.trim()}
6
6
  ${u.trim()}`:o.name.trim(),r.set(o.name.toLowerCase().trim(),o);continue}c={name:u?.trim()||"",comment:p,patterns:[]},r.set(c.name.toLowerCase(),c),s.sections.push(c),o=c;continue}p!==""&&(c.patterns.push(p),s.patterns.push(p)),o=null}return(t.dedupe===!0||t.unique===!0)&&(s=G(s,{...t,format:!1})),s.path=n,s.input=Buffer.from(e),s.format=a=>se(s,{...t,...a}),s.dedupe=a=>G(s,{...t,...a}),s.globs=a=>te(s,{path:n,...t,...a}),s};var G=(e,t)=>{let n=k(e,{...t,dedupe:!1}),i=new Map,r={sections:[],patterns:[]},s;for(let c of n.sections){let{name:o="",comment:a,patterns:p}=c,u=o.trim().toLowerCase();for(let h of p)r.patterns.includes(h)||r.patterns.push(h);o&&i.has(u)?(s=i.get(u),s.patterns=[...s.patterns,...p]):(s={name:o,comment:a,patterns:p},r.sections.push(s),i.set(u,s))}for(let c of r.sections)c.patterns=[...new Set(c.patterns)];return r},ee=e=>{if(J.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}`},te=(e,t={})=>{let n=k(e,t),i=[],r=0,s=n.patterns.concat(t.ignore||[]).concat((t.unignore||[]).map(o=>o.startsWith("!")?o:`!${o}`)),c=(o,a)=>{let p=i[i.length-1],u=o?"unignore":"ignore";p&&p.type===u?p.patterns.includes(a)||p.patterns.push(a):(i.push({type:u,path:t.path||null,patterns:[a],index:r}),r++)};for(let o of s){let a="";o.startsWith("!")&&(o=o.slice(1),a="!"),c(a,o.startsWith("/")?o.slice(1):o),c(a,ee(o))}return i},re=(e={name:"",patterns:[]})=>{let t=[e.comment||""];return e.patterns?.length&&(t.push(e.patterns.join(`
@@ -16,3 +16,4 @@ ${u.trim()}`:o.name.trim(),r.set(o.name.toLowerCase().trim(),o);continue}c={name
16
16
  *
17
17
  * Converted to typescript by Matthias E. <matthias@upstart.gg>
18
18
  */
19
+ //# sourceMappingURL=uploader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/node/cli/commands/publish/uploader.ts","../../../../../src/node/cli/constants.ts","../../../../../src/node/shared/logger.ts","../../../../../package.json","../../../../../src/node/cli/commands/publish/parse-gitignore.ts","../../../../../src/node/cli/store.ts","../../../../../src/node/cli/api.ts"],"sourcesContent":["import path from \"node:path\";\nimport fs from \"node:fs\";\nimport crypto from \"node:crypto\";\nimport fg from \"fast-glob\";\nimport { API_BASE_URL, DEFAULT_UPLOAD_MAX_CONCURRENCY } from \"../../constants\";\nimport http from \"node:http\";\nimport https from \"node:https\";\nimport { pipeline } from \"node:stream\";\nimport type { GenericApiError } from \"../../types\";\nimport { logger } from \"~/node/shared/logger\";\nimport chalk from \"chalk\";\nimport FormData from \"form-data\";\nimport parseGitIgnore from \"./parse-gitignore\";\nimport PQueue from \"p-queue\";\nimport ora from \"ora\";\nimport { customAlphabet } from \"nanoid\";\nimport { post } from \"../../api\";\n\ninterface UploadStats {\n fileName: string;\n fileSize: number;\n uploadDuration: number;\n statusCode: number;\n serverResponse: string;\n}\n\nclass UploadError extends Error implements GenericApiError {\n constructor(\n public error: string,\n public error_description: string,\n public filename: string,\n ) {\n super(`${error}: ${error_description}`);\n this.name = \"UploadError\";\n }\n}\n\ninterface UploadConfig {\n maxDataSize: number;\n retryAttempts: number;\n retryDelay: number;\n}\n\nconst defaultConfig: UploadConfig = {\n maxDataSize: 12 * 1024 * 1024, // 12MB\n retryAttempts: 2,\n retryDelay: 1000,\n};\n\nconst agent = new http.Agent({\n keepAlive: true,\n maxSockets: 10,\n keepAliveMsecs: 3000, // Keep connections open for 3 seconds\n});\n\nasync function discoverFiles(templateDir: string): Promise<string[]> {\n const gitignore = path.join(templateDir, \".gitignore\");\n const gitignoreExists = fs.existsSync(gitignore);\n const gitignored = gitignoreExists ? parseGitIgnore(fs.readFileSync(gitignore, \"utf-8\")).patterns : [];\n\n return fg(\"**/*\", {\n cwd: templateDir,\n onlyFiles: true,\n dot: true,\n absolute: true,\n ignore: [\n \"node_modules/**\",\n \".cache/**\",\n \"**/.DS_Store\",\n \".gitignore\",\n \".env\",\n \".env.*\",\n \".git/**\",\n \"dist/**\",\n ...gitignored,\n ],\n });\n}\n\nasync function uploadFile(\n filePath: string,\n relativePath: string,\n uploadUrl: string,\n templateId: string,\n spinner: ReturnType<typeof ora>,\n token: string,\n config: UploadConfig,\n): Promise<UploadStats> {\n const uploadWithRetry = async (attempt: number): Promise<UploadStats> => {\n try {\n return await performUpload(filePath, relativePath, uploadUrl, templateId, spinner, token, config);\n } catch (error) {\n if (attempt < config.retryAttempts) {\n logger.warn(`Retrying upload for ${relativePath} (attempt ${attempt + 1})`);\n await new Promise((resolve) => setTimeout(resolve, config.retryDelay));\n return uploadWithRetry(attempt + 1);\n }\n throw error;\n }\n };\n\n return uploadWithRetry(0);\n}\n\nasync function performUpload(\n filePath: string,\n relativePath: string,\n uploadUrl: string,\n templateId: string,\n spinner: ReturnType<typeof ora>,\n token: string,\n config: UploadConfig,\n): Promise<UploadStats> {\n return new Promise<UploadStats>((resolve, reject) => {\n const stats = fs.statSync(filePath);\n const fileName = path.basename(filePath);\n const startTime = Date.now();\n\n const form = new FormData({\n maxDataSize: config.maxDataSize,\n });\n const fileStream = fs.createReadStream(filePath);\n let totalUploaded = 0;\n\n const updateProgress = (chunk: Buffer | string) => {\n totalUploaded += chunk.length;\n };\n\n fileStream.on(\"data\", updateProgress);\n form.append(\"file\", fileStream, {\n filename: fileName,\n knownLength: stats.size,\n });\n\n const options: https.RequestOptions = {\n agent,\n method: \"POST\",\n headers: {\n authorization: `Bearer ${token}`,\n \"x-upstart-template-file-path\": relativePath,\n \"x-upstart-template-id\": templateId,\n ...form.getHeaders(),\n },\n };\n\n const protocol = uploadUrl.startsWith(\"https\") ? https : http;\n const req = protocol.request(uploadUrl, options, (res) => {\n let responseBody = \"\";\n res.on(\"data\", (chunk) => {\n responseBody += chunk;\n });\n\n res.on(\"end\", () => {\n const endTime = Date.now();\n const uploadStats: UploadStats = {\n fileName,\n fileSize: stats.size,\n uploadDuration: endTime - startTime,\n statusCode: res.statusCode ?? 0,\n serverResponse: responseBody,\n };\n\n if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {\n spinner.text = `Uploaded ${relativePath}`;\n resolve(uploadStats);\n } else {\n let errorObject: UploadError;\n if (res.headers[\"content-type\"]?.startsWith(\"application/json\")) {\n const parsedError = JSON.parse(responseBody);\n errorObject = new UploadError(\n parsedError.error || \"unknown_error\",\n parsedError.error_description || \"Unknown error occurred\",\n relativePath,\n );\n } else {\n errorObject = new UploadError(\n \"unknown_error\",\n responseBody || \"Unknown error occurred\",\n relativePath,\n );\n }\n\n spinner.fail(\n `Failed to upload ${relativePath} [${errorObject.error}] ${errorObject.error_description}`,\n );\n\n reject(errorObject);\n }\n });\n });\n\n req.on(\"error\", (error) => {\n reject(new UploadError(\"request_error\", error.message, relativePath));\n });\n\n pipeline(form, req, (err) => {\n if (err) {\n reject(\n new UploadError(\"pipeline_error\", `Pipeline failed for ${fileName}: ${err.message}`, relativePath),\n );\n }\n });\n });\n}\n\nfunction reportUploadStatistics(\n templateId: string,\n uploadedFiles: UploadStats[],\n failedFiles: PromiseRejectedResult[],\n) {\n if (failedFiles.length > 0) {\n logger.error(chalk.red(`Failed to upload ${failedFiles.length} files:`));\n failedFiles.forEach((failure) => {\n const error = failure.reason as UploadError;\n logger.error(`- ${error.filename}: ${error.error_description} (${error.error})`);\n });\n } else {\n logger.info(\n chalk.green(`Uploaded ${uploadedFiles.length} files successfully for template ${templateId}.\\n`),\n );\n }\n}\n\nexport async function uploadTemplate(\n templateId: string,\n templateDir: string,\n token: string,\n dryRun = false,\n config: Partial<UploadConfig> = {},\n) {\n const fullConfig = { ...defaultConfig, ...config };\n const queue = new PQueue({ concurrency: DEFAULT_UPLOAD_MAX_CONCURRENCY });\n const files = await discoverFiles(templateDir);\n const filesCount = files.length;\n const signatures: Record<string, string> = {};\n // generate a upload id\n const uploadId = generateUploadId();\n let completedUploads = 0;\n\n // compute signatures\n for (const file of files) {\n const relativePath = path.relative(templateDir, file);\n const md5 = await sha1sum(file);\n signatures[relativePath] = md5;\n }\n\n if (dryRun) {\n logger.info(\"Dry run mode enabled. Skipping upload.\\n\");\n logger.info(\"The following files would have been uploaded:\");\n files.forEach((file) => logger.info(`- ${file}`));\n process.exit(0);\n }\n\n const spinner = ora(`Uploading ${filesCount} files...`).start();\n\n // upload files\n const uploadPromises = files.map((file) => {\n const fullPath = path.resolve(templateDir, file);\n const relativePath = path.relative(templateDir, file);\n const url = `${API_BASE_URL}/v1/templates/${templateId}/upload/${uploadId}`;\n return queue.add(async () => {\n const result = await uploadFile(fullPath, relativePath, url, templateId, spinner, token, fullConfig);\n completedUploads++;\n return result;\n });\n });\n\n const results = await Promise.allSettled(uploadPromises);\n spinner.stop();\n\n const uploadedFiles = results.filter(\n (result): result is PromiseFulfilledResult<UploadStats> => result.status === \"fulfilled\",\n );\n\n const failedFiles = results.filter(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n\n reportUploadStatistics(\n templateId,\n uploadedFiles.map((r) => r.value),\n failedFiles,\n );\n\n // finalize upload\n if (!failedFiles.length && uploadedFiles.length) {\n const finalizeUrl = `${API_BASE_URL}/v1/templates/${templateId}/upload/${uploadId}/finalize`;\n const finalizePayload = {\n signatures,\n };\n\n const finalizeResponse = await post(finalizeUrl, finalizePayload);\n\n if (finalizeResponse.isError) {\n logger.error(\n `Failed to finalize upload: ${finalizeResponse.data.error_description} (${finalizeResponse.data.error})`,\n );\n return {\n filesCount,\n uploadedFiles: uploadedFiles.map((r) => r.value),\n failedFiles: [],\n success: false,\n };\n }\n }\n\n return {\n filesCount,\n uploadedFiles: uploadedFiles.map((r) => r.value),\n failedFiles,\n success: failedFiles.length === 0,\n };\n}\n\nasync function sha1sum(filePath: string): Promise<string> {\n const hash = await crypto.subtle.digest(\"SHA-1\", fs.readFileSync(filePath));\n // convert arrayBuffer to hex\n return Array.from(new Uint8Array(hash))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nfunction generateUploadId(): string {\n const randomId = customAlphabet(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\", 5);\n const now = new Date();\n const year = now.getUTCFullYear();\n const month = (now.getUTCMonth() + 1).toString().padStart(2, \"0\");\n const day = now.getUTCDate().toString().padStart(2, \"0\");\n const hours = now.getUTCHours().toString().padStart(2, \"0\");\n const minutes = now.getUTCMinutes().toString().padStart(2, \"0\");\n const seconds = now.getUTCSeconds().toString().padStart(2, \"0\");\n return `${year}${month}${day}${hours}${minutes}${seconds}_${randomId()}`;\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","/*!\n * parse-gitignore <https://github.com/jonschlinkert/parse-gitignore>\n * Copyright (c) 2015-present, Jon Schlinkert.\n * Released under the MIT License.\n *\n * Converted to typescript by Matthias E. <matthias@upstart.gg>\n */\n\nimport * as fs from \"node:fs\";\n\n// eslint-disable-next-line no-control-regex\nconst INVALID_PATH_CHARS_REGEX = /[<>\"|?*\\n\\r\\t\\f\\x00-\\x1F]/;\nconst GLOBSTAR_REGEX = /(?:^|\\/)[*]{2}($|\\/)/;\nconst MAX_PATH_LENGTH = 260 - 12;\n\ninterface ParseOptions {\n path?: string;\n dedupe?: boolean;\n unique?: boolean;\n ignore?: string[];\n unignore?: string[];\n format?: boolean;\n formatSection?: (section: Section) => string;\n}\n\ninterface Section {\n name: string;\n comment?: string;\n patterns: string[];\n}\n\ninterface ParsedGitignore {\n sections: Section[];\n patterns: string[];\n path?: string;\n input: Buffer;\n format: (opts?: ParseOptions) => string;\n dedupe: (opts?: ParseOptions) => ParsedGitignore;\n globs: (opts?: ParseOptions) => GlobResult[];\n}\n\ninterface GlobResult {\n type: \"ignore\" | \"unignore\";\n path: string | null;\n patterns: string[];\n index: number;\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n v !== null && typeof v === \"object\" && !Array.isArray(v);\n\nconst isValidPath = (input: unknown): input is string =>\n typeof input === \"string\" && input.length <= MAX_PATH_LENGTH && !INVALID_PATH_CHARS_REGEX.test(input);\n\nconst split = (str: string): string[] => str.split(/\\r\\n?|\\n/);\nconst isComment = (str: string): boolean => str.startsWith(\"#\");\nconst isParsed = (input: unknown): input is ParsedGitignore =>\n isObject(input) && Array.isArray(input.patterns) && Array.isArray(input.sections);\n\nconst patterns = (input: string): string[] =>\n split(input)\n .map((l) => l.trim())\n .filter((line) => line !== \"\" && !isComment(line));\n\nconst parse = (input: string | ParsedGitignore, options: ParseOptions = {}): ParsedGitignore => {\n let filepath = options.path;\n\n if (isParsed(input)) return input;\n if (isValidPath(input) && fs.existsSync(input)) {\n filepath = input;\n input = fs.readFileSync(input, \"utf8\");\n }\n\n const lines = split(input);\n const names = new Map<string, Section>();\n\n let parsed: ParsedGitignore = { sections: [], patterns: [] } as unknown as ParsedGitignore;\n let section: Section = { name: \"default\", patterns: [] };\n let prev: Section | null = null;\n\n for (const line of lines) {\n const value = line.trim();\n\n if (value.startsWith(\"#\")) {\n const [, name] = /^#+\\s*(.*)\\s*$/.exec(value) || [];\n\n if (prev) {\n names.delete(prev.name);\n prev.comment = prev.comment ? `${prev.comment}\\n${value}` : value;\n prev.name = name ? `${prev.name.trim()}\\n${name.trim()}` : prev.name.trim();\n names.set(prev.name.toLowerCase().trim(), prev);\n continue;\n }\n\n section = { name: name?.trim() || \"\", comment: value, patterns: [] };\n names.set(section.name.toLowerCase(), section);\n parsed.sections.push(section);\n prev = section;\n continue;\n }\n\n if (value !== \"\") {\n section.patterns.push(value);\n parsed.patterns.push(value);\n }\n\n prev = null;\n }\n\n if (options.dedupe === true || options.unique === true) {\n parsed = dedupe(parsed, { ...options, format: false });\n }\n\n parsed.path = filepath;\n parsed.input = Buffer.from(input);\n parsed.format = (opts?: ParseOptions) => format(parsed, { ...options, ...opts });\n parsed.dedupe = (opts?: ParseOptions) => dedupe(parsed, { ...options, ...opts });\n parsed.globs = (opts?: ParseOptions) => globs(parsed, { path: filepath, ...options, ...opts });\n return parsed;\n};\n\nconst parseFile = (filepath: string, options?: ParseOptions): ParsedGitignore =>\n parse(fs.readFileSync(filepath, \"utf8\"), options);\n\nconst dedupe = (input: string | ParsedGitignore, options: ParseOptions): ParsedGitignore => {\n const parsed = parse(input, { ...options, dedupe: false });\n\n const names = new Map<string, Section>();\n const res: ParsedGitignore = { sections: [], patterns: [] } as unknown as ParsedGitignore;\n let current: Section;\n\n // first, combine duplicate sections\n for (const section of parsed.sections) {\n const { name = \"\", comment, patterns } = section;\n const key = name.trim().toLowerCase();\n\n for (const pattern of patterns) {\n if (!res.patterns.includes(pattern)) {\n res.patterns.push(pattern);\n }\n }\n\n if (name && names.has(key)) {\n current = names.get(key)!;\n current.patterns = [...current.patterns, ...patterns];\n } else {\n current = { name, comment, patterns };\n res.sections.push(current);\n names.set(key, current);\n }\n }\n\n // next, de-dupe patterns in each section\n for (const section of res.sections) {\n section.patterns = [...new Set(section.patterns)];\n }\n\n return res;\n};\n\nconst glob = (pattern: string): string => {\n // Return if a glob pattern has already been specified for sub-directories\n if (GLOBSTAR_REGEX.test(pattern)) {\n return pattern;\n }\n\n // If there is a separator at the beginning or middle (or both) of the pattern,\n // then the pattern is relative to the directory level of the particular .gitignore\n // file itself. Otherwise the pattern may also match at any level below the\n // .gitignore level. relative paths only\n let relative = false;\n if (pattern.startsWith(\"/\")) {\n pattern = pattern.slice(1);\n relative = true;\n } else if (pattern.slice(1, pattern.length - 1).includes(\"/\")) {\n relative = true;\n }\n\n // If there is a separator at the end of the pattern then the pattern will only match directories.\n pattern += pattern.endsWith(\"/\") ? \"**/\" : \"/**\";\n\n // If not relative, the pattern can match any files and directories.\n return relative ? pattern : `**/${pattern}`;\n};\n\nconst globs = (input: string | ParsedGitignore, options: ParseOptions = {}): GlobResult[] => {\n const parsed = parse(input, options);\n const result: GlobResult[] = [];\n let index = 0;\n\n const globPatterns = parsed.patterns\n .concat(options.ignore || [])\n .concat((options.unignore || []).map((p) => (!p.startsWith(\"!\") ? `!${p}` : p)));\n\n const push = (prefix: string, pattern: string) => {\n const prev = result[result.length - 1];\n const type = prefix ? \"unignore\" : \"ignore\";\n\n if (prev && prev.type === type) {\n if (!prev.patterns.includes(pattern)) {\n prev.patterns.push(pattern);\n }\n } else {\n result.push({ type, path: options.path || null, patterns: [pattern], index });\n index++;\n }\n };\n\n for (let pattern of globPatterns) {\n let prefix = \"\";\n\n // An optional prefix \"!\" which negates the pattern; any matching file excluded by\n // a previous pattern will become included again\n if (pattern.startsWith(\"!\")) {\n pattern = pattern.slice(1);\n prefix = \"!\";\n }\n\n // add the raw pattern to the results\n push(prefix, pattern.startsWith(\"/\") ? pattern.slice(1) : pattern);\n\n // add the glob pattern to the results\n push(prefix, glob(pattern));\n }\n\n return result;\n};\n\n/**\n * Formats a .gitignore section\n */\nconst formatSection = (section: Section = { name: \"\", patterns: [] }): string => {\n const output = [section.comment || \"\"];\n\n if (section.patterns?.length) {\n output.push(section.patterns.join(\"\\n\"));\n output.push(\"\");\n }\n\n return output.join(\"\\n\");\n};\n\n/**\n * Format a .gitignore file from the given input or object from `.parse()`.\n * @param {String | ParsedGitignore} input File path or contents.\n * @param {ParseOptions} options\n * @return {String} Returns formatted string.\n * @api public\n */\nconst format = (input: string | ParsedGitignore, options: ParseOptions = {}): string => {\n const parsed = parse(input, options);\n\n const fn = options.formatSection || formatSection;\n const sections = parsed.sections || parsed;\n const output: string[] = [];\n\n for (const section of ([] as Section[]).concat(sections)) {\n output.push(fn(section));\n }\n\n return output.join(\"\\n\");\n};\n\nexport {\n parse,\n parseFile,\n dedupe,\n format,\n globs,\n formatSection,\n patterns,\n type ParseOptions,\n type Section,\n type ParsedGitignore,\n type GlobResult,\n};\n\nexport default parse;\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,MAAU,YACjB,OAAOC,MAAQ,UACf,OAAOC,OAAY,cACnB,OAAOC,OAAQ,YCHR,IAAMC,EAAmB,cAEzB,IAAMC,GACX,QAAQ,IAAI,gCAAkC,uCAEnCC,EAAe,QAAQ,IAAI,6BAA+B,yBAC1DC,GAAkB,QAAQ,IAAI,gCAAkC,qBAChEC,EAAiC,GDF9C,OAAOC,MAAU,YACjB,OAAOC,OAAW,aAClB,OAAS,YAAAC,OAAgB,cEPzB,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,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,EF1BnC,OAAOS,MAAW,QAClB,OAAOC,OAA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AY,EAAE,SAAS,EAAE,SAAS,EAAG,GAAG,EACpDK,EAAUL,EAAI,cAAc,EAAE,SAAS,EAAE,SAAS,EAAG,GAAG,EACxDM,EAAUN,EAAI,cAAc,EAAE,SAAS,EAAE,SAAS,EAAG,GAAG,EAC9D,MAAO,GAAGC,CAAI,GAAGC,CAAK,GAAGC,CAAG,GAAGC,CAAK,GAAGC,CAAO,GAAGC,CAAO,IAAIR,EAAS,CAAC,EACxE","names":["path","fs","crypto","fg","CLI_PROJECT_NAME","CLI_LOGIN_CLIENT_ID","API_BASE_URL","EDITOR_BASE_URL","DEFAULT_UPLOAD_MAX_CONCURRENCY","http","https","pipeline","createLoggerBase","version","chalk","createLogger","level","allowClearScreen","showVersion","logger","createLoggerBase","version","message","options","chalk","FormData","fs","INVALID_PATH_CHARS_REGEX","GLOBSTAR_REGEX","MAX_PATH_LENGTH","isObject","v","isValidPath","input","split","str","isParsed","input","isObject","parse","input","options","filepath","isParsed","isValidPath","lines","split","names","parsed","section","prev","line","value","name","dedupe","opts","format","globs","dedupe","input","options","parsed","parse","names","res","current","section","name","comment","patterns","key","pattern","glob","GLOBSTAR_REGEX","relative","globs","result","index","globPatterns","p","push","prefix","prev","type","formatSection","output","format","fn","sections","parse_gitignore_default","parse","PQueue","ora","customAlphabet","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","UploadError","error","error_description","filename","defaultConfig","agent","http","discoverFiles","templateDir","gitignore","path","gitignored","fs","parse_gitignore_default","fg","uploadFile","filePath","relativePath","uploadUrl","templateId","spinner","token","config","uploadWithRetry","attempt","performUpload","logger","resolve","reject","stats","fileName","startTime","form","FormData","fileStream","totalUploaded","updateProgress","chunk","options","req","https","res","responseBody","endTime","uploadStats","errorObject","parsedError","pipeline","err","reportUploadStatistics","uploadedFiles","failedFiles","chalk","failure","uploadTemplate","dryRun","fullConfig","queue","PQueue","DEFAULT_UPLOAD_MAX_CONCURRENCY","files","filesCount","signatures","uploadId","generateUploadId","completedUploads","file","md5","sha1sum","ora","uploadPromises","fullPath","url","API_BASE_URL","result","results","r","finalizeUrl","finalizeResponse","post","hash","crypto","b","randomId","customAlphabet","now","year","month","day","hours","minutes","seconds"]}
@@ -1,3 +1,4 @@
1
1
  /*! Upstart.gg - Copyright (C) 2024 Flippable - https://github.com/upstart-gg/upstart/blob/main/LICENSE */
2
2
 
3
3
  var _="upstart-cli",t=5e3,o=process.env.PUBLIC_UPSTART_OAUTH_CLIENT_ID??"50000000-0000-0000-0000-000000000001",E=process.env.PUBLIC_UPSTART_API_BASE_URL??"https://api.upstart.gg",I=process.env.PUBLIC_UPSTART_EDITOR_BASE_URL??"https://upstart.gg",T=10,e="oauth/devicecode",s="oauth/token",p="oauth/userinfo",A="v1/templates";export{E as API_BASE_URL,A as API_ENDPOINT_REGISTER_TEMPLATE,o as CLI_LOGIN_CLIENT_ID,t as CLI_LOGIN_POLL_INTERVAL,_ as CLI_PROJECT_NAME,T as DEFAULT_UPLOAD_MAX_CONCURRENCY,I as EDITOR_BASE_URL,e as OAUTH_ENDPOINT_DEVICE_CODE,s as OAUTH_ENDPOINT_TOKEN,p as OAUTH_ENDPOINT_USER_INFO};
4
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/node/cli/constants.ts"],"sourcesContent":["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"],"mappings":";;AAAO,IAAMA,EAAmB,cACnBC,EAA0B,IAC1BC,EACX,QAAQ,IAAI,gCAAkC,uCAEnCC,EAAe,QAAQ,IAAI,6BAA+B,yBAC1DC,EAAkB,QAAQ,IAAI,gCAAkC,qBAChEC,EAAiC,GAEjCC,EAA6B,mBAC7BC,EAAuB,cACvBC,EAA2B,iBAE3BC,EAAiC","names":["CLI_PROJECT_NAME","CLI_LOGIN_POLL_INTERVAL","CLI_LOGIN_CLIENT_ID","API_BASE_URL","EDITOR_BASE_URL","DEFAULT_UPLOAD_MAX_CONCURRENCY","OAUTH_ENDPOINT_DEVICE_CODE","OAUTH_ENDPOINT_TOKEN","OAUTH_ENDPOINT_USER_INFO","API_ENDPOINT_REGISTER_TEMPLATE"]}