chore(root): refactor @pockethost/common

This commit is contained in:
Ben Allfree 2024-06-05 12:21:34 -07:00
parent f03ce2f690
commit 5f2d82f131
98 changed files with 333 additions and 145 deletions

View File

@ -0,0 +1,25 @@
{
"name": "@pockethost/common",
"version": "1.0.0",
"description": "",
"main": "src/index.ts",
"module": "src/index.ts",
"type": "module",
"scripts": {
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@s-libs/micro-dash": "^16.1.0",
"ajv": "^8.12.0",
"bottleneck": "^2.19.5",
"chalk": "^5.3.0",
"json-stringify-safe": "^5.0.1",
"nanoid": "^5.0.2",
"pocketbase": "^0.21.3"
},
"devDependencies": {
"@types/json-stringify-safe": "^5.0.2"
}
}

View File

@ -2,7 +2,7 @@
import chalk from 'chalk'
import stringify from 'json-stringify-safe'
import { mergeConfig } from '../util/mergeConfig'
import { mergeConfig } from '../../pockethost/src/util/mergeConfig'
import { mkSingleton } from './mkSingleton'
export type Config = {

View File

@ -1,7 +1,7 @@
import { LoggerService } from '$shared'
import { uniqueId } from '@s-libs/micro-dash'
import Bottleneck from 'bottleneck'
import { SetReturnType } from 'type-fest'
import { LoggerService } from './Logger'
const limiters: { [lane: string]: Bottleneck } = {}
export const serialAsyncExecutionGuard = <
@ -37,6 +37,7 @@ export const singletonAsyncExecutionGuard = <
const wrapper = (...args: Parameters<T>) => {
const { dbg } = LoggerService().create(`singletonAsyncExecutionGuard`)
const key = keyFactory(...args)
//@ts-ignore
if (singletons[key]) {
return singletons[key] as unknown as ReturnType<T>
}

View File

@ -7,5 +7,7 @@ export * from './events'
export * from './ioc'
export * from './mkSingleton'
export * from './newId'
export * from './pocketbase'
export * from './pocketbase-client-helpers'
export * from './schema'
export * from './stringify'

View File

@ -1,4 +1,4 @@
import { customAlphabet } from 'nanoid'
const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz')
export const newId = () => nanoid(15)
export const newId = (length = 15) => nanoid(length)

View File

@ -1,7 +1,7 @@
import Ajv, { JSONSchemaType } from 'ajv'
import type PocketBase from 'pocketbase'
import { ClientResponseError } from 'pocketbase'
import type { JsonObject } from 'type-fest'
import { PocketBase } from '..'
import { LoggerService } from '../Logger'
import { RestCommands, RestMethods } from '../schema'

View File

@ -0,0 +1,14 @@
import PocketBase, {
BaseAuthStore,
ClientResponseError,
type AuthModel,
type UnsubscribeFunc,
} from 'pocketbase'
export {
AuthModel,
BaseAuthStore,
ClientResponseError,
PocketBase,
UnsubscribeFunc,
}

View File

@ -0,0 +1,3 @@
import stringify from 'json-stringify-safe'
export { stringify }

View File

@ -0,0 +1,109 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

View File

@ -37,6 +37,7 @@
"svelte-highlight": "^7.3.0",
"svelte-preprocess": "^5.0.4",
"tailwindcss": "^3.3.3",
"vite": "^4.4.9"
"vite": "^4.4.9",
"@pockethost/common": "workspace:../common"
}
}

View File

@ -1,5 +1,5 @@
<script lang="ts">
import { InstanceStatus } from '$shared'
import { InstanceStatus } from '@pockethost/common'
import { onMount } from 'svelte'
export let status: InstanceStatus = InstanceStatus.Idle

View File

@ -1,6 +1,6 @@
<script lang="ts">
import { PLAN_NAMES, SubscriptionType } from '$shared'
import { isUserFounder, userSubscriptionType } from '$util/stores'
import { PLAN_NAMES, SubscriptionType } from '@pockethost/common'
isUserFounder

View File

@ -1,4 +1,4 @@
import { assertTruthy } from '$shared'
import { assertTruthy } from '@pockethost/common'
export const html = () => {
const htmlElement = document.querySelector('html')

View File

@ -3,9 +3,9 @@
import FeatureName from '$components/tables/pricing-table/FeatureName.svelte'
import FeatureSupportBlock from '$components/tables/pricing-table/FeatureSupportBlock.svelte'
import MobileTable from '$components/tables/pricing-table/MobileTable.svelte'
import { PLAN_NAMES, SubscriptionType } from '$shared'
import { DISCORD_URL, DOCS_URL } from '$src/env'
import { userSubscriptionType, isUserFounder } from '$util/stores'
import { isUserFounder, userSubscriptionType } from '$util/stores'
import { PLAN_NAMES, SubscriptionType } from '@pockethost/common'
type ItemValue = '1' | 'Unlimited' | 'YesBlock' | 'NoBlock'

View File

@ -1,4 +1,4 @@
import { InstanceFields } from '$shared'
import { InstanceFields } from '@pockethost/common'
import { boolean } from 'boolean'
/**

View File

@ -1,8 +1,15 @@
import { INSTANCE_URL } from '$src/env'
import { createGenericSyncEvent } from '$util/events'
import { fetchEventSource } from '@microsoft/fetch-event-source'
import {
AuthModel,
BaseAuthStore,
ClientResponseError,
CreateInstancePayloadSchema,
DeleteInstancePayload,
DeleteInstancePayloadSchema,
DeleteInstanceResult,
PocketBase,
RestCommands,
RestMethods,
UpdateInstancePayload,
@ -15,16 +22,8 @@ import {
type InstanceFields,
type InstanceId,
type InstanceLogFields,
} from '$shared'
import { INSTANCE_URL } from '$src/env'
import { createGenericSyncEvent } from '$util/events'
import { fetchEventSource } from '@microsoft/fetch-event-source'
} from '@pockethost/common'
import { keys, map } from '@s-libs/micro-dash'
import PocketBase, {
BaseAuthStore,
ClientResponseError,
type AuthModel,
} from 'pocketbase'
export type AuthToken = string
export type AuthStoreProps = {

View File

@ -1,7 +1,6 @@
<script lang="ts">
import AuthStateGuard from '$components/helpers/AuthStateGuard.svelte'
import PricingTable from '$components/tables/pricing-table/PricingTable.svelte'
import { PLAN_NAMES, SubscriptionType } from '$shared'
import { client } from '$src/pocketbase-client'
import FAQSection from '$src/routes/account/FAQSection.svelte'
import PricingCard from '$src/routes/account/PricingCard.svelte'
@ -11,6 +10,7 @@
userStore,
userSubscriptionType,
} from '$util/stores'
import { PLAN_NAMES, SubscriptionType } from '@pockethost/common'
import { onMount } from 'svelte'
import { writable } from 'svelte/store'

View File

@ -1,9 +1,9 @@
<script>
import { page } from '$app/stores'
import AlertBar from '$components/AlertBar.svelte'
import { assert } from '$shared'
import { INSTANCE_ADMIN_URL } from '$src/env'
import { globalInstancesStore } from '$util/stores'
import { assert } from '@pockethost/common'
import { instance } from './store'
let isReady = false

View File

@ -1,5 +1,5 @@
<script lang="ts">
import { assertExists } from '$shared'
import { assertExists } from '@pockethost/common'
import Code from './Code.svelte'
import Ftp from './Ftpx.svelte'
import { instance } from './store'

View File

@ -1,5 +1,5 @@
<script lang="ts">
import { assertExists } from '$shared'
import { assertExists } from '@pockethost/common'
import { instance } from '../store'
import LoggingInner from './LoggingInner.svelte'

View File

@ -1,7 +1,11 @@
<script lang="ts">
import { StreamNames, Unsubscribe, type InstanceLogFields } from '$shared'
import { client } from '$src/pocketbase-client'
import { mkCleanup } from '$util/componentCleanup'
import {
StreamNames,
Unsubscribe,
type InstanceLogFields,
} from '@pockethost/common'
import { onMount, tick } from 'svelte'
import { derived, writable } from 'svelte/store'
import { instance } from '../store'

View File

@ -1,5 +1,5 @@
<script lang="ts">
import { assertExists } from '$shared'
import { assertExists } from '@pockethost/common'
import { instance } from '../store'
import SecretsInner from './SecretsInner.svelte'

View File

@ -1,10 +1,10 @@
<script lang="ts">
import { SECRET_KEY_REGEX, UpdateInstancePayload } from '$shared'
import AlertBar from '$components/AlertBar.svelte'
import { client } from '$src/pocketbase-client/index.js'
import { SECRET_KEY_REGEX, UpdateInstancePayload } from '@pockethost/common'
import { reduce } from '@s-libs/micro-dash'
import { instance } from '../store.js'
import { items } from './stores.js'
import AlertBar from '$components/AlertBar.svelte'
// Keep track of the new key and value to be added
let secretKey: string = ''

View File

@ -1,5 +1,5 @@
<script lang="ts">
import { assertExists } from '$shared'
import { assertExists } from '@pockethost/common'
import { instance } from '../store'
import AdminSync from './AdminSync.svelte'
import CustomDomain from './CustomDomain.svelte'

View File

@ -3,10 +3,10 @@
import CodeSample from '$components/CodeSample.svelte'
import Card from '$components/cards/Card.svelte'
import CardHeader from '$components/cards/CardHeader.svelte'
import { SubscriptionType } from '$shared'
import { DOCS_URL, INSTANCE_BARE_HOST } from '$src/env'
import { client } from '$src/pocketbase-client'
import { userSubscriptionType } from '$util/stores'
import { SubscriptionType } from '@pockethost/common'
import { dns } from 'svelte-highlight/languages'
import { instance } from '../store'

View File

@ -1,4 +1,4 @@
import type { InstanceFields } from '$shared'
import type { InstanceFields } from '@pockethost/common'
import { writable } from 'svelte/store'
export const instance = writable<InstanceFields>()

View File

@ -1,6 +1,6 @@
<script lang="ts">
import { SubscriptionType } from '$shared'
import { globalInstancesStore, userSubscriptionType } from '$util/stores'
import { SubscriptionType } from '@pockethost/common'
import { values } from '@s-libs/micro-dash'
import Creator from './Creator.svelte'
import Paywall from './Paywall.svelte'

View File

@ -1,6 +1,6 @@
<script lang="ts">
import { SubscriptionType } from '$shared'
import { userSubscriptionType } from '$util/stores'
import { SubscriptionType } from '@pockethost/common'
</script>
<div class="card max-w-sm bg-base-100 shadow-xl">

View File

@ -1,9 +1,9 @@
<script lang="ts">
import Card from '$components/cards/Card.svelte'
import CardHeader from '$components/cards/CardHeader.svelte'
import { InstanceFields } from '$shared'
import InstanceRow from '$src/routes/dashboard/InstanceRow.svelte'
import { globalInstancesStore } from '$util/stores'
import { InstanceFields } from '@pockethost/common'
import { values } from '@s-libs/micro-dash'
let arrayOfActiveInstances: InstanceFields[] = []

View File

@ -1,6 +1,6 @@
<script lang="ts">
import { InstanceFields } from '$shared'
import { INSTANCE_ADMIN_URL } from '$src/env.js'
import { InstanceFields } from '@pockethost/common'
export let instance: InstanceFields
export let index: number

View File

@ -1,4 +1,4 @@
import { LoggerService, LogLevelName } from '$shared'
import { LoggerService, LogLevelName } from '@pockethost/common'
import { PUBLIC_DEBUG } from './env'
// Initiate the logging service

View File

@ -1,4 +1,4 @@
import { createCleanupManager } from '$shared'
import { createCleanupManager } from '@pockethost/common'
import { onDestroy } from 'svelte'
// TODO: Document this more

View File

@ -1,11 +1,11 @@
import { client } from '$src/pocketbase-client'
import {
SubscriptionType,
UserFields,
type InstanceFields,
type InstanceId,
} from '$shared'
import { client } from '$src/pocketbase-client'
import { UnsubscribeFunc } from 'pocketbase'
type UnsubscribeFunc,
} from '@pockethost/common'
import { writable } from 'svelte/store'
// TODO: Removing this will cause the app to crash
// Theres a reference inside of `createPocketbaseClient.ts` that needs the information that comes from this file

View File

@ -15,7 +15,6 @@ const config = {
$components: './src/components',
$util: './src/util',
$src: './src',
$shared: '../pockethost/src/shared',
},
},
target: '#svelte',

View File

@ -15,7 +15,6 @@
"paths": {
"$util/*": ["./src/util/*"],
"$src/*": ["./src/*"],
"$shared": ["../pockethost/src/shared/"],
"$components/*": ["./src/components/*"]
}
}

View File

@ -44,6 +44,7 @@
"prettier": "^3.0.3"
},
"dependencies": {
"@pockethost/common": "link:../common",
"@tailwindcss/typography": "^0.5.10",
"autoprefixer": "^10.4.16",
"boolean": "^3.2.0",

View File

@ -7,6 +7,8 @@
},
"license": "MIT",
"main": "src/index.ts",
"module": "src/index.ts",
"type": "module",
"bin": {
"pockethost": "src/cli/index.ts"
},
@ -15,15 +17,14 @@
"start": "tsx ./src/cli/index.ts",
"mail": "tsx ./src/cli/sendmail.ts"
},
"type": "module",
"dependencies": {
"@pockethost/common": "workspace:../common",
"@s-libs/micro-dash": "^16.1.0",
"@types/node-os-utils": "^1.3.4",
"@types/winston-syslog": "^2.4.3",
"ajv": "^8.12.0",
"boolean": "^3.2.0",
"bottleneck": "^2.19.5",
"chalk": "^5.3.0",
"commander": "^11.1.0",
"cors": "^2.8.5",
"decompress": "^4.2.1",
@ -46,13 +47,10 @@
"http-proxy": "^1.18.1",
"http-proxy-middleware": "^2.0.6",
"ip-cidr": "^3.1.0",
"json-stringify-safe": "^5.0.1",
"knex": "^2.5.1",
"memorystream": "^0.3.1",
"nanoid": "^5.0.2",
"node-fetch": "^3.3.2",
"node-os-utils": "^1.3.7",
"pocketbase": "^0.20.1",
"rimraf": "^5.0.5",
"semver": "^7.5.4",
"sqlite3": "^5.1.6",
@ -77,7 +75,6 @@
"@types/inquirer": "^9.0.7",
"@types/js-cookie": "^3.0.5",
"@types/js-yaml": "^4.0.9",
"@types/json-stringify-safe": "^5.0.2",
"@types/memorystream": "^0.3.3",
"@types/ncp": "^2.0.8",
"@types/node": "^20.8.10",

View File

@ -12,8 +12,8 @@ import {
proxyService,
realtimeLog,
} from '$services'
import { LoggerService } from '$shared'
import { discordAlert, tryFetch } from '$util'
import { LoggerService } from '@pockethost/common'
import { ErrorRequestHandler } from 'express'
export async function daemon() {

View File

@ -1,7 +1,7 @@
import { MOTHERSHIP_INTERNAL_URL } from '$constants'
import { ftpService } from '$services'
import { LoggerService } from '$shared'
import { tryFetch } from '$util'
import { LoggerService } from '@pockethost/common'
export async function ftp() {
const logger = LoggerService().create(`EdgeFtpCommand`)

View File

@ -1,6 +1,6 @@
import { SYSLOGD_PORT } from '$constants'
import { InstanceLogger } from '$services'
import { LoggerService } from '$shared'
import { LoggerService } from '@pockethost/common'
import * as dgram from 'dgram'
import parse from 'syslog-parse'

View File

@ -9,8 +9,8 @@ import {
SSL_CERT,
SSL_KEY,
} from '$constants'
import { LoggerService } from '$shared'
import { discordAlert } from '$util'
import { LoggerService } from '@pockethost/common'
import { forEach } from '@s-libs/micro-dash'
import cors from 'cors'
import express, { ErrorRequestHandler } from 'express'

View File

@ -3,8 +3,8 @@ import {
DISCORD_HEALTH_CHANNEL_URL,
MOTHERSHIP_PORT,
} from '$constants'
import { LoggerService } from '$shared'
import { discordAlert } from '$util'
import { LoggerService, stringify } from '@pockethost/common'
import Bottleneck from 'bottleneck'
import { execSync } from 'child_process'
import fetch from 'node-fetch'
@ -140,7 +140,7 @@ export const checkHealth = async () => {
limiter.schedule(() =>
fetch(DISCORD_URL, {
method: 'POST',
body: JSON.stringify({
body: stringify({
content,
}),
headers: { 'content-type': 'application/json' },

View File

@ -1,4 +1,4 @@
import { LoggerService } from '$shared'
import { LoggerService } from '@pockethost/common'
import { Command } from 'commander'
import { checkHealth } from './checkHealth'

View File

@ -10,7 +10,7 @@ import {
mkContainerHomePath,
} from '$constants'
import { PortService } from '$services'
import { LoggerService } from '$shared'
import { LoggerService } from '@pockethost/common'
import copyfiles from 'copyfiles'
import { GobotOptions, gobot } from 'gobot'
import { rimraf } from 'rimraf'

View File

@ -1,4 +1,5 @@
import { MOTHERSHIP_DATA_ROOT } from '$constants'
import { stringify } from '@pockethost/common'
import { writeFileSync } from 'fs'
import { gobot } from 'gobot'
@ -53,7 +54,7 @@ export async function freshenPocketbaseVersions() {
const bot = await gobot(`pocketbase`)
const rawVersions = await bot.versions()
const versions = expandAndSortSemVers(rawVersions)
const cjs = `module.exports = ${JSON.stringify(versions, null, 2)}`
const cjs = `module.exports = ${stringify(versions, null, 2)}`
writeFileSync(MOTHERSHIP_DATA_ROOT(`pb_hooks`, `versions.cjs`), cjs)
return cjs
}

View File

@ -1,4 +1,4 @@
import { LoggerService } from '$shared'
import { LoggerService } from '@pockethost/common'
import { Command } from 'commander'
import { sendMail } from './sendmail'

View File

@ -7,11 +7,10 @@ import {
TEST_EMAIL,
} from '$constants'
import { SqliteService } from '$services'
import { LoggerService, UserFields } from '$shared'
import { LoggerService, PocketBase, UserFields } from '@pockethost/common'
import { map } from '@s-libs/micro-dash'
import Bottleneck from 'bottleneck'
import { InvalidArgumentError, program } from 'commander'
import PocketBase from 'pocketbase'
const TBL_SENT_MESSAGES = `sent_messages`

View File

@ -1,4 +1,4 @@
import { LoggerService } from '$shared'
import { LoggerService } from '@pockethost/common'
import { Command } from 'commander'
import { daemon } from '../EdgeCommand/DaemonCommand/ServeCommand/daemon'
import { syslog } from '../EdgeCommand/SyslogCommand/ServeCommand/syslog'

View File

@ -1,7 +1,7 @@
#!/usr/bin/env node
import { DEBUG, DefaultSettingsService, SETTINGS } from '$constants'
import { LogLevelName, LoggerService } from '$shared'
import { LogLevelName, LoggerService } from '@pockethost/common'
import { program } from 'commander'
import EventSource from 'eventsource'
import { EdgeCommand } from './commands/EdgeCommand'

View File

@ -1,10 +1,3 @@
import {
InstanceFields,
InstanceId,
IoCManager,
UserFields,
mkSingleton,
} from '$shared'
import {
HandlerFactory,
SettingsService,
@ -14,6 +7,13 @@ import {
mkPath,
mkString,
} from '$util'
import {
InstanceFields,
InstanceId,
IoCManager,
UserFields,
mkSingleton,
} from '@pockethost/common'
import { forEach } from '@s-libs/micro-dash'
import devcert from 'devcert'
import dotenv from 'dotenv'

View File

@ -1,6 +1,6 @@
import { DATA_ROOT } from '$constants'
import { InstanceFields, Logger } from '$shared'
import { assert } from '$util'
import { InstanceFields, Logger, PocketBase, newId } from '@pockethost/common'
import { compact, map } from '@s-libs/micro-dash'
import {
Mode,
@ -11,9 +11,7 @@ import {
mkdirSync,
} from 'fs'
import { FileStat, FileSystem, FtpConnection } from 'ftp-srv'
import { customAlphabet } from 'nanoid'
import { isAbsolute, join, normalize, resolve, sep } from 'path'
import pocketbaseEs from 'pocketbase'
import {
FolderNamesMap,
INSTANCE_ROOT_VIRTUAL_FOLDER_NAMES,
@ -23,8 +21,6 @@ import {
} from '.'
import * as fsAsync from './fs-async'
const nanoid = customAlphabet(`abcdefghijklmnop`)
export type PathError = {
cause: {
errno: number
@ -47,9 +43,9 @@ export class PhFs implements FileSystem {
connection: FtpConnection
cwd: string
private _root: string
client: pocketbaseEs
client: PocketBase
constructor(connection: FtpConnection, client: pocketbaseEs, logger: Logger) {
constructor(connection: FtpConnection, client: PocketBase, logger: Logger) {
const cwd = `/`
const root = DATA_ROOT()
this.connection = connection
@ -505,6 +501,6 @@ export class PhFs implements FileSystem {
}
getUniqueName() {
return nanoid(30)
return newId(30)
}
}

View File

@ -7,12 +7,11 @@ import {
SSL_CERT,
SSL_KEY,
} from '$constants'
import { LoggerService, mkSingleton } from '$shared'
import { exitHook, mergeConfig } from '$util'
import { LoggerService, PocketBase, mkSingleton } from '@pockethost/common'
import { keys, values } from '@s-libs/micro-dash'
import { readFileSync } from 'fs'
import { FtpSrv } from 'ftp-srv'
import pocketbaseEs from 'pocketbase'
import { PhFs } from './PhFs'
export type FtpConfig = { mothershipUrl: string }
@ -89,7 +88,7 @@ export const ftpService = mkSingleton((config: Partial<FtpConfig> = {}) => {
async ({ connection, username, password }, resolve, reject) => {
dbg(`Got a connection`)
dbg(`Finding ${mothershipUrl}`)
const client = new pocketbaseEs(mothershipUrl)
const client = new PocketBase(mothershipUrl)
try {
await client.collection('users').authWithPassword(username, password)
dbg(`Logged in`)

View File

@ -1,6 +1,10 @@
import { mkInstanceDataPath } from '$constants'
import { createCleanupManager, LoggerService } from '$shared'
import { asyncExitHook, mergeConfig } from '$util'
import {
LoggerService,
createCleanupManager,
stringify,
} from '@pockethost/common'
import * as fs from 'fs'
import { Tail } from 'tail'
import * as winston from 'winston'
@ -60,7 +64,7 @@ export function InstanceLogger(
winston.format.timestamp(),
winston.format.json(),
winston.format.printf((info) => {
return JSON.stringify({
return stringify({
stream: info.level === 'info' ? 'stdout' : 'stderr',
time: info.timestamp,
message: info.message,

View File

@ -19,8 +19,10 @@ import {
SpawnConfig,
proxyService,
} from '$services'
import { asyncExitHook, mkInternalUrl, now } from '$util'
import {
CLEANUP_PRIORITY_LAST,
ClientResponseError,
InstanceFields,
InstanceId,
InstanceStatus,
@ -29,14 +31,12 @@ import {
createCleanupManager,
createTimerManager,
mkSingleton,
} from '$shared'
import { asyncExitHook, mkInternalUrl, now } from '$util'
stringify,
} from '@pockethost/common'
import { flatten, map, values } from '@s-libs/micro-dash'
import Bottleneck from 'bottleneck'
import { globSync } from 'glob'
import stringify from 'json-stringify-safe'
import { basename, join } from 'path'
import { ClientResponseError } from 'pocketbase'
import { AsyncReturnType } from 'type-fest'
import { mkInstanceCache } from './mkInstanceCache'
@ -452,7 +452,7 @@ export const instanceService = mkSingleton(
.catch((e: ClientResponseError) => {
if (e.status !== 404) {
throw new Error(
`Unexpected response ${JSON.stringify(e)} from mothership`,
`Unexpected response ${stringify(e)} from mothership`,
)
}
})
@ -474,7 +474,7 @@ export const instanceService = mkSingleton(
.catch((e: ClientResponseError) => {
if (e.status !== 404) {
throw new Error(
`Unexpected response ${JSON.stringify(e)} from mothership`,
`Unexpected response ${stringify(e)} from mothership`,
)
}
})
@ -491,7 +491,7 @@ export const instanceService = mkSingleton(
.catch((e: ClientResponseError) => {
if (e.status !== 404) {
throw new Error(
`Unexpected response ${JSON.stringify(e)} from mothership`,
`Unexpected response ${stringify(e)} from mothership`,
)
}
})

View File

@ -4,13 +4,13 @@ import {
InstanceFields_WithUser,
InstanceId,
LoggerService,
PocketBase,
UserFields,
UserId,
} from '$shared'
} from '@pockethost/common'
import { forEach } from '@s-libs/micro-dash'
import pocketbaseEs from 'pocketbase'
export const mkInstanceCache = (client: pocketbaseEs) => {
export const mkInstanceCache = (client: PocketBase) => {
const { dbg } = LoggerService().create(`InstanceCache`)
const cache: { [_: InstanceId]: InstanceFields_WithUser | undefined } = {}

View File

@ -5,7 +5,7 @@ import {
InstanceId,
InstanceStatus,
WithUser,
} from '$shared'
} from '@pockethost/common'
import { MixinContext } from '.'
export type InstanceApi = ReturnType<typeof createInstanceMixin>

View File

@ -3,11 +3,12 @@ import {
GetUserTokenPayloadSchema,
GetUserTokenResult,
LoggerService,
PocketBase,
RestCommands,
RestMethods,
createRestHelper,
} from '$shared'
import { default as PocketBase } from 'pocketbase'
stringify,
} from '@pockethost/common'
import { MixinContext } from '.'
import { createInstanceMixin } from './InstanceMIxin'
@ -30,7 +31,7 @@ export const createAdminPbClient = (url: string) => {
.create({ email, password, passwordConfirm: password })
.catch((res) => {
console.log({ email, password })
console.log(JSON.stringify(res, null, 2))
console.log(stringify(res, null, 2))
return res
})

View File

@ -3,9 +3,13 @@ import {
MOTHERSHIP_ADMIN_USERNAME,
MOTHERSHIP_URL,
} from '$constants'
import { Logger, LoggerService, mkSingleton } from '$shared'
import { mergeConfig } from '$util'
import PocketBase from 'pocketbase'
import {
Logger,
LoggerService,
PocketBase,
mkSingleton,
} from '@pockethost/common'
import { createAdminPbClient } from './createAdminPbClient'
export type ClientServiceConfig = {

View File

@ -6,13 +6,13 @@ import {
mkInstanceDataPath,
} from '$constants'
import { PortService } from '$services'
import { SyslogLogger, asyncExitHook, mkInternalUrl, tryFetch } from '$util'
import {
LoggerService,
SingletonBaseConfig,
createCleanupManager,
mkSingleton,
} from '$shared'
import { SyslogLogger, asyncExitHook, mkInternalUrl, tryFetch } from '$util'
} from '@pockethost/common'
import { map } from '@s-libs/micro-dash'
import Docker, { Container, ContainerCreateOptions } from 'dockerode'
import { existsSync } from 'fs'

View File

@ -1,6 +1,6 @@
import { INITIAL_PORT_POOL_SIZE } from '$constants'
import { mkSingleton } from '$shared'
import { mergeConfig, PromiseAllocator } from '$util'
import { mkSingleton } from '@pockethost/common'
import getPort from 'get-port'
export type Config = { maxPorts: number }

View File

@ -1,11 +1,11 @@
import { DAEMON_PORT } from '$constants'
import { asyncExitHook } from '$util'
import {
Logger,
LoggerService,
SingletonBaseConfig,
mkSingleton,
} from '$shared'
import { asyncExitHook } from '$util'
} from '@pockethost/common'
import cors from 'cors'
import express, { Request, Response } from 'express'
import 'express-async-errors'

View File

@ -2,10 +2,11 @@ import {
InstanceFields,
LoggerService,
mkSingleton,
PocketBase,
SingletonBaseConfig,
} from '$shared'
stringify,
} from '@pockethost/common'
import { text } from 'node:stream/consumers'
import pocketbaseEs from 'pocketbase'
import { JsonifiableObject } from 'type-fest/source/jsonifiable'
import { InstanceLogger } from './InstanceLoggerService'
import { proxyService } from './ProxyService'
@ -13,7 +14,7 @@ import { proxyService } from './ProxyService'
export type RealtimeLogConfig = SingletonBaseConfig & {}
const mkEvent = (name: string, data: JsonifiableObject) => {
return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`
return `event: ${name}\ndata: ${stringify(data)}\n\n`
}
export type RealtimeLog = ReturnType<typeof realtimeLog>
@ -42,7 +43,7 @@ export const realtimeLog = mkSingleton(async (config: RealtimeLogConfig) => {
}
/** Validate auth token */
const client = new pocketbaseEs(coreInternalUrl)
const client = new PocketBase(coreInternalUrl)
client.authStore.loadFromCookie(auth)
dbg(`Cookie here is`, client.authStore.isValid)
await client.collection('users').authRefresh()

View File

@ -4,7 +4,7 @@ import {
mkSingleton,
serialAsyncExecutionGuard,
SingletonBaseConfig,
} from '$shared'
} from '@pockethost/common'
import knex from 'knex'
export type SqliteServiceApi = ReturnType<typeof knex>

View File

@ -1,4 +1,4 @@
import { mkSingleton } from '$shared'
import { mkSingleton } from '@pockethost/common'
import { boolean as castToBoolean } from 'boolean'
import { existsSync, mkdirSync } from 'fs'

View File

@ -1,5 +1,5 @@
import { SYSLOGD_PORT } from '$constants'
import { LoggerService } from '$shared'
import { LoggerService } from '@pockethost/common'
import * as winston from 'winston'
import 'winston-syslog'

View File

@ -1,2 +1,2 @@
import { assert } from '$shared'
import { assert } from '@pockethost/common'
export { assert }

View File

@ -1,4 +1,5 @@
import { DISCORD_ALERT_CHANNEL_URL } from '$constants'
import { stringify } from '@pockethost/common'
const cache: { [_: string]: NodeJS.Timeout } = {}
@ -17,7 +18,7 @@ export const discordAlert = (message: { toString: () => string }) => {
fetch(url, {
method: 'POST',
body: JSON.stringify({
body: stringify({
content: message.toString(),
}),
headers: { 'Content-Type': 'application/json' },

View File

@ -1,4 +1,4 @@
import { Logger } from '$shared'
import { Logger } from '@pockethost/common'
import { exec } from 'child_process'
export const pexec = (logger: Logger) => (cmd: string) => {

View File

@ -1,4 +1,4 @@
import { LoggerService } from '$shared'
import { LoggerService } from '@pockethost/common'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
import fetch from 'node-fetch'
import { dirname } from 'path'

View File

@ -1,4 +1,4 @@
import { LoggerService } from '$shared'
import { LoggerService } from '@pockethost/common'
import fetch, { Response } from 'node-fetch'
export const TRYFETCH_RETRY_MS = 50

View File

@ -20,8 +20,7 @@
"$util": ["./src/util"],
"$services": ["./src/services"],
"$constants": ["./src/constants"],
"$src/*": ["./src/*"],
"$shared": ["./src/shared"]
"$src/*": ["./src/*"]
}
},
"include": ["**/*.ts"],

View File

@ -37,6 +37,7 @@
"svelte-highlight": "^7.3.0",
"svelte-preprocess": "^5.0.4",
"tailwindcss": "^3.3.3",
"vite": "^4.4.9"
"vite": "^4.4.9",
"@pockethost/common": "workspace:../common"
}
}

View File

@ -1,4 +1,4 @@
import { assertTruthy } from '$shared'
import { assertTruthy } from '@pockethost/common'
export const html = () => {
const htmlElement = document.querySelector('html')

View File

@ -1,10 +1,11 @@
import { createGenericSyncEvent } from '$util/events'
import { keys, map } from '@s-libs/micro-dash'
import PocketBase, {
import {
BaseAuthStore,
ClientResponseError,
PocketBase,
type AuthModel,
} from 'pocketbase'
} from '@pockethost/common'
import { keys, map } from '@s-libs/micro-dash'
export type AuthToken = string
export type AuthStoreProps = {

View File

@ -1,4 +1,4 @@
import { LoggerService, LogLevelName } from '$shared'
import { LoggerService, LogLevelName } from '@pockethost/common'
import { PUBLIC_DEBUG } from './env'
// Initiate the logging service

View File

@ -1,4 +1,4 @@
import { createCleanupManager } from '$shared'
import { createCleanupManager } from '@pockethost/common'
import { onDestroy } from 'svelte'
// TODO: Document this more

View File

@ -1,5 +1,5 @@
import { type InstanceFields, type InstanceId } from '$shared'
import { client } from '$src/pocketbase-client'
import { type InstanceFields, type InstanceId } from '@pockethost/common'
import { writable } from 'svelte/store'
// TODO: Removing this will cause the app to crash
// Theres a reference inside of `createPocketbaseClient.ts` that needs the information that comes from this file

View File

@ -15,7 +15,6 @@ const config = {
$components: './src/components',
$util: './src/util',
$src: './src',
$shared: '../pockethost/src/shared',
},
},
target: '#svelte',

View File

@ -15,7 +15,6 @@
"paths": {
"$util/*": ["./src/util/*"],
"$src/*": ["./src/*"],
"$shared": ["../pockethost/src/shared/"],
"$components/*": ["./src/components/*"]
}
}

65
pnpm-lock.yaml generated
View File

@ -186,7 +186,39 @@ importers:
specifier: ^5.2.2
version: 5.2.2
packages/common:
dependencies:
'@s-libs/micro-dash':
specifier: ^16.1.0
version: 16.1.0
ajv:
specifier: ^8.12.0
version: 8.12.0
bottleneck:
specifier: ^2.19.5
version: 2.19.5
chalk:
specifier: ^5.3.0
version: 5.3.0
json-stringify-safe:
specifier: ^5.0.1
version: 5.0.1
nanoid:
specifier: ^5.0.2
version: 5.0.2
pocketbase:
specifier: ^0.21.3
version: 0.21.3
devDependencies:
'@types/json-stringify-safe':
specifier: ^5.0.2
version: 5.0.2
packages/dashboard:
dependencies:
'@pockethost/common':
specifier: link:../common
version: link:../common
devDependencies:
'@microsoft/fetch-event-source':
specifier: https://github.com/pockethost/fetch-event-source.git#ebe3b7122647b48b93fd11effbbfb915d98956b0
@ -266,6 +298,9 @@ importers:
packages/lander:
dependencies:
'@pockethost/common':
specifier: link:../common
version: link:../common
'@tailwindcss/typography':
specifier: ^0.5.10
version: 0.5.10(tailwindcss@3.3.5)
@ -318,6 +353,9 @@ importers:
packages/pockethost:
dependencies:
'@pockethost/common':
specifier: link:../common
version: link:../common
'@s-libs/micro-dash':
specifier: ^16.1.0
version: 16.1.0
@ -336,9 +374,6 @@ importers:
bottleneck:
specifier: ^2.19.5
version: 2.19.5
chalk:
specifier: ^5.3.0
version: 5.3.0
commander:
specifier: ^11.1.0
version: 11.1.0
@ -405,27 +440,18 @@ importers:
ip-cidr:
specifier: ^3.1.0
version: 3.1.0
json-stringify-safe:
specifier: ^5.0.1
version: 5.0.1
knex:
specifier: ^2.5.1
version: 2.5.1(sqlite3@5.1.6(encoding@0.1.13))
memorystream:
specifier: ^0.3.1
version: 0.3.1
nanoid:
specifier: ^5.0.2
version: 5.0.2
node-fetch:
specifier: ^3.3.2
version: 3.3.2
node-os-utils:
specifier: ^1.3.7
version: 1.3.7
pocketbase:
specifier: ^0.20.1
version: 0.20.1
rimraf:
specifier: ^5.0.5
version: 5.0.5
@ -493,9 +519,6 @@ importers:
'@types/js-yaml':
specifier: ^4.0.9
version: 4.0.9
'@types/json-stringify-safe':
specifier: ^5.0.2
version: 5.0.2
'@types/memorystream':
specifier: ^0.3.3
version: 0.3.3
@ -557,7 +580,13 @@ importers:
specifier: ^4.6.0
version: 4.6.0
packages/pockethost-instance: {}
packages/superadmin:
dependencies:
'@pockethost/common':
specifier: link:../common
version: link:../common
devDependencies:
'@microsoft/fetch-event-source':
specifier: https://github.com/pockethost/fetch-event-source.git#ebe3b7122647b48b93fd11effbbfb915d98956b0
@ -4760,8 +4789,8 @@ packages:
engines: {node: '>=18'}
hasBin: true
pocketbase@0.20.1:
resolution: {integrity: sha512-Gl51UBc1U03JlwmwMkUIa1OHbcTmmdhyMPV1aJyHp9HuY5VUlh0t4hcx6D1fdhYsJcoh3kc6mpwhTBfXDoyn8w==}
pocketbase@0.21.3:
resolution: {integrity: sha512-bsQRZ1mj4dhPJ4P5iSrDqWQtBX2NtuBkf6IOZwTv27zZOw6zrISgo963i5JD/99qKKD5aMSMDPGk1BE9ZyI7Cg==}
possible-typed-array-names@1.0.0:
resolution: {integrity: sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==}
@ -10757,7 +10786,7 @@ snapshots:
ora: 8.0.1
v8flags: 4.0.1
pocketbase@0.20.1: {}
pocketbase@0.21.3: {}
possible-typed-array-names@1.0.0: {}