Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -1,5 +1,5 @@
import { t as i18nT } from "i18next";
import { getNativeWorkflowTriggerCapabilityErrors } from "@toolctrl/foundation";
import { getNativeWorkflowTriggerCapabilityErrors } from "@hivegrid/foundation";
import { WorkflowDto } from "../dtos/WorkflowDto";
import { preflightWorkflow, type WorkflowRequiredInputIssue } from "../helpers/WorkflowReferenceUtils";
import WorkflowVariablesAndCredentialsService from "./WorkflowVariablesAndCredentialsService";
@@ -5,7 +5,7 @@ describe("WorkflowsExecutionsService environment boundary", () => {
it("loads runtime mode through the web config boundary", () => {
const source = readRepoFile("apps/web/app/modules/workflowEngine/services/WorkflowsExecutionsService.ts");
expect(source).toContain('from "@toolctrl/config"');
expect(source).toContain('from "@hivegrid/config"');
expect(source).toContain("loadWebConfig().config.nodeEnv");
expect(source).not.toMatch(/process\.env\.NODE_ENV\b/);
});
@@ -47,7 +47,7 @@ vi.mock("~/utils/db.server", () => ({
},
}));
vi.mock("@toolctrl/db/outbox", () => ({
vi.mock("@hivegrid/db/outbox", () => ({
publishOutboxEvent: getMocks().publishOutboxEvent,
}));
@@ -1,6 +1,6 @@
import { loadWebConfig } from "@toolctrl/config";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@toolctrl/db/outbox";
import { buildWorkflowExecutionContinueRequestedOutboxEvent, buildWorkflowExecutionRequestedOutboxEvent, type QueueJsonValue } from "@toolctrl/queue";
import { loadWebConfig } from "@hivegrid/config";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import { buildWorkflowExecutionContinueRequestedOutboxEvent, buildWorkflowExecutionRequestedOutboxEvent, type QueueJsonValue } from "@hivegrid/queue";
import { db } from "~/utils/db.server";
import { getWorkflowExecution, updateWorkflowExecution } from "../db/workflowExecutions.db.server";
import { WorkflowExecutionDto } from "../dtos/WorkflowExecutionDto";
@@ -13,7 +13,7 @@ import type { WorkflowDto } from "../dtos/WorkflowDto";
import { WorkflowStatus } from "../dtos/WorkflowStatus";
import { emitter } from "~/utils/stream/emitter.server";
import WorkflowPreflightService from "./WorkflowPreflightService";
import { emitPluginHook, PLUGIN_HOOK_WORKFLOW_EXECUTED, PLUGIN_HOOK_WORKFLOW_FAILED } from "@toolctrl/plugin-runtime";
import { emitPluginHook, PLUGIN_HOOK_WORKFLOW_EXECUTED, PLUGIN_HOOK_WORKFLOW_FAILED } from "@hivegrid/plugin-runtime";
import { redactWorkflowCredentials } from "./WorkflowsVariablesService";
function assertWorkflowIsLive(workflow: Pick<WorkflowDto, "status">) {
@@ -27,7 +27,7 @@ import {
PLUGIN_HOOK_WORKFLOW_UPDATED,
type PluginHookDefinition,
type PluginHookWorkflowDefinitionPayload,
} from "@toolctrl/plugin-runtime";
} from "@hivegrid/plugin-runtime";
import { emitPluginHookFireAndForget } from "~/modules/plugins/services/.server/pluginHookPublisher";
// Persisted generated names are intentionally stable English identifiers.
@@ -13,7 +13,6 @@ type TemplateImportMocks = {
workflowBlockConditionCreateMany: ReturnType<typeof vi.fn>;
workflowBlockToBlockCreateMany: ReturnType<typeof vi.fn>;
workflowInputExampleCreateMany: ReturnType<typeof vi.fn>;
getAllEntities: ReturnType<typeof vi.fn>;
getWorkflow: ReturnType<typeof vi.fn>;
emitWorkflowCreatedHook: ReturnType<typeof vi.fn>;
};
@@ -31,7 +30,6 @@ function getMocks(): TemplateImportMocks {
workflowBlockConditionCreateMany: vi.fn(),
workflowBlockToBlockCreateMany: vi.fn(),
workflowInputExampleCreateMany: vi.fn(),
getAllEntities: vi.fn(),
getWorkflow: vi.fn(),
emitWorkflowCreatedHook: vi.fn(),
};
@@ -54,10 +52,6 @@ vi.mock("~/utils/db.server", () => ({
},
}));
vi.mock("~/utils/db/entities/entities.db.server", () => ({
getAllEntities: getMocks().getAllEntities,
}));
vi.mock("./WorkflowsService", () => ({
default: {
get: getMocks().getWorkflow,
@@ -123,7 +117,6 @@ describe("WorkflowsTemplatesService import hooks", () => {
mocks.workflowBlockCreate.mockResolvedValue({ id: "block_imported_1" });
mocks.workflowBlockToBlockCreateMany.mockResolvedValue({ count: 0 });
mocks.workflowInputExampleCreateMany.mockResolvedValue({ count: 1 });
mocks.getAllEntities.mockResolvedValue([]);
mocks.getWorkflow.mockResolvedValue(importedWorkflow());
});
@@ -5,10 +5,10 @@ import WorkflowsTemplatesService, { getWorkflowTemplateImportErrorMessage, Workf
describe("WorkflowsTemplatesService import errors", () => {
it("translates missing credential import errors with the missing names", () => {
const error = new WorkflowTemplateImportError("missingCredentialsForImport", ["mail", "stripe"], "fallback");
const error = new WorkflowTemplateImportError("missingCredentialsForImport", ["mail", "billing"], "fallback");
const t = (key: string, options?: Record<string, unknown>) => `${key}:${options?.names}`;
expect(getWorkflowTemplateImportErrorMessage(error, t)).toBe("workflows.errors.missingCredentialsForImport:mail, stripe");
expect(getWorkflowTemplateImportErrorMessage(error, t)).toBe("workflows.errors.missingCredentialsForImport:mail, billing");
});
it("translates missing entity import errors with the missing names", () => {
@@ -3,8 +3,8 @@ import { WorkflowTemplateDto, WorkflowsTemplateDto } from "../dtos/WorkflowsTemp
import { WorkflowBlockTypes } from "../dtos/WorkflowBlockTypes";
import WorkflowsService, { emitWorkflowCreatedHook } from "./WorkflowsService";
import { WorkflowDto } from "../dtos/WorkflowDto";
import { Prisma, WorkflowVariable } from "@toolctrl/db/prisma-browser";
import { getAllEntities } from "~/utils/db/entities/entities.db.server";
import { Prisma, WorkflowVariable } from "@hivegrid/db/prisma-browser";
import { listModelKeys } from "~/services/typed-model-registry/registry.server";
export type WorkflowTemplateImportErrorCode =
| "invalidJson"
@@ -70,13 +70,15 @@ async function importWorkflows(template: WorkflowsTemplateDto, session: { tenant
});
});
if (requiredEntities.length > 0) {
const allEntities = await getAllEntities({ tenantId: session.tenantId });
const missingEntities = requiredEntities.filter((f) => !allEntities.find((g) => g.name === f));
// AD-2 / R-P14D: row* blocks address a typed model from the registry, not a
// generic entity. A template referencing a non-addressable model is rejected.
const addressableModels = listModelKeys();
const missingEntities = requiredEntities.filter((f) => !addressableModels.includes(f));
if (missingEntities.length > 0) {
throw new WorkflowTemplateImportError(
"missingEntitiesForImport",
missingEntities,
"To import this workflow, you must create the following entities first: " + missingEntities.join(", ")
"To import this workflow, you must address one of the following models: " + addressableModels.join(", ")
);
}
}
@@ -1,31 +1,22 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import type { WorkflowBlockDto } from "../../dtos/WorkflowBlockDto";
import { TypedModelError } from "~/services/typed-model-registry/types";
const mocks = vi.hoisted(() => ({
rowsApi: {
adapter: {
key: "kontakt",
labelKey: "crm.contacts.title",
fieldSchema: {},
read: vi.fn(),
create: vi.fn(),
update: vi.fn(),
del: vi.fn(),
get: vi.fn(),
delete: vi.fn(),
},
getEntity: vi.fn(),
getRowPropertiesFromJson: vi.fn(),
getApiFormat: vi.fn(),
getModelAdapterOrThrow: vi.fn(),
}));
vi.mock("~/utils/api/.server/RowsApi", () => ({
RowsApi: mocks.rowsApi,
}));
vi.mock("~/modules/rows/repositories/EntitiesSingleton", () => ({
default: { getEntity: mocks.getEntity },
}));
vi.mock("~/utils/helpers/ApiHelper", () => ({
default: {
getRowPropertiesFromJson: mocks.getRowPropertiesFromJson,
getApiFormat: mocks.getApiFormat,
},
vi.mock("~/services/typed-model-registry/registry.server", () => ({
getModelAdapterOrThrow: mocks.getModelAdapterOrThrow,
}));
vi.mock("~/modules/emails/services/EmailService.server", () => ({
@@ -34,9 +25,8 @@ vi.mock("~/modules/emails/services/EmailService.server", () => ({
import WorkflowBlockProService from "./WorkflowBlockProService";
const entity = { id: "entity-1", name: "contact", slug: "contacts", title: "Contacts" };
const session = { tenantId: "tenant-1", userId: "user-1" };
const rowValues = { dynamicProperties: [{ property: { name: "email" }, value: "hello@example.com" }] };
const ctx = { tenantId: "tenant-1", userId: "user-1" };
function block(overrides: Partial<WorkflowBlockDto>): WorkflowBlockDto {
return {
@@ -65,77 +55,65 @@ function params(workflowBlock: WorkflowBlockDto) {
} as never;
}
describe("WorkflowBlockProService row blocks", () => {
describe("WorkflowBlockProService row blocks (typed model registry)", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getEntity.mockResolvedValue(entity);
mocks.getRowPropertiesFromJson.mockReturnValue(rowValues);
mocks.getApiFormat.mockImplementation((_entity, row) => ({ id: row.id, formatted: true }));
mocks.rowsApi.create.mockResolvedValue({ id: "row-created" });
mocks.rowsApi.update.mockResolvedValue({ id: "row-updated" });
mocks.rowsApi.del.mockResolvedValue(undefined);
mocks.rowsApi.get.mockResolvedValue({ item: { id: "row-1", email: "old@example.com" } });
mocks.getModelAdapterOrThrow.mockImplementation((key: string) => {
if (key === "kontakt") return mocks.adapter;
throw new TypedModelError("workflows.errors.unknownModel", `Model '${key}' is not addressable.`);
});
mocks.adapter.read.mockResolvedValue({ id: "k-1", vorname: "Old" });
mocks.adapter.create.mockResolvedValue({ id: "k-created" });
mocks.adapter.update.mockResolvedValue({ id: "k-updated" });
mocks.adapter.delete.mockResolvedValue({ id: "k-deleted" });
});
test("passes workflow event context to rowCreate mutations", async () => {
test("rowGet reads the addressed model and returns the record", async () => {
const result = await WorkflowBlockProService.executeBlock(
params(
block({
type: "rowCreate",
input: { entity: "contact", row: JSON.stringify({ email: "hello@example.com" }) },
})
)
params(block({ type: "rowGet", input: { entity: "kontakt", id: "k-1" } }))
);
expect(mocks.rowsApi.create).toHaveBeenCalledWith({
entity,
tenantId: "tenant-1",
userId: "user-1",
rowValues,
eventContext: { source: "workflow" },
});
expect(result.output).toEqual({ row: { id: "row-created", formatted: true } });
expect(mocks.adapter.read).toHaveBeenCalledWith("k-1", ctx);
expect(result.output).toEqual({ row: { id: "k-1", vorname: "Old" } });
});
test("passes workflow event context to rowUpdate mutations", async () => {
await WorkflowBlockProService.executeBlock(
params(
block({
type: "rowUpdate",
input: { entity: "contact", id: "row-1", data: JSON.stringify({ email: "new@example.com" }) },
})
)
test("rowCreate parses the row payload and creates through the adapter", async () => {
const result = await WorkflowBlockProService.executeBlock(
params(block({ type: "rowCreate", input: { entity: "kontakt", row: JSON.stringify({ kontaktTyp: "privatperson", vorname: "Max" }) } }))
);
expect(mocks.rowsApi.get).toHaveBeenCalledWith("row-1", {
entity,
tenantId: "tenant-1",
userId: "user-1",
});
expect(mocks.rowsApi.update).toHaveBeenCalledWith("row-1", {
entity,
tenantId: "tenant-1",
userId: "user-1",
rowValues,
eventContext: { source: "workflow" },
});
expect(mocks.adapter.create).toHaveBeenCalledWith({ kontaktTyp: "privatperson", vorname: "Max" }, ctx);
expect(result.output).toEqual({ row: { id: "k-created" } });
});
test("passes workflow event context to rowDelete mutations", async () => {
test("rowUpdate parses the data payload and updates through the adapter", async () => {
await WorkflowBlockProService.executeBlock(
params(
block({
type: "rowDelete",
input: { entity: "contact", id: "row-1" },
})
)
params(block({ type: "rowUpdate", input: { entity: "kontakt", id: "k-1", data: JSON.stringify({ nachname: "Neu" }) } }))
);
expect(mocks.adapter.update).toHaveBeenCalledWith("k-1", { nachname: "Neu" }, ctx);
});
expect(mocks.rowsApi.del).toHaveBeenCalledWith("row-1", {
entity,
tenantId: "tenant-1",
userId: "user-1",
eventContext: { source: "workflow" },
});
test("rowDelete deletes through the adapter and returns the snapshot", async () => {
const result = await WorkflowBlockProService.executeBlock(
params(block({ type: "rowDelete", input: { entity: "kontakt", id: "k-1" } }))
);
expect(mocks.adapter.delete).toHaveBeenCalledWith("k-1", ctx);
expect(result.output).toEqual({ row: { id: "k-deleted" } });
});
test("an unaddressable model yields a Klartext error, not a silent fail", async () => {
const result = await WorkflowBlockProService.executeBlock(
params(block({ type: "rowCreate", input: { entity: "projekt", row: JSON.stringify({}) } }))
);
expect(result.throwsError).toBe(true);
expect(result.error).toContain("projekt");
expect(mocks.adapter.create).not.toHaveBeenCalled();
});
test("an invalid payload (TypedModelError) surfaces as a block error", async () => {
mocks.adapter.create.mockRejectedValueOnce(new TypedModelError("workflows.errors.invalidFieldValue", "Kontakt requires 'kontaktTyp'."));
const result = await WorkflowBlockProService.executeBlock(
params(block({ type: "rowCreate", input: { entity: "kontakt", row: JSON.stringify({ vorname: "Max" }) } }))
);
expect(result.throwsError).toBe(true);
expect(result.error).toContain("kontaktTyp");
});
});
@@ -1,13 +1,28 @@
import { RowsApi } from "~/utils/api/.server/RowsApi";
import { BlockExecutionParamsDto } from "../../dtos/BlockExecutionParamsDto";
import { BlockExecutionResultDto } from "../../dtos/BlockExecutionResultDto";
import WorkflowsValidationService from "../WorkflowsValidationService";
import { parseVariable } from "../WorkflowsVariablesService";
import ApiHelper from "~/utils/helpers/ApiHelper";
import EntitiesSingleton from "~/modules/rows/repositories/EntitiesSingleton";
import { getModelAdapterOrThrow } from "~/services/typed-model-registry/registry.server";
import { TypedModelError, type ModelCtx, type TypedModelAdapter } from "~/services/typed-model-registry/types";
import EmailService from "~/modules/emails/services/EmailService.server";
import { WorkflowBlockType } from "../../dtos/WorkflowBlockTypes";
// AD-2 / R-P14D: the row* blocks address a TYPED model from the registry
// (Kontakt today; the kern chain registers more) instead of resolving a generic
// entity by name and CRUDing through the polymorphic RowsApi. The block JSON keeps
// `entity: "<key>"`, but the key now resolves to a typed adapter; an unaddressable
// key surfaces as a Klartext error (M002), never a silent fail.
/** Resolve the addressed model adapter, or a Klartext error result for the block. */
function resolveModel(entityName: string): { adapter: TypedModelAdapter } | { error: string } {
try {
return { adapter: getModelAdapterOrThrow(entityName) };
} catch (error) {
if (error instanceof TypedModelError) return { error: error.message };
throw error;
}
}
export const PRO_WORKFLOW_BLOCK_TYPES = ["waitForInput", "rowGet", "rowCreate", "rowUpdate", "rowDelete", "email"] satisfies WorkflowBlockType[];
async function executeBlock(args: BlockExecutionParamsDto): Promise<BlockExecutionResultDto> {
@@ -40,6 +55,10 @@ async function executeWaitForInputBlock({ block, workflowContext }: BlockExecuti
};
}
function modelCtx(session: BlockExecutionParamsDto["session"]): ModelCtx {
return { tenantId: session.tenantId, userId: session.userId };
}
async function executeRowGetBlock({ block, workflowContext, session }: BlockExecutionParamsDto): Promise<BlockExecutionResultDto> {
const translated = parseVariable(JSON.stringify(block.input, null, 2), workflowContext)!;
const inputData = JSON.parse(translated);
@@ -59,20 +78,17 @@ async function executeRowGetBlock({ block, workflowContext, session }: BlockExec
if (error) {
return { output: null, error, throwsError: true, toBlockIds: [] };
}
const entity = await EntitiesSingleton.getEntity({ name: entityName });
const resolved = resolveModel(entityName);
if ("error" in resolved) {
return { output: null, error: resolved.error, throwsError: true, toBlockIds: [] };
}
const existing = await RowsApi.get(id, {
entity,
tenantId: session.tenantId,
userId: session.userId ?? undefined,
}).catch(() => {
return null;
});
// read() returns null when the record is absent/not visible (parity with the
// old RowsApi.get(...).catch(() => null)).
const row = await resolved.adapter.read(id, modelCtx(session)).catch(() => null);
return {
output: {
row: !existing ? null : ApiHelper.getApiFormat(entity, existing.item),
},
output: { row },
toBlockIds: block.toBlocks.map((f) => f.toBlockId),
};
}
@@ -96,22 +112,22 @@ async function executeRowCreateBlock({ block, workflowContext, session }: BlockE
if (error) {
return { output: null, error, throwsError: true, toBlockIds: [] };
}
const entity = await EntitiesSingleton.getEntity({ name: entityName });
const rowValues = ApiHelper.getRowPropertiesFromJson(undefined, entity, row);
const created = await RowsApi.create({
entity,
tenantId: session.tenantId,
userId: session.userId ?? undefined,
rowValues,
eventContext: { source: "workflow" },
});
return {
output: {
row: ApiHelper.getApiFormat(entity, created),
},
toBlockIds: block.toBlocks.map((f) => f.toBlockId),
};
const resolved = resolveModel(entityName);
if ("error" in resolved) {
return { output: null, error: resolved.error, throwsError: true, toBlockIds: [] };
}
try {
const created = await resolved.adapter.create(row, modelCtx(session));
return {
output: { row: created },
toBlockIds: block.toBlocks.map((f) => f.toBlockId),
};
} catch (e) {
if (e instanceof TypedModelError) {
return { output: null, error: e.message, throwsError: true, toBlockIds: [] };
}
throw e;
}
}
async function executeRowUpdateBlock({ block, workflowContext, session }: BlockExecutionParamsDto): Promise<BlockExecutionResultDto> {
@@ -135,29 +151,22 @@ async function executeRowUpdateBlock({ block, workflowContext, session }: BlockE
if (error) {
return { output: null, error, throwsError: true, toBlockIds: [] };
}
const entity = await EntitiesSingleton.getEntity({ name: entityName });
const existing = await RowsApi.get(id, {
entity,
tenantId: session.tenantId,
userId: session.userId ?? undefined,
});
const rowValues = ApiHelper.getRowPropertiesFromJson(undefined, entity, data, existing.item);
const updated = await RowsApi.update(id, {
entity,
tenantId: session.tenantId,
userId: session.userId ?? undefined,
rowValues,
eventContext: { source: "workflow" },
});
return {
output: {
row: ApiHelper.getApiFormat(entity, updated),
},
toBlockIds: block.toBlocks.map((f) => f.toBlockId),
};
const resolved = resolveModel(entityName);
if ("error" in resolved) {
return { output: null, error: resolved.error, throwsError: true, toBlockIds: [] };
}
try {
const updated = await resolved.adapter.update(id, data, modelCtx(session));
return {
output: { row: updated },
toBlockIds: block.toBlocks.map((f) => f.toBlockId),
};
} catch (e) {
if (e instanceof TypedModelError) {
return { output: null, error: e.message, throwsError: true, toBlockIds: [] };
}
throw e;
}
}
async function executeRowDeleteBlock({ block, workflowContext, session }: BlockExecutionParamsDto): Promise<BlockExecutionResultDto> {
@@ -179,26 +188,16 @@ async function executeRowDeleteBlock({ block, workflowContext, session }: BlockE
if (error) {
return { output: null, error, throwsError: true, toBlockIds: [] };
}
const entity = await EntitiesSingleton.getEntity({ name: entityName });
const resolved = resolveModel(entityName);
if ("error" in resolved) {
return { output: null, error: resolved.error, throwsError: true, toBlockIds: [] };
}
try {
const existing = await RowsApi.get(id, {
entity,
tenantId: session.tenantId,
userId: session.userId ?? undefined,
});
await RowsApi.del(id, {
entity,
tenantId: session.tenantId,
userId: session.userId ?? undefined,
eventContext: { source: "workflow" },
});
// Returns a snapshot of the deleted record (parity with the old get-then-del).
const row = await resolved.adapter.delete(id, modelCtx(session));
return {
output: {
row: ApiHelper.getApiFormat(entity, existing.item),
},
output: { row },
toBlockIds: block.toBlocks.map((f) => f.toBlockId),
};
} catch (e: any) {