@jini-ai/cms-forms 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -0
- package/LICENSE +201 -0
- package/README.md +43 -2
- package/dist/errors.d.ts +53 -0
- package/dist/errors.js +25 -0
- package/dist/forms.d.ts +59 -0
- package/dist/forms.js +203 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +9 -0
- package/dist/notify-subscriber.d.ts +15 -0
- package/dist/notify-subscriber.js +60 -0
- package/dist/ports.d.ts +111 -0
- package/dist/ports.js +2 -0
- package/dist/rate-limit-key.d.ts +8 -0
- package/dist/rate-limit-key.js +7 -0
- package/dist/submit-service.d.ts +28 -0
- package/dist/submit-service.js +62 -0
- package/dist/types.d.ts +46 -0
- package/dist/types.js +2 -0
- package/dist/write-service.d.ts +78 -0
- package/dist/write-service.js +213 -0
- package/package.json +54 -3
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Logger } from "@jini-ai/core/primitives";
|
|
2
|
+
/** Notification subscriber with host sender, mail and logging ports. Each recipient receives a stable per-submission dedup key; delivery and repository failures never block sibling subscribers. */
|
|
3
|
+
import type { EventBusPort } from "@jini-ai/cms/core";
|
|
4
|
+
import type { MailerPort, EmailAddress } from "./ports.js";
|
|
5
|
+
import type { FormDefinitionRepoPort, FormSubmissionRepoPort } from "./ports.js";
|
|
6
|
+
export interface RegisterFormNotifySubscriberDeps {
|
|
7
|
+
bus: EventBusPort;
|
|
8
|
+
sender: EmailAddress;
|
|
9
|
+
logger: Pick<Logger, 'warn'>;
|
|
10
|
+
mailer: MailerPort;
|
|
11
|
+
formDefinitionRepo: FormDefinitionRepoPort;
|
|
12
|
+
formSubmissionRepo: FormSubmissionRepoPort;
|
|
13
|
+
}
|
|
14
|
+
export declare function registerFormNotifySubscriber(deps: RegisterFormNotifySubscriberDeps): Promise<() => Promise<void>>;
|
|
15
|
+
//# sourceMappingURL=notify-subscriber.d.ts.map
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Domain behavior owns its event contract; reading a host manifest back would invert dependency flow.
|
|
2
|
+
const FORM_SUBMISSION_RECEIVED_TOPIC = "form.submission.received";
|
|
3
|
+
export async function registerFormNotifySubscriber(deps) {
|
|
4
|
+
return deps.bus.subscribe({ eventName: FORM_SUBMISSION_RECEIVED_TOPIC,
|
|
5
|
+
handler: async (event) => {
|
|
6
|
+
try {
|
|
7
|
+
const { workspaceId, formDefinitionId, submissionId } = event.payload;
|
|
8
|
+
const definition = await deps.formDefinitionRepo.findById({ workspaceId, id: formDefinitionId });
|
|
9
|
+
if (!definition || !definition.notify.enabled || definition.notify.recipients.length === 0) {
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
const submission = await deps.formSubmissionRepo.findById({ workspaceId, id: submissionId });
|
|
13
|
+
if (!submission)
|
|
14
|
+
return;
|
|
15
|
+
for (const recipient of definition.notify.recipients) {
|
|
16
|
+
try {
|
|
17
|
+
const result = await deps.mailer.send({
|
|
18
|
+
message: {
|
|
19
|
+
workspaceId,
|
|
20
|
+
to: { email: recipient },
|
|
21
|
+
from: deps.sender,
|
|
22
|
+
subject: `New submission: ${definition.name}`,
|
|
23
|
+
text: JSON.stringify(submission.data),
|
|
24
|
+
},
|
|
25
|
+
options: {
|
|
26
|
+
// Include the recipient so a shared dedup ledger never suppresses a sibling send.
|
|
27
|
+
idempotencyKey: `forms:notify:${submissionId}:${recipient}`,
|
|
28
|
+
workspaceId,
|
|
29
|
+
sourceContext: { module: "forms", ref: formDefinitionId },
|
|
30
|
+
purpose: "transactional",
|
|
31
|
+
// Background notifications use the host mailer's durable-outbox readiness gate,
|
|
32
|
+
// rather than the interactive send lane, when production delivery requires it.
|
|
33
|
+
lane: "notification",
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
if (!result.ok) {
|
|
37
|
+
warn(deps.logger, `[forms:notify] mail send failed for submission '${submissionId}' recipient '${recipient}': ${result.errorCode} (${result.message})`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
// A send failure is terminal for this delivery: log, never retry inline or alter
|
|
42
|
+
// the persisted submission, and continue so the other recipients can still receive it.
|
|
43
|
+
warn(deps.logger, `[forms:notify] mail send threw for submission '${submissionId}' recipient '${recipient}':`, err);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
// Repository failures must not escape the bus's subscriber loop and break sibling handlers.
|
|
49
|
+
warn(deps.logger, "[forms:notify] subscriber failed:", err);
|
|
50
|
+
}
|
|
51
|
+
} });
|
|
52
|
+
}
|
|
53
|
+
/** Failure reporting is isolated too: a logger cannot interrupt sibling event subscribers. */
|
|
54
|
+
function warn(logger, message, error) {
|
|
55
|
+
try {
|
|
56
|
+
logger.warn({ message }, error === undefined ? {} : { error });
|
|
57
|
+
}
|
|
58
|
+
catch { /* Host logging failure is terminal. */ }
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=notify-subscriber.js.map
|
package/dist/ports.d.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/** Forms persistence and outbound effect contracts. Concrete repositories, HTTP routing, tool wiring and transport implementations belong to consumers. */
|
|
2
|
+
import type { UUID } from "@jini-ai/core/primitives";
|
|
3
|
+
import type { FormDefinitionRecord, FormSubmissionPage, FormSubmissionRecord } from "./types.js";
|
|
4
|
+
/** Definitions and submissions have distinct lifecycles and therefore separate ports.
|
|
5
|
+
* Deletion belongs to the host's Trash/purge workflow, so neither persistence port exposes delete.
|
|
6
|
+
* Reads must hide trashed rows at the repository boundary: public submitters, widget resolvers
|
|
7
|
+
* and other direct consumers must get not-found even if they forget an additional domain filter. */
|
|
8
|
+
export interface FormDefinitionRepoPort {
|
|
9
|
+
/** Reads and updates expose only live records; a trashed row still reserves its slug. */
|
|
10
|
+
findById(required: {
|
|
11
|
+
workspaceId: UUID;
|
|
12
|
+
id: UUID;
|
|
13
|
+
}): Promise<FormDefinitionRecord | null>;
|
|
14
|
+
findBySlug(required: {
|
|
15
|
+
workspaceId: UUID;
|
|
16
|
+
slug: string;
|
|
17
|
+
}): Promise<FormDefinitionRecord | null>;
|
|
18
|
+
list(required: {
|
|
19
|
+
workspaceId: UUID;
|
|
20
|
+
}): Promise<FormDefinitionRecord[]>;
|
|
21
|
+
/** The database unique index is the tie-break for (workspaceId, slug); callers translate collisions.
|
|
22
|
+
* A trashed row retains its slug so restoring it is lossless, and can therefore still conflict. */
|
|
23
|
+
create(record: FormDefinitionRecord): Promise<void>;
|
|
24
|
+
/** Update only a live row, affecting zero rows if it was trashed meanwhile. Only Trash restore
|
|
25
|
+
* may revive it. Keep create/update separate so genuine insert uniqueness races remain visible. */
|
|
26
|
+
update(record: FormDefinitionRecord): Promise<void>;
|
|
27
|
+
/** Deliberately trash-blind: both live and trashed rows reserve a slug. Duplication must not
|
|
28
|
+
* propose a trashed slug as available and then collide with the database unique index. */
|
|
29
|
+
isSlugTaken(required: {
|
|
30
|
+
workspaceId: UUID;
|
|
31
|
+
slug: string;
|
|
32
|
+
}): Promise<boolean>;
|
|
33
|
+
}
|
|
34
|
+
export interface FormSubmissionRepoPort {
|
|
35
|
+
findById(required: {
|
|
36
|
+
workspaceId: UUID;
|
|
37
|
+
id: UUID;
|
|
38
|
+
}): Promise<FormSubmissionRecord | null>;
|
|
39
|
+
create(record: FormSubmissionRecord): Promise<void>;
|
|
40
|
+
/** Newest first, submittedAt descending then id descending for ties. The opaque cursor resumes
|
|
41
|
+
* after the last returned row; callers validate limit (1..100) before reaching persistence. */
|
|
42
|
+
listByDefinition(required: {
|
|
43
|
+
workspaceId: UUID;
|
|
44
|
+
formDefinitionId: UUID;
|
|
45
|
+
limit: number;
|
|
46
|
+
}, optional?: {
|
|
47
|
+
cursor?: string | null;
|
|
48
|
+
}): Promise<FormSubmissionPage>;
|
|
49
|
+
}
|
|
50
|
+
export interface RateLimiterPort {
|
|
51
|
+
check(required: {
|
|
52
|
+
key: string;
|
|
53
|
+
}): {
|
|
54
|
+
allowed: true;
|
|
55
|
+
} | {
|
|
56
|
+
allowed: false;
|
|
57
|
+
retryAfterSeconds: number;
|
|
58
|
+
} | Promise<{
|
|
59
|
+
allowed: true;
|
|
60
|
+
} | {
|
|
61
|
+
allowed: false;
|
|
62
|
+
retryAfterSeconds: number;
|
|
63
|
+
}>;
|
|
64
|
+
}
|
|
65
|
+
export interface FormOutboxPort {
|
|
66
|
+
enqueue(event: import("@jini-ai/cms/core").DomainEvent): Promise<void>;
|
|
67
|
+
}
|
|
68
|
+
/** Bound to the host's outbox/bus/clock; dispatch is kicked off without awaiting delivery. */
|
|
69
|
+
export interface OutboxDispatcherPort {
|
|
70
|
+
dispatch(required: Record<string, never>): Promise<void>;
|
|
71
|
+
}
|
|
72
|
+
export interface EmailAddress {
|
|
73
|
+
email: string;
|
|
74
|
+
name?: string;
|
|
75
|
+
}
|
|
76
|
+
export interface OutboundEmail {
|
|
77
|
+
workspaceId: UUID;
|
|
78
|
+
to: EmailAddress;
|
|
79
|
+
from: EmailAddress;
|
|
80
|
+
subject: string;
|
|
81
|
+
text: string;
|
|
82
|
+
}
|
|
83
|
+
export interface MailerSendOptions {
|
|
84
|
+
idempotencyKey: string;
|
|
85
|
+
workspaceId: UUID;
|
|
86
|
+
sourceContext: {
|
|
87
|
+
module: string;
|
|
88
|
+
ref: string;
|
|
89
|
+
};
|
|
90
|
+
purpose: "transactional";
|
|
91
|
+
lane: "notification";
|
|
92
|
+
}
|
|
93
|
+
export type MailerSendResult = {
|
|
94
|
+
ok: true;
|
|
95
|
+
providerMessageId: string;
|
|
96
|
+
acceptedAt: string;
|
|
97
|
+
} | {
|
|
98
|
+
ok: false;
|
|
99
|
+
retryable: boolean;
|
|
100
|
+
errorCode: string;
|
|
101
|
+
message: string;
|
|
102
|
+
};
|
|
103
|
+
export interface MailerPort {
|
|
104
|
+
send(required: {
|
|
105
|
+
message: OutboundEmail;
|
|
106
|
+
options: MailerSendOptions;
|
|
107
|
+
}): Promise<MailerSendResult>;
|
|
108
|
+
}
|
|
109
|
+
/** Generic audited mutation contract supplied by the host composition root. */
|
|
110
|
+
export type FormCommandExecutorPort = typeof import("@jini-ai/cms/core").executeCommand;
|
|
111
|
+
//# sourceMappingURL=ports.d.ts.map
|
package/dist/ports.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Builds a per-source, per-form key; rate-limit windows and quotas belong to the host. */
|
|
2
|
+
/** Include the form id so a visitor submitting to two forms from the same IP is never
|
|
3
|
+
* cross-throttled by the other form's submissions. */
|
|
4
|
+
export declare function buildFormsRateLimitKey({ sourceIp, formDefinitionId }: {
|
|
5
|
+
sourceIp: string;
|
|
6
|
+
formDefinitionId: string;
|
|
7
|
+
}): string;
|
|
8
|
+
//# sourceMappingURL=rate-limit-key.d.ts.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Builds a per-source, per-form key; rate-limit windows and quotas belong to the host. */
|
|
2
|
+
/** Include the form id so a visitor submitting to two forms from the same IP is never
|
|
3
|
+
* cross-throttled by the other form's submissions. */
|
|
4
|
+
export function buildFormsRateLimitKey({ sourceIp, formDefinitionId }) {
|
|
5
|
+
return `${sourceIp}:${formDefinitionId}`;
|
|
6
|
+
}
|
|
7
|
+
//# sourceMappingURL=rate-limit-key.js.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Logger } from "@jini-ai/core/primitives";
|
|
2
|
+
import type { RateLimiterPort, FormOutboxPort, OutboxDispatcherPort } from "./ports.js";
|
|
3
|
+
import type { Clock, IdGenerator, UUID } from "@jini-ai/core/primitives";
|
|
4
|
+
import type { FormDefinitionRepoPort, FormSubmissionRepoPort } from "./ports.js";
|
|
5
|
+
export interface SubmitFormDeps {
|
|
6
|
+
definitionRepo: FormDefinitionRepoPort;
|
|
7
|
+
submissionRepo: FormSubmissionRepoPort;
|
|
8
|
+
outbox: FormOutboxPort;
|
|
9
|
+
dispatcher: OutboxDispatcherPort;
|
|
10
|
+
logger: Pick<Logger, 'warn'>;
|
|
11
|
+
clock: Clock;
|
|
12
|
+
idGen: IdGenerator;
|
|
13
|
+
rateLimiter: RateLimiterPort;
|
|
14
|
+
}
|
|
15
|
+
export interface SubmitFormInput {
|
|
16
|
+
workspaceId: UUID;
|
|
17
|
+
slug: string;
|
|
18
|
+
body: Record<string, unknown>;
|
|
19
|
+
sourceIp: string;
|
|
20
|
+
}
|
|
21
|
+
export interface SubmitFormRequired {
|
|
22
|
+
deps: SubmitFormDeps;
|
|
23
|
+
input: SubmitFormInput;
|
|
24
|
+
}
|
|
25
|
+
export declare function submitForm(required: SubmitFormRequired): Promise<{
|
|
26
|
+
status: "accepted";
|
|
27
|
+
}>;
|
|
28
|
+
//# sourceMappingURL=submit-service.d.ts.map
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { nowIso as kernelNowIso } from "@jini-ai/core/primitives";
|
|
2
|
+
/** Anonymous submission path: active lookup, honeypot, validation, rate check, persistence, event enqueue, then background dispatch. Persistence and enqueue remain separate awaited effects, matching the source contract. */
|
|
3
|
+
import { buildFormsRateLimitKey } from "./rate-limit-key.js";
|
|
4
|
+
import { FormDefinitionNotFoundError, FormRateLimitExceededError, FormSubmissionValidationError, } from "./errors.js";
|
|
5
|
+
import { isHoneypotTripped, validateSubmissionPayload } from "./forms.js";
|
|
6
|
+
const HONEYPOT_KEY = "_hp";
|
|
7
|
+
// Anonymous visitors have no actor/permission for an administrative command gateway; this public
|
|
8
|
+
// path instead owns validation, throttling and durable submission/event persistence directly.
|
|
9
|
+
export async function submitForm(required) {
|
|
10
|
+
const { deps, input } = required;
|
|
11
|
+
// Missing and disabled slugs are deliberately indistinguishable to public callers.
|
|
12
|
+
const definition = await deps.definitionRepo.findBySlug({ workspaceId: input.workspaceId, slug: input.slug });
|
|
13
|
+
if (!definition || definition.status !== "active") {
|
|
14
|
+
throw new FormDefinitionNotFoundError({ message: `form '${input.slug}' was not found` });
|
|
15
|
+
}
|
|
16
|
+
// Discard before validation, rate limiting or writes; a bot sees the same accepted response
|
|
17
|
+
// without consuming capacity or creating a submission/event.
|
|
18
|
+
if (isHoneypotTripped({ hp: input.body[HONEYPOT_KEY] })) {
|
|
19
|
+
return { status: "accepted" };
|
|
20
|
+
}
|
|
21
|
+
const validation = validateSubmissionPayload({ definition, body: input.body });
|
|
22
|
+
if (!validation.valid) {
|
|
23
|
+
throw new FormSubmissionValidationError({ message: "submission failed field validation", fieldErrors: validation.fieldErrors });
|
|
24
|
+
}
|
|
25
|
+
// Scope by both IP and form so one client's different forms cannot cross-throttle each other.
|
|
26
|
+
const rateLimitKey = buildFormsRateLimitKey({ sourceIp: input.sourceIp, formDefinitionId: definition.id });
|
|
27
|
+
const rateLimitResult = await deps.rateLimiter.check({ key: rateLimitKey });
|
|
28
|
+
if (!rateLimitResult.allowed) {
|
|
29
|
+
throw new FormRateLimitExceededError({ message: `rate limit exceeded for form '${definition.id}'`, retryAfterSeconds: rateLimitResult.retryAfterSeconds });
|
|
30
|
+
}
|
|
31
|
+
const now = kernelNowIso({ clock: deps.clock });
|
|
32
|
+
const submissionId = deps.idGen.newId();
|
|
33
|
+
const submission = {
|
|
34
|
+
id: submissionId,
|
|
35
|
+
workspaceId: input.workspaceId,
|
|
36
|
+
formDefinitionId: definition.id,
|
|
37
|
+
data: validation.data,
|
|
38
|
+
sourceIp: input.sourceIp,
|
|
39
|
+
submittedAt: now,
|
|
40
|
+
};
|
|
41
|
+
await deps.submissionRepo.create(submission);
|
|
42
|
+
// Only a persisted accepted submission gets this event; honeypot discards emit nothing.
|
|
43
|
+
await deps.outbox.enqueue({
|
|
44
|
+
id: deps.idGen.newId(),
|
|
45
|
+
name: "form.submission.received",
|
|
46
|
+
occurredAt: now,
|
|
47
|
+
workspaceId: input.workspaceId,
|
|
48
|
+
aggregateId: submissionId,
|
|
49
|
+
payload: { workspaceId: input.workspaceId, formDefinitionId: definition.id, submissionId },
|
|
50
|
+
});
|
|
51
|
+
// Dispatch failures cannot affect an accepted submission or create an unhandled rejection.
|
|
52
|
+
// Never await delivery here: a subscriber sends mail, so awaiting it would reintroduce the
|
|
53
|
+
// response-blocking bug. Persistence/enqueue are awaited; outbox drainage remains background work.
|
|
54
|
+
void Promise.resolve().then(() => deps.dispatcher.dispatch({})).catch((error) => {
|
|
55
|
+
try {
|
|
56
|
+
deps.logger.warn({ message: "form outbox dispatch failed" }, { error });
|
|
57
|
+
}
|
|
58
|
+
catch { /* Logging must not reject background work. */ }
|
|
59
|
+
});
|
|
60
|
+
return { status: "accepted" };
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=submit-service.js.map
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { UUID } from "@jini-ai/core/primitives";
|
|
2
|
+
export type FieldType = "text" | "email" | "textarea" | "checkbox";
|
|
3
|
+
export type FormDefinitionStatus = "active" | "disabled";
|
|
4
|
+
export interface FieldDescriptor {
|
|
5
|
+
id: string;
|
|
6
|
+
label: string;
|
|
7
|
+
type: FieldType;
|
|
8
|
+
required: boolean;
|
|
9
|
+
maxLength?: number | null;
|
|
10
|
+
/** Length-bounded and HTML-escaped at rendering; class names are inert after escaping. */
|
|
11
|
+
className?: string;
|
|
12
|
+
/** Attribute names require a closed allowlist: escaping a name cannot make it safe.
|
|
13
|
+
* Values remain plain strings and must be HTML-escaped by the renderer. */
|
|
14
|
+
attributes?: Record<string, string>;
|
|
15
|
+
}
|
|
16
|
+
export interface NotifyConfig {
|
|
17
|
+
enabled: boolean;
|
|
18
|
+
recipients: string[];
|
|
19
|
+
}
|
|
20
|
+
export interface FormDefinitionRecord {
|
|
21
|
+
id: UUID;
|
|
22
|
+
workspaceId: UUID;
|
|
23
|
+
name: string;
|
|
24
|
+
slug: string;
|
|
25
|
+
fields: FieldDescriptor[];
|
|
26
|
+
notify: NotifyConfig;
|
|
27
|
+
status: FormDefinitionStatus;
|
|
28
|
+
createdAt: string;
|
|
29
|
+
updatedAt: string;
|
|
30
|
+
/** Compare-and-set counter for trash transitions; never an admin-editable field.
|
|
31
|
+
* Every record constructor, including fixtures, must supply it. */
|
|
32
|
+
version: number;
|
|
33
|
+
}
|
|
34
|
+
export interface FormSubmissionRecord {
|
|
35
|
+
id: UUID;
|
|
36
|
+
workspaceId: UUID;
|
|
37
|
+
formDefinitionId: UUID;
|
|
38
|
+
data: Record<string, string | boolean>;
|
|
39
|
+
sourceIp: string;
|
|
40
|
+
submittedAt: string;
|
|
41
|
+
}
|
|
42
|
+
export interface FormSubmissionPage {
|
|
43
|
+
items: FormSubmissionRecord[];
|
|
44
|
+
nextCursor: string | null;
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=types.d.ts.map
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/** Audited definition writes through the CMS command gateway. Host permissions and reserved slugs are explicit policies; notify, idempotency and optional outbox wiring live in the second argument. */
|
|
2
|
+
import type { ChangeSetRepoPort } from "@jini-ai/cms/core";
|
|
3
|
+
import type { Clock, IdGenerator, UUID } from "@jini-ai/core/primitives";
|
|
4
|
+
import type { AuthorizeFn, CommandActor } from "@jini-ai/cms/core";
|
|
5
|
+
import type { FormCommandExecutorPort, FormDefinitionRepoPort } from "./ports.js";
|
|
6
|
+
import type { FieldDescriptor, FormDefinitionRecord, FormDefinitionStatus, NotifyConfig } from "./types.js";
|
|
7
|
+
export interface FormWriteServiceDeps {
|
|
8
|
+
/** Host-bound audited command gateway; no runtime CMS implementation is imported. */
|
|
9
|
+
executeCommand: FormCommandExecutorPort;
|
|
10
|
+
repo: FormDefinitionRepoPort;
|
|
11
|
+
clock: Clock;
|
|
12
|
+
idGen: IdGenerator;
|
|
13
|
+
changeSets: ChangeSetRepoPort;
|
|
14
|
+
permission: string;
|
|
15
|
+
reservedSlugs: ReadonlySet<string>;
|
|
16
|
+
authorize: AuthorizeFn;
|
|
17
|
+
}
|
|
18
|
+
export declare const MAX_NOTIFY_RECIPIENTS = 10;
|
|
19
|
+
export declare const SLUG_PATTERN: RegExp;
|
|
20
|
+
export declare const MAX_NAME_LENGTH = 200;
|
|
21
|
+
export interface CreateFormDefinitionRequired {
|
|
22
|
+
deps: FormWriteServiceDeps;
|
|
23
|
+
input: {
|
|
24
|
+
workspaceId: UUID;
|
|
25
|
+
actor: CommandActor;
|
|
26
|
+
name: string;
|
|
27
|
+
slug: string;
|
|
28
|
+
fields: FieldDescriptor[];
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* All definition writes pass through the injected command gateway for authorization, audit
|
|
33
|
+
* capture and optional change-set event enqueue. There is no delete here: permanent removal
|
|
34
|
+
* belongs to a separate trash purge, and the definition repository exposes no delete method.
|
|
35
|
+
* Slug uniqueness is enforced by the repository's unique index, avoiding a racy pre-insert check;
|
|
36
|
+
* repository slug-conflict errors propagate unchanged from the mutation.
|
|
37
|
+
*/
|
|
38
|
+
export declare function createFormDefinition(required: CreateFormDefinitionRequired, optional?: CreateFormDefinitionOptional): Promise<{
|
|
39
|
+
definition: FormDefinitionRecord;
|
|
40
|
+
}>;
|
|
41
|
+
export interface UpdateFormDefinitionRequired {
|
|
42
|
+
deps: FormWriteServiceDeps;
|
|
43
|
+
input: {
|
|
44
|
+
workspaceId: UUID;
|
|
45
|
+
actor: CommandActor;
|
|
46
|
+
formId: UUID;
|
|
47
|
+
patch: {
|
|
48
|
+
name?: string;
|
|
49
|
+
fields?: FieldDescriptor[];
|
|
50
|
+
notify?: NotifyConfig;
|
|
51
|
+
slug?: string;
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export declare function updateFormDefinition(required: UpdateFormDefinitionRequired, optional?: FormWriteOptional): Promise<{
|
|
56
|
+
definition: FormDefinitionRecord;
|
|
57
|
+
}>;
|
|
58
|
+
export interface SetFormDefinitionStatusRequired {
|
|
59
|
+
deps: FormWriteServiceDeps;
|
|
60
|
+
input: {
|
|
61
|
+
workspaceId: UUID;
|
|
62
|
+
actor: CommandActor;
|
|
63
|
+
formId: UUID;
|
|
64
|
+
status: FormDefinitionStatus;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/** Status changes preserve the row; deletion requires the separate trash lifecycle. */
|
|
68
|
+
export declare function setFormDefinitionStatus(required: SetFormDefinitionStatusRequired, optional?: FormWriteOptional): Promise<{
|
|
69
|
+
definition: FormDefinitionRecord;
|
|
70
|
+
}>;
|
|
71
|
+
export interface FormWriteOptional {
|
|
72
|
+
idempotencyKey?: string;
|
|
73
|
+
outbox?: import("@jini-ai/cms/core").OutboxPort;
|
|
74
|
+
}
|
|
75
|
+
export interface CreateFormDefinitionOptional extends FormWriteOptional {
|
|
76
|
+
notify?: NotifyConfig;
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=write-service.d.ts.map
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { nowIso as kernelNowIso } from "@jini-ai/core/primitives";
|
|
2
|
+
import { FormDefinitionNotFoundError, FormFieldValidationError } from "./errors.js";
|
|
3
|
+
import { validateFieldDescriptors } from "./forms.js";
|
|
4
|
+
// Export validation bounds so host tool schemas can share them rather than drift from the service.
|
|
5
|
+
export const MAX_NOTIFY_RECIPIENTS = 10;
|
|
6
|
+
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
7
|
+
export const SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
8
|
+
const MIN_NAME_LENGTH = 1;
|
|
9
|
+
export const MAX_NAME_LENGTH = 200;
|
|
10
|
+
function defaultNotify() {
|
|
11
|
+
return { enabled: false, recipients: [] };
|
|
12
|
+
}
|
|
13
|
+
function validateNotify(notify) {
|
|
14
|
+
const resolved = notify ?? defaultNotify();
|
|
15
|
+
if (!Array.isArray(resolved.recipients)) {
|
|
16
|
+
throw new FormFieldValidationError({ message: "notify.recipients must be an array", fieldErrors: [
|
|
17
|
+
{ field: "notify.recipients", reason: "must be an array" },
|
|
18
|
+
] });
|
|
19
|
+
}
|
|
20
|
+
if (typeof resolved.enabled !== "boolean") {
|
|
21
|
+
throw new FormFieldValidationError({ message: "notify.enabled must be a boolean", fieldErrors: [
|
|
22
|
+
{ field: "notify.enabled", reason: "must be a boolean" },
|
|
23
|
+
] });
|
|
24
|
+
}
|
|
25
|
+
if (resolved.recipients.length > MAX_NOTIFY_RECIPIENTS) {
|
|
26
|
+
throw new FormFieldValidationError({ message: `notify.recipients may not exceed ${MAX_NOTIFY_RECIPIENTS} addresses`, fieldErrors: [{ field: "notify.recipients", reason: `at most ${MAX_NOTIFY_RECIPIENTS} recipients are allowed` }] });
|
|
27
|
+
}
|
|
28
|
+
for (const recipient of resolved.recipients) {
|
|
29
|
+
if (!EMAIL_PATTERN.test(recipient)) {
|
|
30
|
+
throw new FormFieldValidationError({ message: `'${recipient}' is not a valid email address`, fieldErrors: [
|
|
31
|
+
{ field: "notify.recipients", reason: `'${recipient}' is not a valid email address` },
|
|
32
|
+
] });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return resolved;
|
|
36
|
+
}
|
|
37
|
+
function validateNameAndSlug(name, slug, reservedSlugs) {
|
|
38
|
+
if (name.length < MIN_NAME_LENGTH || name.length > MAX_NAME_LENGTH) {
|
|
39
|
+
throw new FormFieldValidationError({ message: `name must be ${MIN_NAME_LENGTH}-${MAX_NAME_LENGTH} characters`, fieldErrors: [
|
|
40
|
+
{ field: "name", reason: `must be ${MIN_NAME_LENGTH}-${MAX_NAME_LENGTH} characters` },
|
|
41
|
+
] });
|
|
42
|
+
}
|
|
43
|
+
if (!SLUG_PATTERN.test(slug)) {
|
|
44
|
+
throw new FormFieldValidationError({ message: "slug must match ^[a-z0-9][a-z0-9-]{0,63}$", fieldErrors: [
|
|
45
|
+
{ field: "slug", reason: "must match ^[a-z0-9][a-z0-9-]{0,63}$" },
|
|
46
|
+
] });
|
|
47
|
+
}
|
|
48
|
+
if (reservedSlugs.has(slug)) {
|
|
49
|
+
throw new FormFieldValidationError({ message: `slug '${slug}' is reserved`, fieldErrors: [
|
|
50
|
+
{ field: "slug", reason: `'${slug}' is reserved by the host` },
|
|
51
|
+
] });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function assertValidFields(fields) {
|
|
55
|
+
const validation = validateFieldDescriptors({ fields });
|
|
56
|
+
if (!validation.valid) {
|
|
57
|
+
throw new FormFieldValidationError({ message: "one or more field descriptors are invalid", fieldErrors: validation.fieldErrors });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* All definition writes pass through the injected command gateway for authorization, audit
|
|
62
|
+
* capture and optional change-set event enqueue. There is no delete here: permanent removal
|
|
63
|
+
* belongs to a separate trash purge, and the definition repository exposes no delete method.
|
|
64
|
+
* Slug uniqueness is enforced by the repository's unique index, avoiding a racy pre-insert check;
|
|
65
|
+
* repository slug-conflict errors propagate unchanged from the mutation.
|
|
66
|
+
*/
|
|
67
|
+
export async function createFormDefinition(required, optional = {}) {
|
|
68
|
+
const { deps, input } = required;
|
|
69
|
+
validateNameAndSlug(input.name, input.slug, deps.reservedSlugs);
|
|
70
|
+
assertValidFields(input.fields);
|
|
71
|
+
const notify = validateNotify(optional.notify);
|
|
72
|
+
const definitionId = deps.idGen.newId();
|
|
73
|
+
const { result } = await deps.executeCommand({
|
|
74
|
+
deps: {
|
|
75
|
+
clock: deps.clock,
|
|
76
|
+
idGen: deps.idGen,
|
|
77
|
+
changeSets: deps.changeSets,
|
|
78
|
+
outbox: optional.outbox,
|
|
79
|
+
authorize: deps.authorize,
|
|
80
|
+
},
|
|
81
|
+
command: {
|
|
82
|
+
workspaceId: input.workspaceId,
|
|
83
|
+
actor: input.actor,
|
|
84
|
+
summary: `Create form definition '${input.slug}'`,
|
|
85
|
+
idempotencyKey: optional.idempotencyKey,
|
|
86
|
+
permission: deps.permission,
|
|
87
|
+
},
|
|
88
|
+
mutation: {
|
|
89
|
+
entityType: "form_definition",
|
|
90
|
+
entityId: definitionId,
|
|
91
|
+
operation: "create",
|
|
92
|
+
captureInverse: async () => null,
|
|
93
|
+
execute: async () => {
|
|
94
|
+
const now = kernelNowIso({ clock: deps.clock });
|
|
95
|
+
const definition = {
|
|
96
|
+
id: definitionId,
|
|
97
|
+
workspaceId: input.workspaceId,
|
|
98
|
+
name: input.name,
|
|
99
|
+
slug: input.slug,
|
|
100
|
+
fields: input.fields,
|
|
101
|
+
notify,
|
|
102
|
+
status: "active",
|
|
103
|
+
createdAt: now,
|
|
104
|
+
updatedAt: now,
|
|
105
|
+
// Start the optimistic-concurrency version at 1 for the trash compare-and-set lifecycle.
|
|
106
|
+
version: 1,
|
|
107
|
+
};
|
|
108
|
+
await deps.repo.create(definition);
|
|
109
|
+
return { definition };
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
115
|
+
export async function updateFormDefinition(required, optional = {}) {
|
|
116
|
+
const { deps, input } = required;
|
|
117
|
+
const { result } = await deps.executeCommand({
|
|
118
|
+
deps: {
|
|
119
|
+
clock: deps.clock,
|
|
120
|
+
idGen: deps.idGen,
|
|
121
|
+
changeSets: deps.changeSets,
|
|
122
|
+
outbox: optional.outbox,
|
|
123
|
+
authorize: deps.authorize,
|
|
124
|
+
},
|
|
125
|
+
command: {
|
|
126
|
+
workspaceId: input.workspaceId,
|
|
127
|
+
actor: input.actor,
|
|
128
|
+
summary: `Update form definition '${input.formId}'`,
|
|
129
|
+
idempotencyKey: optional.idempotencyKey,
|
|
130
|
+
permission: deps.permission,
|
|
131
|
+
},
|
|
132
|
+
mutation: {
|
|
133
|
+
entityType: "form_definition",
|
|
134
|
+
entityId: input.formId,
|
|
135
|
+
operation: "update",
|
|
136
|
+
captureInverse: async () => null,
|
|
137
|
+
execute: async () => {
|
|
138
|
+
const existing = await deps.repo.findById({ workspaceId: input.workspaceId, id: input.formId });
|
|
139
|
+
if (!existing) {
|
|
140
|
+
throw new FormDefinitionNotFoundError({ message: `form definition '${input.formId}' was not found` });
|
|
141
|
+
}
|
|
142
|
+
const name = input.patch.name !== undefined ? input.patch.name : existing.name;
|
|
143
|
+
if (input.patch.name !== undefined) {
|
|
144
|
+
validateNameAndSlug(name, existing.slug, deps.reservedSlugs);
|
|
145
|
+
}
|
|
146
|
+
let fields = existing.fields;
|
|
147
|
+
if (input.patch.fields !== undefined) {
|
|
148
|
+
assertValidFields(input.patch.fields);
|
|
149
|
+
const existingIds = new Set(existing.fields.map((f) => f.id));
|
|
150
|
+
const newIds = new Set(input.patch.fields.map((f) => f.id));
|
|
151
|
+
const missing = [...existingIds].filter((id) => !newIds.has(id));
|
|
152
|
+
if (missing.length > 0) {
|
|
153
|
+
throw new FormFieldValidationError({ message: `patch omits existing field id(s): ${missing.join(", ")} (behavior.spec.md §1.2)`, fieldErrors: missing.map((id) => ({ field: id, reason: "existing field ids cannot be removed" })) });
|
|
154
|
+
}
|
|
155
|
+
fields = input.patch.fields;
|
|
156
|
+
}
|
|
157
|
+
const notify = input.patch.notify !== undefined ? validateNotify(input.patch.notify) : existing.notify;
|
|
158
|
+
const definition = {
|
|
159
|
+
...existing,
|
|
160
|
+
name,
|
|
161
|
+
fields,
|
|
162
|
+
notify,
|
|
163
|
+
slug: existing.slug,
|
|
164
|
+
updatedAt: kernelNowIso({ clock: deps.clock }),
|
|
165
|
+
};
|
|
166
|
+
await deps.repo.update(definition);
|
|
167
|
+
return { definition };
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
return result;
|
|
172
|
+
}
|
|
173
|
+
/** Status changes preserve the row; deletion requires the separate trash lifecycle. */
|
|
174
|
+
export async function setFormDefinitionStatus(required, optional = {}) {
|
|
175
|
+
const { deps, input } = required;
|
|
176
|
+
const { result } = await deps.executeCommand({
|
|
177
|
+
deps: {
|
|
178
|
+
clock: deps.clock,
|
|
179
|
+
idGen: deps.idGen,
|
|
180
|
+
changeSets: deps.changeSets,
|
|
181
|
+
outbox: optional.outbox,
|
|
182
|
+
authorize: deps.authorize,
|
|
183
|
+
},
|
|
184
|
+
command: {
|
|
185
|
+
workspaceId: input.workspaceId,
|
|
186
|
+
actor: input.actor,
|
|
187
|
+
summary: `Set form definition '${input.formId}' status to '${input.status}'`,
|
|
188
|
+
idempotencyKey: optional.idempotencyKey,
|
|
189
|
+
permission: deps.permission,
|
|
190
|
+
},
|
|
191
|
+
mutation: {
|
|
192
|
+
entityType: "form_definition",
|
|
193
|
+
entityId: input.formId,
|
|
194
|
+
operation: "update",
|
|
195
|
+
captureInverse: async () => null,
|
|
196
|
+
execute: async () => {
|
|
197
|
+
const existing = await deps.repo.findById({ workspaceId: input.workspaceId, id: input.formId });
|
|
198
|
+
if (!existing) {
|
|
199
|
+
throw new FormDefinitionNotFoundError({ message: `form definition '${input.formId}' was not found` });
|
|
200
|
+
}
|
|
201
|
+
const definition = {
|
|
202
|
+
...existing,
|
|
203
|
+
status: input.status,
|
|
204
|
+
updatedAt: kernelNowIso({ clock: deps.clock }),
|
|
205
|
+
};
|
|
206
|
+
await deps.repo.update(definition);
|
|
207
|
+
return { definition };
|
|
208
|
+
},
|
|
209
|
+
},
|
|
210
|
+
});
|
|
211
|
+
return result;
|
|
212
|
+
}
|
|
213
|
+
//# sourceMappingURL=write-service.js.map
|