Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 4 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@
"scripts": {
"build": "tsc",
"start": "dist/index.js",
"test": "npm run test:project && npm run test:snapshots",
"test:generate": "npx tsc && node --test --test-update-snapshots \"**/*.test.js\"",
"test": "npm run test:typecheck && npm run test:project && npm run test:snapshots",
"test:generate": "npx tsc && npm run test:typecheck && node --test --test-update-snapshots \"**/*.test.js\"",
"test:project": "npx tsc && npm test -w ./test/project",
"test:typecheck": "npx tsc -p test/tsconfig.json",
"test:snapshots": "npx tsc && node --test --experimental-test-snapshots \"**/*.test.js\""
},
"workspaces": [
Expand Down
6 changes: 4 additions & 2 deletions test/project/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
"posttest": "node ./scripts/test-project.mjs verify"
},
"dependencies": {
"@wshcmx/cli": "file:../..",
"@wshcmx/types": "^11.0.0-rc.1"
"@wshcmx/cli": "file:../.."
},
"devDependencies": {
"@wshcmx/types": "^12.1.0"
}
}
49 changes: 49 additions & 0 deletions test/transformers/api_patterns/api-patterns.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { suite, test } from 'node:test';
import { strictEqual } from 'node:assert';

import ts from 'typescript';

import { enumsToObjects } from '#dist/transformers/enums_to_objects.js';
import { removeExports } from '#dist/transformers/remove_exports.js';
import { convertTemplateStrings } from '#dist/transformers/template_strings.js';
import { transformNamespaces } from '#dist/transformers/transform_namespaces.js';

suite('API derived transpilation patterns', () => {
const casesPath = join(import.meta.dirname, 'cases');
const expectedPath = join(import.meta.dirname, 'expected');
const caseNames = readdirSync(casesPath)
.filter((name) => name.endsWith('.ts'))
.sort();

for (const caseName of caseNames) {
test(caseName, () => {
const code = readFileSync(join(casesPath, caseName), 'utf-8');
const expectedCode = readFileSync(join(expectedPath, caseName.replace(/\.ts$/, '.js')), 'utf-8');
const result = ts.transpileModule(code, {
compilerOptions: {
module: ts.ModuleKind.Preserve,
target: ts.ScriptTarget.ES5,
},
transformers: {
before: [
removeExports(),
enumsToObjects(),
convertTemplateStrings(),
transformNamespaces(),
],
},
});

strictEqual(formatOutput(result.outputText), formatOutput(expectedCode));
});
}
});

function formatOutput(outputText) {
return outputText
.replaceAll('\r\n', '\n')
.replace(/\\u[\dA-Fa-f]{4}/g, (match) => String.fromCharCode(parseInt(match.slice(2), 16)))
.trimEnd();
}
39 changes: 39 additions & 0 deletions test/transformers/api_patterns/cases/passport-pattern.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { wshcmx, Route } from "../index";

type Authentication = {
id: number;
type: Route["access"];
};

export function authenticateApplication(req: Request, xAppId: string): Authentication | null {
const applicationDocument = tools.get_doc_by_key<RemoteApplicationDocument>("remote_application", "app_id", xAppId);

if (applicationDocument === null) {
return null;
}

const credentials = applicationDocument.TopElem.credentials;
let credentialDocument;

for (let i = 0; i < credentials.ChildNum; i++) {
credentialDocument = tools.open_doc<CredentialDocument>(credentials[i].id);

if (credentialDocument === undefined) {
wshcmx.utils.log.error(`Авторизационные данные по id "${credentials[i].id}" не найдены в базе данных`, "passport");
continue;
}

if (
credentialDocument.TopElem.login == req.AuthLogin
&& tools.make_password(credentialDocument.TopElem.password, true) == req.AuthPassword
) {
return {
id: applicationDocument.DocID,
type: "application"
};
}
}

wshcmx.utils.log.error(`Некорректный логин или пароль для приложения ${xAppId}`, "passport");
return null;
}
41 changes: 41 additions & 0 deletions test/transformers/api_patterns/cases/response-pattern.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { wshcmx } from "../index";

function json<T>(
res: Response,
payload: T,
status = 200,
message: unknown = null
) {
res.ContentType = "application/json; charset=utf-8;";

if (status !== 200) {
res.SetRespStatus(status, String(message));
}

res.Write((wshcmx.utils.type.isPrimitive(payload) ? payload : tools.object_to_text(payload, "json")) as string);
}

export function abort(res: Response, message: unknown, status: number = 500) {
message = (
wshcmx.utils.type.isError(message) && wshcmx.config.env != "development"
? message.message
: RValue(message)
) as string;

json(res, { error: message }, status, message);
}

export function binary(res: Response, file: ResourceDocument) {
if (file.TopElem.file_source.Value === null || file.TopElem.file_url.Value === null) {
return;
}

const url = tools.file_source_get_file_to_save_url(
file.TopElem.file_source.Value,
file.DocID,
file.TopElem.file_url.Value
);

res.AddHeader("Content-Disposition", `attachment; filename=${UrlEncode(file.TopElem.name.Value)}`);
res.Write(url);
}
39 changes: 39 additions & 0 deletions test/transformers/api_patterns/cases/router-pattern.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Route, wshcmx } from "../index";

function createRouterRule() {
const webRuleCode = `wshcmx_${wshcmx.config.pattern}`;
let webRuleDocument = tools.get_doc_by_key<WebRuleDocument>("web_rule", "code", webRuleCode);

if (webRuleDocument === null) {
webRuleDocument = tools.new_doc_by_name<WebRuleDocument>("web_rule");
webRuleDocument.BindToDb();
}

webRuleDocument.TopElem.url.Value = `${wshcmx.config.pattern}/*`;
webRuleDocument.TopElem.redirect_url.Value = `/${wshcmx.config.basepath}/api.html`;

alert(`Правило редиректа ${webRuleDocument.DocID} успешно ${webRuleDocument.NeverSaved ? `${"создано"}` : `${"обновлено"}`}`);
}

export type ControllerLibrary = {
functions(): Route[];
[key: string]: (...args: any[]) => void;
};

export function init() {
createRouterRule();
const apis = ReadDirectory("./../controllers");
const apiFunctions = OpenCodeLib<ControllerLibrary>(apis[0]).functions();
const apiRoute = apiFunctions[0] as Route & {
HasProperty(key: string): boolean;
};

wshcmx.routes.push({
method: apiRoute.method,
pattern: apiRoute.pattern,
callback: apiRoute.callback,
url: apis[0],
access: apiRoute.access,
params: apiRoute.HasProperty("params") ? apiRoute.params : {}
});
}
37 changes: 37 additions & 0 deletions test/transformers/api_patterns/cases/validator-pattern.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { wshcmx, RouteParameter, RouteParameters } from "..";

function normalizeScheme(scheme: RouteParameters) {
let key;

for (key in scheme) {
const schemeProperty = scheme[key] as RouteParameter;
const type = schemeProperty.GetOptProperty("type") as RouteParameter["type"];

if (wshcmx.availableParametersTypes.indexOf(type) === -1) {
throw new Error(`Некорректно определен тип параметра ${key} - "${type}"\nДоступные параметры: ${wshcmx.availableParametersTypes.join(", ")}`);
}

schemeProperty.SetProperty("items", schemeProperty.GetOptProperty("items", null));

if (type == "array" && wshcmx.availableParametersTypes.indexOf(schemeProperty.items) === -1) {
throw new Error(`Некорректно определен тип элемента массива ${key} - ${schemeProperty.items}\nДоступные типы: ${wshcmx.availableParametersTypes.join(", ")}`);
}
}

return scheme;
}

export function parse(req: Request, scheme: RouteParameters) {
scheme = normalizeScheme(scheme);
const bodyParameters = tools.read_object<Record<string, unknown>>(req.Body);
let key;
const result = new Object() as Object & {
SetProperty(key: string, value: unknown): void;
};

for (key in bodyParameters) {
result.SetProperty(key, bodyParameters[key]);
}

return result;
}
24 changes: 24 additions & 0 deletions test/transformers/api_patterns/expected/passport-pattern.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
function authenticateApplication(req, xAppId) {
var applicationDocument = tools.get_doc_by_key("remote_application", "app_id", xAppId);
if (applicationDocument === null) {
return null;
}
var credentials = applicationDocument.TopElem.credentials;
var credentialDocument;
for (var i = 0; i < credentials.ChildNum; i++) {
credentialDocument = tools.open_doc(credentials[i].id);
if (credentialDocument === undefined) {
wshcmx.utils.log.error("Авторизационные данные по id \"" + credentials[i].id + "\" не найдены в базе данных", "passport");
continue;
}
if (credentialDocument.TopElem.login == req.AuthLogin
&& tools.make_password(credentialDocument.TopElem.password, true) == req.AuthPassword) {
return {
id: applicationDocument.DocID,
type: "application"
};
}
}
wshcmx.utils.log.error("Некорректный логин или пароль для приложения " + xAppId, "passport");
return null;
}
24 changes: 24 additions & 0 deletions test/transformers/api_patterns/expected/response-pattern.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
function json(res, payload, status, message) {
if (status === void 0) { status = 200; }
if (message === void 0) { message = null; }
res.ContentType = "application/json; charset=utf-8;";
if (status !== 200) {
res.SetRespStatus(status, String(message));
}
res.Write((wshcmx.utils.type.isPrimitive(payload) ? payload : tools.object_to_text(payload, "json")));
}
function abort(res, message, status) {
if (status === void 0) { status = 500; }
message = (wshcmx.utils.type.isError(message) && wshcmx.config.env != "development"
? message.message
: RValue(message));
json(res, { error: message }, status, message);
}
function binary(res, file) {
if (file.TopElem.file_source.Value === null || file.TopElem.file_url.Value === null) {
return;
}
var url = tools.file_source_get_file_to_save_url(file.TopElem.file_source.Value, file.DocID, file.TopElem.file_url.Value);
res.AddHeader("Content-Disposition", "attachment; filename=" + UrlEncode(file.TopElem.name.Value));
res.Write(url);
}
25 changes: 25 additions & 0 deletions test/transformers/api_patterns/expected/router-pattern.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
function createRouterRule() {
var webRuleCode = "wshcmx_" + wshcmx.config.pattern;
var webRuleDocument = tools.get_doc_by_key("web_rule", "code", webRuleCode);
if (webRuleDocument === null) {
webRuleDocument = tools.new_doc_by_name("web_rule");
webRuleDocument.BindToDb();
}
webRuleDocument.TopElem.url.Value = wshcmx.config.pattern + "/*";
webRuleDocument.TopElem.redirect_url.Value = "/" + wshcmx.config.basepath + "/api.html";
alert("Правило редиректа " + webRuleDocument.DocID + " успешно " + (webRuleDocument.NeverSaved ? "создано" : "обновлено"));
}
function init() {
createRouterRule();
var apis = ReadDirectory("./../controllers");
var apiFunctions = OpenCodeLib(apis[0]).functions();
var apiRoute = apiFunctions[0];
wshcmx.routes.push({
method: apiRoute.method,
pattern: apiRoute.pattern,
callback: apiRoute.callback,
url: apis[0],
access: apiRoute.access,
params: apiRoute.HasProperty("params") ? apiRoute.params : {}
});
}
25 changes: 25 additions & 0 deletions test/transformers/api_patterns/expected/validator-pattern.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
function normalizeScheme(scheme) {
var key;
for (key in scheme) {
var schemeProperty = scheme[key];
var type = schemeProperty.GetOptProperty("type");
if (wshcmx.availableParametersTypes.indexOf(type) === -1) {
throw new Error("Некорректно определен тип параметра " + key + " - \"" + type + "\"\nДоступные параметры: " + wshcmx.availableParametersTypes.join(", "));
}
schemeProperty.SetProperty("items", schemeProperty.GetOptProperty("items", null));
if (type == "array" && wshcmx.availableParametersTypes.indexOf(schemeProperty.items) === -1) {
throw new Error("Некорректно определен тип элемента массива " + key + " - " + schemeProperty.items + "\nДоступные типы: " + wshcmx.availableParametersTypes.join(", "));
}
}
return scheme;
}
function parse(req, scheme) {
scheme = normalizeScheme(scheme);
var bodyParameters = tools.read_object(req.Body);
var key;
var result = new Object();
for (key in bodyParameters) {
result.SetProperty(key, bodyParameters[key]);
}
return result;
}
Loading
Loading