init-project-ts
Version:
Init fast project typescript
457 lines (328 loc) • 21.7 kB
JavaScript
var V=Object.create;var x=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var K=Object.getPrototypeOf,Q=Object.prototype.hasOwnProperty;var X=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Z=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of H(t))!Q.call(e,r)&&r!==n&&x(e,r,{get:()=>t[r],enumerable:!(o=Y(t,r))||o.enumerable});return e};var w=(e,t,n)=>(n=e!=null?V(K(e)):{},Z(t||!e||!e.__esModule?x(n,"default",{value:e,enumerable:!0}):n,e));var q=X((Ye,ee)=>{ee.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"}}});var d=w(require("prompts")),h=require("path"),l=require("child_process"),c=require("fs");var C=require("path"),i={pathRoot:"",projectName:(0,C.basename)(process.cwd()),projectRuntime:""};var j={filename:"package.json",command:()=>"",content:({previousContent:e})=>{let{projectName:t,projectRuntime:n}=i,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 n=="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 k={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 T={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 P={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 S={filename:"README.md",command:()=>"",content:({previousContent:e})=>{let{projectName:t}=i;return`<h1 align="center">${t}</h1>`}};var _={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 E={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 R={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 I={filename:"tsconfig.json",command:()=>"",content:({previousContent:e})=>{let{projectRuntime:t}=i;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 O={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 N={filename:"src/index.ts",command:()=>"",content:({previousContent:e})=>`import context from "./core/index"
export default context
`};var D={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 M={filename:"src/libs/index.ts",command:()=>"",content:({previousContent:e})=>`const context = {}
export { context }
export default context`};var F={filename:"src/types/config.ts",command:()=>"",content:({previousContent:e})=>"export type TypeConfig = {}"};var B={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 A={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 J={filename:"src/components/index.ts",command:()=>"",content:({previousContent:e})=>`const context = {}
export {context}
export default context`};var L={filename:"config/config.json",command:()=>"",content:({previousContent:e})=>JSON.stringify({})};var U=require("fs");var W=require("path"),$={filename:"test/index.test.ts",command:()=>{let{projectRuntime:e}=i;return e=="bun"?"":"npm i vitest --force --save-dev"},content:({previousContent:e})=>{let{pathRoot:t,projectRuntime:n}=i;return n=="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)
})
})`:((0,U.writeFileSync)((0,W.join)(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 g=[j,k,T,P,S,_,E,R,I,O,N,D,M,F,B,A,J,L,$];var te=q(),ne=async()=>{let{first:e}=await(0,d.default)({type:"confirm",name:"first",message:`\u{1F680} Welcome to init project typescript v${te.version}, do you want continue?`});if(e===!1)return;let{two:t}=await(0,d.default)({type:"select",name:"two",message:"What is your runtime project typescript?",choices:[{title:"Node",value:"node"},{title:"Bun",value:"bun"}],initial:0});i.projectRuntime=t;let n=g.map((r,a)=>({type:"confirm",name:`val_${a}`,message:`Install file ${r.filename}?`,initial:!0})),o=[];return await(0,d.default)(n,{onCancel(r,a){process.exit()},onSubmit(r,a,s){let p=parseInt(r.name.toString().replace("val_","")),m={...g[p],answer:a};o.push(m)}}),o},z=async(e=process.cwd())=>{i.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,n=await ne();for(let a=0;a<n.length;a++){let{filename:s,command:p,content:m,answer:G}=n[a],y=p();if(G===!1)continue;if(y.length>1){let f=t(`Installing with command for ${s}
`).start(),v=(0,l.execSync)(y,{stdio:"inherit"});f.succeed(`Success installing ${s}: ${v===null?"":v.toString()}`)}let b,u=(0,h.join)(e,s);if((0,c.existsSync)(u)===!0&&(b=JSON.parse((0,c.readFileSync)(u,{encoding:"utf8"}))),s.includes("/")){let f=s.slice(0,s.lastIndexOf("/"));(0,c.mkdirSync)(f,{recursive:!0})}(0,c.writeFileSync)(u,m({previousContent:b}),{encoding:"utf8"})}let o=n.find(a=>a.filename=="package.json"),{projectRuntime:r}=i;if(o.answer===!0&&([["node-bun","npm i @types/node --force --save-dev"],["node","npm i --save-dev tsx"]].forEach(s=>{let[p,m]=s;p.includes(r)!==!1&&(0,l.execSync)(m,{stdio:"inherit"})}),t(`Success install default command for runtime node
`).succeed(),r=="bun")){["bun i","bun add -d @types/bun"].forEach(m=>{(0,l.execSync)(m,{stdio:"inherit"})}),t(`Success install default command for runtime bun
`).succeed();let p=(0,h.join)(e,"package-lock.json");(0,c.rmSync)(p,{force:!0,recursive:!0})}return t(`Success installing all files
`).succeed(),!0};z();