@typegraph/sdk
Advanced tools
Comparing version 0.4.2 to 0.4.3
export { caller } from "./_import.js"; | ||
export declare function mapValues(object: Object, fn: (value: any, key: string, object: Object) => any): any; | ||
export declare function mapValues(object: object, fn: (value: any, key: string, object: object) => any): any; | ||
export declare function dirname(path: string): string; | ||
export declare function fromFileUrl(path: string): string; |
@@ -19,4 +19,4 @@ // Copyright Metatype OÜ, licensed under the Mozilla Public License Version 2.0. | ||
// Examples: file://C:, file://D: | ||
const isWin32 = /^file:\/\/\w\:/.test(path); | ||
const isWin32 = /^file:\/\/\w:/.test(path); | ||
return isWin32 ? fromFileUrlWin32(path) : fromFileUrlPosix(path); | ||
} |
export namespace MetatypeTypegraphCore { | ||
export function initTypegraph(params: TypegraphInitParams): void; | ||
export function finalizeTypegraph(config: ArtifactResolutionConfig | undefined): [string, Artifact[]]; | ||
export function serializeTypegraph(params: SerializeParams): [string, Artifact[]]; | ||
export function withInjection(typeId: TypeId, injection: string): TypeId; | ||
@@ -61,16 +61,18 @@ export function refb(name: string, attributes: [string, string][]): TypeId; | ||
export interface MigrationAction { | ||
apply: boolean, | ||
create: boolean, | ||
reset: boolean, | ||
} | ||
export interface MigrationConfig { | ||
migrationDir: string, | ||
globalAction: MigrationAction, | ||
runtimeActions?: [string, MigrationAction][], | ||
export interface PrismaMigrationConfig { | ||
migrationsDir: string, | ||
migrationActions: [string, MigrationAction][], | ||
defaultMigrationAction: MigrationAction, | ||
} | ||
export interface ArtifactResolutionConfig { | ||
dir?: string, | ||
export interface SerializeParams { | ||
typegraphPath: string, | ||
prefix?: string, | ||
disableArtifactResolution?: boolean, | ||
prismaMigration: MigrationConfig, | ||
codegen?: boolean, | ||
artifactResolution: boolean, | ||
codegen: boolean, | ||
prismaMigration: PrismaMigrationConfig, | ||
pretty: boolean, | ||
} | ||
@@ -77,0 +79,0 @@ export type TypeId = number; |
export namespace MetatypeTypegraphHost { | ||
export function eprint(s: string): void; | ||
export function print(s: string): void; | ||
export function expandPath(root: string, exclude: string[]): string[]; | ||
@@ -7,3 +7,2 @@ export function pathExists(path: string): boolean; | ||
export function writeFile(path: string, data: Uint8Array): void; | ||
export function getCwd(): string; | ||
} |
@@ -12,5 +12,5 @@ export namespace MetatypeTypegraphUtils { | ||
export function gqlRemoveQuery(tgName: string[]): string; | ||
export function unpackTarb64(tarB64: string, dest: string): void; | ||
export function removeInjections(typeId: TypeId): TypeId; | ||
export function getCwd(): string; | ||
export function metagenExec(config: MdkConfig): MdkOutput[]; | ||
export function metagenWriteFiles(items: MdkOutput[], typegraphDir: string): void; | ||
} | ||
@@ -50,1 +50,12 @@ import type { Error } from './metatype-typegraph-core.js'; | ||
} | ||
export interface MdkConfig { | ||
workspacePath: string, | ||
targetName: string, | ||
configJson: string, | ||
tgJson: string, | ||
} | ||
export interface MdkOutput { | ||
path: string, | ||
content: string, | ||
overwrite: boolean, | ||
} |
{ | ||
"name": "@typegraph/sdk", | ||
"version": "0.4.2", | ||
"version": "0.4.3", | ||
"description": "Declarative API development platform. Build backend components with WASM, Typescript and Python, no matter where and how your (legacy) systems are.", | ||
@@ -18,4 +18,8 @@ "type": "module", | ||
"devDependencies": { | ||
"@eslint/js": "^9.3.0", | ||
"@types/node": "^20.11.10", | ||
"typescript": "^5.3.3" | ||
"eslint": "^9.3.0", | ||
"globals": "^15.3.0", | ||
"typescript": "^5.3.3", | ||
"typescript-eslint": "^7.10.0" | ||
}, | ||
@@ -22,0 +26,0 @@ "scripts": { |
@@ -20,3 +20,3 @@ import * as t from "../types.js"; | ||
export interface DenoFunc { | ||
code: string | Function; | ||
code: string | ((...args: any[]) => any); | ||
secrets?: Array<string>; | ||
@@ -23,0 +23,0 @@ effect?: Effect; |
@@ -18,4 +18,4 @@ import * as t from "../types.js"; | ||
constructor(artifactPath: string); | ||
handler<I extends t.Typedef = t.Typedef, O extends t.Typedef = t.Typedef>(inp: I, out: O, { func, effect }: { | ||
func: string; | ||
handler<I extends t.Typedef = t.Typedef, O extends t.Typedef = t.Typedef>(inp: I, out: O, { name, effect }: { | ||
name: string; | ||
effect?: Effect; | ||
@@ -26,4 +26,4 @@ }): t.Func<I, O, WireHandlerWasmMat>; | ||
constructor(artifactPath: string); | ||
fromExport<I extends t.Typedef = t.Typedef, O extends t.Typedef = t.Typedef>(inp: I, out: O, { func, effect }: { | ||
func: string; | ||
export<I extends t.Typedef = t.Typedef, O extends t.Typedef = t.Typedef>(inp: I, out: O, { name, effect }: { | ||
name: string; | ||
effect?: Effect; | ||
@@ -30,0 +30,0 @@ }): t.Func<I, O, ReflectedFuncWasmMat>; |
@@ -21,3 +21,3 @@ // Copyright Metatype OÜ, licensed under the Mozilla Public License Version 2.0. | ||
} | ||
handler(inp, out, { func, effect = fx.read() }) { | ||
handler(inp, out, { name, effect = fx.read() }) { | ||
const matId = runtimes.fromWasmWireHandler({ | ||
@@ -27,3 +27,3 @@ runtime: this._id, | ||
}, { | ||
funcName: func, | ||
funcName: name, | ||
}); | ||
@@ -33,3 +33,3 @@ return t.func(inp, out, { | ||
effect, | ||
funcName: func, | ||
funcName: name, | ||
}); | ||
@@ -44,3 +44,3 @@ } | ||
} | ||
fromExport(inp, out, { func, effect = fx.read() }) { | ||
export(inp, out, { name, effect = fx.read() }) { | ||
const matId = runtimes.fromWasmReflectedFunc({ | ||
@@ -50,3 +50,3 @@ runtime: this._id, | ||
}, { | ||
funcName: func, | ||
funcName: name, | ||
}); | ||
@@ -56,5 +56,5 @@ return t.func(inp, out, { | ||
effect, | ||
funcName: func, | ||
funcName: name, | ||
}); | ||
} | ||
} |
import { BasicAuth } from "./tg_deploy.js"; | ||
import { Artifact } from "./gen/interfaces/metatype-typegraph-core.js"; | ||
export declare class ArtifactUploader { | ||
private baseUrl; | ||
private refArtifacts; | ||
@@ -9,5 +10,4 @@ private tgName; | ||
private tgPath; | ||
private getUploadUrl; | ||
constructor(baseUrl: string, refArtifacts: Artifact[], tgName: string, auth: BasicAuth | undefined, headers: Headers, tgPath: string); | ||
private fetchUploadUrls; | ||
private getUploadTokens; | ||
private upload; | ||
@@ -14,0 +14,0 @@ private getMetas; |
@@ -5,4 +5,7 @@ // Copyright Metatype OÜ, licensed under the Mozilla Public License Version 2.0. | ||
import * as fsp from "node:fs/promises"; | ||
import { log } from "./io.js"; | ||
import { execRequest } from "./utils/func_utils.js"; | ||
export class ArtifactUploader { | ||
constructor(baseUrl, refArtifacts, tgName, auth, headers, tgPath) { | ||
this.baseUrl = baseUrl; | ||
this.refArtifacts = refArtifacts; | ||
@@ -13,17 +16,18 @@ this.tgName = tgName; | ||
this.tgPath = tgPath; | ||
const suffix = `${tgName}/artifacts/upload-urls`; | ||
this.getUploadUrl = new URL(suffix, baseUrl); | ||
} | ||
async fetchUploadUrls(artifactMetas) { | ||
async getUploadTokens(artifactMetas) { | ||
const artifactsJson = JSON.stringify(artifactMetas); | ||
const response = await fetch(this.getUploadUrl, { | ||
const uploadUrls = await execRequest(new URL(`${this.tgName}/artifacts/prepare-upload`, this.baseUrl), { | ||
method: "POST", | ||
headers: this.headers, | ||
body: artifactsJson, | ||
}); | ||
if (!response.ok) { | ||
const err = await response.text(); | ||
throw new Error(`Failed requesting artifact upload URLs: ${response.status} - ${err}`); | ||
} | ||
const uploadUrls = await response.json(); | ||
}, `tgDeploy failed to get upload urls`); | ||
// if (!response.ok) { | ||
// log.debug("response", response); | ||
// const err = await response.text(); | ||
// throw new Error( | ||
// `Failed requesting artifact upload URLs: ${response.status} - ${err}`, | ||
// ); | ||
// } | ||
// const uploadUrls: Array<string | null> = await response.json(); | ||
if (uploadUrls.length !== artifactMetas.length) { | ||
@@ -35,3 +39,3 @@ const diff = `array length mismatch: ${uploadUrls.length} !== ${artifactMetas.length}`; | ||
} | ||
async upload(url, meta) { | ||
async upload(token, meta) { | ||
const uploadHeaders = new Headers({ | ||
@@ -43,19 +47,19 @@ "Content-Type": "application/octet-stream", | ||
} | ||
if (url == null) { | ||
// console.error(`Skipping upload for artifact: ${meta.relativePath}`); | ||
if (token == null) { | ||
log.info("skipping artifact upload:", meta.relativePath); | ||
return; | ||
} | ||
const uploadUrl = new URL(`${this.tgName}/artifacts`, this.baseUrl); | ||
uploadUrl.searchParams.set("token", token); | ||
const path = join(dirname(this.tgPath), meta.relativePath); | ||
// TODO: stream | ||
const content = await fsp.readFile(path); | ||
const res = await fetch(url, { | ||
log.debug("uploading artifact", meta.relativePath, uploadUrl.href); | ||
const res = await execRequest(uploadUrl, { | ||
method: "POST", | ||
headers: uploadHeaders, | ||
body: new Uint8Array(content), | ||
}); | ||
if (!res.ok) { | ||
const err = await res.text(); | ||
throw new Error(`Failed to upload artifact '${path}' (${res.status}): ${err}`); | ||
} | ||
return res.json(); | ||
}, `failed to upload artifact ${meta.relativePath}`); | ||
log.info("✓ artifact uploaded:", meta.relativePath); | ||
return res; | ||
} | ||
@@ -91,5 +95,6 @@ getMetas(artifacts) { | ||
const artifactMetas = this.getMetas(this.refArtifacts); | ||
const uploadUrls = await this.fetchUploadUrls(artifactMetas); | ||
const results = await Promise.allSettled(uploadUrls.map(async (url, i) => { | ||
return await this.upload(url, artifactMetas[i]); | ||
const tokens = await this.getUploadTokens(artifactMetas); | ||
log.debug("upload urls", tokens); | ||
const results = await Promise.allSettled(tokens.map(async (token, i) => { | ||
return await this.upload(token, artifactMetas[i]); | ||
})); | ||
@@ -96,0 +101,0 @@ this.handleUploadErrors(results, artifactMetas); |
@@ -1,2 +0,2 @@ | ||
import { ArtifactResolutionConfig } from "./gen/interfaces/metatype-typegraph-core.js"; | ||
import { MigrationAction } from "./gen/interfaces/metatype-typegraph-core.js"; | ||
import { TypegraphOutput } from "./typegraph.js"; | ||
@@ -9,16 +9,21 @@ export declare class BasicAuth { | ||
} | ||
export interface TypegateConnectionOptions { | ||
url: string; | ||
auth?: BasicAuth; | ||
} | ||
export interface TypegraphDeployParams { | ||
typegate: TypegateConnectionOptions; | ||
typegraphPath: string; | ||
baseUrl: string; | ||
auth?: BasicAuth; | ||
artifactsConfig: ArtifactResolutionConfig; | ||
secrets: Record<string, string>; | ||
prefix?: string; | ||
secrets?: Record<string, string>; | ||
migrationsDir?: string; | ||
migrationActions?: Record<string, MigrationAction>; | ||
defaultMigrationAction?: MigrationAction; | ||
} | ||
export interface TypegraphRemoveParams { | ||
baseUrl: string; | ||
auth?: BasicAuth; | ||
typegate: TypegateConnectionOptions; | ||
} | ||
export interface DeployResult { | ||
serialized: string; | ||
typegate: Record<string, any> | string; | ||
response: Record<string, any>; | ||
} | ||
@@ -25,0 +30,0 @@ export interface RemoveResult { |
@@ -5,2 +5,4 @@ // Copyright Metatype OÜ, licensed under the Mozilla Public License Version 2.0. | ||
import { wit_utils } from "./wit.js"; | ||
import { execRequest } from "./utils/func_utils.js"; | ||
import { log } from "./io.js"; | ||
export class BasicAuth { | ||
@@ -16,4 +18,20 @@ constructor(username, password) { | ||
export async function tgDeploy(typegraph, params) { | ||
const { baseUrl, secrets, auth, artifactsConfig } = params; | ||
const serialized = typegraph.serialize(artifactsConfig); | ||
var _a, _b, _c, _d; | ||
const serializeParams = { | ||
typegraphPath: params.typegraphPath, | ||
prefix: params.prefix, | ||
artifactResolution: true, | ||
codegen: false, | ||
prismaMigration: { | ||
migrationsDir: (_a = params.migrationsDir) !== null && _a !== void 0 ? _a : "prisma-migrations", | ||
migrationActions: Object.entries((_b = params.migrationActions) !== null && _b !== void 0 ? _b : {}), | ||
defaultMigrationAction: (_c = params.defaultMigrationAction) !== null && _c !== void 0 ? _c : { | ||
apply: true, | ||
create: false, | ||
reset: false, | ||
}, | ||
}, | ||
pretty: false, | ||
}; | ||
const serialized = typegraph.serialize(serializeParams); | ||
const tgJson = serialized.tgJson; | ||
@@ -23,12 +41,16 @@ const refArtifacts = serialized.ref_artifacts; | ||
headers.append("Content-Type", "application/json"); | ||
if (auth) { | ||
headers.append("Authorization", auth.asHeaderValue()); | ||
const typegate = params.typegate; | ||
if (typegate.auth) { | ||
headers.append("Authorization", typegate.auth.asHeaderValue()); | ||
} | ||
if (refArtifacts.length > 0) { | ||
// upload the artifacts | ||
const artifactUploader = new ArtifactUploader(baseUrl, refArtifacts, typegraph.name, auth, headers, params.typegraphPath); | ||
const artifactUploader = new ArtifactUploader(typegate.url, refArtifacts, typegraph.name, typegate.auth, headers, params.typegraphPath); | ||
await artifactUploader.uploadArtifacts(); | ||
} | ||
else { | ||
log.debug("no artifacts to upload"); | ||
} | ||
// deploy the typegraph | ||
const response = await execRequest(new URL("/typegate", baseUrl), { | ||
const response = await execRequest(new URL("/typegate", typegate.url), { | ||
method: "POST", | ||
@@ -38,12 +60,18 @@ headers, | ||
tg: tgJson, | ||
secrets: Object.entries(secrets !== null && secrets !== void 0 ? secrets : {}), | ||
secrets: Object.entries((_d = params.secrets) !== null && _d !== void 0 ? _d : {}), | ||
}), | ||
}); | ||
}, `tgDeploy failed to deploy typegraph ${typegraph.name}`); | ||
if (response.errors) { | ||
for (const err of response.errors) { | ||
console.error(err.message); | ||
} | ||
throw new Error(`failed to deploy typegraph ${typegraph.name}`); | ||
} | ||
return { | ||
serialized: tgJson, | ||
typegate: response, | ||
response: response.data.addTypegraph, | ||
}; | ||
} | ||
export async function tgRemove(typegraph, params) { | ||
const { baseUrl, auth } = params; | ||
const { url, auth } = params.typegate; | ||
const headers = new Headers(); | ||
@@ -54,24 +82,8 @@ headers.append("Content-Type", "application/json"); | ||
} | ||
const response = await execRequest(new URL("/typegate", baseUrl), { | ||
const response = await execRequest(new URL("/typegate", url), { | ||
method: "POST", | ||
headers, | ||
body: wit_utils.gqlRemoveQuery([typegraph.name]), | ||
}); | ||
}, `tgRemove failed to remove typegraph ${typegraph.name}`); | ||
return { typegate: response }; | ||
} | ||
/** | ||
* Simple fetch wrapper with more verbose errors | ||
*/ | ||
async function execRequest(url, reqInit) { | ||
try { | ||
const response = await fetch(url, reqInit); | ||
if (response.headers.get("Content-Type") == "application/json") { | ||
return await response.json(); | ||
} | ||
throw Error(`expected json object, got "${await response.text()}"`); | ||
} | ||
catch (err) { | ||
const message = err instanceof Error ? err.message : err; | ||
throw Error(`error executing request to ${url.toString()}: ${message}`); | ||
} | ||
} |
import { TypegraphOutput } from "./typegraph.js"; | ||
export declare class Manager { | ||
#private; | ||
static isRunFromCLI(): boolean; | ||
constructor(typegraph: TypegraphOutput, port?: number); | ||
constructor(typegraph: TypegraphOutput); | ||
run(): Promise<void>; | ||
} |
195
tg_manage.js
@@ -14,149 +14,130 @@ // Copyright Metatype OÜ, licensed under the Mozilla Public License Version 2.0. | ||
}; | ||
var _Manager_instances, _Manager_port, _Manager_typegraph, _Manager_endpoint, _Manager_typegraphPath, _Manager_requestCommands, _Manager_requestConfig, _Manager_serialize, _Manager_deploy, _Manager_relayResultToCLI, _Manager_relayErrorToCLI; | ||
var _Manager_instances, _Manager_typegraph, _Manager_env, _Manager_getMigrationsDir, _Manager_serialize, _Manager_deploy; | ||
import { BasicAuth, tgDeploy } from "./tg_deploy.js"; | ||
import { getEnvVariable } from "./utils/func_utils.js"; | ||
const PORT = "META_CLI_SERVER_PORT"; // meta-cli instance that executes the current file | ||
const SELF_PATH = "META_CLI_TG_PATH"; // path to the current file to uniquely identify the run results | ||
import { freezeTgOutput } from "./utils/func_utils.js"; | ||
import { log, rpc } from "./io.js"; | ||
import { getCliEnv } from "./envs/cli.js"; | ||
import * as path from "node:path"; | ||
export class Manager { | ||
static isRunFromCLI() { | ||
return !!getEnvVariable(PORT); | ||
} | ||
constructor(typegraph, port) { | ||
constructor(typegraph) { | ||
_Manager_instances.add(this); | ||
_Manager_port.set(this, void 0); | ||
_Manager_typegraph.set(this, void 0); | ||
_Manager_endpoint.set(this, void 0); | ||
_Manager_typegraphPath.set(this, void 0); | ||
_Manager_env.set(this, void 0); | ||
__classPrivateFieldSet(this, _Manager_typegraph, typegraph, "f"); | ||
__classPrivateFieldSet(this, _Manager_typegraphPath, getEnvVariable(SELF_PATH), "f"); | ||
if (port == undefined) { | ||
const envPort = parseInt(getEnvVariable(PORT)); | ||
if (isNaN(envPort)) { | ||
throw new Error(`Environment variable ${PORT} is not a number or is undefined`); | ||
} | ||
__classPrivateFieldSet(this, _Manager_port, envPort, "f"); | ||
} | ||
else { | ||
__classPrivateFieldSet(this, _Manager_port, port, "f"); | ||
} | ||
__classPrivateFieldSet(this, _Manager_endpoint, `http://localhost:${__classPrivateFieldGet(this, _Manager_port, "f")}`, "f"); | ||
__classPrivateFieldSet(this, _Manager_env, getCliEnv(), "f"); | ||
} | ||
async run() { | ||
let { config, command } = await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_requestCommands).call(this); | ||
switch (command) { | ||
switch (__classPrivateFieldGet(this, _Manager_env, "f").command) { | ||
case "serialize": | ||
await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_serialize).call(this, config); | ||
await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_serialize).call(this); | ||
break; | ||
case "deploy": | ||
await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_deploy).call(this, config); | ||
await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_deploy).call(this); | ||
break; | ||
default: | ||
throw new Error(`command ${command} from meta-cli not supported`); | ||
throw new Error(`command ${__classPrivateFieldGet(this, _Manager_env, "f").command} from meta-cli not supported`); | ||
} | ||
} | ||
} | ||
_Manager_port = new WeakMap(), _Manager_typegraph = new WeakMap(), _Manager_endpoint = new WeakMap(), _Manager_typegraphPath = new WeakMap(), _Manager_instances = new WeakSet(), _Manager_requestCommands = async function _Manager_requestCommands() { | ||
const { data: config } = await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_requestConfig).call(this); | ||
// console.error("SDK received config", config); | ||
const { data: command } = await (await fetch(new URL("command", __classPrivateFieldGet(this, _Manager_endpoint, "f")))) | ||
.json(); | ||
// console.error("SDK received command", command); | ||
return { command, config }; | ||
}, _Manager_requestConfig = async function _Manager_requestConfig() { | ||
const params = new URLSearchParams({ | ||
typegraph: __classPrivateFieldGet(this, _Manager_typegraph, "f").name, | ||
typegraph_path: __classPrivateFieldGet(this, _Manager_typegraphPath, "f"), | ||
}); | ||
const response = await fetch(new URL("config?" + params, __classPrivateFieldGet(this, _Manager_endpoint, "f"))); | ||
return (await response.json()); | ||
}, _Manager_serialize = async function _Manager_serialize(config) { | ||
var _a; | ||
_Manager_typegraph = new WeakMap(), _Manager_env = new WeakMap(), _Manager_instances = new WeakSet(), _Manager_getMigrationsDir = function _Manager_getMigrationsDir() { | ||
return path.join(__classPrivateFieldGet(this, _Manager_env, "f").migrations_dir, __classPrivateFieldGet(this, _Manager_typegraph, "f").name); | ||
}, _Manager_serialize = async function _Manager_serialize() { | ||
let finalizationResult; | ||
try { | ||
const env = __classPrivateFieldGet(this, _Manager_env, "f"); | ||
finalizationResult = __classPrivateFieldGet(this, _Manager_typegraph, "f").serialize({ | ||
...config.artifactsConfig, | ||
prefix: config.prefix, | ||
typegraphPath: env.typegraph_path, | ||
prefix: env.prefix, | ||
artifactResolution: __classPrivateFieldGet(this, _Manager_env, "f").artifact_resolution, | ||
codegen: false, | ||
prismaMigration: { | ||
migrationsDir: __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_getMigrationsDir).call(this), | ||
migrationActions: [], | ||
defaultMigrationAction: { | ||
apply: true, | ||
create: false, | ||
reset: false, | ||
}, | ||
}, | ||
pretty: false, | ||
}); | ||
log.success(finalizationResult.tgJson, true); | ||
} | ||
catch (err) { | ||
return await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_relayErrorToCLI).call(this, "serialize", "serialization_err", (_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : "error serializing typegraph", { | ||
err, | ||
log.failure({ | ||
typegraph: __classPrivateFieldGet(this, _Manager_typegraph, "f").name, | ||
errors: getErrorStack(err, "failed to serialize typegraph"), | ||
}); | ||
} | ||
await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_relayResultToCLI).call(this, "serialize", JSON.parse(finalizationResult.tgJson)); | ||
}, _Manager_deploy = async function _Manager_deploy({ typegate, artifactsConfig, secrets, prefix }) { | ||
var _a, _b; | ||
const { endpoint, auth } = typegate; | ||
if (!auth) { | ||
throw new Error(`"${__classPrivateFieldGet(this, _Manager_typegraph, "f").name}" received null or undefined "auth" field on the configuration`); | ||
}, _Manager_deploy = async function _Manager_deploy() { | ||
const deployData = await rpc.getDeployData(__classPrivateFieldGet(this, _Manager_typegraph, "f").name); | ||
const env = __classPrivateFieldGet(this, _Manager_env, "f"); | ||
if (!env.artifact_resolution) { | ||
log.failure({ | ||
typegraph: __classPrivateFieldGet(this, _Manager_typegraph, "f").name, | ||
errors: ["artifact resolution must be enabled for deployment"], | ||
}); | ||
return; | ||
} | ||
const config = { | ||
...artifactsConfig, | ||
prefix, | ||
const params = { | ||
typegraphPath: env.typegraph_path, | ||
prefix: env.prefix, | ||
artifactResolution: true, | ||
codegen: false, | ||
prismaMigration: { | ||
migrationsDir: __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_getMigrationsDir).call(this), | ||
migrationActions: Object.entries(deployData.migrationActions), | ||
defaultMigrationAction: deployData.defaultMigrationAction, | ||
}, | ||
pretty: false, | ||
}; | ||
// hack for allowing tg.serialize(config) to be called more than once | ||
let localMemo; | ||
const frozenOut = freezeTgOutput(params, __classPrivateFieldGet(this, _Manager_typegraph, "f")); | ||
// hack for allowing tg.serialize(config) to be called more than once | ||
let frozenSerialized; | ||
try { | ||
localMemo = __classPrivateFieldGet(this, _Manager_typegraph, "f").serialize(config); | ||
frozenSerialized = frozenOut.serialize(params); | ||
} | ||
catch (err) { | ||
return await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_relayErrorToCLI).call(this, "deploy", "serialization_err", (_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : "error serializing typegraph", { | ||
err, | ||
log.failure({ | ||
typegraph: __classPrivateFieldGet(this, _Manager_typegraph, "f").name, | ||
errors: getErrorStack(err, "failed to serialize typegraph"), | ||
}); | ||
return; | ||
} | ||
const reusableTgOutput = { | ||
...__classPrivateFieldGet(this, _Manager_typegraph, "f"), | ||
serialize: (_) => localMemo, | ||
serialize: () => frozenSerialized, | ||
}; | ||
if (artifactsConfig.codegen) { | ||
await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_relayResultToCLI).call(this, "codegen", JSON.parse(localMemo.tgJson)); | ||
} | ||
let deployRes; | ||
try { | ||
const { typegate } = await tgDeploy(reusableTgOutput, { | ||
baseUrl: endpoint, | ||
artifactsConfig: config, | ||
secrets, | ||
auth: new BasicAuth(auth.username, auth.password), | ||
typegraphPath: __classPrivateFieldGet(this, _Manager_typegraphPath, "f"), | ||
const deployTarget = await rpc.getDeployTarget(); | ||
const { response } = await tgDeploy(reusableTgOutput, { | ||
typegate: { | ||
url: deployTarget.baseUrl, | ||
auth: new BasicAuth(deployTarget.auth.username, deployTarget.auth.password), | ||
}, | ||
typegraphPath: env.typegraph_path, | ||
prefix: env.prefix, | ||
secrets: deployData.secrets, | ||
migrationsDir: __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_getMigrationsDir).call(this), | ||
migrationActions: deployData.migrationActions, | ||
defaultMigrationAction: deployData.defaultMigrationAction, | ||
}); | ||
deployRes = typegate; | ||
log.success({ typegraph: __classPrivateFieldGet(this, _Manager_typegraph, "f").name, ...response }); | ||
} | ||
catch (err) { | ||
return await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_relayErrorToCLI).call(this, "deploy", "deploy_err", (_b = err === null || err === void 0 ? void 0 : err.message) !== null && _b !== void 0 ? _b : "error deploying typegraph to typegate", { | ||
err, | ||
...(err.cause ? { cause: err.cause } : {}), | ||
log.failure({ | ||
typegraph: __classPrivateFieldGet(this, _Manager_typegraph, "f").name, | ||
errors: getErrorStack(err, "failed to deploy typegraph"), | ||
}); | ||
return; | ||
} | ||
await __classPrivateFieldGet(this, _Manager_instances, "m", _Manager_relayResultToCLI).call(this, "deploy", deployRes); | ||
}, _Manager_relayResultToCLI = async function _Manager_relayResultToCLI(initiator, data) { | ||
const typegraphName = __classPrivateFieldGet(this, _Manager_typegraph, "f").name; | ||
const response = { | ||
command: initiator, | ||
typegraphName, | ||
typegraphPath: __classPrivateFieldGet(this, _Manager_typegraphPath, "f"), | ||
data, | ||
}; | ||
await fetch(new URL("response", __classPrivateFieldGet(this, _Manager_endpoint, "f")), { | ||
method: "POST", | ||
headers: { "Content-Type": "application/json" }, | ||
body: JSON.stringify(response), | ||
}); | ||
}, _Manager_relayErrorToCLI = async function _Manager_relayErrorToCLI(initiator, code, msg, value) { | ||
const typegraphName = __classPrivateFieldGet(this, _Manager_typegraph, "f").name; | ||
const response = { | ||
command: initiator, | ||
typegraphName, | ||
typegraphPath: __classPrivateFieldGet(this, _Manager_typegraphPath, "f"), | ||
error: { | ||
code, | ||
msg, | ||
value, | ||
}, | ||
}; | ||
await fetch(new URL("response", __classPrivateFieldGet(this, _Manager_endpoint, "f")), { | ||
method: "POST", | ||
headers: { "Content-Type": "application/json" }, | ||
body: JSON.stringify(response), | ||
}); | ||
}; | ||
function getErrorStack(err, defaultErr) { | ||
var _a, _b; | ||
if (err instanceof Error) { | ||
log.debug(err); | ||
return [err.message]; | ||
} | ||
return (_a = err === null || err === void 0 ? void 0 : err.stack) !== null && _a !== void 0 ? _a : [(_b = err === null || err === void 0 ? void 0 : err.toString()) !== null && _b !== void 0 ? _b : defaultErr]; | ||
} |
import * as t from "./types.js"; | ||
import { InjectionValue } from "./utils/type_utils.js"; | ||
import { Auth, Cors as CorsWit, Rate } from "./wit.js"; | ||
import { Artifact, ArtifactResolutionConfig } from "./gen/interfaces/metatype-typegraph-core.js"; | ||
import { Artifact, SerializeParams } from "./gen/interfaces/metatype-typegraph-core.js"; | ||
type Exports = Record<string, t.Func>; | ||
@@ -72,3 +72,3 @@ type Cors = Partial<CorsWit>; | ||
export interface TypegraphOutput { | ||
serialize: (config: ArtifactResolutionConfig) => TgFinalizationResult; | ||
serialize: (config: SerializeParams) => TgFinalizationResult; | ||
name: string; | ||
@@ -75,0 +75,0 @@ } |
@@ -10,2 +10,4 @@ // Copyright Metatype OÜ, licensed under the Mozilla Public License Version 2.0. | ||
import { Manager } from "./tg_manage.js"; | ||
import { log } from "./io.js"; | ||
import { hasCliEnv } from "./envs/cli.js"; | ||
export class ApplyFromArg { | ||
@@ -76,7 +78,9 @@ constructor(name, type) { | ||
} | ||
let counter = 0; | ||
export async function typegraph(nameOrArgs, maybeBuilder) { | ||
++counter; | ||
const args = typeof nameOrArgs === "string" | ||
? { name: nameOrArgs } | ||
: nameOrArgs; | ||
const { name, dynamic, cors, prefix, rate, secrets, } = args; | ||
const { name, dynamic, cors, prefix, rate, secrets } = args; | ||
const builder = "builder" in args | ||
@@ -139,3 +143,3 @@ ? args.builder | ||
try { | ||
const [tgJson, ref_artifacts] = core.finalizeTypegraph(config); | ||
const [tgJson, ref_artifacts] = core.serializeTypegraph(config); | ||
const result = { | ||
@@ -158,6 +162,14 @@ tgJson: tgJson, | ||
}; | ||
if (Manager.isRunFromCLI()) { | ||
if (hasCliEnv()) { | ||
const manager = new Manager(ret); | ||
await manager.run(); | ||
// TODO solve hanging process (stdin??) | ||
setTimeout(() => { | ||
if (counter === 0) { | ||
log.debug("exiting"); | ||
process.exit(0); | ||
} | ||
}, 10); | ||
} | ||
--counter; | ||
return ret; | ||
@@ -164,0 +176,0 @@ } |
@@ -1,3 +0,4 @@ | ||
import { InheritDef } from "../typegraph.js"; | ||
import { InheritDef, TypegraphOutput } from "../typegraph.js"; | ||
import { ReducePath } from "../gen/interfaces/metatype-typegraph-utils.js"; | ||
import { SerializeParams } from "../gen/interfaces/metatype-typegraph-core.js"; | ||
export declare function stringifySymbol(symbol: symbol): string; | ||
@@ -8,1 +9,7 @@ export declare function serializeRecordValues<T>(obj: Record<string, T>): Array<[string, string]>; | ||
export declare function getAllEnvVariables(): any; | ||
/** Create a reusable version of a `TypegraphOutput` */ | ||
export declare function freezeTgOutput(config: SerializeParams, tgOutput: TypegraphOutput): TypegraphOutput; | ||
/** | ||
* Simple fetch wrapper with more verbose errors | ||
*/ | ||
export declare function execRequest(url: URL, reqInit: RequestInit, errMsg: string): Promise<any>; |
// Copyright Metatype OÜ, licensed under the Mozilla Public License Version 2.0. | ||
// SPDX-License-Identifier: MPL-2.0 | ||
import { InheritDef } from "../typegraph.js"; | ||
import { InheritDef, } from "../typegraph.js"; | ||
import { serializeStaticInjection } from "./injection_utils.js"; | ||
import { log } from "../io.js"; | ||
export function stringifySymbol(symbol) { | ||
@@ -62,1 +63,33 @@ var _a; | ||
} | ||
const frozenMemo = {}; | ||
/** Create a reusable version of a `TypegraphOutput` */ | ||
export function freezeTgOutput(config, tgOutput) { | ||
var _a; | ||
frozenMemo[tgOutput.name] = (_a = frozenMemo[tgOutput.name]) !== null && _a !== void 0 ? _a : tgOutput.serialize(config); | ||
return { | ||
...tgOutput, | ||
serialize: () => frozenMemo[tgOutput.name], | ||
}; | ||
} | ||
/** | ||
* Simple fetch wrapper with more verbose errors | ||
*/ | ||
export async function execRequest(url, reqInit, errMsg) { | ||
try { | ||
const response = await fetch(url, reqInit); | ||
if (!response.ok) { | ||
log.debug("error", response.json()); | ||
throw Error(`${errMsg}: request failed with status ${response.status} (${response.statusText})`); | ||
} | ||
if (response.headers.get("Content-Type") == "application/json") { | ||
return await response.json(); | ||
} | ||
log.debug("response", response); | ||
throw Error(`${errMsg}: expected json object, got "${await response.text()}"`); | ||
} | ||
catch (err) { | ||
log.debug("fetch error", { url, requestInit: reqInit, error: err }); | ||
const message = err instanceof Error ? err.message : err; | ||
throw Error(`${errMsg}: ${message}`); | ||
} | ||
} |
import { PerEffect } from "../effects.js"; | ||
type RequiredKeys<T> = { | ||
[K in keyof T]-?: {} extends { | ||
[K in keyof T]-?: object extends { | ||
[P in K]: T[K]; | ||
@@ -8,3 +8,3 @@ } ? never : K; | ||
type OptionalKeys<T> = { | ||
[K in keyof T]-?: {} extends { | ||
[K in keyof T]-?: object extends { | ||
[P in K]: T[K]; | ||
@@ -11,0 +11,0 @@ } ? K : never; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
5830808
68
10472
2
6