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

@@ -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;
}