@nanobpm/urban 0.82.1 → 0.83.0

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.
@@ -13,6 +13,12 @@
13
13
 
14
14
  import type {
15
15
  EngineClient,
16
+ ElementInstanceState,
17
+ ElementInstanceSummary,
18
+ ElementInstanceFilter,
19
+ ElementInstanceWaitState,
20
+ ElementInstanceWaitStateFilter,
21
+ WaitStateType,
16
22
  EngineJob,
17
23
  FormSchema,
18
24
  JobHandler,
@@ -63,6 +69,222 @@ export function normalizeProcessInstanceState(
63
69
  }
64
70
  }
65
71
 
72
+ /** Map the engine's element-instance `state` onto the transport-agnostic
73
+ * {@link ElementInstanceState} union, or `undefined` for an unrecognized value (which the
74
+ * caller skips rather than surfacing a malformed row). Case-insensitive so a future casing
75
+ * tweak on the engine side doesn't silently drop element instances. Kept separate from
76
+ * {@link normalizeProcessInstanceState} — the two model distinct engine enums that only
77
+ * coincide today — so element and process state can diverge without a hidden coupling. */
78
+ export function normalizeElementInstanceState(
79
+ raw: unknown,
80
+ ): ElementInstanceState | undefined {
81
+ if (typeof raw !== "string") return undefined;
82
+ switch (raw.toUpperCase()) {
83
+ case "ACTIVE":
84
+ return "ACTIVE";
85
+ case "COMPLETED":
86
+ return "COMPLETED";
87
+ case "TERMINATED":
88
+ return "TERMINATED";
89
+ default:
90
+ return undefined;
91
+ }
92
+ }
93
+
94
+ /** Map the engine's wait-state `waitStateType` onto the transport-agnostic
95
+ * {@link WaitStateType} union, or `undefined` for an unrecognized value. Case-insensitive
96
+ * so a casing tweak doesn't silently drop parks. */
97
+ export function normalizeWaitStateType(raw: unknown): WaitStateType | undefined {
98
+ if (typeof raw !== "string") return undefined;
99
+ switch (raw.toUpperCase()) {
100
+ case "JOB":
101
+ return "JOB";
102
+ case "MESSAGE":
103
+ return "MESSAGE";
104
+ case "USER_TASK":
105
+ return "USER_TASK";
106
+ case "TIMER":
107
+ return "TIMER";
108
+ case "SIGNAL":
109
+ return "SIGNAL";
110
+ case "CONDITION":
111
+ return "CONDITION";
112
+ default:
113
+ return undefined;
114
+ }
115
+ }
116
+
117
+ /** A non-empty string form of an engine key/id, or `undefined` when absent/blank (including a
118
+ * whitespace-only string). Coerces a numeric key to a string (the engine may serialize a key
119
+ * either way) but never `String(...)`-coerces an arbitrary object into a garbage
120
+ * `"[object Object]"` id. The blank check trims, matching `getElementInstance`'s blank-key
121
+ * guard and the form-key presence helpers, so a `" "` key can never leak into a result. */
122
+ function presentEngineKey(value: unknown): string | undefined {
123
+ if (typeof value === "number") {
124
+ return Number.isFinite(value) ? String(value) : undefined;
125
+ }
126
+ if (typeof value !== "string") return undefined;
127
+ const trimmed = value.trim();
128
+ return trimmed === "" ? undefined : trimmed;
129
+ }
130
+
131
+ /** A required text field (a wait-state discriminator's `jobType`/`messageName`/`signalName`),
132
+ * or `undefined` when absent or blank — the caller skips the row rather than emitting a typed
133
+ * wait state carrying an empty required string. Returns the trimmed value, matching the
134
+ * presence rule used for keys, so surrounding whitespace can never leak into a result. */
135
+ function presentText(value: unknown): string | undefined {
136
+ if (typeof value !== "string") return undefined;
137
+ const trimmed = value.trim();
138
+ return trimmed === "" ? undefined : trimmed;
139
+ }
140
+
141
+ /** The element type carried on an element-instance/wait-state row. The Camunda SDK DTO calls
142
+ * it `type`; a plain REST/Rust-engine body may call it `elementType`. Accept either. */
143
+ function pickElementType(row: Record<string, unknown>): string | undefined {
144
+ return presentText(row.elementType) ?? presentText(row.type);
145
+ }
146
+
147
+ /** Map one engine element-instance row onto an {@link ElementInstanceSummary}, or `undefined`
148
+ * when the row is malformed (missing key/elementId/process instance, or an unrecognized
149
+ * state). The single source of truth both `searchElementInstances` and `getElementInstance`
150
+ * extract through, so the two cannot drift. */
151
+ export function mapElementInstanceRow(
152
+ row: Record<string, unknown>,
153
+ log: Log,
154
+ ): ElementInstanceSummary | undefined {
155
+ const elementInstanceKey = presentEngineKey(row.elementInstanceKey);
156
+ if (elementInstanceKey === undefined) {
157
+ log("warn", "skipping element instance with no key in engine response");
158
+ return undefined;
159
+ }
160
+ const processInstanceKey = presentEngineKey(row.processInstanceKey);
161
+ if (processInstanceKey === undefined) {
162
+ log("warn", "skipping element instance with no processInstanceKey in engine response", {
163
+ elementInstanceKey,
164
+ });
165
+ return undefined;
166
+ }
167
+ const elementId = typeof row.elementId === "string" && row.elementId.trim() !== ""
168
+ ? row.elementId.trim()
169
+ : undefined;
170
+ if (elementId === undefined) {
171
+ log("warn", "skipping element instance with no elementId in engine response", {
172
+ elementInstanceKey,
173
+ });
174
+ return undefined;
175
+ }
176
+ const state = normalizeElementInstanceState(row.state);
177
+ if (state === undefined) {
178
+ log("warn", "skipping element instance with unrecognized state", {
179
+ elementInstanceKey,
180
+ state: String(row.state),
181
+ });
182
+ return undefined;
183
+ }
184
+ const elementType = pickElementType(row);
185
+ return {
186
+ elementInstanceKey,
187
+ processInstanceKey,
188
+ elementId,
189
+ ...(elementType ? { elementType } : {}),
190
+ state,
191
+ };
192
+ }
193
+
194
+ /** Map one engine wait-state row onto an {@link ElementInstanceWaitState}, or `undefined`
195
+ * when the row is malformed (missing identity, or an unrecognized `waitStateType`). The
196
+ * Camunda SDK nests the park-specific fields under `details`; a plain REST body may inline
197
+ * them — read `details` first, then fall back to the row itself, so both wire shapes map. */
198
+ export function mapElementInstanceWaitStateRow(
199
+ row: Record<string, unknown>,
200
+ log: Log,
201
+ ): ElementInstanceWaitState | undefined {
202
+ const elementInstanceKey = presentEngineKey(row.elementInstanceKey);
203
+ const processInstanceKey = presentEngineKey(row.processInstanceKey);
204
+ const elementId = typeof row.elementId === "string" && row.elementId.trim() !== ""
205
+ ? row.elementId.trim()
206
+ : undefined;
207
+ if (elementInstanceKey === undefined || processInstanceKey === undefined || elementId === undefined) {
208
+ log("warn", "skipping element-instance wait state with incomplete identity in engine response");
209
+ return undefined;
210
+ }
211
+ const details = isRecord(row.details) ? row.details : row;
212
+ const waitStateType = normalizeWaitStateType(details.waitStateType ?? row.waitStateType);
213
+ if (waitStateType === undefined) {
214
+ log("warn", "skipping element-instance wait state with unrecognized waitStateType", {
215
+ elementInstanceKey,
216
+ waitStateType: String(details.waitStateType ?? row.waitStateType),
217
+ });
218
+ return undefined;
219
+ }
220
+ const elementType = pickElementType(row);
221
+ const base = {
222
+ elementInstanceKey,
223
+ processInstanceKey,
224
+ elementId,
225
+ ...(elementType ? { elementType } : {}),
226
+ };
227
+ switch (waitStateType) {
228
+ case "JOB": {
229
+ // `jobType` is the required discriminator of a JOB park; without it the row is malformed.
230
+ const jobType = presentText(details.jobType);
231
+ if (jobType === undefined) {
232
+ log("warn", "skipping JOB wait state with no jobType in engine response", {
233
+ elementInstanceKey,
234
+ });
235
+ return undefined;
236
+ }
237
+ const jobKey = presentEngineKey(details.jobKey);
238
+ return { ...base, waitStateType, jobType, ...(jobKey ? { jobKey } : {}) };
239
+ }
240
+ case "MESSAGE": {
241
+ // `messageName` is the required discriminator of a MESSAGE park.
242
+ const messageName = presentText(details.messageName);
243
+ if (messageName === undefined) {
244
+ log("warn", "skipping MESSAGE wait state with no messageName in engine response", {
245
+ elementInstanceKey,
246
+ });
247
+ return undefined;
248
+ }
249
+ const correlationKey = presentText(details.correlationKey);
250
+ return {
251
+ ...base,
252
+ waitStateType,
253
+ messageName,
254
+ ...(correlationKey ? { correlationKey } : {}),
255
+ };
256
+ }
257
+ case "USER_TASK": {
258
+ // `userTaskKey` is the required identity of a USER_TASK park; without it the row is
259
+ // malformed. Skip it (like the missing-identity guards above) rather than emit a typed
260
+ // wait state carrying an empty key that would break a downstream join.
261
+ const userTaskKey = presentEngineKey(details.taskKey ?? details.userTaskKey);
262
+ if (userTaskKey === undefined) {
263
+ log("warn", "skipping USER_TASK wait state with no userTaskKey in engine response", {
264
+ elementInstanceKey,
265
+ });
266
+ return undefined;
267
+ }
268
+ return { ...base, waitStateType, userTaskKey };
269
+ }
270
+ case "SIGNAL": {
271
+ // `signalName` is the required discriminator of a SIGNAL park.
272
+ const signalName = presentText(details.signalName);
273
+ if (signalName === undefined) {
274
+ log("warn", "skipping SIGNAL wait state with no signalName in engine response", {
275
+ elementInstanceKey,
276
+ });
277
+ return undefined;
278
+ }
279
+ return { ...base, waitStateType, signalName };
280
+ }
281
+ case "TIMER":
282
+ return { ...base, waitStateType };
283
+ case "CONDITION":
284
+ return { ...base, waitStateType };
285
+ }
286
+ }
287
+
66
288
  /** A job as delivered to a nano-sdk job handler: the frame fields plus the
67
289
  * acknowledgement actions the handler must call. */
68
290
  export interface NanoSdkActivatedJob {
@@ -146,6 +368,21 @@ export interface NanoSdkClient {
146
368
  consistency?: unknown,
147
369
  options?: unknown,
148
370
  ): Promise<Record<string, unknown>>;
371
+ searchElementInstances(
372
+ input: { filter?: Record<string, unknown>; page?: Record<string, unknown> },
373
+ consistency?: unknown,
374
+ options?: unknown,
375
+ ): Promise<Record<string, unknown>>;
376
+ searchElementInstanceWaitStates(
377
+ input: { filter?: Record<string, unknown>; page?: Record<string, unknown> },
378
+ consistency?: unknown,
379
+ options?: unknown,
380
+ ): Promise<Record<string, unknown>>;
381
+ getElementInstance(
382
+ input: { elementInstanceKey: string },
383
+ consistency?: unknown,
384
+ options?: unknown,
385
+ ): Promise<Record<string, unknown>>;
149
386
  createJobWorker(cfg: NanoSdkJobWorkerConfig): NanoSdkJobWorker;
150
387
  /** Stop every worker created on this client. Used on teardown to also drain a
151
388
  * REST-fallback worker, whose handle the `createJobWorker` proxy starts internally
@@ -355,6 +592,80 @@ export class SdkEngineClient implements EngineClient {
355
592
  });
356
593
  }
357
594
 
595
+ async searchElementInstances(
596
+ filter?: ElementInstanceFilter,
597
+ ): Promise<ElementInstanceSummary[]> {
598
+ // Mirror `searchProcessInstances`: build the engine filter from the transport-agnostic
599
+ // selectors, read at zero-wait consistency (an element-instance search is eventually
600
+ // consistent), and map each row through the single `mapElementInstanceRow` gate — which
601
+ // also `searchElementInstances`/`getElementInstance` share — dropping malformed rows.
602
+ const f: Record<string, unknown> = {};
603
+ if (filter?.processInstanceKey) f.processInstanceKey = filter.processInstanceKey;
604
+ if (filter?.elementId) f.elementId = filter.elementId;
605
+ if (filter?.state) f.state = filter.state;
606
+ const body = await this.client.searchElementInstances(
607
+ { filter: f },
608
+ { consistency: { waitUpToMs: 0 } },
609
+ );
610
+ const items = Array.isArray(body.items) ? body.items.filter(isRecord) : [];
611
+ return items.flatMap((it) => {
612
+ const mapped = mapElementInstanceRow(it, this.log);
613
+ return mapped ? [mapped] : [];
614
+ });
615
+ }
616
+
617
+ async searchElementInstanceWaitStates(
618
+ filter?: ElementInstanceWaitStateFilter,
619
+ ): Promise<ElementInstanceWaitState[]> {
620
+ // The wait-states search surfaces *every* park (job/message/timer/signal/condition/user
621
+ // task), not just user tasks. Same zero-wait read + per-row mapping-gate shape as
622
+ // `searchElementInstances`; the SDK nests park-specific fields under `details`, which
623
+ // `mapElementInstanceWaitStateRow` unwraps.
624
+ const f: Record<string, unknown> = {};
625
+ if (filter?.processInstanceKey) f.processInstanceKey = filter.processInstanceKey;
626
+ if (filter?.elementId) f.elementId = filter.elementId;
627
+ if (filter?.waitStateType) f.waitStateType = filter.waitStateType;
628
+ const body = await this.client.searchElementInstanceWaitStates(
629
+ { filter: f },
630
+ { consistency: { waitUpToMs: 0 } },
631
+ );
632
+ const items = Array.isArray(body.items) ? body.items.filter(isRecord) : [];
633
+ return items.flatMap((it) => {
634
+ const mapped = mapElementInstanceWaitStateRow(it, this.log);
635
+ return mapped ? [mapped] : [];
636
+ });
637
+ }
638
+
639
+ async getElementInstance(
640
+ elementInstanceKey: string,
641
+ ): Promise<ElementInstanceSummary | null> {
642
+ // A blank key can never address an element instance — short-circuit to null rather than
643
+ // issue a `GET /element-instances/` with an empty segment. Normalize the key up front (as
644
+ // `getForm` resolves a normalized identifier before fetching) so a padded-but-valid key
645
+ // like `" 5 "` addresses the same element instance rather than 404ing on the raw segment.
646
+ if (typeof elementInstanceKey !== "string" || elementInstanceKey.trim() === "") {
647
+ return null;
648
+ }
649
+ const key = elementInstanceKey.trim();
650
+ let body: Record<string, unknown>;
651
+ try {
652
+ body = await this.client.getElementInstance(
653
+ { elementInstanceKey: key },
654
+ { consistency: { waitUpToMs: 0 } },
655
+ );
656
+ } catch (err) {
657
+ // A 404 (no such element instance) is an expected "not found", not a fault — mirror
658
+ // `getForm`, which treats a failed fetch as absence (null) rather than propagating.
659
+ this.log("warn", "getElementInstance: engine fetch failed", {
660
+ elementInstanceKey: key,
661
+ err: err instanceof Error ? err.message : String(err),
662
+ });
663
+ return null;
664
+ }
665
+ if (!isRecord(body)) return null;
666
+ return mapElementInstanceRow(body, this.log) ?? null;
667
+ }
668
+
358
669
  async registerWorker(
359
670
  jobType: string,
360
671
  handler: JobHandler,
@@ -83,6 +83,12 @@ export type { ValidationIssue } from "./core/validate.ts";
83
83
  // Host + engine contracts (for custom hosts / tests)
84
84
  export type {
85
85
  EngineClient,
86
+ ElementInstanceState,
87
+ ElementInstanceSummary,
88
+ ElementInstanceFilter,
89
+ ElementInstanceWaitState,
90
+ ElementInstanceWaitStateFilter,
91
+ WaitStateType,
86
92
  EngineJob,
87
93
  FormSchema,
88
94
  HostContext,