├── .github ├── dependabot.yml └── workflows │ ├── build.yml │ └── release.yml ├── .gitignore ├── .vscode └── settings.json ├── LICENSE ├── README.md ├── nestia.config.ts ├── package.json ├── prettier.config.js ├── src ├── ExperimentalRoute.ts ├── Placeholder.ts ├── RouteIcon.ts ├── SecretKey.ts ├── SelectBenchmark.ts └── index.ts ├── test ├── TestGlobal.ts ├── controllers │ ├── BbsArticleController.ts │ ├── BbsArticleModule.ts │ └── IBbsArticle.ts ├── features │ ├── test_experimental_route.ts │ ├── test_placeholder.ts │ ├── test_route_icon.ts │ ├── test_secret_key.ts │ ├── test_secret_scopes.ts │ └── test_select_benchmark.ts ├── index.ts └── tsconfig.json └── tsconfig.json /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "npm" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | open-pull-requests-limit: 25 8 | # versioning-strategy: increase 9 | allow: 10 | - dependency-name: "@nestjs/*" 11 | - dependency-name: "@nestia/*" 12 | - dependency-name: "nestia" 13 | - dependency-name: "typia" 14 | - dependency-name: "typescript" 15 | - dependency-name: "ts-node" 16 | - dependency-name: "ts-patch" 17 | groups: 18 | NestJS: 19 | patterns: 20 | - "@nestjs/*" 21 | Ecosystem: 22 | patterns: 23 | - "@samchon/openapi" 24 | - "@nestia/*" 25 | - "@wrtnlabs/*" 26 | - "nestia" 27 | - "typia" 28 | Builder: 29 | patterns: 30 | - "typescript" 31 | - "ts-node" 32 | - "ts-patch" 33 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | on: 3 | pull_request: 4 | paths: 5 | - 'src/**' 6 | - 'test/**' 7 | - 'package.json' 8 | - '.github/workflows/build.yml' 9 | jobs: 10 | Ubuntu: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: actions/setup-node@v4 15 | with: 16 | node-version: 20.x 17 | - uses: pnpm/action-setup@v2 18 | with: 19 | version: 8 20 | - run: pnpm install 21 | - run: pnpm run build 22 | - run: pnpm run test -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | # author: elliot-huffman 2 | name: release 3 | on: 4 | release: 5 | types: [created] 6 | jobs: 7 | publish: 8 | runs-on: ubuntu-latest 9 | permissions: 10 | id-token: write 11 | contents: none 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: actions/setup-node@v4 15 | with: 16 | node-version: 20.x 17 | - uses: pnpm/action-setup@v2 18 | with: 19 | version: 8 20 | - name: Install dependencies 21 | run: pnpm install 22 | - name: Build 23 | run: pnpm run build 24 | - name: Test 25 | run: pnpm run test 26 | - name: Publish to npm 27 | run: npm publish --provenance 28 | env: 29 | NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | lib/ 3 | node_modules/ 4 | 5 | package-lock.json 6 | pnpm-lock.yaml -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.tabSize": 2, 3 | "[javascript][typescript]": { 4 | "editor.formatOnSave": true, 5 | "editor.defaultFormatter": "esbenp.prettier-vscode", 6 | "editor.codeActionsOnSave": { 7 | "source.fixAll.eslint": "explicit" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Wrtn Technologies 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `@wrtn/decorators` 2 | 스튜디오 프로젝트를 위한 NestJS 디코레이터 모음. 3 | 4 | ```bash 5 | npm i @wrtn/decorators 6 | ``` 7 | 8 | 9 | 10 | 11 | ## `Placeholder` 12 | ```typescript 13 | import { Placeholder } from "@wrtn/decorators"; 14 | import { tags } from "typia"; 15 | 16 | export interface Something { 17 | /** 18 | * 고객의 이름. 19 | * 20 | * @title 이름 21 | */ 22 | name: string & Placeholder<"이름을 입력해주세요.">; 23 | 24 | /** 25 | * 고객의 생년월일. 26 | * 27 | * @title 생년월일 28 | */ 29 | birthdate: string & 30 | tags.Format<"date"> & 31 | Placeholder<"생년월일을 입력해주세요. 형식은 YYYY-MM-DD 입니다.">; 32 | 33 | flag: number & Placeholder<"Something">; 34 | } 35 | ``` 36 | 37 | - [💻 JSON Schema Playground](https://typia.io/playground/?script=JYWwDg9gTgLgBDAnmYBDANHA3g1BzAZzgF84AzKCEOAIiRVRoG4AoF+gUzgAUAbVAMYcAFhF4ATDlAA8ANVS8Arlw4APGBwB24ogRhRgmvAD44AXlyEAdABV8AIVQEO0rCzi4oeDjABctACMIMQ5UTRo4AB9aTUUQAKkI6Jo9AyNmdzgAa0NxfxowfiFRCUTWDwA3BWV-eSUOcrgCAWEOEFR-Nw8PGlUAWgB3WE0+wsERMUkoGlrqhsziVmJjVhZDDSgycbgAZSofYUM8bEyAegAqc8y4c7hAA5rAXBrADXG4QBdxwBDOq2ur7tuAARgwBgvC4H2+p0ymlQIA4-lSRzgADIeEUJqUZDQAOoGDRwRAQRRQOBQmFWGgrNgeC4-Dy3R4vQC7A4ARRsAK2OAH3Gvr9vnAAUCQXBmezwZkAsBYMJxKgNHD9AjEddLAQrAAxaDtGDSGiSjTkpEKvjjEpTTXYoFcfGEuCi8XajhWOA2VrkNVSuDAIgATS9Hr6AFlfX0ACKBskUzJkfh4fyxeJSJEow2TKSavYwmCHdIU4hsehoKwAKwIEE0VlQYEKwAEUuAxekAG1UwcjgBdYwACgAlEwgA) 38 | 39 | `boolean` 이나 `number` 및 `string` 타입을 부여할 때, 위와 같이 `Placeholder` 타입을 `intersection (&)` 으로 결합해주면, JSON Schema 에 `x-wrtn-placeholder` 속성이 추가된다. 40 | 41 | 만일 위와 같은 JSON Schema customizer 가 필요하다면, 아래 문서를 보고 참고하여, 새로운 JSON Schema customizer 타입을 만들어주도록 하자. 그리고 새로이 추가한 커스텀 속성에 대하여, inspector 개발자들에게 전파하도록 한다. 42 | 43 | - https://typia.io/docs/json/schema/#customization 44 | 45 | 46 | 47 | 48 | ## `SecretKey` 49 | ```typescript 50 | export interface IGoogleDriveFileUploader { 51 | token: string & SecretKey<"google-auth-key">; 52 | location: string; 53 | file: File; 54 | } 55 | ``` 56 | 57 | - [💻 JSON Schema Playground](https://typia.io/playground/?script=JYWwDg9gTgLgBDAnmYBDANHA3g1BzAZzgF84AzKCEOAIiRVRoG4AoF+gUzgGUOBjKBxgBpDogA8LOHABqqADYBXLhwAeMDgDsAJkQIwowTXnRSefCGA5E1GnUUU6OZIx21wAPnE0cAbhyhPOH1DYwBtAF04AF5vPwDTAD4Y3EIAOgAVfAAhVAIOcSwzGFQoPCEALloQozxmMwBrI20qml4BIVFEeulfBWUqx21nV21WaQI+AAsOEFQqoulpGlUAWgB3WE1V-I6YVYaxGiq5JQ5xpZWNrZ3+QX3Jy2tj8yeCC+JWYkTWFiMNKBkVB8LgASQA4hAIHh5BwACKGfwAMWAsIAqmB5BBUMNAosEBBDpoqjVjHAAGQ8O6dMTiGh4KEwjirVCKGBTA5HTBhGiCHE0TA0TbADQ0CI-MxYvioGDACDE4IGWoXFywqoo2FfNj0NBpABWBHlaVQYExwGlsvl4jCEMZsIRwGRqI4GKxOIC4oAFABKJhAA) 58 | 59 | `SecretKey` 타입은 스튜디오의 워크플로우 프로그램에서 특정 커넥터 함수를 실행함에 있어, 어떠한 속성 내지 파라미터가 외부 서비스의 secret key 를 필요로 할 때 사용하는 타입이다. 만일 해당 서비스가 OAuth 의 `scopes` 에 대한 제약 또한 가해진 경우, 두 번째 template argument `string[]` 타입을 설정해주면 된다. 60 | 61 | 위 예제 코드 `IGoogleDriveFileUploader` 와 같이 구글 드라이브에 파일을 업로드하는 경우, DTO 수준에서 구글 사용자 인증 토큰이 필요하기 마련이다. 그리고 구글처럼 각각이 발생되는 사용자 인증 토큰에 OAuth 의 `scopes` 라는 제약을 두어 그 권한을 깐깐하게 관리하는 경우, 두 번째 파라미터 `string[]` 또한 그에 맞추어 설정해줘야 한다. 62 | 63 | 64 | 65 | 66 | ## `@RouteIcon()` 67 | ```typescript 68 | export function RouteIcon(uri: string): MethodDecorator; 69 | ``` 70 | 71 | Controller 메서드에 `@RouteIcon()` 을 적용하면, 아이콘을 적용할 수 있다. 72 | 73 | `@RouteIcon(url: string)` 에 입력한 URL 주소는 스웨거 문서의 해당 endpoint 부에, `ISwaggerRoute["x-wrtn-icon"]` 속성으로 기입된다. 74 | 75 | 단, 본 디코레이터는 파라미터로 입력한 URL 값의 실존 여부를 검증하지 않으니, 이 점 주의하기 바란다. -------------------------------------------------------------------------------- /nestia.config.ts: -------------------------------------------------------------------------------- 1 | import { INestiaConfig } from "@nestia/sdk"; 2 | 3 | export const NESTIA_CONFIG: INestiaConfig = { 4 | input: ["test/TestController.ts"], 5 | swagger: { 6 | output: "test/swagger.json", 7 | beautify: true, 8 | }, 9 | }; 10 | export default NESTIA_CONFIG; 11 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@wrtnlabs/decorators", 3 | "version": "2.0.0", 4 | "description": "NestJS Decorators for Wrtn Technologies", 5 | "main": "lib/index.js", 6 | "typings": "lib/index.d.ts", 7 | "keywords": [], 8 | "author": "Wrtn Technologies", 9 | "license": "MIT", 10 | "dependencies": { 11 | "@samchon/openapi": "^3.0.0", 12 | "@wrtnlabs/schema": "^4.0.0", 13 | "typia": "^8.0.0" 14 | }, 15 | "peerDependencies": { 16 | "@nestia/core": ">=5.0.0 <6.0.0", 17 | "@nestia/sdk": ">=5.0.0 <6.0.0", 18 | "@samchon/openapi": ">=3.0.0 <4.0.0", 19 | "@wrtnlabs/schema": ">=4.0.0 <5.0.0", 20 | "typia": ">=8.0.0 <9.0.0" 21 | }, 22 | "devDependencies": { 23 | "@nestia/core": "^5.0.0", 24 | "@nestia/e2e": "^0.8.2", 25 | "@nestia/fetcher": "^5.0.0", 26 | "@nestia/sdk": "^5.0.0", 27 | "@nestjs/core": "^11.0.11", 28 | "@nestjs/common": "^11.0.11", 29 | "@nestjs/platform-express": "^11.0.11", 30 | "@trivago/prettier-plugin-sort-imports": "^5.2.2", 31 | "@types/jmespath": "^0.15.2", 32 | "@types/node": "^20.14.11", 33 | "chalk": "4.1.2", 34 | "jmespath": "^0.16.0", 35 | "nestia": "^7.0.0", 36 | "prettier": "^3.5.3", 37 | "rimraf": "^6.0.1", 38 | "ts-node": "^10.9.2", 39 | "ts-patch": "^3.3.0", 40 | "typescript": "~5.8.2", 41 | "typescript-transform-paths": "^3.5.3" 42 | }, 43 | "scripts": { 44 | "build": "npm run build:main && npm run build:test", 45 | "build:main": "rimraf lib && tsc", 46 | "build:test": "rimraf bin && tsc -p test/tsconfig.json", 47 | "dev": "npm run build:test -- --watch", 48 | "prepare": "ts-patch install", 49 | "prettier": "prettier src --write && prettier test --write", 50 | "test": "node bin/test" 51 | }, 52 | "includes": [ 53 | "lib", 54 | "src", 55 | "package.json", 56 | "README.md" 57 | ], 58 | "homepage": "https://github.com/wrtnio/decorators", 59 | "repository": { 60 | "type": "git", 61 | "url": "https://github.com/wrtnio/decorators" 62 | }, 63 | "bugs": { 64 | "url": "https://github.com/samchon/typia/issues" 65 | }, 66 | "publishConfig": { 67 | "registry": "https://registry.npmjs.org/" 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: "typescript", 3 | printWidth: 80, 4 | semi: true, 5 | tabWidth: 2, 6 | trailingComma: "all", 7 | plugins: [require.resolve("@trivago/prettier-plugin-sort-imports")], 8 | importOrder: ["", "^[./]"], 9 | importOrderSeparation: true, 10 | importOrderSortSpecifiers: true, 11 | importOrderParserPlugins: ["decorators-legacy", "typescript", "jsx"], 12 | }; 13 | -------------------------------------------------------------------------------- /src/ExperimentalRoute.ts: -------------------------------------------------------------------------------- 1 | import { SwaggerCustomizer } from "@nestia/core"; 2 | import "@wrtnlabs/schema"; 3 | 4 | /** 5 | * Experimental API marking. 6 | * 7 | * This decorator marks the API as experimental, so that LLM function calling schema composer 8 | * excludes the API in the production environments. Of course, test and development environments 9 | * are not affected by this decorator. 10 | * 11 | * In other words, if you adjust the `@ExperimentalRoute()` decorator to the API, the API never 12 | * participates in the LLM function calling in the production environments. Only test and 13 | * development environments can access the API through the LLM function calling. 14 | * 15 | * @returns Method decorator 16 | * @author Samchon 17 | */ 18 | export function ExperimentalRoute(): MethodDecorator { 19 | return function ( 20 | target: Object, 21 | key: string | symbol | undefined, 22 | descriptor: PropertyDescriptor, 23 | ) { 24 | return SwaggerCustomizer((props) => { 25 | props.route["x-wrtn-experimental"] = true; 26 | })(target, key!, descriptor); 27 | }; 28 | } 29 | -------------------------------------------------------------------------------- /src/Placeholder.ts: -------------------------------------------------------------------------------- 1 | import "@wrtnlabs/schema"; 2 | import { tags } from "typia"; 3 | 4 | /** 5 | * JSON Schema에 `x-wrtn-placeholder` 를 추가해주는 타입. 6 | * 7 | * 아래와 같이 원시 원자 타입들에 대하여 사용 가능하다. 8 | * 9 | * - `boolean & Placeholder<"Some placeholder text">` 10 | * - `number & Placeholder<"Some placeholder text">` 11 | * - `string & Placeholder<"Some placeholder text">` 12 | * 13 | * @reference https://typia.io/docs/json/schema/#customization 14 | * @author Samchon 15 | */ 16 | export type Placeholder = tags.TagBase<{ 17 | target: "boolean" | "number" | "string"; 18 | kind: "placeholder"; 19 | value: Value; 20 | schema: { 21 | "x-wrtn-placeholder": Value; 22 | }; 23 | }>; 24 | -------------------------------------------------------------------------------- /src/RouteIcon.ts: -------------------------------------------------------------------------------- 1 | import { SwaggerCustomizer } from "@nestia/core"; 2 | import "@wrtnlabs/schema"; 3 | import typia, { tags } from "typia"; 4 | 5 | export function RouteIcon(url: string & tags.Format<"uri">): MethodDecorator { 6 | typia.assert(url); 7 | return function ( 8 | target: Object, 9 | key: string | symbol, 10 | descriptor: PropertyDescriptor, 11 | ) { 12 | return SwaggerCustomizer((props) => { 13 | props.route["x-wrtn-icon"] = url; 14 | })(target, key, descriptor); 15 | }; 16 | } 17 | -------------------------------------------------------------------------------- /src/SecretKey.ts: -------------------------------------------------------------------------------- 1 | import "@wrtnlabs/schema"; 2 | import { tags } from "typia"; 3 | 4 | /** 5 | * JSON Scheme에 `x-secret-key` 를 추가해주는 타입. 6 | * 7 | * 아래와 같이 원시 원자 타입들에 대하여 사용 가능하다. 8 | * 9 | * - `string & SecretKey<"Some secret">` 10 | * 11 | * @template Value Secret Key, 어떤 종류의 인증키가 필요한가 12 | * @template Scopes 필요한 스코프 리스트, 스코프가 필요없으면 빈 배열을 사용한다 13 | * @reference https://typia.io/docs/json/schema/#customization 14 | * @author Jake 15 | */ 16 | export type SecretKey< 17 | Value extends string, 18 | Scopes extends undefined | never | string[] = never, 19 | > = tags.TagBase<{ 20 | target: "string"; 21 | kind: "SecretKey"; 22 | value: undefined; 23 | schema: { 24 | "x-wrtn-secret-key": Value; 25 | "x-wrtn-secret-scopes": Scopes; 26 | }; 27 | }>; 28 | -------------------------------------------------------------------------------- /src/SelectBenchmark.ts: -------------------------------------------------------------------------------- 1 | import { SwaggerCustomizer } from "@nestia/core"; 2 | import "@wrtnlabs/schema"; 3 | 4 | export function SelectBenchmark(keyword: string | string[]): MethodDecorator { 5 | return function ( 6 | target: any, 7 | key: string | symbol, 8 | descriptor: PropertyDescriptor, 9 | ) { 10 | return SwaggerCustomizer((props) => { 11 | props.route["x-wrtn-function-select-benchmarks"] ??= []; 12 | props.route["x-wrtn-function-select-benchmarks"].push( 13 | ...(Array.isArray(keyword) ? keyword : [keyword]), 14 | ); 15 | })(target, key, descriptor); 16 | }; 17 | } 18 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import "@wrtnlabs/schema"; 2 | 3 | export * from "./ExperimentalRoute"; 4 | export * from "./Placeholder"; 5 | export * from "./RouteIcon"; 6 | export * from "./SecretKey"; 7 | export * from "./SelectBenchmark"; 8 | -------------------------------------------------------------------------------- /test/TestGlobal.ts: -------------------------------------------------------------------------------- 1 | export class TestGlobal { 2 | public static getArguments(type: string): string[] { 3 | const from: number = process.argv.indexOf(`--${type}`) + 1; 4 | if (from === 0) return []; 5 | const to: number = process.argv 6 | .slice(from) 7 | .findIndex((str) => str.startsWith("--"), from); 8 | return process.argv.slice( 9 | from, 10 | to === -1 ? process.argv.length : to + from, 11 | ); 12 | } 13 | } 14 | 15 | interface IEnvironments { 16 | CHATGPT_API_KEY?: string; 17 | CLAUDE_API_KEY?: string; 18 | GEMINI_API_KEY?: string; 19 | LLAMA_API_KEY?: string; 20 | } 21 | -------------------------------------------------------------------------------- /test/controllers/BbsArticleController.ts: -------------------------------------------------------------------------------- 1 | import { TypedBody, TypedParam, TypedRoute } from "@nestia/core"; 2 | import { Controller } from "@nestjs/common"; 3 | import { 4 | ExperimentalRoute, 5 | Placeholder, 6 | RouteIcon, 7 | SecretKey, 8 | SelectBenchmark, 9 | } from "@wrtnlabs/decorators"; 10 | import typia, { tags } from "typia"; 11 | 12 | import { IBbsArticle } from "./IBbsArticle"; 13 | 14 | @Controller("bbs/articles") 15 | export class BbsArticleController { 16 | @ExperimentalRoute() 17 | @TypedRoute.Patch("details") 18 | public async details(): Promise { 19 | return typia.random(); 20 | } 21 | 22 | @SelectBenchmark("List up articles") 23 | @TypedRoute.Patch() 24 | public async index(): Promise { 25 | return typia.random(); 26 | } 27 | 28 | @TypedRoute.Get(":id") 29 | public async at( 30 | @TypedParam("id") id: string & tags.Format<"uuid">, 31 | ): Promise { 32 | id; 33 | return typia.random(); 34 | } 35 | 36 | @SelectBenchmark(["I wanna create an article", "Write an article"]) 37 | @RouteIcon("https://example.com/write.icon.png") 38 | @TypedRoute.Post() 39 | public async create( 40 | @TypedBody() input: IBbsArticle.ICreate, 41 | ): Promise { 42 | input; 43 | return typia.random(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /test/controllers/BbsArticleModule.ts: -------------------------------------------------------------------------------- 1 | import { Module } from "@nestjs/common"; 2 | 3 | import { BbsArticleController } from "./BbsArticleController"; 4 | 5 | @Module({ controllers: [BbsArticleController] }) 6 | export class BbsArticleModule {} 7 | -------------------------------------------------------------------------------- /test/controllers/IBbsArticle.ts: -------------------------------------------------------------------------------- 1 | import { Placeholder, SecretKey } from "@wrtnlabs/decorators"; 2 | import { tags } from "typia"; 3 | 4 | export interface IBbsArticle { 5 | id: string & tags.Format<"uuid">; 6 | writer: string; 7 | title: string; 8 | body: string; 9 | created_at: string & tags.Format<"date-time">; 10 | } 11 | export namespace IBbsArticle { 12 | export interface ICreate { 13 | title: string & Placeholder<"Write title of the article">; 14 | body: string & Placeholder<"Write content body of the article">; 15 | secretKey: string & SecretKey<"bbs", ["write"]>; 16 | } 17 | export interface ISummary { 18 | id: string & tags.Format<"uuid">; 19 | writer: string; 20 | title: string; 21 | created_at: string & tags.Format<"date-time">; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /test/features/test_experimental_route.ts: -------------------------------------------------------------------------------- 1 | import { TestValidator } from "@nestia/e2e"; 2 | import { OpenApi } from "@samchon/openapi"; 3 | import "@wrtnlabs/schema"; 4 | 5 | export const test_experimental_route = (document: OpenApi.IDocument): void => { 6 | TestValidator.equals("@ExperimentalRoute()")( 7 | document.paths?.["/bbs/articles/details"].patch?.["x-wrtn-experimental"], 8 | )(true); 9 | }; 10 | -------------------------------------------------------------------------------- /test/features/test_placeholder.ts: -------------------------------------------------------------------------------- 1 | import { TestValidator } from "@nestia/e2e"; 2 | import { OpenApi } from "@samchon/openapi"; 3 | import "@wrtnlabs/schema"; 4 | import typia from "typia"; 5 | 6 | export const test_placeholder = (document: OpenApi.IDocument): void => { 7 | const schema: OpenApi.IJsonSchema.IObject = 8 | typia.assert( 9 | document.components.schemas?.["IBbsArticle.ICreate"], 10 | ); 11 | TestValidator.equals("Placeholder")( 12 | schema.properties?.title?.["x-wrtn-placeholder"], 13 | )("Write title of the article"); 14 | }; 15 | -------------------------------------------------------------------------------- /test/features/test_route_icon.ts: -------------------------------------------------------------------------------- 1 | import { TestValidator } from "@nestia/e2e"; 2 | import { OpenApi } from "@samchon/openapi"; 3 | import "@wrtnlabs/schema"; 4 | 5 | export const test_route_icon = (document: OpenApi.IDocument): void => { 6 | TestValidator.equals("@RouteIcon()")( 7 | document.paths?.["/bbs/articles"]?.post?.["x-wrtn-icon"], 8 | )("https://example.com/write.icon.png"); 9 | }; 10 | -------------------------------------------------------------------------------- /test/features/test_secret_key.ts: -------------------------------------------------------------------------------- 1 | import { TestValidator } from "@nestia/e2e"; 2 | import { OpenApi } from "@samchon/openapi"; 3 | import "@wrtnlabs/schema"; 4 | import typia from "typia"; 5 | 6 | export const test_secret_key = (document: OpenApi.IDocument): void => { 7 | const object: OpenApi.IJsonSchema.IObject = 8 | typia.assert( 9 | document.components.schemas?.["IBbsArticle.ICreate"], 10 | ); 11 | const string: OpenApi.IJsonSchema.IString = 12 | typia.assert(object.properties?.secretKey); 13 | TestValidator.equals("SecretKey")(string["x-wrtn-secret-key"])("bbs"); 14 | }; 15 | -------------------------------------------------------------------------------- /test/features/test_secret_scopes.ts: -------------------------------------------------------------------------------- 1 | import { TestValidator } from "@nestia/e2e"; 2 | import { OpenApi } from "@samchon/openapi"; 3 | import "@wrtnlabs/schema"; 4 | import typia from "typia"; 5 | 6 | export const test_secret_scopes = (document: OpenApi.IDocument): void => { 7 | const object: OpenApi.IJsonSchema.IObject = 8 | typia.assert( 9 | document.components.schemas?.["IBbsArticle.ICreate"], 10 | ); 11 | const string: OpenApi.IJsonSchema.IString = 12 | typia.assert(object.properties?.secretKey); 13 | TestValidator.equals("SecretKey")( 14 | string["x-wrtn-secret-scopes"], 15 | )(["write"]); 16 | }; 17 | -------------------------------------------------------------------------------- /test/features/test_select_benchmark.ts: -------------------------------------------------------------------------------- 1 | import { TestValidator } from "@nestia/e2e"; 2 | import { OpenApi } from "@samchon/openapi"; 3 | import "@wrtnlabs/schema"; 4 | 5 | export const test_select_benchmark = (document: OpenApi.IDocument): void => { 6 | TestValidator.equals("@SelectBenchmark(string)")( 7 | document.paths?.["/bbs/articles"]?.patch?.[ 8 | "x-wrtn-function-select-benchmarks" 9 | ], 10 | )(["List up articles"]); 11 | 12 | TestValidator.equals("@SelectBenchmark(string[])")( 13 | document.paths?.["/bbs/articles"]?.post?.[ 14 | "x-wrtn-function-select-benchmarks" 15 | ], 16 | )(["I wanna create an article", "Write an article"]); 17 | }; 18 | -------------------------------------------------------------------------------- /test/index.ts: -------------------------------------------------------------------------------- 1 | import { DynamicExecutor } from "@nestia/e2e"; 2 | import { NestiaSwaggerComposer } from "@nestia/sdk"; 3 | import { INestApplication } from "@nestjs/common"; 4 | import { NestFactory } from "@nestjs/core"; 5 | import { OpenApi } from "@samchon/openapi"; 6 | import "@wrtnlabs/schema"; 7 | import chalk from "chalk"; 8 | 9 | import { TestGlobal } from "./TestGlobal"; 10 | import { BbsArticleModule } from "./controllers/BbsArticleModule"; 11 | 12 | const main = async () => { 13 | // MOUNT SWAGGER DOCUMENT 14 | const app: INestApplication = await NestFactory.create(BbsArticleModule, { 15 | logger: false, 16 | }); 17 | const document: OpenApi.IDocument = OpenApi.convert( 18 | await NestiaSwaggerComposer.document(app, {}), 19 | ); 20 | 21 | // DO TEST 22 | const include: string[] = TestGlobal.getArguments("include"); 23 | const exclude: string[] = TestGlobal.getArguments("exclude"); 24 | const report: DynamicExecutor.IReport = await DynamicExecutor.validate({ 25 | prefix: "test_", 26 | location: __dirname + "/features", 27 | extension: __filename.substring(__filename.length - 2), 28 | parameters: () => [document], 29 | onComplete: (exec) => { 30 | const trace = (str: string) => 31 | console.log(` - ${chalk.green(exec.name)}: ${str}`); 32 | if (exec.value === false) trace(chalk.gray("Pass")); 33 | else if (exec.error === null) { 34 | const elapsed: number = 35 | new Date(exec.completed_at).getTime() - 36 | new Date(exec.started_at).getTime(); 37 | trace(`${chalk.yellow(elapsed.toLocaleString())} ms`); 38 | } else trace(chalk.red(exec.error.name)); 39 | }, 40 | filter: (name) => 41 | (include.length ? include.some((str) => name.includes(str)) : true) && 42 | (exclude.length ? exclude.every((str) => !name.includes(str)) : true), 43 | }); 44 | 45 | // REPORT EXCEPTIONS 46 | const exceptions: Error[] = report.executions 47 | .filter((exec) => exec.error !== null) 48 | .map((exec) => exec.error!); 49 | if (exceptions.length === 0) { 50 | console.log("Success"); 51 | console.log("Elapsed time", report.time.toLocaleString(), `ms`); 52 | } else { 53 | for (const exp of exceptions) console.log(exp); 54 | console.log("Failed"); 55 | console.log("Elapsed time", report.time.toLocaleString(), `ms`); 56 | } 57 | await app.close(); 58 | if (exceptions.length) process.exit(-1); 59 | }; 60 | main(); 61 | -------------------------------------------------------------------------------- /test/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "target": "ES2015", 5 | "outDir": "../bin", 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "paths": { 9 | "@wrtnlabs/decorators": ["../src/index.ts"], 10 | "@wrtnlabs/decorators/lib/*": ["../src/*"] 11 | }, 12 | "plugins": [ 13 | { "transform": "typescript-transform-paths" }, 14 | { "transform": "typia/lib/transform" }, 15 | { "transform": "@nestia/core/lib/transform" }, 16 | { "transform": "@nestia/sdk/lib/transform" } 17 | ] 18 | }, 19 | "include": ["../src", "./"], 20 | } 21 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | /* Projects */ 5 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 6 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 7 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 8 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 9 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 10 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 11 | /* Language and Environment */ 12 | "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 13 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 14 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ 15 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 16 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 17 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 18 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 19 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 20 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 21 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 22 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 23 | /* Modules */ 24 | "module": "commonjs" /* Specify what module code is generated. */, // "rootDir": "./", /* Specify the root folder within your source files. */ 25 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ 26 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 27 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 28 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 29 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 30 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 31 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 32 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 33 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ 34 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ 35 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ 36 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ 37 | // "resolveJsonModule": true, /* Enable importing .json files. */ 38 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ 39 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 40 | /* JavaScript Support */ 41 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 42 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 43 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 44 | /* Emit */ 45 | "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */, 46 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 47 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 48 | "sourceMap": true /* Create source map files for emitted JavaScript files. */, 49 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 50 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 51 | "outDir": "./lib" /* Specify an output folder for all emitted files. */, 52 | // "removeComments": true, /* Disable emitting comments. */ 53 | // "noEmit": true, /* Disable emitting files from a compilation. */ 54 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 55 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 56 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 57 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 58 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 59 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 60 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 61 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 62 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 63 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 64 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 65 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 66 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 67 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 68 | /* Interop Constraints */ 69 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 70 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ 71 | "allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */, 72 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 73 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */ /* Type Checking */, 74 | "strict": true /* Enable all strict type-checking options. */, // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 75 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 76 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 77 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 78 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 79 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 80 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 81 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 82 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 83 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 84 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 85 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 86 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 87 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 88 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 89 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 90 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 91 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 92 | /* Completeness */ 93 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 94 | "skipLibCheck": true /* Skip type checking all .d.ts files. */, 95 | }, 96 | "include": ["src"] 97 | } 98 | --------------------------------------------------------------------------------