Commit e156167e authored by nanahira's avatar nanahira

first

parent 29033b7e
webpack.config.js
dist/*
build/*
*.js
/src/schemastery
\ No newline at end of file
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
/test
/dist/test
\ No newline at end of file
stages:
- build
- deploy
variables:
GIT_DEPTH: "1"
build:
stage: build
tags:
- linux
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
deploy_npm:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- apt update;apt -y install coreutils
- echo $NPMRC | base64 --decode > ~/.npmrc
- npm publish . || true
only:
- master
[submodule "src/schemastery"]
path = src/schemastery
url = https://github.com/Shigma/schemastery
/install-npm.sh
.git*
/data
/output
/config.yaml
.idea
.dockerignore
Dockerfile
/test
/dist/test
\ No newline at end of file
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
The MIT License (MIT)
Copyright (c) 2021 Nanahira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
export * from './src/def';
export * from './src/decorators';
#!/bin/bash
npm install --save-dev \
@types/node \
typescript \
'@typescript-eslint/eslint-plugin@^4.28.2' \
'@typescript-eslint/parser@^4.28.2 '\
'eslint@^7.30.0' \
'eslint-config-prettier@^8.3.0' \
'eslint-plugin-prettier@^3.4.0' \
prettier
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "schemastery-gen",
"description": "Decorator style of [Schemastery](https://github.com/Shigma/schemastery)",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"build": "tsc",
"start": "node dist/index.js"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/3rdeye/schemastery-gen.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/schemastery-gen/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/schemastery-gen",
"devDependencies": {
"@types/lodash": "^4.14.176",
"@types/node": "^16.11.7",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.1",
"prettier": "^2.4.1",
"schemastery": "^1.0.0",
"typescript": "^4.4.4"
},
"dependencies": {
"lodash": "^4.17.21",
"reflect-metadata": "^0.1.13",
"typed-reflector": "^1.0.5"
}
}
import { ClassType, SchemaOptions } from '../def/interfaces';
import { getStringFromNativeType } from '../utility/utility';
import { Metadata } from '../metadata/metadata';
import {
SetTransformer,
transformArray,
transformDict,
transformSingle,
} from '../utility/transformer';
import Schema from 'schemastery';
export function DefineSchema(options: SchemaOptions = {}): PropertyDecorator {
return (obj, key) => {
const nativeType = Reflect.getMetadata('design:type', obj, key);
const nativeTypeString = getStringFromNativeType(nativeType);
if (!options.type) {
if (nativeTypeString && nativeTypeString !== 'array') {
options.type =
nativeTypeString === 'class' ? nativeType : nativeTypeString;
} else {
options.type = 'any';
}
}
if (nativeTypeString === 'array') {
options.array = true;
}
if (
options.type &&
typeof options.type !== 'string' &&
typeof (options.type as Schema<any>).type === 'string'
) {
const cl = options.type as ClassType<any>;
let dec: PropertyDecorator;
if (options.dict) {
dec = SetTransformer((value) =>
transformDict(cl, value, options.array),
);
} else if (options.array) {
dec = SetTransformer((value) => transformArray(cl, value));
} else {
dec = SetTransformer((value) => transformSingle(cl, value));
}
dec(obj, key);
}
return Metadata.set('SchemaMeta', options, 'SchemaMetaKey')(obj, key);
};
}
export * from './define-property';
export * from './register';
import {
SchemaClassOptions,
SchemaOptions,
SchemaOptionsDict,
TypeFromClass,
} from '../def';
import Schema from 'schemastery';
import { reflector } from '../metadata/reflector';
import _ from 'lodash';
import { Metadata } from '../metadata/metadata';
function getBasePropertySchemaFromOptions(options: SchemaOptions) {
if (options.schema) {
return options.schema;
}
if (typeof options.type !== 'string') {
return schemaFromClass(options.type);
}
switch (options.type as string) {
case 'any':
return Schema.any();
case 'never':
return Schema.never();
case 'string':
return Schema.string();
case 'number':
return Schema.number();
case 'boolean':
return Schema.boolean();
case 'object':
return Schema.object({}, true);
default:
return Schema.any();
}
}
function applyOptionsToSchema(schema: Schema, options: SchemaClassOptions) {
if (options.required != undefined) {
schema.meta.required = options.required;
}
if (options.hidden != undefined) {
schema.meta.hidden = options.hidden;
}
if (options.default != undefined) {
schema.meta.default = options.default;
}
if (options.comment != undefined) {
schema.meta.comment = options.comment;
}
if (options.allowUnknown != undefined) {
schema.flag = options.allowUnknown;
}
if (options.desc != undefined) {
schema.desc = options.desc;
}
}
function getPropertySchemaFromOptions<PT>(options: SchemaOptions): Schema<PT> {
let schema = getBasePropertySchemaFromOptions(options);
if (options.dict) {
schema = Schema.dict(schema);
}
if (options.array) {
schema = Schema.array(schema);
}
applyOptionsToSchema(schema, options);
return schema;
}
function schemasFromDict<T>(dict: SchemaOptionsDict<T>): Schema<T> {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return Schema.object<T>(
_.mapValues(dict, (opt) => getPropertySchemaFromOptions(opt)),
);
}
function schemaOptionsFromClass<C extends { new (...args: any[]): any }>(
cl: C,
): SchemaOptionsDict<TypeFromClass<C>> {
const keys = reflector.getArray(
'SchemaMetaKey',
cl,
) as (keyof TypeFromClass<C> & (string | symbol))[];
if (!keys) {
return null;
}
const result: SchemaOptionsDict<TypeFromClass<C>> = {};
for (const key of keys) {
const option = reflector.get('SchemaMeta', cl, key);
result[key] = option;
}
return result;
}
export function schemaFromClass<C extends { new (...args: any[]): any }>(
cl: C,
): Schema<TypeFromClass<C>> {
let schema: Schema;
const optionsDict = schemaOptionsFromClass(cl);
if (!optionsDict) {
schema = Schema.object({}, true);
} else {
schema = schemasFromDict<TypeFromClass<C>>(optionsDict);
}
const classOptions = reflector.get('SchemaClassOptions', cl);
if (classOptions) {
applyOptionsToSchema(schema, classOptions);
}
return schema;
}
const schemaFields: (keyof Schema.Base)[] = [
'type',
'desc',
'key',
'flag',
'value',
'alt',
'sDict',
'list',
'dict',
'callback',
'meta',
];
export function RegisterSchema(options: SchemaClassOptions = {}) {
return function <C extends { new (...args: any[]): any }>(originalClass: C) {
Metadata.set('SchemaClassOptions', options)(originalClass);
const schema = schemaFromClass(originalClass);
const newClass = (function (...args: any[]): any {
const instance = new originalClass(...args);
const originalObject = args[0];
const newRawObject = new schema(originalObject);
console.log('before', JSON.stringify(newRawObject, null, 2));
for (const key in schema.dict) {
const transformer = reflector.get('Transformer', originalClass, key);
if (transformer) {
newRawObject[key] = transformer(newRawObject[key]);
}
}
console.log('after', JSON.stringify(newRawObject, null, 2));
for (const key in newRawObject) {
Object.defineProperty(instance, key, {
writable: true,
enumerable: true,
configurable: true,
value: newRawObject[key],
});
}
//Object.assign(instance, newRawObject);
return instance;
} as unknown) as C & Schema<TypeFromClass<C>>;
Object.defineProperty(newClass, 'name', {
value: originalClass.name,
});
Object.setPrototypeOf(newClass, originalClass.prototype);
for (const field of schemaFields) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
newClass[field] = schema[field];
}
return newClass;
};
}
// for backward compatibility
export const SchemaConf = RegisterSchema;
export * from '../decorators/define-property';
export * from './interfaces';
import Schema from 'schemastery';
export type ClassType<T> = { new <T>(...args: any[]): T };
export type TypeFromClass<C> = C extends { new (...args: any[]): infer T }
? T
: never;
export type SchemaType =
| 'string'
| 'number'
| 'boolean'
| 'object'
| 'any'
| 'never'
| { new (...args: any[]): any };
export interface SchemaClassOptions {
desc?: string;
required?: boolean;
hidden?: boolean;
allowUnknown?: boolean;
comment?: string;
default?: any;
}
export interface SchemaOptions extends SchemaClassOptions {
schema?: Schema<any>;
dict?: boolean;
array?: boolean;
type?: SchemaType;
}
export type SchemaOptionsDict<T> = { [P in keyof T]?: SchemaOptions };
import { SchemaClassOptions, SchemaOptions } from '../def';
export interface MetadataArrayMap {
SchemaMetaKey: string;
}
export interface MetadataMap {
SchemaMeta: SchemaOptions;
SchemaClassOptions: SchemaClassOptions;
Transformer: (value: any) => any;
}
import { MetadataSetter } from 'typed-reflector';
import { MetadataArrayMap, MetadataMap } from './constants';
export const Metadata = new MetadataSetter<MetadataMap, MetadataArrayMap>();
import { Reflector } from 'typed-reflector';
import { MetadataArrayMap, MetadataMap } from './constants';
export const reflector = new Reflector<MetadataMap, MetadataArrayMap>();
import { Metadata } from '../metadata/metadata';
import { ClassType } from '../def';
import Schema from 'schemastery';
import _ from 'lodash';
export function SetTransformer(transformer: (val: any) => any) {
return Metadata.set('Transformer', transformer);
}
export function transformSingle<T>(
cl: ClassType<T> & Partial<Schema>,
val: any,
) {
if (typeof cl.type === 'string') {
return new cl(val);
} else {
return val;
}
}
export function transformArray<T>(cl: ClassType<T>, val: any[]) {
const result = val.map((v) => transformSingle(cl, v));
return result;
}
export function transformDict<T>(cl: ClassType<T>, val: any, array: boolean) {
let result: any;
if (array) {
result = (val as Record<string, any>[]).map((v) =>
_.mapValues(v, (_v) => transformSingle(cl, _v)),
);
} else {
result = _.mapValues(val, (_v) => transformSingle(cl, _v));
}
return result;
}
import Schema from 'schemastery';
// eslint-disable-next-line @typescript-eslint/ban-types
export function getStringFromNativeType(nativeType: Function) {
if (!nativeType) {
return;
}
if (typeof (nativeType as Schema<any>).type === 'string') {
// nested schema
return 'class';
}
const nativeTypeString = nativeType.toString() as string;
if (!nativeTypeString) {
return;
}
if (nativeTypeString.startsWith('class')) {
return 'class';
}
if (!nativeTypeString.startsWith('function ')) {
return;
}
return nativeType.name?.toLowerCase();
}
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es2021",
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": true,
"sourceMap": true
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts",
"test/**/*.ts"
]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment