Skip to content
Open
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
6 changes: 3 additions & 3 deletions src/lib/deps.js → src/lib/deps.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
export { create, insert, remove, search } from "jsr:@orama/orama@2";
export { persist, restore } from "npm:@orama/plugin-data-persistence@latest";

import "./error.js";
import { db, get_kv } from "./persistence.js";
import "./error.ts";
import { db, get_kv } from "./persistence.ts";
//import push from "./middleware/push.js";
import logger from "./logger.js";
import logger from "./logger.ts";

/**
* @class Oomph
Expand Down
2 changes: 1 addition & 1 deletion src/lib/error.js → src/lib/error.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import logger from "./logger.js";
import logger from "./logger.ts";

Error.prototype.log = async function () {
// console.log(this)
Expand Down
4 changes: 0 additions & 4 deletions src/lib/index.js

This file was deleted.

4 changes: 4 additions & 0 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import "./error.ts";
export { db, get_kv } from "./persistence.ts";

console.log("observabilty loaded into app");
22 changes: 11 additions & 11 deletions src/lib/logger.js → src/lib/logger.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const logger = async (type, ...body) => {
const logger = async (type, ...body) : Promise<void>=> {
try {
const kv = await Deno.openKv();
const id = Date.now();
const key = ["Log", id];
const kv: Deno.Kv = await Deno.openKv();
const id:number = Date.now();
const key: (string | number)[] = ["Log", id];
let value;

if (typeof body[0] === "object") {
Expand All @@ -24,27 +24,27 @@ const logger = async (type, ...body) => {
}
};

const file_logger = async (msg) => {
const kv = await Deno.openKv(`${import.meta.dirname}/observability/logs`);
const file_logger = async (msg:string) => {
const kv:Deno.Kv = await Deno.openKv(`${import.meta.dirname}/observability/logs`);

const logs = await kv.get(["logs"]);
const logs:Deno.KvEntryMaybe<unknown> = await kv.get(["logs"]);

const log = {
...logs.value,
[Date.now()]: msg,
};

const result = await kv.set(["logs"], log);
const result:Deno.KvCommitResult = await kv.set(["logs"], log);
};

const readLogs = async () => {
const kv = await Deno.openKv(`${import.meta.dirname}/observability/logs`);
const kv:Deno.Kv = await Deno.openKv(`${import.meta.dirname}/observability/logs`);
//
// const result = await kv.get(["logs"]);
const stream = kv.watch([["logs"]]).getReader();
const stream: ReadableStreamDefaultReader<[Deno.KvEntryMaybe<unknown>]> = kv.watch([["logs"]]).getReader();

while (true) {
const value = await stream.read();
const value: ReadableStreamDefaultReadResult<[Deno.KvEntryMaybe<unknown>]> = await stream.read();

if (value.done) {
break;
Expand Down
12 changes: 6 additions & 6 deletions src/lib/persistence.js → src/lib/persistence.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//https://docs.oramasearch.com/
import logger from "./logger.js";
import { create, insert, persist, remove, restore, search } from "./deps.js";
import logger from "./logger.ts";
import { create, insert, persist, remove, restore, search } from "./deps.ts";
//import { persist, restore } from "npm:@orama/plugin-data-persistence";

/**
Expand All @@ -14,9 +14,9 @@ import { create, insert, persist, remove, restore, search } from "./deps.js";
*/
const get_kv = async () => {
const app_root = window._cwd;
const db_path = window.isQARequest ? "qa-db" : "db";
const db_path:string = window.isQARequest ? "qa-db" : "db";

const kv_path = app_root && Deno.build.os !== "windows"
const kv_path: string | undefined = app_root && Deno.build.os !== "windows"
? `${app_root}/${db_path}/`
: undefined;
return await Deno.openKv(`${kv_path}`);
Expand Down Expand Up @@ -51,15 +51,15 @@ const db = (name) => {

class DB {
schema = {};
dbName;
dbName:string;
oramaDB;
// for now search everything

constructor() {
this.dbName = this.constructor.name;
}

async search(term) {
async search(term:string):Promise<[]> {
const kv = await get_kv();
const res = await kv.get(["orama", this.dbName]);

Expand Down
30 changes: 17 additions & 13 deletions src/middleware/api.js → src/middleware/api.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
import html from "./html.js";
import html from "./html.ts";

const valid_domain = (referer) => {

const valid_domain = (referer: string): boolean => {
// need to handle valid domain better as a person could just read the code and figure out what refer to use
return ["sauveur.xyz", "http://localhost:8080/", "mmereko.co.za"].includes(
referer,
);
};

const is_authenticated = (auth) => {
const is_authenticated = (auth:string): boolean => {
return [Deno.env.get("SERVER_KEY")].includes(auth);
};

const get_data = async (request) => {
type get_data_response = {
result: {},
type:string
}
const get_data = async (request:Request) : Promise<get_data_response>=> {
let _data = {};
let type = "json";
const referer = request.headers.get("referer");
const isFormReq = request.headers.get("content-type") ===
const referer: string | null = request.headers.get("referer");
const isFormReq : boolean = request.headers.get("content-type") ===
"application/x-www-form-urlencoded";
const isBlob =
const isBlob : boolean =
request.headers.get("content-type") === "application/octet-stream";

if (isFormReq && referer) {
let referer = new URL(request.headers.get("referer"));
let data = new URLSearchParams(await request.text());
let data: URLSearchParams = new URLSearchParams(await request.text());

for (const key of data.keys()) {
const value = data.get(key);
Expand All @@ -48,18 +52,18 @@ const get_data = async (request) => {
return { result: _data, type };
};

const api_middleware = async (request) => {
const api_middleware = async (request: Request) : Promise<Response> => {
const app_path = window._app;
const { pathname } = new URL(request.url);

let response;
try {
let data = {};
const auth = request.headers.get("authorization");
const host = request.headers.get("host");
const auth: string | null = request.headers.get("authorization");
const host : string | null = request.headers.get("host");
const { protocol } = new URL(request.url);
const referer = request.headers.get("referer");
const paths = pathname.split("/");
const paths : string[] = pathname.split("/");
let subPath = "";
if (paths.length > 3) {
paths.pop();
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/asset.js → src/middleware/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import tailwindcss from "npm:tailwindcss@latest";
// https://lightningcss.dev/docs.html
import { transform } from "npm:lightningcss@latest";

const asset_middlware = async (request, type) => {
const asset_middlware = async (request:Request, type:string) :Promise<Response> => {
const _cwd = window._cwd;
const { pathname } = new URL(request.url);
// const isServiceWorker = pathname.includes("sw.js");
Expand Down
6 changes: 3 additions & 3 deletions src/middleware/auth.js → src/middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { getCookies } from "jsr:@std/http@0.216/cookie";

const getAuthToken = (req) => {
const getAuthToken = (req:Request) => {
const { id } = getCookies(req.headers);

return id ? id : req.headers.get("authorization");
};

const isAuthenticated = (req) => {
const isAuthenticated = (req:Request) => {
const id = getAuthToken(req);
return id ? true : false;
};

const authenticate = async (pathname, request) => {
const authenticate = async (pathname:string, request:Request) => {
if (!isAuthenticated(request)) {
const { pathname } = new URL(request.url);

Expand Down
6 changes: 3 additions & 3 deletions src/middleware/hmr.js → src/middleware/hmr.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
const hmr = (pathname, request) => {
const hmr = (pathname:string, request:Request): Response | void => {
if (request.headers.get("upgrade") === "websocket" && pathname === "/hmr") {
const { socket: ws, response } = Deno.upgradeWebSocket(request);

const handleConnected = () => console.log("Connection established");
const handleConnected = ()=> console.log("Connection established");
ws.onopen = () => handleConnected();

const handleDisconnected = () => console.log("Connection closed");
ws.onclose = () => handleDisconnected();

const handleMessage = (ws, msg) => {
const handleMessage = (ws:WebSocket, msg:any) => {
console.log(msg);
};

Expand Down
10 changes: 5 additions & 5 deletions src/middleware/html.js → src/middleware/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import{exists}from "jsr:@std/fs@0.216/exists";
import { compileDoc, getComponents } from "./utls/components/index.js";

let isError = false;
let errorPath;
let errorPath:any;

const html_middleware = async (req, isProd) => {
const html_middleware = async (req:Request, isProd:boolean): Promise<Response> => {
const app_path = window._app;
const paths = new URL(req.url).pathname.replace(/\/$/, "");
const paths : string = new URL(req.url).pathname.replace(/\/$/, "");
let src;
const pathArrays = paths
.replace("/", "")
Expand All @@ -22,7 +22,7 @@ const html_middleware = async (req, isProd) => {
tempSrc = `${app_path}/index.html`;
}

const paramArray = pathArrays;
const paramArray: string[] = pathArrays;
paramArray.pop();

const paramPage = `${app_path}/${paramArray.join("/")}/@.html`;
Expand All @@ -46,7 +46,7 @@ const html_middleware = async (req, isProd) => {
return html_response(src);
};

const getManifest = async (isProd) => {
const getManifest = async (isProd: boolean) => {
const app_path = window._app;
let manifest_path = `file:///${app_path}/src/public/manifest.json`;

Expand Down
6 changes: 0 additions & 6 deletions src/middleware/index.js

This file was deleted.

6 changes: 6 additions & 0 deletions src/middleware/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import script_middleware from "./script.ts";
import asset_middlware from "./asset.ts";
import api_middleware from "./api.ts";
import html_middleware from "./html.ts";

export { api_middleware, asset_middlware, html_middleware, script_middleware };
5 changes: 3 additions & 2 deletions src/middleware/push.js → src/middleware/push.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@
// https://datatracker.ietf.org/doc/html/draft-ietf-webpush-vapid-02#section-4
// https://datatracker.ietf.org/doc/html/rfc8030#section-8
// https://blog.mozilla.org/services/2016/04/04/using-vapid-with-webpush/

import { generateKeys, getHeaders, getRawKey } from "../lib/vapid/index.js";

const push = async (request) => {
const push = async (request:Request): Promise<Response | undefined> => {
const { pathname, searchParams } = oomph.req(request);

const publicKey = Deno.env.get("PUSH_PUBLIC_KEY");
const publicKey:string | undefined = Deno.env.get("PUSH_PUBLIC_KEY");

if (pathname === "/push/vapidPublicKey" && request.method === "GET") {
return new Response(await getRawKey());
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/script.js → src/middleware/script.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const script_middleware = async (req) => {
const script_middleware = async (req:Request) : Promise<Response> => {
const app_path = window._app;
const { pathname: _pathname } = new URL(req.url);
console.log(_pathname);
Expand Down
File renamed without changes.
File renamed without changes.
4 changes: 2 additions & 2 deletions src/mod.js → src/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ export {
asset_middlware,
html_middleware,
script_middleware,
} from "./middleware/index.js";
} from "./middleware/index.ts";

import oomph from "./lib/deps.js";
import oomph from "./lib/deps.ts";

export { oomph };

8 changes: 4 additions & 4 deletions src/views/logger.js → src/views/logger.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
const logView = async (request) => {
const logView = async (request:Request) :Promise<Response | undefined> => {
const { pathname } = oomph.req(request);

if (pathname === "/logs" && request.method === "GET") {
const kv = await Deno.openKv();
const log = await kv.list({ prefix: ["Log"] });
const kv: Deno.Kv = await Deno.openKv();
const log: Deno.KvListIterator<any> = await kv.list({ prefix: ["Log"] });

// for await (const entry of log) {
// kv.delete(entry.key)
// }
const logs = [];
const logs: Array<Deno.KvEntry<any>> = [];

for await (const res of log) logs.push(res);
logs.sort().reverse();
Expand Down
Empty file added tests/lib/deps.test.ts
Empty file.
Empty file added tests/lib/error.test.ts
Empty file.
Empty file added tests/lib/index.test.ts
Empty file.
1 change: 1 addition & 0 deletions tests/lib/logger.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import {assertEquals} from "https://deno.land/std@0.216.0/assert/mod.ts"
Empty file added tests/lib/persistence.test.ts
Empty file.
1 change: 1 addition & 0 deletions tests/lib/vapid/common.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import { assert } from "https://deno.land/std@0.216.0/assert/assert.ts";
Empty file added tests/lib/vapid/der.test.ts
Empty file.
Empty file added tests/lib/vapid/index.test.ts
Empty file.
Empty file added tests/lib/vapid/vapid.test.ts
Empty file.
Empty file added tests/middleware/api.test.ts
Empty file.
Empty file added tests/middleware/asset.test.ts
Empty file.
Empty file added tests/middleware/auth.test.ts
Empty file.
Empty file added tests/middleware/hmr.test.ts
Empty file.
Empty file added tests/middleware/html.test.ts
Empty file.
54 changes: 54 additions & 0 deletions tests/middleware/push.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { assertEquals } from "https://deno.land/std@0.216.0/assert/mod.ts"
import push from "../../src/middleware/push.ts";

Deno.test("Test /push endpoint for POST request", async () => {
const request = new Request("/push", {
method: "POST",
body: JSON.stringify({
subscription: {
endpoint: "https://example.com/endpoint",
},
ttl: 3600,
}),
});

const response = await push(request);

assertEquals(response, new Response("Pushed Attempted", { status: 201 }));
});


Deno.test("Test /push/vapidPublicKey endpoint for GET request", async () => {
const request = new Request("/push/vapidPublicKey", {
method: "GET",
body: JSON.stringify({
subscription: {
endpoint: "https://example.com/endpoint",
},
ttl: 3600,
}),
});

const response = await push(request);

assertEquals(response?.status, 200);
});


Deno.test("Test /push/register endpoint for POST request", async () => {
const request = new Request("/push/register", {
method: "POST",
body: JSON.stringify({
subscription: {
endpoint: "https://example.com/endpoint",
},
ttl: 3600,
}),
});

const response = await push(request);

assertEquals(response, new Response("Registered", { status: 201 }));
});


Loading