mirror of
https://github.com/bknd-io/bknd/
synced 2026-08-02 08:06:00 +00:00
merged origin/release/0.12
This commit is contained in:
@@ -117,8 +117,6 @@ export class Api {
|
||||
this.updateToken(token);
|
||||
}
|
||||
}
|
||||
|
||||
//console.warn("Couldn't extract token");
|
||||
}
|
||||
|
||||
updateToken(token?: string, rebuild?: boolean) {
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ import * as SystemPermissions from "modules/permissions";
|
||||
import { AdminController, type AdminControllerOptions } from "modules/server/AdminController";
|
||||
import { SystemController } from "modules/server/SystemController";
|
||||
|
||||
// biome-ignore format: must be there
|
||||
// biome-ignore format: must be here
|
||||
import { Api, type ApiOptions } from "Api";
|
||||
import type { ServerEnv } from "modules/Controller";
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getFresh } from "./modes/fresh";
|
||||
import { getCached } from "./modes/cached";
|
||||
import { getDurable } from "./modes/durable";
|
||||
import type { App } from "bknd";
|
||||
import { $console } from "core";
|
||||
|
||||
export type CloudflareEnv = object;
|
||||
export type CloudflareBkndConfig<Env = CloudflareEnv> = RuntimeBkndConfig<Env> & {
|
||||
@@ -37,7 +38,7 @@ export function serve<Env extends CloudflareEnv = CloudflareEnv>(
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (config.manifest && config.static === "assets") {
|
||||
console.warn("manifest is not useful with static 'assets'");
|
||||
$console.warn("manifest is not useful with static 'assets'");
|
||||
} else if (!config.manifest && config.static === "kv") {
|
||||
throw new Error("manifest is required with static 'kv'");
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { CloudflareBkndConfig, CloudflareEnv } from ".";
|
||||
import { App } from "bknd";
|
||||
import { makeConfig as makeAdapterConfig } from "bknd/adapter";
|
||||
import type { ExecutionContext } from "hono";
|
||||
import { $console } from "core";
|
||||
|
||||
export const constants = {
|
||||
exec_async_event_id: "cf_register_waituntil",
|
||||
@@ -27,12 +28,12 @@ export function makeConfig<Env extends CloudflareEnv = CloudflareEnv>(
|
||||
if (!appConfig.connection) {
|
||||
let db: D1Database | undefined;
|
||||
if (bindings?.db) {
|
||||
console.log("Using database from bindings");
|
||||
$console.log("Using database from bindings");
|
||||
db = bindings.db;
|
||||
} else if (Object.keys(args).length > 0) {
|
||||
const binding = getBinding(args, "D1Database");
|
||||
if (binding) {
|
||||
console.log(`Using database from env "${binding.key}"`);
|
||||
$console.log(`Using database from env "${binding.key}"`);
|
||||
db = binding.value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { App, CreateAppConfig } from "bknd";
|
||||
import { createRuntimeApp, makeConfig } from "bknd/adapter";
|
||||
import type { CloudflareBkndConfig, Context, CloudflareEnv } from "../index";
|
||||
import { constants, registerAsyncsExecutionContext } from "../config";
|
||||
import { $console } from "core";
|
||||
|
||||
export async function getDurable<Env extends CloudflareEnv = CloudflareEnv>(
|
||||
config: CloudflareBkndConfig<Env>,
|
||||
@@ -13,7 +14,7 @@ export async function getDurable<Env extends CloudflareEnv = CloudflareEnv>(
|
||||
const key = config.key ?? "app";
|
||||
|
||||
if ([config.onBuilt, config.beforeBuild].some((x) => x)) {
|
||||
console.log("onBuilt and beforeBuild are not supported with DurableObject mode");
|
||||
$console.warn("onBuilt and beforeBuild are not supported with DurableObject mode");
|
||||
}
|
||||
|
||||
const start = performance.now();
|
||||
|
||||
@@ -124,12 +124,10 @@ export class StorageR2Adapter extends StorageAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
//console.log("response headers:before", headersToObject(responseHeaders));
|
||||
this.writeHttpMetadata(responseHeaders, object);
|
||||
responseHeaders.set("etag", object.httpEtag);
|
||||
responseHeaders.set("Content-Length", String(object.size));
|
||||
responseHeaders.set("Last-Modified", object.uploaded.toUTCString());
|
||||
//console.log("response headers:after", headersToObject(responseHeaders));
|
||||
|
||||
return new Response(object.body, {
|
||||
status: object.range ? 206 : 200,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { serveStatic } from "@hono/node-server/serve-static";
|
||||
import { registerLocalMediaAdapter } from "adapter/node/index";
|
||||
import { type RuntimeBkndConfig, createRuntimeApp, type RuntimeOptions } from "bknd/adapter";
|
||||
import { config as $config } from "bknd/core";
|
||||
import { $console } from "core";
|
||||
|
||||
type NodeEnv = NodeJS.ProcessEnv;
|
||||
export type NodeBkndConfig<Env = NodeEnv> = RuntimeBkndConfig<Env> & {
|
||||
@@ -62,7 +63,7 @@ export function serve<Env = NodeEnv>(
|
||||
fetch: createHandler(config, args, opts),
|
||||
},
|
||||
(connInfo) => {
|
||||
console.log(`Server is running on http://localhost:${connInfo.port}`);
|
||||
$console.log(`Server is running on http://localhost:${connInfo.port}`);
|
||||
listener?.(connInfo);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -36,7 +36,7 @@ export class AppAuth extends Module<typeof authConfigSchema> {
|
||||
|
||||
if (!from.enabled && to.enabled) {
|
||||
if (to.jwt.secret === defaultSecret) {
|
||||
console.warn("No JWT secret provided, generating a random one");
|
||||
$console.warn("No JWT secret provided, generating a random one");
|
||||
to.jwt.secret = secureRandomString(64);
|
||||
}
|
||||
}
|
||||
@@ -171,7 +171,6 @@ export class AppAuth extends Module<typeof authConfigSchema> {
|
||||
|
||||
// compare strategy and identifier
|
||||
if (result.data.strategy !== strategy.getName()) {
|
||||
//console.log("!!! User registered with different strategy");
|
||||
throw new Exception("User registered with different strategy");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { type DB, Exception, type PrimaryFieldType } from "core";
|
||||
import { $console, type DB, Exception, type PrimaryFieldType } from "core";
|
||||
import { addFlashMessage } from "core/server/flash";
|
||||
import { type Static, StringEnum, type TObject, parse, runtimeSupports } from "core/utils";
|
||||
import {
|
||||
type Static,
|
||||
StringEnum,
|
||||
type TObject,
|
||||
parse,
|
||||
runtimeSupports,
|
||||
} from "core/utils";
|
||||
import type { Context, Hono } from "hono";
|
||||
import { deleteCookie, getSignedCookie, setSignedCookie } from "hono/cookie";
|
||||
import { sign, verify } from "hono/jwt";
|
||||
@@ -123,7 +129,6 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
|
||||
identifier: string,
|
||||
profile: ProfileExchange,
|
||||
): Promise<AuthResponse> {
|
||||
//console.log("resolve", { action, strategy: strategy.getName(), profile });
|
||||
const user = await this.userResolver(action, strategy, identifier, profile);
|
||||
|
||||
if (user) {
|
||||
@@ -219,7 +224,7 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
|
||||
return token;
|
||||
} catch (e: any) {
|
||||
if (e instanceof Error) {
|
||||
console.error("[Error:getAuthCookie]", e.message);
|
||||
$console.error("[getAuthCookie]", e.message);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
@@ -256,7 +261,6 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
|
||||
|
||||
// @todo: move this to a server helper
|
||||
isJsonRequest(c: Context): boolean {
|
||||
//return c.req.header("Content-Type") === "application/x-www-form-urlencoded";
|
||||
return c.req.header("Content-Type") === "application/json";
|
||||
}
|
||||
|
||||
@@ -283,7 +287,6 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
|
||||
async respond(c: Context, data: AuthResponse | Error | any, redirect?: string) {
|
||||
const successUrl = this.getSafeUrl(c, redirect ?? this.config.cookie.pathSuccess ?? "/");
|
||||
const referer = redirect ?? c.req.header("Referer") ?? successUrl;
|
||||
//console.log("auth respond", { redirect, successUrl, successPath });
|
||||
|
||||
if ("token" in data) {
|
||||
await this.setAuthCookie(c, data.token);
|
||||
@@ -293,7 +296,6 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
|
||||
}
|
||||
|
||||
// can't navigate to "/" – doesn't work on nextjs
|
||||
//console.log("auth success, redirecting to", successUrl);
|
||||
return c.redirect(successUrl);
|
||||
}
|
||||
|
||||
@@ -307,7 +309,6 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
|
||||
}
|
||||
|
||||
await addFlashMessage(c, message, "error");
|
||||
//console.log("auth failed, redirecting to", referer);
|
||||
return c.redirect(referer);
|
||||
}
|
||||
|
||||
|
||||
@@ -11,13 +11,10 @@ type LoginSchema = { username: string; password: string } | { email: string; pas
|
||||
type RegisterSchema = { email: string; password: string; [key: string]: any };
|
||||
|
||||
const schema = Type.Object({
|
||||
hashing: StringEnum(["plain", "sha256" /*, "bcrypt"*/] as const, { default: "sha256" }),
|
||||
hashing: StringEnum(["plain", "sha256"] as const, { default: "sha256" }),
|
||||
});
|
||||
|
||||
export type PasswordStrategyOptions = Static<typeof schema>;
|
||||
/*export type PasswordStrategyOptions2 = {
|
||||
hashing?: "plain" | "bcrypt" | "sha256";
|
||||
};*/
|
||||
|
||||
export class PasswordStrategy implements Strategy {
|
||||
private options: PasswordStrategyOptions;
|
||||
|
||||
@@ -5,8 +5,8 @@ import { OAuthCallbackException, OAuthStrategy } from "./oauth/OAuthStrategy";
|
||||
export * as issuers from "./oauth/issuers";
|
||||
|
||||
export {
|
||||
PasswordStrategy,
|
||||
type PasswordStrategyOptions,
|
||||
PasswordStrategy,
|
||||
OAuthStrategy,
|
||||
OAuthCallbackException,
|
||||
CustomOAuthStrategy,
|
||||
|
||||
@@ -15,7 +15,6 @@ type RequireKeys<T extends object, K extends keyof T> = Required<Pick<T, K>> & O
|
||||
|
||||
const schemaProvided = Type.Object(
|
||||
{
|
||||
//type: StringEnum(["oidc", "oauth2"] as const, { default: "oidc" }),
|
||||
name: StringEnum(Object.keys(issuers) as ConfiguredIssuers[]),
|
||||
client: Type.Object(
|
||||
{
|
||||
@@ -174,8 +173,7 @@ export class OAuthStrategy implements Strategy {
|
||||
) {
|
||||
const config = await this.getConfig();
|
||||
const { client, as, type } = config;
|
||||
//console.log("config", config);
|
||||
console.log("callbackParams", callbackParams, options);
|
||||
|
||||
const parameters = oauth.validateAuthResponse(
|
||||
as,
|
||||
client, // no client_secret required
|
||||
@@ -183,13 +181,9 @@ export class OAuthStrategy implements Strategy {
|
||||
oauth.expectNoState,
|
||||
);
|
||||
if (oauth.isOAuth2Error(parameters)) {
|
||||
//console.log("callback.error", parameters);
|
||||
throw new OAuthCallbackException(parameters, "validateAuthResponse");
|
||||
}
|
||||
/*console.log(
|
||||
"callback.parameters",
|
||||
JSON.stringify(Object.fromEntries(parameters.entries()), null, 2),
|
||||
);*/
|
||||
|
||||
const response = await oauth.authorizationCodeGrantRequest(
|
||||
as,
|
||||
client,
|
||||
@@ -197,13 +191,9 @@ export class OAuthStrategy implements Strategy {
|
||||
options.redirect_uri,
|
||||
options.state,
|
||||
);
|
||||
//console.log("callback.response", response);
|
||||
|
||||
const challenges = oauth.parseWwwAuthenticateChallenges(response);
|
||||
if (challenges) {
|
||||
for (const challenge of challenges) {
|
||||
//console.log("callback.challenge", challenge);
|
||||
}
|
||||
// @todo: Handle www-authenticate challenges as needed
|
||||
throw new OAuthCallbackException(challenges, "www-authenticate");
|
||||
}
|
||||
@@ -218,20 +208,13 @@ export class OAuthStrategy implements Strategy {
|
||||
expectedNonce,
|
||||
);
|
||||
if (oauth.isOAuth2Error(result)) {
|
||||
console.log("callback.error", result);
|
||||
// @todo: Handle OAuth 2.0 response body error
|
||||
throw new OAuthCallbackException(result, "processAuthorizationCodeOpenIDResponse");
|
||||
}
|
||||
|
||||
//console.log("callback.result", result);
|
||||
|
||||
const claims = oauth.getValidatedIdTokenClaims(result);
|
||||
//console.log("callback.IDTokenClaims", claims);
|
||||
|
||||
const infoRequest = await oauth.userInfoRequest(as, client, result.access_token!);
|
||||
|
||||
const resultUser = await oauth.processUserInfoResponse(as, client, claims.sub, infoRequest);
|
||||
//console.log("callback.resultUser", resultUser);
|
||||
|
||||
return await config.profile(resultUser, config, claims); // @todo: check claims
|
||||
}
|
||||
@@ -242,8 +225,7 @@ export class OAuthStrategy implements Strategy {
|
||||
) {
|
||||
const config = await this.getConfig();
|
||||
const { client, type, as, profile } = config;
|
||||
console.log("config", { client, as, type });
|
||||
console.log("callbackParams", callbackParams, options);
|
||||
|
||||
const parameters = oauth.validateAuthResponse(
|
||||
as,
|
||||
client, // no client_secret required
|
||||
@@ -251,13 +233,9 @@ export class OAuthStrategy implements Strategy {
|
||||
oauth.expectNoState,
|
||||
);
|
||||
if (oauth.isOAuth2Error(parameters)) {
|
||||
console.log("callback.error", parameters);
|
||||
throw new OAuthCallbackException(parameters, "validateAuthResponse");
|
||||
}
|
||||
console.log(
|
||||
"callback.parameters",
|
||||
JSON.stringify(Object.fromEntries(parameters.entries()), null, 2),
|
||||
);
|
||||
|
||||
const response = await oauth.authorizationCodeGrantRequest(
|
||||
as,
|
||||
client,
|
||||
@@ -268,9 +246,6 @@ export class OAuthStrategy implements Strategy {
|
||||
|
||||
const challenges = oauth.parseWwwAuthenticateChallenges(response);
|
||||
if (challenges) {
|
||||
for (const challenge of challenges) {
|
||||
//console.log("callback.challenge", challenge);
|
||||
}
|
||||
// @todo: Handle www-authenticate challenges as needed
|
||||
throw new OAuthCallbackException(challenges, "www-authenticate");
|
||||
}
|
||||
@@ -281,19 +256,15 @@ export class OAuthStrategy implements Strategy {
|
||||
try {
|
||||
result = await oauth.processAuthorizationCodeOAuth2Response(as, client, response);
|
||||
if (oauth.isOAuth2Error(result)) {
|
||||
console.log("error", result);
|
||||
throw new Error(); // Handle OAuth 2.0 response body error
|
||||
}
|
||||
} catch (e) {
|
||||
result = (await copy.json()) as any;
|
||||
console.log("failed", result);
|
||||
}
|
||||
|
||||
const res2 = await oauth.userInfoRequest(as, client, result.access_token!);
|
||||
const user = await res2.json();
|
||||
console.log("res2", res2, user);
|
||||
|
||||
console.log("result", result);
|
||||
return await config.profile(user, config, result);
|
||||
}
|
||||
|
||||
@@ -303,7 +274,6 @@ export class OAuthStrategy implements Strategy {
|
||||
): Promise<UserProfile> {
|
||||
const type = this.getIssuerConfig().type;
|
||||
|
||||
console.log("type", type);
|
||||
switch (type) {
|
||||
case "oidc":
|
||||
return await this.oidc(callbackParams, options);
|
||||
@@ -327,7 +297,6 @@ export class OAuthStrategy implements Strategy {
|
||||
};
|
||||
|
||||
const setState = async (c: Context, config: TState): Promise<void> => {
|
||||
console.log("--- setting state", config);
|
||||
await setSignedCookie(c, cookie_name, JSON.stringify(config), secret, {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
@@ -358,7 +327,6 @@ export class OAuthStrategy implements Strategy {
|
||||
const params = new URLSearchParams(url.search);
|
||||
|
||||
const state = await getState(c);
|
||||
console.log("state", state);
|
||||
|
||||
// @todo: add config option to determine if state.action is allowed
|
||||
const redirect_uri =
|
||||
@@ -373,7 +341,6 @@ export class OAuthStrategy implements Strategy {
|
||||
|
||||
try {
|
||||
const data = await auth.resolve(state.action, this, profile.sub, profile);
|
||||
console.log("******** RESOLVED ********", data);
|
||||
|
||||
if (state.mode === "cookie") {
|
||||
return await auth.respond(c, data, state.redirect);
|
||||
@@ -414,10 +381,8 @@ export class OAuthStrategy implements Strategy {
|
||||
redirect_uri,
|
||||
state,
|
||||
});
|
||||
//console.log("_state", state);
|
||||
|
||||
await setState(c, { state, action, redirect: referer.toString(), mode: "cookie" });
|
||||
console.log("--redirecting to", response.url);
|
||||
|
||||
return c.redirect(response.url);
|
||||
});
|
||||
|
||||
@@ -34,8 +34,6 @@ export const github: IssuerConfig<GithubUserInfo> = {
|
||||
config: Omit<IssuerConfig, "profile">,
|
||||
tokenResponse: any,
|
||||
) => {
|
||||
console.log("github info", info, config, tokenResponse);
|
||||
|
||||
try {
|
||||
const res = await fetch("https://api.github.com/user/emails", {
|
||||
headers: {
|
||||
@@ -45,7 +43,6 @@ export const github: IssuerConfig<GithubUserInfo> = {
|
||||
},
|
||||
});
|
||||
const data = (await res.json()) as GithubUserEmailResponse;
|
||||
console.log("data", data);
|
||||
const email = data.find((e: any) => e.primary)?.email;
|
||||
if (!email) {
|
||||
throw new Error("No primary email found");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Exception, Permission } from "core";
|
||||
import { $console, Exception, Permission } from "core";
|
||||
import { objectTransform } from "core/utils";
|
||||
import type { Context } from "hono";
|
||||
import type { ServerEnv } from "modules/Controller";
|
||||
@@ -14,8 +14,6 @@ export type GuardConfig = {
|
||||
};
|
||||
export type GuardContext = Context<ServerEnv> | GuardUserContext;
|
||||
|
||||
const debug = false;
|
||||
|
||||
export class Guard {
|
||||
permissions: Permission[];
|
||||
roles?: Role[];
|
||||
@@ -95,16 +93,15 @@ export class Guard {
|
||||
if (user && typeof user.role === "string") {
|
||||
const role = this.roles?.find((role) => role.name === user?.role);
|
||||
if (role) {
|
||||
debug && console.log("guard: role found", [user.role]);
|
||||
$console.debug("guard: role found", [user.role]);
|
||||
return role;
|
||||
}
|
||||
}
|
||||
|
||||
debug &&
|
||||
console.log("guard: role not found", {
|
||||
user: user,
|
||||
role: user?.role,
|
||||
});
|
||||
$console.debug("guard: role not found", {
|
||||
user: user,
|
||||
role: user?.role,
|
||||
});
|
||||
return this.getDefaultRole();
|
||||
}
|
||||
|
||||
@@ -120,7 +117,6 @@ export class Guard {
|
||||
hasPermission(name: string, user?: GuardUserContext): boolean;
|
||||
hasPermission(permissionOrName: Permission | string, user?: GuardUserContext): boolean {
|
||||
if (!this.isEnabled()) {
|
||||
//console.log("guard not enabled, allowing");
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -133,10 +129,10 @@ export class Guard {
|
||||
const role = this.getUserRole(user);
|
||||
|
||||
if (!role) {
|
||||
debug && console.log("guard: role not found, denying");
|
||||
$console.debug("guard: role not found, denying");
|
||||
return false;
|
||||
} else if (role.implicit_allow === true) {
|
||||
debug && console.log("guard: role implicit allow, allowing");
|
||||
$console.debug("guard: role implicit allow, allowing");
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -144,12 +140,11 @@ export class Guard {
|
||||
(rolePermission) => rolePermission.permission.name === name,
|
||||
);
|
||||
|
||||
debug &&
|
||||
console.log("guard: rolePermission, allowing?", {
|
||||
permission: name,
|
||||
role: role.name,
|
||||
allowing: !!rolePermission,
|
||||
});
|
||||
$console.debug("guard: rolePermission, allowing?", {
|
||||
permission: name,
|
||||
role: role.name,
|
||||
allowing: !!rolePermission,
|
||||
});
|
||||
return !!rolePermission;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
export { UserExistsException, UserNotFoundException, InvalidCredentialsException } from "./errors";
|
||||
export { sha256 } from "./utils/hash";
|
||||
export {
|
||||
type ProfileExchange,
|
||||
type Strategy,
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
// @deprecated: moved to @bknd/core
|
||||
export async function sha256(password: string, salt?: string) {
|
||||
// 1. Convert password to Uint8Array
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode((salt ?? "") + password);
|
||||
|
||||
// 2. Hash the data using SHA-256
|
||||
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
||||
|
||||
// 3. Convert hash to hex string for easier display
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
||||
return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
@@ -8,6 +8,8 @@ export const config: CliCommand = (program) => {
|
||||
.option("--pretty", "pretty print")
|
||||
.action((options) => {
|
||||
const config = getDefaultConfig();
|
||||
|
||||
// biome-ignore lint/suspicious/noConsoleLog:
|
||||
console.log(options.pretty ? JSON.stringify(config, null, 2) : JSON.stringify(config));
|
||||
});
|
||||
};
|
||||
|
||||
@@ -32,5 +32,6 @@ async function action(options: { out?: string; clean?: boolean }) {
|
||||
// delete ".vite" directory in out
|
||||
await fs.rm(path.resolve(out, ".vite"), { recursive: true });
|
||||
|
||||
// biome-ignore lint/suspicious/noConsoleLog:
|
||||
console.log(c.green(`Assets copied to: ${c.bold(out)}`));
|
||||
}
|
||||
|
||||
@@ -43,10 +43,12 @@ export const create: CliCommand = (program) => {
|
||||
|
||||
function errorOutro() {
|
||||
$p.outro(color.red("Failed to create project."));
|
||||
// biome-ignore lint/suspicious/noConsoleLog:
|
||||
console.log(
|
||||
color.yellow("Sorry that this happened. If you think this is a bug, please report it at: ") +
|
||||
color.cyan("https://github.com/bknd-io/bknd/issues"),
|
||||
);
|
||||
// biome-ignore lint/suspicious/noConsoleLog:
|
||||
console.log("");
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -55,7 +57,14 @@ async function onExit() {
|
||||
await flush();
|
||||
}
|
||||
|
||||
async function action(options: { template?: string; dir?: string; integration?: string, yes?: boolean, clean?: boolean }) {
|
||||
async function action(options: {
|
||||
template?: string;
|
||||
dir?: string;
|
||||
integration?: string;
|
||||
yes?: boolean;
|
||||
clean?: boolean;
|
||||
}) {
|
||||
// biome-ignore lint/suspicious/noConsoleLog:
|
||||
console.log("");
|
||||
const $t = createScoped("create");
|
||||
$t.capture("start", {
|
||||
@@ -96,10 +105,12 @@ async function action(options: { template?: string; dir?: string; integration?:
|
||||
|
||||
$t.properties.at = "dir";
|
||||
if (fs.existsSync(downloadOpts.dir)) {
|
||||
const clean = options.clean ?? await $p.confirm({
|
||||
message: `Directory ${color.cyan(downloadOpts.dir)} exists. Clean it?`,
|
||||
initialValue: false,
|
||||
});
|
||||
const clean =
|
||||
options.clean ??
|
||||
(await $p.confirm({
|
||||
message: `Directory ${color.cyan(downloadOpts.dir)} exists. Clean it?`,
|
||||
initialValue: false,
|
||||
}));
|
||||
if ($p.isCancel(clean)) {
|
||||
await onExit();
|
||||
process.exit(1);
|
||||
@@ -174,8 +185,6 @@ async function action(options: { template?: string; dir?: string; integration?:
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
//console.log("integration", { type, integration });
|
||||
|
||||
const choices = templates.filter((t) => t.integration === integration);
|
||||
if (choices.length === 0) {
|
||||
await onExit();
|
||||
@@ -261,9 +270,11 @@ async function action(options: { template?: string; dir?: string; integration?:
|
||||
$p.log.success(`Updated package name to ${color.cyan(ctx.name)}`);
|
||||
|
||||
{
|
||||
const install = options.yes ?? await $p.confirm({
|
||||
message: "Install dependencies?",
|
||||
});
|
||||
const install =
|
||||
options.yes ??
|
||||
(await $p.confirm({
|
||||
message: "Install dependencies?",
|
||||
}));
|
||||
|
||||
if ($p.isCancel(install)) {
|
||||
await onExit();
|
||||
|
||||
@@ -17,6 +17,7 @@ export const debug: CliCommand = (program) => {
|
||||
|
||||
const subjects = {
|
||||
paths: async () => {
|
||||
// biome-ignore lint/suspicious/noConsoleLog:
|
||||
console.log("[PATHS]", {
|
||||
rootpath: getRootPath(),
|
||||
distPath: getDistPath(),
|
||||
@@ -27,6 +28,7 @@ const subjects = {
|
||||
});
|
||||
},
|
||||
routes: async () => {
|
||||
// biome-ignore lint/suspicious/noConsoleLog:
|
||||
console.log("[APP ROUTES]");
|
||||
const credentials = getConnectionCredentialsFromEnv();
|
||||
const app = createApp({ connection: credentials });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import path from "node:path";
|
||||
import type { Config } from "@libsql/client/node";
|
||||
import { config } from "core";
|
||||
import { $console, config } from "core";
|
||||
import type { MiddlewareHandler } from "hono";
|
||||
import open from "open";
|
||||
import { fileExists, getRelativeDistPath } from "../../utils/sys";
|
||||
@@ -36,7 +36,7 @@ export async function startServer(
|
||||
options: { port: number; open?: boolean },
|
||||
) {
|
||||
const port = options.port;
|
||||
console.log(`Using ${server} serve`);
|
||||
$console.log(`Using ${server} serve`);
|
||||
|
||||
switch (server) {
|
||||
case "node": {
|
||||
@@ -58,7 +58,8 @@ export async function startServer(
|
||||
}
|
||||
|
||||
const url = `http://localhost:${port}`;
|
||||
console.info("Server listening on", url);
|
||||
$console.info("Server listening on", url);
|
||||
|
||||
if (options.open) {
|
||||
await open(url);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ export const schema: CliCommand = (program) => {
|
||||
.option("--pretty", "pretty print")
|
||||
.action((options) => {
|
||||
const schema = getDefaultSchema();
|
||||
// biome-ignore lint/suspicious/noConsoleLog:
|
||||
console.log(options.pretty ? JSON.stringify(schema, null, 2) : JSON.stringify(schema));
|
||||
});
|
||||
};
|
||||
|
||||
@@ -169,6 +169,7 @@ async function token(app: App, options: any) {
|
||||
}
|
||||
$log.info(`User found: ${c.cyan(user.email)}`);
|
||||
|
||||
// biome-ignore lint/suspicious/noConsoleLog:
|
||||
console.log(
|
||||
`\n${c.dim("Token:")}\n${c.yellow(await app.module.auth.authenticator.jwt(user))}\n`,
|
||||
);
|
||||
|
||||
@@ -29,7 +29,6 @@ export class AwsClient extends Aws4fetchClient {
|
||||
}
|
||||
|
||||
getUrl(path: string = "/", searchParamsObj: Record<string, any> = {}): string {
|
||||
//console.log("super:getUrl", path, searchParamsObj);
|
||||
const url = new URL(path);
|
||||
const converted = this.convertParams(searchParamsObj);
|
||||
Object.entries(converted).forEach(([key, value]) => {
|
||||
@@ -76,8 +75,6 @@ export class AwsClient extends Aws4fetchClient {
|
||||
}
|
||||
|
||||
const raw = await response.text();
|
||||
//console.log("raw", raw);
|
||||
//console.log(JSON.stringify(xmlToObject(raw), null, 2));
|
||||
return xmlToObject(raw) as T;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { type Event, type EventClass, InvalidEventReturn } from "./Event";
|
||||
import { EventListener, type ListenerHandler, type ListenerMode } from "./EventListener";
|
||||
import { $console } from "core";
|
||||
|
||||
export type RegisterListenerConfig =
|
||||
| ListenerMode
|
||||
@@ -83,10 +84,6 @@ export class EventManager<
|
||||
} else {
|
||||
// @ts-expect-error
|
||||
slug = eventOrSlug.constructor?.slug ?? eventOrSlug.slug;
|
||||
/*eventOrSlug instanceof Event
|
||||
? // @ts-expect-error slug is static
|
||||
eventOrSlug.constructor.slug
|
||||
: eventOrSlug.slug;*/
|
||||
}
|
||||
|
||||
return !!this.events.find((e) => slug === e.slug);
|
||||
@@ -128,8 +125,7 @@ export class EventManager<
|
||||
if (listener.id) {
|
||||
const existing = this.listeners.find((l) => l.id === listener.id);
|
||||
if (existing) {
|
||||
// @todo: add a verbose option?
|
||||
//console.warn(`Listener with id "${listener.id}" already exists.`);
|
||||
$console.debug(`Listener with id "${listener.id}" already exists.`);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -191,7 +187,7 @@ export class EventManager<
|
||||
// @ts-expect-error slug is static
|
||||
const slug = event.constructor.slug;
|
||||
if (!this.enabled) {
|
||||
console.log("EventManager disabled, not emitting", slug);
|
||||
$console.debug("EventManager disabled, not emitting", slug);
|
||||
return event;
|
||||
}
|
||||
|
||||
@@ -240,7 +236,7 @@ export class EventManager<
|
||||
} catch (e) {
|
||||
if (e instanceof InvalidEventReturn) {
|
||||
this.options?.onInvalidReturn?.(_event, e);
|
||||
console.warn(`Invalid return of event listener for "${slug}": ${e.message}`);
|
||||
$console.warn(`Invalid return of event listener for "${slug}": ${e.message}`);
|
||||
} else if (this.options?.onError) {
|
||||
this.options.onError(_event, e);
|
||||
} else {
|
||||
|
||||
@@ -73,6 +73,7 @@ export class SchemaObject<Schema extends TObject> {
|
||||
forceParse: true,
|
||||
skipMark: this.isForceParse(),
|
||||
});
|
||||
|
||||
// regardless of "noEmit" – this should always be triggered
|
||||
const updatedConfig = await this.onBeforeUpdate(this._config, valid);
|
||||
|
||||
@@ -122,19 +123,15 @@ export class SchemaObject<Schema extends TObject> {
|
||||
const partial = path.length > 0 ? (set({}, path, value) as Partial<Static<Schema>>) : value;
|
||||
|
||||
this.throwIfRestricted(partial);
|
||||
//console.log(getFullPathKeys(value).map((k) => path + "." + k));
|
||||
|
||||
// overwrite arrays and primitives, only deep merge objects
|
||||
// @ts-ignore
|
||||
//console.log("---alt:new", _jsonp(mergeObject(current, partial)));
|
||||
const config = mergeObjectWith(current, partial, (objValue, srcValue) => {
|
||||
if (Array.isArray(objValue) && Array.isArray(srcValue)) {
|
||||
return srcValue;
|
||||
}
|
||||
});
|
||||
//console.log("---new", _jsonp(config));
|
||||
|
||||
//console.log("overwritePaths", this.options?.overwritePaths);
|
||||
if (this.options?.overwritePaths) {
|
||||
const keys = getFullPathKeys(value).map((k) => {
|
||||
// only prepend path if given
|
||||
@@ -149,7 +146,6 @@ export class SchemaObject<Schema extends TObject> {
|
||||
}
|
||||
});
|
||||
});
|
||||
//console.log("overwritePaths", keys, overwritePaths);
|
||||
|
||||
if (overwritePaths.length > 0) {
|
||||
// filter out less specific paths (but only if more than 1)
|
||||
@@ -157,12 +153,10 @@ export class SchemaObject<Schema extends TObject> {
|
||||
overwritePaths.length > 1
|
||||
? overwritePaths.filter((k) =>
|
||||
overwritePaths.some((k2) => {
|
||||
//console.log("keep?", { k, k2 }, k2 !== k && k2.startsWith(k));
|
||||
return k2 !== k && k2.startsWith(k);
|
||||
}),
|
||||
)
|
||||
: overwritePaths;
|
||||
//console.log("specific", specific);
|
||||
|
||||
for (const p of specific) {
|
||||
set(config, p, get(partial, p));
|
||||
@@ -170,8 +164,6 @@ export class SchemaObject<Schema extends TObject> {
|
||||
}
|
||||
}
|
||||
|
||||
//console.log("patch", _jsonp({ path, value, partial, config, current }));
|
||||
|
||||
const newConfig = await this.set(config);
|
||||
return [partial, newConfig];
|
||||
}
|
||||
@@ -181,14 +173,11 @@ export class SchemaObject<Schema extends TObject> {
|
||||
const partial = path.length > 0 ? (set({}, path, value) as Partial<Static<Schema>>) : value;
|
||||
|
||||
this.throwIfRestricted(partial);
|
||||
//console.log(getFullPathKeys(value).map((k) => path + "." + k));
|
||||
|
||||
// overwrite arrays and primitives, only deep merge objects
|
||||
// @ts-ignore
|
||||
const config = set(current, path, value);
|
||||
|
||||
//console.log("overwrite", { path, value, partial, config, current });
|
||||
|
||||
const newConfig = await this.set(config);
|
||||
return [partial, newConfig];
|
||||
}
|
||||
@@ -198,7 +187,6 @@ export class SchemaObject<Schema extends TObject> {
|
||||
if (p.length > 1) {
|
||||
const parent = p.slice(0, -1).join(".");
|
||||
if (!has(this._config, parent)) {
|
||||
//console.log("parent", parent, JSON.stringify(this._config, null, 2));
|
||||
throw new Error(`Parent path "${parent}" does not exist`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ export class SimpleRenderer {
|
||||
}
|
||||
|
||||
static hasMarkup(template: string | object): boolean {
|
||||
//console.log("has markup?", template);
|
||||
let flat: string = "";
|
||||
|
||||
if (Array.isArray(template) || typeof template === "object") {
|
||||
@@ -34,12 +33,8 @@ export class SimpleRenderer {
|
||||
flat = String(template);
|
||||
}
|
||||
|
||||
//console.log("** flat", flat);
|
||||
|
||||
const checks = ["{{", "{%", "{#", "{:"];
|
||||
const hasMarkup = checks.some((check) => flat.includes(check));
|
||||
//console.log("--has markup?", hasMarkup);
|
||||
return hasMarkup;
|
||||
return checks.some((check) => flat.includes(check));
|
||||
}
|
||||
|
||||
async render<Given extends TemplateTypes>(template: Given): Promise<Given> {
|
||||
@@ -75,7 +70,6 @@ export class SimpleRenderer {
|
||||
}
|
||||
|
||||
async renderString(template: string): Promise<string> {
|
||||
//console.log("*** renderString", template, this.variables);
|
||||
return this.engine.parseAndRender(template, this.variables, this.options);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,13 +9,11 @@ export class DebugLogger {
|
||||
}
|
||||
|
||||
context(context: string) {
|
||||
//console.log("[ settings context ]", context, this._context);
|
||||
this._context.push(context);
|
||||
return this;
|
||||
}
|
||||
|
||||
clear() {
|
||||
//console.log("[ clear context ]", this._context.pop(), this._context);
|
||||
this._context.pop();
|
||||
return this;
|
||||
}
|
||||
@@ -33,6 +31,8 @@ export class DebugLogger {
|
||||
const indents = " ".repeat(Math.max(this._context.length - 1, 0));
|
||||
const context =
|
||||
this._context.length > 0 ? `[${this._context[this._context.length - 1]}]` : "";
|
||||
|
||||
// biome-ignore lint/suspicious/noConsoleLog: <explanation>
|
||||
console.log(indents, context, time, ...args);
|
||||
|
||||
this.last = now;
|
||||
|
||||
@@ -4,7 +4,6 @@ import weekOfYear from "dayjs/plugin/weekOfYear.js";
|
||||
declare module "dayjs" {
|
||||
interface Dayjs {
|
||||
week(): number;
|
||||
|
||||
week(value: number): dayjs.Dayjs;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { extension, guess, isMimeType } from "media/storage/mime-types-tiny";
|
||||
import { randomString } from "core/utils/strings";
|
||||
import type { Context } from "hono";
|
||||
import { invariant } from "core/utils/runtime";
|
||||
import { $console } from "../console";
|
||||
|
||||
export function getContentName(request: Request): string | undefined;
|
||||
export function getContentName(contentDisposition: string): string | undefined;
|
||||
@@ -130,7 +131,7 @@ export async function getFileFromContext(c: Context<any>): Promise<File> {
|
||||
return await blobToFile(v);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Error parsing form data", e);
|
||||
$console.warn("Error parsing form data", e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
@@ -141,7 +142,7 @@ export async function getFileFromContext(c: Context<any>): Promise<File> {
|
||||
return await blobToFile(blob, { name: getContentName(c.req.raw), type: contentType });
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Error parsing blob", e);
|
||||
$console.warn("Error parsing blob", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import { randomString } from "core/utils/strings";
|
||||
import type { Context } from "hono";
|
||||
import { extension, guess, isMimeType } from "media/storage/mime-types-tiny";
|
||||
|
||||
export function headersToObject(headers: Headers): Record<string, string> {
|
||||
if (!headers) return {};
|
||||
return { ...Object.fromEntries(headers.entries()) };
|
||||
|
||||
@@ -107,7 +107,6 @@ export function parse<Schema extends tb.TSchema = tb.TSchema>(
|
||||
} else if (options?.onError) {
|
||||
options.onError(Errors(schema, data));
|
||||
} else {
|
||||
//console.warn("errors", JSON.stringify([...Errors(schema, data)], null, 2));
|
||||
throw new TypeInvalidError(schema, data);
|
||||
}
|
||||
|
||||
@@ -119,13 +118,11 @@ export function parseDecode<Schema extends tb.TSchema = tb.TSchema>(
|
||||
schema: Schema,
|
||||
data: RecursivePartial<tb.StaticDecode<Schema>>,
|
||||
): tb.StaticDecode<Schema> {
|
||||
//console.log("parseDecode", schema, data);
|
||||
const parsed = Default(schema, data);
|
||||
|
||||
if (Check(schema, parsed)) {
|
||||
return parsed as tb.StaticDecode<typeof schema>;
|
||||
}
|
||||
//console.log("errors", ...Errors(schema, data));
|
||||
|
||||
throw new TypeInvalidError(schema, data);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isDebug, tbValidator as tb } from "core";
|
||||
import { $console, isDebug, tbValidator as tb } from "core";
|
||||
import { StringEnum } from "core/utils";
|
||||
import * as tbbox from "@sinclair/typebox";
|
||||
import {
|
||||
@@ -47,7 +47,6 @@ export class DataController extends Controller {
|
||||
const template = { data: res.data, meta };
|
||||
|
||||
// @todo: this works but it breaks in FE (need to improve DataTable)
|
||||
//return objectCleanEmpty(template) as any;
|
||||
// filter empty
|
||||
return Object.fromEntries(
|
||||
Object.entries(template).filter(([_, v]) => typeof v !== "undefined" && v !== null),
|
||||
@@ -58,7 +57,6 @@ export class DataController extends Controller {
|
||||
const template = { data: res.data };
|
||||
|
||||
// filter empty
|
||||
//return objectCleanEmpty(template);
|
||||
return Object.fromEntries(Object.entries(template).filter(([_, v]) => v !== undefined));
|
||||
}
|
||||
|
||||
@@ -74,11 +72,6 @@ export class DataController extends Controller {
|
||||
const { permission, auth } = this.middlewares;
|
||||
const hono = this.create().use(auth(), permission(SystemPermissions.accessApi));
|
||||
|
||||
const definedEntities = this.em.entities.map((e) => e.name);
|
||||
const tbNumber = Type.Transform(Type.String({ pattern: "^[1-9][0-9]{0,}$" }))
|
||||
.Decode(Number.parseInt)
|
||||
.Encode(String);
|
||||
|
||||
// @todo: sample implementation how to augment handler with additional info
|
||||
function handler<HH extends Handler>(name: string, h: HH): any {
|
||||
const func = h;
|
||||
@@ -143,10 +136,8 @@ export class DataController extends Controller {
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
//console.log("request", c.req.raw);
|
||||
const { entity, context } = c.req.param();
|
||||
if (!this.entityExists(entity)) {
|
||||
console.warn("not found:", entity, definedEntities);
|
||||
return this.notFound(c);
|
||||
}
|
||||
const _entity = this.em.entity(entity);
|
||||
@@ -256,7 +247,6 @@ export class DataController extends Controller {
|
||||
async (c) => {
|
||||
const { entity } = c.req.param();
|
||||
if (!this.entityExists(entity)) {
|
||||
console.warn("not found:", entity, definedEntities);
|
||||
return this.notFound(c);
|
||||
}
|
||||
const options = c.req.valid("query") as RepoQuery;
|
||||
@@ -330,7 +320,6 @@ export class DataController extends Controller {
|
||||
return this.notFound(c);
|
||||
}
|
||||
const options = (await c.req.valid("json")) as RepoQuery;
|
||||
//console.log("options", options);
|
||||
const result = await this.em.repository(entity).findMany(options);
|
||||
|
||||
return c.json(this.repoResult(result), { status: result.data ? 200 : 404 });
|
||||
|
||||
@@ -38,7 +38,7 @@ export class LibsqlConnection extends SqliteConnection {
|
||||
if (clientOrCredentials && "url" in clientOrCredentials) {
|
||||
let { url, authToken, protocol } = clientOrCredentials;
|
||||
if (protocol && LIBSQL_PROTOCOLS.includes(protocol)) {
|
||||
console.log("changing protocol to", protocol);
|
||||
$console.log("changing protocol to", protocol);
|
||||
const [, rest] = url.split("://");
|
||||
url = `${protocol}://${rest}`;
|
||||
}
|
||||
|
||||
@@ -35,7 +35,6 @@ export type TAppDataField = Static<typeof fieldsSchema>;
|
||||
export type TAppDataEntityFields = Static<typeof entityFields>;
|
||||
|
||||
export const entitiesSchema = tb.Type.Object({
|
||||
//name: Type.String(),
|
||||
type: tb.Type.Optional(
|
||||
tb.Type.String({ enum: entityTypes, default: "regular", readOnly: true }),
|
||||
),
|
||||
@@ -63,7 +62,6 @@ export const indicesSchema = tb.Type.Object(
|
||||
{
|
||||
entity: tb.Type.String(),
|
||||
fields: tb.Type.Array(tb.Type.String(), { minItems: 1 }),
|
||||
//name: Type.Optional(Type.String()),
|
||||
unique: tb.Type.Optional(tb.Type.Boolean({ default: false })),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { config } from "core";
|
||||
import { $console, config } from "core";
|
||||
import {
|
||||
type Static,
|
||||
StringEnum,
|
||||
@@ -184,9 +184,9 @@ export class Entity<
|
||||
if (existing) {
|
||||
// @todo: for now adding a graceful method
|
||||
if (JSON.stringify(existing) === JSON.stringify(field)) {
|
||||
/*console.warn(
|
||||
$console.warn(
|
||||
`Field "${field.name}" already exists on entity "${this.name}", but it's the same, so skipping.`,
|
||||
);*/
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -233,7 +233,13 @@ export class Entity<
|
||||
|
||||
for (const field of fields) {
|
||||
if (!field.isValid(data[field.name], context)) {
|
||||
console.log("Entity.isValidData:invalid", context, field.name, data[field.name]);
|
||||
$console.warn(
|
||||
"invalid data given for",
|
||||
this.name,
|
||||
context,
|
||||
field.name,
|
||||
data[field.name],
|
||||
);
|
||||
if (options?.explain) {
|
||||
throw new Error(`Field "${field.name}" has invalid data: "${data[field.name]}"`);
|
||||
}
|
||||
@@ -259,7 +265,6 @@ export class Entity<
|
||||
const _fields = Object.fromEntries(fields.map((field) => [field.name, field]));
|
||||
const schema = Type.Object(
|
||||
transformObject(_fields, (field) => {
|
||||
//const hidden = field.isHidden(options?.context);
|
||||
const fillable = field.isFillable(options?.context);
|
||||
return {
|
||||
title: field.config.label,
|
||||
@@ -277,9 +282,7 @@ export class Entity<
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
//name: this.name,
|
||||
type: this.type,
|
||||
//fields: transformObject(this.fields, (field) => field.toJSON()),
|
||||
fields: Object.fromEntries(this.fields.map((field) => [field.name, field.toJSON()])),
|
||||
config: this.config,
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { DB as DefaultDB } from "core";
|
||||
import { $console, type DB as DefaultDB } from "core";
|
||||
import { EventManager } from "core/events";
|
||||
import { sql } from "kysely";
|
||||
import { Connection } from "../connection/Connection";
|
||||
@@ -55,7 +55,6 @@ export class EntityManager<TBD extends object = DefaultDB> {
|
||||
|
||||
this.connection = connection;
|
||||
this.emgr = emgr ?? new EventManager();
|
||||
//console.log("registering events", EntityManager.Events);
|
||||
this.emgr.registerEvents(EntityManager.Events);
|
||||
}
|
||||
|
||||
@@ -90,7 +89,9 @@ export class EntityManager<TBD extends object = DefaultDB> {
|
||||
if (existing) {
|
||||
// @todo: for now adding a graceful method
|
||||
if (JSON.stringify(existing) === JSON.stringify(entity)) {
|
||||
//console.warn(`Entity "${entity.name}" already exists, but it's the same, so skipping.`);
|
||||
$console.warn(
|
||||
`Entity "${entity.name}" already exists, but it's the same, skipping adding it.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -108,7 +109,6 @@ export class EntityManager<TBD extends object = DefaultDB> {
|
||||
}
|
||||
|
||||
this._entities[entityIndex] = entity;
|
||||
|
||||
// caused issues because this.entity() was using a reference (for when initial config was given)
|
||||
}
|
||||
|
||||
@@ -295,7 +295,6 @@ export class EntityManager<TBD extends object = DefaultDB> {
|
||||
return {
|
||||
entities: Object.fromEntries(this.entities.map((e) => [e.name, e.toJSON()])),
|
||||
relations: Object.fromEntries(this.relations.all.map((r) => [r.getName(), r.toJSON()])),
|
||||
//relations: this.relations.all.map((r) => r.toJSON()),
|
||||
indices: Object.fromEntries(this.indices.map((i) => [i.name, i.toJSON()])),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { DB as DefaultDB, PrimaryFieldType } from "core";
|
||||
import { $console, type DB as DefaultDB, type PrimaryFieldType } from "core";
|
||||
import { type EmitsEvents, EventManager } from "core/events";
|
||||
import type { DeleteQueryBuilder, InsertQueryBuilder, UpdateQueryBuilder } from "kysely";
|
||||
import { type TActionContext, WhereBuilder } from "..";
|
||||
@@ -72,7 +72,6 @@ export class Mutator<
|
||||
|
||||
// if relation field (include key and value in validatedData)
|
||||
if (Array.isArray(result)) {
|
||||
//console.log("--- (instructions)", result);
|
||||
const [relation_key, relation_value] = result;
|
||||
validatedData[relation_key] = relation_value;
|
||||
}
|
||||
@@ -122,7 +121,7 @@ export class Mutator<
|
||||
};
|
||||
} catch (e) {
|
||||
// @todo: redact
|
||||
console.log("[Error in query]", sql);
|
||||
$console.error("[Error in query]", sql);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,6 @@ export class BooleanField<Required extends true | false = false> extends Field<
|
||||
}
|
||||
|
||||
override transformRetrieve(value: unknown): boolean | null {
|
||||
//console.log("Boolean:transformRetrieve:value", value);
|
||||
if (typeof value === "undefined" || value === null) {
|
||||
if (this.isRequired()) return false;
|
||||
if (this.hasDefault()) return this.getDefault();
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { type Static, StringEnum, dayjs } from "core/utils";
|
||||
import type { EntityManager } from "../entities";
|
||||
import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field";
|
||||
import { $console } from "core";
|
||||
import * as tbbox from "@sinclair/typebox";
|
||||
const { Type } = tbbox;
|
||||
|
||||
export const dateFieldConfigSchema = Type.Composite(
|
||||
[
|
||||
Type.Object({
|
||||
//default_value: Type.Optional(Type.Date()),
|
||||
type: StringEnum(["date", "datetime", "week"] as const, { default: "date" }),
|
||||
timezone: Type.Optional(Type.String()),
|
||||
min_date: Type.Optional(Type.String()),
|
||||
@@ -53,13 +53,11 @@ export class DateField<Required extends true | false = false> extends Field<
|
||||
}
|
||||
|
||||
private parseDateFromString(value: string): Date {
|
||||
//console.log("parseDateFromString", value);
|
||||
if (this.config.type === "week" && value.includes("-W")) {
|
||||
const [year, week] = value.split("-W").map((n) => Number.parseInt(n, 10)) as [
|
||||
number,
|
||||
number,
|
||||
];
|
||||
//console.log({ year, week });
|
||||
// @ts-ignore causes errors on build?
|
||||
return dayjs().year(year).week(week).toDate();
|
||||
}
|
||||
@@ -69,15 +67,12 @@ export class DateField<Required extends true | false = false> extends Field<
|
||||
|
||||
override getValue(value: string, context?: TRenderContext): string | undefined {
|
||||
if (value === null || !value) return;
|
||||
//console.log("getValue", { value, context });
|
||||
const date = this.parseDateFromString(value);
|
||||
//console.log("getValue.date", date);
|
||||
|
||||
if (context === "submit") {
|
||||
try {
|
||||
return date.toISOString();
|
||||
} catch (e) {
|
||||
//console.warn("DateField.getValue:value/submit", value, e);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -86,7 +81,7 @@ export class DateField<Required extends true | false = false> extends Field<
|
||||
try {
|
||||
return `${date.getFullYear()}-W${dayjs(date).week()}`;
|
||||
} catch (e) {
|
||||
console.warn("error - DateField.getValue:week", value, e);
|
||||
$console.warn("DateField.getValue:week error", value, String(e));
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -99,8 +94,7 @@ export class DateField<Required extends true | false = false> extends Field<
|
||||
|
||||
return this.formatDate(local);
|
||||
} catch (e) {
|
||||
console.warn("DateField.getValue:value", value);
|
||||
console.warn("DateField.getValue:e", e);
|
||||
$console.warn("DateField.getValue error", this.config.type, value, String(e));
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -119,7 +113,6 @@ export class DateField<Required extends true | false = false> extends Field<
|
||||
}
|
||||
|
||||
override transformRetrieve(_value: string): Date | null {
|
||||
//console.log("transformRetrieve DateField", _value);
|
||||
const value = super.transformRetrieve(_value);
|
||||
if (value === null) return null;
|
||||
|
||||
@@ -138,7 +131,6 @@ export class DateField<Required extends true | false = false> extends Field<
|
||||
const value = await super.transformPersist(_value, em, context);
|
||||
if (this.nullish(value)) return value;
|
||||
|
||||
//console.log("transformPersist DateField", value);
|
||||
switch (this.config.type) {
|
||||
case "date":
|
||||
case "week":
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Const, type Static, StringEnum } from "core/utils";
|
||||
import type { EntityManager } from "data";
|
||||
import { TransformPersistFailedException } from "../errors";
|
||||
import { Field, type TActionContext, type TRenderContext, baseFieldConfigSchema } from "./Field";
|
||||
import { baseFieldConfigSchema, Field, type TActionContext, type TRenderContext } from "./Field";
|
||||
import * as tbbox from "@sinclair/typebox";
|
||||
const { Type } = tbbox;
|
||||
|
||||
@@ -55,10 +55,6 @@ export class EnumField<Required extends true | false = false, TypeOverride = str
|
||||
constructor(name: string, config: Partial<EnumFieldConfig>) {
|
||||
super(name, config);
|
||||
|
||||
/*if (this.config.options.values.length === 0) {
|
||||
throw new Error(`Enum field "${this.name}" requires at least one option`);
|
||||
}*/
|
||||
|
||||
if (this.config.default_value && !this.isValidValue(this.config.default_value)) {
|
||||
throw new Error(`Default value "${this.config.default_value}" is not a valid option`);
|
||||
}
|
||||
@@ -71,10 +67,6 @@ export class EnumField<Required extends true | false = false, TypeOverride = str
|
||||
getOptions(): { label: string; value: string }[] {
|
||||
const options = this.config?.options ?? { type: "strings", values: [] };
|
||||
|
||||
/*if (options.values?.length === 0) {
|
||||
throw new Error(`Enum field "${this.name}" requires at least one option`);
|
||||
}*/
|
||||
|
||||
if (options.type === "strings") {
|
||||
return options.values?.map((option) => ({ label: option, value: option }));
|
||||
}
|
||||
|
||||
@@ -84,7 +84,6 @@ export class JsonField<Required extends true | false = false, TypeOverride = obj
|
||||
context: TActionContext,
|
||||
): Promise<string | undefined> {
|
||||
const value = await super.transformPersist(_value, em, context);
|
||||
//console.log("value", value);
|
||||
if (this.nullish(value)) return value;
|
||||
|
||||
if (!this.isSerializable(value)) {
|
||||
|
||||
@@ -48,22 +48,16 @@ export class JsonSchemaField<
|
||||
|
||||
override isValid(value: any, context: TActionContext = "update"): boolean {
|
||||
const parentValid = super.isValid(value, context);
|
||||
//console.log("jsonSchemaField:isValid", this.getJsonSchema(), this.name, value, parentValid);
|
||||
|
||||
if (parentValid) {
|
||||
// already checked in parent
|
||||
if (!this.isRequired() && (!value || typeof value !== "object")) {
|
||||
//console.log("jsonschema:valid: not checking", this.name, value, context);
|
||||
return true;
|
||||
}
|
||||
|
||||
const result = this.validator.validate(value);
|
||||
//console.log("jsonschema:errors", this.name, result.errors);
|
||||
return result.valid;
|
||||
} else {
|
||||
//console.log("jsonschema:invalid", this.name, value, context);
|
||||
}
|
||||
//console.log("jsonschema:invalid:fromParent", this.name, value, context);
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -91,7 +85,6 @@ export class JsonSchemaField<
|
||||
try {
|
||||
return Default(FromSchema(this.getJsonSchema()), {});
|
||||
} catch (e) {
|
||||
//console.error("jsonschema:transformRetrieve", e);
|
||||
return null;
|
||||
}
|
||||
} else if (this.hasDefault()) {
|
||||
@@ -109,13 +102,9 @@ export class JsonSchemaField<
|
||||
): Promise<string | undefined> {
|
||||
const value = await super.transformPersist(_value, em, context);
|
||||
if (this.nullish(value)) return value;
|
||||
//console.log("jsonschema:transformPersist", this.name, _value, context);
|
||||
|
||||
if (!this.isValid(value)) {
|
||||
//console.error("jsonschema:transformPersist:invalid", this.name, value);
|
||||
throw new TransformPersistFailedException(this.name, value);
|
||||
} else {
|
||||
//console.log("jsonschema:transformPersist:valid", this.name, value);
|
||||
}
|
||||
|
||||
if (!value || typeof value !== "object") return this.getDefault();
|
||||
|
||||
@@ -98,12 +98,9 @@ export function fieldTestSuite(
|
||||
test("toJSON", async () => {
|
||||
const _config = {
|
||||
..._requiredConfig,
|
||||
//order: 1,
|
||||
fillable: true,
|
||||
required: false,
|
||||
hidden: false,
|
||||
//virtual: false,
|
||||
//default_value: undefined
|
||||
};
|
||||
|
||||
function fieldJson(field: Field) {
|
||||
@@ -115,19 +112,16 @@ export function fieldTestSuite(
|
||||
}
|
||||
|
||||
expect(fieldJson(noConfigField)).toEqual({
|
||||
//name: "no_config",
|
||||
type: noConfigField.type,
|
||||
config: _config,
|
||||
});
|
||||
|
||||
expect(fieldJson(fillable)).toEqual({
|
||||
//name: "fillable",
|
||||
type: noConfigField.type,
|
||||
config: _config,
|
||||
});
|
||||
|
||||
expect(fieldJson(required)).toEqual({
|
||||
//name: "required",
|
||||
type: required.type,
|
||||
config: {
|
||||
..._config,
|
||||
@@ -136,7 +130,6 @@ export function fieldTestSuite(
|
||||
});
|
||||
|
||||
expect(fieldJson(hidden)).toEqual({
|
||||
//name: "hidden",
|
||||
type: required.type,
|
||||
config: {
|
||||
..._config,
|
||||
@@ -145,7 +138,6 @@ export function fieldTestSuite(
|
||||
});
|
||||
|
||||
expect(fieldJson(dflt)).toEqual({
|
||||
//name: "dflt",
|
||||
type: dflt.type,
|
||||
config: {
|
||||
..._config,
|
||||
@@ -154,7 +146,6 @@ export function fieldTestSuite(
|
||||
});
|
||||
|
||||
expect(fieldJson(requiredAndDefault)).toEqual({
|
||||
//name: "full",
|
||||
type: requiredAndDefault.type,
|
||||
config: {
|
||||
..._config,
|
||||
|
||||
@@ -39,7 +39,6 @@ export class EntityIndex {
|
||||
return {
|
||||
entity: this.entity.name,
|
||||
fields: this.fields.map((f) => f.name),
|
||||
//name: this.name,
|
||||
unique: this.unique,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ export function getChangeSet(
|
||||
data: EntityData,
|
||||
fields: Field[],
|
||||
): EntityData {
|
||||
//console.log("getChangeSet", formData, data);
|
||||
return transform(
|
||||
formData,
|
||||
(acc, _value, key) => {
|
||||
@@ -32,17 +31,6 @@ export function getChangeSet(
|
||||
// @todo: add typing for "action"
|
||||
if (action === "create" || newValue !== data[key]) {
|
||||
acc[key] = newValue;
|
||||
/*console.log("changed", {
|
||||
key,
|
||||
value,
|
||||
valueType: typeof value,
|
||||
prev: data[key],
|
||||
newValue,
|
||||
new: value,
|
||||
sent: acc[key]
|
||||
});*/
|
||||
} else {
|
||||
//console.log("no change", key, value, data[key]);
|
||||
}
|
||||
},
|
||||
{} as typeof formData,
|
||||
|
||||
@@ -14,15 +14,6 @@ const { Type } = tbbox;
|
||||
export type KyselyJsonFrom = any;
|
||||
export type KyselyQueryBuilder = SelectQueryBuilder<any, any, any>;
|
||||
|
||||
/*export type RelationConfig = {
|
||||
mappedBy?: string;
|
||||
inversedBy?: string;
|
||||
sourceCardinality?: number;
|
||||
connectionTable?: string;
|
||||
connectionTableMappedName?: string;
|
||||
required?: boolean;
|
||||
};*/
|
||||
|
||||
export type BaseRelationConfig = Static<typeof EntityRelation.schema>;
|
||||
|
||||
// @todo: add generic type for relation config
|
||||
@@ -167,7 +158,6 @@ export abstract class EntityRelation<
|
||||
* @param entity
|
||||
*/
|
||||
isListableFor(entity: Entity): boolean {
|
||||
//console.log("isListableFor", entity.name, this.source.entity.name, this.target.entity.name);
|
||||
return this.target.entity.name === entity.name;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { Static } from "core/utils";
|
||||
import type { ExpressionBuilder } from "kysely";
|
||||
import { Entity, type EntityManager } from "../entities";
|
||||
import { type Field, PrimaryField, VirtualField } from "../fields";
|
||||
import { type Field, PrimaryField } from "../fields";
|
||||
import type { RepoQuery } from "../server/data-query-impl";
|
||||
import { EntityRelation, type KyselyJsonFrom, type KyselyQueryBuilder } from "./EntityRelation";
|
||||
import { EntityRelation, type KyselyQueryBuilder } from "./EntityRelation";
|
||||
import { EntityRelationAnchor } from "./EntityRelationAnchor";
|
||||
import { RelationField } from "./RelationField";
|
||||
import { type RelationType, RelationTypes } from "./relation-types";
|
||||
@@ -48,7 +48,6 @@ export class ManyToManyRelation extends EntityRelation<typeof ManyToManyRelation
|
||||
|
||||
this.connectionTableMappedName = config?.connectionTableMappedName || connectionTable;
|
||||
this.additionalFields = additionalFields || [];
|
||||
//this.connectionTable = connectionTable;
|
||||
}
|
||||
|
||||
static defaultConnectionTable(source: Entity, target: Entity) {
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { Static } from "core/utils";
|
||||
import type { ExpressionBuilder } from "kysely";
|
||||
import type { Entity, EntityManager } from "../entities";
|
||||
import type { RepoQuery } from "../server/data-query-impl";
|
||||
import { EntityRelation, type KyselyJsonFrom, type KyselyQueryBuilder } from "./EntityRelation";
|
||||
import { EntityRelation, type KyselyQueryBuilder } from "./EntityRelation";
|
||||
import { EntityRelationAnchor } from "./EntityRelationAnchor";
|
||||
import { RelationField, type RelationFieldBaseConfig } from "./RelationField";
|
||||
import type { MutationInstructionResponse } from "./RelationMutator";
|
||||
@@ -127,7 +127,6 @@ export class ManyToOneRelation extends EntityRelation<typeof ManyToOneRelation.s
|
||||
}
|
||||
|
||||
const groupBy = `${entity.name}.${entity.getPrimaryField().name}`;
|
||||
//console.log("queryInfo", entity.name, { reference, side, relationRef, entityRef, otherRef });
|
||||
|
||||
return {
|
||||
other,
|
||||
|
||||
@@ -17,11 +17,6 @@ export const relationFieldConfigSchema = Type.Composite([
|
||||
on_delete: Type.Optional(StringEnum(CASCADES, { default: "set null" })),
|
||||
}),
|
||||
]);
|
||||
/*export const relationFieldConfigSchema = baseFieldConfigSchema.extend({
|
||||
reference: z.string(),
|
||||
target: z.string(),
|
||||
target_field: z.string().catch("id"),
|
||||
});*/
|
||||
|
||||
export type RelationFieldConfig = Static<typeof relationFieldConfigSchema>;
|
||||
export type RelationFieldBaseConfig = { label?: string };
|
||||
@@ -33,16 +28,6 @@ export class RelationField extends Field<RelationFieldConfig> {
|
||||
return relationFieldConfigSchema;
|
||||
}
|
||||
|
||||
/*constructor(name: string, config?: Partial<RelationFieldConfig>) {
|
||||
//relation_name = relation_name || target.name;
|
||||
//const name = [relation_name, target.getPrimaryField().name].join("_");
|
||||
super(name, config);
|
||||
|
||||
//console.log(this.config);
|
||||
//this.relation.target = target;
|
||||
//this.relation.name = relation_name;
|
||||
}*/
|
||||
|
||||
static create(
|
||||
relation: EntityRelation,
|
||||
target: EntityRelationAnchor,
|
||||
@@ -52,7 +37,7 @@ export class RelationField extends Field<RelationFieldConfig> {
|
||||
target.reference ?? target.entity.name,
|
||||
target.entity.getPrimaryField().name,
|
||||
].join("_");
|
||||
//console.log('name', name);
|
||||
|
||||
return new RelationField(name, {
|
||||
...config,
|
||||
required: relation.required,
|
||||
|
||||
@@ -63,7 +63,6 @@ export class RelationMutator {
|
||||
// make sure it's a primitive value
|
||||
// @todo: this is not a good way of checking primitives. Null is also an object
|
||||
if (typeof value === "object") {
|
||||
console.log("value", value);
|
||||
throw new Error(`Invalid value for relation field "${key}" given, expected primitive.`);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
type Field<Type, Required extends true | false> = {
|
||||
_type: Type;
|
||||
_required: Required;
|
||||
};
|
||||
type TextField<Required extends true | false = false> = Field<string, Required> & {
|
||||
_type: string;
|
||||
required: () => TextField<true>;
|
||||
};
|
||||
type NumberField<Required extends true | false = false> = Field<number, Required> & {
|
||||
_type: number;
|
||||
required: () => NumberField<true>;
|
||||
};
|
||||
|
||||
type Entity<Fields extends Record<string, Field<any, any>> = {}> = { name: string; fields: Fields };
|
||||
|
||||
function entity<Fields extends Record<string, Field<any, any>>>(
|
||||
name: string,
|
||||
fields: Fields,
|
||||
): Entity<Fields> {
|
||||
return { name, fields };
|
||||
}
|
||||
|
||||
function text(): TextField<false> {
|
||||
return {} as any;
|
||||
}
|
||||
function number(): NumberField<false> {
|
||||
return {} as any;
|
||||
}
|
||||
|
||||
const field1 = text();
|
||||
const field1_req = text().required();
|
||||
const field2 = number();
|
||||
const user = entity("users", {
|
||||
name: text().required(),
|
||||
bio: text(),
|
||||
age: number(),
|
||||
some: number().required(),
|
||||
});
|
||||
|
||||
type InferEntityFields<T> = T extends Entity<infer Fields>
|
||||
? {
|
||||
[K in keyof Fields]: Fields[K] extends { _type: infer Type; _required: infer Required }
|
||||
? Required extends true
|
||||
? Type
|
||||
: Type | undefined
|
||||
: never;
|
||||
}
|
||||
: never;
|
||||
|
||||
type Prettify<T> = {
|
||||
[K in keyof T]: T[K];
|
||||
};
|
||||
export type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};
|
||||
|
||||
// from https://github.com/type-challenges/type-challenges/issues/28200
|
||||
type Merge<T> = {
|
||||
[K in keyof T]: T[K];
|
||||
};
|
||||
type OptionalUndefined<
|
||||
T,
|
||||
Props extends keyof T = keyof T,
|
||||
OptionsProps extends keyof T = Props extends keyof T
|
||||
? undefined extends T[Props]
|
||||
? Props
|
||||
: never
|
||||
: never,
|
||||
> = Merge<
|
||||
{
|
||||
[K in OptionsProps]?: T[K];
|
||||
} & {
|
||||
[K in Exclude<keyof T, OptionsProps>]: T[K];
|
||||
}
|
||||
>;
|
||||
|
||||
type UserFields = InferEntityFields<typeof user>;
|
||||
type UserFields2 = Simplify<OptionalUndefined<UserFields>>;
|
||||
|
||||
const obj: UserFields2 = { name: "h", age: 1, some: 1 };
|
||||
@@ -25,7 +25,6 @@ export class AppFlows extends Module<typeof flowsConfigSchema> {
|
||||
}
|
||||
|
||||
override async build() {
|
||||
//console.log("building flows", this.config);
|
||||
const flows = transformObject(this.config.flows, (flowConfig, name) => {
|
||||
return Flow.fromObject(name, flowConfig as any, TASKS);
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Event, EventManager, type ListenerHandler } from "core/events";
|
||||
import type { EmitsEvents } from "core/events";
|
||||
import type { Task, TaskResult } from "../tasks/Task";
|
||||
import type { Flow } from "./Flow";
|
||||
import { $console } from "core";
|
||||
|
||||
export type TaskLog = TaskResult & {
|
||||
task: Task;
|
||||
@@ -185,10 +186,9 @@ export class Execution implements EmitsEvents {
|
||||
await Promise.all(promises);
|
||||
return this.run();
|
||||
} catch (e) {
|
||||
console.log("RuntimeExecutor: error", e);
|
||||
$console.error("RuntimeExecutor: error", e);
|
||||
|
||||
// for now just throw
|
||||
// biome-ignore lint/complexity/noUselessCatch: @todo: add error task on flow
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Condition, TaskConnection } from "../tasks/TaskConnection";
|
||||
import { Execution } from "./Execution";
|
||||
import { FlowTaskConnector } from "./FlowTaskConnector";
|
||||
import { Trigger } from "./triggers/Trigger";
|
||||
import { $console } from "core";
|
||||
|
||||
type Jsoned<T extends { toJSON: () => object }> = ReturnType<T["toJSON"]>;
|
||||
|
||||
@@ -53,8 +54,6 @@ export class Flow {
|
||||
}
|
||||
|
||||
getSequence(sequence: Task[][] = []): Task[][] {
|
||||
//console.log("queue", queue.map((step) => step.map((t) => t.name)));
|
||||
|
||||
// start task
|
||||
if (sequence.length === 0) {
|
||||
sequence.push([this.startTask]);
|
||||
@@ -69,7 +68,6 @@ export class Flow {
|
||||
// check if task already in one of queue steps
|
||||
// this is when we have a circle back
|
||||
if (sequence.some((step) => step.includes(outTask))) {
|
||||
//console.log("Task already in queue", outTask.name);
|
||||
return;
|
||||
}
|
||||
nextStep.push(outTask);
|
||||
@@ -110,14 +108,6 @@ export class Flow {
|
||||
return this;
|
||||
}
|
||||
|
||||
/*getResponse() {
|
||||
if (!this.respondingTask) {
|
||||
return;
|
||||
}
|
||||
|
||||
return this.respondingTask.log.output;
|
||||
}*/
|
||||
|
||||
// @todo: check for existence
|
||||
addConnection(connection: TaskConnection) {
|
||||
// check if connection already exists
|
||||
@@ -179,7 +169,7 @@ export class Flow {
|
||||
// @ts-ignore
|
||||
return new cls(name, obj.params);
|
||||
} catch (e: any) {
|
||||
console.log("Error creating task", name, obj.type, obj, taskClass);
|
||||
$console.error("Error creating task", name, obj.type, obj, taskClass);
|
||||
throw new Error(`Error creating task ${obj.type}: ${e.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -31,37 +31,11 @@ export class FlowTaskConnector {
|
||||
}
|
||||
}
|
||||
|
||||
/*const targetDepth = this.task(target).getDepth();
|
||||
console.log("depth", ownDepth, targetDepth);
|
||||
|
||||
// if target has a lower depth
|
||||
if (targetDepth > 0 && ownDepth >= targetDepth) {
|
||||
// check for unique out conditions
|
||||
console.log(
|
||||
"out conditions",
|
||||
this.source.name,
|
||||
this.getOutConnections().map((c) => [c.target.name, c.condition])
|
||||
);
|
||||
if (
|
||||
this.getOutConnections().some(
|
||||
(c) =>
|
||||
c.condition[0] === condition[0] &&
|
||||
c.condition[1] === condition[1]
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
"Task cannot be connected to a deeper task with the same condition"
|
||||
);
|
||||
}
|
||||
}*/
|
||||
|
||||
this.flow.addConnection(new TaskConnection(this.source, target, { condition, max_retries }));
|
||||
}
|
||||
|
||||
asOutputFor(target: Task, condition?: Condition) {
|
||||
this.task(target).asInputFor(this.source, condition);
|
||||
//new FlowTaskConnector(this.flow, target).asInputFor(this.source);
|
||||
//this.flow.addConnection(new TaskConnection(target, this.source));
|
||||
}
|
||||
|
||||
getNext() {
|
||||
@@ -107,12 +81,4 @@ export class FlowTaskConnector {
|
||||
getOutTasks(result?: TaskResult): Task[] {
|
||||
return this.getOutConnections(result).map((c) => c.target);
|
||||
}
|
||||
|
||||
/*getNextRunnableConnections() {
|
||||
return this.getOutConnections().filter((c) => c.source.log.success);
|
||||
}
|
||||
|
||||
getNextRunnableTasks() {
|
||||
return this.getNextRunnableConnections().map((c) => c.target);
|
||||
}*/
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Task } from "../../tasks/Task";
|
||||
import { $console } from "core";
|
||||
|
||||
export class RuntimeExecutor {
|
||||
async run(
|
||||
@@ -10,7 +11,6 @@ export class RuntimeExecutor {
|
||||
return;
|
||||
}
|
||||
|
||||
//const promises = tasks.map((t) => t.run());
|
||||
const promises = tasks.map(async (t) => {
|
||||
const result = await t.run();
|
||||
onDone?.(t, result);
|
||||
@@ -20,7 +20,7 @@ export class RuntimeExecutor {
|
||||
try {
|
||||
await Promise.all(promises);
|
||||
} catch (e) {
|
||||
console.log("RuntimeExecutor: error", e);
|
||||
$console.error("RuntimeExecutor: error", e);
|
||||
}
|
||||
|
||||
return this.run(nextTasks, onDone);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { EventManager } from "core/events";
|
||||
import type { Flow } from "../Flow";
|
||||
import { Trigger } from "./Trigger";
|
||||
import { $console } from "core";
|
||||
import * as tbbox from "@sinclair/typebox";
|
||||
const { Type } = tbbox;
|
||||
|
||||
@@ -23,17 +24,13 @@ export class EventTrigger extends Trigger<typeof EventTrigger.schema> {
|
||||
emgr.on(
|
||||
this.config.event,
|
||||
async (event) => {
|
||||
console.log("event", event);
|
||||
/*if (!this.match(event)) {
|
||||
return;
|
||||
}*/
|
||||
const execution = flow.createExecution();
|
||||
this.executions.push(execution);
|
||||
|
||||
try {
|
||||
await execution.start(event.params);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
$console.error(e);
|
||||
}
|
||||
},
|
||||
this.config.mode,
|
||||
|
||||
@@ -12,14 +12,11 @@ export class HttpTrigger extends Trigger<typeof HttpTrigger.schema> {
|
||||
|
||||
static override schema = Type.Composite([
|
||||
Trigger.schema,
|
||||
Type.Object(
|
||||
{
|
||||
path: Type.String({ pattern: "^/.*$" }),
|
||||
method: StringEnum(httpMethods, { default: "GET" }),
|
||||
response_type: StringEnum(["json", "text", "html"], { default: "json" }),
|
||||
},
|
||||
//{ additionalProperties: false }
|
||||
),
|
||||
Type.Object({
|
||||
path: Type.String({ pattern: "^/.*$" }),
|
||||
method: StringEnum(httpMethods, { default: "GET" }),
|
||||
response_type: StringEnum(["json", "text", "html"], { default: "json" }),
|
||||
}),
|
||||
]);
|
||||
|
||||
override async register(flow: Flow, hono: Hono<any>) {
|
||||
@@ -45,7 +42,5 @@ export class HttpTrigger extends Trigger<typeof HttpTrigger.schema> {
|
||||
execution.start(params);
|
||||
return c.json({ success: true });
|
||||
});
|
||||
|
||||
//console.log("--registered flow", flow.name, "on", method, this.config.path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,12 +10,9 @@ export class Trigger<Schema extends typeof Trigger.schema = typeof Trigger.schem
|
||||
type = "manual";
|
||||
config: Static<Schema>;
|
||||
|
||||
static schema = Type.Object(
|
||||
{
|
||||
mode: StringEnum(["sync", "async"], { default: "async" }),
|
||||
},
|
||||
//{ additionalProperties: false }
|
||||
);
|
||||
static schema = Type.Object({
|
||||
mode: StringEnum(["sync", "async"], { default: "async" }),
|
||||
});
|
||||
|
||||
constructor(config?: Partial<Static<Schema>>) {
|
||||
const schema = (this.constructor as typeof Trigger).schema;
|
||||
|
||||
@@ -4,7 +4,6 @@ import { Trigger } from "./Trigger";
|
||||
|
||||
export { Trigger, EventTrigger, HttpTrigger };
|
||||
|
||||
//export type TriggerMapType = { [key: string]: { cls: typeof Trigger } };
|
||||
export const TriggerMap = {
|
||||
manual: { cls: Trigger },
|
||||
event: { cls: EventTrigger },
|
||||
|
||||
@@ -23,13 +23,9 @@ export {
|
||||
} from "./flows/triggers";
|
||||
|
||||
import { Task } from "./tasks/Task";
|
||||
export { type TaskResult, type TaskRenderProps } from "./tasks/Task";
|
||||
export type { TaskResult, TaskRenderProps } from "./tasks/Task";
|
||||
export { TaskConnection, Condition } from "./tasks/TaskConnection";
|
||||
|
||||
// test
|
||||
//export { simpleFetch } from "./examples/simple-fetch";
|
||||
|
||||
//export type TaskMapType = { [key: string]: { cls: typeof Task<any> } };
|
||||
export const TaskMap = {
|
||||
fetch: { cls: FetchTask },
|
||||
log: { cls: LogTask },
|
||||
|
||||
@@ -14,10 +14,6 @@ export type TaskResult<Output = any> = {
|
||||
params: any;
|
||||
};
|
||||
|
||||
/*export type TaskRenderProps<T extends Task = Task> = NodeProps<{
|
||||
task: T;
|
||||
state: { i: number; isStartTask: boolean; isRespondingTask; event: ExecutionEvent | undefined };
|
||||
}>;*/
|
||||
export type TaskRenderProps<T extends Task = Task> = any;
|
||||
|
||||
export function dynamic<Type extends TSchema>(
|
||||
@@ -94,21 +90,6 @@ export abstract class Task<Params extends TObject = TObject, Output = unknown> {
|
||||
|
||||
// @todo: string enums fail to validate
|
||||
this._params = parse(schema, params || {});
|
||||
|
||||
/*const validator = new Validator(schema as any);
|
||||
const _params = Default(schema, params || {});
|
||||
const result = validator.validate(_params);
|
||||
if (!result.valid) {
|
||||
//console.log("---errors", result, { params, _params });
|
||||
const error = result.errors[0]!;
|
||||
throw new Error(
|
||||
`Invalid params for task "${name}.${error.keyword}": "${
|
||||
error.error
|
||||
}". Params given: ${JSON.stringify(params)}`
|
||||
);
|
||||
}
|
||||
|
||||
this._params = _params as Static<Params>;*/
|
||||
}
|
||||
|
||||
get params() {
|
||||
@@ -127,11 +108,8 @@ export abstract class Task<Params extends TObject = TObject, Output = unknown> {
|
||||
const newParams: any = {};
|
||||
const renderer = new SimpleRenderer(inputs, { strictVariables: true, renderKeys: true });
|
||||
|
||||
//console.log("--resolveParams", params);
|
||||
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value && SimpleRenderer.hasMarkup(value)) {
|
||||
//console.log("--- has markup", value);
|
||||
try {
|
||||
newParams[key] = await renderer.render(value as string);
|
||||
} catch (e: any) {
|
||||
@@ -151,29 +129,21 @@ export abstract class Task<Params extends TObject = TObject, Output = unknown> {
|
||||
throw e;
|
||||
}
|
||||
continue;
|
||||
} else {
|
||||
//console.log("-- no markup", key, value);
|
||||
}
|
||||
|
||||
newParams[key] = value;
|
||||
}
|
||||
|
||||
//console.log("--beforeDecode", newParams);
|
||||
const v = Value.Decode(schema, newParams);
|
||||
//console.log("--afterDecode", v);
|
||||
//process.exit();
|
||||
return v;
|
||||
return Value.Decode(schema, newParams);
|
||||
}
|
||||
|
||||
private async cloneWithResolvedParams(_inputs: Map<string, any>) {
|
||||
const inputs = Object.fromEntries(_inputs.entries());
|
||||
//console.log("--clone:inputs", inputs, this.params);
|
||||
const newParams = await Task.resolveParams(
|
||||
(this.constructor as any).schema,
|
||||
this._params,
|
||||
inputs,
|
||||
);
|
||||
//console.log("--clone:newParams", this.name, newParams);
|
||||
|
||||
return this.clone(this.name, newParams as any);
|
||||
}
|
||||
@@ -201,7 +171,6 @@ export abstract class Task<Params extends TObject = TObject, Output = unknown> {
|
||||
success = true;
|
||||
} catch (e: any) {
|
||||
success = false;
|
||||
//status.output = undefined;
|
||||
|
||||
if (e instanceof BkndError) {
|
||||
error = e.toJSON();
|
||||
|
||||
@@ -80,7 +80,6 @@ export class Condition {
|
||||
return result.success === false;
|
||||
case "matches":
|
||||
return get(result.output, this.path) === this.value;
|
||||
//return this.value === output[this.path];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,6 @@ export class FetchTask<Output extends Record<string, any>> extends Task<
|
||||
url: Type.String({
|
||||
pattern: "^(http|https)://",
|
||||
}),
|
||||
//method: Type.Optional(Type.Enum(FetchMethodsEnum)),
|
||||
//method: Type.Optional(dynamic(Type.String({ enum: FetchMethods, default: "GET" }))),
|
||||
method: Type.Optional(dynamic(StringEnum(FetchMethods, { default: "GET" }))),
|
||||
headers: Type.Optional(
|
||||
dynamic(
|
||||
@@ -43,7 +41,6 @@ export class FetchTask<Output extends Record<string, any>> extends Task<
|
||||
}
|
||||
|
||||
async execute() {
|
||||
//console.log(`method: (${this.params.method})`);
|
||||
if (!FetchMethods.includes(this.params.method ?? "GET")) {
|
||||
throw this.error("Invalid method", {
|
||||
given: this.params.method,
|
||||
@@ -54,19 +51,12 @@ export class FetchTask<Output extends Record<string, any>> extends Task<
|
||||
const body = this.getBody();
|
||||
const headers = new Headers(this.params.headers?.map((h) => [h.key, h.value]));
|
||||
|
||||
/*console.log("[FETCH]", {
|
||||
url: this.params.url,
|
||||
method: this.params.method ?? "GET",
|
||||
headers,
|
||||
body
|
||||
});*/
|
||||
const result = await fetch(this.params.url, {
|
||||
method: this.params.method ?? "GET",
|
||||
headers,
|
||||
body,
|
||||
});
|
||||
|
||||
//console.log("fetch:response", result);
|
||||
if (!result.ok) {
|
||||
throw this.error("Failed to fetch", {
|
||||
status: result.status,
|
||||
@@ -75,8 +65,6 @@ export class FetchTask<Output extends Record<string, any>> extends Task<
|
||||
}
|
||||
|
||||
const data = (await result.json()) as Output;
|
||||
//console.log("fetch:response:data", data);
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Task } from "../Task";
|
||||
import { $console } from "core";
|
||||
import * as tbbox from "@sinclair/typebox";
|
||||
const { Type } = tbbox;
|
||||
|
||||
@@ -11,7 +12,7 @@ export class LogTask extends Task<typeof LogTask.schema> {
|
||||
|
||||
async execute() {
|
||||
await new Promise((resolve) => setTimeout(resolve, this.params.delay));
|
||||
console.log(`[DONE] LogTask: ${this.name}`);
|
||||
$console.log(`[DONE] LogTask: ${this.name}`);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { PrimaryFieldType } from "core";
|
||||
import { type Entity, EntityIndex, type EntityManager } from "data";
|
||||
import { $console, type PrimaryFieldType } from "core";
|
||||
import { type Entity, type EntityManager } from "data";
|
||||
import { type FileUploadedEventData, Storage, type StorageAdapter } from "media";
|
||||
import { Module } from "modules/Module";
|
||||
import {
|
||||
@@ -145,11 +145,10 @@ export class AppMedia extends Module<typeof mediaConfigSchema> {
|
||||
// simple file deletion sync
|
||||
const { data } = await em.repo(media).findOne({ path: e.params.name });
|
||||
if (data) {
|
||||
console.log("item.data", data);
|
||||
await em.mutator(media).deleteOne(data.id);
|
||||
}
|
||||
|
||||
console.log("App:storage:file deleted", e);
|
||||
$console.log("App:storage:file deleted", e.params);
|
||||
},
|
||||
{ mode: "sync", id: "delete-data-media" },
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { PrimaryFieldType } from "core";
|
||||
import { $console, type PrimaryFieldType } from "core";
|
||||
import { isDebug } from "core/env";
|
||||
import { encodeSearch } from "core/utils/reqres";
|
||||
|
||||
@@ -87,7 +87,6 @@ export abstract class ModuleApi<Options extends BaseModuleApiOptions = BaseModul
|
||||
|
||||
// only add token if initial headers not provided
|
||||
if (this.options.token && this.options.token_transport === "header") {
|
||||
//console.log("setting token", this.options.token);
|
||||
headers.set("Authorization", `Bearer ${this.options.token}`);
|
||||
}
|
||||
|
||||
@@ -245,7 +244,7 @@ export class FetchPromise<T = ApiResponse<any>> implements Promise<T> {
|
||||
|
||||
const fetcher = this.options?.fetcher ?? fetch;
|
||||
if (this.verbose) {
|
||||
console.log("[FetchPromise] Request", {
|
||||
$console.debug("[FetchPromise] Request", {
|
||||
method: this.request.method,
|
||||
url: this.request.url,
|
||||
});
|
||||
@@ -253,7 +252,7 @@ export class FetchPromise<T = ApiResponse<any>> implements Promise<T> {
|
||||
|
||||
const res = await fetcher(this.request);
|
||||
if (this.verbose) {
|
||||
console.log("[FetchPromise] Response", {
|
||||
$console.debug("[FetchPromise] Response", {
|
||||
res: res,
|
||||
ok: res.ok,
|
||||
status: res.status,
|
||||
|
||||
@@ -561,7 +561,7 @@ export class ModuleManager {
|
||||
}
|
||||
|
||||
return async (...args) => {
|
||||
console.log("[Safe Mutate]", name);
|
||||
$console.log("[Safe Mutate]", name);
|
||||
try {
|
||||
// overwrite listener to run build inside this try/catch
|
||||
module.setListener(async () => {
|
||||
@@ -583,12 +583,12 @@ export class ModuleManager {
|
||||
|
||||
return result;
|
||||
} catch (e) {
|
||||
console.error("[Safe Mutate] failed", e);
|
||||
$console.error("[Safe Mutate] failed", e);
|
||||
|
||||
// revert to previous config & rebuild using original listener
|
||||
this.setConfigs(copy);
|
||||
await this.onModuleConfigUpdated(name, module.config as any);
|
||||
console.log("[Safe Mutate] reverted");
|
||||
$console.warn("[Safe Mutate] reverted");
|
||||
|
||||
// make sure to throw the error
|
||||
throw e;
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export { auth, permission } from "auth/middlewares";
|
||||
@@ -1,7 +1,6 @@
|
||||
import { _jsonp, transformObject } from "core/utils";
|
||||
import { type Kysely, sql } from "kysely";
|
||||
import { transformObject } from "core/utils";
|
||||
import type { Kysely } from "kysely";
|
||||
import { set } from "lodash-es";
|
||||
import type { InitialModuleConfigs } from "modules/ModuleManager";
|
||||
|
||||
export type MigrationContext = {
|
||||
db: Kysely<any>;
|
||||
@@ -17,7 +16,6 @@ export type Migration = {
|
||||
export const migrations: Migration[] = [
|
||||
{
|
||||
version: 1,
|
||||
//schema: true,
|
||||
up: async (config) => config,
|
||||
},
|
||||
{
|
||||
@@ -28,7 +26,6 @@ export const migrations: Migration[] = [
|
||||
},
|
||||
{
|
||||
version: 3,
|
||||
//schema: true,
|
||||
up: async (config) => config,
|
||||
},
|
||||
{
|
||||
@@ -46,7 +43,6 @@ export const migrations: Migration[] = [
|
||||
{
|
||||
version: 5,
|
||||
up: async (config, { db }) => {
|
||||
//console.log("config", _jsonp(config));
|
||||
const cors = config.server.cors?.allow_methods ?? [];
|
||||
set(config.server, "cors.allow_methods", [...new Set([...cors, "PATCH"])]);
|
||||
return config;
|
||||
@@ -114,15 +110,12 @@ export async function migrateTo(
|
||||
config: GenericConfigObject,
|
||||
ctx: MigrationContext,
|
||||
): Promise<[number, GenericConfigObject]> {
|
||||
//console.log("migrating from", current, "to", CURRENT_VERSION, config);
|
||||
const todo = migrations.filter((m) => m.version > current && m.version <= to);
|
||||
//console.log("todo", todo.length);
|
||||
let updated = Object.assign({}, config);
|
||||
|
||||
let i = 0;
|
||||
let version = current;
|
||||
for (const migration of todo) {
|
||||
//console.log("-- running migration", i + 1, "of", todo.length, { version: migration.version });
|
||||
try {
|
||||
updated = await migration.up(updated, ctx);
|
||||
version = migration.version;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** @jsxImportSource hono/jsx */
|
||||
|
||||
import type { App } from "App";
|
||||
import { config, isDebug } from "core";
|
||||
import { $console, config, isDebug } from "core";
|
||||
import { addFlashMessage } from "core/server/flash";
|
||||
import { html } from "hono/html";
|
||||
import { Fragment } from "hono/jsx";
|
||||
@@ -99,7 +99,7 @@ export class AdminController extends Controller {
|
||||
onGranted: async (c) => {
|
||||
// @todo: add strict test to permissions middleware?
|
||||
if (c.get("auth")?.user) {
|
||||
console.log("redirecting to success");
|
||||
$console.log("redirecting to success");
|
||||
return c.redirect(authRoutes.success);
|
||||
}
|
||||
},
|
||||
@@ -122,7 +122,7 @@ export class AdminController extends Controller {
|
||||
onDenied: async (c) => {
|
||||
addFlashMessage(c, "You are not authorized to access the Admin UI", "error");
|
||||
|
||||
console.log("redirecting");
|
||||
$console.log("redirecting");
|
||||
return c.redirect(authRoutes.login);
|
||||
},
|
||||
}),
|
||||
@@ -150,7 +150,7 @@ export class AdminController extends Controller {
|
||||
);
|
||||
}
|
||||
|
||||
console.warn(
|
||||
$console.warn(
|
||||
`Custom HTML needs to include '${htmlBkndContextReplace}' to inject BKND context`,
|
||||
);
|
||||
return this.options.html as string;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Exception, isDebug } from "core";
|
||||
import { Exception, isDebug, $console } from "core";
|
||||
import { type Static, StringEnum } from "core/utils";
|
||||
import { cors } from "hono/cors";
|
||||
import { Module } from "modules/Module";
|
||||
@@ -31,8 +31,6 @@ export const serverConfigSchema = Type.Object(
|
||||
export type AppServerConfig = Static<typeof serverConfigSchema>;
|
||||
|
||||
export class AppServer extends Module<typeof serverConfigSchema> {
|
||||
//private admin_html?: string;
|
||||
|
||||
override getRestrictedPaths() {
|
||||
return [];
|
||||
}
|
||||
@@ -72,14 +70,13 @@ export class AppServer extends Module<typeof serverConfigSchema> {
|
||||
|
||||
this.client.onError((err, c) => {
|
||||
//throw err;
|
||||
console.error(err);
|
||||
$console.error(err);
|
||||
|
||||
if (err instanceof Response) {
|
||||
return err;
|
||||
}
|
||||
|
||||
if (err instanceof Exception) {
|
||||
console.log("---is exception", err.code);
|
||||
return c.json(err.toJSON(), err.code as any);
|
||||
}
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ export class SystemController extends Controller {
|
||||
try {
|
||||
return c.json(await cb(), { status: 202 });
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
$console.error("config update error", e);
|
||||
|
||||
if (e instanceof TypeInvalidError) {
|
||||
return c.json(
|
||||
@@ -161,7 +161,6 @@ export class SystemController extends Controller {
|
||||
if (this.app.modules.get(module).schema().has(path)) {
|
||||
return c.json({ success: false, path, error: "Path already exists" }, { status: 400 });
|
||||
}
|
||||
console.log("-- add", module, path, value);
|
||||
|
||||
return await handleConfigUpdateResponse(c, async () => {
|
||||
await this.app.mutateConfig(module).patch(path, value);
|
||||
|
||||
@@ -35,16 +35,14 @@ export function Panels({ children, ...props }: PanelsProps) {
|
||||
)}
|
||||
<Panel unstyled position="bottom-right">
|
||||
{props.zoom && (
|
||||
<>
|
||||
<Panel.Wrapper className="px-1.5">
|
||||
<Panel.IconButton Icon={TbPlus} round onClick={handleZoomIn} />
|
||||
<Panel.Text className="px-2" mono onClick={handleZoomReset}>
|
||||
{percent}%
|
||||
</Panel.Text>
|
||||
<Panel.IconButton Icon={TbMinus} round onClick={handleZoomOut} />
|
||||
<Panel.IconButton Icon={TbMaximize} round onClick={handleZoomReset} />
|
||||
</Panel.Wrapper>
|
||||
</>
|
||||
<Panel.Wrapper className="px-1.5">
|
||||
<Panel.IconButton Icon={TbPlus} round onClick={handleZoomIn} />
|
||||
<Panel.Text className="px-2" mono onClick={handleZoomReset}>
|
||||
{percent}%
|
||||
</Panel.Text>
|
||||
<Panel.IconButton Icon={TbMinus} round onClick={handleZoomOut} />
|
||||
<Panel.IconButton Icon={TbMaximize} round onClick={handleZoomReset} />
|
||||
</Panel.Wrapper>
|
||||
)}
|
||||
{props.minimap && (
|
||||
<>
|
||||
|
||||
@@ -55,7 +55,7 @@ export default function BaseInputTemplate<
|
||||
...getInputProps<T, S, F>(schema, type, options),
|
||||
};
|
||||
|
||||
let inputValue;
|
||||
let inputValue: any;
|
||||
if (inputProps.type === "number" || inputProps.type === "integer") {
|
||||
inputValue = value || value === 0 ? value : "";
|
||||
} else {
|
||||
@@ -68,11 +68,11 @@ export default function BaseInputTemplate<
|
||||
[onChange, options],
|
||||
);
|
||||
const _onBlur = useCallback(
|
||||
({ target }: FocusEvent<HTMLInputElement>) => onBlur(id, target && target.value),
|
||||
({ target }: FocusEvent<HTMLInputElement>) => onBlur(id, target?.value),
|
||||
[onBlur, id],
|
||||
);
|
||||
const _onFocus = useCallback(
|
||||
({ target }: FocusEvent<HTMLInputElement>) => onFocus(id, target && target.value),
|
||||
({ target }: FocusEvent<HTMLInputElement>) => onFocus(id, target?.value),
|
||||
[onFocus, id],
|
||||
);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Handle, type Node, type NodeProps, Position, useReactFlow } from "@xyflow/react";
|
||||
import { Handle, type Node, type NodeProps, Position } from "@xyflow/react";
|
||||
|
||||
import type { TAppDataEntity } from "data/data-schema";
|
||||
import { useState } from "react";
|
||||
@@ -24,8 +24,6 @@ function NodeComponent(props: NodeProps<Node<TAppDataEntity & { label: string }>
|
||||
const { data } = props;
|
||||
const fields = props.data.fields ?? {};
|
||||
const field_count = Object.keys(fields).length;
|
||||
//const flow = useReactFlow();
|
||||
//const flow = useTestContext();
|
||||
|
||||
return (
|
||||
<DefaultNode selected={props.selected}>
|
||||
@@ -92,15 +90,13 @@ const TableRow = ({
|
||||
<div className="flex opacity-60">{field.type}</div>
|
||||
|
||||
{handles && (
|
||||
<>
|
||||
<Handle
|
||||
type="target"
|
||||
title={handleId}
|
||||
id={handleId}
|
||||
position={Position.Right}
|
||||
style={{ top: handleTop, right: -5, ...handleStyle }}
|
||||
/>
|
||||
</>
|
||||
<Handle
|
||||
type="target"
|
||||
title={handleId}
|
||||
id={handleId}
|
||||
position={Position.Right}
|
||||
style={{ top: handleTop, right: -5, ...handleStyle }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -73,18 +73,16 @@ export default function AppShellAccordionsTest() {
|
||||
<div className="flex flex-col h-full">
|
||||
<AppShell.SectionHeader
|
||||
right={
|
||||
<>
|
||||
<Dropdown
|
||||
items={[
|
||||
{
|
||||
label: "Settings",
|
||||
},
|
||||
]}
|
||||
position="bottom-end"
|
||||
>
|
||||
<IconButton Icon={TbDots} />
|
||||
</Dropdown>
|
||||
</>
|
||||
<Dropdown
|
||||
items={[
|
||||
{
|
||||
label: "Settings",
|
||||
},
|
||||
]}
|
||||
position="bottom-end"
|
||||
>
|
||||
<IconButton Icon={TbDots} />
|
||||
</Dropdown>
|
||||
}
|
||||
className="pl-3"
|
||||
>
|
||||
|
||||
+2
-1
@@ -69,7 +69,8 @@
|
||||
"noExplicitAny": "off",
|
||||
"noArrayIndexKey": "off",
|
||||
"noImplicitAnyLet": "warn",
|
||||
"noConfusingVoidType": "off"
|
||||
"noConfusingVoidType": "off",
|
||||
"noConsoleLog": "warn"
|
||||
},
|
||||
"security": {
|
||||
"noDangerouslySetInnerHtml": "off"
|
||||
|
||||
Reference in New Issue
Block a user