Page MenuHomeSealhub

No OneTemporary

Authored By
Unknown
Size
93 KB
Referenced Files
None
Subscribers
None
diff --git a/src/app/base-chips/field-types/json-object.test.ts b/src/app/base-chips/field-types/json-object.test.ts
index f045c2db..9a06fd00 100644
--- a/src/app/base-chips/field-types/json-object.test.ts
+++ b/src/app/base-chips/field-types/json-object.test.ts
@@ -1,140 +1,140 @@
import assert from "assert";
import {
type TestAppConstructor,
withRunningApp,
} from "../../../test_utils/with-test-app.js";
import { assertThrowsAsync } from "../../../test_utils/assert-throws-async.js";
import { Collection, FieldTypes } from "../../../main.js";
import { TestApp } from "../../../test_utils/test-app.js";
function extend(t: TestAppConstructor) {
return class extends t {
collections = {
...TestApp.BaseCollections,
seals: new (class extends Collection {
fields = {
name: new FieldTypes.Text(),
metadata: new FieldTypes.JsonObject(),
};
})(),
};
};
}
describe("json-object", () => {
it("Correctly adds and edits record with json field", async () =>
withRunningApp(extend, async ({ rest_api }) => {
const item = {
name: "Hoover",
metadata: {
gender: "male",
weight: 300,
},
};
const { id } = await rest_api.post(
"/api/v1/collections/seals",
item
);
let {
items: [{ name, metadata }],
- } = (await rest_api.get(`/api/v1/collections/seals/${id}`)) as any;
+ } = await rest_api.get(`/api/v1/collections/seals/${id}`);
assert.deepEqual({ name, metadata }, item);
item.metadata.weight = 320;
await rest_api.patch(`/api/v1/collections/seals/${id}`, item);
let {
items: [{ name: name2, metadata: metadata2 }],
- } = (await rest_api.get(`/api/v1/collections/seals/${id}`)) as any;
+ } = await rest_api.get(`/api/v1/collections/seals/${id}`);
assert.deepEqual({ name: name2, metadata: metadata2 }, item);
}));
it("Doesn't allow to post a primitive", async () =>
withRunningApp(extend, async ({ app, rest_api }) => {
await assertThrowsAsync(
() =>
rest_api.post("/api/v1/collections/seals", {
name: "Hoover",
metadata: "atadatem",
}),
(e) =>
assert.equal(
e.response.data.data.field_messages.metadata.message,
app.i18n("invalid_json_object")
)
);
}));
it("Respects filter passed to query", async () =>
withRunningApp(extend, async ({ rest_api }) => {
await rest_api.post("/api/v1/collections/seals", {
name: "Hoover",
metadata: {
gender: "male",
weight: 300,
},
});
await rest_api.post("/api/v1/collections/seals", {
name: "Maksiu",
metadata: {
gender: "male",
weight: 280,
},
});
let seals = (await rest_api.get("/api/v1/collections/seals")).items;
assert.equal(seals.length, 2);
seals = (
await rest_api.get(
"/api/v1/collections/seals?filter[name]=Hoover"
)
).items;
assert.equal(seals[0].name, "Hoover");
seals = (
await rest_api.get(
"/api/v1/collections/seals?filter[metadata][weight]=280"
)
).items;
assert.equal(seals.length, 1);
assert.equal(seals[0].name, "Maksiu");
}));
it("Respects filter passed to query when value can be parsed as number", async () =>
withRunningApp(extend, async ({ rest_api }) => {
const seals = [
{
name: "Hoover",
metadata: {
gender: "male",
weight: "300.253",
},
},
{
name: "Maksiu",
metadata: {
gender: "male",
weight: "280",
},
},
];
for (let seal of seals) {
await rest_api.post("/api/v1/collections/seals", seal);
}
for (let seal of seals) {
let { items: actual_seals } = await rest_api.get(
`/api/v1/collections/seals?filter[metadata][weight]=${seal.metadata.weight}`
);
assert.equal(actual_seals.length, 1);
assert.equal(actual_seals[0].name, seal.name);
}
}));
});
diff --git a/src/app/base-chips/field-types/json-object.ts b/src/app/base-chips/field-types/json-object.ts
index 063ecb4b..0d6a09b6 100644
--- a/src/app/base-chips/field-types/json-object.ts
+++ b/src/app/base-chips/field-types/json-object.ts
@@ -1,61 +1,61 @@
import { Field, Context } from "../../../main.js";
import { OpenApiTypes } from "../../../schemas/open-api-types.js";
import flattenObjectToDotNotation from "../../../utils/flatten-object-dot-notation.js";
export default class JsonObject extends Field<Record<string, unknown>> {
typeName = "json-object";
open_api_type = OpenApiTypes.OBJECT;
async isProperValue(context: Context, new_value: {}, __: {}) {
let stringified_value;
try {
stringified_value = JSON.stringify(new_value);
} catch (e) {
return Field.invalid(
context.app.i18n("invalid_json_object", [new_value])
);
}
if (!stringified_value.startsWith("{")) {
return Field.invalid(context.app.i18n("invalid_json_object"));
}
return Field.valid();
}
async encode(_: Context, value: {}) {
if (value === null) {
return null;
}
return JSON.parse(JSON.stringify(value));
}
async getAggregationStages(
_: Context,
filter_value: { [value: string]: any }
) {
// the following will pick only filters relating to this particular field and turn them into dot notation.
// example when field "metadata" is of type json-object:
// {name: "Hoover", metadata: {"age": 22}}
// will become
// {"metadata.age": 22 }
// note that "name" is missing
const flattened_filter = flattenObjectToDotNotation(
await this.getValuePath(),
filter_value || {}
);
- for (let prop_path of Object.keys(flattened_filter)) {
+ for (const prop_path of Object.keys(flattened_filter)) {
const filter_entry = flattened_filter[prop_path];
flattened_filter[prop_path] =
getQueryWithProperOperator(filter_entry);
}
return [{ $match: flattened_filter }];
}
}
function getQueryWithProperOperator(filter: any) {
- let filter_as_number = parseFloat(filter);
+ const filter_as_number = parseFloat(filter);
return Number.isFinite(filter_as_number)
? { $in: [filter, filter_as_number] }
: { $eq: filter };
}
diff --git a/src/app/base-chips/field-types/money.test.ts b/src/app/base-chips/field-types/money.test.ts
index 218ce467..e090d22a 100644
--- a/src/app/base-chips/field-types/money.test.ts
+++ b/src/app/base-chips/field-types/money.test.ts
@@ -1,53 +1,56 @@
import assert from "assert";
import { Collection, FieldTypes, Policies } from "../../../main.js";
import { TestApp } from "../../../test_utils/test-app.js";
-import { type TestAppConstructor, withRunningApp } from "../../../test_utils/with-test-app.js";
+import {
+ type TestAppConstructor,
+ withRunningApp,
+} from "../../../test_utils/with-test-app.js";
function extend(t: TestAppConstructor) {
return class extends t {
collections = {
...TestApp.BaseCollections,
wallet: new (class extends Collection {
fields = {
simoleon: new FieldTypes.Money(),
};
defaultPolicy = new Policies.Public();
})(),
};
};
}
describe("money", () => {
it("should return two digits after the decimal separator even for integers", async () =>
withRunningApp(extend, async ({ app }) => {
await app.collections.wallet.suCreate({ simoleon: 1 });
const response = await app.collections.wallet
.list(new app.SuperContext())
.format({ simoleon: "string" })
.fetch();
assert.strictEqual(response.items[0]!.get("simoleon"), "1.00");
}));
it("should correctly format with two decimal points float value", async () =>
withRunningApp(extend, async ({ app }) => {
await app.collections.wallet.suCreate({ simoleon: 14.43 });
const response = await app.collections.wallet
.list(new app.SuperContext())
.format({ simoleon: "string" })
.fetch();
assert.strictEqual(response.items[0]!.get("simoleon"), "14.43");
}));
it("should correctly format with more than two decimal points float value", async () =>
withRunningApp(extend, async ({ app }) => {
await app.collections.wallet.suCreate({ simoleon: 53.1423 });
const response = await app.collections.wallet
.list(new app.SuperContext())
.format({ simoleon: "string" })
.fetch();
assert.strictEqual(response.items[0]!.get("simoleon"), "53.14");
}));
});
diff --git a/src/app/base-chips/field-types/password.test.ts b/src/app/base-chips/field-types/password.test.ts
index bf597749..f8408dc4 100644
--- a/src/app/base-chips/field-types/password.test.ts
+++ b/src/app/base-chips/field-types/password.test.ts
@@ -1,52 +1,61 @@
import assert from "assert";
import { withRunningApp } from "../../../test_utils/with-test-app.js";
import SecureHasher from "../../../utils/secure-hasher.js";
import type { App } from "../../app.js";
describe("password", () => {
const password = "it-really-doesnt-matter";
const username = "some-user";
let user_id: string;
async function setup(app: App) {
user_id = (
await app.collections.users.suCreate({
username,
password,
})
).id;
}
it("Hides password", async () =>
withRunningApp(null, async ({ app, rest_api }) => {
await setup(app);
const session = await rest_api.login({
username,
password,
});
assert.ok(
- !(await rest_api.get(`/api/v1/collections/users/${user_id}`, session)).password
+ !(
+ await rest_api.get(
+ `/api/v1/collections/users/${user_id}`,
+ session
+ )
+ ).password
);
assert.equal(
- (await app.collections.users.suGetByID(user_id)).get("password"),
+ (await app.collections.users.suGetByID(user_id)).get(
+ "password"
+ ),
"secret"
);
}));
it("Stores correct password value", async () =>
withRunningApp(null, async ({ app }) => {
await setup(app);
const hashed_password = (
await app.Datastore.find("users", {
id: user_id,
})
)[0]!.password as string;
assert.ok(await SecureHasher.matches(password, hashed_password));
- assert.ok(!(await SecureHasher.matches("wrong-password", hashed_password)));
+ assert.ok(
+ !(await SecureHasher.matches("wrong-password", hashed_password))
+ );
assert.ok(!(await SecureHasher.matches("", hashed_password)));
}));
});
diff --git a/src/app/collections/sessions.ts b/src/app/collections/sessions.ts
index 5a0c201c..f08b9ae6 100644
--- a/src/app/collections/sessions.ts
+++ b/src/app/collections/sessions.ts
@@ -1,102 +1,102 @@
import Router from "@koa/router";
import Collection from "../../chip-types/collection.js";
import { Context, Errors, FieldTypes, Policies } from "../../main.js";
import SecureHasher from "../../utils/secure-hasher.js";
export default class Sessions extends Collection {
name = "sessions";
fields = {
"session-id": new FieldTypes.SessionID(),
user: new FieldTypes.SingleReference("users"),
};
policies = {
list: new Policies.UserReferencedInField("user"),
delete: new Policies.UserReferencedInField("user"),
};
defaultPolicy = new Policies.Super();
internal = true;
getRouter() {
const router = new Router();
router.delete("/current", async (ctx) => {
try {
const sessions = await ctx.$app.collections.sessions
.suList()
.filter({ "session-id": ctx.$context.session_id })
.fetch();
await Promise.all(
sessions.items.map(async (session) =>
session.remove(new this.app.SuperContext())
)
);
ctx.body = "You've been logged out";
} catch (e) {
return Promise.reject(
new Errors.BadContext("Invalid session id!")
);
}
});
const super_router = super.getRouter();
router.use(super_router.routes(), super_router.allowedMethods());
return router;
}
//returns a session ID to put in the cookie or throws an error if something went wrong
async login(username: string, password: string): Promise<string> {
if (!username) {
throw new Errors.InvalidCredentials("Missing username!");
}
if (!password) {
throw new Errors.InvalidCredentials("Missing password!");
}
const [user] = await this.app.Datastore.find("users", {
"username.safe": username,
});
if (!user) {
throw new Errors.InvalidCredentials("Incorrect username!");
}
const is_valid = await SecureHasher.matches(
password,
user.password as string
);
if (!is_valid) {
throw new Errors.InvalidCredentials("Incorrect password!");
}
const session = (this as Sessions).make({
- user: user.id as unknown as string,
+ user: user.id as string,
"session-id": undefined,
});
await session.save(new this.app.SuperContext());
const session_id = session.get("session-id");
return session_id as string;
}
async logout(context: Context, session_id: string): Promise<void> {
const {
items: [session],
} = await this.app.collections.sessions
.list(context)
.filter({ "session-id": session_id })
.fetch();
if (!session) {
throw new Error(
"Logout error: Wrong session ID or you don't have access to that session"
);
}
try {
await session.delete(context);
} catch (e) {
console.error(e);
throw new Error(
"Logout: Could not delete the session. Do you have the right permisions?"
);
}
}
}
diff --git a/src/app/policy-types/not.test.ts b/src/app/policy-types/not.test.ts
index 58e54dea..7f2a2b86 100644
--- a/src/app/policy-types/not.test.ts
+++ b/src/app/policy-types/not.test.ts
@@ -1,178 +1,178 @@
import assert from "assert";
import Bluebird from "bluebird";
import type Context from "../../context.js";
import * as Sealious from "../../main.js";
import {
Collection,
CollectionItem,
FieldTypes,
Policies,
} from "../../main.js";
import { assertThrowsAsync } from "../../test_utils/assert-throws-async.js";
import {
type TestAppConstructor,
withRunningApp,
} from "../../test_utils/with-test-app.js";
import getAttachment from "../../test_utils/get-attachment.js";
import { TestApp } from "../../test_utils/test-app.js";
function create_less_than_policy(number: number) {
return new (class extends Sealious.Policy {
async _getRestrictingQuery() {
const query = new Sealious.Query();
const id = query.lookup({
from: "numbers",
localField: "number",
foreignField: "id",
unwind: true,
});
query.match({
[`${id}.number`]: {
$lt: number,
},
});
return query;
}
async checkerFunction(
_: Context,
item_getter: () => Promise<CollectionItem>
) {
const item = await item_getter();
const item_number = (
item as unknown as {
number: { number: number };
}
).number.number;
if (item_number >= number) {
return Sealious.Policy.deny(
`Given value is not lower than ${number}`
);
}
return Sealious.Policy.allow(`Number is less than ${number}`);
}
isItemSensitive = async () => true;
})();
}
const l = (n: number) => create_less_than_policy(n);
const collections_to_create = [
{
name: "collection-not(less-than(2))",
policy: l(2),
},
{
name: "collection-not(less-than(6))",
policy: l(6),
},
{
name: "collection-not(public)",
policy: new Policies.Public(),
},
{
name: "collection-not(noone)",
policy: new Policies.Noone(),
},
];
function extend(t: TestAppConstructor) {
const collections_to_add: { [name: string]: Collection } = {};
for (const { name, policy } of collections_to_create) {
collections_to_add[name] = new (class extends Collection {
fields = {
number: new FieldTypes.SingleReference("numbers"),
};
policies = {
list: new Policies.Not(policy),
show: new Policies.Not(policy),
create: new Policies.Public(),
};
})();
}
return class extends t {
collections = {
...TestApp.BaseCollections,
...collections_to_add,
numbers: new (class extends Collection {
fields = {
number: new FieldTypes.Int(),
};
})(),
};
};
}
describe("NotPolicy", () => {
async function setup(app: Sealious.App) {
for (let i of [0, 1, 2, 3, 4]) {
const { id } = await app.collections.numbers!.suCreate({
number: i,
});
await Bluebird.map(collections_to_create, ({ name }) =>
app.collections[name]!.suCreate({
number: id,
})
);
}
}
it("returns nothing for collection-not(public)", () =>
withRunningApp(extend, async ({ app, rest_api }) => {
await setup(app);
await assertThrowsAsync(
async () =>
await rest_api.get(
"/api/v1/collections/collection-not(public)"
),
(e) => {
- assert.strictEqual((e as any).response.status, 401);
+ assert.strictEqual(e.response.status, 401);
}
);
}));
it("returns everything for collection-not(noone)", () =>
withRunningApp(extend, async ({ app, rest_api }) => {
await setup(app);
const response = await rest_api.get(
"/api/v1/collections/collection-not(noone)?attachments[number]=true"
);
const numbers = response.items.map(
(item: any) => getAttachment(item, "number", response).number
);
assert.deepEqual(numbers, [0, 1, 2, 3, 4]);
}));
it("returns correct numbers for collection-not(less-than(2))", () =>
withRunningApp(extend, async ({ app, rest_api }) => {
await setup(app);
const response = await rest_api.get(
"/api/v1/collections/collection-not(less-than(2))?attachments[number]=true"
);
const numbers = response.items.map(
(item: any) => getAttachment(item, "number", response).number
);
assert.deepEqual(numbers, [2, 3, 4]);
}));
it("returns correct numbers for collection-not(less-than(6))", () =>
withRunningApp(extend, async ({ app, rest_api }) => {
await setup(app);
const response = await rest_api.get(
"/api/v1/collections/collection-not(less-than(6))?attachments[number]=true"
);
const numbers = response.items.map(
(item: any) => getAttachment(item, "number", response).number
);
assert.deepEqual(numbers, []);
}));
});
diff --git a/src/app/search.test.ts b/src/app/search.test.ts
index a522955f..ee07fb9f 100644
--- a/src/app/search.test.ts
+++ b/src/app/search.test.ts
@@ -1,53 +1,53 @@
import assert from "assert";
import Collection from "../chip-types/collection.js";
import { FieldTypes } from "../main.js";
import { TestApp } from "../test_utils/test-app.js";
import { withRunningApp } from "../test_utils/with-test-app.js";
describe("search", () => {
it("Performs full-text-search", async () => {
return withRunningApp(
(test_app) => {
return class extends test_app {
collections = {
...TestApp.BaseCollections,
dogs: new (class extends Collection {
fields = {
name: new FieldTypes.Text({
full_text_search: true,
}),
};
})(),
};
};
},
async ({ app, rest_api }) => {
await app.collections.dogs.create(new app.Context(), {
name: "Nora",
});
await app.collections.dogs.create(new app.Context(), {
name: "Greta",
});
- const { items } = (await rest_api.get(
+ const { items } = await rest_api.get(
"/api/v1/collections/dogs?search=Greta"
- )) as any;
+ );
assert.deepEqual(items.length, 1);
const { items: items2 } = await app.collections["dogs"]
.list(new app.Context())
.search("Nora")
.fetch();
assert.deepEqual(items2.length, 1);
const { items: items3 } = await app.collections["dogs"]
.list(new app.Context())
.search()
.fetch();
assert.deepEqual(items3.length, 2);
}
);
});
});
diff --git a/src/app/sort.test.ts b/src/app/sort.test.ts
index b7d61ddb..5ef08566 100644
--- a/src/app/sort.test.ts
+++ b/src/app/sort.test.ts
@@ -1,110 +1,110 @@
import assert from "assert";
import {
type TestAppConstructor,
withRunningApp,
} from "../test_utils/with-test-app.js";
import { assertThrowsAsync } from "../test_utils/assert-throws-async.js";
import { App, Collection, FieldTypes } from "../main.js";
import type { SerializedItemBody } from "../chip-types/collection-item.js";
import type MockRestApi from "../test_utils/rest-api.js";
import { TestApp } from "../test_utils/test-app.js";
function extend(t: TestAppConstructor) {
return class extends t {
collections = {
...TestApp.BaseCollections,
water_areas: new (class extends Collection {
fields = {
name: new FieldTypes.Text(),
temperature: new FieldTypes.Int(),
};
})(),
seals: new (class extends Collection {
fields = {
name: new FieldTypes.Text(),
favorite_number: new FieldTypes.Int(),
water_area: new FieldTypes.SingleReference("water_areas"),
};
})(),
};
};
}
describe("sorting", () => {
const items: { [name: string]: SerializedItemBody } = {};
async function create_resources(app: App, rest_api: MockRestApi) {
- items.baltic_sea = (await rest_api.post(
+ items.baltic_sea = await rest_api.post(
"/api/v1/collections/water_areas",
{
name: "Baltic Sea",
temperature: 10,
}
- )) as any;
+ );
- items.arabic_sea = (await rest_api.post(
+ items.arabic_sea = await rest_api.post(
"/api/v1/collections/water_areas",
{
name: "Arabic Sea",
temperature: 20,
}
- )) as any;
+ );
const seals = [
{
name: "Hoover",
favorite_number: 3,
water_area: items.arabic_sea!.id,
},
{
name: "Maksiu",
favorite_number: 3,
water_area: items.baltic_sea!.id,
},
{
name: "Nelly",
favorite_number: 8,
water_area: items.baltic_sea!.id,
},
];
const promises = [];
for (let seal of seals) {
promises.push(app.collections.seals!.suCreate(seal));
}
await Promise.all(promises);
}
it("properly sorts for correct sort key", async () => {
return withRunningApp(extend, async ({ app, rest_api }) => {
await create_resources(app, rest_api);
- const { items } = (await rest_api.get(
+ const { items } = await rest_api.get(
"/api/v1/collections/seals?sort[favorite_number]=desc"
- )) as any;
+ );
assert.deepEqual(
items.map((item: any) => item.favorite_number),
[8, 3, 3]
);
});
});
it("throws application error for incorrect sort key", async () =>
withRunningApp(extend, async ({ app, rest_api }) => {
await create_resources(app, rest_api);
await assertThrowsAsync(
async () =>
await rest_api.get(
"/api/v1/collections/seals?sort[favorite_number]=dsc"
),
(e) => {
assert.equal(e.response.status, 405);
assert.equal(
e.response.data.message,
`Unknown sort key: "dsc". Available sort keys are: desc, descending, asc, ascending.`
);
}
);
}));
});
diff --git a/src/chip-types/field-base.ts b/src/chip-types/field-base.ts
index 0d800235..41e81716 100644
--- a/src/chip-types/field-base.ts
+++ b/src/chip-types/field-base.ts
@@ -1,327 +1,327 @@
import type Collection from "./collection.js";
import type Context from "../context.js";
import type { ActionName } from "../action.js";
import type { QueryStage } from "../datastore/query-stage.js";
import type { MatchBody } from "../datastore/query-stage.js";
import { BadSubjectAction } from "../response/errors.js";
import isEmpty from "../utils/is-empty.js";
import type { App } from "../app/app.js";
import { ItemListResult } from "./item-list-result.js";
import { OpenApiTypeMapping, OpenApiTypes } from "../schemas/open-api-types.js";
export type Depromisify<T> = T extends Promise<infer V> ? V : T;
export type ExtractParams<F extends Field<unknown, unknown, unknown>> =
Parameters<F["setParams"]>[0];
export type ExtractFilterParams<F extends Field<unknown, unknown, unknown>> =
Parameters<F["getMatchQueryValue"]>[1];
export type ValidationResult = {
valid: boolean;
reason?: string;
};
export type ExtractFieldDecoded<F extends Field<unknown, unknown, unknown>> =
F extends Field<infer T, unknown, unknown> ? T : never;
export type ExtractFieldInput<F extends Field<unknown, unknown, unknown>> =
F extends Field<unknown, infer T, unknown> ? T : never;
export type ExtractFieldStorage<F extends Field<unknown, unknown, unknown>> =
F extends Field<unknown, unknown, infer T> ? T : never;
export type RequiredField<DecodedType, InputType, StorageType> = Field<
DecodedType,
InputType,
StorageType
> & { required: true };
/** The field class itself. Stores information on the field name, and
* methods that decide waht values are valid and how they are
* stored. The {@link Field} class describes a type of field in
* general (like "Text" and "Number"), and a {@link Field} instance
* describes one particular field in a collection (like "name" and
* "age").
*
* Extend this class to create fields with custom behavior.
*
* **The recommended way to create a field for a collection is {@link
* FieldDefinitionHelper}, as it performs type checking of the
* field params.**
*
* Some of the most useful field types include:
* * {@link Boolean}
* * {@link DateField | Date}
* * {@link Datetime}
* * {@link Email}
* * {@link Enum}
* * {@link FileField | Field}
* * {@link Float}
* * {@link Html}
* * {@link Image}
* * {@link Int}
* * {@link SingleReference}
* * {@link Text}
*/
export abstract class Field<
DecodedType,
InputType = DecodedType,
StorageType = DecodedType,
> {
/** the name of the field */
name: string;
/** the app that the field exists in
* @internal
*/
app: App;
/** The display hints specified for this field */
display_hints: any;
/** Whether or not the field handles large data
* @todo: see if there's any viability in storing this
*/
- handles_large_data: boolean = false;
+ handles_large_data = false;
/** The collection this field is attached to */
collection: Collection;
/** Whether or not this field should always have a value. Creating
* a resource with a value missing for a required field will throw
* an error */
required: boolean;
/** Sets the collection @internal */
setCollection(collection: Collection) {
this.collection = collection;
}
setRequired(
required: boolean
): RequiredField<DecodedType, InputType, StorageType> {
this.required = required;
return this as RequiredField<DecodedType, InputType, StorageType>;
}
/** Sets the name @internal */
setName(name: string) {
this.name = name;
}
/** This method is used to set and process the params upon the
* field's creation when the app starts up. The type of argument
* of this method determines type checking that's performed by
* @{link FieldDefinitionHelper}. */
setParams(_: any): void {}
/** Return a summary of this field */
getSpecification() {
return {
name: this.name,
type: this.typeName,
display_hints: this.display_hints,
};
}
/** Whether or not this field should have a dedicated index in the
* database */
async hasIndex(): Promise<
boolean | "text" | { [subfield_name: string]: boolean | "text" }
> {
return false;
}
/** Value path is where inside a single record should the DB look
* for the field's value when filtering resources. Some fields use
* complex objects for storage and overwrite this method, and
* thanks to that they don't have to reimplement {@link
* Field.getAggregationStages} */
async getValuePath(): Promise<string> {
return this.name;
}
abstract typeName: string;
// base open api type - sets type & format
abstract open_api_type: OpenApiTypes;
// generates field schema - can be overriden to add extra fields
// (for example to add max_length & min_length fields to text types)
async getOpenApiSchema(context: Context): Promise<Record<string, unknown>> {
return {
...OpenApiTypeMapping[this.open_api_type],
default:
this.hasDefaultValue?.() &&
(await this.getDefaultValue(context)),
// nullable: ? // not sure if/when applicable
// readOnly: ? // not sure if/when applicable
};
}
protected abstract isProperValue(
context: Context,
new_value: unknown,
old_value: unknown,
new_value_blessing_token: symbol | null
): Promise<ValidationResult>;
public async checkValue(
context: Context,
new_value: unknown,
old_value: unknown,
new_value_blessing_token: symbol | null
): Promise<ValidationResult> {
if (isEmpty(new_value) && this.required) {
return Field.invalid(`Missing value for field '${this.name}'.`);
} else if (isEmpty(new_value)) {
return Field.valid();
} else {
return this.isProperValue(
context,
new_value,
old_value,
new_value_blessing_token
);
}
}
/** Decides how to store the given value in the database, based on
* the context and previous value of the field */
async encode(
_: Context,
value: InputType | null,
__?: any
): Promise<StorageType | null> {
return value as any;
}
/** Reverse to the {@link Field.encode} function. Takes what's inside the database and returns the value in a given format */
async decode(
context: Context,
storage_value: StorageType,
old_value: any,
format_params: any,
is_http_api_request = false
): Promise<DecodedType | null> {
context.app.Logger.debug3("FIELD DECODE", this.name, {
storage_value,
old_value,
});
return storage_value as unknown as DecodedType;
}
/** Generates a mongo query based on the filter value */
async getMatchQueryValue(context: Context, filter: any): Promise<any> {
return this.encode(context, filter);
}
async getMatchQuery(
context: Context,
filter: any,
value_path: string
): Promise<any> {
return {
[value_path]: await this.getMatchQueryValue(context, filter),
};
}
/** Whether or not the db should create a fulltext index on this field */
async fullTextSearchEnabled(): Promise<boolean> {
return false;
}
/** Whether or not a field has a default value - that is, a value
* given to the field if no value is provided */
hasDefaultValue() {
return true;
}
/** The default value that will be assigned to the field if no
* value is given */
async getDefaultValue(_: Context): Promise<InputType | null> {
return null;
}
/** Whether or not any of the methods of the field depend on the
* previous value of the field */
isOldValueSensitive(_: ActionName) {
return false;
}
/** Used to signal a positive decision from within {@link
* Field.isProperValue}. */
static valid(): ValidationResult {
return { valid: true };
}
/** Used to signal a negative decition from within {@link
* Field.isProperValue}. */
static invalid(reason: string): ValidationResult {
return { valid: false, reason };
}
/** Runs when the app is being started. Hooks can be set up within
* this function */
async init(app: App, collection: Collection): Promise<void> {
this.app = app;
this.collection = collection;
}
async getAttachments(
context: Context,
values: any[], // this method gets called once for multiple resources, to limit the number of queries. Field values of all the resources are passed in this array
attachment_options: any,
format_params: any
): Promise<ItemListResult<any>> {
if (attachment_options !== undefined) {
throw new BadSubjectAction(
`Field '${this.name}' does not support attachments`
);
}
return new ItemListResult([], [], {});
}
/** Creates parts of a Mongo Pipieline that will be used to filter
* the items when listing items of a collection */
async getAggregationStages(
context: Context,
field_filter: unknown
): Promise<QueryStage[]> {
context.app.Logger.debug2(
"FIELD",
`${this.name}.getAggregationStages`,
field_filter
);
if (field_filter === undefined) return [];
const value_path = await this.getValuePath();
let $match: MatchBody = {};
if (field_filter === null) {
$match = {
$or: [
{ [value_path]: { $exists: false } },
{ [value_path]: null },
],
};
} else if (field_filter instanceof Array) {
$match = {
[value_path]: {
$in: await Promise.all(
field_filter.map((value) => this.encode(context, value))
),
},
};
} else {
$match = await this.getMatchQuery(
context,
field_filter,
await this.getValuePath()
);
context.app.Logger.debug3("FIELD", "getAggregationStages", {
value_path,
$match,
field_type: this.typeName,
});
}
return [{ $match }];
}
}
diff --git a/src/chip-types/fieldset.ts b/src/chip-types/fieldset.ts
index 84b8ae87..48dea8b9 100644
--- a/src/chip-types/fieldset.ts
+++ b/src/chip-types/fieldset.ts
@@ -1,285 +1,275 @@
import type Context from "../context.js";
import type {
ExtractFieldDecoded,
ExtractFieldInput,
ExtractFieldStorage,
RequiredField,
} from "./field.js";
import type Field from "./field.js";
export type FieldNames<T extends Record<string, Field<any, any, any>>> =
keyof T & string;
export type FieldsetOutput<T extends Record<string, Field<any, any>>> = {
[field in keyof T]: T[field] extends RequiredField<any, any, any>
? ExtractFieldDecoded<T[field]>
: ExtractFieldDecoded<T[field]> | null;
};
-export type FieldsetInput<T extends Record<string, Field<any, any, any>>> =
- | {
- [field in keyof T & string as T[field] extends RequiredField<
- any,
- any,
- any
- >
- ? field
- : never]: ExtractFieldInput<T[field]>;
- } & {
- [field in keyof T & string as T[field] extends RequiredField<
- any,
- any,
- any
- >
- ? never
- : field]?: ExtractFieldInput<T[field]>;
- };
+export type FieldsetInput<T extends Record<string, Field<any, any, any>>> = {
+ [field in keyof T & string as T[field] extends RequiredField<any, any, any>
+ ? field
+ : never]: ExtractFieldInput<T[field]>;
+} & {
+ [field in keyof T & string as T[field] extends RequiredField<any, any, any>
+ ? never
+ : field]?: ExtractFieldInput<T[field]>;
+};
export type FieldsetEncoded<T extends Record<string, Field<any, any, any>>> = {
[field in keyof T]: ExtractFieldStorage<T[field]>;
};
// a quick test for the types, shoud know which fields can be undefined
// const f = {
// a: new FieldTypes.Text().setRequired(true),
// b: new FieldTypes.Text(),
// };
// type fi = FieldsetInput<typeof f>;
export class Fieldset<Fields extends Record<string, Field<any, any, any>>> {
changed_fields: Set<keyof Fields> = new Set();
is_decoded = false;
is_encoded = false;
blessings: Partial<Record<keyof Fields, symbol | null>> = {};
constructor(
public fields: Fields,
public raw_input: Partial<FieldsetInput<Fields>> = {},
public decoded: Partial<FieldsetOutput<Fields>> = {},
public encoded: Partial<FieldsetEncoded<Fields>> = {}
) {
for (const field_name in raw_input) {
if (!encoded[field_name as keyof Fields]) {
this.changed_fields.add(field_name as keyof Fields);
}
}
}
getRequiredFields(): Field<unknown>[] {
return Object.values(this.fields).filter((f) => f.required);
}
set<FieldName extends keyof FieldsetInput<Fields> & string>(
field_name: FieldName,
field_value: FieldsetInput<Fields>[FieldName],
blessing_symbol: symbol | null = null // those symbols can be used as a proof that a value came from e.g. an internal callback, and not from user input
): this {
this.raw_input[field_name] = field_value;
this.is_decoded = false;
this.is_encoded = false;
this.changed_fields.add(field_name);
this.blessings[field_name] = blessing_symbol;
return this;
}
clearChangedFields() {
this.changed_fields.clear();
}
getDecoded<FieldName extends keyof Fields>(field_name: FieldName) {
if (!this.is_decoded) {
throw new Error("Decode first!");
}
return this.decoded[field_name as keyof typeof this.decoded];
}
getInput<FieldName extends keyof FieldsetInput<Fields>>(
field_name: FieldName
) {
return this.raw_input[field_name];
}
getEncoded<FieldName extends keyof Fields>(field_name: FieldName) {
return this.encoded[field_name];
}
/** Returns encoded values for every field */
async encode(
context: Context,
original_body: FieldsetInput<Fields> = {} as FieldsetInput<Fields>,
only_changed = false
): Promise<Partial<FieldsetOutput<Fields>>> {
context.app.Logger.debug3(
"ITEM BODY",
"encode",
this.changed_fields.values()
);
const new_encoded: Partial<FieldsetOutput<Fields>> = {};
const promises = [];
for (const field_name of this.changed_fields.values()) {
const to_encode =
this.raw_input[field_name as keyof FieldsetInput<Fields>];
context.app.Logger.debug3("ITEM BODY", "encoding value", {
[field_name]:
this.raw_input[field_name as keyof FieldsetInput<Fields>],
is_the_value_empty:
to_encode === undefined || to_encode === null,
});
if (!this.fields[field_name as string]) {
// field does not exist in this collection
continue;
}
if (to_encode === undefined) {
- new_encoded[field_name as keyof typeof new_encoded] =
- null as any;
+ new_encoded[field_name] = null as any;
continue;
}
if (!this.fields[field_name as string]) {
throw new Error("field name is missing");
}
promises.push(
this.fields[field_name as string]!.encode(
context,
to_encode,
original_body[field_name as keyof FieldsetInput<Fields>]
).then((value) => {
new_encoded[field_name as keyof typeof new_encoded] = value;
})
);
}
await Promise.all(promises);
this.encoded = { ...this.encoded, ...new_encoded };
this.is_encoded = true;
context.app.Logger.debug2("ITEM BODY", "encode result", this.encoded);
return only_changed ? new_encoded : this.encoded;
}
async decode(
context: Context,
format: { [field_name: string]: any } = {},
is_http_api_request = false
): Promise<Fieldset<Fields>> {
if (this.is_decoded) return this;
context.app.Logger.debug3("ITEM BODY", "Decoding item", {
format,
body: this.encoded,
});
const promises: Promise<any>[] = [];
for (const [field_name, encoded_value] of Object.entries(
this.encoded
)) {
const field = this.fields?.[field_name];
if (!field) {
continue;
}
const encoded = this.encoded;
if (!field) {
throw new Error("field name is missing");
}
promises.push(
field
.decode(
context,
encoded[field_name],
null,
format?.[field_name],
is_http_api_request
)
.then((decoded_value) => {
this.decoded = {
...this.decoded,
[field_name]: decoded_value,
};
context.app.Logger.debug3(
"ITEM BODY",
"Decoded value",
{
[field_name]: decoded_value,
}
);
})
);
}
await Promise.all(promises);
this.is_decoded = true;
return this;
}
copy(): Fieldset<Fields> {
return new Fieldset<Fields>(
this.fields,
{ ...this.raw_input },
{ ...this.decoded },
{ ...this.encoded }
);
}
async validate(
context: Context,
original_body: Fieldset<Fields>,
replace_mode: boolean //if true, meaning that if a field has no value, it should be deleted
): Promise<{
valid: boolean;
errors: { [f in keyof Fields]?: { message: string } };
}> {
const promises = [];
const errors: { [f in keyof Fields]?: { message: string } } = {};
let valid = true;
const fields_to_check = new Set(this.changed_fields.values());
if (replace_mode) {
for (const field of this.getRequiredFields()) {
fields_to_check.add(field.name as keyof Fields);
}
}
for (const field_name of fields_to_check) {
const field = this.fields[field_name as string];
if (!field) {
// field does not exist
continue;
}
if (!field) {
throw new Error("field name is missing");
}
promises.push(
field
.checkValue(
context,
this.raw_input[
field_name as keyof FieldsetInput<Fields>
],
- original_body.encoded[field_name as keyof Fields],
+ original_body.encoded[field_name],
this.blessings[field_name] || null
)
.then(async (result) => {
if (!result.valid) {
valid = false;
errors[field_name] = {
message: result.reason as string,
};
}
})
);
}
await Promise.all(promises);
return { valid, errors };
}
getBlessing<FieldName extends keyof Fields>(
field_name: FieldName
): symbol | null {
return this.blessings[field_name] || null;
}
setMultiple(values: Partial<FieldsetInput<Fields>>): this {
for (const [field_name, value] of Object.entries(values)) {
this.set(field_name as any, value as any);
}
return this;
}
}
diff --git a/src/chip-types/item-list.test.ts b/src/chip-types/item-list.test.ts
index 2c73a6e1..f47b7cec 100644
--- a/src/chip-types/item-list.test.ts
+++ b/src/chip-types/item-list.test.ts
@@ -1,215 +1,213 @@
import assert, { strictEqual, deepStrictEqual } from "assert";
import Int from "../app/base-chips/field-types/int.js";
import { App, Collection, FieldTypes, Query } from "../main.js";
import { sleep } from "../test_utils/sleep.js";
import { TestApp } from "../test_utils/test-app.js";
import { withRunningApp } from "../test_utils/with-test-app.js";
class Entries extends Collection {
fields = {
name: new FieldTypes.Text(),
};
}
class EntriesCSV extends Collection {
fields = {
name: new FieldTypes.Text(),
age: new FieldTypes.Int(),
};
}
describe("ItemList", () => {
it("allows to sort by modified_date", () =>
withRunningApp(
(test_app) =>
class extends test_app {
collections = {
...App.BaseCollections,
entries: new Entries(),
};
},
async ({ app }) => {
await app.collections.entries.suCreate({ name: "older" });
await sleep(100);
await app.collections.entries.suCreate({ name: "newer" });
- const { items: desc } = await (
- app.collections.entries as Entries
- )
+ const { items: desc } = await app.collections.entries
.suList()
.sort({ "_metadata.modified_at": "desc" })
.fetch();
strictEqual(desc[0]!.get("name"), "newer");
strictEqual(desc[1]!.get("name"), "older");
const { items: asc } = await app.collections.entries
.suList()
.sort({ "_metadata.modified_at": "asc" })
.fetch();
strictEqual(asc[0]!.get("name"), "older");
strictEqual(asc[1]!.get("name"), "newer");
}
));
it("properly parses params in HTTP GET", () =>
withRunningApp(
(test_app) =>
class extends test_app {
collections = {
...App.BaseCollections,
entries: new Entries(),
};
},
async ({ rest_api }) => {
// shouldn't throw
await rest_api.get(
"/api/v1/collections/entries?pagination[items]=10"
);
}
));
it("generate CSV string", () =>
withRunningApp(
(test_app) =>
class extends test_app {
collections = {
...App.BaseCollections,
entries: new EntriesCSV(),
};
},
async ({ app }) => {
await app.collections.entries.suCreate({
name: "older",
age: 15,
});
const csv = await app.collections.entries.suList().toCSV();
deepStrictEqual(csv.split("\n")[0]!.split(",").sort(), [
"age",
"name",
]);
deepStrictEqual(csv.split("\n")[1]!.split(",").sort(), [
"15",
"older",
]);
}
));
it("allows to add a custom aggregation stage", async () =>
withRunningApp(
(test_app) =>
class extends test_app {
collections = {
...App.BaseCollections,
entries: new (class extends Collection {
fields = {
number: new Int(),
};
})(),
};
},
async ({ app }) => {
await app.collections.entries.suCreate({
number: 15,
});
await app.collections.entries.suCreate({
number: 16,
});
await app.collections.entries.suCreate({
number: 17,
});
const result = (
await app.collections.entries
.suList()
.filter({ number: { ">": 15 } })
.addCustomAggregationStages(
Query.fromSingleMatch({
number: { $gt: 16 },
}).toPipeline()
)
.fetch()
).serialize();
assert.deepStrictEqual(result.items.length, 1);
assert.deepStrictEqual(result.items[0]!.number, 17);
}
));
it("should return the items in the order they were provided in the .ids() function", async () =>
withRunningApp(
(test_app) =>
class extends test_app {
collections = {
...App.BaseCollections,
entries: new (class extends Collection {
fields = {
number: new Int(),
};
})(),
};
},
async ({ app }) => {
const one = await app.collections.entries.suCreate({
number: 1,
});
const two = await app.collections.entries.suCreate({
number: 1,
});
const result1 = await app.collections.entries
.suList()
.ids([one.id, two.id])
.fetch();
assert.deepStrictEqual(
result1.items.map(({ id }) => id),
[one.id, two.id]
);
const result2 = await app.collections.entries
.suList()
.ids([two.id, one.id])
.fetch();
assert.deepStrictEqual(
result2.items.map(({ id }) => id),
[two.id, one.id]
);
}
));
it("should return empty array if all referenced items have been deleted", async () =>
withRunningApp(
(test_app) => {
const A = new (class extends Collection {
name = "A";
fields = {
reference_to_b: new FieldTypes.SingleReference("B"),
};
})();
const B = new (class extends Collection {
name = "B";
fields = { number: new FieldTypes.Int() };
})();
return class extends test_app {
collections = {
...TestApp.BaseCollections,
A,
B,
};
};
},
async ({ app }) => {
const b = await app.collections.B.suCreate({ number: 2 });
const a = await app.collections.A.suCreate({
reference_to_b: b.id,
});
await b.delete(new app.SuperContext());
const { items } = await app.collections.A.suList()
.attach({ reference_to_b: true })
.fetch();
assert.strictEqual(items.length, 1);
assert.deepStrictEqual(
items[0]!.getAttachments("reference_to_b"),
[]
);
assert.deepStrictEqual(
items[0]!.getAttachments("reference_to_b").length,
0
);
}
));
});
diff --git a/src/chip-types/policy.ts b/src/chip-types/policy.ts
index 65fb78d8..eebdb112 100644
--- a/src/chip-types/policy.ts
+++ b/src/chip-types/policy.ts
@@ -1,111 +1,111 @@
import type Context from "../context.js";
import type Query from "../datastore/query.js";
import { AllowAll } from "../datastore/allow-all.js";
import type { CollectionItem } from "../main.js";
export type PolicyDefinition = [PolicyClass, any] | Policy | PolicyClass;
export type PolicyDecision = {
allowed: boolean;
reason: string;
} | null;
export type PolicyClass = {
new (params?: any): Policy;
type_name: string;
};
export default abstract class Policy {
static type_name: string;
constructor(public params: any = {}) {
this.params = params;
}
// return null if not possible to give an answer
abstract checkerFunction(
context: Context,
item_getter?: () => Promise<CollectionItem<any>>
): Promise<PolicyDecision | null>;
async isItemSensitive(_: Context) {
return false;
}
protected abstract _getRestrictingQuery(context: Context): Promise<Query>;
async getRestrictingQuery(context: Context): Promise<Query> {
if (context.is_super) {
return new AllowAll();
}
return this._getRestrictingQuery(context);
}
async check(
context: Context,
item_getter?: () => Promise<CollectionItem<any>>
): Promise<PolicyDecision | null> {
context.app.Logger.debug3(
"POLICY",
`Checking policy`,
{
this: this,
context,
},
1
);
if (context.is_super) {
return Policy.allow(context.app.i18n("policy_allow"));
}
const is_item_sensitive = await this.isItemSensitive(context);
if (is_item_sensitive && item_getter === undefined) {
return null;
}
return this.checkerFunction(context, item_getter);
}
public static fromDefinition(definition: PolicyDefinition): Policy {
let ret: Policy | null = null;
if (definition instanceof Policy) {
ret = definition;
} else if (Array.isArray(definition)) {
ret = new definition[0](definition[1]);
} else if (typeof definition == "function") {
- ret = new (definition as PolicyClass)({});
+ ret = new definition({});
}
if (!ret) {
throw new Error("could not read the definition");
}
return ret;
}
static allow(reason: string) {
return { allowed: true, reason };
}
static deny(reason: string) {
return { allowed: false, reason };
}
}
export abstract class ReducingPolicy extends Policy {
policies: Policy[];
constructor(params: Policy[]) {
super(params);
this.policies = params.map((definition) =>
Policy.fromDefinition(definition)
);
}
checkAllPolicies(
context: Context,
item_getter?: () => Promise<CollectionItem>
): Promise<PolicyDecision[]> {
return Promise.all(
this.policies.map((strategy) =>
strategy.check(context, item_getter)
)
);
}
}
diff --git a/src/data-structures/long-running-process.ts b/src/data-structures/long-running-process.ts
index cdbe1bc6..0f00a7aa 100644
--- a/src/data-structures/long-running-process.ts
+++ b/src/data-structures/long-running-process.ts
@@ -1,165 +1,165 @@
import EventEmitter from "events";
import type LongRunningProcessEvents from "../app/collections/long-running-process-events.js";
import type LongRunningProcesses from "../app/collections/long-running-processes.js";
import type { CollectionInput, CollectionItem, Context } from "../main.js";
type LongRunningProcessEvent = {
type: string;
message: string;
timestamp: number;
};
export type LPRState = "running" | "error" | "finished";
export class LongRunningProcess<
- Args extends Array<unknown> = []
+ Args extends Array<unknown> = [],
> extends EventEmitter {
public status: "ready" | LPRState = "ready";
protected itemPromise: Promise<CollectionItem<LongRunningProcesses>>;
protected isFinishedPromise: Promise<void>;
protected static registry: Record<string, LongRunningProcess | undefined> =
{};
constructor(
protected context: Context,
callback: (
process: LongRunningProcess<Args> | null,
...rest: Args
) => Promise<unknown>,
args: Args,
- name: string = "Long running process",
+ name = "Long running process",
owner_id: string | null = context.user_id
) {
super();
if (owner_id == null && !context.is_super) {
throw new Error(
"While creating a LongRunningProcess, you can do it either in 'super' access control mode, or in 'user' access control mode. If you want the process to only be available with a supercontext, use SuperContext for the LRP constructor. Otherwise use a regular context with a logged in user or provide the owner id as an argument"
);
}
const item_body = {
started: Date.now(),
name,
owner: owner_id,
} as CollectionInput<LongRunningProcesses>;
if (owner_id == null) {
item_body.access_mode = "super";
} else {
item_body.access_mode = "user";
}
this.itemPromise =
context.app.collections.long_running_processes.suCreate(item_body);
this.getID().then((id) => (LongRunningProcess.registry[id] = this));
this.isFinishedPromise = callback(this, ...args)
.then(() => this.setState("finished"))
.catch((error) => {
this.context.app.Logger.error(
"LRP",
error.message.split("\n")[0],
error
);
return this.error(error.message);
});
}
async error(message: string) {
await this.setState("error");
await this.addEvent(message, "error");
}
async addEvent(message: string, type: "info" | "error", progress?: number) {
const event_body = {
process: await this.getID(),
type,
timestamp: Date.now(),
message: message,
} as CollectionInput<LongRunningProcessEvents>;
if (progress !== undefined) {
event_body.progress = progress;
}
await this.context.app.collections.long_running_process_events.suCreate(
event_body
);
}
emit(...args: Parameters<EventEmitter["emit"]>) {
if (args[0] === "error") {
args[0] = "_error"; // otherwise Emitter screams;
}
return super.emit(...args);
}
async info(message: string, progress?: number) {
if (this.status == "finished") {
throw new Error("cannot send more info, this LRP is finished");
}
await this.addEvent(message, "info", progress);
this.emit("info", { message, progress });
}
private async setState(state: "finished" | "error") {
const id = await this.getID();
delete LongRunningProcess.registry[id];
const item =
await this.context.app.collections.long_running_processes.getByID(
this.context,
id
);
item.set("state", state);
await item.save(this.context);
this.status = state;
this.emit(state);
}
async getID() {
return (await this.itemPromise).id;
}
async waitForFinished() {
await this.isFinishedPromise;
}
static async getByID(
context: Context,
id: string
): Promise<{
emitter: LongRunningProcess | null; // it returns null if the LRP is finished, as there will be nothing more to emit;
events: LongRunningProcessEvent[];
latestEvent: LongRunningProcessEvent;
state: LPRState;
progress: number;
}> {
const {
items: [lrp_item],
} = await context.app.collections.long_running_processes
.list(context)
.ids([id])
.attach({ events: true })
.fetch();
if (!lrp_item) {
throw new Error("No access or bad ID");
}
const events = lrp_item
.getAttachments("events")
.map((e: CollectionItem<LongRunningProcessEvents>) => ({
type: e.get("type"),
message: e.get("message"),
timestamp: e.get("timestamp") as number,
progress: e.get("progress"),
}))
.sort(({ timestamp: t1 }, { timestamp: t2 }) =>
!t1 || !t2 ? 0 : t1 > t2 ? 1 : -1
);
if (!events.length) {
throw new Error("no events found");
}
const latestEvent = events.at(-1)!;
return {
emitter: this.registry[lrp_item.id] || null,
events,
latestEvent,
state: lrp_item.get("state") as LPRState,
progress: latestEvent?.progress || 0,
};
}
}
diff --git a/src/datastore/allow-all.ts b/src/datastore/allow-all.ts
index 46cc02b6..cd28629f 100644
--- a/src/datastore/allow-all.ts
+++ b/src/datastore/allow-all.ts
@@ -1,15 +1,15 @@
import Query from "./query.js";
export class AllowAll extends Query {
constructor() {
super();
super.match({ _id: { $exists: true } });
}
lookup() {
throw new Error("The query is not mutable!");
return "";
}
- match() {
+ match(): void {
throw new Error("The query is not mutable!");
}
}
diff --git a/src/datastore/deny-all.ts b/src/datastore/deny-all.ts
index 46d80aab..0e28a617 100644
--- a/src/datastore/deny-all.ts
+++ b/src/datastore/deny-all.ts
@@ -1,15 +1,15 @@
import Query from "./query.js";
export default class DenyAll extends Query {
constructor() {
super();
super.match({ _id: { $eq: -1 } });
}
lookup() {
throw new Error("The query is not mutable!");
return "";
}
- match() {
+ match(): void {
throw new Error("The query is not mutable!");
}
}
diff --git a/src/datastore/graph.ts b/src/datastore/graph.ts
index 2dbeb511..d7707d46 100644
--- a/src/datastore/graph.ts
+++ b/src/datastore/graph.ts
@@ -1,207 +1,207 @@
export type NodeID = string | number;
export type Node = {
id: NodeID;
priority: number;
};
type NextNodeCandidate = {
index: number | null;
mean_priority_of_succcessors: number;
priority: number;
};
export default class Graph {
node_ids: NodeID[];
nodes: Node[];
adjacency_matrix: (0 | 1)[][];
indexes: number[];
front: number[];
visited: number[];
static MAX_PRIORITY = 0;
constructor() {
this.adjacency_matrix = [];
this.node_ids = [];
this.nodes = [];
this.indexes = [];
}
- addNode(id: NodeID, priority: number) {
+ addNode(id: NodeID, priority: number): void {
this.adjacency_matrix.push(Array(this.getNoOfNodes()).fill(0));
for (const row of this.adjacency_matrix) {
row.push(0);
}
this.node_ids.push(id);
this.nodes.push({ id, priority });
this.indexes.push(this.nodes.length - 1);
}
- getNoOfNodes() {
+ getNoOfNodes(): number {
return this.nodes.length;
}
- addEdge(id_i: NodeID, id_j: NodeID) {
+ addEdge(id_i: NodeID, id_j: NodeID): void {
const [i, j] = this._getIndexesOfNodePair(id_i, id_j);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.adjacency_matrix[i]![j] = 1;
}
_getIndexesOfNodePair(id_i: NodeID, id_j: NodeID): [number, number] {
return [this.node_ids.indexOf(id_i), this.node_ids.indexOf(id_j)];
}
- pathExists(id_i: NodeID, id_j: NodeID) {
+ pathExists(id_i: NodeID, id_j: NodeID): boolean {
const [i, j] = this._getIndexesOfNodePair(id_i, id_j);
return this._pathExists(i, j);
}
_pathExists(i: number, j: number): boolean {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (this.adjacency_matrix[i]?.[j]) {
return true;
}
for (let k = 0; k < this.getNoOfNodes(); ++k) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (this.adjacency_matrix[i]?.[k]) {
return this._pathExists(k, j);
}
}
return false;
}
bestFirstSearch(): NodeID[] {
this.front = [];
this.visited = [];
while (this.visited.length < this.nodes.length) {
const { front_node, next_node } = this._getNextNode();
this.visited.push(next_node as number);
if (front_node !== null) {
if (this._areAllSuccessorsVisited(front_node)) {
const index = this.front.indexOf(front_node);
this.front.splice(index, 1);
}
}
if (!this._areAllSuccessorsVisited(next_node as number)) {
this.front.push(next_node as number);
}
}
return this.visited
.map((i) => this.nodes[i]?.id)
.filter((i) => i !== undefined) as number[];
}
- _areAllSuccessorsVisited(i: number) {
+ _areAllSuccessorsVisited(i: number): boolean {
for (let j = 0; j < this.nodes.length; ++j) {
if (this.adjacency_matrix[i]?.[j] && !this._isVisited(j)) {
return false;
}
}
return true;
}
- _isVisited(i: number) {
+ _isVisited(i: number): boolean {
return this.visited.includes(i);
}
- _isNodeWithoutPredecessors(i: number) {
+ _isNodeWithoutPredecessors(i: number): boolean {
for (let j = 0; j < this.nodes.length; ++j) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (this.adjacency_matrix[j]?.[i]) {
return false;
}
}
return true;
}
_getNextNode(): { front_node: number | null; next_node: number | null } {
const nodesWithoutPredecessorsYetToBeVisited = this.indexes.filter(
(i) => this._isNodeWithoutPredecessors(i) && !this._isVisited(i)
);
const candidate1 = this._lookForNextNodeInCandidates(
nodesWithoutPredecessorsYetToBeVisited
);
if (candidate1.priority === Graph.MAX_PRIORITY) {
return { front_node: null, next_node: candidate1.index };
}
const successorsYetToBeVisited = this.front.reduce((successors, i) => {
if (!this.adjacency_matrix[i]) {
throw new Error("adjacency matrix is missing");
}
this.indexes
.filter(
(j) => this.adjacency_matrix[i]![j] && !this._isVisited(j)
)
.map((j) => successors.add(j));
return successors;
}, new Set<number>());
const candidate2 = this._lookForNextNodeInCandidates(
successorsYetToBeVisited
);
if (candidate1.priority < candidate2.priority) {
return { front_node: null, next_node: candidate1.index };
}
if (candidate1.priority === candidate2.priority) {
if (
candidate1.mean_priority_of_succcessors <
candidate2.mean_priority_of_succcessors
) {
return { front_node: null, next_node: candidate1.index };
}
}
const front_node =
this.indexes.find(
(i) => this.adjacency_matrix[i]?.[candidate2.index as number]
) || null;
return { front_node, next_node: candidate2.index };
}
_lookForNextNodeInCandidates(
candidates: Iterable<number>
): NextNodeCandidate {
let next_node = null,
best_priority = Infinity,
current_mean,
best_mean = Infinity;
for (const candidate of candidates) {
const node = this.nodes[candidate];
if (!node) {
throw new Error("nodes[candidate] is missing");
}
if (node.priority < best_priority) {
best_priority = node.priority;
best_mean = this._meanPriorityOfSuccessors(candidate);
next_node = candidate;
if (node.priority === Graph.MAX_PRIORITY) {
break;
}
} else if (node.priority === best_priority) {
current_mean = this._meanPriorityOfSuccessors(candidate);
if (current_mean < best_mean) {
best_mean = current_mean;
next_node = candidate;
}
}
}
return {
index: next_node,
priority: best_priority,
mean_priority_of_succcessors: best_mean,
};
}
- _meanPriorityOfSuccessors(i: number) {
+ _meanPriorityOfSuccessors(i: number): number {
let sum = 0,
length = 0;
for (let j of this.indexes) {
if (
this.nodes[j] &&
this.adjacency_matrix[i]?.[j] &&
!this._isVisited(j)
) {
sum += this.nodes[j]!.priority;
++length;
}
}
return length > 0 ? sum / length : 0;
}
}
diff --git a/src/datastore/query-and.ts b/src/datastore/query-and.ts
index 12757a6e..e14d9f6d 100644
--- a/src/datastore/query-and.ts
+++ b/src/datastore/query-and.ts
@@ -1,125 +1,125 @@
import { Query, type SQLPreparedStatement } from "./query-base.js";
import QueryStep, { Match } from "./query-step.js";
import Graph from "./graph.js";
import { QueryTypes } from "../main.js";
import type { QueryStage } from "./query-stage.js";
export default class And extends Query {
graph: Graph;
aggregation_steps: { [id: string]: QueryStep };
received_deny_all: boolean;
queries: Query[];
constructor(...queries: Query[]) {
super();
this.queries = queries;
this._reset();
- for (let query of queries) {
+ for (const query of queries) {
this.addQuery(query);
}
}
_reset() {
this.graph = new Graph();
this.aggregation_steps = {};
this.received_deny_all = false;
}
addQuery(query: Query) {
if (this.received_deny_all) {
return;
}
if (query instanceof QueryTypes.DenyAll) {
this._reset();
this.received_deny_all = true;
}
const steps = query.dump();
- for (let step of steps) {
+ for (const step of steps) {
const id = step.hash();
if (this._isInGraph(id)) {
continue;
}
this._addToAggregationSteps(id, step);
this._addDependenciesInGraph(id, step);
}
}
_isInGraph(key: string) {
return key.length === 32 && this.graph.node_ids.includes(key);
}
_addToAggregationSteps(id: string, step: QueryStep) {
this.graph.addNode(id, step.getCost());
this.aggregation_steps[id] = step;
}
_addDependenciesInGraph(id: string, step: QueryStep) {
let dependencies = step
.getUsedFields()
.filter((field) => this._isInGraph(field));
if (step instanceof Match) {
dependencies = dependencies.filter((d1) =>
this._isNotDependencyForAnyInGroup(d1, dependencies)
);
}
- for (let dependency of dependencies) {
+ for (const dependency of dependencies) {
this.graph.addEdge(dependency, id);
}
}
_isNotDependencyForAnyInGroup(id: string, nodeGroup: string[]) {
return !nodeGroup.some(
(node) => id !== node && this.graph.pathExists(id, node)
);
}
dump() {
const sortedStepIds = this.graph.bestFirstSearch();
return sortedStepIds.reduce((steps, id) => {
const currentAggregationStepId = this.aggregation_steps[id];
if (!currentAggregationStepId) {
throw new Error("aggregation steps id is missing");
}
steps.push(currentAggregationStepId);
return steps;
}, [] as QueryStep[]);
}
toPipeline(): QueryStage[] {
const sortedStepIds = this.graph.bestFirstSearch();
const ret = sortedStepIds.reduce((pipeline: QueryStage[], id) => {
const currentAggregationStepId = this.aggregation_steps[id];
if (currentAggregationStepId) {
return [...pipeline, ...currentAggregationStepId.toPipeline()];
} else {
throw new Error("aggregation steps id is missing");
}
}, [] as QueryStage[]);
return ret;
}
toPreparedStatement(): SQLPreparedStatement {
const compiledStatements = this.queries.map((query) =>
query.toPreparedStatement()
);
const parameters = compiledStatements.flatMap(
(statement) => statement.parameters
);
const sqlExpressions = compiledStatements.map(
(statement) => statement.where
);
const sqlJoins = compiledStatements.flatMap(
(statement) => statement.join
);
let counter = 0;
return {
where: `(${sqlExpressions.join(" AND ")})`.replace(
/\$[0-9]+/g,
() => `$${++counter}`
),
join: sqlJoins,
parameters,
};
}
}
diff --git a/src/email/logger-mailer.ts b/src/email/logger-mailer.ts
index 480ce8bc..4f39613c 100644
--- a/src/email/logger-mailer.ts
+++ b/src/email/logger-mailer.ts
@@ -1,15 +1,15 @@
import Mailer from "./mailer.js";
import type { MessageData } from "./message.js";
export default class LoggerMailer extends Mailer {
- async verify() {
+ async verify(): Promise<true> {
return true;
}
- async sendEmail({ to, subject, text }: MessageData) {
+ async sendEmail({ to, subject, text }: MessageData): Promise<void> {
this.app.Logger.info("✉ MAIL", "Would send an email here", {
to,
subject,
text,
});
}
}
diff --git a/src/email/mailer.ts b/src/email/mailer.ts
index 20d5c835..73716bca 100644
--- a/src/email/mailer.ts
+++ b/src/email/mailer.ts
@@ -1,19 +1,19 @@
import type { App } from "../main.js";
import type { MessageData } from "./message.js";
export default abstract class Mailer {
app: App;
abstract verify(): Promise<boolean>;
abstract sendEmail(
message: MessageData & { from_name: string }
): Promise<void>;
- async send(message_data: MessageData) {
+ async send(message_data: MessageData): Promise<void> {
return this.sendEmail({
...message_data,
from_name: this.app.ConfigManager.get("email").from_name,
});
}
- async init(app: App) {
+ async init(app: App): Promise<void> {
this.app = app;
}
}
diff --git a/src/email/message.ts b/src/email/message.ts
index 1a30db8f..54ed3d5d 100644
--- a/src/email/message.ts
+++ b/src/email/message.ts
@@ -1,27 +1,27 @@
import assert from "assert";
import type { App } from "../app/app.js";
export type MessageData = {
to: string;
subject: string;
html: string;
attachments: any[];
text: string;
replyTo?: string;
};
export default class Message {
data: MessageData;
constructor(data: MessageData) {
assert(data.to);
assert(data.subject);
assert(data.html);
assert(
data.attachments === undefined || Array.isArray(data.attachments)
);
this.data = data;
}
- async send(app: App) {
+ async send(app: App): Promise<void> {
return app.mailer.send(this.data);
}
}
diff --git a/src/email/smtp-mailer.ts b/src/email/smtp-mailer.ts
index d20a0c7d..4ee55b39 100644
--- a/src/email/smtp-mailer.ts
+++ b/src/email/smtp-mailer.ts
@@ -1,73 +1,73 @@
import assert from "assert";
import nodemailer from "nodemailer";
import type SMTPTransport from "nodemailer/lib/smtp-transport/index.js";
import type { App } from "../main.js";
import Mailer from "./mailer.js";
import type { MessageData } from "./message.js";
export default class SmtpMailer extends Mailer {
mail_config: { from_name: string; from_address: string };
transport: nodemailer.Transporter;
constructor(
config: {
host: string;
port: number;
user: string;
password: string;
},
additional_options: SMTPTransport.Options = {}
) {
super();
assert(typeof config.host == "string");
assert(typeof config.port == "number");
assert(typeof config.user == "string");
assert(typeof config.password == "string");
this.transport = nodemailer.createTransport({
host: config.host,
port: config.port,
auth: {
user: config.user,
pass: config.password,
},
...additional_options,
});
}
- async verify() {
+ async verify(): Promise<true> {
return this.transport.verify();
}
- async init(app: App) {
+ async init(app: App): Promise<void> {
await super.init(app);
this.mail_config = app.ConfigManager.get("email");
}
async sendEmail({
to,
subject,
text,
html,
from_name,
attachments,
replyTo,
}: MessageData & { from_name: string }) {
return this.transport.sendMail({
from: `${from_name || this.mail_config.from_name} <${
this.mail_config.from_address
}>`,
to,
subject: subject.toString(),
text,
html,
attachments,
replyTo,
});
}
static default_config = {
host: null,
port: null,
user: null,
password: null,
};
}
diff --git a/src/email/templates/simple.test.ts b/src/email/templates/simple.test.ts
index ca191ff6..003aa5d2 100644
--- a/src/email/templates/simple.test.ts
+++ b/src/email/templates/simple.test.ts
@@ -1,22 +1,22 @@
import assert from "assert";
-import { withRunningApp, withTestApp } from "../../test_utils/with-test-app.js";
+import { withTestApp } from "../../test_utils/with-test-app.js";
import SimpleTemplate from "./simple.js";
describe("simpleTemplate", () => {
it("sends an email", async () =>
withTestApp(true, "production", null, async ({ app, mail_api }) => {
await mail_api.deleteAllInstanceEmails();
const message = await SimpleTemplate(app, {
to: "test@example.com",
subject: "Congratulations!",
text: "Enlarge your 'seal' with herbal supplements",
});
await message.send(app);
const messages = await mail_api.getMessages();
assert.strictEqual(messages.length, 1);
assert.strictEqual(
messages[0]!.sender,
`<${app.ConfigManager.get("email").from_address}>`
);
}));
});
diff --git a/src/email/templates/simple.ts b/src/email/templates/simple.ts
index 37a5f1aa..736e4264 100644
--- a/src/email/templates/simple.ts
+++ b/src/email/templates/simple.ts
@@ -1,98 +1,98 @@
import Message from "./../message.js";
import path from "path";
import mjml2html from "mjml";
import assert from "assert";
import type { App } from "../../main.js";
export type Button = { text: string; href: string };
export type SimpleTemplateData = {
text: string;
subject: string;
to: string;
buttons?: Button[];
replyTo?: string;
};
export default async function SimpleTemplate(
app: App,
data: SimpleTemplateData
-) {
+): Promise<Message> {
assert(data.text);
assert(data.subject);
assert(data.to);
assert(data.buttons === undefined || Array.isArray(data.buttons));
if (data.buttons === undefined) {
data.buttons = [];
}
const logo_cid = Math.floor(Math.random() * 10e6).toString();
let html;
if ((app.ConfigManager.get("core") as any).environment === "production") {
html = get_html(app, data, logo_cid);
} else {
html = /* HTML */ `Dummy html text. Enable production mode in app config
to render html each time. This is disabled by default to speed up test
execution time.`;
}
const text = data.text + "\n\n" + buttons_to_text(data.buttons);
return new Message({
to: data.to,
subject: data.subject,
attachments: [
{
filename: path.basename(app.manifest.logo),
path: app.manifest.logo,
cid: logo_cid,
},
],
text,
html,
replyTo: data.replyTo,
});
}
function buttons_to_text(buttons: Button[]) {
return buttons
.map((button) => `\t* ${button.text}: ${button.href}`)
.join("\n");
}
function get_html(app: App, data: SimpleTemplateData, logo_cid: string) {
const result = mjml2html(`
<mjml>
<mj-body>
<mj-section>
<mj-column>
<mj-image width="220" src="cid:${logo_cid}"></mj-image>
<mj-divider border-color="${
(app.manifest.colors && app.manifest.colors.primary) ||
"black"
}"></mj-divider>
<mj-text>
<h1>
${data.subject}
</h1>
${data.text}
</mj-text>
${
(data.buttons &&
data.buttons.map(
(button) =>
`<mj-button href="${
button.href
}" font-size="20px" background-color="${
(app.manifest.colors &&
app.manifest.colors.primary) ||
"#0074D9"
}">${button.text}</mj-button>`
)) ||
""
}
</mj-column>
</mj-section>
</mj-body>
</mjml>
`);
return result.html;
}
diff --git a/src/http/http.ts b/src/http/http.ts
index 5fc11412..108ace43 100644
--- a/src/http/http.ts
+++ b/src/http/http.ts
@@ -1,53 +1,53 @@
import { default as Koa } from "koa";
import Static from "koa-static";
import Router from "@koa/router";
import type { Server } from "http";
import mount from "koa-mount";
import installQS from "koa-qs";
import handleError from "./handle-error.js";
import type { App } from "../main.js";
export default class HttpServer {
name: "www-serer";
private server: Server;
koa: Koa;
router: Router;
config: {
port: number;
"session-cookie-name": string;
"max-payload-bytes": number;
"api-base": string;
};
constructor(public app: App) {
this.koa = new Koa();
installQS(this.koa);
this.koa.context.$app = this.app;
this.router = new Router();
// const rest_url_base = this.config["api-base"];
}
- async start() {
+ async start(): Promise<void> {
this.koa.use(handleError());
this.koa.use(this.router.routes());
this.config = this.app.ConfigManager.get("www-server");
this.server = this.koa.listen(this.config.port);
this.app.Logger.info(
"STARTED",
`App running. URL set in manifest: ${this.app.manifest.base_url}`
);
}
- async stop() {
+ async stop(): Promise<void> {
this.server.close();
}
- addStaticRoute(url_path: string, local_path: string) {
+ addStaticRoute(url_path: string, local_path: string): void {
this.koa.use(mount(url_path, Static(local_path)));
}
}
diff --git a/src/i18n/languages/en.ts b/src/i18n/languages/en.ts
index 3d6efb71..017e0856 100644
--- a/src/i18n/languages/en.ts
+++ b/src/i18n/languages/en.ts
@@ -1,110 +1,117 @@
export const translations = {
- password_reset_email_subject: (app_name: string) =>
+ password_reset_email_subject: (app_name: string): string =>
`[${app_name}] Password reset request`,
- password_reset_email_text: ([app_name, username]: [string, string]) =>
+ password_reset_email_text: ([app_name, username]: [
+ string,
+ string,
+ ]): string =>
`Hello, ${username}. Someone requested a password reset on your account on ${app_name}. If it was you, use the link below to change the password. Otherwise, ignore this message.`,
- password_reset_cta: () => "Change password",
- password_reset_input_cta: (email_address: string) =>
+ password_reset_cta: (): string => "Change password",
+ password_reset_input_cta: (email_address: string): string =>
`Enter the new password for ${email_address}`,
- reveal_password: () => "Reveal password",
- registration_intent_email_subject: (app_name: string) =>
+ reveal_password: (): string => "Reveal password",
+ registration_intent_email_subject: (app_name: string): string =>
`Finish creating your ${app_name} account`,
- registration_intent_email_text: () =>
+ registration_intent_email_text: (): string =>
`To finish setting up your account, click the following link:`,
- registration_intent_cta: () => `Create an account`,
- registration_intent_form_description: () =>
+ registration_intent_cta: (): string => `Create an account`,
+ registration_intent_form_description: (): string =>
`Please fill in the details of your account`,
- password: () => `password`,
- invalid_boolean: (value: string) =>
+ password: (): string => `password`,
+ invalid_boolean: (value: string): string =>
`Value '${value}' is not boolean format.`,
- invalid_context: () =>
+ invalid_context: (): string =>
`Provided value is not an instance of Sealious.Context.`,
- invalid_update: () => `You cannot change a previously set value.`,
- invalid_image: () => `Only image files are allowed.`,
- invalid_email: (value: string) => `${value} is a not valid e-mail address.`,
+ invalid_update: (): string => `You cannot change a previously set value.`,
+ invalid_image: (): string => `Only image files are allowed.`,
+ invalid_email: (value: string): string =>
+ `${value} is a not valid e-mail address.`,
invalid_non_existing_value: (
collection: string,
field: string,
value: string
- ) =>
+ ): string =>
`Collection ${collection} already has a record with '${field}' set to '${value}'.`,
- invalid_date: (value: string) =>
+ invalid_date: (value: string): string =>
`Value '${value}' is not date calendar format. Expected value in standard IS0 8601 (YYYY-MM-DD) format.`,
- invalid_single_reference: (collection: string) =>
+ invalid_single_reference: (collection: string): string =>
`You don't have access to specified resource from collection '${collection}' or it's absent.`,
- invalid_password: (length: number) =>
+ invalid_password: (length: number): string =>
`Password must have at least ${length} characters.`,
- invalid_float: (value: number) =>
+ invalid_float: (value: number): string =>
`Value '${value}' is not a float number format.`,
invalid_existing_value: (
collection: string,
field: string,
value: string
- ) => `No ${collection} with ${field} set to ${value}.`,
- invalid_username: (value: string) =>
+ ): string => `No ${collection} with ${field} set to ${value}.`,
+ invalid_username: (value: string): string =>
`'${value}' is a reserved keyword. Please pick another username.`,
- username_taken: () => `Username already taken.`,
- invalid_text: (value: string, value_type: string) =>
+ username_taken: (): string => `Username already taken.`,
+ invalid_text: (value: string, value_type: string): string =>
`Type of ${value} is ${value_type}, not string.`,
- too_short_text: (value: string, length: number) =>
+ too_short_text: (value: string, length: number): string =>
`Text '${value}' is too short, minimum length is ${length} chars.`,
- too_long_text: (value: string, length: number) =>
+ too_long_text: (value: string, length: number): string =>
`Text '${value}' has exceeded max length of ${length} chars.`,
- invalid_enum: (allowed_values: string) =>
+ invalid_enum: (allowed_values: string): string =>
`Allowed values: ${allowed_values}`,
- invalid_file_id: () => `File of given ID does not exist.`,
- invalid_json_value: (value: string) =>
+ invalid_file_id: (): string => `File of given ID does not exist.`,
+ invalid_json_value: (value: string): string =>
`Value ${value} cannot be represented as JSON object.`,
- invalid_json_object: () => `Value is not an object.`,
- read_only_field: () => `This is a read-only field.`,
- invalid_file_storage: () =>
- `This value should e a file upload or an instance of the File object.`,
- invalid_datetime: (value: number | string) =>
+ invalid_json_object: (): string => `Value is not an object.`,
+ read_only_field: (): string => `This is a read-only field.`,
+ invalid_file_storage: (): string =>
+ `This value should be a file upload or an instance of the File object.`,
+ invalid_datetime: (value: number | string): string =>
`Value '${value}' is not datetime format. Only timestamps are accepted.`,
- invalid_color: () => `Couldn't parse the color.`,
- invalid_integer: (value: string) =>
+ invalid_color: (): string => `Couldn't parse the color.`,
+ invalid_integer: (value: string): string =>
`Value '${value}' is not a int number format.`,
- too_small_integer: (value: string, min: number) =>
+ too_small_integer: (value: string, min: number): string =>
`Value ${value} should be larger than or equal to ${min}.`,
- too_big_integer: (value: string, max: number) =>
+ too_big_integer: (value: string, max: number): string =>
`Value ${value} should be smaller than or equal to ${max}.`,
- policy_if_allow: (filter_name: string) =>
+ policy_if_allow: (filter_name: string): string =>
`Item passes '${filter_name}' filter.`,
- policy_public_allow: () => `Everyone is allowed.`,
- policy_themselves_allow: () => `You are the user in question.`,
- policy_themselves_deny: (user_id: string) =>
+ policy_public_allow: (): string => `Everyone is allowed.`,
+ policy_themselves_allow: (): string => `You are the user in question.`,
+ policy_themselves_deny: (user_id: string): string =>
`You are not the user of ID '${user_id}'.`,
- policy_roles_allow: (roles: string) =>
+ policy_roles_allow: (roles: string): string =>
`You have one of the roles: ${roles}.`,
- policy_roles_deny: (roles: string) =>
+ policy_roles_deny: (roles: string): string =>
`You don't have any of the roles: ${roles}.`,
- policy_logged_in_allow: () => `You are logged in.`,
- policy_logged_in_deny: () => `You are not logged in.`,
- policy_owner_allow: () => `You have created this item.`,
- policy_owner_deny: () => `You are not who created this item.`,
- policy_not_allow: (reason: string) => `It's not true that '${reason}'.`,
- policy_super_allow: () => `This method was ran with a supercontext.`,
- policy_super_deny: () => `This method was not ran with a supercontext.`,
- policy_users_who_can_allow: (action: string, collection: string) =>
+ policy_logged_in_allow: (): string => `You are logged in.`,
+ policy_logged_in_deny: (): string => `You are not logged in.`,
+ policy_owner_allow: (): string => `You have created this item.`,
+ policy_owner_deny: (): string => `You are not who created this item.`,
+ policy_not_allow: (reason: string): string =>
+ `It's not true that '${reason}'.`,
+ policy_super_allow: (): string =>
+ `This method was ran with a supercontext.`,
+ policy_super_deny: (): string =>
+ `This method was not ran with a supercontext.`,
+ policy_users_who_can_allow: (action: string, collection: string): string =>
`You can run action '${action}' on collection '${collection}'.`,
policy_users_who_can_deny: (
action: string,
collection: string,
reason: string
- ) => `You can't ${action} ${collection} - because '${reason}'.`,
- policy_allow: () => `Super-context is always allowed.`,
- policy_user_referenced_in_field_allow: (field: string) =>
+ ): string => `You can't ${action} ${collection} - because '${reason}'.`,
+ policy_allow: (): string => `Super-context is always allowed.`,
+ policy_user_referenced_in_field_allow: (field: string): string =>
`You are the user mentioned in field '${field}'`,
- policy_user_referenced_in_field_deny: (field: string) =>
+ policy_user_referenced_in_field_deny: (field: string): string =>
`You are not the user mentioned in field ${field}.`,
- policy_noone_deny: () => `Noone is allowed.`,
- not_allowed_domain: (domain: string, domains: string[]) =>
+ policy_noone_deny: (): string => `Noone is allowed.`,
+ not_allowed_domain: (domain: string, domains: string[]): string =>
`Domain ${domain} is not allowed here. Allowed domains are: [${domains.join(
", "
)}]`,
- not_allowed_protocol: (protocol: string, protocols: string[]) =>
+ not_allowed_protocol: (protocol: string, protocols: string[]): string =>
`Procotol ${protocol} is not accepted by this field. Allowed protocols are: [${protocols.join(
", "
)}]`,
};
export default translations;
diff --git a/src/test_utils/database-clear.ts b/src/test_utils/database-clear.ts
index c4304e66..88e5d089 100644
--- a/src/test_utils/database-clear.ts
+++ b/src/test_utils/database-clear.ts
@@ -1,12 +1,12 @@
import type { App } from "../main.js";
-export async function databaseClear(app: App) {
+export async function databaseClear(app: App): Promise<void> {
if (app.Datastore.db) {
app.Logger.info("TEST APP", "Clearing the database...");
for (const collection_name in app.collections) {
// eslint-disable-next-line no-await-in-loop
await app.Datastore.remove(collection_name, {}, false);
}
await app.Datastore.remove(app.Metadata.db_collection_name, {}, false);
}
}
diff --git a/src/test_utils/test-app.ts b/src/test_utils/test-app.ts
index 3862ead6..b6eccd91 100644
--- a/src/test_utils/test-app.ts
+++ b/src/test_utils/test-app.ts
@@ -1,90 +1,90 @@
/* eslint-disable */
import locreq_curry from "locreq";
const locreq = locreq_curry(module_dirname(import.meta.url));
import { App, SMTPMailer } from "../main.js";
import type { Environment } from "../app/config.js";
import type { LoggerLevel } from "../app/logger.js";
import LoggerMailer from "../email/logger-mailer.js";
import { module_dirname } from "../utils/module_filename.js";
export class TestApp extends App {
clear_database_on_stop: boolean = true;
collections = { ...App.BaseCollections };
constructor(
uniq_id: string,
env: Environment,
port: number,
base_url: string,
public config = {
upload_path: "/tmp/sealious-uploads",
datastore_mongo: {
host: process.env.SEALIOUS_DB_HOST || "127.0.0.1",
password: "sealious-test",
port: parseInt(process.env.SEALIOUS_DB_PORT || "20722"),
db_name: "sealious-test",
},
datastore_postgres: {
host: process.env.SEALIOUS_PG_HOST || "127.0.0.1",
password: "example",
username: "postgres",
port: parseInt(process.env.SEALIOUS_PG_PORT || "5432"),
db_name: "sealious-test",
},
email: {
from_name: "Sealious test app",
from_address: `sealious-${uniq_id}@example.com`,
},
core: { environment: env },
app: { version: "0.0.0-test" },
logger: {
level: (process.env.SEALIOUS_DEBUG || "none") as LoggerLevel,
// level: "debug3" as LoggerLevel,
},
"www-server": {
port,
},
password_hash: {
iterations: 1,
},
},
public manifest = {
name: "testing app",
logo: locreq.resolve("src/assets/logo.png"),
default_language: "pl",
version: "0.0.0-test",
base_url,
colors: {
primary: "#4d394b",
},
admin_email: "admin@example.com",
},
public mailer = env == "production"
? new SMTPMailer({
host: process.env.SEALIOUS_SMTP_HOST || "127.0.0.1",
port: parseInt(process.env.SEALIOUS_SMTP_PORT || "1825"),
user: "any",
password: "any",
- })
+ })
: new LoggerMailer()
) {
super();
}
async start() {
this.on("stopping", async () => {
if (this.clear_database_on_stop && this.Datastore.db) {
this.Logger.info("TEST APP", "Clearing the database...");
for (const collection_name in this.collections) {
await this.Datastore.remove(collection_name, {}, false);
}
await this.Datastore.remove(
this.Metadata.db_collection_name,
{},
false
);
}
});
await super.start();
}
}
diff --git a/src/test_utils/with-test-app.ts b/src/test_utils/with-test-app.ts
index 8c26da5d..ba2ceb09 100644
--- a/src/test_utils/with-test-app.ts
+++ b/src/test_utils/with-test-app.ts
@@ -1,111 +1,111 @@
import { v4 as uuid } from "uuid";
import getPort from "get-port";
import type { Environment } from "../app/config.js";
import MockRestApi from "./rest-api.js";
import MailcatcherAPI from "./mailcatcher.js";
import { TestApp } from "./test-app.js";
export type TestAppConstructor<T extends TestApp = TestApp> = new (
uniq_id: string,
env: Environment,
port: number,
base_url: string
) => T;
type CallbackParams<FinalTestAppType extends TestApp> = {
app: FinalTestAppType;
base_url: string;
smtp_api_url: string;
rest_api: MockRestApi;
port: number;
mail_api: MailcatcherAPI;
app_class: TestAppConstructor<TestApp>;
uniq_id: string;
env: Environment;
};
type TestCallback<FinalTestAppType extends TestApp> = (
params: CallbackParams<FinalTestAppType>
-) => Promise<any>;
+) => Promise<unknown>;
type extendFn<FinalTestAppType extends TestApp> =
| null
| ((
app_class: TestAppConstructor<TestApp>
) => TestAppConstructor<FinalTestAppType>);
const test_collections: { [collection: string]: string } = {};
export async function withStoppedApp<FinalTestAppType extends TestApp>(
extend_fn: extendFn<FinalTestAppType>,
cb: TestCallback<FinalTestAppType>,
test_collection?: string // tests with the same collection get assigned the same db id
): Promise<any> {
await withTestApp(false, "dev", extend_fn, cb, test_collection);
}
export async function withRunningApp<FinalTestAppType extends TestApp>(
extend_fn: extendFn<FinalTestAppType>,
cb: TestCallback<FinalTestAppType>,
test_collection?: string // tests with the same collection get assigned the same db id
): Promise<any> {
await withTestApp(true, "dev", extend_fn, cb, test_collection);
}
function getAppID(test_collection?: string) {
let uniq_id;
if (test_collection) {
if (!test_collections[test_collection]) {
test_collections[test_collection] = uuid();
}
uniq_id = test_collections[test_collection];
} else {
uniq_id = uuid();
}
return uniq_id;
}
export async function withTestApp<FinalTestAppType extends TestApp>(
auto_start: boolean,
env: Environment,
extend_fn: extendFn<FinalTestAppType>,
fn: (params: CallbackParams<FinalTestAppType>) => Promise<unknown>,
test_collection?: string
-) {
+): Promise<void> {
const port = await getPort();
const base_url = `http://127.0.0.1:${port}`;
const smtp_api_url = `http://${
process.env.SEALIOUS_SMTP_HOST || "127.0.0.1"
}:1088`;
const constructor = extend_fn ? extend_fn(TestApp) : TestApp;
const uniq_id = getAppID(test_collection);
if (!uniq_id || !env || !port || !base_url) {
throw new Error("uniq_id, env, port, or base_url is missing.");
}
const test_app = new constructor(uniq_id, env, port, base_url);
if (auto_start) {
await test_app.start();
}
try {
await fn({
app: test_app as FinalTestAppType,
port,
app_class: constructor,
env,
base_url,
uniq_id,
smtp_api_url,
mail_api: new MailcatcherAPI(smtp_api_url, test_app),
rest_api: new MockRestApi(base_url),
});
} catch (e) {
console.error(e);
throw e;
} finally {
if (test_app.status !== "stopped") {
await test_app.stop();
}
}
}
diff --git a/src/utils/get-datetime.ts b/src/utils/get-datetime.ts
index a16fc4ee..cf303404 100644
--- a/src/utils/get-datetime.ts
+++ b/src/utils/get-datetime.ts
@@ -1,55 +1,58 @@
import prettyMs from "pretty-ms";
const dateFormatters = {
"yyyy-mm-dd": (date: Date) => date.toISOString().split("T")[0],
};
const timeFormatters = {
"hh:mm:ss": (parsed_time: string) => parsed_time.substring(0, 8),
"hh:mm:ss.mmm": (parsed_time: string) => parsed_time.slice(0, -1),
};
const dateFormats = Object.keys(dateFormatters);
const timeFormats = Object.keys(timeFormatters);
-export function getTimeOfNow() {
+export function getTimeOfNow(): string {
return getDateTime(new Date(), "hh:mm:ss.mmm");
}
-export function getTimeDifference(begin: number, end: number) {
+export function getTimeDifference(begin: number, end: number): string {
const date = new Date();
const currentTime = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}.${date.getMilliseconds()}`;
const difference = `${prettyMs(end - begin)}`;
return `${currentTime} (${difference})`;
}
-export function getNow() {
+export function getNow(): string {
return getDateTime(new Date(), "yyyy-mm-dd hh:mm:ss.mmm");
}
-export function getDateTime(date: Date, format_string = "yyyy-mm-dd hh:mm:ss") {
+export function getDateTime(
+ date: Date,
+ format_string = "yyyy-mm-dd hh:mm:ss"
+): string {
const formats = format_string.split(" ");
return formats
.reduce((date_string, format) => {
if (dateFormats.includes(format)) {
return (
date_string +
" " +
dateFormatters[format as keyof typeof dateFormatters](date)
);
} else if (timeFormats.includes(format)) {
const parsed_time = date.toISOString().split("T")[1];
if (!parsed_time) {
throw new Error("Time could not be parsed from date");
}
return (
date_string +
" " +
timeFormatters[format as keyof typeof timeFormatters](
parsed_time
)
);
} else {
throw new Error("Unknown format: " + format);
}
}, "")
- .trimLeft();
+ .trimStart();
}
diff --git a/src/utils/is-empty.ts b/src/utils/is-empty.ts
index 30fa630d..a1ec0b94 100644
--- a/src/utils/is-empty.ts
+++ b/src/utils/is-empty.ts
@@ -1,3 +1,3 @@
-export default function isEmpty(value: any): boolean {
+export default function isEmpty(value: unknown): boolean {
return value === undefined || value === null;
}
diff --git a/src/utils/secure-hasher.ts b/src/utils/secure-hasher.ts
index 79a8ce47..3fba42cf 100644
--- a/src/utils/secure-hasher.ts
+++ b/src/utils/secure-hasher.ts
@@ -1,43 +1,48 @@
import crypto from "crypto";
const algorithm = "sha512";
import { promisify } from "util";
const pbkdf2 = promisify(crypto.pbkdf2);
const SecureHasher = {
- generateRandomSalt(salt_length: number) {
+ generateRandomSalt(salt_length: number): string {
return crypto.randomBytes(salt_length).toString("base64");
},
async hash(
value_to_hash: crypto.BinaryLike,
salt: crypto.BinaryLike,
- { iterations, key_length }: any
- ) {
+ { iterations, key_length }: { iterations: number; key_length: number }
+ ): Promise<string> {
const key = await pbkdf2(
value_to_hash,
salt,
iterations,
key_length,
algorithm
);
- return `${iterations}.${key_length}.${salt}.${key.toString("hex")}`;
+ return `${iterations}.${key_length}.${salt.toString()}.${key.toString(
+ "hex"
+ )}`;
},
- async matches(value: crypto.BinaryLike, hash_with_params: string) {
+ async matches(
+ value: crypto.BinaryLike,
+ hash_with_params: string
+ ): Promise<boolean> {
const [iterations, key_length, salt, hash] =
hash_with_params.split(".");
if (!iterations || !key_length || !salt) {
throw new Error("iterations, key_length or salt is missing");
}
const key = await pbkdf2(
value,
salt,
parseInt(iterations, 10),
parseInt(key_length, 10),
algorithm
);
return key.toString("hex") === hash;
},
};
export default SecureHasher;
diff --git a/src/utils/time-units.ts b/src/utils/time-units.ts
index 5609193c..a9c0c511 100644
--- a/src/utils/time-units.ts
+++ b/src/utils/time-units.ts
@@ -1,23 +1,23 @@
export type TimeUnit = "h" | "m" | "s" | "ms";
const formats: { [unit in TimeUnit]: number } = {
h: 3600000,
m: 60000,
s: 1000,
ms: 1,
};
export default function time_units(
from: TimeUnit,
to: TimeUnit,
amount: number
-) {
+): string {
if (!formats[from] || !formats[to]) {
throw new Error("Please provide a valid time format");
}
if (!amount || typeof amount.valueOf() !== "number") {
throw new Error("Please provide a valid amount to convert");
}
return (formats[from] / formats[to]).toPrecision(8);
}

File Metadata

Mime Type
text/x-diff
Expires
Sat, Nov 28, 03:16 (1 d, 14 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1230153
Default Alt Text
(93 KB)

Event Timeline