Skip to content

Commit

Permalink
Auto configuration works
Browse files Browse the repository at this point in the history
  • Loading branch information
julienmalard committed Nov 10, 2024
1 parent 280a158 commit 600e549
Show file tree
Hide file tree
Showing 5 changed files with 121 additions and 17 deletions.
86 changes: 79 additions & 7 deletions src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import {
} from "@constl/ipa";

import { createOrbiter } from "@/orbiter.js";
import { configIsComplete, exportConfig, getConfig } from "@/config.js";
import { ConfigMode } from "./types.js";

const MACHINE_PREFIX = "MACHINE MESSAGE:";

const baseDir = url.fileURLToPath(new URL("..", import.meta.url));
Expand Down Expand Up @@ -75,6 +78,76 @@ const followConnections = async ({ ipa }: { ipa: Constellation }) => {

yargs(hideBin(process.argv))
.usage("Usage: $0 <command> [options]")
.command(["config [--dir <dir>]"],
"Configure Orbiter",
(yargs) => {
return yargs
.option("dir", {
alias: "d",
describe: "The directory of the Orbiter node.",
type: "string",
});
},
async (argv) => {
const wheel = ora(chalk.yellow(`Creating config`));
wheel.start(chalk.yellow("Configuring Orbiter..."));
const constellation = créerConstellation({
dossier: argv.dir || ".orbiter",
});

await createOrbiter({
constellation,
});
await constellation.fermer();
wheel?.succeed(chalk.yellow("Orbiter configured. Use `orbiter export-config` to export for use in static deployments."))
process.exit(0);
}
)
.command(["export-config [--format <format>]"],
"Export Orbiter config for use in UIs, etc.",
(yargs) => {
return yargs
.option("dir", {
alias: "d",
describe: "The directory of the Orbiter node.",
type: "string",
default: ".orbiter",
})
.option("format", {
alias: "f",
describe: "The configuration format to output ('vite' available for now).",
type: "string",
default: 'vite'
})
.option("out", {
alias: "o",
describe: "The output env file in which to store the exported configuration.",
type: "string",
});
},
async (argv) => {
const wheel = ora();
wheel.start(chalk.yellow("Obtaining Orbiter config..."));

const outputFile = argv.out || (argv.format === 'json' ? 'config.json': '.env')

const config = await getConfig({
dir: argv.dir
})
if (configIsComplete(config)) {
wheel.info(chalk.yellow("Exporting Orbiter config..."));

const exportedConfig = exportConfig({
config,
mode: (argv.format as ConfigMode) || 'vite',
})
fs.writeFileSync(outputFile, exportedConfig);
wheel.succeed(chalk.yellow(`Configuration exported to ${path.resolve(outputFile)}.`))
} else {
wheel.fail(chalk.red("Orbiter is not properly configured. Run `orbiter config` first."))
}
}
)
.command(
["run [-m] [--dir <dir>]"],
"Start orbiter",
Expand All @@ -84,6 +157,7 @@ yargs(hideBin(process.argv))
alias: "d",
describe: "The directory of the Orbiter node.",
type: "string",
default: ".orbiter",
})
.option("machine", {
alias: "m",
Expand All @@ -94,7 +168,7 @@ yargs(hideBin(process.argv))
},
async (argv) => {
let wheel: Ora | undefined = undefined;
let oublierConnexions: types.schémaFonctionOublier | undefined =
let forgetConnections: types.schémaFonctionOublier | undefined =
undefined;

if (argv.machine) {
Expand All @@ -104,23 +178,21 @@ yargs(hideBin(process.argv))
}

const constellation = créerConstellation({
dossier: argv.dir || ".orbiter",
dossier: argv.dir,
});

const { config } = await createOrbiter({
await createOrbiter({
constellation,
});

console.log(config);

process.stdin.on("data", async () => {
if (argv.machine) {
sendMachineMessage({ message: { type: "Closing Orbiter" } });
} else {
wheel?.start(chalk.yellow("Closing Orbiter..."));
}
try {
await oublierConnexions?.();
await forgetConnections?.();
await constellation.fermer();
} finally {
if (argv.machine) {
Expand All @@ -139,7 +211,7 @@ yargs(hideBin(process.argv))
wheel!.succeed(
chalk.yellow("Orbiter is running. Press `enter` to close."),
);
oublierConnexions = await followConnections({ ipa: constellation });
forgetConnections = await followConnections({ ipa: constellation });
}
},
)
Expand Down
24 changes: 20 additions & 4 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import {
ConfigMode,
VariableIds,
orbiterConfigSchema,
possiblyIncompleteOrbiterConfigSchema,
type OrbiterConfig,
type PossiblyIncompleteOrbiterConfig,
} from "./types";
} from "./types.js";

import {constantCase} from 'change-case';
import {
Expand All @@ -13,12 +14,18 @@ import {
isReactNative,
isWebWorker,
} from "wherearewe";
import Ajv from "ajv/dist/jtd";
import Ajv from "ajv/dist/jtd.js";

import { CONFIG_FILE_NAME } from "./consts.js";

const ajv = new Ajv();
const validateConfig = ajv.compile(possiblyIncompleteOrbiterConfigSchema);
const validateCompleteConfig = ajv.compile(orbiterConfigSchema)

export const configIsComplete = (config: unknown): config is OrbiterConfig => {
if (validateCompleteConfig(config)) return true;
return false;
};

export const getConfig = async ({
dir,
Expand Down Expand Up @@ -52,7 +59,7 @@ export const getConfig = async ({
export const saveConfig = async ({
dir,
config,
mode = "vite",
mode,
}: {
dir: string;
config: OrbiterConfig;
Expand All @@ -72,12 +79,13 @@ export const saveConfig = async ({

export const exportConfig = ({
config,
mode = "vite",
mode,
}: {
config: OrbiterConfig;
mode: ConfigMode;
}): string => {
if (mode === "vite") return exportViteConfig({ config });
else if (mode === 'json') return exportJsonConfig({ config });
else throw new Error(`Unknown exportation mode ${mode}.`);
};

Expand All @@ -104,3 +112,11 @@ export const exportViteConfig = ({
;
return envFileText;
};

export const exportJsonConfig = ({
config,
}: {
config: OrbiterConfig;
}): string => {
return JSON.stringify(config, undefined, 2);
}
9 changes: 6 additions & 3 deletions src/orbiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ import type {
} from "./types.js";
import { variableIdKeys } from "./types.js";
import { removeUndefined } from "./utils.js";
import { getConfig } from "./config.js";
import { exportConfig, getConfig, saveConfig } from "./config.js";

type forgetFunction = () => Promise<void>;

Expand Down Expand Up @@ -1766,12 +1766,15 @@ export const createOrbiter = async ({
}: {
constellation: Constellation;
}) => {
const dir = await constellation.dossier()
const existingConfig = getConfig({
dir: await constellation.dossier(),
dir,
});

const orbiter = new Orbiter({ constellation, ...existingConfig });
const config = await orbiter.setUpSite();
if (!isEqual(existingConfig, config)) saveConfig(config);
if (!isEqual(existingConfig, config)) {
saveConfig({dir, config, mode: 'json'})
};
return { config, orbiter };
};
17 changes: 15 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type JTDSchemaType } from "ajv/dist/jtd";
import { type JTDSchemaType } from "ajv/dist/jtd.js";

import type {
BLOCKED_RELEASES_RELEASE_ID_COLUMN,
Expand Down Expand Up @@ -81,7 +81,20 @@ export const possiblyIncompleteOrbiterConfigSchema: JTDSchemaType<PossiblyIncomp
},
},
};
export type ConfigMode = "vite"; // Todo: add for other compilers?
export const orbiterConfigSchema: JTDSchemaType<OrbiterConfig> =
{
properties: {
siteId: { type: "string" },
swarmId: { type: "string" },
variableIds: {
properties: Object.fromEntries(
variableIdKeys.map((v) => [v, { type: "string" }]),
) as { [P in keyof VariableIds]: { type: "string" } },
},
},
};

export type ConfigMode = "vite" | "json"; // Todo: add for other compilers?

export type Release = {
[RELEASES_NAME_COLUMN]: string;
Expand Down
2 changes: 1 addition & 1 deletion src/version.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
// Generated by genversion.
export const version = "0.0.3";
export const version = '0.0.3';

0 comments on commit 600e549

Please sign in to comment.