rework modals and more

This commit is contained in:
Matt Hill
2021-07-05 20:26:42 -06:00
committed by Aiden McClelland
parent b16ef3c621
commit 01c6b91c52
84 changed files with 380 additions and 508 deletions

View File

@@ -1,7 +1,7 @@
import { Dump, Revision } from 'patch-db-client'
import { PackagePropertiesVersioned } from 'src/app/util/properties.util'
import { ConfigSpec } from 'src/app/pkg-config/config-types'
import { DataModel, DependencyError, Manifest, URL } from 'src/app/models/patch-db/data-model'
import { DataModel, DependencyError, Manifest, URL } from 'src/app/services/patch-db/data-model'
export module RR {
@@ -187,6 +187,8 @@ export interface AvailablePreview {
export interface AvailableShow {
icon: URL
license: URL
instructions: URL
manifest: Manifest
categories: string[]
versions: string[]

View File

@@ -1,22 +1,17 @@
import { Subject, Observable } from 'rxjs'
import { Http, Update, Operation, Revision } from 'patch-db-client'
import { Http, Update, Operation, Revision, Source, Store } from 'patch-db-client'
import { RR } from './api-types'
import { DataModel } from 'src/app/models/patch-db/data-model'
import { filter } from 'rxjs/operators'
import { DataModel } from 'src/app/services/patch-db/data-model'
export abstract class ApiService implements Http<DataModel> {
export abstract class ApiService implements Source<DataModel>, Http<DataModel> {
protected readonly sync = new Subject<Update<DataModel>>()
private syncing = true
/** PatchDb Source interface. Post/Patch requests provide a source of patches to the db. */
// sequenceStream '_' is not used by the live api, but is overridden by the mock
watch$ (_?: Observable<number>): Observable<Update<DataModel>> {
return this.sync.asObservable().pipe(filter(() => this.syncing))
watch$ (_?: Store<DataModel>): Observable<Update<DataModel>> {
return this.sync.asObservable()
}
// used for determining internet connectivity
abstract echo (): Promise<string>
// for getting static files: ex icons, instructions, licenses
abstract getStatic (url: string): Promise<string>
@@ -189,18 +184,4 @@ export abstract class ApiService implements Http<DataModel> {
}) as any
}
}
// @TODO better types?
// private async process<T, F extends (args: object) => Promise<{ response: T, revision?: Revision }>> (f: F, temps: Operation[] = []): Promise<T> {
// let expireId = undefined
// if (temps.length) {
// expireId = uuid.v4()
// this.sync.next({ patch: temps, expiredBy: expireId })
// }
// const { response, revision } = await f({ ...f.arguments, expireId })
// if (revision) this.sync.next(revision)
// return response
// }
}
// used for type inference in syncResponse
type ExtractResultPromise<T extends Promise<any>> = T extends Promise<infer R> ? Promise<R> : any

View File

@@ -10,10 +10,6 @@ export class LiveApiService extends ApiService {
private readonly http: HttpService,
) { super() }
async echo (): Promise<string> {
return this.http.rpcRequest({ method: 'echo', params: { } })
}
async getStatic (url: string): Promise<string> {
return this.http.httpRequest({ method: Method.GET, url })
}

View File

@@ -1,195 +0,0 @@
# Size Limit [![Cult Of Martians][cult-img]][cult]
Size Limit is a performance budget tool for JavaScript. It checks every commit
on CI, calculates the real cost of your JS for end-users and throws an error
if the cost exceeds the limit.
* **ES modules** and **tree-shaking** support.
* Add Size Limit to **Travis CI**, **Circle CI**, **GitHub Actions**
or another CI system to know if a pull request adds a massive dependency.
* **Modular** to fit different use cases: big JS applications
that use their own bundler or small npm libraries with many files.
* Can calculate **the time** it would take a browser
to download and **execute** your JS. Time is a much more accurate
and understandable metric compared to the size in bytes.
* Calculations include **all dependencies and polyfills**
used in your JS.
<p align="center">
<img src="./img/example.png" alt="Size Limit CLI" width="738">
</p>
With **[GitHub action]** Size Limit will post bundle size changes as a comment
in pull request discussion.
<p align="center">
<img src="https://raw.githubusercontent.com/andresz1/size-limit-action/master/assets/pr.png"
alt="Size Limit comment in pull request about bundle size changes"
width="686" height="289">
</p>
With `--why`, Size Limit can tell you *why* your library is of this size
and show the real cost of all your internal dependencies.
<p align="center">
<img src="./img/why.png" alt="Bundle Analyzer example" width="650">
</p>
<p align="center">
<a href="https://evilmartians.com/?utm_source=size-limit">
<img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
alt="Sponsored by Evil Martians" width="236" height="54">
</a>
</p>
[GitHub action]: https://github.com/andresz1/size-limit-action
[cult-img]: http://cultofmartians.com/assets/badges/badge.svg
[cult]: http://cultofmartians.com/tasks/size-limit-config.html
## Who Uses Size Limit
* [MobX](https://github.com/mobxjs/mobx)
* [Material-UI](https://github.com/callemall/material-ui)
* [Autoprefixer](https://github.com/postcss/autoprefixer)
* [PostCSS](https://github.com/postcss/postcss) reduced
[25% of the size](https://github.com/postcss/postcss/commit/150edaa42f6d7ede73d8c72be9909f0a0f87a70f).
* [Browserslist](https://github.com/ai/browserslist) reduced
[25% of the size](https://github.com/ai/browserslist/commit/640b62fa83a20897cae75298a9f2715642531623).
* [EmojiMart](https://github.com/missive/emoji-mart) reduced
[20% of the size](https://github.com/missive/emoji-mart/pull/111)
* [nanoid](https://github.com/ai/nanoid) reduced
[33% of the size](https://github.com/ai/nanoid/commit/036612e7d6cc5760313a8850a2751a5e95184eab).
* [React Focus Lock](https://github.com/theKashey/react-focus-lock) reduced
[32% of the size](https://github.com/theKashey/react-focus-lock/pull/48).
* [Logux](https://github.com/logux) reduced
[90% of the size](https://github.com/logux/logux-client/commit/62b258e20e1818b23ae39b9c4cd49e2495781e91).
## How It Works
1. Size Limit contains a CLI tool, 3 plugins (`file`, `webpack`, `time`)
and 3 plugin presets for popular use cases (`app`, `big-lib`, `small-lib`).
A CLI tool finds plugins in `package.json` and loads the config.
2. If you use the `webpack` plugin, Size Limit will bundle your JS files into
a single file. It is important to track dependencies and webpack polyfills.
It is also useful for small libraries with many small files and without
a bundler.
3. The `webpack` plugin creates an empty webpack project, adds your library
and looks for the bundle size difference.
4. The `time` plugin compares the current machine performance with that of
a low-priced Android devices to calculate the CPU throttling rate.
5. Then the `time` plugin runs headless Chrome (or desktop Chrome if its
available) to track the time a browser takes to compile and execute your JS.
Note that these measurements depend on available resources and might
be unstable. [See here](https://github.com/mbalabash/estimo/issues/5)
for more details.
## Usage
### JS Applications
Suitable for applications that have their own bundler and send the JS bundle
directly to a client (without publishing it to npm). Think of a user-facing app
or website, like an email client, a CRM, a landing page or a blog with
interactive elements, using React/Vue/Svelte lib or vanilla JS.
<details><summary><b>Show instructions</b></summary>
1. Install the preset:
```sh
$ npm install --save-dev size-limit @size-limit/preset-app
```
2. Add the `size-limit` section and the `size` script to your `package.json`:
```diff
+ "size-limit": [
+ {
+ "path": "dist/app-*.js"
+ }
+ ],
"scripts": {
"build": "webpack ./webpack.config.js",
+ "size": "npm run build && size-limit",
"test": "jest && eslint ."
}
```
3. Heres how you can get the size for your current project:
```sh
$ npm run size
Package size: 30.08 KB with all dependencies, minified and gzipped
Loading time: 602 ms on slow 3G
Running time: 214 ms on Snapdragon 410
Total time: 815 ms
```
4. Now, lets set the limit. Add 25% to the current total time and use that as
the limit in your `package.json`:
```diff
"size-limit": [
{
+ "limit": "1 s",
"path": "dist/app-*.js"
}
],
```
5. Add the `size` script to your test suite:
```diff
"scripts": {
"build": "webpack ./webpack.config.js",
"size": "npm run build && size-limit",
- "test": "jest && eslint ."
+ "test": "jest && eslint . && npm run size"
}
```
6. If you dont have a continuous integration service running, dont forget
to add one — start with [Travis CI].
</details>
## Reports
Size Limit has a [GitHub action] that comments and rejects pull requests based
on Size Limit output.
1. Install and configure Size Limit as shown above.
2. Add the following action inside `.github/workflows/size-limit.yml`
```yaml
name: "size"
on:
pull_request:
branches:
- master
jobs:
size:
runs-on: ubuntu-latest
env:
CI_JOB_NUMBER: 1
steps:
- uses: actions/checkout@v1
- uses: andresz1/size-limit-action@v1.0.0
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
```
## JS API
```js
const sizeLimit = require('size-limit')
const filePlugin = require('@size-limit/file')
const webpackPlugin = require('@size-limit/webpack')
sizeLimit([filePlugin, webpackPlugin], [filePath]).then(result => {
result //=> { size: 12480 }
})
```

View File

@@ -2,13 +2,14 @@ import { Injectable } from '@angular/core'
import { pauseFor } from '../../util/misc.util'
import { ApiService } from './api.service'
import { Observable } from 'rxjs'
import { PatchOp, Update } from 'patch-db-client'
import { DataModel, PackageDataEntry, PackageMainStatus, PackageState, ServerStatus } from 'src/app/models/patch-db/data-model'
import { PatchOp, Store, Update } from 'patch-db-client'
import { DataModel, PackageDataEntry, PackageMainStatus, PackageState, ServerStatus } from 'src/app/services/patch-db/data-model'
import { RR } from './api-types'
import { parsePropertiesPermissive } from 'src/app/util/properties.util'
import { Mock } from './mock-app-fixures'
import { HttpService } from '../http.service'
import { ConfigService } from '../config.service'
import markdown from 'raw-loader!src/assets/markdown/md-sample.md'
import { map } from 'rxjs/operators'
@Injectable()
export class MockApiService extends ApiService {
@@ -20,18 +21,20 @@ export class MockApiService extends ApiService {
) { super() }
// every time a patch is returned from the mock, we override its sequence to be 1 more than the last sequence in the patch-db as provided by `o`.
watch$ (sequenceStream: Observable<number>): Observable<Update<DataModel>> {
sequenceStream.subscribe(i => this.sequence < i ? (this.sequence = i) : { })
watch$ (store: Store<DataModel>): Observable<Update<DataModel>> {
store.watchCache$().pipe(map(cache => cache.sequence)).subscribe(seq => {
console.log('INCOMING: ', seq)
if (this.sequence < seq) {
console.log('hererereree')
this.sequence = seq
}
})
return super.watch$()
}
async echo (): Promise<string> {
console.log('echo...echo')
return ''
}
async getStatic (url: string): Promise<string> {
return Mock.DbDump.value['package-data']['bitcoind']['static-files'].instructions
await pauseFor(2000)
return markdown
}
// db

View File

@@ -1,13 +1,12 @@
import { DependencyErrorType, DockerIoFormat, Manifest, PackageDataEntry, PackageMainStatus, PackageState, ServerStatus } from 'src/app/models/patch-db/data-model'
import { DependencyErrorType, DockerIoFormat, Manifest, PackageDataEntry, PackageMainStatus, PackageState, ServerStatus } from 'src/app/services/patch-db/data-model'
import { NotificationLevel, RR, ServerNotification, ServerNotifications } from './api-types'
import markdown from 'raw-loader!./md-sample.md'
export module Mock {
export const MarketplaceEos: RR.GetMarketplaceEOSRes = {
version: '1.0.0',
headline: 'Our biggest release ever.',
'release-notes': { '1.0.0': markdown },
'release-notes': { '1.0.0': 'Some **Markdown** release _notes_' },
}
export const AvailableList: RR.GetAvailableListRes = [
@@ -402,6 +401,8 @@ export module Mock {
'bitcoind': {
'0.19.2': {
icon: 'assets/img/service-icons/bitcoind.png',
license: 'licenseUrl',
instructions: 'instructionsUrl',
manifest: {
...Mock.MockManifestBitcoind,
version: '0.19.0',
@@ -417,6 +418,8 @@ export module Mock {
},
'0.20.0': {
icon: 'assets/img/service-icons/bitcoind.png',
license: 'licenseUrl',
instructions: 'instructionsUrl',
manifest: {
...Mock.MockManifestBitcoind,
version: '0.20.0',
@@ -432,6 +435,8 @@ export module Mock {
},
'0.21.0': {
icon: 'assets/img/service-icons/bitcoind.png',
license: 'licenseUrl',
instructions: 'instructionsUrl',
manifest: {
...Mock.MockManifestBitcoind,
version: '0.21.0',
@@ -448,6 +453,8 @@ export module Mock {
},
'latest': {
icon: 'assets/img/service-icons/bitcoind.png',
license: 'licenseUrl',
instructions: 'instructionsUrl',
manifest: {
...Mock.MockManifestBitcoind,
'release-notes': 'Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.',
@@ -465,6 +472,8 @@ export module Mock {
'lnd': {
'0.11.0': {
icon: 'assets/img/service-icons/lnd.png',
license: 'licenseUrl',
instructions: 'instructionsUrl',
manifest: {
...Mock.MockManifestLnd,
version: '0.11.0',
@@ -490,6 +499,8 @@ export module Mock {
},
'0.11.1': {
icon: 'assets/img/service-icons/lnd.png',
license: 'licenseUrl',
instructions: 'instructionsUrl',
manifest: {
...Mock.MockManifestLnd,
version: '0.11.1',
@@ -515,6 +526,8 @@ export module Mock {
},
'latest': {
icon: 'assets/img/service-icons/lnd.png',
license: 'licenseUrl',
instructions: 'instructionsUrl',
manifest: Mock.MockManifestLnd,
categories: ['bitcoin', 'lightning', 'cryptocurrency'],
versions: ['0.11.0', '0.11.1'],
@@ -538,6 +551,8 @@ export module Mock {
'bitcoin-proxy': {
'latest': {
icon: 'assets/img/service-icons/bitcoin-proxy.png',
license: 'licenseUrl',
instructions: 'instructionsUrl',
manifest: Mock.MockManifestBitcoinProxy,
categories: ['bitcoin'],
versions: ['0.2.2'],
@@ -559,9 +574,9 @@ export module Mock {
export const bitcoind: PackageDataEntry = {
state: PackageState.Installed,
'static-files': {
license: 'licenseURL',
license: 'licenseUrl', // /public/package-data/bitcoind/0.21.1/LICENSE.md,
icon: 'assets/img/service-icons/bitcoind.png',
instructions: markdown, // /public/package-data/bitcoind/0.21.1/INSTRUCTIONS.md
instructions: 'instructionsUrl', // /public/package-data/bitcoind/0.21.1/INSTRUCTIONS.md
},
'temp-manifest': undefined,
installed: {
@@ -610,9 +625,9 @@ export module Mock {
export const lnd: PackageDataEntry = {
state: PackageState.Installed,
'static-files': {
license: 'licenseURL',
license: 'licenseUrl', // /public/package-data/lnd/0.21.1/LICENSE.md,
icon: 'assets/img/service-icons/lnd.png',
instructions: markdown, // /public/package-data/bitcoind/0.21.1/INSTRUCTIONS.md
instructions: 'instructionsUrl', // /public/package-data/lnd/0.21.1/INSTRUCTIONS.md
},
'temp-manifest': undefined,
installed: {
@@ -662,9 +677,9 @@ export module Mock {
export const bitcoinproxy: PackageDataEntry = {
state: PackageState.Installed,
'static-files': {
license: 'licenseURL',
license: 'licenseUrl', // /public/package-data/bitcoinproxy/0.21.1/LICENSE.md,
icon: 'assets/img/service-icons/bitcoin-proxy.png',
instructions: '*These are some instructions.*', // /public/package-data/bitcoinproxy/0.2.2/INSTRUCTIONS.md
instructions: 'instructionsUrl', // /public/package-data/bitcoinproxy/0.2.2/INSTRUCTIONS.md
},
'temp-manifest': undefined,
installed: {
@@ -737,7 +752,6 @@ export module Mock {
'lnd': lnd,
},
ui: {
'server-name': 'My Embassy',
'welcome-ack': '1.0.0',
'auto-check-updates': true,
},

View File

@@ -3,7 +3,6 @@ import { BehaviorSubject, Observable } from 'rxjs'
import { distinctUntilChanged } from 'rxjs/operators'
import { ApiService } from './api/api.service'
import { Storage } from '@ionic/storage'
import { StorageKeys } from '../models/storage-keys'
export enum AuthState {
UNVERIFIED,
@@ -14,6 +13,7 @@ export enum AuthState {
providedIn: 'root',
})
export class AuthService {
private readonly LOGGED_IN_KEY = 'loggedInKey'
private readonly authState$: BehaviorSubject<AuthState> = new BehaviorSubject(AuthState.INITIALIZING)
constructor (
@@ -22,7 +22,7 @@ export class AuthService {
) { }
async init (): Promise<void> {
const loggedIn = await this.storage.get(StorageKeys.LOGGED_IN_KEY)
const loggedIn = await this.storage.get(this.LOGGED_IN_KEY)
this.authState$.next( loggedIn ? AuthState.VERIFIED : AuthState.UNVERIFIED)
}
@@ -32,7 +32,7 @@ export class AuthService {
async login (password: string): Promise<void> {
await this.api.login({ password })
await this.storage.set(StorageKeys.LOGGED_IN_KEY, true)
await this.storage.set(this.LOGGED_IN_KEY, true)
this.authState$.next(AuthState.VERIFIED)
}

View File

@@ -1,5 +1,5 @@
import { Injectable } from '@angular/core'
import { InstalledPackageDataEntry, InterfaceDef, Manifest, PackageDataEntry, PackageMainStatus, PackageState } from '../models/patch-db/data-model'
import { InstalledPackageDataEntry, InterfaceDef, Manifest, PackageDataEntry, PackageMainStatus, PackageState } from './patch-db/data-model'
const { patchDb, api, mocks } = require('../../../ui-config.json') as UiConfig

View File

@@ -1,9 +1,9 @@
import { Injectable } from '@angular/core'
import { BehaviorSubject, combineLatest, fromEvent, merge, Observable, Subscription } from 'rxjs'
import { ConnectionStatus } from '../../../../../patch-db/client/dist'
import { DataModel } from '../models/patch-db/data-model'
import { PatchDbModel } from '../models/patch-db/patch-db-model'
import { BehaviorSubject, combineLatest, fromEvent, merge, Subscription } from 'rxjs'
import { DataModel } from './patch-db/data-model'
import { ConnectionStatus, PatchDbModel } from './patch-db/patch-db.service'
import { HttpService, Method } from './http.service'
import { distinctUntilChanged } from 'rxjs/operators'
@Injectable({
providedIn: 'root',
@@ -19,7 +19,7 @@ export class ConnectionService {
private readonly patch: PatchDbModel,
) { }
watch$ () {
watchFailure$ () {
return this.connectionFailure$.asObservable()
}
@@ -39,22 +39,27 @@ export class ConnectionService {
this.networkState$.next(event.type === 'online')
}),
combineLatest([this.networkState$, this.patch.connectionStatus$()])
combineLatest([this.networkState$.pipe(distinctUntilChanged()), this.patch.watchConnection$().pipe(distinctUntilChanged())])
.subscribe(async ([network, connectionStatus]) => {
console.log('CONNECTION STATUS', connectionStatus)
if (connectionStatus !== ConnectionStatus.Disconnected) {
this.connectionFailure$.next(ConnectionFailure.None)
} else if (!network) {
this.connectionFailure$.next(ConnectionFailure.Network)
} else {
console.log('diagnosing')
this.connectionFailure$.next(ConnectionFailure.Diagnosing)
const torSuccess = await this.testAddrs(this.addrs.tor)
if (torSuccess) {
console.log('TOR SUCCESS, EMBASSY IS PROBLEM')
this.connectionFailure$.next(ConnectionFailure.Embassy)
} else {
const clearnetSuccess = await this.testAddrs(this.addrs.clearnet)
if (clearnetSuccess) {
console.log('CLEARNET SUCCESS, TOR IS PROBLEM')
this.connectionFailure$.next(ConnectionFailure.Tor)
} else {
console.log('INTERNET IS PROBLEM')
this.connectionFailure$.next(ConnectionFailure.Internet)
}
}

View File

@@ -0,0 +1,384 @@
import { ConfigSpec } from 'src/app/pkg-config/config-types'
export interface DataModel {
'server-info': ServerInfo
'package-data': { [id: string]: PackageDataEntry }
ui: UIData
}
export interface ServerInfo {
id: string
version: string
'lan-address': URL
'tor-address': URL
status: ServerStatus
'package-registry': URL
'system-registry': URL
wifi: WiFiInfo
'unread-notification-count': number
specs: {
CPU: string
Disk: string
Memory: string
}
'connection-addresses': {
tor: string[]
clearnet: string[]
}
}
export enum ServerStatus {
Running = 'running',
Updating = 'updating',
BackingUp = 'backing-up',
}
export interface WiFiInfo {
ssids: string[]
selected: string | null
connected: string | null
}
export interface PackageDataEntry {
state: PackageState
'static-files': {
license: URL
instructions: URL
icon: URL
}
'temp-manifest'?: Manifest // exists when: installing, updating, removing
installed?: InstalledPackageDataEntry, // exists when: installed, updating
'install-progress'?: InstallProgress, // exists when: installing, updating
}
export interface InstallProgress {
size: number | null
downloaded: number
'download-complete': boolean
validated: number
'validation-complete': boolean
read: number
'read-complete': boolean
}
export interface InstalledPackageDataEntry {
manifest: Manifest
status: Status
'interface-info': InterfaceInfo
'system-pointers': any[]
'current-dependents': { [id: string]: CurrentDependencyInfo }
'current-dependencies': { [id: string]: CurrentDependencyInfo }
}
export interface CurrentDependencyInfo {
pointers: any[]
'health-checks': string[] // array of health check IDs
}
export enum PackageState {
Installing = 'installing',
Installed = 'installed',
Updating = 'updating',
Removing = 'removing',
}
export interface Manifest {
id: string
title: string
version: string
description: {
short: string
long: string
}
'release-notes': string
license: string // name
'wrapper-repo': URL
'upstream-repo': URL
'support-site': URL
'marketing-site': URL
'donation-url': URL | null
alerts: {
install: string | null
uninstall: string | null
restore: string | null
start: string | null
stop: string | null
}
main: ActionImpl
'health-checks': { [id: string]: ActionImpl & { critical: boolean } }
config: ConfigActions | null
volumes: { [id: string]: Volume }
'min-os-version': string
interfaces: { [id: string]: InterfaceDef }
backup: BackupActions
migrations: Migrations
actions: { [id: string]: Action }
permissions: any // @TODO
dependencies: DependencyInfo
}
export interface ActionImpl {
type: 'docker'
image: string
system: boolean
entrypoint: string
args: string[]
mounts: { [id: string]: string }
'io-format': DockerIoFormat | null
inject: boolean
'shm-size': string
}
export enum DockerIoFormat {
Json = 'json',
Yaml = 'yaml',
Cbor = 'cbor',
Toml = 'toml',
}
export interface ConfigActions {
get: ActionImpl
set: ActionImpl
}
export type Volume = VolumeData
export interface VolumeData {
type: VolumeType.Data
readonly: boolean
}
export interface VolumePointer {
type: VolumeType.Pointer
'package-id': string
'volume-id': string
path: string
readonly: boolean
}
export interface VolumeCertificate {
type: VolumeType.Certificate
'interface-id': string
}
export interface VolumeHiddenService {
type: VolumeType.HiddenService
'interface-id': string
}
export interface VolumeBackup {
type: VolumeType.Backup
readonly: boolean
}
export enum VolumeType {
Data = 'data',
Pointer = 'pointer',
Certificate = 'certificate',
HiddenService = 'hidden-service',
Backup = 'backup',
}
export interface InterfaceDef {
name: string
description: string
ui: boolean
'tor-config': TorConfig | null
'lan-config': LanConfig | null
protocols: string[]
}
export interface TorConfig {
'hidden-service-version': string
'port-mapping': { [port: number]: number }
}
export type LanConfig = {
[port: number]: { ssl: boolean, mapping: number }
}
export interface BackupActions {
create: ActionImpl
restore: ActionImpl
}
export interface Migrations {
from: { [versionRange: string]: ActionImpl }
to: { [versionRange: string]: ActionImpl }
}
export interface Action {
name: string
description: string
warning: string | null
implementation: ActionImpl
'allowed-statuses': (PackageMainStatus.Stopped | PackageMainStatus.Running)[]
'input-spec': ConfigSpec
}
export interface Status {
configured: boolean
main: MainStatus
'dependency-errors': { [id: string]: DependencyError }
}
export type MainStatus = MainStatusStopped | MainStatusStopping | MainStatusRunning | MainStatusBackingUp | MainStatusRestoring
export interface MainStatusStopped {
status: PackageMainStatus.Stopped
}
export interface MainStatusStopping {
status: PackageMainStatus.Stopping
}
export interface MainStatusRunning {
status: PackageMainStatus.Running
started: string // UTC date string
health: { [id: string]: HealthCheckResult }
}
export interface MainStatusBackingUp {
status: PackageMainStatus.BackingUp
started: string | null // UTC date string
}
export interface MainStatusRestoring {
status: PackageMainStatus.Restoring
running: boolean
}
export enum PackageMainStatus {
Running = 'running',
Stopping = 'stopping',
Stopped = 'stopped',
BackingUp = 'backing-up',
Restoring = 'restoring',
}
export type HealthCheckResult = HealthCheckResultStarting | HealthCheckResultLoading | HealthCheckResultDisabled | HealthCheckResultSuccess | HealthCheckResultFailure
export enum HealthResult {
Starting = 'starting',
Loading = 'loading',
Disabled = 'disabled',
Success = 'success',
Failure = 'failure',
}
export interface HealthCheckResultStarting {
time: string // UTC date string
result: HealthResult.Starting
}
export interface HealthCheckResultDisabled {
time: string // UTC date string
result: HealthResult.Disabled
}
export interface HealthCheckResultSuccess {
time: string // UTC date string
result: HealthResult.Success
}
export interface HealthCheckResultLoading {
time: string // UTC date string
result: HealthResult.Loading
message: string
}
export interface HealthCheckResultFailure {
time: string // UTC date string
result: HealthResult.Failure
error: string
}
export type DependencyError = DependencyErrorNotInstalled | DependencyErrorNotRunning | DependencyErrorIncorrectVersion | DependencyErrorConfigUnsatisfied | DependencyErrorHealthCheckFailed | DependencyErrorInterfaceHealthChecksFailed
export enum DependencyErrorType {
NotInstalled = 'not-installed',
NotRunning = 'not-running',
IncorrectVersion = 'incorrect-version',
ConfigUnsatisfied = 'config-unsatisfied',
HealthCheckFailed = 'health-check-failed',
InterfaceHealthChecksFailed = 'interface-health-checks-failed',
}
export interface DependencyErrorNotInstalled {
type: DependencyErrorType.NotInstalled
title: string
icon: URL
}
export interface DependencyErrorNotRunning {
type: DependencyErrorType.NotRunning
}
export interface DependencyErrorIncorrectVersion {
type: DependencyErrorType.IncorrectVersion
expected: string // version range
received: string // version
}
export interface DependencyErrorConfigUnsatisfied {
type: DependencyErrorType.ConfigUnsatisfied
errors: string[]
}
export interface DependencyErrorHealthCheckFailed {
type: DependencyErrorType.HealthCheckFailed
check: HealthCheckResult
}
export interface DependencyErrorInterfaceHealthChecksFailed {
type: DependencyErrorType.InterfaceHealthChecksFailed
failures: { [id: string]: HealthCheckResult }
}
export interface DependencyInfo {
[id: string]: DependencyEntry
}
export interface DependencyEntry {
version: string
optional: string | null
recommended: boolean
description: string | null
config: ConfigRuleEntryWithSuggestions[]
interfaces: any[] // @TODO placeholder
}
export interface ConfigRuleEntryWithSuggestions {
rule: string
description: string
suggestions: Suggestion[]
}
export interface Suggestion {
condition: string | null
set?: {
var: string
to?: string
'to-value'?: any
'to-entropy'?: { charset: string, len: number }
}
delete?: string
push?: {
to: string
value: any
}
}
export interface InterfaceInfo {
ip: string
addresses: {
[id: string]: { 'tor-address': string, 'lan-address': string }
}
}
export type URL = string
export interface UIData {
'welcome-ack': string
'auto-check-updates': boolean
}

View File

@@ -0,0 +1,24 @@
import { Bootstrapper, DBCache } from 'patch-db-client'
import { DataModel } from './data-model'
import { Injectable } from '@angular/core'
import { Storage } from '@ionic/storage'
@Injectable({
providedIn: 'root',
})
export class LocalStorageBootstrap implements Bootstrapper<DataModel> {
static CONTENT_KEY = 'patch-db-cache'
constructor (
private readonly storage: Storage,
) { }
async init (): Promise<DBCache<DataModel>> {
const cache: DBCache<DataModel> = await this.storage.get(LocalStorageBootstrap.CONTENT_KEY)
return cache || { sequence: 0, data: { } }
}
async update (cache: DBCache<DataModel>): Promise<void> {
await this.storage.set(LocalStorageBootstrap.CONTENT_KEY, cache)
}
}

View File

@@ -0,0 +1,35 @@
import { PollSource, Source, WebsocketSource } from 'patch-db-client'
import { ConfigService } from 'src/app/services/config.service'
import { DataModel } from './data-model'
import { LocalStorageBootstrap } from './local-storage-bootstrap'
import { PatchDbModel } from './patch-db.service'
import { ApiService } from 'src/app/services/api/api.service'
export function PatchDbModelFactory (
config: ConfigService,
bootstrapper: LocalStorageBootstrap,
apiService: ApiService,
): PatchDbModel {
const { mocks, patchDb: { poll }, isConsulate } = config
let source: Source<DataModel>
if (mocks.enabled) {
if (mocks.connection === 'poll') {
source = new PollSource({ ...poll }, apiService)
} else {
source = new WebsocketSource(`ws://localhost:${config.mocks.wsPort}/db`)
}
} else {
if (isConsulate) {
source = new PollSource({ ...poll }, apiService)
} else {
const protocol = window.location.protocol === 'http:' ? 'ws' : 'wss'
const host = window.location.host
source = new WebsocketSource(`${protocol}://${host}/ws/db`)
}
}
return new PatchDbModel(bootstrapper, [source, apiService])
}

View File

@@ -0,0 +1,89 @@
import { Inject, Injectable, InjectionToken } from '@angular/core'
import { Bootstrapper, PatchDB, Source, Store } from 'patch-db-client'
import { BehaviorSubject, Observable, of, Subscription } from 'rxjs'
import { catchError, debounceTime, map, tap } from 'rxjs/operators'
import { DataModel } from './data-model'
export const BOOTSTRAPPER = new InjectionToken<Bootstrapper<DataModel>>('app.config')
export const PATCH_SOURCE = new InjectionToken<Source<DataModel>>('app.config')
export enum ConnectionStatus {
Initializing = 'initializing',
Connected = 'connected',
Disconnected = 'disconnected',
}
@Injectable({
providedIn: 'root',
})
export class PatchDbModel {
connectionStatus$ = new BehaviorSubject(ConnectionStatus.Initializing)
private patchDb: PatchDB<DataModel>
private patchSub: Subscription
constructor (
@Inject(BOOTSTRAPPER) private readonly bootstrapper: Bootstrapper<DataModel>,
@Inject(PATCH_SOURCE) private readonly sources: Source<DataModel>[],
) { }
async init (): Promise<void> {
const cache = await this.bootstrapper.init()
this.patchDb = new PatchDB(this.sources, cache)
}
start (): void {
// make sure everything is stopped before initializing
this.stop()
try {
this.patchSub = this.patchDb.sync$()
.pipe(debounceTime(500))
.subscribe({
next: cache => {
console.log('saving cacheee: ', cache)
this.connectionStatus$.next(ConnectionStatus.Connected)
this.bootstrapper.update(cache)
},
error: e => {
console.error('patch-db-sync sub ERROR', e)
this.connectionStatus$.next(ConnectionStatus.Disconnected)
// this.start()
},
complete: () => {
console.error('patch-db-sync sub COMPLETE')
},
})
} catch (e) {
console.log('Failed to initialize PatchDB', e)
}
}
stop (): void {
if (this.patchSub) {
this.patchSub.unsubscribe()
this.patchSub = undefined
}
}
connected$ (): Observable<boolean> {
return this.connectionStatus$
.pipe(
map(status => status === ConnectionStatus.Connected),
)
}
watchConnection$ (): Observable<ConnectionStatus> {
return this.connectionStatus$.asObservable()
}
watch$: Store<DataModel> ['watch$'] = (...args: (string | number)[]): Observable<DataModel> => {
// console.log('WATCHING')
return this.patchDb.store.watch$(...(args as [])).pipe(
tap(cache => console.log('CHANGE IN STORE', cache)),
catchError(e => {
console.error(e)
return of(e.message)
}),
// finalize(() => console.log('unSUBSCRIBing')),
)
}
}

View File

@@ -1,4 +1,4 @@
import { HealthCheckResultLoading, MainStatusRunning, PackageDataEntry, PackageMainStatus, PackageState, Status } from '../models/patch-db/data-model'
import { HealthCheckResultLoading, MainStatusRunning, PackageDataEntry, PackageMainStatus, PackageState, Status } from './patch-db/data-model'
export function renderPkgStatus (pkg: PackageDataEntry): PkgStatusRendering {
switch (pkg.state) {
@@ -15,7 +15,7 @@ function handleInstalledState (status: Status): PkgStatusRendering {
}
if (Object.keys(status['dependency-errors']).length) {
return { display: 'Needs Attention', color: 'warning', showDots: false, feStatus: FEStatus.DependencyIssue }
return { display: 'Dependency Issue', color: 'warning', showDots: false, feStatus: FEStatus.DependencyIssue }
}
switch (status.main.status) {

View File

@@ -1,10 +1,10 @@
import { Injectable } from '@angular/core'
import { ModalController } from '@ionic/angular'
import { AppConfigValuePage } from '../modals/app-config-value/app-config-value.page'
import { ApiService } from './api/api.service'
import { ConfigSpec } from '../pkg-config/config-types'
import { ConfigCursor } from '../pkg-config/config-cursor'
import { SSHService } from '../pages/server-routes/developer-routes/dev-ssh-keys/ssh.service'
import { TrackingModalController } from './tracking-modal-controller.service'
@Injectable({
providedIn: 'root',
@@ -12,7 +12,7 @@ import { SSHService } from '../pages/server-routes/developer-routes/dev-ssh-keys
export class ServerConfigService {
constructor (
private readonly modalCtrl: ModalController,
private readonly trackingModalCtrl: TrackingModalController,
private readonly apiService: ApiService,
private readonly sshService: SSHService,
) { }
@@ -20,10 +20,10 @@ export class ServerConfigService {
async presentModalValueEdit (key: string, current?: string) {
const cursor = new ConfigCursor(serverConfig, { [key]: current }).seekNext(key)
const modal = await this.modalCtrl.create({
const modal = await this.trackingModalCtrl.create({
backdropDismiss: false,
component: AppConfigValuePage,
presentingElement: await this.modalCtrl.getTop(),
presentingElement: await this.trackingModalCtrl.getTop(),
componentProps: {
cursor,
saveFn: this.saveFns[key],

View File

@@ -1,10 +1,11 @@
import { Inject, Injectable } from '@angular/core'
import { Inject, Injectable, InjectionToken } from '@angular/core'
import { Observable, Subject } from 'rxjs'
import { ModalController } from '@ionic/angular'
import { ModalOptions } from '@ionic/core'
import { APP_CONFIG_COMPONENT_MAPPING } from '../modals/app-config-injectable/modal-injectable-token'
import { AppConfigComponentMapping } from '../modals/app-config-injectable/modal-injectable-type'
import { ValueSpec } from '../pkg-config/config-types'
import { AppConfigComponentMapping } from '../modals/app-config-injectable'
export const APP_CONFIG_COMPONENT_MAPPING = new InjectionToken<string>('APP_CONFIG_COMPONENTS')
@Injectable({
providedIn: 'root',