chore: New sdk things

This commit is contained in:
BluJ
2023-03-06 15:28:11 -07:00
parent 40c75cfcb2
commit b4fc6e891e
19 changed files with 157 additions and 185 deletions

View File

@@ -12,6 +12,9 @@ bundle: fmt $(TS_FILES) .FORCE node_modules
npx tsc-multi
npx tsc --emitDeclarationOnly
check:
npm run check
fmt: node_modules
npx prettier --write "**/*.ts"

View File

@@ -4,7 +4,7 @@
For making the patterns that are wanted in making services for the startOS.
### Generate: Config class from legacy ConfigSpec
### Generate: Config class from legacy InputSpec
```sh
cat utils/test/config.json | deno run https://deno.land/x/embassyd_sdk/scripts/oldSpecToBuilder.ts "../../mod" |deno fmt - > utils/test/output.ts

View File

@@ -1,4 +1,3 @@
import { ok } from "../util";
import * as T from "../types";
export const DEFAULT_OPTIONS: T.BackupOptions = {
@@ -41,7 +40,7 @@ export class Backups {
constructor(
private options = DEFAULT_OPTIONS,
private backupSet = [] as BackupSet[]
private backupSet = [] as BackupSet[],
) {}
static volumes(...volumeNames: string[]) {
return new Backups().addSets(
@@ -50,7 +49,7 @@ export class Backups {
srcPath: "./",
dstPath: `./${srcVolume}/`,
dstVolume: Backups.BACKUP,
}))
})),
);
}
static addSets(...options: BackupSet[]) {
@@ -73,12 +72,12 @@ export class Backups {
srcPath: "./",
dstPath: `./${srcVolume}/`,
dstVolume: Backups.BACKUP,
}))
})),
);
}
addSets(...options: BackupSet[]) {
options.forEach((x) =>
this.backupSet.push({ ...x, options: { ...this.options, ...x.options } })
this.backupSet.push({ ...x, options: { ...this.options, ...x.options } }),
);
return this;
}
@@ -99,7 +98,7 @@ export class Backups {
.map((x) => x.dstPath)
.map((x) => x.replace(/\.\/([^]*)\//, "$1"));
const filteredItems = previousItems.filter(
(x) => backupPaths.indexOf(x) === -1
(x) => backupPaths.indexOf(x) === -1,
);
for (const itemToRemove of filteredItems) {
effects.error(`Trying to remove ${itemToRemove}`);
@@ -112,7 +111,7 @@ export class Backups {
effects.removeFile({
volumeId: Backups.BACKUP,
path: itemToRemove,
})
}),
)
.catch(() => {
effects.warn(`Failed to remove ${itemToRemove} from backup volume`);
@@ -135,7 +134,7 @@ export class Backups {
})
.wait();
}
return ok;
return;
};
const restoreBackup: T.ExpectedExports.restoreBackup = async ({
effects,
@@ -160,7 +159,7 @@ export class Backups {
})
.wait();
}
return ok;
return;
};
return { createBackup, restoreBackup };
}

View File

@@ -1,4 +1,4 @@
import { ConfigSpec, ValueSpec } from "../../types/config-types";
import { InputSpec, ValueSpec } from "../../types/config-types";
import { typeFromProps } from "../../util";
import { BuilderExtract, IBuilder } from "./builder";
import { Value } from "./value";
@@ -483,19 +483,19 @@ import { Value } from "./value";
```
*/
export class Config<A extends ConfigSpec> extends IBuilder<A> {
export class Config<A extends InputSpec> extends IBuilder<A> {
static empty() {
return new Config({});
}
static withValue<K extends string, B extends ValueSpec>(
key: K,
value: Value<B>
value: Value<B>,
) {
return Config.empty().withValue(key, value);
}
static addValue<K extends string, B extends ValueSpec>(
key: K,
value: Value<B>
value: Value<B>,
) {
return Config.empty().withValue(key, value);
}

View File

@@ -4,7 +4,7 @@ import { Default, NumberSpec, StringSpec } from "./value";
import { Description } from "./value";
import { Variants } from "./variants";
import {
ConfigSpec,
InputSpec,
UniqueBy,
ValueSpecList,
ValueSpecListOf,
@@ -38,7 +38,7 @@ export class List<A extends ValueSpecList> extends IBuilder<A> {
Default<string[]> & {
range: string;
spec: StringSpec;
}
},
>(a: A) {
return new List({
type: "list" as const,
@@ -51,7 +51,7 @@ export class List<A extends ValueSpecList> extends IBuilder<A> {
Default<number[]> & {
range: string;
spec: NumberSpec;
}
},
>(a: A) {
return new List({
type: "list" as const,
@@ -69,7 +69,7 @@ export class List<A extends ValueSpecList> extends IBuilder<A> {
[key: string]: string;
};
};
}
},
>(a: A) {
return new List({
type: "list" as const,
@@ -82,11 +82,11 @@ export class List<A extends ValueSpecList> extends IBuilder<A> {
Default<Record<string, unknown>[]> & {
range: string;
spec: {
spec: Config<ConfigSpec>;
spec: Config<InputSpec>;
"display-as": null | string;
"unique-by": null | UniqueBy;
};
}
},
>(a: A) {
const { spec: previousSpec, ...rest } = a;
const { spec: previousSpecSpec, ...restSpec } = previousSpec;
@@ -121,13 +121,13 @@ export class List<A extends ValueSpecList> extends IBuilder<A> {
[key: string]: string;
};
};
variants: Variants<{ [key: string]: ConfigSpec }>;
variants: Variants<{ [key: string]: InputSpec }>;
"display-as": null | string;
"unique-by": UniqueBy;
default: string;
};
},
B extends string
B extends string,
>(a: A) {
const { spec: previousSpec, ...rest } = a;
const { variants: previousVariants, ...restSpec } = previousSpec;

View File

@@ -3,7 +3,7 @@ import { Config } from "./config";
import { List } from "./list";
import { Variants } from "./variants";
import {
ConfigSpec,
InputSpec,
UniqueBy,
ValueSpec,
ValueSpecList,
@@ -80,7 +80,7 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
A extends Description &
NullableDefault<DefaultString> &
Nullable &
StringSpec
StringSpec,
>(a: A) {
return new Value({
type: "string" as const,
@@ -88,7 +88,7 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
} as ValueSpecString);
}
static number<
A extends Description & NullableDefault<number> & Nullable & NumberSpec
A extends Description & NullableDefault<number> & Nullable & NumberSpec,
>(a: A) {
return new Value({
type: "number" as const,
@@ -100,7 +100,7 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
Default<string> & {
values: readonly string[] | string[];
"value-names": Record<string, string>;
}
},
>(a: A) {
return new Value({
type: "enum" as const,
@@ -115,9 +115,9 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
default: null | { [k: string]: unknown };
"display-as": null | string;
"unique-by": null | string;
spec: Config<ConfigSpec>;
spec: Config<InputSpec>;
"value-names": Record<string, string>;
}
},
>(a: A) {
const { spec: previousSpec, ...rest } = a;
const spec = previousSpec.build() as BuilderExtract<A["spec"]>;
@@ -139,11 +139,11 @@ export class Value<A extends ValueSpec> extends IBuilder<A> {
[key: string]: string;
};
};
variants: Variants<{ [key: string]: ConfigSpec }>;
variants: Variants<{ [key: string]: InputSpec }>;
"display-as": string | null;
"unique-by": UniqueBy;
},
B extends string
B extends string,
>(a: A) {
const { variants: previousVariants, ...rest } = a;
const variants = previousVariants.build() as BuilderExtract<A["variants"]>;

View File

@@ -1,4 +1,4 @@
import { ConfigSpec } from "../../types/config-types";
import { InputSpec } from "../../types/config-types";
import { BuilderExtract, IBuilder } from "./builder";
import { Config } from ".";
@@ -39,12 +39,12 @@ import { Config } from ".";
```
*/
export class Variants<
A extends { [key: string]: ConfigSpec }
A extends { [key: string]: InputSpec },
> extends IBuilder<A> {
static of<
A extends {
[key: string]: Config<ConfigSpec>;
}
[key: string]: Config<InputSpec>;
},
>(a: A) {
const variants: { [K in keyof A]: BuilderExtract<A[K]> } = {} as any;
for (const key in a) {
@@ -56,17 +56,14 @@ export class Variants<
static empty() {
return Variants.of({});
}
static withVariant<K extends string, B extends ConfigSpec>(
static withVariant<K extends string, B extends InputSpec>(
key: K,
value: Config<B>
value: Config<B>,
) {
return Variants.empty().withVariant(key, value);
}
withVariant<K extends string, B extends ConfigSpec>(
key: K,
value: Config<B>
) {
withVariant<K extends string, B extends InputSpec>(key: K, value: Config<B>) {
return new Variants({
...this.a,
[key]: value.build(),

View File

@@ -1,7 +1,7 @@
import { Config } from "./builder";
import { DeepPartial, DependsOn, Effects, ExpectedExports } from "../types";
import { ConfigSpec } from "../types/config-types";
import { nullIfEmpty, okOf } from "../util";
import { InputSpec } from "../types/config-types";
import { nullIfEmpty } from "../util";
import { TypeFromProps } from "../util/propertiesMatcher";
/**
@@ -11,7 +11,7 @@ import { TypeFromProps } from "../util/propertiesMatcher";
* @param options
* @returns
*/
export function setupConfigExports<A extends ConfigSpec>(options: {
export function setupConfigExports<A extends InputSpec>(options: {
spec: Config<A>;
dependsOn: DependsOn;
write(effects: Effects, config: TypeFromProps<A>): Promise<void>;
@@ -25,16 +25,16 @@ export function setupConfigExports<A extends ConfigSpec>(options: {
return { error: "Set config type error for config" };
}
await options.write(effects, config);
return okOf({
return {
signal: "SIGTERM",
"depends-on": options.dependsOn,
});
};
}) as ExpectedExports.setConfig,
getConfig: (async ({ effects }) => {
return okOf({
return {
spec: options.spec.build(),
config: nullIfEmpty(await options.read(effects)),
});
};
}) as ExpectedExports.getConfig,
};
}

View File

@@ -1,4 +1,4 @@
import { Effects, ResultType } from "../types";
import { Effects } from "../types";
import { isKnownError } from "../util";
import { HealthResult } from "./healthRunner";
@@ -10,10 +10,10 @@ import { HealthResult } from "./healthRunner";
*/
export const checkWebUrl: (
url: string,
createSuccess?: null | ((response?: string | null) => string)
createSuccess?: null | ((response?: string | null) => string),
) => (effects: Effects, duration: number) => Promise<HealthResult> = (
url,
createSuccess = null
createSuccess = null,
) => {
return async (effects, duration) => {
const errorValue = guardDurationAboveMinimum({
@@ -55,22 +55,12 @@ export const runHealthScript =
args: string[];
message: ((result: unknown) => string) | null;
}) =>
async (
effects: Effects,
_duration: number
): Promise<ResultType<HealthResult>> => {
async (effects: Effects, _duration: number): Promise<HealthResult> => {
const res = await effects.runCommand({ command, args });
if ("result" in res) {
return {
result: {
success:
message?.(res) ??
`Have ran script ${command} and the result: ${res.result}`,
},
};
} else {
throw res;
}
return {
success:
message?.(res) ?? `Have ran script ${command} and the result: ${res}`,
};
};
// Ensure the starting duration is pass a minimum

View File

@@ -4,16 +4,16 @@ import * as fs from "fs";
export async function writeConvertedFile(
file: string,
inputData: Promise<any> | any,
options: Parameters<typeof makeFileContent>[1]
options: Parameters<typeof makeFileContent>[1],
) {
await fs.writeFile(file, await makeFileContent(inputData, options), (err) =>
console.error(err)
console.error(err),
);
}
export default async function makeFileContent(
inputData: Promise<any> | any,
{ startSdk = "start-sdk" } = {}
{ startSdk = "start-sdk" } = {},
) {
const outputLines: string[] = [];
outputLines.push(`
@@ -22,13 +22,13 @@ export default async function makeFileContent(
const data = await inputData;
const namedConsts = new Set(["Config", "Value", "List"]);
const configName = newConst("configSpec", convertConfigSpec(data));
const configName = newConst("InputSpec", convertInputSpec(data));
const configMatcherName = newConst(
"matchConfigSpec",
`${configName}.validator()`
"matchInputSpec",
`${configName}.validator()`,
);
outputLines.push(
`export type ConfigSpec = typeof ${configMatcherName}._TYPE;`
`export type InputSpec = typeof ${configMatcherName}._TYPE;`,
);
return outputLines.join("\n");
@@ -38,7 +38,7 @@ export default async function makeFileContent(
outputLines.push(`export const ${variableName} = ${data};`);
return variableName;
}
function convertConfigSpec(data: any) {
function convertInputSpec(data: any) {
let answer = "Config.of({";
for (const [key, value] of Object.entries(data)) {
const variableName = newConst(key, convertValueSpec(value));
@@ -64,7 +64,7 @@ export default async function makeFileContent(
textarea: value.textarea || null,
},
null,
2
2,
)})`;
}
case "number": {
@@ -81,7 +81,7 @@ export default async function makeFileContent(
placeholder: value.placeholder || null,
},
null,
2
2,
)})`;
}
case "boolean": {
@@ -93,7 +93,7 @@ export default async function makeFileContent(
warning: value.warning || null,
},
null,
2
2,
)})`;
}
case "enum": {
@@ -107,13 +107,13 @@ export default async function makeFileContent(
"value-names": value["value-names"] || null,
},
null,
2
2,
)})`;
}
case "object": {
const specName = newConst(
value.name + "_spec",
convertConfigSpec(value.spec)
convertInputSpec(value.spec),
);
return `Value.object({
name: ${JSON.stringify(value.name || null)},
@@ -129,7 +129,7 @@ export default async function makeFileContent(
case "union": {
const variants = newConst(
value.name + "_variants",
convertVariants(value.variants)
convertVariants(value.variants),
);
return `Value.union({
name: ${JSON.stringify(value.name || null)},
@@ -147,7 +147,7 @@ export default async function makeFileContent(
"display-as": ${JSON.stringify(value["display-as"] || null)},
"unique-by": ${JSON.stringify(value["unique-by"] || null)},
"variant-names": ${JSON.stringify(
(value["variant-names"] as any) || null
(value["variant-names"] as any) || null,
)},
})`;
}
@@ -182,7 +182,7 @@ export default async function makeFileContent(
warning: value.warning || null,
},
null,
2
2,
)})`;
}
case "number": {
@@ -201,7 +201,7 @@ export default async function makeFileContent(
warning: value.warning || null,
},
null,
2
2,
)})`;
}
case "enum": {
@@ -218,13 +218,13 @@ export default async function makeFileContent(
warning: value.warning || null,
},
null,
2
2,
)})`;
}
case "object": {
const specName = newConst(
value.name + "_spec",
convertConfigSpec(value.spec.spec)
convertInputSpec(value.spec.spec),
);
return `List.obj({
name: ${JSON.stringify(value.name || null)},
@@ -232,7 +232,7 @@ export default async function makeFileContent(
spec: {
spec: ${specName},
"display-as": ${JSON.stringify(
value?.spec?.["display-as"] || null
value?.spec?.["display-as"] || null,
)},
"unique-by": ${JSON.stringify(value?.spec?.["unique-by"] || null)},
},
@@ -244,7 +244,7 @@ export default async function makeFileContent(
case "union": {
const variants = newConst(
value.name + "_variants",
convertConfigSpec(value.spec.variants)
convertInputSpec(value.spec.variants),
);
return `List.union(
{
@@ -254,24 +254,24 @@ export default async function makeFileContent(
tag: {
"id":${JSON.stringify(value?.spec?.tag?.["id"] || null)},
"name": ${JSON.stringify(
value?.spec?.tag?.["name"] || null
value?.spec?.tag?.["name"] || null,
)},
"description": ${JSON.stringify(
value?.spec?.tag?.["description"] || null
value?.spec?.tag?.["description"] || null,
)},
"warning": ${JSON.stringify(
value?.spec?.tag?.["warning"] || null
value?.spec?.tag?.["warning"] || null,
)},
"variant-names": ${JSON.stringify(
value?.spec?.tag?.["variant-names"] || {}
value?.spec?.tag?.["variant-names"] || {},
)},
},
variants: ${variants},
"display-as": ${JSON.stringify(
value?.spec?.["display-as"] || null
value?.spec?.["display-as"] || null,
)},
"unique-by": ${JSON.stringify(
value?.spec?.["unique-by"] || null
value?.spec?.["unique-by"] || null,
)},
default: ${JSON.stringify(value?.spec?.["default"] || null)},
},
@@ -288,7 +288,7 @@ export default async function makeFileContent(
function convertVariants(variants: any) {
let answer = "Variants.of({";
for (const [key, value] of Object.entries(variants)) {
const variableName = newConst(key, convertConfigSpec(value));
const variableName = newConst(key, convertInputSpec(value));
answer += `"${key}": ${variableName},`;
}
return `${answer}})`;

View File

@@ -1,5 +1,5 @@
export * as configTypes from "./types/config-types";
import { ConfigSpec } from "./types/config-types";
import { InputSpec } from "./types/config-types";
export namespace ExpectedExports {
version: 1;
@@ -7,25 +7,26 @@ export namespace ExpectedExports {
export type setConfig = (options: {
effects: Effects;
input: Record<string, unknown>;
}) => Promise<ResultType<SetResult>>;
}) => Promise<unknown>;
/** Get configuration returns a shape that describes the format that the embassy ui will generate, and later send to the set config */
export type getConfig = (options: {
effects: Effects;
}) => Promise<ResultType<ConfigRes>>;
config: unknown;
}) => Promise<ConfigRes>;
/** These are how we make sure the our dependency configurations are valid and if not how to fix them. */
export type dependencies = Dependencies;
/** For backing up service data though the embassyOS UI */
export type createBackup = (options: {
effects: Effects;
}) => Promise<ResultType<unknown>>;
}) => Promise<unknown>;
/** For restoring service data that was previously backed up using the embassyOS UI create backup flow. Backup restores are also triggered via the embassyOS UI, or doing a system restore flow during setup. */
export type restoreBackup = (options: {
effects: Effects;
}) => Promise<ResultType<unknown>>;
}) => Promise<unknown>;
/** Properties are used to get values from the docker, like a username + password, what ports we are hosting from */
export type properties = (options: {
effects: Effects;
}) => Promise<ResultType<Properties>>;
}) => Promise<Properties>;
/** Health checks are used to determine if the service is working properly after starting
* A good use case is if we are using a web server, seeing if we can get to the web server.
@@ -35,7 +36,7 @@ export namespace ExpectedExports {
[id: string]: (options: {
effects: Effects;
input: TimeMs;
}) => Promise<ResultType<unknown>>;
}) => Promise<unknown>;
};
/**
@@ -47,7 +48,7 @@ export namespace ExpectedExports {
[id: string]: (options: {
effects: Effects;
input?: Record<string, unknown>;
}) => Promise<ResultType<ActionResult>>;
}) => Promise<ActionResult>;
};
/**
@@ -56,8 +57,8 @@ export namespace ExpectedExports {
*/
export type main = (options: {
effects: Effects;
started(): null;
}) => Promise<ResultType<unknown>>;
started(onTerm: () => void): null;
}) => Promise<unknown>;
/**
* Every time a package completes an install, this function is called before the main.
@@ -66,14 +67,14 @@ export namespace ExpectedExports {
export type init = (options: {
effects: Effects;
previousVersion: null | string;
}) => Promise<ResultType<unknown>>;
}) => Promise<unknown>;
/** This will be ran during any time a package is uninstalled, for example during a update
* this will be called.
*/
export type uninit = (options: {
effects: Effects;
nextVersion: null | string;
}) => Promise<ResultType<unknown>>;
}) => Promise<unknown>;
}
export type TimeMs = number;
export type VersionString = string;
@@ -82,7 +83,7 @@ export type ConfigRes = {
/** This should be the previous config, that way during set config we start with the previous */
config?: null | Record<string, unknown>;
/** Shape that is describing the form in the ui */
spec: ConfigSpec;
spec: InputSpec;
};
/** Used to reach out from the pure js runtime */
export type Effects = {
@@ -119,9 +120,9 @@ export type Effects = {
command: string;
args?: string[];
timeoutMillis?: number;
}): Promise<ResultType<string>>;
}): Promise<string>;
runDaemon(input: { command: string; args?: string[] }): {
wait(): Promise<ResultType<string>>;
wait(): Promise<string>;
term(): Promise<void>;
};
@@ -170,7 +171,7 @@ export type Effects = {
method?: "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "PATCH";
headers?: Record<string, string>;
body?: string;
}
},
): Promise<{
method: string;
ok: boolean;
@@ -200,6 +201,12 @@ export type Effects = {
progress: () => Promise<number>;
};
getServiceConfig(options?: {
packageId?: string;
path?: string;
callback?: (config: unknown, previousConfig: unknown) => void;
}): Promise<unknown>;
/** Get the address for another service for local internet*/
getServiceLocalAddress(options: {
packageId: string;
@@ -249,7 +256,7 @@ export type Effects = {
name: string;
description: string;
id: string;
input: null | ConfigSpec;
input: null | InputSpec;
}): Promise<void>;
/**
* Remove an action that was exported. Used problably during main or during setConfig.
@@ -349,7 +356,6 @@ export type KnownError =
| {
"error-code": [number, string] | readonly [number, string];
};
export type ResultType<T> = KnownError | { result: T };
export type PackagePropertiesV2 = {
[name: string]: PackagePropertyObject | PackagePropertyString;
@@ -380,15 +386,9 @@ export type Dependencies = {
/** Id is the id of the package, should be the same as the manifest */
[id: string]: {
/** Checks are called to make sure that our dependency is in the correct shape. If a known error is returned we know that the dependency needs modification */
check(
effects: Effects,
input: ConfigSpec
): Promise<ResultType<void | null>>;
check(effects: Effects, input: InputSpec): Promise<void | null>;
/** This is called after we know that the dependency package needs a new configuration, this would be a transform for defaults */
autoConfigure(
effects: Effects,
input: ConfigSpec
): Promise<ResultType<ConfigSpec>>;
autoConfigure(effects: Effects, input: InputSpec): Promise<InputSpec>;
};
};

View File

@@ -1,4 +1,4 @@
export type ConfigSpec = Record<string, ValueSpec>;
export type InputSpec = Record<string, ValueSpec>;
export type ValueType =
| "string"
@@ -53,13 +53,13 @@ export interface ValueSpecBoolean extends WithStandalone {
export interface ValueSpecUnion {
type: "union";
tag: UnionTagSpec;
variants: { [key: string]: ConfigSpec };
variants: { [key: string]: InputSpec };
default: string;
}
export interface ValueSpecObject extends WithStandalone {
type: "object";
spec: ConfigSpec;
spec: InputSpec;
}
export interface WithStandalone {
@@ -111,7 +111,7 @@ export interface ValueSpecListOf<T extends ListValueSpecType>
// sometimes the type checker needs just a little bit of help
export function isValueSpecListOf<S extends ListValueSpecType>(
t: ValueSpecList,
s: S
s: S,
): t is ValueSpecListOf<S> {
return t.subtype === s;
}
@@ -136,7 +136,7 @@ export interface ListValueSpecEnum {
}
export interface ListValueSpecObject {
spec: ConfigSpec; // this is a mapped type of the config object at this level, replacing the object's values with specs on those values
spec: InputSpec; // this is a mapped type of the config object at this level, replacing the object's values with specs on those values
"unique-by": UniqueBy; // indicates whether duplicates can be permitted in the list
"display-as": null | string; // this should be a handlebars template which can make use of the entire config which corresponds to 'spec'
}
@@ -150,7 +150,7 @@ export type UniqueBy =
export interface ListValueSpecUnion {
tag: UnionTagSpec;
variants: { [key: string]: ConfigSpec };
variants: { [key: string]: InputSpec };
"display-as": null | string; // this may be a handlebars template which can conditionally (on tag.id) make use of each union's entries, or if left blank will display as tag.id
"unique-by": UniqueBy;
default: string; // this should be the variantName which one prefers a user to start with by default when creating a new union instance in a list

View File

@@ -6,6 +6,7 @@ export const enable = Value.boolean({
description: "Allow remote RPC requests.",
warning: null,
});
export const username = Value.string({
name: "Username",
default: "bitcoin",
@@ -438,12 +439,12 @@ export const advanced1 = Value.object({
spec: advancedSpec1,
"value-names": {},
});
export const configSpec = Config.of({
export const InputSpec = Config.of({
rpc: rpc,
"zmq-enabled": zmqEnabled,
txindex: txindex,
wallet: wallet,
advanced: advanced1,
});
export const matchConfigSpec = configSpec.validator();
export type ConfigSpec = typeof matchConfigSpec._TYPE;
export const matchInputSpec = InputSpec.validator();
export type InputSpec = typeof matchInputSpec._TYPE;

View File

@@ -12,7 +12,7 @@ const previousPath = /(.+?)\/([^/]*)$/;
* to keep the same path on the read and write, and have methods for helping with structured data.
* And if we are not using a structured data, we can use the raw method which forces the construction of a BiMap
* ```ts
import {configSpec} from './configSpec.ts'
import {InputSpec} from './InputSpec.ts'
import {matches, T} from '../deps.ts';
const { object, string, number, boolean, arrayOf, array, anyOf, allOf } = matches
const someValidator = object({
@@ -45,7 +45,7 @@ const previousPath = /(.+?)\/([^/]*)$/;
}
export const getConfig: T.ExpectedExports.getConfig = async (effects, config) => ({
spec: configSpec,
spec: InputSpec,
config: nullIfEmpty({
...jsonFile.get(effects)
})
@@ -56,7 +56,7 @@ export class FileHelper<A> {
readonly path: string,
readonly volume: string,
readonly writeData: (dataIn: A) => string,
readonly readData: (stringValue: string) => A
readonly readData: (stringValue: string) => A,
) {}
async write(data: A, effects: T.Effects) {
let matched;
@@ -86,21 +86,21 @@ export class FileHelper<A> {
await effects.readFile({
path: this.path,
volumeId: this.volume,
})
}),
);
}
static raw<A>(
path: string,
volume: string,
toFile: (dataIn: A) => string,
fromFile: (rawData: string) => A
fromFile: (rawData: string) => A,
) {
return new FileHelper<A>(path, volume, toFile, fromFile);
}
static json<A>(
path: string,
volume: string,
shape: matches.Validator<unknown, A>
shape: matches.Validator<unknown, A>,
) {
return new FileHelper<A>(
path,
@@ -110,13 +110,13 @@ export class FileHelper<A> {
},
(inString) => {
return shape.unsafeCast(JSON.parse(inString));
}
},
);
}
static toml<A extends Record<string, unknown>>(
path: string,
volume: string,
shape: matches.Validator<unknown, A>
shape: matches.Validator<unknown, A>,
) {
return new FileHelper<A>(
path,
@@ -126,13 +126,13 @@ export class FileHelper<A> {
},
(inString) => {
return shape.unsafeCast(TOML.parse(inString));
}
},
);
}
static yaml<A extends Record<string, unknown>>(
path: string,
volume: string,
shape: matches.Validator<unknown, A>
shape: matches.Validator<unknown, A>,
) {
return new FileHelper<A>(
path,
@@ -142,7 +142,7 @@ export class FileHelper<A> {
},
(inString) => {
return shape.unsafeCast(YAML.parse(inString));
}
},
);
}
}

View File

@@ -4,34 +4,15 @@ export { guardAll, typeFromProps } from "./propertiesMatcher";
export { default as nullIfEmpty } from "./nullIfEmpty";
export { FileHelper } from "./fileHelper";
export function unwrapResultType<T>(res: T.ResultType<T>): T {
if ("error-code" in res) {
throw new Error(res["error-code"][1]);
} else if ("error" in res) {
throw new Error(res["error"]);
} else {
return res.result;
}
}
/** Used to check if the file exists before hand */
export const exists = (
effects: T.Effects,
props: { path: string; volumeId: string }
props: { path: string; volumeId: string },
) =>
effects.metadata(props).then(
(_) => true,
(_) => false
(_) => false,
);
export const errorCode = (code: number, error: string) => ({
"error-code": [code, error] as const,
});
export const error = (error: string) => ({ error });
export const okOf = <A>(result: A) => ({
result,
});
export const ok = { result: null };
export const isKnownError = (e: unknown): e is T.KnownError =>
e instanceof Object && ("error" in e || "error-code" in e);

View File

@@ -4,7 +4,7 @@ describe("Properties Matcher", () => {
// import * as PM from "./propertiesMatcher";
// import { expect } from "https://deno.land/x/expect@v0.2.9/mod";
// import * as matches from "ts-matches";
// import { configSpec as bitcoinPropertiesConfig } from "./test/output";
// import { InputSpec as bitcoinPropertiesConfig } from "./test/output";
// const randWithSeed = (seed = 1) => {
// return function random() {

View File

@@ -1,5 +1,5 @@
import * as matches from "ts-matches";
import { ConfigSpec, ValueSpec as ValueSpecAny } from "../types/config-types";
import { InputSpec, ValueSpec as ValueSpecAny } from "../types/config-types";
type TypeBoolean = "boolean";
type TypeString = "string";
@@ -107,7 +107,7 @@ function charRange(value = "") {
*/
export function generateDefault(
generate: { charset: string; len: number },
{ random = () => Math.random() } = {}
{ random = () => Math.random() } = {},
) {
const validCharSets: number[][] = generate.charset
.split(",")
@@ -118,7 +118,7 @@ export function generateDefault(
}
const max = validCharSets.reduce(
(acc, x) => x.reduce((x, y) => Math.max(x, y), acc),
0
0,
);
let i = 0;
const answer: string[] = Array(generate.len);
@@ -127,7 +127,7 @@ export function generateDefault(
const inRange = validCharSets.reduce(
(acc, [lower, upper]) =>
acc || (nextValue >= lower && nextValue <= upper),
false
false,
);
if (!inRange) continue;
answer[i] = String.fromCharCode(nextValue);
@@ -155,7 +155,7 @@ export function matchNumberWithRange(range: string) {
? "any"
: left === "["
? `greaterThanOrEqualTo${leftValue}`
: `greaterThan${leftValue}`
: `greaterThan${leftValue}`,
)
.validate(
// prettier-ignore
@@ -165,7 +165,7 @@ export function matchNumberWithRange(range: string) {
// prettier-ignore
rightValue === "*" ? "any" :
right === "]" ? `lessThanOrEqualTo${rightValue}` :
`lessThan${rightValue}`
`lessThan${rightValue}`,
);
}
function withIntegral(parser: matches.Parser<unknown, number>, value: unknown) {
@@ -186,12 +186,12 @@ const isGenerator = matches.shape({
}).test;
function defaultNullable<A>(
parser: matches.Parser<unknown, A>,
value: unknown
value: unknown,
) {
if (matchDefault.test(value)) {
if (isGenerator(value.default)) {
return parser.defaultTo(
parser.unsafeCast(generateDefault(value.default))
parser.unsafeCast(generateDefault(value.default)),
);
}
return parser.defaultTo(value.default);
@@ -201,7 +201,7 @@ function defaultNullable<A>(
}
/**
* ConfigSpec: Tells the UI how to ask for information, verification, and will send the service a config in a shape via the spec.
* InputSpec: Tells the UI how to ask for information, verification, and will send the service a config in a shape via the spec.
* ValueSpecAny: This is any of the values in a config spec.
*
* Use this when we want to convert a value spec any into a parser for what a config will look like
@@ -209,7 +209,7 @@ function defaultNullable<A>(
* @returns
*/
export function guardAll<A extends ValueSpecAny>(
value: A
value: A,
): matches.Parser<unknown, GuardAll<A>> {
if (!isType.test(value)) {
return matches.unknown as any;
@@ -224,7 +224,7 @@ export function guardAll<A extends ValueSpecAny>(
case "number":
return defaultNullable(
withIntegral(withRange(value), value),
value
value,
) as any;
case "object":
@@ -244,14 +244,14 @@ export function guardAll<A extends ValueSpecAny>(
matches
.arrayOf(guardAll({ type: subtype, ...spec } as any))
.validate((x) => rangeValidate(x.length), "valid length"),
value
value,
) as any;
}
case "enum":
if (matchValues.test(value)) {
return defaultNullable(
matches.literals(value.values[0], ...value.values),
value
value,
) as any;
}
return matches.unknown as any;
@@ -261,8 +261,8 @@ export function guardAll<A extends ValueSpecAny>(
...Object.entries(value.variants).map(([variant, spec]) =>
matches
.shape({ [value.tag.id]: matches.literal(variant) })
.concat(typeFromProps(spec))
)
.concat(typeFromProps(spec)),
),
) as any;
}
return matches.unknown as any;
@@ -271,15 +271,15 @@ export function guardAll<A extends ValueSpecAny>(
return matches.unknown as any;
}
/**
* ConfigSpec: Tells the UI how to ask for information, verification, and will send the service a config in a shape via the spec.
* InputSpec: Tells the UI how to ask for information, verification, and will send the service a config in a shape via the spec.
* ValueSpecAny: This is any of the values in a config spec.
*
* Use this when we want to convert a config spec into a parser for what a config will look like
* @param valueDictionary
* @returns
*/
export function typeFromProps<A extends ConfigSpec>(
valueDictionary: A
export function typeFromProps<A extends InputSpec>(
valueDictionary: A,
): matches.Parser<unknown, TypeFromProps<A>> {
if (!recordString.test(valueDictionary)) return matches.unknown as any;
return matches.shape(
@@ -287,7 +287,7 @@ export function typeFromProps<A extends ConfigSpec>(
Object.entries(valueDictionary).map(([key, value]) => [
key,
guardAll(value),
])
)
]),
),
) as any;
}

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "start-sdk",
"version": "0.4.0-lib0.alpha4",
"version": "0.4.0-lib0.alpha5",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "start-sdk",
"version": "0.4.0-lib0.alpha4",
"version": "0.4.0-lib0.alpha5",
"license": "MIT",
"dependencies": {
"@iarna/toml": "^2.2.5",

View File

@@ -1,13 +1,14 @@
{
"name": "start-sdk",
"version": "0.4.0-lib0.alpha5",
"version": "0.4.0-lib0.alpha6",
"description": "For making the patterns that are wanted in making services for the startOS.",
"main": "./index.cjs",
"types": "./index.d.ts",
"module": "./index.mjs",
"scripts": {
"test": "jest -c ./jest.config.js",
"buildOutput": "ts-node --esm ./lib/util/artifacts/makeOutput.ts"
"buildOutput": "ts-node --esm ./lib/util/artifacts/makeOutput.ts",
"check": "tsc --noEmit"
},
"repository": {
"type": "git",