UNPKG

init-project-ts

Version:
457 lines (328 loc) 21.2 kB
#!/usr/bin/env node var U=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var B=U((Ve,z)=>{z.exports={name:"init-project-ts",version:"1.4.0",description:"Init fast project typescript",scripts:{test:"vitest && node ./test/index.js",build:"tsup",tsx:"tsx watch ./tsx.ts",start:"node ./dist/src/index.js",publish_npm:"npm run build && npm publish --access public"},homepage:"https://github.com/damartripamungkas/init-project-ts",repository:{type:"git",url:"https://github.com/damartripamungkas/init-project-ts.git"},bugs:{url:"https://github.com/damartripamungkas/init-project-ts/issues"},keywords:["init-project-typescript","init-project-ts","i-p-t","ipt","typescript","node","bun","backend","frontend","browser"],bin:"./dist/src/index.js",main:"./dist/src/index.js",module:"./dist/src/index.mjs",types:"./dist/src/index.d.ts",files:["dist"],author:"damartripamungkas",license:"MIT",devDependencies:{"@types/node":"^22.3.0","@types/prompts":"^2.4.9","@typescript-eslint/eslint-plugin":"^8.14.0","@typescript-eslint/parser":"^8.14.0",eslint:"^9.9.0",tsup:"^8.2.4",tsx:"^4.19.2",vitest:"^2.1.0"},dependencies:{ora:"^8.0.1",prompts:"^2.4.2"}}});import u from"prompts";import{join as A}from"node:path";import{execSync as f}from"node:child_process";import{existsSync as G,mkdirSync as V,readFileSync as Y,rmSync as H,writeFileSync as K}from"node:fs";import{basename as W}from"node:path";var n={pathRoot:"",projectName:W(process.cwd()),projectRuntime:""};var b={filename:"package.json",command:()=>"",content:({previousContent:e})=>{let{projectName:t,projectRuntime:a}=n,o={name:t,version:"1.0.0",description:"",type:"commonjs",scripts:{build:"tsup",test:"vitest",dev:"tsx watch ./src/index.ts",start:"node ./dist/src/index.js",publish_npm:"npm run build && npm publish"},generator:"init-project-ts",homepage:`https://github.com/{USERNAME}/${t}`,repository:{type:"git",url:`https://github.com/{USERNAME}/${t}.git`},bugs:{url:`https://github.com/{USERNAME}/${t}/issues`},keywords:[],main:"./dist/src/index.js",module:"./dist/src/index.mjs",types:"./dist/src/index.d.ts",files:["dist"],author:"{YOUR_NAME}",license:"MIT",devDependencies:{},dependencies:{}};return a=="bun"&&(o.type="module",o.scripts.test="bun test --watch",o.scripts.dev="bun --watch ./src/index.ts",o.scripts.start="bun ./src/index.ts"),JSON.stringify(o,null,2)}};var v={filename:".eslintrc.json",command:()=>"npm init @eslint/config --force --save-dev",content:({previousContent:e})=>(e.rules={"@typescript-eslint/no-explicit-any":0},JSON.stringify(e,null,2))};var x={filename:".gitignore",command:()=>"",content:({previousContent:e})=>`node_modules dist .encore encore.gen.go encore.gen.cue /.encore node_modules /encore.gen # Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore # Logs logs _.log npm-debug.log_ yarn-debug.log* yarn-error.log* lerna-debug.log* .pnpm-debug.log* # Caches .cache # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json # Runtime data pids _.pid _.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # Snowpack dependency directory (https://snowpack.dev/) web_modules/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Optional stylelint cache .stylelintcache # Microbundle cache .rpt2_cache/ .rts2_cache_cjs/ .rts2_cache_es/ .rts2_cache_umd/ # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variable files .env .env.development.local .env.test.local .env.production.local .env.local # parcel-bundler cache (https://parceljs.org/) .parcel-cache # Next.js build output .next out # Nuxt.js build / generate output .nuxt dist # Gatsby files # Comment in the public line in if your project uses Gatsby and not Next.js # https://nextjs.org/blog/next-9-1#public-directory-support # public # vuepress build output .vuepress/dist # vuepress v2.x temp and cache directory .temp # Docusaurus cache and generated files .docusaurus # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # TernJS port file .tern-port # Stores VSCode versions used for testing VSCode extensions .vscode-test # yarn v2 .yarn/cache .yarn/unplugged .yarn/build-state.yml .yarn/install-state.gz .pnp.* # IntelliJ based IDEs .idea # Finder (MacOS) folder config .DS_Store`};var w={filename:".prettierrc",command:()=>"",content:({previousContent:e})=>JSON.stringify({overrides:[{files:"*.json",options:{tabWidth:2,printWidth:200}},{files:"*.{ts,mts}",options:{printWidth:200,tabWidth:2,useTabs:!1,semi:!1,arrowParens:"always",trailingComma:"none",bracketSameLine:!1}},{files:"*.js",options:{printWidth:200,tabWidth:2,useTabs:!1,semi:!1,trailingComma:"none",arrowParens:"always",bracketSameLine:!1}},{files:"*.md",options:{printWidth:400,tabWidth:2,useTabs:!1,semi:!1,trailingComma:"none",arrowParens:"always",bracketSameLine:!1}}]},null,2)};var C={filename:"README.md",command:()=>"",content:({previousContent:e})=>{let{projectName:t}=n;return`<h1 align="center">${t}</h1>`}};var j={filename:"CONTRIBUTING.md",command:()=>"",content:({previousContent:e})=>`# Contributing When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change. Please note we have a code of conduct, please follow it in all your interactions with the project. ## Pull Request Process 1. Ensure any install or build dependencies are removed before the end of the layer when doing a build. 2. Update the README.md with details of changes to the interface, this includes new environment variables, exposed ports, useful file locations and container parameters. 3. Increase the version numbers in any examples files and the README.md to the new version that this Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). 4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you do not have permission to do that, you may request the second reviewer to merge it for you. ## Code of Conduct ### Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ### Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ### Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ### Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ### Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [INSERT EMAIL ADDRESS]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ### Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/`};var k={filename:"CODE_OF_CONDUCT.md",command:()=>"",content:({previousContent:e})=>`# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at hahwul@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq`};var T={filename:"SECURITY.md",command:()=>"",content:({previousContent:e})=>`# Security Policy ## Supported Versions | Version | Supported | | ------- | ------------------ | | 1.x.x | :white_check_mark: | | 2.x.x | :white_check_mark: | ## Reporting a Vulnerability pull request`};var P={filename:"tsconfig.json",command:()=>"",content:({previousContent:e})=>{let{projectRuntime:t}=n;return t=="bun"?JSON.stringify({compilerOptions:{lib:["ESNext","DOM"],target:"ESNext",module:"ES2022",moduleDetection:"force",jsx:"react-jsx",allowJs:!0,moduleResolution:"bundler",allowImportingTsExtensions:!0,verbatimModuleSyntax:!0,noEmit:!0,strict:!0,skipLibCheck:!0,noFallthroughCasesInSwitch:!0,noUnusedLocals:!1,noUnusedParameters:!1,noPropertyAccessFromIndexSignature:!1}},null,2):JSON.stringify({compilerOptions:{target:"ESNext",module:"ES2022",moduleResolution:"Bundler",allowSyntheticDefaultImports:!0},include:["src/*.ts","src/**/*.ts","src/**/**/*.ts","**/*.ts"]},null,2)}};var S={filename:"tsup.config.ts",command:()=>"npm i tsup --force --save-dev",content:({previousContent:e})=>`import { defineConfig } from "tsup" export default defineConfig({ outDir: "./dist/src", entry: ["./src/index.ts"], format: ["cjs", "esm"], cjsInterop: false, dts: true, clean: true, minify: true }) `};var _={filename:"src/index.ts",command:()=>"",content:({previousContent:e})=>`import context from "./core/index" export default context `};var E={filename:"src/config/config.ts",command:()=>"",content:({previousContent:e})=>`import { join } from "node:path" import { readFileSync } from "node:fs" import { TypeConfig } from "../types/config"; const pathConfig = join(process.cwd(), "config", "config.json") export const getConfig = () => JSON.parse(readFileSync(pathConfig, { encoding: "utf8" })) export const config = getConfig()`};var R={filename:"src/libs/index.ts",command:()=>"",content:({previousContent:e})=>`const context = {} export { context } export default context`};var I={filename:"src/types/config.ts",command:()=>"",content:({previousContent:e})=>"export type TypeConfig = {}"};var O={filename:"src/utils/int.ts",command:()=>"",content:({previousContent:e})=>`type TypeInt = number | bigint export const formatToHex = (v: TypeInt) => { return "0x" + v.toString(16) } export const parseWithDecimals = (v: TypeInt | string, d: TypeInt) => { return BigInt(v) * BigInt(10) ** BigInt(d) }`};var N={filename:"src/core/index.ts",command:()=>"",content:({previousContent:e})=>`export default () => { return { id: 1, title: "Essence Mascara Lash Princess", description: "The Essence Mascara Lash Princess is a popular mascara known for its volumizing and lengthening effects. Achieve dramatic lashes with this long-lasting and cruelty-free formula.", category: "beauty", price: 9.99 } }`};var D={filename:"src/components/index.ts",command:()=>"",content:({previousContent:e})=>`const context = {} export {context} export default context`};var M={filename:"config/config.json",command:()=>"",content:({previousContent:e})=>JSON.stringify({})};import{writeFileSync as $}from"node:fs";import{join as q}from"node:path";var F={filename:"test/index.test.ts",command:()=>{let{projectRuntime:e}=n;return e=="bun"?"":"npm i vitest --force --save-dev"},content:({previousContent:e})=>{let{pathRoot:t,projectRuntime:a}=n;return a=="bun"?`import { describe, it, expect } from "bun:test" import contextDummy from "../src/index" describe("test file index.ts", () => { it("get context dummy", () => { const res = contextDummy() expect(res.id).toBe(1) }) })`:($(q(t,"vitest.config.mts"),`import { defineConfig } from "vitest/config" export default defineConfig({ test: { globals: true, // Mengaktifkan global test functions (describe, it, etc.) include: ["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"], // Pola file yang akan diuji exclude: ["node_modules/", "dist/", "coverage/"], // File/direktori yang dikecualikan dari pengujian environment: "node", // Lingkungan pengujian (node, jsdom, happy-dom, etc.) setupFiles: [], // File konfigurasi tambahan yang akan dimuat sebelum pengujian clearMocks: true, // Membersihkan mock/spy setelah setiap tes coverage: { enabled: false, // Mengaktifkan pengukuran coverage provider: "istanbul", // Provider coverage yang digunakan (istanbul, c8, etc.) reporter: "json" // Format laporan coverage }, restoreMocks: true, // Mengembalikan mock/spy ke state awal setelah tes mockReset: true, // Reset mock/spy ke state awal setelah tes maxConcurrency: 5, // Jumlah maksimal konkurensi yang digunakan silent: false, // Menyembunyikan log output watch: true, // Mengaktifkan mode watch logHeapUsage: true, // Mencatat penggunaan memori testTimeout: 0, // Batas waktu tes (dalam millisecond) hookTimeout: 10000, // Batas waktu hook (dalam millisecond) testNamePattern: "" // Filter tes berdasarkan nama } }) `,{encoding:"utf8"}),`import { describe, expect, test } from "vitest" import contextDummy from "../src/index" describe("test file index.ts", () => { test("get context dummy", () => { const res = contextDummy() expect(res.id).toBe(1) }) }) `)}};var l=[b,v,x,w,C,j,k,T,P,S,_,E,R,I,O,N,D,M,F];var Q=B(),X=async()=>{let{first:e}=await u({type:"confirm",name:"first",message:`\u{1F680} Welcome to init project typescript v${Q.version}, do you want continue?`});if(e===!1)return;let{two:t}=await u({type:"select",name:"two",message:"What is your runtime project typescript?",choices:[{title:"Node",value:"node"},{title:"Bun",value:"bun"}],initial:0});n.projectRuntime=t;let a=l.map((s,r)=>({type:"confirm",name:`val_${r}`,message:`Install file ${s.filename}?`,initial:!0})),o=[];return await u(a,{onCancel(s,r){process.exit()},onSubmit(s,r,i){let c=parseInt(s.name.toString().replace("val_","")),p={...l[c],answer:r};o.push(p)}}),o},J=async(e=process.cwd())=>{n.pathRoot=e,console.log(` \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D https://github.com/damartripamungkas/init-project-ts `);let t=(await import("ora")).default,a=await X();for(let r=0;r<a.length;r++){let{filename:i,command:c,content:p,answer:L}=a[r],g=c();if(L===!1)continue;if(g.length>1){let d=t(`Installing with command for ${i} `).start(),y=f(g,{stdio:"inherit"});d.succeed(`Success installing ${i}: ${y===null?"":y.toString()}`)}let h,m=A(e,i);if(G(m)===!0&&(h=JSON.parse(Y(m,{encoding:"utf8"}))),i.includes("/")){let d=i.slice(0,i.lastIndexOf("/"));V(d,{recursive:!0})}K(m,p({previousContent:h}),{encoding:"utf8"})}let o=a.find(r=>r.filename=="package.json"),{projectRuntime:s}=n;if(o.answer===!0&&([["node-bun","npm i @types/node --force --save-dev"],["node","npm i --save-dev tsx"]].forEach(i=>{let[c,p]=i;c.includes(s)!==!1&&f(p,{stdio:"inherit"})}),t(`Success install default command for runtime node `).succeed(),s=="bun")){["bun i","bun add -d @types/bun"].forEach(p=>{f(p,{stdio:"inherit"})}),t(`Success install default command for runtime bun `).succeed();let c=A(e,"package-lock.json");H(c,{force:!0,recursive:!0})}return t(`Success installing all files `).succeed(),!0};J();