1
0

Reduce lint errors

This commit is contained in:
Zef Hemel 2022-10-15 19:02:56 +02:00
parent 68809ff958
commit 574014a8be
27 changed files with 199 additions and 194 deletions

View File

@ -79,7 +79,7 @@ export class DiskSpacePrimitives implements SpacePrimitives {
contentType: contentType,
},
};
} catch (e) {
} catch {
// console.error("Error while reading file", name, e);
throw Error(`Could not read file ${name}`);
}
@ -137,7 +137,7 @@ export class DiskSpacePrimitives implements SpacePrimitives {
lastModified: s.mtime!.getTime(),
perm: "rw",
};
} catch (e) {
} catch {
// console.error("Error while getting page meta", pageName, e);
throw Error(`Could not get meta for ${name}`);
}
@ -157,7 +157,7 @@ export class DiskSpacePrimitives implements SpacePrimitives {
continue;
}
const fullPath = path.join(dir, file.name);
let s = await Deno.stat(fullPath);
const s = await Deno.stat(fullPath);
if (file.isDirectory) {
await walkPath(fullPath);
} else {
@ -180,7 +180,7 @@ export class DiskSpacePrimitives implements SpacePrimitives {
// Plugs
invokeFunction(
plug: Plug<any>,
env: string,
_env: string,
name: string,
args: any[],
): Promise<any> {

View File

@ -1,4 +1,4 @@
import { AttachmentMeta, FileMeta, PageMeta } from "../types.ts";
import { FileMeta } from "../types.ts";
import { Plug } from "../../plugos/plug.ts";
import { FileData, FileEncoding, SpacePrimitives } from "./space_primitives.ts";
@ -21,7 +21,7 @@ export class HttpSpacePrimitives implements SpacePrimitives {
options.headers = options.headers || {};
options.headers["Authorization"] = `Bearer ${this.token}`;
}
let result = await fetch(url, options);
const result = await fetch(url, options);
if (result.status === 401) {
throw Error("Unauthorized");
}
@ -29,20 +29,18 @@ export class HttpSpacePrimitives implements SpacePrimitives {
}
public async fetchFileList(): Promise<FileMeta[]> {
let req = await this.authenticatedFetch(this.fsUrl, {
const req = await this.authenticatedFetch(this.fsUrl, {
method: "GET",
});
let result: FileMeta[] = await req.json();
return result;
return req.json();
}
async readFile(
name: string,
encoding: FileEncoding,
): Promise<{ data: FileData; meta: FileMeta }> {
let res = await this.authenticatedFetch(`${this.fsUrl}/${name}`, {
const res = await this.authenticatedFetch(`${this.fsUrl}/${name}`, {
method: "GET",
});
if (res.status === 404) {
@ -52,13 +50,13 @@ export class HttpSpacePrimitives implements SpacePrimitives {
switch (encoding) {
case "arraybuffer":
{
let abBlob = await res.blob();
const abBlob = await res.blob();
data = await abBlob.arrayBuffer();
}
break;
case "dataurl":
{
let dUBlob = await res.blob();
const dUBlob = await res.blob();
data = arrayBufferToDataUrl(await dUBlob.arrayBuffer());
}
break;
@ -76,7 +74,6 @@ export class HttpSpacePrimitives implements SpacePrimitives {
name: string,
encoding: FileEncoding,
data: FileData,
selfUpdate?: boolean,
): Promise<FileMeta> {
let body: any = null;
@ -89,7 +86,7 @@ export class HttpSpacePrimitives implements SpacePrimitives {
data = dataUrlToArrayBuffer(data as string);
break;
}
let res = await this.authenticatedFetch(`${this.fsUrl}/${name}`, {
const res = await this.authenticatedFetch(`${this.fsUrl}/${name}`, {
method: "PUT",
headers: {
"Content-type": "application/octet-stream",
@ -101,7 +98,7 @@ export class HttpSpacePrimitives implements SpacePrimitives {
}
async deleteFile(name: string): Promise<void> {
let req = await this.authenticatedFetch(`${this.fsUrl}/${name}`, {
const req = await this.authenticatedFetch(`${this.fsUrl}/${name}`, {
method: "DELETE",
});
if (req.status !== 200) {
@ -110,7 +107,7 @@ export class HttpSpacePrimitives implements SpacePrimitives {
}
async getFileMeta(name: string): Promise<FileMeta> {
let res = await this.authenticatedFetch(`${this.fsUrl}/${name}`, {
const res = await this.authenticatedFetch(`${this.fsUrl}/${name}`, {
method: "OPTIONS",
});
if (res.status === 404) {
@ -132,7 +129,7 @@ export class HttpSpacePrimitives implements SpacePrimitives {
// Plugs
async proxySyscall(plug: Plug<any>, name: string, args: any[]): Promise<any> {
let req = await this.authenticatedFetch(
const req = await this.authenticatedFetch(
`${this.plugUrl}/${plug.name}/syscall/${name}`,
{
method: "POST",
@ -143,7 +140,7 @@ export class HttpSpacePrimitives implements SpacePrimitives {
},
);
if (req.status !== 200) {
let error = await req.text();
const error = await req.text();
throw Error(error);
}
if (req.headers.get("Content-length") === "0") {
@ -163,7 +160,7 @@ export class HttpSpacePrimitives implements SpacePrimitives {
return plug.invoke(name, args);
}
// Or dispatch to server
let req = await this.authenticatedFetch(
const req = await this.authenticatedFetch(
`${this.plugUrl}/${plug.name}/function/${name}`,
{
method: "POST",
@ -174,7 +171,7 @@ export class HttpSpacePrimitives implements SpacePrimitives {
},
);
if (req.status !== 200) {
let error = await req.text();
const error = await req.text();
throw Error(error);
}
if (req.headers.get("Content-length") === "0") {
@ -189,21 +186,21 @@ export class HttpSpacePrimitives implements SpacePrimitives {
}
function dataUrlToArrayBuffer(dataUrl: string): ArrayBuffer {
var binary_string = window.atob(dataUrl.split(",")[1]);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
const binary_string = atob(dataUrl.split(",")[1]);
const len = binary_string.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
function arrayBufferToDataUrl(buffer: ArrayBuffer): string {
var binary = "";
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
let binary = "";
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return `data:application/octet-stream,${window.btoa(binary)}`;
return `data:application/octet-stream,${btoa(binary)}`;
}

View File

@ -25,9 +25,9 @@ export class Space extends EventEmitter<SpaceEvents> {
}
public async updatePageList() {
let newPageList = await this.fetchPageList();
const newPageList = await this.fetchPageList();
// console.log("Updating page list", newPageList);
let deletedPages = new Set<string>(this.pageMetaCache.keys());
const deletedPages = new Set<string>(this.pageMetaCache.keys());
newPageList.forEach((meta) => {
const pageName = meta.name;
const oldPageMeta = this.pageMetaCache.get(pageName);
@ -84,7 +84,7 @@ export class Space extends EventEmitter<SpaceEvents> {
this.updatePageList().catch(console.error);
}
async deletePage(name: string, deleteDate?: number): Promise<void> {
async deletePage(name: string): Promise<void> {
await this.getPageMeta(name); // Check if page exists, if not throws Error
await this.space.deleteFile(`${name}.md`);
@ -94,8 +94,8 @@ export class Space extends EventEmitter<SpaceEvents> {
}
async getPageMeta(name: string): Promise<PageMeta> {
let oldMeta = this.pageMetaCache.get(name);
let newMeta = fileMetaToPageMeta(
const oldMeta = this.pageMetaCache.get(name);
const newMeta = fileMetaToPageMeta(
await this.space.getFileMeta(`${name}.md`),
);
if (oldMeta) {
@ -121,7 +121,7 @@ export class Space extends EventEmitter<SpaceEvents> {
}
async listPlugs(): Promise<string[]> {
let allFiles = await this.space.fetchFileList();
const allFiles = await this.space.fetchFileList();
return allFiles
.filter((fileMeta) => fileMeta.name.endsWith(".plug.json"))
.map((fileMeta) => fileMeta.name);
@ -132,16 +132,16 @@ export class Space extends EventEmitter<SpaceEvents> {
}
async readPage(name: string): Promise<{ text: string; meta: PageMeta }> {
let pageData = await this.space.readFile(`${name}.md`, "string");
let previousMeta = this.pageMetaCache.get(name);
let newMeta = fileMetaToPageMeta(pageData.meta);
const pageData = await this.space.readFile(`${name}.md`, "string");
const previousMeta = this.pageMetaCache.get(name);
const newMeta = fileMetaToPageMeta(pageData.meta);
if (previousMeta) {
if (previousMeta.lastModified !== newMeta.lastModified) {
// Page changed since last cached metadata, trigger event
this.emit("pageChanged", newMeta);
}
}
let meta = this.metaCacher(name, newMeta);
const meta = this.metaCacher(name, newMeta);
return {
text: pageData.data as string,
meta: meta,

View File

@ -18,7 +18,14 @@
},
"fmt": {
"files": {
"exclude": ["website", "dist", "dist_bundle", "pages"]
"exclude": [
"dist",
"dist_bundle",
"pages",
"website",
"test_space",
"plugos/environments/worker_bundle.json"
]
}
},
"tasks": {

View File

@ -36,7 +36,7 @@ export function applyQuery<T>(parsedQuery: ParsedQuery, records: T[]): T[] {
recordLoop:
for (const record of records) {
const recordAny: any = record;
for (let { op, prop, value } of parsedQuery.filter) {
for (const { op, prop, value } of parsedQuery.filter) {
switch (op) {
case "=": {
const recordPropVal = recordAny[prop];
@ -123,8 +123,8 @@ export function applyQuery<T>(parsedQuery: ParsedQuery, records: T[]): T[] {
}
if (parsedQuery.select) {
resultRecords = resultRecords.map((rec) => {
let newRec: any = {};
for (let k of parsedQuery.select!) {
const newRec: any = {};
for (const k of parsedQuery.select!) {
newRec[k] = rec[k];
}
return newRec;
@ -139,27 +139,27 @@ export function removeQueries(pt: ParseTree) {
if (t.type !== "CommentBlock") {
return false;
}
let text = t.children![0].text!;
let match = directiveStartRegex.exec(text);
const text = t.children![0].text!;
const match = directiveStartRegex.exec(text);
if (!match) {
return false;
}
let directiveType = match[1];
let parentChildren = t.parent!.children!;
let index = parentChildren.indexOf(t);
let nodesToReplace: ParseTree[] = [];
const directiveType = match[1];
const parentChildren = t.parent!.children!;
const index = parentChildren.indexOf(t);
const nodesToReplace: ParseTree[] = [];
for (let i = index + 1; i < parentChildren.length; i++) {
let n = parentChildren[i];
const n = parentChildren[i];
if (n.type === "CommentBlock") {
let text = n.children![0].text!;
let match = directiveEndRegex.exec(text);
const text = n.children![0].text!;
const match = directiveEndRegex.exec(text);
if (match && match[1] === directiveType) {
break;
}
}
nodesToReplace.push(n);
}
let renderedText = nodesToReplace.map(renderToText).join("");
const renderedText = nodesToReplace.map(renderToText).join("");
parentChildren.splice(index + 1, nodesToReplace.length, {
text: new Array(renderedText.length + 1).join(" "),
});

View File

@ -12,7 +12,7 @@ export function addParentPointers(tree: ParseTree) {
if (!tree.children) {
return;
}
for (let child of tree.children) {
for (const child of tree.children) {
if (child.parent) {
// Already added parent pointers before
return;
@ -27,7 +27,7 @@ export function removeParentPointers(tree: ParseTree) {
if (!tree.children) {
return;
}
for (let child of tree.children) {
for (const child of tree.children) {
removeParentPointers(child);
}
}
@ -62,7 +62,7 @@ export function collectNodesMatching(
}
let results: ParseTree[] = [];
if (tree.children) {
for (let child of tree.children) {
for (const child of tree.children) {
results = [...results, ...collectNodesMatching(child, matchFn)];
}
}
@ -75,11 +75,11 @@ export function replaceNodesMatching(
substituteFn: (tree: ParseTree) => ParseTree | null | undefined,
) {
if (tree.children) {
let children = tree.children.slice();
for (let child of children) {
let subst = substituteFn(child);
const children = tree.children.slice();
for (const child of children) {
const subst = substituteFn(child);
if (subst !== undefined) {
let pos = tree.children.indexOf(child);
const pos = tree.children.indexOf(child);
if (subst) {
tree.children.splice(pos, 1, subst);
} else {
@ -124,8 +124,8 @@ export function nodeAtPos(tree: ParseTree, pos: number): ParseTree | null {
if (!tree.children) {
return tree;
}
for (let child of tree.children) {
let n = nodeAtPos(child, pos);
for (const child of tree.children) {
const n = nodeAtPos(child, pos);
if (n && n.text !== undefined) {
// Got a text node, let's return its parent
return tree;
@ -139,11 +139,11 @@ export function nodeAtPos(tree: ParseTree, pos: number): ParseTree | null {
// Turn ParseTree back into text
export function renderToText(tree: ParseTree): string {
let pieces: string[] = [];
const pieces: string[] = [];
if (tree.text !== undefined) {
return tree.text;
}
for (let child of tree.children!) {
for (const child of tree.children!) {
pieces.push(renderToText(child));
}
return pieces.join("");

View File

@ -1,5 +1,3 @@
import { buf } from "https://deno.land/x/sqlite3@0.6.1/src/util.ts";
export function base64Decode(s: string): Uint8Array {
const binString = atob(s);
const len = binString.length;

View File

@ -36,8 +36,8 @@ export class ConsoleLogger {
}
logMessage(values: any[]): string {
let pieces: string[] = [];
for (let val of values) {
const pieces: string[] = [];
for (const val of values) {
switch (typeof val) {
case "string":
case "number":

View File

@ -86,7 +86,7 @@ self.addEventListener("message", (event: { data: WorkerMessage }) => {
switch (data.type) {
case "load":
{
let fn2 = new Function(wrapScript(data.code!));
const fn2 = new Function(wrapScript(data.code!));
loadedFunctions.set(data.name!, fn2());
workerPostMessage({
type: "inited",
@ -98,8 +98,8 @@ self.addEventListener("message", (event: { data: WorkerMessage }) => {
case "load-dependency":
{
// console.log("Received dep", data.name);
let fn3 = new Function(`return ${data.code!}`);
let v = fn3();
const fn3 = new Function(`return ${data.code!}`);
const v = fn3();
loadedModules.set(data.name!, v);
// console.log("Dep val", v);
workerPostMessage({
@ -110,12 +110,12 @@ self.addEventListener("message", (event: { data: WorkerMessage }) => {
break;
case "invoke":
{
let fn = loadedFunctions.get(data.name!);
const fn = loadedFunctions.get(data.name!);
if (!fn) {
throw new Error(`Function not loaded: ${data.name}`);
}
try {
let result = await Promise.resolve(fn(...(data.args || [])));
const result = await Promise.resolve(fn(...(data.args || [])));
workerPostMessage({
type: "result",
id: data.id,
@ -136,7 +136,7 @@ self.addEventListener("message", (event: { data: WorkerMessage }) => {
break;
case "syscall-response":
{
let syscallId = data.id!;
const syscallId = data.id!;
const lookup = pendingRequests.get(syscallId);
if (!lookup) {
console.log(

View File

@ -8,7 +8,6 @@ import {
import { load as nativeLoad } from "./src/native_loader.ts";
import { load as portableLoad } from "./src/portable_loader.ts";
import { ModuleEntry } from "./src/deno.ts";
import { resolve } from "https://deno.land/std@0.122.0/path/win32.ts";
export interface DenoPluginOptions {
/**

View File

@ -24,7 +24,7 @@ export class DenoCronHook implements Hook<CronHookT> {
function reloadCrons() {
tasks.forEach((task) => task.stop());
tasks = [];
for (let plug of system.loadedPlugs.values()) {
for (const plug of system.loadedPlugs.values()) {
if (!plug.manifest) {
continue;
}
@ -59,15 +59,15 @@ export class DenoCronHook implements Hook<CronHookT> {
}
validateManifest(manifest: Manifest<CronHookT>): string[] {
let errors: string[] = [];
for (const [name, functionDef] of Object.entries(manifest.functions)) {
const errors: string[] = [];
for (const functionDef of Object.values(manifest.functions)) {
if (!functionDef.cron) {
continue;
}
const crons = Array.isArray(functionDef.cron)
? functionDef.cron
: [functionDef.cron];
for (let cronDef of crons) {
for (const _cronDef of crons) {
// if (!cron.validate(cronDef)) {
// errors.push(`Invalid cron expression ${cronDef}`);
// }

View File

@ -50,7 +50,7 @@ export class EndpointHook implements Hook<EndpointHookT> {
}
const functions = manifest.functions;
console.log("Checking plug", plugName);
let prefix = `${this.prefix}/${plugName}`;
const prefix = `${this.prefix}/${plugName}`;
if (!requestPath.startsWith(prefix)) {
continue;
}
@ -58,12 +58,12 @@ export class EndpointHook implements Hook<EndpointHookT> {
if (!functionDef.http) {
continue;
}
let endpoints = Array.isArray(functionDef.http)
const endpoints = Array.isArray(functionDef.http)
? functionDef.http
: [functionDef.http];
console.log(endpoints);
for (const { path, method } of endpoints) {
let prefixedPath = `${prefix}${path}`;
const prefixedPath = `${prefix}${path}`;
if (
prefixedPath === requestPath &&
((method || "GET") === req.method || method === "ANY")
@ -109,15 +109,15 @@ export class EndpointHook implements Hook<EndpointHookT> {
}
validateManifest(manifest: Manifest<EndpointHookT>): string[] {
let errors = [];
for (const [name, functionDef] of Object.entries(manifest.functions)) {
const errors = [];
for (const functionDef of Object.values(manifest.functions)) {
if (!functionDef.http) {
continue;
}
let endpoints = Array.isArray(functionDef.http)
const endpoints = Array.isArray(functionDef.http)
? functionDef.http
: [functionDef.http];
for (let { path, method } of endpoints) {
for (const { path, method } of endpoints) {
if (!path) {
errors.push("Path not defined for endpoint");
}

View File

@ -68,7 +68,7 @@ export class Plug<HookT> {
return await this.sandbox.invoke(name, args);
}
async stop() {
stop() {
this.sandbox.stop();
}
}

View File

@ -40,7 +40,7 @@ export class Sandbox {
async load(name: string, code: string): Promise<void> {
await this.worker.ready;
let outstandingInit = this.outstandingInits.get(name);
const outstandingInit = this.outstandingInits.get(name);
if (outstandingInit) {
// Load already in progress, let's wait for it...
return new Promise((resolve) => {
@ -82,19 +82,21 @@ export class Sandbox {
async onMessage(data: ControllerMessage) {
switch (data.type) {
case "inited":
let initCb = this.outstandingInits.get(data.name!);
case "inited": {
const initCb = this.outstandingInits.get(data.name!);
initCb && initCb();
this.outstandingInits.delete(data.name!);
break;
case "dependency-inited":
let depInitCb = this.outstandingDependencyInits.get(data.name!);
}
case "dependency-inited": {
const depInitCb = this.outstandingDependencyInits.get(data.name!);
depInitCb && depInitCb();
this.outstandingDependencyInits.delete(data.name!);
break;
}
case "syscall":
try {
let result = await this.plug.syscall(data.name!, data.args!);
const result = await this.plug.syscall(data.name!, data.args!);
this.worker.postMessage({
type: "syscall-response",
@ -110,8 +112,8 @@ export class Sandbox {
} as WorkerMessage);
}
break;
case "result":
let resultCbs = this.outstandingInvocations.get(data.id!);
case "result": {
const resultCbs = this.outstandingInvocations.get(data.id!);
this.outstandingInvocations.delete(data.id!);
if (data.error) {
resultCbs &&
@ -122,7 +124,8 @@ export class Sandbox {
resultCbs && resultCbs.resolve(data.result);
}
break;
case "log":
}
case "log": {
this.logBuffer.push({
level: data.level!,
message: data.message!,
@ -133,12 +136,13 @@ export class Sandbox {
}
console.log(`[Sandbox ${data.level}]`, data.message);
break;
}
default:
console.error("Unknown message type", data);
}
}
async invoke(name: string, args: any[]): Promise<any> {
invoke(name: string, args: any[]): Promise<any> {
this.reqId++;
this.worker.postMessage({
type: "invoke",

View File

@ -10,9 +10,9 @@ const pagePrefix = "💭 ";
export async function readFileCloud(
name: string,
encoding: FileEncoding,
_encoding: FileEncoding,
): Promise<{ data: FileData; meta: FileMeta } | undefined> {
let originalUrl = name.substring(
const originalUrl = name.substring(
pagePrefix.length,
name.length - ".md".length,
);
@ -27,7 +27,7 @@ export async function readFileCloud(
}
let text = "";
try {
let r = await fetch(`${url}.md`);
const r = await fetch(`${url}.md`);
text = await r.text();
if (r.status !== 200) {
text = `ERROR: ${text}`;

View File

@ -11,7 +11,7 @@ import {
system,
} from "$sb/silverbullet-syscall/mod.ts";
import { events, store } from "$sb/plugos-syscall/mod.ts";
import { events } from "$sb/plugos-syscall/mod.ts";
import {
addParentPointers,
@ -67,7 +67,7 @@ export async function pageQueryProvider({
for (const { page, value } of await index.queryPrefix("meta:")) {
const p = allPageMap.get(page);
if (p) {
for (let [k, v] of Object.entries(value)) {
for (const [k, v] of Object.entries(value)) {
p[k] = v;
}
}

View File

@ -32,7 +32,7 @@ export async function queryProvider({
for (const { page, value } of await index.queryPrefix("meta:")) {
const p = allPageMap.get(page);
if (p) {
for (let [k, v] of Object.entries(value)) {
for (const [k, v] of Object.entries(value)) {
p[k] = v;
}
}

View File

@ -65,7 +65,7 @@ export function extractMeta(
if (t.type === "Hashtag") {
// Check if if nested directly into a Paragraph
if (t.parent && t.parent.type === "Paragraph") {
let tagname = t.children![0].text;
const tagname = t.children![0].text;
if (!data.tags) {
data.tags = [];
}

View File

@ -2,11 +2,11 @@ const maxWidth = 70;
// Nicely format an array of JSON objects as a Markdown table
export function jsonToMDTable(
jsonArray: any[],
valueTransformer: (k: string, v: any) => string = (k, v) => "" + v,
valueTransformer: (k: string, v: any) => string = (_k, v) => "" + v,
): string {
const fieldWidths = new Map<string, number>();
for (let entry of jsonArray) {
for (let k of Object.keys(entry)) {
for (const entry of jsonArray) {
for (const k of Object.keys(entry)) {
let fieldWidth = fieldWidths.get(k);
if (!fieldWidth) {
fieldWidth = valueTransformer(k, entry[k]).length;
@ -18,7 +18,7 @@ export function jsonToMDTable(
}
let fullWidth = 0;
for (let v of fieldWidths.values()) {
for (const v of fieldWidths.values()) {
fullWidth += v + 1;
}
@ -43,9 +43,9 @@ export function jsonToMDTable(
"|",
);
for (const val of jsonArray) {
let el = [];
for (let prop of headerList) {
let s = valueTransformer(prop, val[prop]);
const el = [];
for (const prop of headerList) {
const s = valueTransformer(prop, val[prop]);
el.push(s + charPad(" ", fieldWidths.get(prop)! - s.length));
}
lines.push("|" + el.join("|") + "|");

View File

@ -11,7 +11,6 @@ import {
space,
} from "$sb/silverbullet-syscall/mod.ts";
import { events } from "$sb/plugos-syscall/mod.ts";
import {
addParentPointers,
collectNodesMatching,
@ -178,7 +177,7 @@ export async function postponeCommand() {
if (!option) {
return;
}
let d = new Date(date);
const d = new Date(date);
switch (option.name) {
case "a day":
d.setDate(d.getDate() + 1);
@ -207,8 +206,8 @@ export async function queryProvider({
query,
}: QueryProviderEvent): Promise<Task[]> {
const allTasks: Task[] = [];
for (let { key, page, value } of await index.queryPrefix("task:")) {
let [, pos] = key.split(":");
for (const { key, page, value } of await index.queryPrefix("task:")) {
const pos = key.split(":")[1];
allTasks.push({
...value,
page: page,

View File

@ -4,7 +4,7 @@ import {
FileEncoding,
SpacePrimitives,
} from "../../common/spaces/space_primitives.ts";
import { AttachmentMeta, FileMeta, PageMeta } from "../../common/types.ts";
import { FileMeta } from "../../common/types.ts";
import { NamespaceOperation, PageNamespaceHook } from "./page_namespace.ts";
export class PlugSpacePrimitives implements SpacePrimitives {
@ -18,7 +18,7 @@ export class PlugSpacePrimitives implements SpacePrimitives {
pageName: string,
...args: any[]
): Promise<any> | false {
for (let { operation, pattern, plug, name } of this.hook.spaceFunctions) {
for (const { operation, pattern, plug, name } of this.hook.spaceFunctions) {
if (operation === type && pageName.match(pattern)) {
return plug.invoke(name, [pageName, ...args]);
}
@ -27,11 +27,11 @@ export class PlugSpacePrimitives implements SpacePrimitives {
}
async fetchFileList(): Promise<FileMeta[]> {
let allFiles: FileMeta[] = [];
for (let { plug, name, operation } of this.hook.spaceFunctions) {
const allFiles: FileMeta[] = [];
for (const { plug, name, operation } of this.hook.spaceFunctions) {
if (operation === "listFiles") {
try {
for (let pm of await plug.invoke(name, [])) {
for (const pm of await plug.invoke(name, [])) {
allFiles.push(pm);
}
} catch (e) {
@ -39,8 +39,8 @@ export class PlugSpacePrimitives implements SpacePrimitives {
}
}
}
let result = await this.wrapped.fetchFileList();
for (let pm of result) {
const result = await this.wrapped.fetchFileList();
for (const pm of result) {
allFiles.push(pm);
}
return allFiles;
@ -58,7 +58,7 @@ export class PlugSpacePrimitives implements SpacePrimitives {
}
getFileMeta(name: string): Promise<FileMeta> {
let result = this.performOperation("getFileMeta", name);
const result = this.performOperation("getFileMeta", name);
if (result) {
return result;
}
@ -71,7 +71,7 @@ export class PlugSpacePrimitives implements SpacePrimitives {
data: FileData,
selfUpdate?: boolean,
): Promise<FileMeta> {
let result = this.performOperation(
const result = this.performOperation(
"writeFile",
name,
encoding,
@ -86,7 +86,7 @@ export class PlugSpacePrimitives implements SpacePrimitives {
}
deleteFile(name: string): Promise<void> {
let result = this.performOperation("deleteFile", name);
const result = this.performOperation("deleteFile", name);
if (result) {
return result;
}

View File

@ -40,7 +40,7 @@ export function ensureTable(db: SQLite): Promise<void> {
export function pageIndexSyscalls(db: SQLite): SysCallMapping {
const apiObj: SysCallMapping = {
"index.set": async (ctx, page: string, key: string, value: any) => {
"index.set": async (_ctx, page: string, key: string, value: any) => {
await asyncExecute(
db,
`UPDATE ${tableName} SET value = ? WHERE key = ? AND page = ?`,
@ -59,11 +59,11 @@ export function pageIndexSyscalls(db: SQLite): SysCallMapping {
}
},
"index.batchSet": async (ctx, page: string, kvs: KV[]) => {
for (let { key, value } of kvs) {
for (const { key, value } of kvs) {
await apiObj["index.set"](ctx, page, key, value);
}
},
"index.delete": async (ctx, page: string, key: string) => {
"index.delete": async (_ctx, page: string, key: string) => {
await asyncExecute(
db,
`DELETE FROM ${tableName} WHERE key = ? AND page = ?`,
@ -71,7 +71,7 @@ export function pageIndexSyscalls(db: SQLite): SysCallMapping {
page,
);
},
"index.get": async (ctx, page: string, key: string) => {
"index.get": async (_ctx, page: string, key: string) => {
const result = await asyncQuery<Item>(
db,
`SELECT value FROM ${tableName} WHERE key = ? AND page = ?`,
@ -84,7 +84,7 @@ export function pageIndexSyscalls(db: SQLite): SysCallMapping {
return null;
}
},
"index.queryPrefix": async (ctx, prefix: string) => {
"index.queryPrefix": async (_ctx, prefix: string) => {
return (
await asyncQuery<Item>(
db,
@ -97,7 +97,7 @@ export function pageIndexSyscalls(db: SQLite): SysCallMapping {
value: JSON.parse(value),
}));
},
"index.query": async (ctx, query: Query) => {
"index.query": async (_ctx, query: Query) => {
const { sql, params } = queryToSql(query);
return (
await asyncQuery<Item>(
@ -114,7 +114,7 @@ export function pageIndexSyscalls(db: SQLite): SysCallMapping {
"index.clearPageIndexForPage": async (ctx, page: string) => {
await apiObj["index.deletePrefixForPage"](ctx, page, "");
},
"index.deletePrefixForPage": async (ctx, page: string, prefix: string) => {
"index.deletePrefixForPage": async (_ctx, page: string, prefix: string) => {
await asyncExecute(
db,
`DELETE FROM ${tableName} WHERE key LIKE ? AND page = ?`,

View File

@ -12,17 +12,17 @@ export const pasteLinkExtension = ViewPlugin.fromClass(
update(update: ViewUpdate): void {
update.transactions.forEach((tr) => {
if (tr.isUserEvent("input.paste")) {
let pastedText: string[] = [];
const pastedText: string[] = [];
let from = 0;
let to = 0;
tr.changes.iterChanges((fromA, toA, fromB, toB, inserted) => {
tr.changes.iterChanges((fromA, _toA, _fromB, toB, inserted) => {
pastedText.push(inserted.sliceString(0));
from = fromA;
to = toB;
});
let pastedString = pastedText.join("");
const pastedString = pastedText.join("");
if (pastedString.match(urlRegexp)) {
let selection = update.startState.selection.main;
const selection = update.startState.selection.main;
if (!selection.empty) {
setTimeout(() => {
update.view.dispatch({
@ -57,7 +57,7 @@ export function attachmentExtension(editor: Editor) {
// TODO: This doesn't take into account the target cursor position,
// it just drops the attachment wherever the cursor was last.
if (event.dataTransfer) {
let payload = [...event.dataTransfer.files];
const payload = [...event.dataTransfer.files];
if (!payload.length) {
return;
}
@ -67,7 +67,7 @@ export function attachmentExtension(editor: Editor) {
}
},
paste: (event: ClipboardEvent) => {
let payload = [...event.clipboardData!.items];
const payload = [...event.clipboardData!.items];
if (!payload.length || payload.length === 0) {
return false;
}
@ -78,23 +78,23 @@ export function attachmentExtension(editor: Editor) {
});
async function processFileTransfer(payload: File[]) {
let data = await payload[0].arrayBuffer();
const data = await payload[0].arrayBuffer();
await saveFile(data!, payload[0].name, payload[0].type);
}
async function processItemTransfer(payload: DataTransferItem[]) {
let file = payload.find((item) => item.kind === "file");
const file = payload.find((item) => item.kind === "file");
if (!file) {
return false;
}
const fileType = file.type;
let ext = fileType.split("/")[1];
let fileName = new Date()
const ext = fileType.split("/")[1];
const fileName = new Date()
.toISOString()
.split(".")[0]
.replace("T", "_")
.replaceAll(":", "-");
let data = await file!.getAsFile()?.arrayBuffer();
const data = await file!.getAsFile()?.arrayBuffer();
await saveFile(data!, `${fileName}.${ext}`, fileType);
}
@ -113,7 +113,7 @@ export function attachmentExtension(editor: Editor) {
return;
}
let finalFileName = prompt(
const finalFileName = prompt(
"File name for pasted attachment",
suggestedName,
);

View File

@ -31,7 +31,7 @@ export class SlashCommandHook implements Hook<SlashCommandHookT> {
buildAllCommands(system: System<SlashCommandHookT>) {
this.slashCommands.clear();
for (let plug of system.loadedPlugs.values()) {
for (const plug of system.loadedPlugs.values()) {
for (
const [name, functionDef] of Object.entries(
plug.manifest!.functions,
@ -55,19 +55,19 @@ export class SlashCommandHook implements Hook<SlashCommandHookT> {
public slashCommandCompleter(
ctx: CompletionContext,
): CompletionResult | null {
let prefix = ctx.matchBefore(slashCommandRegexp);
const prefix = ctx.matchBefore(slashCommandRegexp);
if (!prefix) {
return null;
}
const prefixText = prefix.text;
let options: Completion[] = [];
const options: Completion[] = [];
// No slash commands in comment blocks (queries and such)
let currentNode = syntaxTree(ctx.state).resolveInner(ctx.pos);
const currentNode = syntaxTree(ctx.state).resolveInner(ctx.pos);
if (currentNode.type.name === "CommentBlock") {
return null;
}
for (let [name, def] of this.slashCommands.entries()) {
for (const def of this.slashCommands.values()) {
options.push({
label: def.slashCommand.name,
detail: def.slashCommand.description,
@ -105,7 +105,7 @@ export class SlashCommandHook implements Hook<SlashCommandHookT> {
}
validateManifest(manifest: Manifest<SlashCommandHookT>): string[] {
let errors = [];
const errors = [];
for (const [name, functionDef] of Object.entries(manifest.functions)) {
if (!functionDef.slashCommand) {
continue;

View File

@ -35,10 +35,10 @@ class InlineImageWidget extends WidgetType {
}
const inlineImages = (view: EditorView) => {
let widgets: Range<Decoration>[] = [];
const widgets: Range<Decoration>[] = [];
const imageRegex = /!\[(?<title>[^\]]*)\]\((?<url>.+)\)/;
for (let { from, to } of view.visibleRanges) {
for (const { from, to } of view.visibleRanges) {
syntaxTree(view.state).iterate({
from,
to,
@ -56,7 +56,7 @@ const inlineImages = (view: EditorView) => {
const url = imageRexexResult.groups.url;
const title = imageRexexResult.groups.title;
let deco = Decoration.widget({
const deco = Decoration.widget({
widget: new InlineImageWidget(url, title),
});
widgets.push(deco.range(node.to));

View File

@ -1,8 +1,5 @@
import { Action, AppViewState } from "./types.ts";
let m = new Map();
m.size;
export default function reducer(
state: AppViewState,
action: Action,
@ -49,11 +46,13 @@ export default function reducer(
...state,
showPageNavigator: false,
};
case "pages-listed":
case "pages-listed": {
// Let's move over any "lastOpened" times to the "allPages" list
let oldPageMeta = new Map([...state.allPages].map((pm) => [pm.name, pm]));
for (let pageMeta of action.pages) {
let oldPageMetaItem = oldPageMeta.get(pageMeta.name);
const oldPageMeta = new Map(
[...state.allPages].map((pm) => [pm.name, pm]),
);
for (const pageMeta of action.pages) {
const oldPageMetaItem = oldPageMeta.get(pageMeta.name);
if (oldPageMetaItem && oldPageMetaItem.lastOpened) {
pageMeta.lastOpened = oldPageMetaItem.lastOpened;
}
@ -62,9 +61,10 @@ export default function reducer(
...state,
allPages: action.pages,
};
case "show-palette":
let commands = new Map(state.commands);
for (let [k, v] of state.commands.entries()) {
}
case "show-palette": {
const commands = new Map(state.commands);
for (const [k, v] of state.commands.entries()) {
if (
v.command.contexts &&
(!action.context || !v.command.contexts.includes(action.context))
@ -77,6 +77,7 @@ export default function reducer(
commands,
showCommandPalette: true,
};
}
case "hide-palette":
return {
...state,

View File

@ -11,9 +11,9 @@ type SyntaxNode = {
};
function ensureAnchor(expr: any, start: boolean) {
var _a;
let { source } = expr;
let addStart = start && source[0] != "^",
let _a;
const { source } = expr;
const addStart = start && source[0] != "^",
addEnd = source[source.length - 1] != "$";
if (!addStart && !addEnd) return expr;
return new RegExp(
@ -40,11 +40,11 @@ export function editorSyscalls(editor: Editor): SysCallMapping {
"editor.getSelection": (): { from: number; to: number } => {
return editor.editorView!.state.selection.main;
},
"editor.save": async () => {
"editor.save": () => {
return editor.save(true);
},
"editor.navigate": async (
ctx,
_ctx,
name: string,
pos: number | string,
replaceState = false,
@ -55,29 +55,29 @@ export function editorSyscalls(editor: Editor): SysCallMapping {
await editor.reloadPage();
},
"editor.openUrl": (_ctx, url: string) => {
let win = window.open(url, "_blank");
const win = window.open(url, "_blank");
if (win) {
win.focus();
}
},
"editor.flashNotification": (
ctx,
_ctx,
message: string,
type: "error" | "info" = "info",
) => {
editor.flashNotification(message, type);
},
"editor.filterBox": (
ctx,
_ctx,
label: string,
options: FilterOption[],
helpText: string = "",
placeHolder: string = "",
helpText = "",
placeHolder = "",
): Promise<FilterOption | undefined> => {
return editor.filterBox(label, options, helpText, placeHolder);
},
"editor.showPanel": (
ctx,
_ctx,
id: string,
mode: number,
html: string,
@ -89,13 +89,13 @@ export function editorSyscalls(editor: Editor): SysCallMapping {
config: { html, script, mode },
});
},
"editor.hidePanel": (ctx, id: string) => {
"editor.hidePanel": (_ctx, id: string) => {
editor.viewDispatch({
type: "hide-panel",
id: id as any,
});
},
"editor.insertAtPos": (ctx, text: string, pos: number) => {
"editor.insertAtPos": (_ctx, text: string, pos: number) => {
editor.editorView!.dispatch({
changes: {
insert: text,
@ -103,7 +103,7 @@ export function editorSyscalls(editor: Editor): SysCallMapping {
},
});
},
"editor.replaceRange": (ctx, from: number, to: number, text: string) => {
"editor.replaceRange": (_ctx, from: number, to: number, text: string) => {
editor.editorView!.dispatch({
changes: {
insert: text,
@ -112,15 +112,15 @@ export function editorSyscalls(editor: Editor): SysCallMapping {
},
});
},
"editor.moveCursor": (ctx, pos: number) => {
"editor.moveCursor": (_ctx, pos: number) => {
editor.editorView!.dispatch({
selection: {
anchor: pos,
},
});
},
"editor.setSelection": (ctx, from: number, to: number) => {
let editorView = editor.editorView!;
"editor.setSelection": (_ctx, from: number, to: number) => {
const editorView = editor.editorView!;
editorView.dispatch({
selection: {
anchor: from,
@ -129,9 +129,9 @@ export function editorSyscalls(editor: Editor): SysCallMapping {
});
},
"editor.insertAtCursor": (ctx, text: string) => {
let editorView = editor.editorView!;
let from = editorView.state.selection.main.from;
"editor.insertAtCursor": (_ctx, text: string) => {
const editorView = editor.editorView!;
const from = editorView.state.selection.main.from;
editorView.dispatch({
changes: {
insert: text,
@ -144,17 +144,17 @@ export function editorSyscalls(editor: Editor): SysCallMapping {
},
"editor.matchBefore": (
ctx,
_ctx,
regexp: string,
): { from: number; to: number; text: string } | null => {
const editorState = editor.editorView!.state;
let selection = editorState.selection.main;
let from = selection.from;
const selection = editorState.selection.main;
const from = selection.from;
if (selection.empty) {
let line = editorState.doc.lineAt(from);
let start = Math.max(line.from, from - 250);
let str = line.text.slice(start - line.from, from - line.from);
let found = str.search(ensureAnchor(new RegExp(regexp), false));
const line = editorState.doc.lineAt(from);
const start = Math.max(line.from, from - 250);
const str = line.text.slice(start - line.from, from - line.from);
const found = str.search(ensureAnchor(new RegExp(regexp), false));
// console.log("Line", line, start, str, new RegExp(regexp), found);
return found < 0
? null
@ -162,17 +162,17 @@ export function editorSyscalls(editor: Editor): SysCallMapping {
}
return null;
},
"editor.dispatch": (ctx, change: Transaction) => {
"editor.dispatch": (_ctx, change: Transaction) => {
editor.editorView!.dispatch(change);
},
"editor.prompt": (
ctx,
_ctx,
message: string,
defaultValue = "",
): string | null => {
return prompt(message, defaultValue);
},
"editor.enableReadOnlyMode": (ctx, enabled: boolean) => {
"editor.enableReadOnlyMode": (_ctx, enabled: boolean) => {
editor.viewDispatch({
type: "set-editor-ro",
enabled,