@fire-spark/core 0.36.1 → 0.36.7
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/dist/index.d.ts +787 -8
- package/dist/index.js +3954 -133
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1928,7 +1928,7 @@ const MAX_RETRY_DELAY_MS = 1e4;
|
|
|
1928
1928
|
const DEFAULT_RETRY_DELAY_MS = 2e3;
|
|
1929
1929
|
/** Node refusals retried as is after `retry-after` (status → code). */
|
|
1930
1930
|
const RETRIED = /* @__PURE__ */ new Map([[503, "LOCAL_NODE_DRAINING"], [502, "LOCAL_CLOUD_UNREACHABLE"]]);
|
|
1931
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
1931
|
+
const listeners$1 = /* @__PURE__ */ new Set();
|
|
1932
1932
|
const downUntil = /* @__PURE__ */ new Map();
|
|
1933
1933
|
let current = null;
|
|
1934
1934
|
const defaultSleep$2 = (ms) => {
|
|
@@ -1941,9 +1941,9 @@ let sleepImpl = defaultSleep$2;
|
|
|
1941
1941
|
const getOrigin = () => current;
|
|
1942
1942
|
/** Called when the answering origin (cloud, local, fallback) changes. */
|
|
1943
1943
|
const onOriginChange = (listener) => {
|
|
1944
|
-
listeners.add(listener);
|
|
1944
|
+
listeners$1.add(listener);
|
|
1945
1945
|
return () => {
|
|
1946
|
-
listeners.delete(listener);
|
|
1946
|
+
listeners$1.delete(listener);
|
|
1947
1947
|
};
|
|
1948
1948
|
};
|
|
1949
1949
|
const report = (next) => {
|
|
@@ -1952,7 +1952,7 @@ const report = (next) => {
|
|
|
1952
1952
|
return;
|
|
1953
1953
|
}
|
|
1954
1954
|
current = next;
|
|
1955
|
-
for (const listener of listeners) listener(next);
|
|
1955
|
+
for (const listener of listeners$1) listener(next);
|
|
1956
1956
|
};
|
|
1957
1957
|
const originOf = (response) => {
|
|
1958
1958
|
return (response.headers?.get?.("x-firespark-origin"))?.toLowerCase() === "local" ? "local" : "cloud";
|
|
@@ -2152,7 +2152,7 @@ const decodeJwtSub = (token) => {
|
|
|
2152
2152
|
if (typeof payload?.sub !== "string" || !payload.sub) return null;
|
|
2153
2153
|
return payload.sub;
|
|
2154
2154
|
};
|
|
2155
|
-
const emit$
|
|
2155
|
+
const emit$2 = (customerId) => {
|
|
2156
2156
|
if (!state) return;
|
|
2157
2157
|
for (const listener of state.listeners) listener(customerId);
|
|
2158
2158
|
};
|
|
@@ -2217,7 +2217,7 @@ const clear = () => {
|
|
|
2217
2217
|
const had = dropDelegated();
|
|
2218
2218
|
state.accessToken = null;
|
|
2219
2219
|
state.expiresAt = 0;
|
|
2220
|
-
if (had) emit$
|
|
2220
|
+
if (had) emit$2(null);
|
|
2221
2221
|
};
|
|
2222
2222
|
const isDelegatedSession = () => {
|
|
2223
2223
|
return state?.delegated !== null && state?.delegated !== void 0;
|
|
@@ -2260,7 +2260,7 @@ const onCustomerChange = (listener) => {
|
|
|
2260
2260
|
const releaseDelegatedOrder = (orderId) => {
|
|
2261
2261
|
if (!state?.delegated || state.delegated.orderId !== orderId) return;
|
|
2262
2262
|
dropDelegated();
|
|
2263
|
-
emit$
|
|
2263
|
+
emit$2(null);
|
|
2264
2264
|
};
|
|
2265
2265
|
const issueToken = async (current) => {
|
|
2266
2266
|
if (current.getDirectToken) return current.getDirectToken();
|
|
@@ -2308,7 +2308,7 @@ const getAccessToken = async () => {
|
|
|
2308
2308
|
const issued = await issueToken(state);
|
|
2309
2309
|
state.accessToken = issued.access_token;
|
|
2310
2310
|
state.expiresAt = now + issued.expires_in * 1e3;
|
|
2311
|
-
if (rotated) emit$
|
|
2311
|
+
if (rotated) emit$2(null);
|
|
2312
2312
|
return state.accessToken;
|
|
2313
2313
|
};
|
|
2314
2314
|
const orderIdFromProof = (token) => {
|
|
@@ -2379,7 +2379,7 @@ const switchCustomer = async (input) => {
|
|
|
2379
2379
|
};
|
|
2380
2380
|
state.accessToken = result.access_token;
|
|
2381
2381
|
state.expiresAt = expiresAt;
|
|
2382
|
-
emit$
|
|
2382
|
+
emit$2(result.customer_id);
|
|
2383
2383
|
return result;
|
|
2384
2384
|
};
|
|
2385
2385
|
//#endregion
|
|
@@ -2669,6 +2669,7 @@ const isStorefrontNotFound = (error) => {
|
|
|
2669
2669
|
};
|
|
2670
2670
|
const httpBaseUrl = (options) => {
|
|
2671
2671
|
if (options.baseUrl) return resolveBaseUrl(options.baseUrl);
|
|
2672
|
+
if (options.routes?.cloud) return resolveBaseUrl(options.routes.cloud);
|
|
2672
2673
|
try {
|
|
2673
2674
|
return auth.getBaseUrl();
|
|
2674
2675
|
} catch {
|
|
@@ -4020,6 +4021,316 @@ const isGenId = (value) => {
|
|
|
4020
4021
|
return HASH_RUN.test(value);
|
|
4021
4022
|
};
|
|
4022
4023
|
//#endregion
|
|
4024
|
+
//#region src/order/routing/errors.ts
|
|
4025
|
+
var TlsFingerprintMismatchError = class extends Error {
|
|
4026
|
+
code = "TLS_FINGERPRINT_MISMATCH";
|
|
4027
|
+
url;
|
|
4028
|
+
expected;
|
|
4029
|
+
actual;
|
|
4030
|
+
constructor(url, expected, actual = null) {
|
|
4031
|
+
super(`TLS certificate fingerprint mismatch for ${url}`);
|
|
4032
|
+
this.name = "TlsFingerprintMismatchError";
|
|
4033
|
+
this.url = url;
|
|
4034
|
+
this.expected = expected;
|
|
4035
|
+
this.actual = actual;
|
|
4036
|
+
}
|
|
4037
|
+
};
|
|
4038
|
+
const isTlsFingerprintMismatchError = (error) => {
|
|
4039
|
+
return error instanceof TlsFingerprintMismatchError;
|
|
4040
|
+
};
|
|
4041
|
+
var OrderRouteUnavailableError = class extends Error {
|
|
4042
|
+
code = "ROUTE_UNAVAILABLE";
|
|
4043
|
+
eligibility;
|
|
4044
|
+
constructor(eligibility, message) {
|
|
4045
|
+
const codes = eligibility.reasons.map((r) => r.code).join(", ");
|
|
4046
|
+
const detail = codes ? ` (${codes})` : "";
|
|
4047
|
+
super(message ?? `No eligible order route available${detail}`);
|
|
4048
|
+
this.name = "OrderRouteUnavailableError";
|
|
4049
|
+
this.eligibility = eligibility;
|
|
4050
|
+
}
|
|
4051
|
+
};
|
|
4052
|
+
const isOrderRouteUnavailableError = (error) => {
|
|
4053
|
+
return error instanceof OrderRouteUnavailableError;
|
|
4054
|
+
};
|
|
4055
|
+
//#endregion
|
|
4056
|
+
//#region src/shared/certFingerprint.ts
|
|
4057
|
+
const SHA256_COLON_RE = /^(?:[0-9a-fA-F]{2}:){31}[0-9a-fA-F]{2}$/;
|
|
4058
|
+
const SHA256_HEX_RE = /^[0-9a-fA-F]{64}$/;
|
|
4059
|
+
/** Normalize a SHA-256 certificate fingerprint to colon-separated uppercase. */
|
|
4060
|
+
const normalizeCertFingerprint = (raw) => {
|
|
4061
|
+
const trimmed = raw.trim().replace(/^sha256:/i, "");
|
|
4062
|
+
if (SHA256_COLON_RE.test(trimmed)) return trimmed.toUpperCase();
|
|
4063
|
+
if (SHA256_HEX_RE.test(trimmed)) {
|
|
4064
|
+
const pairs = trimmed.toUpperCase().match(/.{2}/g);
|
|
4065
|
+
return pairs ? pairs.join(":") : null;
|
|
4066
|
+
}
|
|
4067
|
+
return null;
|
|
4068
|
+
};
|
|
4069
|
+
/** Constant-length comparison of two SHA-256 certificate fingerprints. */
|
|
4070
|
+
const certFingerprintsMatch = (expected, actual) => {
|
|
4071
|
+
if (!expected || !actual) return false;
|
|
4072
|
+
const a = normalizeCertFingerprint(expected);
|
|
4073
|
+
const b = normalizeCertFingerprint(actual);
|
|
4074
|
+
if (!a || !b || a.length !== b.length) return false;
|
|
4075
|
+
let diff = 0;
|
|
4076
|
+
for (let i = 0; i < a.length; i += 1) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
4077
|
+
return diff === 0;
|
|
4078
|
+
};
|
|
4079
|
+
/**
|
|
4080
|
+
* Collects and normalizes all valid SHA-256 leaf pins from a local server
|
|
4081
|
+
* config (`tls_fingerprint` + optional rotation `tls_fingerprints`).
|
|
4082
|
+
* Empty array means no valid pin is configured (fail-closed).
|
|
4083
|
+
*/
|
|
4084
|
+
const resolveLocalPins = (local) => {
|
|
4085
|
+
if (!local) return [];
|
|
4086
|
+
const raw = [];
|
|
4087
|
+
if (typeof local.tls_fingerprint === "string") raw.push(local.tls_fingerprint);
|
|
4088
|
+
if (Array.isArray(local.tls_fingerprints)) {
|
|
4089
|
+
for (const item of local.tls_fingerprints) if (typeof item === "string") raw.push(item);
|
|
4090
|
+
}
|
|
4091
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4092
|
+
const pins = [];
|
|
4093
|
+
for (const item of raw) {
|
|
4094
|
+
const norm = normalizeCertFingerprint(item);
|
|
4095
|
+
if (!norm || seen.has(norm)) continue;
|
|
4096
|
+
seen.add(norm);
|
|
4097
|
+
pins.push(norm);
|
|
4098
|
+
}
|
|
4099
|
+
return pins;
|
|
4100
|
+
};
|
|
4101
|
+
/** Returns true when `actual` matches any normalized SHA-256 pin in `pins`. */
|
|
4102
|
+
const certMatchesAnyPin = (pins, actual) => {
|
|
4103
|
+
if (!actual || pins.length === 0) return false;
|
|
4104
|
+
let matched = false;
|
|
4105
|
+
for (const pin of pins) if (certFingerprintsMatch(pin, actual)) matched = true;
|
|
4106
|
+
return matched;
|
|
4107
|
+
};
|
|
4108
|
+
//#endregion
|
|
4109
|
+
//#region src/shared/nodePinnedFetch.ts
|
|
4110
|
+
let cachedModules = null;
|
|
4111
|
+
const loadNodeModules = () => {
|
|
4112
|
+
if (!cachedModules) cachedModules = Promise.resolve().then(() => {
|
|
4113
|
+
const getBuiltin = (typeof process !== "undefined" ? process : void 0)?.getBuiltinModule;
|
|
4114
|
+
if (typeof getBuiltin !== "function") throw new Error("Node.js built-in module loader is unavailable in this runtime");
|
|
4115
|
+
const https = getBuiltin("node:https");
|
|
4116
|
+
const tls = getBuiltin("node:tls");
|
|
4117
|
+
const net = getBuiltin("node:net");
|
|
4118
|
+
if (!https || !tls || !net) throw new Error("Required Node.js TLS built-in modules are unavailable");
|
|
4119
|
+
return {
|
|
4120
|
+
https,
|
|
4121
|
+
tls,
|
|
4122
|
+
net
|
|
4123
|
+
};
|
|
4124
|
+
});
|
|
4125
|
+
return cachedModules;
|
|
4126
|
+
};
|
|
4127
|
+
const normalizePins = (pins) => {
|
|
4128
|
+
const out = [];
|
|
4129
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4130
|
+
for (const raw of pins) {
|
|
4131
|
+
const norm = normalizeCertFingerprint(raw);
|
|
4132
|
+
if (!norm || seen.has(norm)) continue;
|
|
4133
|
+
seen.add(norm);
|
|
4134
|
+
out.push(norm);
|
|
4135
|
+
}
|
|
4136
|
+
return out;
|
|
4137
|
+
};
|
|
4138
|
+
const toBodyBytes = async (body) => {
|
|
4139
|
+
if (body == null) return null;
|
|
4140
|
+
if (typeof body === "string") return new TextEncoder().encode(body);
|
|
4141
|
+
if (body instanceof Uint8Array) return body;
|
|
4142
|
+
if (body instanceof ArrayBuffer) return new Uint8Array(body);
|
|
4143
|
+
if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
|
|
4144
|
+
if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams) return new TextEncoder().encode(body.toString());
|
|
4145
|
+
if (typeof Blob !== "undefined" && body instanceof Blob) return new Uint8Array(await body.arrayBuffer());
|
|
4146
|
+
return new TextEncoder().encode(String(body));
|
|
4147
|
+
};
|
|
4148
|
+
const toPlainHeaders = (init) => {
|
|
4149
|
+
const out = {};
|
|
4150
|
+
if (!init) return out;
|
|
4151
|
+
new Headers(init).forEach((value, key) => {
|
|
4152
|
+
out[key] = value;
|
|
4153
|
+
});
|
|
4154
|
+
return out;
|
|
4155
|
+
};
|
|
4156
|
+
const toResponseHeaders = (raw) => {
|
|
4157
|
+
const headers = new Headers();
|
|
4158
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
4159
|
+
if (value === void 0) continue;
|
|
4160
|
+
if (Array.isArray(value)) for (const item of value) headers.append(key, item);
|
|
4161
|
+
else headers.set(key, value);
|
|
4162
|
+
}
|
|
4163
|
+
return headers;
|
|
4164
|
+
};
|
|
4165
|
+
const concatChunks = (chunks) => {
|
|
4166
|
+
let total = 0;
|
|
4167
|
+
for (const chunk of chunks) total += chunk.byteLength;
|
|
4168
|
+
const merged = new Uint8Array(total);
|
|
4169
|
+
let offset = 0;
|
|
4170
|
+
for (const chunk of chunks) {
|
|
4171
|
+
merged.set(chunk, offset);
|
|
4172
|
+
offset += chunk.byteLength;
|
|
4173
|
+
}
|
|
4174
|
+
return merged;
|
|
4175
|
+
};
|
|
4176
|
+
const makeAbortError = () => {
|
|
4177
|
+
const err = /* @__PURE__ */ new Error("The operation was aborted");
|
|
4178
|
+
err.name = "AbortError";
|
|
4179
|
+
return err;
|
|
4180
|
+
};
|
|
4181
|
+
const stripBrackets = (hostname) => {
|
|
4182
|
+
if (hostname.startsWith("[") && hostname.endsWith("]")) return hostname.slice(1, -1);
|
|
4183
|
+
return hostname;
|
|
4184
|
+
};
|
|
4185
|
+
const resolveHref = (input) => {
|
|
4186
|
+
if (typeof input === "string") return input;
|
|
4187
|
+
if (input instanceof URL) return input.toString();
|
|
4188
|
+
return input.url;
|
|
4189
|
+
};
|
|
4190
|
+
/**
|
|
4191
|
+
* Node.js TLS-layer certificate pinning fetch.
|
|
4192
|
+
* Verifies the peer leaf X.509 certificate SHA-256 fingerprint during the
|
|
4193
|
+
* TLS handshake (`secureConnect`) BEFORE handing the socket to `https.request`,
|
|
4194
|
+
* ensuring zero HTTP headers or request body bytes are sent on mismatch.
|
|
4195
|
+
*/
|
|
4196
|
+
const createNodePinnedFetch = (pins, options = {}) => {
|
|
4197
|
+
const normalizedPins = normalizePins(pins);
|
|
4198
|
+
const expectedSummary = normalizedPins.join(",");
|
|
4199
|
+
return (async (input, init) => {
|
|
4200
|
+
const href = resolveHref(input);
|
|
4201
|
+
if (normalizedPins.length === 0) throw new TlsFingerprintMismatchError(href, "", null);
|
|
4202
|
+
const parsed = new URL(href);
|
|
4203
|
+
if (parsed.protocol !== "https:") throw new TlsFingerprintMismatchError(href, expectedSummary, null);
|
|
4204
|
+
const signal = init?.signal;
|
|
4205
|
+
if (signal?.aborted) throw makeAbortError();
|
|
4206
|
+
const { https, tls, net } = await loadNodeModules();
|
|
4207
|
+
const method = init?.method ?? "GET";
|
|
4208
|
+
const headers = toPlainHeaders(init?.headers);
|
|
4209
|
+
const bodyBytes = await toBodyBytes(init?.body);
|
|
4210
|
+
if (bodyBytes && !("content-length" in headers)) headers["content-length"] = String(bodyBytes.byteLength);
|
|
4211
|
+
const host = stripBrackets(parsed.hostname);
|
|
4212
|
+
const port = parsed.port ? Number(parsed.port) : 443;
|
|
4213
|
+
const path = `${parsed.pathname}${parsed.search}`;
|
|
4214
|
+
const isIp = net.isIP(host) !== 0;
|
|
4215
|
+
return new Promise((resolve, reject) => {
|
|
4216
|
+
let settled = false;
|
|
4217
|
+
const done = (fn) => {
|
|
4218
|
+
if (settled) return;
|
|
4219
|
+
settled = true;
|
|
4220
|
+
signal?.removeEventListener("abort", onAbort);
|
|
4221
|
+
fn();
|
|
4222
|
+
};
|
|
4223
|
+
const createConnection = (_opts, onConnect) => {
|
|
4224
|
+
const tlsOpts = {
|
|
4225
|
+
host,
|
|
4226
|
+
port,
|
|
4227
|
+
rejectUnauthorized: false
|
|
4228
|
+
};
|
|
4229
|
+
if (!isIp) tlsOpts.servername = host;
|
|
4230
|
+
const socket = tls.connect(tlsOpts);
|
|
4231
|
+
let handedOff = false;
|
|
4232
|
+
socket.once("secureConnect", () => {
|
|
4233
|
+
const rawFp = socket.getPeerCertificate(false)?.fingerprint256 ?? null;
|
|
4234
|
+
const actual = rawFp ? normalizeCertFingerprint(rawFp) : null;
|
|
4235
|
+
if (!certMatchesAnyPin(normalizedPins, actual)) {
|
|
4236
|
+
const err = new TlsFingerprintMismatchError(href, expectedSummary, actual);
|
|
4237
|
+
handedOff = true;
|
|
4238
|
+
socket.destroy(err);
|
|
4239
|
+
onConnect(err);
|
|
4240
|
+
return;
|
|
4241
|
+
}
|
|
4242
|
+
handedOff = true;
|
|
4243
|
+
onConnect(null, socket);
|
|
4244
|
+
});
|
|
4245
|
+
socket.once("error", (rawErr) => {
|
|
4246
|
+
if (handedOff) return;
|
|
4247
|
+
handedOff = true;
|
|
4248
|
+
onConnect(rawErr instanceof Error ? rawErr : new Error(String(rawErr)));
|
|
4249
|
+
});
|
|
4250
|
+
};
|
|
4251
|
+
const agent = new https.Agent({ keepAlive: false });
|
|
4252
|
+
agent.createConnection = createConnection;
|
|
4253
|
+
const reqOpts = {
|
|
4254
|
+
protocol: "https:",
|
|
4255
|
+
hostname: host,
|
|
4256
|
+
port,
|
|
4257
|
+
path,
|
|
4258
|
+
method,
|
|
4259
|
+
headers,
|
|
4260
|
+
agent
|
|
4261
|
+
};
|
|
4262
|
+
const req = https.request(reqOpts, (res) => {
|
|
4263
|
+
const chunks = [];
|
|
4264
|
+
res.on("data", (chunk) => {
|
|
4265
|
+
if (chunk instanceof Uint8Array) chunks.push(chunk);
|
|
4266
|
+
else if (typeof chunk === "string") chunks.push(new TextEncoder().encode(chunk));
|
|
4267
|
+
});
|
|
4268
|
+
res.on("end", () => {
|
|
4269
|
+
done(() => {
|
|
4270
|
+
const status = res.statusCode ?? 200;
|
|
4271
|
+
const statusText = res.statusMessage ?? "";
|
|
4272
|
+
const resHeaders = toResponseHeaders(res.headers);
|
|
4273
|
+
const merged = concatChunks(chunks);
|
|
4274
|
+
const payload = status === 204 || status === 304 ? null : merged;
|
|
4275
|
+
const body = payload ? payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.byteLength) : null;
|
|
4276
|
+
resolve(new Response(body, {
|
|
4277
|
+
status,
|
|
4278
|
+
statusText,
|
|
4279
|
+
headers: resHeaders
|
|
4280
|
+
}));
|
|
4281
|
+
});
|
|
4282
|
+
});
|
|
4283
|
+
res.on("error", (err) => {
|
|
4284
|
+
done(() => reject(err));
|
|
4285
|
+
});
|
|
4286
|
+
});
|
|
4287
|
+
const onAbort = () => {
|
|
4288
|
+
const err = makeAbortError();
|
|
4289
|
+
req.destroy(err);
|
|
4290
|
+
done(() => reject(err));
|
|
4291
|
+
};
|
|
4292
|
+
if (signal) signal.addEventListener("abort", onAbort, { once: true });
|
|
4293
|
+
if (options.timeoutMs && options.timeoutMs > 0) req.setTimeout(options.timeoutMs, () => {
|
|
4294
|
+
const err = makeAbortError();
|
|
4295
|
+
req.destroy(err);
|
|
4296
|
+
done(() => reject(err));
|
|
4297
|
+
});
|
|
4298
|
+
req.on("error", (err) => {
|
|
4299
|
+
done(() => reject(err));
|
|
4300
|
+
});
|
|
4301
|
+
if (bodyBytes && bodyBytes.byteLength > 0) req.end(bodyBytes);
|
|
4302
|
+
else req.end();
|
|
4303
|
+
});
|
|
4304
|
+
});
|
|
4305
|
+
};
|
|
4306
|
+
//#endregion
|
|
4307
|
+
//#region src/shared/tlsPinning.ts
|
|
4308
|
+
let registeredTransport = null;
|
|
4309
|
+
/** True when running on Node.js where `node:tls` pinning is built in. */
|
|
4310
|
+
const isNodeRuntime = () => {
|
|
4311
|
+
return typeof process !== "undefined" && typeof process.versions === "object" && Boolean(process.versions?.node);
|
|
4312
|
+
};
|
|
4313
|
+
/**
|
|
4314
|
+
* Registers the host's real TLS-layer pinning transport (e.g. the Expo
|
|
4315
|
+
* `@fire-spark/tls-pinning` native iOS/Android bridge). Pass `null` to reset.
|
|
4316
|
+
*/
|
|
4317
|
+
const configureLocalTlsPinning = (factory) => {
|
|
4318
|
+
registeredTransport = factory;
|
|
4319
|
+
};
|
|
4320
|
+
/**
|
|
4321
|
+
* Returns the active TLS-layer pinning transport, or `null` when the current
|
|
4322
|
+
* runtime cannot enforce certificate pinning at the TLS layer (fail-closed).
|
|
4323
|
+
*/
|
|
4324
|
+
const getLocalTlsPinning = () => {
|
|
4325
|
+
if (registeredTransport) return registeredTransport;
|
|
4326
|
+
if (isNodeRuntime()) return createNodePinnedFetch;
|
|
4327
|
+
return null;
|
|
4328
|
+
};
|
|
4329
|
+
/** True when the current host can enforce TLS-layer certificate pinning. */
|
|
4330
|
+
const hasLocalTlsPinning = () => {
|
|
4331
|
+
return getLocalTlsPinning() !== null;
|
|
4332
|
+
};
|
|
4333
|
+
//#endregion
|
|
4023
4334
|
//#region src/order/OrderNotOpenError.ts
|
|
4024
4335
|
/**
|
|
4025
4336
|
* The order is not `OPEN` (`CLOSED`, `COMPLETED`, `VOIDED`, `REVERSED`,
|
|
@@ -4299,15 +4610,30 @@ const createFlushController = (runtime) => {
|
|
|
4299
4610
|
if (!pending) return;
|
|
4300
4611
|
await flushNow();
|
|
4301
4612
|
};
|
|
4613
|
+
const currentHttp = () => runtime.getHttp?.() ?? runtime.http;
|
|
4302
4614
|
const recreate = async () => {
|
|
4303
4615
|
const payload = structuredClone(runtime.getDraft());
|
|
4304
4616
|
const body = insertBody(payload);
|
|
4305
|
-
const created = await services.orders.post(body,
|
|
4617
|
+
const created = await services.orders.post(body, currentHttp());
|
|
4306
4618
|
runtime.setPersisted(true);
|
|
4307
4619
|
runtime.setSynced(created);
|
|
4308
4620
|
runtime.setDraft(created);
|
|
4309
4621
|
runtime.notify();
|
|
4310
4622
|
};
|
|
4623
|
+
const executeWrite = (payload, batchBase, wasPersisted) => {
|
|
4624
|
+
const http = currentHttp();
|
|
4625
|
+
if (!wasPersisted) return services.orders.post(insertBody(payload), http);
|
|
4626
|
+
const body = patchBody(payload, batchBase);
|
|
4627
|
+
const p1 = [
|
|
4628
|
+
payload.id,
|
|
4629
|
+
body,
|
|
4630
|
+
http
|
|
4631
|
+
];
|
|
4632
|
+
return services.orders.patch(...p1).catch((error) => {
|
|
4633
|
+
if (!isLocalOrderUnknown(error)) throw error;
|
|
4634
|
+
return services.orders.post(insertBody(payload), currentHttp());
|
|
4635
|
+
});
|
|
4636
|
+
};
|
|
4311
4637
|
const run = async () => {
|
|
4312
4638
|
const batchBase = structuredClone(runtime.getSynced());
|
|
4313
4639
|
const payload = structuredClone(runtime.getDraft());
|
|
@@ -4315,19 +4641,13 @@ const createFlushController = (runtime) => {
|
|
|
4315
4641
|
inFlight = true;
|
|
4316
4642
|
dirtyDuringFlight = false;
|
|
4317
4643
|
try {
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
4321
|
-
|
|
4322
|
-
|
|
4323
|
-
|
|
4324
|
-
|
|
4325
|
-
];
|
|
4326
|
-
return services.orders.patch(...p1).catch((error) => {
|
|
4327
|
-
if (!isLocalOrderUnknown(error)) throw error;
|
|
4328
|
-
return services.orders.post(insertBody(payload), runtime.http);
|
|
4329
|
-
});
|
|
4330
|
-
}, { sleep: runtime.sleep });
|
|
4644
|
+
let updated;
|
|
4645
|
+
try {
|
|
4646
|
+
updated = await withExponentialRetry(() => executeWrite(payload, batchBase, wasPersisted), { sleep: runtime.sleep });
|
|
4647
|
+
} catch (firstError) {
|
|
4648
|
+
if (!(runtime.onRouteError ? await runtime.onRouteError(firstError) : false)) throw firstError;
|
|
4649
|
+
updated = await executeWrite(payload, batchBase, runtime.isPersisted());
|
|
4650
|
+
}
|
|
4331
4651
|
pending = false;
|
|
4332
4652
|
rejected = null;
|
|
4333
4653
|
runtime.setPersisted(true);
|
|
@@ -5126,6 +5446,9 @@ var PaymentSession = class {
|
|
|
5126
5446
|
constructor(deps) {
|
|
5127
5447
|
this.deps = deps;
|
|
5128
5448
|
}
|
|
5449
|
+
currentHttp() {
|
|
5450
|
+
return this.deps.getHttp?.() ?? this.deps.http;
|
|
5451
|
+
}
|
|
5129
5452
|
setAdapters(adapters) {
|
|
5130
5453
|
this.adapters.clear();
|
|
5131
5454
|
for (const adapter of adapters) this.adapters.set(adapterKey(adapter.provider, adapter.method), adapter);
|
|
@@ -5172,7 +5495,7 @@ var PaymentSession = class {
|
|
|
5172
5495
|
}
|
|
5173
5496
|
server(payment, attempt) {
|
|
5174
5497
|
const order_id = this.deps.getOrder().id;
|
|
5175
|
-
const http = this.
|
|
5498
|
+
const http = this.currentHttp();
|
|
5176
5499
|
return { call: (operation, input) => {
|
|
5177
5500
|
const body = {
|
|
5178
5501
|
order_id,
|
|
@@ -5304,7 +5627,7 @@ var PaymentSession = class {
|
|
|
5304
5627
|
async recordResult(tender, result) {
|
|
5305
5628
|
const order = this.deps.getOrder();
|
|
5306
5629
|
const input = this.toRecord(tender, result);
|
|
5307
|
-
const http = this.
|
|
5630
|
+
const http = this.currentHttp();
|
|
5308
5631
|
const next = await services.orders.recordPayment(order.id, input, http);
|
|
5309
5632
|
this.deps.applyOrder(next);
|
|
5310
5633
|
}
|
|
@@ -5517,7 +5840,7 @@ var PaymentSession = class {
|
|
|
5517
5840
|
provider,
|
|
5518
5841
|
collect_at
|
|
5519
5842
|
};
|
|
5520
|
-
const http = this.
|
|
5843
|
+
const http = this.currentHttp();
|
|
5521
5844
|
const replace = services.orders.replaceTender;
|
|
5522
5845
|
const next = await replace(order.id, tenderId, body, http);
|
|
5523
5846
|
this.deps.applyOrder(next);
|
|
@@ -5701,7 +6024,7 @@ var PaymentSession = class {
|
|
|
5701
6024
|
error
|
|
5702
6025
|
};
|
|
5703
6026
|
const report = services.payments.terminalFailure;
|
|
5704
|
-
await report(payment.id, body, this.
|
|
6027
|
+
await report(payment.id, body, this.currentHttp()).catch(() => void 0);
|
|
5705
6028
|
}
|
|
5706
6029
|
};
|
|
5707
6030
|
//#endregion
|
|
@@ -6312,65 +6635,952 @@ const redemptionSteps = (order) => {
|
|
|
6312
6635
|
return steps;
|
|
6313
6636
|
};
|
|
6314
6637
|
//#endregion
|
|
6315
|
-
//#region src/order/
|
|
6316
|
-
|
|
6317
|
-
const
|
|
6318
|
-
|
|
6319
|
-
|
|
6320
|
-
|
|
6321
|
-
|
|
6322
|
-
|
|
6323
|
-
|
|
6324
|
-
|
|
6325
|
-
|
|
6326
|
-
|
|
6327
|
-
|
|
6638
|
+
//#region src/order/routing/classify.ts
|
|
6639
|
+
const GATEWAY_REFUSAL_CODES = /* @__PURE__ */ new Map([[503, "LOCAL_NODE_DRAINING"], [502, "LOCAL_CLOUD_UNREACHABLE"]]);
|
|
6640
|
+
const OBVIOUS_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
6641
|
+
"ENOTFOUND",
|
|
6642
|
+
"EAI_AGAIN",
|
|
6643
|
+
"ECONNREFUSED",
|
|
6644
|
+
"EHOSTUNREACH",
|
|
6645
|
+
"ENETUNREACH",
|
|
6646
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
6647
|
+
"ERR_NAME_NOT_RESOLVED",
|
|
6648
|
+
"ERR_CONNECTION_REFUSED",
|
|
6649
|
+
"ERR_INTERNET_DISCONNECTED"
|
|
6650
|
+
]);
|
|
6651
|
+
const TLS_ERROR_PREFIXES = [
|
|
6652
|
+
"CERT_",
|
|
6653
|
+
"ERR_TLS_",
|
|
6654
|
+
"UNABLE_TO_VERIFY",
|
|
6655
|
+
"DEPTH_ZERO_SELF_SIGNED",
|
|
6656
|
+
"SELF_SIGNED_CERT",
|
|
6657
|
+
"HOSTNAME_MISMATCH"
|
|
6658
|
+
];
|
|
6659
|
+
const AMBIGUOUS_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
6660
|
+
"ETIMEDOUT",
|
|
6661
|
+
"ECONNRESET",
|
|
6662
|
+
"EPIPE",
|
|
6663
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
6664
|
+
"UND_ERR_BODY_TIMEOUT",
|
|
6665
|
+
"UND_ERR_SOCKET"
|
|
6666
|
+
]);
|
|
6667
|
+
const OBVIOUS_TYPEERROR_MESSAGES = [
|
|
6668
|
+
"network request failed",
|
|
6669
|
+
"failed to fetch",
|
|
6670
|
+
"load failed",
|
|
6671
|
+
"networkerror when attempting to fetch resource"
|
|
6672
|
+
];
|
|
6673
|
+
const readErrorCode = (error) => {
|
|
6674
|
+
if (!error || typeof error !== "object") return null;
|
|
6675
|
+
const record = error;
|
|
6676
|
+
if (typeof record.code === "string" && record.code) return record.code;
|
|
6677
|
+
if (record.cause && typeof record.cause === "object") {
|
|
6678
|
+
const cause = record.cause;
|
|
6679
|
+
if (typeof cause.code === "string" && cause.code) return cause.code;
|
|
6328
6680
|
}
|
|
6329
|
-
|
|
6330
|
-
|
|
6331
|
-
|
|
6332
|
-
|
|
6333
|
-
|
|
6681
|
+
return null;
|
|
6682
|
+
};
|
|
6683
|
+
const readErrorName = (error) => {
|
|
6684
|
+
if (!error || typeof error !== "object") return "";
|
|
6685
|
+
const record = error;
|
|
6686
|
+
if (typeof record.name === "string" && record.name) return record.name;
|
|
6687
|
+
if (record.cause && typeof record.cause === "object") {
|
|
6688
|
+
const cause = record.cause;
|
|
6689
|
+
if (typeof cause.name === "string") return cause.name;
|
|
6334
6690
|
}
|
|
6335
|
-
|
|
6336
|
-
|
|
6691
|
+
return "";
|
|
6692
|
+
};
|
|
6693
|
+
const isTlsCode = (code) => {
|
|
6694
|
+
if (!code) return false;
|
|
6695
|
+
return TLS_ERROR_PREFIXES.some((prefix) => code.startsWith(prefix));
|
|
6696
|
+
};
|
|
6697
|
+
const isBusinessError = (error) => {
|
|
6698
|
+
if (error instanceof OrderValidationError) return true;
|
|
6699
|
+
if (error instanceof OrderNotOpenError) return true;
|
|
6700
|
+
if (error instanceof OrderPaymentRequiredError) return true;
|
|
6701
|
+
if (error instanceof OrderAuthPinnedError) return true;
|
|
6702
|
+
if (error instanceof DelegatedSessionExpiredError) return true;
|
|
6703
|
+
return false;
|
|
6704
|
+
};
|
|
6705
|
+
/**
|
|
6706
|
+
* Classifies a route failure per Local Nodes Architecture §4:
|
|
6707
|
+
* - Business 4xx -> never reroute
|
|
6708
|
+
* - TLS mismatch / DNS / connection refused / connect timeout -> obvious outage
|
|
6709
|
+
* - Gateway 503 LOCAL_NODE_DRAINING / 502 LOCAL_CLOUD_UNREACHABLE -> reroute
|
|
6710
|
+
* - Generic 5xx / response timeout / mid-response drop -> ambiguous (verify first)
|
|
6711
|
+
*/
|
|
6712
|
+
const classifyRouteFailure = (error, options = {}) => {
|
|
6713
|
+
const name = readErrorName(error);
|
|
6714
|
+
if (Boolean(options.signal?.aborted) && name === "AbortError") return {
|
|
6715
|
+
kind: "business_4xx",
|
|
6716
|
+
shouldReroute: false,
|
|
6717
|
+
shouldVerifyOriginal: false,
|
|
6718
|
+
markRouteDown: false,
|
|
6719
|
+
aborted: true,
|
|
6720
|
+
reason: "CALLER_ABORTED"
|
|
6721
|
+
};
|
|
6722
|
+
if (error instanceof TlsFingerprintMismatchError) return {
|
|
6723
|
+
kind: "tls_mismatch",
|
|
6724
|
+
shouldReroute: true,
|
|
6725
|
+
shouldVerifyOriginal: false,
|
|
6726
|
+
markRouteDown: true,
|
|
6727
|
+
aborted: false,
|
|
6728
|
+
reason: error.code
|
|
6729
|
+
};
|
|
6730
|
+
if (isBusinessError(error)) return {
|
|
6731
|
+
kind: "business_4xx",
|
|
6732
|
+
shouldReroute: false,
|
|
6733
|
+
shouldVerifyOriginal: false,
|
|
6734
|
+
markRouteDown: false,
|
|
6735
|
+
aborted: false,
|
|
6736
|
+
reason: error instanceof Error ? error.name : "BUSINESS_ERROR"
|
|
6737
|
+
};
|
|
6738
|
+
if (error instanceof StorefrontHttpError) {
|
|
6739
|
+
if (error.status >= 400 && error.status < 500) return {
|
|
6740
|
+
kind: "business_4xx",
|
|
6741
|
+
shouldReroute: false,
|
|
6742
|
+
shouldVerifyOriginal: false,
|
|
6743
|
+
markRouteDown: false,
|
|
6744
|
+
aborted: false,
|
|
6745
|
+
reason: error.code ?? `HTTP_${error.status}`
|
|
6746
|
+
};
|
|
6747
|
+
const refusalCode = GATEWAY_REFUSAL_CODES.get(error.status);
|
|
6748
|
+
if (refusalCode && error.code === refusalCode) return {
|
|
6749
|
+
kind: "gateway_refusal",
|
|
6750
|
+
shouldReroute: true,
|
|
6751
|
+
shouldVerifyOriginal: false,
|
|
6752
|
+
markRouteDown: true,
|
|
6753
|
+
aborted: false,
|
|
6754
|
+
reason: refusalCode
|
|
6755
|
+
};
|
|
6756
|
+
return {
|
|
6757
|
+
kind: "ambiguous",
|
|
6758
|
+
shouldReroute: false,
|
|
6759
|
+
shouldVerifyOriginal: true,
|
|
6760
|
+
markRouteDown: true,
|
|
6761
|
+
aborted: false,
|
|
6762
|
+
reason: error.code ?? `HTTP_${error.status}`
|
|
6763
|
+
};
|
|
6764
|
+
}
|
|
6765
|
+
const code = readErrorCode(error);
|
|
6766
|
+
if (isTlsCode(code)) return {
|
|
6767
|
+
kind: "tls_mismatch",
|
|
6768
|
+
shouldReroute: true,
|
|
6769
|
+
shouldVerifyOriginal: false,
|
|
6770
|
+
markRouteDown: true,
|
|
6771
|
+
aborted: false,
|
|
6772
|
+
reason: code ?? "TLS_ERROR"
|
|
6773
|
+
};
|
|
6774
|
+
if (name === "ConnectTimeoutError" || code && OBVIOUS_ERROR_CODES.has(code)) return {
|
|
6775
|
+
kind: "obvious_outage",
|
|
6776
|
+
shouldReroute: true,
|
|
6777
|
+
shouldVerifyOriginal: false,
|
|
6778
|
+
markRouteDown: true,
|
|
6779
|
+
aborted: false,
|
|
6780
|
+
reason: code ?? name
|
|
6781
|
+
};
|
|
6782
|
+
if (name === "TimeoutError" || name === "AbortError" || code && AMBIGUOUS_ERROR_CODES.has(code)) return {
|
|
6783
|
+
kind: "ambiguous",
|
|
6784
|
+
shouldReroute: false,
|
|
6785
|
+
shouldVerifyOriginal: true,
|
|
6786
|
+
markRouteDown: true,
|
|
6787
|
+
aborted: false,
|
|
6788
|
+
reason: code ?? name
|
|
6789
|
+
};
|
|
6790
|
+
const message = error instanceof Error ? error.message.toLowerCase() : "";
|
|
6791
|
+
if (error instanceof TypeError && OBVIOUS_TYPEERROR_MESSAGES.some((part) => message.includes(part))) return {
|
|
6792
|
+
kind: "obvious_outage",
|
|
6793
|
+
shouldReroute: true,
|
|
6794
|
+
shouldVerifyOriginal: false,
|
|
6795
|
+
markRouteDown: true,
|
|
6796
|
+
aborted: false,
|
|
6797
|
+
reason: "NETWORK_UNREACHABLE"
|
|
6798
|
+
};
|
|
6799
|
+
return {
|
|
6800
|
+
kind: "ambiguous",
|
|
6801
|
+
shouldReroute: false,
|
|
6802
|
+
shouldVerifyOriginal: true,
|
|
6803
|
+
markRouteDown: true,
|
|
6804
|
+
aborted: false,
|
|
6805
|
+
reason: code ?? (name || "UNKNOWN_FAILURE")
|
|
6806
|
+
};
|
|
6807
|
+
};
|
|
6808
|
+
//#endregion
|
|
6809
|
+
//#region src/shared/localServer.ts
|
|
6810
|
+
const DEFAULT_HEALTH_TIMEOUT_MS = 4e3;
|
|
6811
|
+
/** Build `https://<host>:<port>`, wrapping bare IPv6 literals in brackets. */
|
|
6812
|
+
const formatLocalServerUrl = (host, port) => {
|
|
6813
|
+
const trimmed = host.trim();
|
|
6814
|
+
const bare = trimmed.startsWith("[") && trimmed.endsWith("]") ? trimmed.slice(1, -1) : trimmed;
|
|
6815
|
+
return `https://${bare.includes(":") ? `[${bare}]` : bare}:${port}`;
|
|
6816
|
+
};
|
|
6817
|
+
/** Extract the local server base URL from `OrderRoutes`, or `null` if disabled. */
|
|
6818
|
+
const resolveLocalRouteUrl = (routes) => {
|
|
6819
|
+
const local = routes?.local;
|
|
6820
|
+
if (!local) return null;
|
|
6821
|
+
if (typeof local === "string") return local.replace(/\/+$/, "") || null;
|
|
6822
|
+
if (!local.enabled || !local.url) return null;
|
|
6823
|
+
return local.url.replace(/\/+$/, "");
|
|
6824
|
+
};
|
|
6825
|
+
const parseHealthJson = async (response) => {
|
|
6826
|
+
try {
|
|
6827
|
+
const parsed = await response.json();
|
|
6828
|
+
if (!parsed || typeof parsed !== "object") return {};
|
|
6829
|
+
const record = parsed;
|
|
6830
|
+
if (record.data && typeof record.data === "object") return record.data;
|
|
6831
|
+
return record;
|
|
6832
|
+
} catch {
|
|
6833
|
+
return {};
|
|
6834
|
+
}
|
|
6835
|
+
};
|
|
6836
|
+
const readString = (value) => {
|
|
6837
|
+
return typeof value === "string" ? value : null;
|
|
6838
|
+
};
|
|
6839
|
+
const readSnapshotAgeMs = (body, now) => {
|
|
6840
|
+
if (typeof body.snapshot_age_ms === "number" && body.snapshot_age_ms >= 0) return body.snapshot_age_ms;
|
|
6841
|
+
const state = body.state;
|
|
6842
|
+
if (!state || typeof state !== "object") return null;
|
|
6843
|
+
if (typeof state.age_ms === "number" && state.age_ms >= 0) return state.age_ms;
|
|
6844
|
+
if (typeof state.synced_at === "string") {
|
|
6845
|
+
const parsed = Date.parse(state.synced_at);
|
|
6846
|
+
if (Number.isFinite(parsed)) return Math.max(0, now - parsed);
|
|
6847
|
+
}
|
|
6848
|
+
return null;
|
|
6849
|
+
};
|
|
6850
|
+
const verifyAnyPin = async (pins, verify) => {
|
|
6851
|
+
for (const pin of pins) if (await verify(pin)) return true;
|
|
6852
|
+
return false;
|
|
6853
|
+
};
|
|
6854
|
+
/** Test connectivity to a local server via `GET /local/v1/health`. */
|
|
6855
|
+
const testLocalServerHealth = async (target, options = {}) => {
|
|
6856
|
+
const pins = resolveLocalPins(target);
|
|
6857
|
+
if (pins.length === 0) return {
|
|
6858
|
+
ok: false,
|
|
6859
|
+
status: null,
|
|
6860
|
+
latency_ms: 0,
|
|
6861
|
+
fingerprint_matched: false,
|
|
6862
|
+
error: "TLS_PIN_MISSING"
|
|
6863
|
+
};
|
|
6864
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_HEALTH_TIMEOUT_MS;
|
|
6865
|
+
let fetchImpl = options.fetchImpl;
|
|
6866
|
+
let verifiedAtTlsLayer = false;
|
|
6867
|
+
if (!fetchImpl) {
|
|
6868
|
+
const factory = getLocalTlsPinning();
|
|
6869
|
+
if (!factory) {
|
|
6870
|
+
const b1 = {
|
|
6871
|
+
ok: false,
|
|
6872
|
+
status: null,
|
|
6873
|
+
latency_ms: 0
|
|
6874
|
+
};
|
|
6875
|
+
const b2 = { fingerprint_matched: false };
|
|
6876
|
+
return {
|
|
6877
|
+
...b1,
|
|
6878
|
+
...b2,
|
|
6879
|
+
error: "TLS_PINNING_UNAVAILABLE"
|
|
6880
|
+
};
|
|
6881
|
+
}
|
|
6882
|
+
fetchImpl = factory(pins, { timeoutMs });
|
|
6883
|
+
verifiedAtTlsLayer = true;
|
|
6884
|
+
}
|
|
6885
|
+
const url = `${target.url.replace(/\/+$/, "")}/local/v1/health`;
|
|
6886
|
+
const started = Date.now();
|
|
6887
|
+
const controller = new AbortController();
|
|
6888
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
6889
|
+
try {
|
|
6890
|
+
let fingerprintMatched = verifiedAtTlsLayer ? true : null;
|
|
6891
|
+
if (options.verifyFingerprint) {
|
|
6892
|
+
fingerprintMatched = await verifyAnyPin(pins, options.verifyFingerprint);
|
|
6893
|
+
if (!fingerprintMatched) {
|
|
6894
|
+
const b1 = {
|
|
6895
|
+
ok: false,
|
|
6896
|
+
status: null,
|
|
6897
|
+
latency_ms: Date.now() - started
|
|
6898
|
+
};
|
|
6899
|
+
const b2 = { fingerprint_matched: false };
|
|
6900
|
+
return {
|
|
6901
|
+
...b1,
|
|
6902
|
+
...b2,
|
|
6903
|
+
error: "TLS_FINGERPRINT_MISMATCH"
|
|
6904
|
+
};
|
|
6905
|
+
}
|
|
6906
|
+
}
|
|
6907
|
+
const init = {
|
|
6908
|
+
method: "GET",
|
|
6909
|
+
headers: { Accept: "application/json" },
|
|
6910
|
+
signal: controller.signal
|
|
6911
|
+
};
|
|
6912
|
+
const response = await fetchImpl(url, init);
|
|
6913
|
+
const latency_ms = Date.now() - started;
|
|
6914
|
+
const body = await parseHealthJson(response);
|
|
6915
|
+
const reportedFp = readString(body.tls_fingerprint);
|
|
6916
|
+
if (reportedFp && fingerprintMatched === null) {
|
|
6917
|
+
fingerprintMatched = certMatchesAnyPin(pins, reportedFp);
|
|
6918
|
+
if (!fingerprintMatched) {
|
|
6919
|
+
const b1 = {
|
|
6920
|
+
ok: false,
|
|
6921
|
+
status: response.status,
|
|
6922
|
+
latency_ms
|
|
6923
|
+
};
|
|
6924
|
+
const b2 = { fingerprint_matched: false };
|
|
6925
|
+
return {
|
|
6926
|
+
...b1,
|
|
6927
|
+
...b2,
|
|
6928
|
+
error: "TLS_FINGERPRINT_MISMATCH"
|
|
6929
|
+
};
|
|
6930
|
+
}
|
|
6931
|
+
}
|
|
6932
|
+
const bodyOk = body.ok === void 0 ? response.ok : body.ok === true;
|
|
6933
|
+
const ok = response.ok && bodyOk;
|
|
6934
|
+
const snapshot_age_ms = readSnapshotAgeMs(body, Date.now());
|
|
6935
|
+
const b1 = {
|
|
6936
|
+
ok,
|
|
6937
|
+
status: response.status,
|
|
6938
|
+
latency_ms
|
|
6939
|
+
};
|
|
6940
|
+
const b2 = {
|
|
6941
|
+
mode: readString(body.mode),
|
|
6942
|
+
serving: readString(body.serving)
|
|
6943
|
+
};
|
|
6944
|
+
const b3 = {
|
|
6945
|
+
phase: readString(body.phase),
|
|
6946
|
+
fingerprint_matched: fingerprintMatched
|
|
6947
|
+
};
|
|
6948
|
+
const snap = snapshot_age_ms !== null ? { snapshot_age_ms } : {};
|
|
6949
|
+
const error = ok ? null : `HTTP_${response.status}`;
|
|
6950
|
+
return {
|
|
6951
|
+
...b1,
|
|
6952
|
+
...b2,
|
|
6953
|
+
...b3,
|
|
6954
|
+
...snap,
|
|
6955
|
+
error
|
|
6956
|
+
};
|
|
6957
|
+
} catch (err) {
|
|
6958
|
+
const latency_ms = Date.now() - started;
|
|
6959
|
+
if (isTlsFingerprintMismatchError(err)) {
|
|
6960
|
+
const b1 = {
|
|
6961
|
+
ok: false,
|
|
6962
|
+
status: null,
|
|
6963
|
+
latency_ms
|
|
6964
|
+
};
|
|
6965
|
+
const b2 = { fingerprint_matched: false };
|
|
6966
|
+
return {
|
|
6967
|
+
...b1,
|
|
6968
|
+
...b2,
|
|
6969
|
+
error: "TLS_FINGERPRINT_MISMATCH"
|
|
6970
|
+
};
|
|
6971
|
+
}
|
|
6972
|
+
const isAbort = err instanceof Error && err.name === "AbortError";
|
|
6973
|
+
const msg = err instanceof Error ? err.message : "NETWORK_ERROR";
|
|
6974
|
+
return {
|
|
6975
|
+
ok: false,
|
|
6976
|
+
status: null,
|
|
6977
|
+
latency_ms,
|
|
6978
|
+
fingerprint_matched: null,
|
|
6979
|
+
error: isAbort ? "TIMEOUT" : msg
|
|
6980
|
+
};
|
|
6981
|
+
} finally {
|
|
6982
|
+
clearTimeout(timer);
|
|
6983
|
+
}
|
|
6984
|
+
};
|
|
6985
|
+
//#endregion
|
|
6986
|
+
//#region src/order/routing/eligibility.ts
|
|
6987
|
+
const CLOUD_ONLY = {
|
|
6988
|
+
local_eligible: false,
|
|
6989
|
+
offline_eligible: false
|
|
6990
|
+
};
|
|
6991
|
+
const LOCAL_ONLY = {
|
|
6992
|
+
local_eligible: true,
|
|
6993
|
+
offline_eligible: false
|
|
6994
|
+
};
|
|
6995
|
+
/**
|
|
6996
|
+
* Provider + method eligibility ceilings mirrored from P1/P5
|
|
6997
|
+
* (`PAYMENT_PROVIDER_ELIGIBILITY_CEILINGS`). Online CARD, 3DS, redirect,
|
|
6998
|
+
* DEUNA, and Cashea are always cloud-only; REDEMPTION is never offline.
|
|
6999
|
+
*/
|
|
7000
|
+
const SDK_PAYMENT_ELIGIBILITY_CEILINGS = {
|
|
7001
|
+
"firespark:CASH": {
|
|
7002
|
+
local_eligible: true,
|
|
7003
|
+
offline_eligible: true
|
|
7004
|
+
},
|
|
7005
|
+
"firespark:PIN_PAD": LOCAL_ONLY,
|
|
7006
|
+
"clisitef:PIN_PAD": LOCAL_ONLY,
|
|
7007
|
+
"medianet:PIN_PAD": LOCAL_ONLY,
|
|
7008
|
+
"transbank:PIN_PAD": LOCAL_ONLY,
|
|
7009
|
+
"redeban:PIN_PAD": LOCAL_ONLY,
|
|
7010
|
+
"sitef_venezuela:PIN_PAD": LOCAL_ONLY,
|
|
7011
|
+
"mxp_paybridge:PIN_PAD": LOCAL_ONLY,
|
|
7012
|
+
"kushki:PIN_PAD": LOCAL_ONLY,
|
|
7013
|
+
"yape:PIN_PAD": LOCAL_ONLY,
|
|
7014
|
+
"niubiz:PIN_PAD": LOCAL_ONLY,
|
|
7015
|
+
"firespark:REDEMPTION": LOCAL_ONLY,
|
|
7016
|
+
"mxp_paybridge:WALLET": LOCAL_ONLY,
|
|
7017
|
+
"mxp_paybridge:BANK_TRANSFER": LOCAL_ONLY,
|
|
7018
|
+
"mxp_paybridge:FINANCING": LOCAL_ONLY,
|
|
7019
|
+
"payphone:WALLET": LOCAL_ONLY,
|
|
7020
|
+
"sitef_venezuela:BANK_TRANSFER": LOCAL_ONLY,
|
|
7021
|
+
"deuna:CARD": CLOUD_ONLY,
|
|
7022
|
+
"deuna:WALLET": CLOUD_ONLY,
|
|
7023
|
+
"deuna:BANK_TRANSFER": CLOUD_ONLY,
|
|
7024
|
+
"cashea:FINANCING": CLOUD_ONLY,
|
|
7025
|
+
"credibanco:CARD": CLOUD_ONLY,
|
|
7026
|
+
"credibanco:BANK_TRANSFER": CLOUD_ONLY,
|
|
7027
|
+
"nuvei:CARD": CLOUD_ONLY,
|
|
7028
|
+
"pagoplux:CARD": CLOUD_ONLY,
|
|
7029
|
+
"paymentez:CARD": CLOUD_ONLY,
|
|
7030
|
+
"payphone:CARD": CLOUD_ONLY,
|
|
7031
|
+
"place_to_pay:CARD": CLOUD_ONLY,
|
|
7032
|
+
"sitef_venezuela:CARD": CLOUD_ONLY,
|
|
7033
|
+
"transbank:CARD": CLOUD_ONLY,
|
|
7034
|
+
"cardvault:CARD": CLOUD_ONLY,
|
|
7035
|
+
"kushki:CARD": CLOUD_ONLY,
|
|
7036
|
+
"kushki:WALLET": CLOUD_ONLY,
|
|
7037
|
+
"yape:BANK_TRANSFER": CLOUD_ONLY
|
|
7038
|
+
};
|
|
7039
|
+
const ceilingKey = (providerId, method) => {
|
|
7040
|
+
return `${providerId.trim().toLowerCase()}:${method.trim().toUpperCase()}`;
|
|
7041
|
+
};
|
|
7042
|
+
const resolveSdkPaymentEligibilityCeiling = (providerId, method) => {
|
|
7043
|
+
if (!providerId || !method) return CLOUD_ONLY;
|
|
7044
|
+
return SDK_PAYMENT_ELIGIBILITY_CEILINGS[ceilingKey(providerId, method)] ?? CLOUD_ONLY;
|
|
7045
|
+
};
|
|
7046
|
+
/**
|
|
7047
|
+
* Effective payment eligibility:
|
|
7048
|
+
* `payment.local_eligible && method.local_eligible && ceiling.local_eligible`
|
|
7049
|
+
* (and `offline_eligible => local_eligible`).
|
|
7050
|
+
*/
|
|
7051
|
+
const resolvePaymentEligibility = (payment) => {
|
|
7052
|
+
const providerId = payment.provider?.provider_id ?? null;
|
|
7053
|
+
const methodName = payment.method?.method ?? null;
|
|
7054
|
+
const ceiling = resolveSdkPaymentEligibilityCeiling(providerId, methodName);
|
|
7055
|
+
if (!ceiling.local_eligible) return {
|
|
7056
|
+
local_eligible: false,
|
|
7057
|
+
offline_eligible: false,
|
|
7058
|
+
ceiling
|
|
7059
|
+
};
|
|
7060
|
+
const paymentLocal = payment.local_eligible === true;
|
|
7061
|
+
const rawMethodLocal = payment.method?.local_eligible;
|
|
7062
|
+
const local_eligible = paymentLocal && (rawMethodLocal === void 0 ? true : rawMethodLocal === true) && ceiling.local_eligible;
|
|
7063
|
+
const paymentOffline = payment.offline_eligible === true;
|
|
7064
|
+
const rawMethodOffline = payment.method?.offline_eligible;
|
|
7065
|
+
return {
|
|
7066
|
+
local_eligible,
|
|
7067
|
+
offline_eligible: local_eligible && paymentOffline && (rawMethodOffline === void 0 ? true : rawMethodOffline === true) && ceiling.offline_eligible,
|
|
7068
|
+
ceiling
|
|
7069
|
+
};
|
|
7070
|
+
};
|
|
7071
|
+
const DEFAULT_HEALTH = {
|
|
7072
|
+
cloudDown: false,
|
|
7073
|
+
localDown: false,
|
|
7074
|
+
localSnapshotStale: false,
|
|
7075
|
+
localTlsMismatch: false
|
|
7076
|
+
};
|
|
7077
|
+
const evaluateTenders = (tenders, paymentsById, reasons) => {
|
|
7078
|
+
let allLocal = true;
|
|
7079
|
+
let allOffline = true;
|
|
7080
|
+
let anyLocal = false;
|
|
7081
|
+
let anyCloudOnly = false;
|
|
7082
|
+
for (const tender of tenders) {
|
|
7083
|
+
const pid = tender.payment_id ?? null;
|
|
7084
|
+
const registered = pid ? paymentsById.get(pid) : void 0;
|
|
7085
|
+
const provider = registered?.provider?.provider_id ?? tender.provider ?? null;
|
|
7086
|
+
const method = registered?.method?.method ?? tender.method ?? null;
|
|
7087
|
+
const resolved = resolvePaymentEligibility(registered ?? {
|
|
7088
|
+
id: pid ?? void 0,
|
|
7089
|
+
local_eligible: false,
|
|
7090
|
+
offline_eligible: false,
|
|
7091
|
+
provider: provider ? { provider_id: provider } : null,
|
|
7092
|
+
method: method ? { method } : null
|
|
7093
|
+
});
|
|
7094
|
+
if (resolved.local_eligible) anyLocal = true;
|
|
7095
|
+
else {
|
|
7096
|
+
allLocal = false;
|
|
7097
|
+
anyCloudOnly = true;
|
|
7098
|
+
const d1 = {
|
|
7099
|
+
code: !resolved.ceiling.local_eligible ? "PAYMENT_PROVIDER_CLOUD_ONLY" : "PAYMENT_NOT_LOCAL_ELIGIBLE",
|
|
7100
|
+
payment_id: pid,
|
|
7101
|
+
method,
|
|
7102
|
+
provider
|
|
7103
|
+
};
|
|
7104
|
+
reasons.push(d1);
|
|
7105
|
+
}
|
|
7106
|
+
if (!resolved.offline_eligible) {
|
|
7107
|
+
allOffline = false;
|
|
7108
|
+
if (method?.toUpperCase() === "REDEMPTION") {
|
|
7109
|
+
const d1 = {
|
|
7110
|
+
payment_id: pid,
|
|
7111
|
+
method,
|
|
7112
|
+
provider
|
|
7113
|
+
};
|
|
7114
|
+
reasons.push({
|
|
7115
|
+
code: "REDEMPTION_NOT_OFFLINE_ELIGIBLE",
|
|
7116
|
+
...d1
|
|
7117
|
+
});
|
|
7118
|
+
} else if (resolved.local_eligible) {
|
|
7119
|
+
const d1 = {
|
|
7120
|
+
payment_id: pid,
|
|
7121
|
+
method,
|
|
7122
|
+
provider
|
|
7123
|
+
};
|
|
7124
|
+
reasons.push({
|
|
7125
|
+
code: "PAYMENT_NOT_OFFLINE_ELIGIBLE",
|
|
7126
|
+
...d1
|
|
7127
|
+
});
|
|
7128
|
+
}
|
|
7129
|
+
}
|
|
7130
|
+
}
|
|
7131
|
+
if (anyLocal && anyCloudOnly) reasons.push({ code: "MIXED_TENDER_CLOUD_ONLY" });
|
|
7132
|
+
return {
|
|
7133
|
+
allLocal,
|
|
7134
|
+
allOffline
|
|
7135
|
+
};
|
|
7136
|
+
};
|
|
7137
|
+
const resolveOrderRouteEligibility = (input) => {
|
|
7138
|
+
const { routes, fulfillment, tenders, paymentsById } = input;
|
|
7139
|
+
const health = input.health ?? DEFAULT_HEALTH;
|
|
7140
|
+
const offline = Boolean(input.offline || routes?.offline);
|
|
7141
|
+
const reasons = [];
|
|
7142
|
+
const workflowLocal = fulfillment?.local_eligible === true;
|
|
7143
|
+
const workflowOffline = workflowLocal && fulfillment?.offline_eligible === true;
|
|
7144
|
+
if (!workflowLocal) {
|
|
7145
|
+
const fid = fulfillment?.id ?? null;
|
|
7146
|
+
reasons.push({
|
|
7147
|
+
code: "WORKFLOW_NOT_LOCAL_ELIGIBLE",
|
|
7148
|
+
fulfillment_id: fid
|
|
7149
|
+
});
|
|
7150
|
+
} else if (!workflowOffline) {
|
|
7151
|
+
const fid = fulfillment?.id ?? null;
|
|
7152
|
+
reasons.push({
|
|
7153
|
+
code: "WORKFLOW_NOT_OFFLINE_ELIGIBLE",
|
|
7154
|
+
fulfillment_id: fid
|
|
7155
|
+
});
|
|
7156
|
+
}
|
|
7157
|
+
const tenderRes = evaluateTenders(tenders, paymentsById, reasons);
|
|
7158
|
+
const local_eligible = workflowLocal && tenderRes.allLocal;
|
|
7159
|
+
const offline_eligible = local_eligible && workflowOffline && tenderRes.allOffline;
|
|
7160
|
+
if (!resolveLocalRouteUrl(routes)) {
|
|
7161
|
+
reasons.push({ code: "LOCAL_NOT_CONFIGURED" });
|
|
7162
|
+
if (offline) {
|
|
7163
|
+
reasons.push({ code: "DEVICE_OFFLINE" });
|
|
7164
|
+
return {
|
|
7165
|
+
local_eligible,
|
|
7166
|
+
offline_eligible,
|
|
7167
|
+
routes: [],
|
|
7168
|
+
preferred: null,
|
|
7169
|
+
reasons
|
|
7170
|
+
};
|
|
7171
|
+
}
|
|
7172
|
+
return {
|
|
7173
|
+
local_eligible,
|
|
7174
|
+
offline_eligible,
|
|
7175
|
+
routes: ["cloud"],
|
|
7176
|
+
preferred: "cloud",
|
|
7177
|
+
reasons
|
|
7178
|
+
};
|
|
7179
|
+
}
|
|
7180
|
+
if (input.hasInFlightCharge && input.activeRoute) {
|
|
7181
|
+
reasons.push({ code: "IN_FLIGHT_PAYMENT_PINNED" });
|
|
7182
|
+
return {
|
|
7183
|
+
local_eligible,
|
|
7184
|
+
offline_eligible,
|
|
7185
|
+
routes: [input.activeRoute],
|
|
7186
|
+
preferred: input.activeRoute,
|
|
7187
|
+
reasons
|
|
7188
|
+
};
|
|
7189
|
+
}
|
|
7190
|
+
const hasValidPin = resolveLocalPins(routes?.local && typeof routes.local !== "string" ? routes.local : null).length > 0;
|
|
7191
|
+
const hasTransport = input.tlsPinningAvailable ?? hasLocalTlsPinning();
|
|
7192
|
+
if (offline) reasons.push({ code: "DEVICE_OFFLINE" });
|
|
7193
|
+
if (health.cloudDown) reasons.push({ code: "CLOUD_ROUTE_DOWN" });
|
|
7194
|
+
if (!hasValidPin) reasons.push({ code: "LOCAL_TLS_PIN_MISSING" });
|
|
7195
|
+
if (hasValidPin && !hasTransport) reasons.push({ code: "LOCAL_TLS_PINNING_UNAVAILABLE" });
|
|
7196
|
+
if (health.localTlsMismatch) reasons.push({ code: "LOCAL_TLS_MISMATCH" });
|
|
7197
|
+
if (health.localDown) reasons.push({ code: "LOCAL_ROUTE_DOWN" });
|
|
7198
|
+
if (!offline && health.localSnapshotStale) reasons.push({ code: "LOCAL_SNAPSHOT_STALE" });
|
|
7199
|
+
const cloudAvailable = !offline && !health.cloudDown;
|
|
7200
|
+
const modeEligible = offline ? offline_eligible : local_eligible;
|
|
7201
|
+
const fresh = offline || !health.localSnapshotStale;
|
|
7202
|
+
const localAvailable = modeEligible && hasValidPin && hasTransport && !health.localDown && !health.localTlsMismatch && fresh;
|
|
7203
|
+
const prefer = routes?.prefer ?? "local";
|
|
7204
|
+
const available = [];
|
|
7205
|
+
if (prefer === "local") {
|
|
7206
|
+
if (localAvailable) available.push("local");
|
|
7207
|
+
if (cloudAvailable) available.push("cloud");
|
|
7208
|
+
} else {
|
|
7209
|
+
if (cloudAvailable) available.push("cloud");
|
|
7210
|
+
if (localAvailable) available.push("local");
|
|
7211
|
+
}
|
|
7212
|
+
return {
|
|
7213
|
+
local_eligible,
|
|
7214
|
+
offline_eligible,
|
|
7215
|
+
routes: available,
|
|
7216
|
+
preferred: available[0] ?? null,
|
|
7217
|
+
reasons
|
|
7218
|
+
};
|
|
7219
|
+
};
|
|
7220
|
+
//#endregion
|
|
7221
|
+
//#region src/order/routing/health.ts
|
|
7222
|
+
/** Default cooldown before re-probing a failed route (30 s). */
|
|
7223
|
+
const DEFAULT_ROUTE_COOLDOWN_MS = 3e4;
|
|
7224
|
+
/** Default max local snapshot age for online local routing (24 h). */
|
|
7225
|
+
const DEFAULT_MAX_SNAPSHOT_AGE_MS = 1440 * 60 * 1e3;
|
|
7226
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
7227
|
+
const records = /* @__PURE__ */ new Map();
|
|
7228
|
+
const verifiedPins = /* @__PURE__ */ new Map();
|
|
7229
|
+
const routeKey = (route, baseUrl) => {
|
|
7230
|
+
return `${route}\n${baseUrl.replace(/\/+$/, "")}`;
|
|
7231
|
+
};
|
|
7232
|
+
const emit$1 = (event, extraListener) => {
|
|
7233
|
+
for (const listener of listeners) listener(event);
|
|
7234
|
+
if (extraListener && !listeners.has(extraListener)) extraListener(event);
|
|
7235
|
+
};
|
|
7236
|
+
/** Subscribe to route health transitions (down, degraded, healthy). */
|
|
7237
|
+
const onRouteHealth = (listener) => {
|
|
7238
|
+
listeners.add(listener);
|
|
7239
|
+
return () => {
|
|
7240
|
+
listeners.delete(listener);
|
|
7241
|
+
};
|
|
7242
|
+
};
|
|
7243
|
+
const getRouteHealth = (route, baseUrl) => {
|
|
7244
|
+
return records.get(routeKey(route, baseUrl))?.event ?? null;
|
|
7245
|
+
};
|
|
7246
|
+
const markRouteDown = (input) => {
|
|
7247
|
+
const now = input.now ?? Date.now();
|
|
7248
|
+
const downUntil = now + (input.cooldownMs ?? 3e4);
|
|
7249
|
+
const tlsMismatch = input.failureKind === "tls_mismatch";
|
|
6337
7250
|
const b1 = {
|
|
6338
|
-
|
|
6339
|
-
|
|
7251
|
+
route: input.route,
|
|
7252
|
+
baseUrl: input.baseUrl
|
|
6340
7253
|
};
|
|
6341
7254
|
const b2 = {
|
|
6342
|
-
|
|
6343
|
-
|
|
7255
|
+
status: "down",
|
|
7256
|
+
downUntil
|
|
6344
7257
|
};
|
|
6345
|
-
const b3 = {
|
|
6346
|
-
|
|
6347
|
-
|
|
6348
|
-
|
|
7258
|
+
const b3 = { reason: input.reason ?? null };
|
|
7259
|
+
const b4 = {
|
|
7260
|
+
failureKind: input.failureKind ?? null,
|
|
7261
|
+
timestamp: now
|
|
6349
7262
|
};
|
|
6350
|
-
|
|
7263
|
+
const event = {
|
|
6351
7264
|
...b1,
|
|
6352
7265
|
...b2,
|
|
6353
|
-
...b3
|
|
7266
|
+
...b3,
|
|
7267
|
+
...b4
|
|
6354
7268
|
};
|
|
6355
|
-
|
|
6356
|
-
const
|
|
7269
|
+
const key = routeKey(input.route, input.baseUrl);
|
|
7270
|
+
const snapshotStale = records.get(key)?.snapshotStale ?? false;
|
|
7271
|
+
records.set(key, {
|
|
7272
|
+
event,
|
|
7273
|
+
snapshotStale,
|
|
7274
|
+
tlsMismatch
|
|
7275
|
+
});
|
|
7276
|
+
if (input.route === "local") verifiedPins.delete(input.baseUrl.replace(/\/+$/, ""));
|
|
7277
|
+
emit$1(event, input.listener);
|
|
7278
|
+
return event;
|
|
7279
|
+
};
|
|
7280
|
+
const markRouteHealthy = (route, baseUrl, options = {}) => {
|
|
7281
|
+
const key = routeKey(route, baseUrl);
|
|
7282
|
+
const prev = records.get(key);
|
|
7283
|
+
if (!prev || prev.event.status === "healthy") return null;
|
|
7284
|
+
const now = options.now ?? Date.now();
|
|
6357
7285
|
const b1 = {
|
|
6358
|
-
|
|
6359
|
-
|
|
6360
|
-
|
|
6361
|
-
discount_total: 0
|
|
7286
|
+
route,
|
|
7287
|
+
baseUrl,
|
|
7288
|
+
status: "healthy"
|
|
6362
7289
|
};
|
|
6363
7290
|
const b2 = {
|
|
6364
|
-
|
|
6365
|
-
|
|
6366
|
-
|
|
7291
|
+
downUntil: null,
|
|
7292
|
+
reason: null,
|
|
7293
|
+
failureKind: null
|
|
6367
7294
|
};
|
|
6368
|
-
|
|
7295
|
+
const event = {
|
|
6369
7296
|
...b1,
|
|
6370
|
-
...b2
|
|
7297
|
+
...b2,
|
|
7298
|
+
timestamp: now
|
|
6371
7299
|
};
|
|
7300
|
+
records.set(key, {
|
|
7301
|
+
event,
|
|
7302
|
+
snapshotStale: false,
|
|
7303
|
+
tlsMismatch: false
|
|
7304
|
+
});
|
|
7305
|
+
emit$1(event, options.listener);
|
|
7306
|
+
return event;
|
|
6372
7307
|
};
|
|
6373
|
-
|
|
7308
|
+
/**
|
|
7309
|
+
* Returns true while `downUntil` is active. Automatically clears expired
|
|
7310
|
+
* cooldowns so the next request re-probes the route.
|
|
7311
|
+
*/
|
|
7312
|
+
const isRouteCircuitOpen = (route, baseUrl, now = Date.now()) => {
|
|
7313
|
+
const key = routeKey(route, baseUrl);
|
|
7314
|
+
const record = records.get(key);
|
|
7315
|
+
if (!record) return false;
|
|
7316
|
+
const until = record.event.downUntil;
|
|
7317
|
+
if (until === null) return false;
|
|
7318
|
+
if (until > now) return true;
|
|
7319
|
+
records.set(key, {
|
|
7320
|
+
event: {
|
|
7321
|
+
...record.event,
|
|
7322
|
+
status: "degraded",
|
|
7323
|
+
downUntil: null
|
|
7324
|
+
},
|
|
7325
|
+
snapshotStale: record.snapshotStale,
|
|
7326
|
+
tlsMismatch: false
|
|
7327
|
+
});
|
|
7328
|
+
return false;
|
|
7329
|
+
};
|
|
7330
|
+
const getLocalRouteFlags = (baseUrl, now = Date.now()) => {
|
|
7331
|
+
const down = isRouteCircuitOpen("local", baseUrl, now);
|
|
7332
|
+
const record = records.get(routeKey("local", baseUrl));
|
|
7333
|
+
return {
|
|
7334
|
+
localDown: down,
|
|
7335
|
+
localSnapshotStale: record?.snapshotStale ?? false,
|
|
7336
|
+
localTlsMismatch: down && Boolean(record?.tlsMismatch)
|
|
7337
|
+
};
|
|
7338
|
+
};
|
|
7339
|
+
const verifyLocalRoutePin = async (local, verifyFingerprint, now = Date.now()) => {
|
|
7340
|
+
const base = local.url.replace(/\/+$/, "");
|
|
7341
|
+
const pins = resolveLocalPins(local);
|
|
7342
|
+
if (pins.length === 0) throw new TlsFingerprintMismatchError(base, "", null);
|
|
7343
|
+
if (!verifyFingerprint) return;
|
|
7344
|
+
const pinKey = pins.join(",");
|
|
7345
|
+
const cacheKey = `${base}\n${pinKey}`;
|
|
7346
|
+
const validUntil = verifiedPins.get(cacheKey);
|
|
7347
|
+
if (validUntil && validUntil > now) return;
|
|
7348
|
+
let matched = false;
|
|
7349
|
+
for (const pin of pins) if (await verifyFingerprint(pin)) {
|
|
7350
|
+
matched = true;
|
|
7351
|
+
break;
|
|
7352
|
+
}
|
|
7353
|
+
if (!matched) {
|
|
7354
|
+
verifiedPins.delete(cacheKey);
|
|
7355
|
+
throw new TlsFingerprintMismatchError(base, pinKey, null);
|
|
7356
|
+
}
|
|
7357
|
+
verifiedPins.set(cacheKey, now + DEFAULT_ROUTE_COOLDOWN_MS);
|
|
7358
|
+
};
|
|
7359
|
+
const TLS_HEALTH_ERRORS = /* @__PURE__ */ new Set([
|
|
7360
|
+
"TLS_FINGERPRINT_MISMATCH",
|
|
7361
|
+
"TLS_PIN_MISSING",
|
|
7362
|
+
"TLS_PINNING_UNAVAILABLE"
|
|
7363
|
+
]);
|
|
7364
|
+
/**
|
|
7365
|
+
* Probes `GET /local/v1/health`, verifies TLS pin + snapshot freshness,
|
|
7366
|
+
* and updates circuit breaker state + `onRouteHealth` listeners.
|
|
7367
|
+
*/
|
|
7368
|
+
const probeLocalRouteHealth = async (local, options = {}) => {
|
|
7369
|
+
const baseUrl = local.url.replace(/\/+$/, "");
|
|
7370
|
+
const maxAge = options.maxSnapshotAgeMs ?? 864e5;
|
|
7371
|
+
const result = await testLocalServerHealth(local, options);
|
|
7372
|
+
if (!result.ok) {
|
|
7373
|
+
const failureKind = Boolean(result.error && TLS_HEALTH_ERRORS.has(result.error)) ? "tls_mismatch" : "obvious_outage";
|
|
7374
|
+
const m1 = {
|
|
7375
|
+
route: "local",
|
|
7376
|
+
baseUrl
|
|
7377
|
+
};
|
|
7378
|
+
const m2 = {
|
|
7379
|
+
cooldownMs: options.cooldownMs,
|
|
7380
|
+
reason: result.error
|
|
7381
|
+
};
|
|
7382
|
+
const m3 = { failureKind };
|
|
7383
|
+
markRouteDown({
|
|
7384
|
+
...m1,
|
|
7385
|
+
...m2,
|
|
7386
|
+
...m3,
|
|
7387
|
+
listener: options.listener
|
|
7388
|
+
});
|
|
7389
|
+
return {
|
|
7390
|
+
...result,
|
|
7391
|
+
snapshot_stale: false
|
|
7392
|
+
};
|
|
7393
|
+
}
|
|
7394
|
+
const age = result.snapshot_age_ms;
|
|
7395
|
+
const snapshot_stale = typeof age === "number" && age > maxAge;
|
|
7396
|
+
const key = routeKey("local", baseUrl);
|
|
7397
|
+
const prev = records.get(key);
|
|
7398
|
+
const now = Date.now();
|
|
7399
|
+
const status = snapshot_stale ? "degraded" : "healthy";
|
|
7400
|
+
const reason = snapshot_stale ? "LOCAL_SNAPSHOT_STALE" : null;
|
|
7401
|
+
const b1 = {
|
|
7402
|
+
route: "local",
|
|
7403
|
+
baseUrl,
|
|
7404
|
+
status
|
|
7405
|
+
};
|
|
7406
|
+
const b2 = {
|
|
7407
|
+
downUntil: null,
|
|
7408
|
+
reason,
|
|
7409
|
+
failureKind: null,
|
|
7410
|
+
timestamp: now
|
|
7411
|
+
};
|
|
7412
|
+
const event = {
|
|
7413
|
+
...b1,
|
|
7414
|
+
...b2
|
|
7415
|
+
};
|
|
7416
|
+
records.set(key, {
|
|
7417
|
+
event,
|
|
7418
|
+
snapshotStale: snapshot_stale,
|
|
7419
|
+
tlsMismatch: false
|
|
7420
|
+
});
|
|
7421
|
+
if (!prev || prev.event.status !== status || prev.snapshotStale !== snapshot_stale) emit$1(event, options.listener);
|
|
7422
|
+
return {
|
|
7423
|
+
...result,
|
|
7424
|
+
snapshot_stale
|
|
7425
|
+
};
|
|
7426
|
+
};
|
|
7427
|
+
//#endregion
|
|
7428
|
+
//#region src/order/routing/router.ts
|
|
7429
|
+
/** Request header hinting to the local node that the device is offline. */
|
|
7430
|
+
const MODE_HINT_HEADER = "x-firespark-mode-hint";
|
|
7431
|
+
/**
|
|
7432
|
+
* @deprecated TLS pinning is enforced at the TLS handshake layer, never via
|
|
7433
|
+
* request headers. Kept exported only so existing callers do not break.
|
|
7434
|
+
*/
|
|
7435
|
+
const TLS_PIN_HEADER = "x-firespark-tls-pin";
|
|
7436
|
+
/**
|
|
7437
|
+
* @deprecated TLS pinning is enforced at the TLS handshake layer, never via
|
|
7438
|
+
* response headers. Kept exported only so existing callers do not break.
|
|
7439
|
+
*/
|
|
7440
|
+
const TLS_FINGERPRINT_RESPONSE_HEADER = "x-firespark-tls-fingerprint";
|
|
7441
|
+
const hasSmartRouting = (routes) => {
|
|
7442
|
+
return resolveLocalRouteUrl(routes) !== null;
|
|
7443
|
+
};
|
|
7444
|
+
const resolveLocalConfig = (routes) => {
|
|
7445
|
+
const local = routes?.local;
|
|
7446
|
+
if (!local) return null;
|
|
7447
|
+
if (typeof local === "string") {
|
|
7448
|
+
const url = local.replace(/\/+$/, "");
|
|
7449
|
+
if (!url) return null;
|
|
7450
|
+
return {
|
|
7451
|
+
enabled: true,
|
|
7452
|
+
host: url,
|
|
7453
|
+
port: 443,
|
|
7454
|
+
url,
|
|
7455
|
+
tls_fingerprint: null
|
|
7456
|
+
};
|
|
7457
|
+
}
|
|
7458
|
+
if (!local.enabled || !local.url) return null;
|
|
7459
|
+
return {
|
|
7460
|
+
...local,
|
|
7461
|
+
url: local.url.replace(/\/+$/, "")
|
|
7462
|
+
};
|
|
7463
|
+
};
|
|
7464
|
+
const resolveCloudRouteUrl = (routes, fallbackBaseUrl) => {
|
|
7465
|
+
return (routes?.cloud ?? fallbackBaseUrl ?? "").replace(/\/+$/, "");
|
|
7466
|
+
};
|
|
7467
|
+
/**
|
|
7468
|
+
* True when any live tender on the current intent has an in-flight charge
|
|
7469
|
+
* (`status === "PENDING"` with an `attempt_reference` on a PIN pad / provider).
|
|
7470
|
+
* Per §4, the SDK never reroutes until that tender resolves.
|
|
7471
|
+
*/
|
|
7472
|
+
const hasInFlightPayment = (order) => {
|
|
7473
|
+
return liveTenders(currentIntent(order.payment_intents)).some((tender) => {
|
|
7474
|
+
if (tender.status !== "PENDING") return false;
|
|
7475
|
+
if (!tender.attempt_reference) return false;
|
|
7476
|
+
return tender.method !== "CASH" || isDeviceCharged(tender);
|
|
7477
|
+
});
|
|
7478
|
+
};
|
|
7479
|
+
const createLocalPinnedFetch = (baseFetch, local, offlineHint, verifyTlsFingerprint) => {
|
|
7480
|
+
return (async (input, init) => {
|
|
7481
|
+
const pins = resolveLocalPins(local);
|
|
7482
|
+
if (pins.length === 0) throw new TlsFingerprintMismatchError(local.url, "", null);
|
|
7483
|
+
let transport = baseFetch;
|
|
7484
|
+
if (!transport) {
|
|
7485
|
+
const factory = getLocalTlsPinning();
|
|
7486
|
+
if (!factory) throw new TlsFingerprintMismatchError(local.url, pins.join(","), null);
|
|
7487
|
+
transport = factory(pins);
|
|
7488
|
+
}
|
|
7489
|
+
if (verifyTlsFingerprint) await verifyLocalRoutePin(local, verifyTlsFingerprint);
|
|
7490
|
+
const headers = new Headers(init?.headers);
|
|
7491
|
+
if (offlineHint && !headers.has("x-firespark-mode-hint")) headers.set(MODE_HINT_HEADER, "offline");
|
|
7492
|
+
return transport(input, {
|
|
7493
|
+
...init,
|
|
7494
|
+
headers
|
|
7495
|
+
});
|
|
7496
|
+
});
|
|
7497
|
+
};
|
|
7498
|
+
/**
|
|
7499
|
+
* Builds route-scoped `ServiceHttpOptions`. Cloud requests are sent directly
|
|
7500
|
+
* to `routes.cloud` with no local headers; local requests enforce TLS-layer
|
|
7501
|
+
* certificate pinning (fail-closed) and optional offline mode hint headers.
|
|
7502
|
+
*/
|
|
7503
|
+
const buildRouteHttpOptions = (input) => {
|
|
7504
|
+
const { base, routes, target, offlineHint = false } = input;
|
|
7505
|
+
const { verifyTlsFingerprint } = input;
|
|
7506
|
+
if (target === "cloud") {
|
|
7507
|
+
const cloudUrl = resolveCloudRouteUrl(routes, base.baseUrl);
|
|
7508
|
+
return {
|
|
7509
|
+
...base,
|
|
7510
|
+
baseUrl: cloudUrl,
|
|
7511
|
+
fallbackBaseUrl: void 0
|
|
7512
|
+
};
|
|
7513
|
+
}
|
|
7514
|
+
const local = resolveLocalConfig(routes);
|
|
7515
|
+
if (!local) return base;
|
|
7516
|
+
const fetchImpl = createLocalPinnedFetch(base.fetchImpl, local, offlineHint, verifyTlsFingerprint);
|
|
7517
|
+
return {
|
|
7518
|
+
...base,
|
|
7519
|
+
baseUrl: local.url,
|
|
7520
|
+
fallbackBaseUrl: void 0,
|
|
7521
|
+
fetchImpl
|
|
7522
|
+
};
|
|
7523
|
+
};
|
|
7524
|
+
//#endregion
|
|
7525
|
+
//#region src/order/totals.ts
|
|
7526
|
+
/** Sum root line group totals into order totals (Big.js). */
|
|
7527
|
+
const recomputeTotals = (lines, currency = "USD") => {
|
|
7528
|
+
let subtotal = new Big(0);
|
|
7529
|
+
let discountTotal = new Big(0);
|
|
7530
|
+
let taxTotal = new Big(0);
|
|
7531
|
+
let total = new Big(0);
|
|
7532
|
+
for (const line of lines) {
|
|
7533
|
+
if (line.parent_uid != null) continue;
|
|
7534
|
+
subtotal = subtotal.plus(line.group_subtotal);
|
|
7535
|
+
discountTotal = discountTotal.plus(line.group_discount);
|
|
7536
|
+
taxTotal = taxTotal.plus(line.group_tax_total);
|
|
7537
|
+
total = total.plus(line.group_total);
|
|
7538
|
+
}
|
|
7539
|
+
let taxRate = 0;
|
|
7540
|
+
let discountRate = 0;
|
|
7541
|
+
if (subtotal.gt(0)) {
|
|
7542
|
+
taxRate = taxTotal.div(subtotal).toNumber();
|
|
7543
|
+
discountRate = discountTotal.div(subtotal).toNumber();
|
|
7544
|
+
}
|
|
7545
|
+
const discount_total = discountTotal.toNumber();
|
|
7546
|
+
const tax_total = taxTotal.toNumber();
|
|
7547
|
+
const b1 = {
|
|
7548
|
+
currency,
|
|
7549
|
+
subtotal: subtotal.toNumber()
|
|
7550
|
+
};
|
|
7551
|
+
const b2 = {
|
|
7552
|
+
discount_rate: discountRate,
|
|
7553
|
+
discount_total
|
|
7554
|
+
};
|
|
7555
|
+
const b3 = {
|
|
7556
|
+
tax_rate: taxRate,
|
|
7557
|
+
tax_total,
|
|
7558
|
+
total: total.toNumber()
|
|
7559
|
+
};
|
|
7560
|
+
return {
|
|
7561
|
+
...b1,
|
|
7562
|
+
...b2,
|
|
7563
|
+
...b3
|
|
7564
|
+
};
|
|
7565
|
+
};
|
|
7566
|
+
const emptyTotals = (currency = "USD") => {
|
|
7567
|
+
const b1 = {
|
|
7568
|
+
currency,
|
|
7569
|
+
subtotal: 0,
|
|
7570
|
+
discount_rate: 0,
|
|
7571
|
+
discount_total: 0
|
|
7572
|
+
};
|
|
7573
|
+
const b2 = {
|
|
7574
|
+
tax_rate: 0,
|
|
7575
|
+
tax_total: 0,
|
|
7576
|
+
total: 0
|
|
7577
|
+
};
|
|
7578
|
+
return {
|
|
7579
|
+
...b1,
|
|
7580
|
+
...b2
|
|
7581
|
+
};
|
|
7582
|
+
};
|
|
7583
|
+
//#endregion
|
|
6374
7584
|
//#region src/order/Order.ts
|
|
6375
7585
|
const cloneOrder = (order) => {
|
|
6376
7586
|
return structuredClone(order);
|
|
@@ -6383,6 +7593,7 @@ const redeemSignature = (items) => {
|
|
|
6383
7593
|
const buildHttpOptions = (options) => {
|
|
6384
7594
|
return {
|
|
6385
7595
|
baseUrl: options.baseUrl,
|
|
7596
|
+
routes: options.routes,
|
|
6386
7597
|
accessToken: options.accessToken,
|
|
6387
7598
|
fetchImpl: options.fetchImpl
|
|
6388
7599
|
};
|
|
@@ -6614,12 +7825,27 @@ var Order = class Order {
|
|
|
6614
7825
|
device;
|
|
6615
7826
|
/** Device voids a failed cancel / refund call did not report yet. */
|
|
6616
7827
|
unreported = [];
|
|
7828
|
+
routes;
|
|
7829
|
+
activeRoute = null;
|
|
7830
|
+
fulfillment;
|
|
7831
|
+
paymentEligibility = /* @__PURE__ */ new Map();
|
|
7832
|
+
onRouteHealthListener;
|
|
7833
|
+
verifyTlsFingerprint;
|
|
7834
|
+
isOfflineFn;
|
|
6617
7835
|
constructor(config, notify) {
|
|
6618
7836
|
this.draft = cloneOrder(config.order);
|
|
6619
7837
|
this.synced = cloneOrder(config.order);
|
|
6620
7838
|
this.rememberLogScope();
|
|
6621
7839
|
this.persisted = config.persisted;
|
|
6622
7840
|
this.http = config.http;
|
|
7841
|
+
this.routes = config.http.routes;
|
|
7842
|
+
this.fulfillment = config.fulfillment ?? null;
|
|
7843
|
+
this.onRouteHealthListener = config.onRouteHealth;
|
|
7844
|
+
this.verifyTlsFingerprint = config.verifyTlsFingerprint;
|
|
7845
|
+
this.isOfflineFn = config.isOffline;
|
|
7846
|
+
if (config.payments) this.registerPaymentEligibility(config.payments);
|
|
7847
|
+
if (hasSmartRouting(this.routes)) this.activeRoute = this.getRouteEligibility().preferred ?? "cloud";
|
|
7848
|
+
else this.activeRoute = "cloud";
|
|
6623
7849
|
this.debounceMs = config.debounceMs;
|
|
6624
7850
|
this.device = config.device;
|
|
6625
7851
|
this.externalNotify = notify;
|
|
@@ -6641,11 +7867,17 @@ var Order = class Order {
|
|
|
6641
7867
|
this.persisted = next;
|
|
6642
7868
|
};
|
|
6643
7869
|
const b6 = { setPersisted };
|
|
7870
|
+
const getHttp = () => this.activeHttp();
|
|
7871
|
+
const onRouteError = hasSmartRouting(this.routes) ? (error) => this.handleFlushRouteError(error) : void 0;
|
|
6644
7872
|
const b7 = {
|
|
6645
7873
|
notify: () => this.notify(),
|
|
6646
|
-
http: this.http
|
|
7874
|
+
http: this.http,
|
|
7875
|
+
getHttp
|
|
7876
|
+
};
|
|
7877
|
+
const b8 = {
|
|
7878
|
+
debounceMs: config.debounceMs,
|
|
7879
|
+
onRouteError
|
|
6647
7880
|
};
|
|
6648
|
-
const b8 = { debounceMs: config.debounceMs };
|
|
6649
7881
|
const b9 = {
|
|
6650
7882
|
fresh: config.fresh ?? false,
|
|
6651
7883
|
sleep: config.sleep
|
|
@@ -6664,7 +7896,8 @@ var Order = class Order {
|
|
|
6664
7896
|
this.flush = createFlushController(flush);
|
|
6665
7897
|
const c1 = {
|
|
6666
7898
|
getOrder: () => this.draft,
|
|
6667
|
-
http: this.http
|
|
7899
|
+
http: this.http,
|
|
7900
|
+
getHttp
|
|
6668
7901
|
};
|
|
6669
7902
|
const place = (input) => this.placeOrder(input);
|
|
6670
7903
|
const apply = (next) => this.applyServerOrder(next);
|
|
@@ -6706,12 +7939,20 @@ var Order = class Order {
|
|
|
6706
7939
|
}
|
|
6707
7940
|
const reuse = options.reuseOpen ?? true;
|
|
6708
7941
|
const existing = reuse ? await findOpenOrder(scope, http) : null;
|
|
7942
|
+
const routing = {
|
|
7943
|
+
fulfillment: options.fulfillment,
|
|
7944
|
+
payments: options.payments,
|
|
7945
|
+
onRouteHealth: options.onRouteHealth,
|
|
7946
|
+
verifyTlsFingerprint: options.verifyTlsFingerprint,
|
|
7947
|
+
isOffline: options.isOffline
|
|
7948
|
+
};
|
|
6709
7949
|
if (existing) return new Order({
|
|
6710
7950
|
order: existing,
|
|
6711
7951
|
http,
|
|
6712
7952
|
debounceMs,
|
|
6713
7953
|
persisted: true,
|
|
6714
|
-
device: options.device
|
|
7954
|
+
device: options.device,
|
|
7955
|
+
...routing
|
|
6715
7956
|
}, notify);
|
|
6716
7957
|
const d1 = {
|
|
6717
7958
|
order: buildLocalDraft(body),
|
|
@@ -6721,7 +7962,8 @@ var Order = class Order {
|
|
|
6721
7962
|
};
|
|
6722
7963
|
const d2 = {
|
|
6723
7964
|
fresh: !reuse,
|
|
6724
|
-
device: options.device
|
|
7965
|
+
device: options.device,
|
|
7966
|
+
...routing
|
|
6725
7967
|
};
|
|
6726
7968
|
return new Order({
|
|
6727
7969
|
...d1,
|
|
@@ -6760,9 +8002,17 @@ var Order = class Order {
|
|
|
6760
8002
|
sleep: config.sleep,
|
|
6761
8003
|
device: config.device
|
|
6762
8004
|
};
|
|
8005
|
+
const d3 = {
|
|
8006
|
+
fulfillment: config.fulfillment,
|
|
8007
|
+
payments: config.payments,
|
|
8008
|
+
onRouteHealth: config.onRouteHealth,
|
|
8009
|
+
verifyTlsFingerprint: config.verifyTlsFingerprint,
|
|
8010
|
+
isOffline: config.isOffline
|
|
8011
|
+
};
|
|
6763
8012
|
return new Order({
|
|
6764
8013
|
...d1,
|
|
6765
|
-
...d2
|
|
8014
|
+
...d2,
|
|
8015
|
+
...d3
|
|
6766
8016
|
}, notify);
|
|
6767
8017
|
}
|
|
6768
8018
|
/** Whether this session has a server row yet. */
|
|
@@ -6772,8 +8022,118 @@ var Order = class Order {
|
|
|
6772
8022
|
/** Persist a local draft via POST (no-op if already on the server). */
|
|
6773
8023
|
async persist() {
|
|
6774
8024
|
if (this.deleted || this.persisted) return;
|
|
8025
|
+
if (hasSmartRouting(this.routes)) {
|
|
8026
|
+
const preferred = this.getRouteEligibility().preferred;
|
|
8027
|
+
if (preferred) this.activeRoute = preferred;
|
|
8028
|
+
}
|
|
6775
8029
|
await this.flush.flushNow();
|
|
6776
8030
|
}
|
|
8031
|
+
/** Route currently selected for this order (`cloud` when local is unset). */
|
|
8032
|
+
getActiveRoute() {
|
|
8033
|
+
return this.activeRoute ?? "cloud";
|
|
8034
|
+
}
|
|
8035
|
+
/** Updates fulfillment eligibility (`local_eligible`, `offline_eligible`). */
|
|
8036
|
+
setFulfillment(fulfillment) {
|
|
8037
|
+
this.fulfillment = fulfillment;
|
|
8038
|
+
}
|
|
8039
|
+
/** Registers payment eligibility metadata for `getRouteEligibility()`. */
|
|
8040
|
+
setPaymentEligibility(payments) {
|
|
8041
|
+
this.registerPaymentEligibility(payments);
|
|
8042
|
+
}
|
|
8043
|
+
registerPaymentEligibility(payments) {
|
|
8044
|
+
for (const payment of payments) if (payment.id) this.paymentEligibility.set(payment.id, payment);
|
|
8045
|
+
}
|
|
8046
|
+
isDeviceOffline() {
|
|
8047
|
+
return Boolean(this.isOfflineFn?.() || this.routes?.offline);
|
|
8048
|
+
}
|
|
8049
|
+
routeBaseUrl(target) {
|
|
8050
|
+
if (target === "local") return resolveLocalConfig(this.routes)?.url ?? "";
|
|
8051
|
+
return resolveCloudRouteUrl(this.routes, this.http.baseUrl);
|
|
8052
|
+
}
|
|
8053
|
+
routeHttp(target) {
|
|
8054
|
+
if (!this.routes || !hasSmartRouting(this.routes)) return this.http;
|
|
8055
|
+
const cloudDown = isRouteCircuitOpen("cloud", this.routeBaseUrl("cloud"));
|
|
8056
|
+
const offlineHint = target === "local" && (this.isDeviceOffline() || cloudDown);
|
|
8057
|
+
return buildRouteHttpOptions({
|
|
8058
|
+
base: this.http,
|
|
8059
|
+
routes: this.routes,
|
|
8060
|
+
target,
|
|
8061
|
+
offlineHint,
|
|
8062
|
+
verifyTlsFingerprint: this.verifyTlsFingerprint
|
|
8063
|
+
});
|
|
8064
|
+
}
|
|
8065
|
+
activeHttp() {
|
|
8066
|
+
return this.routeHttp(this.activeRoute ?? "cloud");
|
|
8067
|
+
}
|
|
8068
|
+
collectRouteTenders(payment) {
|
|
8069
|
+
const nextTenders = this.getTenders(payment);
|
|
8070
|
+
if (nextTenders.length > 0) return nextTenders.map((tender) => {
|
|
8071
|
+
return {
|
|
8072
|
+
payment_id: tender.payment_id ?? null,
|
|
8073
|
+
method: tender.method,
|
|
8074
|
+
provider: tender.provider ?? null
|
|
8075
|
+
};
|
|
8076
|
+
});
|
|
8077
|
+
return liveTenders(currentIntent(this.draft.payment_intents)).map((tender) => {
|
|
8078
|
+
return {
|
|
8079
|
+
payment_id: tender.payment_id ?? null,
|
|
8080
|
+
method: tender.method,
|
|
8081
|
+
provider: tender.provider ?? null
|
|
8082
|
+
};
|
|
8083
|
+
});
|
|
8084
|
+
}
|
|
8085
|
+
/**
|
|
8086
|
+
* Computes effective local/offline eligibility, available routes, preferred
|
|
8087
|
+
* route, and machine-readable reasons for this order.
|
|
8088
|
+
*/
|
|
8089
|
+
getRouteEligibility(input = {}) {
|
|
8090
|
+
const tenders = this.collectRouteTenders(input.payment);
|
|
8091
|
+
const cloudUrl = this.routeBaseUrl("cloud");
|
|
8092
|
+
const localUrl = this.routeBaseUrl("local");
|
|
8093
|
+
const cloudDown = cloudUrl ? isRouteCircuitOpen("cloud", cloudUrl) : false;
|
|
8094
|
+
const localFlags = localUrl ? getLocalRouteFlags(localUrl) : {
|
|
8095
|
+
localDown: false,
|
|
8096
|
+
localSnapshotStale: false,
|
|
8097
|
+
localTlsMismatch: false
|
|
8098
|
+
};
|
|
8099
|
+
const offline = input.offline ?? this.isDeviceOffline();
|
|
8100
|
+
const tlsPinningAvailable = hasLocalTlsPinning() || Boolean(this.http.fetchImpl);
|
|
8101
|
+
return resolveOrderRouteEligibility({
|
|
8102
|
+
routes: this.routes,
|
|
8103
|
+
fulfillment: this.fulfillment,
|
|
8104
|
+
tenders,
|
|
8105
|
+
paymentsById: this.paymentEligibility,
|
|
8106
|
+
hasInFlightCharge: hasInFlightPayment(this.draft),
|
|
8107
|
+
activeRoute: this.activeRoute,
|
|
8108
|
+
health: {
|
|
8109
|
+
cloudDown,
|
|
8110
|
+
...localFlags
|
|
8111
|
+
},
|
|
8112
|
+
offline,
|
|
8113
|
+
tlsPinningAvailable
|
|
8114
|
+
});
|
|
8115
|
+
}
|
|
8116
|
+
async handleFlushRouteError(error) {
|
|
8117
|
+
if (!hasSmartRouting(this.routes)) return false;
|
|
8118
|
+
const cls = classifyRouteFailure(error, { signal: this.http.signal });
|
|
8119
|
+
if (cls.aborted || cls.kind === "business_4xx") return false;
|
|
8120
|
+
const failedRoute = this.activeRoute ?? "cloud";
|
|
8121
|
+
const failedUrl = this.routeBaseUrl(failedRoute);
|
|
8122
|
+
if (cls.markRouteDown && failedUrl) markRouteDown({
|
|
8123
|
+
route: failedRoute,
|
|
8124
|
+
baseUrl: failedUrl,
|
|
8125
|
+
cooldownMs: this.routes?.cooldownMs,
|
|
8126
|
+
reason: cls.reason,
|
|
8127
|
+
failureKind: cls.kind,
|
|
8128
|
+
listener: this.onRouteHealthListener
|
|
8129
|
+
});
|
|
8130
|
+
if (hasInFlightPayment(this.draft)) return false;
|
|
8131
|
+
const alternate = this.getRouteEligibility().routes.find((r) => r !== failedRoute);
|
|
8132
|
+
if (!alternate) return false;
|
|
8133
|
+
this.activeRoute = alternate;
|
|
8134
|
+
this.persisted = false;
|
|
8135
|
+
return true;
|
|
8136
|
+
}
|
|
6777
8137
|
/** Whether local edits failed to reach the server (e.g. offline). */
|
|
6778
8138
|
hasPendingSync() {
|
|
6779
8139
|
return this.flush.getPending();
|
|
@@ -7010,7 +8370,7 @@ var Order = class Order {
|
|
|
7010
8370
|
const body = { customer_id: customerId };
|
|
7011
8371
|
const run = () => {
|
|
7012
8372
|
const id = this.draft.id;
|
|
7013
|
-
return services.orders.setCustomer(id, body, this.
|
|
8373
|
+
return services.orders.setCustomer(id, body, this.activeHttp());
|
|
7014
8374
|
};
|
|
7015
8375
|
return this.commitCustomer(run);
|
|
7016
8376
|
}
|
|
@@ -7024,7 +8384,7 @@ var Order = class Order {
|
|
|
7024
8384
|
if (this.deleted) return this.getOrder();
|
|
7025
8385
|
const run = () => {
|
|
7026
8386
|
const id = this.draft.id;
|
|
7027
|
-
return services.orders.clearCustomer(id, this.
|
|
8387
|
+
return services.orders.clearCustomer(id, this.activeHttp());
|
|
7028
8388
|
};
|
|
7029
8389
|
return this.commitCustomer(run);
|
|
7030
8390
|
}
|
|
@@ -7049,7 +8409,7 @@ var Order = class Order {
|
|
|
7049
8409
|
if (this.deleted) return;
|
|
7050
8410
|
this.flush.cancel();
|
|
7051
8411
|
if (this.persisted) {
|
|
7052
|
-
const next = await services.orders.cancel(this.draft.id, this.
|
|
8412
|
+
const next = await services.orders.cancel(this.draft.id, this.activeHttp());
|
|
7053
8413
|
this.draft = cloneOrder(next);
|
|
7054
8414
|
this.synced = cloneOrder(next);
|
|
7055
8415
|
} else {
|
|
@@ -7098,7 +8458,7 @@ var Order = class Order {
|
|
|
7098
8458
|
this.flush.cancel();
|
|
7099
8459
|
const body = orderId !== void 0 ? { order_id: orderId } : void 0;
|
|
7100
8460
|
const c1 = {
|
|
7101
|
-
order: await services.orders.reopen(this.draft.id, this.
|
|
8461
|
+
order: await services.orders.reopen(this.draft.id, this.activeHttp(), body),
|
|
7102
8462
|
http: this.http,
|
|
7103
8463
|
debounceMs: this.debounceMs
|
|
7104
8464
|
};
|
|
@@ -7114,7 +8474,7 @@ var Order = class Order {
|
|
|
7114
8474
|
if (this.deleted) return;
|
|
7115
8475
|
this.flush.cancel();
|
|
7116
8476
|
if (!this.persisted) return;
|
|
7117
|
-
const next = await services.orders.refund(this.draft.id, this.
|
|
8477
|
+
const next = await services.orders.refund(this.draft.id, this.activeHttp());
|
|
7118
8478
|
this.draft = cloneOrder(next);
|
|
7119
8479
|
this.synced = cloneOrder(next);
|
|
7120
8480
|
this.deleted = true;
|
|
@@ -7130,7 +8490,7 @@ var Order = class Order {
|
|
|
7130
8490
|
async rate(input) {
|
|
7131
8491
|
if (!this.persisted) throw new Error("Only a placed order is rated");
|
|
7132
8492
|
this.flush.cancel();
|
|
7133
|
-
const next = await services.orders.rate(this.draft.id, input, this.
|
|
8493
|
+
const next = await services.orders.rate(this.draft.id, input, this.activeHttp());
|
|
7134
8494
|
this.applyServerOrder(next);
|
|
7135
8495
|
if (!next.rating) throw new Error("Storefront response missing rating");
|
|
7136
8496
|
return next.rating;
|
|
@@ -7162,7 +8522,7 @@ var Order = class Order {
|
|
|
7162
8522
|
...b4,
|
|
7163
8523
|
...b5
|
|
7164
8524
|
};
|
|
7165
|
-
await services.orders.validate(body, this.
|
|
8525
|
+
await services.orders.validate(body, this.activeHttp());
|
|
7166
8526
|
}
|
|
7167
8527
|
/**
|
|
7168
8528
|
* Tenders of the next intent: one REDEMPTION per `payment_id` that
|
|
@@ -7193,7 +8553,9 @@ var Order = class Order {
|
|
|
7193
8553
|
this.realTenders = null;
|
|
7194
8554
|
if (activeIntent(this.draft.payment_intents)?.status !== "DRAFT") return this.getOrder();
|
|
7195
8555
|
const id = this.draft.id;
|
|
7196
|
-
const drop = () =>
|
|
8556
|
+
const drop = () => {
|
|
8557
|
+
return services.orders.deletePaymentIntent(id, this.activeHttp());
|
|
8558
|
+
};
|
|
7197
8559
|
const next = await this.onKnownCart(drop);
|
|
7198
8560
|
this.applyServerOrder(next);
|
|
7199
8561
|
return this.getOrder();
|
|
@@ -7223,7 +8585,7 @@ var Order = class Order {
|
|
|
7223
8585
|
await this.flush.settle();
|
|
7224
8586
|
const id = this.draft.id;
|
|
7225
8587
|
const put = services.orders.putPaymentIntent;
|
|
7226
|
-
const save = () => put(id, { tenders }, this.
|
|
8588
|
+
const save = () => put(id, { tenders }, this.activeHttp());
|
|
7227
8589
|
const next = await this.onKnownCart(save);
|
|
7228
8590
|
this.applyServerOrder(next);
|
|
7229
8591
|
return this.getOrder();
|
|
@@ -7251,16 +8613,154 @@ var Order = class Order {
|
|
|
7251
8613
|
* `OrderPaymentRequiredError` instead of placing.
|
|
7252
8614
|
*/
|
|
7253
8615
|
async placeOrder(input = {}) {
|
|
8616
|
+
if (!hasSmartRouting(this.routes)) {
|
|
8617
|
+
try {
|
|
8618
|
+
await this.placeOnce(input);
|
|
8619
|
+
} catch (error) {
|
|
8620
|
+
if (!isLocalOrderUnknown(error)) throw error;
|
|
8621
|
+
await this.flush.recreate();
|
|
8622
|
+
const { intent_id: _stale, ...fresh } = input;
|
|
8623
|
+
await this.placeOnce(fresh);
|
|
8624
|
+
}
|
|
8625
|
+
return;
|
|
8626
|
+
}
|
|
8627
|
+
await this.placeOrderSmart(input);
|
|
8628
|
+
}
|
|
8629
|
+
async placeOrderSmart(input) {
|
|
8630
|
+
const eligibility = this.getRouteEligibility({ payment: input.payment });
|
|
8631
|
+
const primary = eligibility.preferred;
|
|
8632
|
+
if (!primary) throw new OrderRouteUnavailableError(eligibility);
|
|
8633
|
+
const alternate = eligibility.routes.find((r) => r !== primary) ?? null;
|
|
8634
|
+
let currentInput = input;
|
|
8635
|
+
if (this.persisted && this.activeRoute !== primary) {
|
|
8636
|
+
this.activeRoute = primary;
|
|
8637
|
+
await this.flush.recreate();
|
|
8638
|
+
const { intent_id: _stale, ...fresh } = input;
|
|
8639
|
+
currentInput = fresh;
|
|
8640
|
+
} else if (!this.persisted) this.activeRoute = primary;
|
|
8641
|
+
const state = {
|
|
8642
|
+
placeSent: false,
|
|
8643
|
+
sentBody: null
|
|
8644
|
+
};
|
|
7254
8645
|
try {
|
|
7255
|
-
await this.
|
|
8646
|
+
await this.placeOnceTracked(currentInput, state);
|
|
8647
|
+
const settled = this.activeRoute ?? primary;
|
|
8648
|
+
const url = this.routeBaseUrl(settled);
|
|
8649
|
+
if (url) markRouteHealthy(settled, url, { listener: this.onRouteHealthListener });
|
|
8650
|
+
return;
|
|
7256
8651
|
} catch (error) {
|
|
7257
|
-
if (
|
|
8652
|
+
if (isLocalOrderUnknown(error)) {
|
|
8653
|
+
await this.flush.recreate();
|
|
8654
|
+
const { intent_id: _stale, ...fresh } = currentInput;
|
|
8655
|
+
await this.placeOnceTracked(fresh, {
|
|
8656
|
+
placeSent: false,
|
|
8657
|
+
sentBody: null
|
|
8658
|
+
});
|
|
8659
|
+
return;
|
|
8660
|
+
}
|
|
8661
|
+
await this.recoverPlaceFailure({
|
|
8662
|
+
error,
|
|
8663
|
+
primary,
|
|
8664
|
+
alternate,
|
|
8665
|
+
input,
|
|
8666
|
+
placeSent: state.placeSent,
|
|
8667
|
+
sentBody: state.sentBody
|
|
8668
|
+
});
|
|
8669
|
+
}
|
|
8670
|
+
}
|
|
8671
|
+
async recoverPlaceFailure(ctx) {
|
|
8672
|
+
const { error, primary, alternate, input, placeSent, sentBody } = ctx;
|
|
8673
|
+
const cls = classifyRouteFailure(error, { signal: this.http.signal });
|
|
8674
|
+
if (cls.aborted || cls.kind === "business_4xx") throw error;
|
|
8675
|
+
const primaryUrl = this.routeBaseUrl(primary);
|
|
8676
|
+
let canReroute = cls.shouldReroute || !placeSent;
|
|
8677
|
+
if (placeSent && cls.shouldVerifyOriginal && sentBody) {
|
|
8678
|
+
const outcome = await this.verifyPlacedOnRoute(primary, sentBody);
|
|
8679
|
+
if (outcome.placed) return;
|
|
8680
|
+
if (outcome.absent) canReroute = true;
|
|
8681
|
+
else if (outcome.unreachable) canReroute = true;
|
|
8682
|
+
else {
|
|
8683
|
+
if (primaryUrl) markRouteDown({
|
|
8684
|
+
route: primary,
|
|
8685
|
+
baseUrl: primaryUrl,
|
|
8686
|
+
cooldownMs: this.routes?.cooldownMs,
|
|
8687
|
+
reason: cls.reason,
|
|
8688
|
+
failureKind: cls.kind,
|
|
8689
|
+
listener: this.onRouteHealthListener
|
|
8690
|
+
});
|
|
8691
|
+
throw error;
|
|
8692
|
+
}
|
|
8693
|
+
}
|
|
8694
|
+
if (cls.markRouteDown && primaryUrl) markRouteDown({
|
|
8695
|
+
route: primary,
|
|
8696
|
+
baseUrl: primaryUrl,
|
|
8697
|
+
cooldownMs: this.routes?.cooldownMs,
|
|
8698
|
+
reason: cls.reason,
|
|
8699
|
+
failureKind: cls.kind,
|
|
8700
|
+
listener: this.onRouteHealthListener
|
|
8701
|
+
});
|
|
8702
|
+
if (!canReroute || !alternate || hasInFlightPayment(this.draft)) throw error;
|
|
8703
|
+
if (!this.getRouteEligibility({ payment: input.payment }).routes.includes(alternate)) throw error;
|
|
8704
|
+
this.activeRoute = alternate;
|
|
8705
|
+
try {
|
|
7258
8706
|
await this.flush.recreate();
|
|
7259
8707
|
const { intent_id: _stale, ...fresh } = input;
|
|
7260
|
-
await this.
|
|
8708
|
+
await this.placeOnceTracked(fresh, {
|
|
8709
|
+
placeSent: false,
|
|
8710
|
+
sentBody: null
|
|
8711
|
+
});
|
|
8712
|
+
const altUrl = this.routeBaseUrl(alternate);
|
|
8713
|
+
if (altUrl) markRouteHealthy(alternate, altUrl, { listener: this.onRouteHealthListener });
|
|
8714
|
+
} catch (altError) {
|
|
8715
|
+
const altCls = classifyRouteFailure(altError, { signal: this.http.signal });
|
|
8716
|
+
const altUrl = this.routeBaseUrl(alternate);
|
|
8717
|
+
if (altCls.markRouteDown && altUrl) markRouteDown({
|
|
8718
|
+
route: alternate,
|
|
8719
|
+
baseUrl: altUrl,
|
|
8720
|
+
cooldownMs: this.routes?.cooldownMs,
|
|
8721
|
+
reason: altCls.reason,
|
|
8722
|
+
failureKind: altCls.kind,
|
|
8723
|
+
listener: this.onRouteHealthListener
|
|
8724
|
+
});
|
|
8725
|
+
throw altError;
|
|
8726
|
+
}
|
|
8727
|
+
}
|
|
8728
|
+
async verifyPlacedOnRoute(route, body) {
|
|
8729
|
+
const http = this.routeHttp(route);
|
|
8730
|
+
const url = this.routeBaseUrl(route);
|
|
8731
|
+
try {
|
|
8732
|
+
await services.orders.place(this.draft.id, body, http);
|
|
8733
|
+
} catch (verifyErr) {
|
|
8734
|
+
if (!(verifyErr instanceof StorefrontHttpError && verifyErr.status === 409 && !isLocalOrderUnknown(verifyErr))) {
|
|
8735
|
+
if (verifyErr instanceof StorefrontHttpError && (verifyErr.status === 404 || isLocalOrderUnknown(verifyErr))) return {
|
|
8736
|
+
placed: false,
|
|
8737
|
+
absent: true,
|
|
8738
|
+
unreachable: false
|
|
8739
|
+
};
|
|
8740
|
+
const vCls = classifyRouteFailure(verifyErr, { signal: this.http.signal });
|
|
8741
|
+
return {
|
|
8742
|
+
placed: false,
|
|
8743
|
+
absent: false,
|
|
8744
|
+
unreachable: vCls.kind === "obvious_outage" || vCls.kind === "tls_mismatch" || vCls.kind === "gateway_refusal"
|
|
8745
|
+
};
|
|
8746
|
+
}
|
|
7261
8747
|
}
|
|
8748
|
+
const next = await services.orders.get(this.draft.id, http);
|
|
8749
|
+
this.applyServerOrder(next);
|
|
8750
|
+
if (url) markRouteHealthy(route, url, { listener: this.onRouteHealthListener });
|
|
8751
|
+
return {
|
|
8752
|
+
placed: true,
|
|
8753
|
+
absent: false,
|
|
8754
|
+
unreachable: false
|
|
8755
|
+
};
|
|
7262
8756
|
}
|
|
7263
8757
|
async placeOnce(input) {
|
|
8758
|
+
await this.placeOnceTracked(input, {
|
|
8759
|
+
placeSent: false,
|
|
8760
|
+
sentBody: null
|
|
8761
|
+
});
|
|
8762
|
+
}
|
|
8763
|
+
async placeOnceTracked(input, tracker) {
|
|
7264
8764
|
await this.persist();
|
|
7265
8765
|
await this.flush.settle();
|
|
7266
8766
|
if (!input.intent_id) this.assertPayable(input.payment);
|
|
@@ -7281,13 +8781,16 @@ var Order = class Order {
|
|
|
7281
8781
|
} : { intent_id: intent.id };
|
|
7282
8782
|
}
|
|
7283
8783
|
}
|
|
8784
|
+
const http = this.activeHttp();
|
|
8785
|
+
tracker.placeSent = true;
|
|
8786
|
+
tracker.sentBody = body;
|
|
7284
8787
|
try {
|
|
7285
|
-
await services.orders.place(this.draft.id, body,
|
|
8788
|
+
await services.orders.place(this.draft.id, body, http);
|
|
7286
8789
|
} catch (error) {
|
|
7287
8790
|
const known = !isLocalOrderUnknown(error);
|
|
7288
8791
|
if (!(error instanceof StorefrontHttpError && known) || error.status !== 409) throw error;
|
|
7289
8792
|
}
|
|
7290
|
-
const next = await services.orders.get(this.draft.id,
|
|
8793
|
+
const next = await services.orders.get(this.draft.id, http);
|
|
7291
8794
|
this.applyServerOrder(next);
|
|
7292
8795
|
}
|
|
7293
8796
|
/** Installed `@fire-spark/payments-*` adapters (provider + method). */
|
|
@@ -7321,6 +8824,7 @@ var Order = class Order {
|
|
|
7321
8824
|
/** Merchant payments the tenders point to (`payment_id`). */
|
|
7322
8825
|
setPayments(payments) {
|
|
7323
8826
|
this.payments.registerPayments(payments);
|
|
8827
|
+
this.registerPaymentEligibility(payments);
|
|
7324
8828
|
}
|
|
7325
8829
|
/**
|
|
7326
8830
|
* Places the order if needed and charges its real device tenders in
|
|
@@ -7371,7 +8875,8 @@ var Order = class Order {
|
|
|
7371
8875
|
async freshCancelType() {
|
|
7372
8876
|
if (!this.persisted) throw new Error("Only a placed order is cancelled");
|
|
7373
8877
|
this.flush.cancel();
|
|
7374
|
-
|
|
8878
|
+
const next = await services.orders.get(this.draft.id, this.activeHttp());
|
|
8879
|
+
this.applyServerOrder(next);
|
|
7375
8880
|
return cancelTypeOf(this.draft);
|
|
7376
8881
|
}
|
|
7377
8882
|
async runCancel(path, type, options) {
|
|
@@ -7398,7 +8903,7 @@ var Order = class Order {
|
|
|
7398
8903
|
const call = path === "refund" ? services.orders.refund : services.orders.cancel;
|
|
7399
8904
|
let next;
|
|
7400
8905
|
try {
|
|
7401
|
-
next = await call(this.draft.id, this.
|
|
8906
|
+
next = await call(this.draft.id, this.activeHttp(), body);
|
|
7402
8907
|
} catch (error) {
|
|
7403
8908
|
this.unreported = reversals.filter(isDeviceReversed);
|
|
7404
8909
|
throw error;
|
|
@@ -7431,7 +8936,7 @@ var Order = class Order {
|
|
|
7431
8936
|
this.draft.id,
|
|
7432
8937
|
tenderId,
|
|
7433
8938
|
body,
|
|
7434
|
-
this.
|
|
8939
|
+
this.activeHttp()
|
|
7435
8940
|
];
|
|
7436
8941
|
const next = await services.orders.voidTender(...p1);
|
|
7437
8942
|
this.applyServerOrder(next);
|
|
@@ -7445,7 +8950,7 @@ var Order = class Order {
|
|
|
7445
8950
|
};
|
|
7446
8951
|
const id = this.draft.id;
|
|
7447
8952
|
const refund = services.orders.refundTender;
|
|
7448
|
-
const next = await refund(id, tenderId, body, this.
|
|
8953
|
+
const next = await refund(id, tenderId, body, this.activeHttp());
|
|
7449
8954
|
this.applyServerOrder(next);
|
|
7450
8955
|
return this.getOrder();
|
|
7451
8956
|
}
|
|
@@ -7514,7 +9019,7 @@ var Order = class Order {
|
|
|
7514
9019
|
};
|
|
7515
9020
|
//#endregion
|
|
7516
9021
|
//#region src/order/fulfillmentTrack.ts
|
|
7517
|
-
const isPrimaryPathKind$
|
|
9022
|
+
const isPrimaryPathKind$2 = (pathKind) => {
|
|
7518
9023
|
return pathKind === "default" || pathKind === "success" || pathKind == null;
|
|
7519
9024
|
};
|
|
7520
9025
|
const pathKindForTarget = (target) => {
|
|
@@ -7588,7 +9093,7 @@ const walkPrimaryMilestones = (workflow) => {
|
|
|
7588
9093
|
if (!nodesById.has(edge.source) || !nodesById.has(edge.target)) continue;
|
|
7589
9094
|
const target = nodesById.get(edge.target);
|
|
7590
9095
|
const pathKind = edge.data?.pathKind ?? pathKindForTarget(target);
|
|
7591
|
-
if (!isPrimaryPathKind$
|
|
9096
|
+
if (!isPrimaryPathKind$2(pathKind)) continue;
|
|
7592
9097
|
primaryOut.get(edge.source)?.push(edge.target);
|
|
7593
9098
|
primaryIn.get(edge.target)?.push(edge.source);
|
|
7594
9099
|
}
|
|
@@ -9515,6 +11020,22 @@ const orderIsScheduled = (condition, scheduledAt) => {
|
|
|
9515
11020
|
assert(value != null, "Invalid value");
|
|
9516
11021
|
return matchBooleanOperator(condition, Boolean(scheduledAt));
|
|
9517
11022
|
};
|
|
11023
|
+
const isRunningLocal = (condition, isLocal) => {
|
|
11024
|
+
const { type, primitive, value } = condition;
|
|
11025
|
+
const matcherType = "Is running local";
|
|
11026
|
+
assert(primitive === "boolean", primitiveError("boolean"));
|
|
11027
|
+
assert(type === matcherType, typeError(matcherType));
|
|
11028
|
+
assert(value != null, "Invalid value");
|
|
11029
|
+
return matchBooleanOperator(condition, isLocal ?? false);
|
|
11030
|
+
};
|
|
11031
|
+
const isRunningOffline = (condition, isOffline) => {
|
|
11032
|
+
const { type, primitive, value } = condition;
|
|
11033
|
+
const matcherType = "Is running offline";
|
|
11034
|
+
assert(primitive === "boolean", primitiveError("boolean"));
|
|
11035
|
+
assert(type === matcherType, typeError(matcherType));
|
|
11036
|
+
assert(value != null, "Invalid value");
|
|
11037
|
+
return matchBooleanOperator(condition, isOffline ?? false);
|
|
11038
|
+
};
|
|
9518
11039
|
//#endregion
|
|
9519
11040
|
//#region src/rules/currencyMatcher.ts
|
|
9520
11041
|
const matchCurrencyOperator = (condition, matcher) => {
|
|
@@ -10209,16 +11730,18 @@ var RulesEngine = class {
|
|
|
10209
11730
|
customer;
|
|
10210
11731
|
payment;
|
|
10211
11732
|
monitoring;
|
|
11733
|
+
execution;
|
|
10212
11734
|
referenceDate;
|
|
10213
11735
|
timezone;
|
|
10214
11736
|
runtime;
|
|
10215
11737
|
constructor(params = {}) {
|
|
10216
11738
|
const { order, customer, payment, monitoring, referenceDate } = params;
|
|
10217
|
-
const { runtime, timezone } = params;
|
|
11739
|
+
const { runtime, timezone, execution } = params;
|
|
10218
11740
|
this.order = order;
|
|
10219
11741
|
this.customer = customer;
|
|
10220
11742
|
this.payment = payment;
|
|
10221
11743
|
this.monitoring = monitoring;
|
|
11744
|
+
this.execution = execution;
|
|
10222
11745
|
this.referenceDate = referenceDate;
|
|
10223
11746
|
this.timezone = timezone;
|
|
10224
11747
|
this.runtime = runtime;
|
|
@@ -10326,6 +11849,11 @@ var RulesEngine = class {
|
|
|
10326
11849
|
const order = this.getDependency("order", type);
|
|
10327
11850
|
return orderIsScheduled(condition, order.scheduled_at);
|
|
10328
11851
|
}
|
|
11852
|
+
if (type === "Is running local") return isRunningLocal(condition, this.execution?.is_local);
|
|
11853
|
+
if (type === "Is running offline") {
|
|
11854
|
+
const offline = this.execution?.is_offline;
|
|
11855
|
+
return isRunningOffline(condition, offline);
|
|
11856
|
+
}
|
|
10329
11857
|
throw new Error(`Condition ${type} not supported in boolean matcher`);
|
|
10330
11858
|
};
|
|
10331
11859
|
assertCurrency = (condition) => {
|
|
@@ -12392,7 +13920,7 @@ const paymentFacts = (order) => {
|
|
|
12392
13920
|
captured
|
|
12393
13921
|
};
|
|
12394
13922
|
};
|
|
12395
|
-
const orderFactsFromOrder = (order) => {
|
|
13923
|
+
const orderFactsFromOrder = (order, execution) => {
|
|
12396
13924
|
const lines = (order.lines ?? []).map((line) => {
|
|
12397
13925
|
return {
|
|
12398
13926
|
id: line.id,
|
|
@@ -12421,24 +13949,50 @@ const orderFactsFromOrder = (order) => {
|
|
|
12421
13949
|
scheduled_at
|
|
12422
13950
|
};
|
|
12423
13951
|
const dob = (order.customer?.customer_info)?.dob ?? void 0;
|
|
13952
|
+
const customer = {
|
|
13953
|
+
is_anonymous: order.is_anonymous,
|
|
13954
|
+
dob
|
|
13955
|
+
};
|
|
13956
|
+
const payment = paymentFacts(order);
|
|
13957
|
+
if (execution) return {
|
|
13958
|
+
order: orderScope,
|
|
13959
|
+
customer,
|
|
13960
|
+
payment,
|
|
13961
|
+
execution
|
|
13962
|
+
};
|
|
12424
13963
|
return {
|
|
12425
13964
|
order: orderScope,
|
|
12426
|
-
customer
|
|
12427
|
-
|
|
12428
|
-
dob
|
|
12429
|
-
},
|
|
12430
|
-
payment: paymentFacts(order)
|
|
13965
|
+
customer,
|
|
13966
|
+
payment
|
|
12431
13967
|
};
|
|
12432
13968
|
};
|
|
12433
|
-
const buildRulesEngineFromOrder = (order) => {
|
|
12434
|
-
return new RulesEngine(orderFactsFromOrder(order));
|
|
13969
|
+
const buildRulesEngineFromOrder = (order, execution) => {
|
|
13970
|
+
return new RulesEngine(orderFactsFromOrder(order, execution));
|
|
12435
13971
|
};
|
|
12436
13972
|
//#endregion
|
|
12437
13973
|
//#region src/fulfillment/status.ts
|
|
13974
|
+
/** Terminal fulfillment statuses recognized by the workflow model. */
|
|
13975
|
+
const FULFILLMENT_WORKFLOW_TERMINAL_STATUSES = [
|
|
13976
|
+
"FULFILLED",
|
|
13977
|
+
"VOIDED",
|
|
13978
|
+
"REFUNDED",
|
|
13979
|
+
"REVERSED",
|
|
13980
|
+
"FAILED"
|
|
13981
|
+
];
|
|
13982
|
+
/** System-reserved status keys set by the engine, not merchant steps. */
|
|
13983
|
+
const RESERVED_FULFILLMENT_STATUSES = ["FAILED"];
|
|
13984
|
+
const reservedSet = new Set(RESERVED_FULFILLMENT_STATUSES);
|
|
13985
|
+
const terminalSet = new Set(FULFILLMENT_WORKFLOW_TERMINAL_STATUSES);
|
|
12438
13986
|
/** `injecting` / ` Injecting ` → `INJECTING`. Casing never matters. */
|
|
12439
13987
|
const normalizeFulfillmentStatus = (status) => {
|
|
12440
13988
|
return status.trim().toUpperCase();
|
|
12441
13989
|
};
|
|
13990
|
+
const isReservedFulfillmentStatus = (status) => {
|
|
13991
|
+
return reservedSet.has(normalizeFulfillmentStatus(status));
|
|
13992
|
+
};
|
|
13993
|
+
const isTerminalFulfillmentStatus = (status) => {
|
|
13994
|
+
return terminalSet.has(normalizeFulfillmentStatus(status));
|
|
13995
|
+
};
|
|
12442
13996
|
const fulfillmentStatusesEqual = (left, right) => {
|
|
12443
13997
|
return normalizeFulfillmentStatus(left) === normalizeFulfillmentStatus(right);
|
|
12444
13998
|
};
|
|
@@ -12446,14 +14000,14 @@ const fulfillmentStatusesEqual = (left, right) => {
|
|
|
12446
14000
|
const pathKindForTargetNode = (target) => {
|
|
12447
14001
|
if (!target || target.kind !== "terminal") return "default";
|
|
12448
14002
|
const status = normalizeFulfillmentStatus(target.mappedStatus ?? "");
|
|
12449
|
-
if (status === "VOIDED") return "cancel";
|
|
14003
|
+
if (status === "VOIDED" || status === "FAILED") return "cancel";
|
|
12450
14004
|
if (status === "REFUNDED" || status === "RETURNED") return "refund";
|
|
12451
14005
|
if (status === "REVERSED") return "refund";
|
|
12452
14006
|
return "success";
|
|
12453
14007
|
};
|
|
12454
14008
|
//#endregion
|
|
12455
14009
|
//#region src/fulfillment/graph.ts
|
|
12456
|
-
const isPrimaryPathKind = (pathKind) => {
|
|
14010
|
+
const isPrimaryPathKind$1 = (pathKind) => {
|
|
12457
14011
|
return pathKind === "default" || pathKind === "success" || pathKind == null;
|
|
12458
14012
|
};
|
|
12459
14013
|
const edgePathKind = (edge, target) => {
|
|
@@ -12475,7 +14029,7 @@ const defaultOutgoingEdge = (workflow, nodeId) => {
|
|
|
12475
14029
|
const outgoing = outgoingEdges(workflow, nodeId);
|
|
12476
14030
|
return outgoing.find((edge) => {
|
|
12477
14031
|
const target = findNodeById(workflow, edge.target);
|
|
12478
|
-
return isPrimaryPathKind(edgePathKind(edge, target));
|
|
14032
|
+
return isPrimaryPathKind$1(edgePathKind(edge, target));
|
|
12479
14033
|
}) ?? outgoing[0] ?? null;
|
|
12480
14034
|
};
|
|
12481
14035
|
const findFirstState = (workflow) => {
|
|
@@ -12502,11 +14056,11 @@ const canEnterJoin = (workflow, node) => {
|
|
|
12502
14056
|
if ((node.data.joinPolicy ?? "all") === "any") return taken.length > 0;
|
|
12503
14057
|
return taken.length === incoming.length;
|
|
12504
14058
|
};
|
|
12505
|
-
const edgeMatchesConditions = (edge, order, engine) => {
|
|
14059
|
+
const edgeMatchesConditions = (edge, order, engine, execution) => {
|
|
12506
14060
|
const conditions = edge.data?.conditions ?? [];
|
|
12507
14061
|
if (conditions.length === 0) return true;
|
|
12508
14062
|
try {
|
|
12509
|
-
const rules = engine ?? buildRulesEngineFromOrder(order);
|
|
14063
|
+
const rules = engine ?? buildRulesEngineFromOrder(order, execution);
|
|
12510
14064
|
return Boolean(rules.matchOrConditions(conditions).match);
|
|
12511
14065
|
} catch {
|
|
12512
14066
|
return false;
|
|
@@ -12514,15 +14068,15 @@ const edgeMatchesConditions = (edge, order, engine) => {
|
|
|
12514
14068
|
};
|
|
12515
14069
|
/** Unused primary outs whose conditions match the order (Door fork, etc.). */
|
|
12516
14070
|
const matchingPrimaryOutgoing = (input) => {
|
|
12517
|
-
const { workflow, nodeId, order, outgoingBySource } = input;
|
|
14071
|
+
const { workflow, nodeId, order, execution, outgoingBySource } = input;
|
|
12518
14072
|
const unused = unusedOutgoing(workflow, nodeId, outgoingBySource);
|
|
12519
14073
|
let engine;
|
|
12520
14074
|
const matches = [];
|
|
12521
14075
|
for (const edge of unused) {
|
|
12522
14076
|
const node = input.nodesById?.get(edge.target) ?? findNodeById(workflow, edge.target);
|
|
12523
|
-
if (!isPrimaryPathKind(edgePathKind(edge, node))) continue;
|
|
12524
|
-
if ((edge.data?.conditions ?? []).length > 0 && !engine) engine = buildRulesEngineFromOrder(order);
|
|
12525
|
-
if (!edgeMatchesConditions(edge, order, engine)) continue;
|
|
14077
|
+
if (!isPrimaryPathKind$1(edgePathKind(edge, node))) continue;
|
|
14078
|
+
if ((edge.data?.conditions ?? []).length > 0 && !engine) engine = buildRulesEngineFromOrder(order, execution);
|
|
14079
|
+
if (!edgeMatchesConditions(edge, order, engine, execution)) continue;
|
|
12526
14080
|
matches.push(edge);
|
|
12527
14081
|
}
|
|
12528
14082
|
return matches;
|
|
@@ -12531,18 +14085,28 @@ const matchingPrimaryOutgoing = (input) => {
|
|
|
12531
14085
|
const unusedPrimaryOutgoing = (workflow, nodeId, outgoingBySource, nodesById) => {
|
|
12532
14086
|
return unusedOutgoing(workflow, nodeId, outgoingBySource).filter((edge) => {
|
|
12533
14087
|
const node = nodesById?.get(edge.target) ?? findNodeById(workflow, edge.target);
|
|
12534
|
-
return isPrimaryPathKind(edgePathKind(edge, node));
|
|
14088
|
+
return isPrimaryPathKind$1(edgePathKind(edge, node));
|
|
12535
14089
|
});
|
|
12536
14090
|
};
|
|
12537
14091
|
const leftoverPrimaryOutgoing = (input) => {
|
|
12538
|
-
const { workflow, nodeId, order,
|
|
12539
|
-
|
|
12540
|
-
|
|
12541
|
-
|
|
12542
|
-
|
|
12543
|
-
|
|
12544
|
-
|
|
12545
|
-
|
|
14092
|
+
const { workflow, nodeId, order, execution, outgoingBySource } = input;
|
|
14093
|
+
const { nodesById } = input;
|
|
14094
|
+
if (order) {
|
|
14095
|
+
const p1 = {
|
|
14096
|
+
workflow,
|
|
14097
|
+
nodeId,
|
|
14098
|
+
order,
|
|
14099
|
+
execution
|
|
14100
|
+
};
|
|
14101
|
+
const p2 = {
|
|
14102
|
+
outgoingBySource,
|
|
14103
|
+
nodesById
|
|
14104
|
+
};
|
|
14105
|
+
return matchingPrimaryOutgoing({
|
|
14106
|
+
...p1,
|
|
14107
|
+
...p2
|
|
14108
|
+
});
|
|
14109
|
+
}
|
|
12546
14110
|
return unusedPrimaryOutgoing(workflow, nodeId, outgoingBySource, nodesById);
|
|
12547
14111
|
};
|
|
12548
14112
|
const indexOutgoingBySource = (workflow) => {
|
|
@@ -12569,6 +14133,7 @@ const pickAdvanceTarget = (edges) => {
|
|
|
12569
14133
|
};
|
|
12570
14134
|
const resolveAdvanceEdges = (input) => {
|
|
12571
14135
|
const { workflow, currentNodeIds, fulfillmentStatus, order } = input;
|
|
14136
|
+
const { execution } = input;
|
|
12572
14137
|
if (currentNodeIds.length === 0) return [];
|
|
12573
14138
|
const current = new Set(currentNodeIds);
|
|
12574
14139
|
const nodesById = new Map(workflow.nodes.map((node) => [node.id, node]));
|
|
@@ -12590,8 +14155,8 @@ const resolveAdvanceEdges = (input) => {
|
|
|
12590
14155
|
if (!target) continue;
|
|
12591
14156
|
const mapped = target.data.mappedStatus;
|
|
12592
14157
|
if (!fulfillmentStatusesEqual(mapped, fulfillmentStatus)) continue;
|
|
12593
|
-
if ((edge.data?.conditions ?? []).length > 0 && !engine) engine = buildRulesEngineFromOrder(order);
|
|
12594
|
-
if (!edgeMatchesConditions(edge, order, engine)) continue;
|
|
14158
|
+
if ((edge.data?.conditions ?? []).length > 0 && !engine) engine = buildRulesEngineFromOrder(order, execution);
|
|
14159
|
+
if (!edgeMatchesConditions(edge, order, engine, execution)) continue;
|
|
12595
14160
|
matches.push(edge);
|
|
12596
14161
|
}
|
|
12597
14162
|
}
|
|
@@ -12608,6 +14173,7 @@ const findMappedStatusNode = (workflow, status) => {
|
|
|
12608
14173
|
}) ?? null;
|
|
12609
14174
|
};
|
|
12610
14175
|
const isTerminalMappedStatus = (workflow, status) => {
|
|
14176
|
+
if (isReservedFulfillmentStatus(status)) return true;
|
|
12611
14177
|
return workflow.nodes.some((node) => {
|
|
12612
14178
|
if (node.data.kind !== "terminal") return false;
|
|
12613
14179
|
return fulfillmentStatusesEqual(node.data.mappedStatus, status);
|
|
@@ -12615,7 +14181,7 @@ const isTerminalMappedStatus = (workflow, status) => {
|
|
|
12615
14181
|
};
|
|
12616
14182
|
/** Unused primary outs are only success terminals — ready to auto-enter. */
|
|
12617
14183
|
const resolveSuccessTerminalEdges = (input) => {
|
|
12618
|
-
const { workflow, currentNodeIds, order } = input;
|
|
14184
|
+
const { workflow, currentNodeIds, order, execution } = input;
|
|
12619
14185
|
if (currentNodeIds.length === 0) return [];
|
|
12620
14186
|
const nodesById = new Map(workflow.nodes.map((node) => [node.id, node]));
|
|
12621
14187
|
const outgoingBySource = indexOutgoingBySource(workflow);
|
|
@@ -12624,12 +14190,19 @@ const resolveSuccessTerminalEdges = (input) => {
|
|
|
12624
14190
|
const sitting = nodesById.get(id);
|
|
12625
14191
|
if (!sitting || sitting.data.exited_at) continue;
|
|
12626
14192
|
if (sitting.data.kind === "terminal") continue;
|
|
12627
|
-
const
|
|
14193
|
+
const m1 = {
|
|
12628
14194
|
workflow,
|
|
12629
14195
|
nodeId: id,
|
|
12630
14196
|
order,
|
|
14197
|
+
execution
|
|
14198
|
+
};
|
|
14199
|
+
const m2 = {
|
|
12631
14200
|
outgoingBySource,
|
|
12632
14201
|
nodesById
|
|
14202
|
+
};
|
|
14203
|
+
const matches = matchingPrimaryOutgoing({
|
|
14204
|
+
...m1,
|
|
14205
|
+
...m2
|
|
12633
14206
|
});
|
|
12634
14207
|
if (matches.length === 0) return [];
|
|
12635
14208
|
for (const edge of matches) {
|
|
@@ -12637,7 +14210,7 @@ const resolveSuccessTerminalEdges = (input) => {
|
|
|
12637
14210
|
if (target?.data.kind !== "terminal") return [];
|
|
12638
14211
|
const inferred = pathKindForTargetNode(target.data);
|
|
12639
14212
|
const pathKind = edge.data?.pathKind ?? inferred;
|
|
12640
|
-
if (!isPrimaryPathKind(pathKind) || inferred !== "success") return [];
|
|
14213
|
+
if (!isPrimaryPathKind$1(pathKind) || inferred !== "success") return [];
|
|
12641
14214
|
edges.push(edge);
|
|
12642
14215
|
}
|
|
12643
14216
|
}
|
|
@@ -12653,7 +14226,7 @@ const FAILURE_PATH_KINDS = ["cancel", "refund"];
|
|
|
12653
14226
|
* (§7.1). `null` when none applies: no terminal is invented.
|
|
12654
14227
|
*/
|
|
12655
14228
|
const resolveFailureTerminalEdge = (input) => {
|
|
12656
|
-
const { workflow, currentNodeIds, order } = input;
|
|
14229
|
+
const { workflow, currentNodeIds, order, execution } = input;
|
|
12657
14230
|
const nodesById = new Map(workflow.nodes.map((node) => [node.id, node]));
|
|
12658
14231
|
let engine;
|
|
12659
14232
|
for (const id of currentNodeIds) for (const edge of outgoingEdges(workflow, id)) {
|
|
@@ -12661,8 +14234,8 @@ const resolveFailureTerminalEdge = (input) => {
|
|
|
12661
14234
|
const target = nodesById.get(edge.target);
|
|
12662
14235
|
if (target?.data.kind !== "terminal") continue;
|
|
12663
14236
|
if (!FAILURE_PATH_KINDS.includes(edgePathKind(edge, target))) continue;
|
|
12664
|
-
if ((edge.data?.conditions ?? []).length > 0 && !engine) engine = buildRulesEngineFromOrder(order);
|
|
12665
|
-
if (!edgeMatchesConditions(edge, order, engine)) continue;
|
|
14237
|
+
if ((edge.data?.conditions ?? []).length > 0 && !engine) engine = buildRulesEngineFromOrder(order, execution);
|
|
14238
|
+
if (!edgeMatchesConditions(edge, order, engine, execution)) continue;
|
|
12666
14239
|
return {
|
|
12667
14240
|
edge,
|
|
12668
14241
|
target
|
|
@@ -12688,12 +14261,16 @@ const nextCurrentNodeIds = (input) => {
|
|
|
12688
14261
|
};
|
|
12689
14262
|
const l2 = {
|
|
12690
14263
|
order: input.order,
|
|
14264
|
+
execution: input.execution
|
|
14265
|
+
};
|
|
14266
|
+
const l3 = {
|
|
12691
14267
|
outgoingBySource,
|
|
12692
14268
|
nodesById
|
|
12693
14269
|
};
|
|
12694
14270
|
if (leftoverPrimaryOutgoing({
|
|
12695
14271
|
...l1,
|
|
12696
|
-
...l2
|
|
14272
|
+
...l2,
|
|
14273
|
+
...l3
|
|
12697
14274
|
}).length === 0) next.delete(sourceId);
|
|
12698
14275
|
}
|
|
12699
14276
|
if (target?.data.kind === "join") {
|
|
@@ -12811,7 +14388,7 @@ const markEdgeTaken = (edge, at = (/* @__PURE__ */ new Date()).toISOString()) =>
|
|
|
12811
14388
|
};
|
|
12812
14389
|
};
|
|
12813
14390
|
const enterWorkflowNode = (input) => {
|
|
12814
|
-
const { workflow, nodeId, order } = input;
|
|
14391
|
+
const { workflow, nodeId, order, execution } = input;
|
|
12815
14392
|
const node = findNodeById(workflow, nodeId);
|
|
12816
14393
|
if (!node) throw new Error(`Node ${nodeId} not found`);
|
|
12817
14394
|
const fromEdgeIds = [...input.fromEdgeIds ?? []];
|
|
@@ -12844,6 +14421,7 @@ const enterWorkflowNode = (input) => {
|
|
|
12844
14421
|
workflow,
|
|
12845
14422
|
nodeId: edge.source,
|
|
12846
14423
|
order,
|
|
14424
|
+
execution,
|
|
12847
14425
|
outgoingBySource,
|
|
12848
14426
|
nodesById
|
|
12849
14427
|
};
|
|
@@ -12928,6 +14506,2249 @@ const orderFieldsFromNode = (node, terminalStatus, paymentCaptured = false) => {
|
|
|
12928
14506
|
return status("VOIDED");
|
|
12929
14507
|
};
|
|
12930
14508
|
//#endregion
|
|
14509
|
+
//#region src/fulfillment/engine/engine.types.ts
|
|
14510
|
+
const WORKFLOW_SCHEMA_VERSION = 1;
|
|
14511
|
+
const MAX_SUPPORTED_WORKFLOW_SCHEMA_VERSION = 1;
|
|
14512
|
+
const SCHEDULED_STATUS = "AWAITING_SCHEDULED_TIME";
|
|
14513
|
+
const CALLBACK_MISSING_LOCAL_URL = "CALLBACK_MISSING_LOCAL_URL";
|
|
14514
|
+
const WORKFLOW_TIMEOUT = "WORKFLOW_TIMEOUT";
|
|
14515
|
+
const OFFLINE_NO_LOCAL_URL = "OFFLINE_NO_LOCAL_URL";
|
|
14516
|
+
const DEFAULT_WEBHOOK_TIMEOUT_S = 10;
|
|
14517
|
+
const DEFAULT_MAX_INCOMPLETE_MINUTES = 240;
|
|
14518
|
+
const MIN_MAX_INCOMPLETE_MINUTES = 1;
|
|
14519
|
+
const MAX_MAX_INCOMPLETE_MINUTES = 43200;
|
|
14520
|
+
//#endregion
|
|
14521
|
+
//#region src/fulfillment/engine/timeout.ts
|
|
14522
|
+
const MS_PER_MINUTE = 6e4;
|
|
14523
|
+
const toEpochMs = (value) => {
|
|
14524
|
+
if (value == null) return NaN;
|
|
14525
|
+
if (value instanceof Date) return value.getTime();
|
|
14526
|
+
return Date.parse(value);
|
|
14527
|
+
};
|
|
14528
|
+
const normalizeMaxIncompleteMinutes = (value) => {
|
|
14529
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 1) return Math.min(Math.trunc(value), MAX_MAX_INCOMPLETE_MINUTES);
|
|
14530
|
+
return 240;
|
|
14531
|
+
};
|
|
14532
|
+
/**
|
|
14533
|
+
* Computes `expires_at = max(placed_at, scheduled_at) + max_incomplete_minutes`
|
|
14534
|
+
* so future-scheduled orders do not expire before their scheduled window.
|
|
14535
|
+
*/
|
|
14536
|
+
const computeOrderExpiresAt = (input) => {
|
|
14537
|
+
const placedMs = toEpochMs(input.placedAt);
|
|
14538
|
+
const scheduledMs = toEpochMs(input.scheduledAt);
|
|
14539
|
+
const anchorMs = Number.isFinite(scheduledMs) && scheduledMs > placedMs ? scheduledMs : placedMs;
|
|
14540
|
+
const minutes = normalizeMaxIncompleteMinutes(input.maxIncompleteMinutes);
|
|
14541
|
+
return new Date(anchorMs + minutes * MS_PER_MINUTE).toISOString();
|
|
14542
|
+
};
|
|
14543
|
+
const ACTIVE_RUN_STATUSES = /* @__PURE__ */ new Set(["PROCESSING", "WAITING"]);
|
|
14544
|
+
/** True when a run is still active and its `expires_at` deadline has passed. */
|
|
14545
|
+
const isExpiredFulfillment = (row, now = /* @__PURE__ */ new Date()) => {
|
|
14546
|
+
if (!ACTIVE_RUN_STATUSES.has(row.status)) return false;
|
|
14547
|
+
if (!row.expires_at) return false;
|
|
14548
|
+
const expiresMs = Date.parse(row.expires_at);
|
|
14549
|
+
if (!Number.isFinite(expiresMs)) return false;
|
|
14550
|
+
return expiresMs <= now.getTime();
|
|
14551
|
+
};
|
|
14552
|
+
const labelTextOf = (label) => {
|
|
14553
|
+
if (typeof label === "string") return label.trim() || null;
|
|
14554
|
+
if (!label || typeof label !== "object") return null;
|
|
14555
|
+
const rec = label;
|
|
14556
|
+
for (const key of [
|
|
14557
|
+
"en",
|
|
14558
|
+
"es",
|
|
14559
|
+
"pt-BR"
|
|
14560
|
+
]) {
|
|
14561
|
+
const val = rec[key];
|
|
14562
|
+
if (typeof val === "string" && val.trim()) return val.trim();
|
|
14563
|
+
}
|
|
14564
|
+
for (const val of Object.values(rec)) if (typeof val === "string" && val.trim()) return val.trim();
|
|
14565
|
+
return null;
|
|
14566
|
+
};
|
|
14567
|
+
const buildWorkflowTimeoutDetails = (input) => {
|
|
14568
|
+
const { row, order, createdAt } = input;
|
|
14569
|
+
const now = input.now ?? /* @__PURE__ */ new Date();
|
|
14570
|
+
const maxMinutes = normalizeMaxIncompleteMinutes(input.maxIncompleteMinutes);
|
|
14571
|
+
const placedMs = toEpochMs(order?.issued_at ?? createdAt ?? now);
|
|
14572
|
+
const scheduledMs = toEpochMs(order?.scheduled_at);
|
|
14573
|
+
const anchorMs = Number.isFinite(scheduledMs) && Number.isFinite(placedMs) && scheduledMs > placedMs ? scheduledMs : placedMs;
|
|
14574
|
+
const elapsedMs = Number.isFinite(anchorMs) ? Math.max(0, now.getTime() - anchorMs) : maxMinutes * MS_PER_MINUTE;
|
|
14575
|
+
const elapsed_minutes = Math.max(0, Math.round(elapsedMs / MS_PER_MINUTE));
|
|
14576
|
+
const sitting = sittingWorkflowNode(row.workflow, row.current_node_ids);
|
|
14577
|
+
const node_id = sitting?.id ?? row.current_node_ids[0] ?? null;
|
|
14578
|
+
const node_name = sitting ? labelTextOf(sitting.data.label) ?? sitting.data.mappedStatus ?? null : null;
|
|
14579
|
+
const status = sitting?.data.mappedStatus ?? row.status;
|
|
14580
|
+
const details = {
|
|
14581
|
+
max_incomplete_minutes: maxMinutes,
|
|
14582
|
+
elapsed_minutes,
|
|
14583
|
+
node_id,
|
|
14584
|
+
node_name,
|
|
14585
|
+
status
|
|
14586
|
+
};
|
|
14587
|
+
return {
|
|
14588
|
+
message: `Order exceeded max_incomplete_minutes (${maxMinutes}m) at ${node_name ?? node_id ?? status}`,
|
|
14589
|
+
details
|
|
14590
|
+
};
|
|
14591
|
+
};
|
|
14592
|
+
//#endregion
|
|
14593
|
+
//#region src/fulfillment/engine/versioning.ts
|
|
14594
|
+
var WorkflowSchemaVersionError = class extends Error {
|
|
14595
|
+
code = "UNSUPPORTED_WORKFLOW_SCHEMA_VERSION";
|
|
14596
|
+
schemaVersion;
|
|
14597
|
+
maxSupportedVersion;
|
|
14598
|
+
constructor(schemaVersion, maxSupportedVersion) {
|
|
14599
|
+
const tail = `max supported is ${maxSupportedVersion}`;
|
|
14600
|
+
super(`Unsupported workflow schema version ${schemaVersion} (${tail})`);
|
|
14601
|
+
this.name = "WorkflowSchemaVersionError";
|
|
14602
|
+
this.schemaVersion = schemaVersion;
|
|
14603
|
+
this.maxSupportedVersion = maxSupportedVersion;
|
|
14604
|
+
}
|
|
14605
|
+
};
|
|
14606
|
+
/** Reads the schema version from a workflow object; absent defaults to 1. */
|
|
14607
|
+
const workflowSchemaVersionOf = (workflow) => {
|
|
14608
|
+
if (!workflow || typeof workflow !== "object") return 1;
|
|
14609
|
+
const raw = workflow.schema_version;
|
|
14610
|
+
if (typeof raw === "number" && Number.isInteger(raw) && raw >= 1) return raw;
|
|
14611
|
+
return 1;
|
|
14612
|
+
};
|
|
14613
|
+
const isSupportedWorkflowSchemaVersion = (workflow, maxSupported = 1) => {
|
|
14614
|
+
return workflowSchemaVersionOf(workflow) <= maxSupported;
|
|
14615
|
+
};
|
|
14616
|
+
const assertSupportedWorkflowSchemaVersion = (workflow, maxSupported = 1) => {
|
|
14617
|
+
const version = workflowSchemaVersionOf(workflow);
|
|
14618
|
+
if (version > maxSupported) throw new WorkflowSchemaVersionError(version, maxSupported);
|
|
14619
|
+
return version;
|
|
14620
|
+
};
|
|
14621
|
+
//#endregion
|
|
14622
|
+
//#region src/fulfillment/engine/stepsLogs.ts
|
|
14623
|
+
const STEP_INFO_MESSAGES = {
|
|
14624
|
+
ACCEPTING: "Validating the order and opening fulfillment",
|
|
14625
|
+
PROCESS_STATE_NODE: "Entering a fulfillment state and running actions",
|
|
14626
|
+
PAUSE_FOR_ADVANCE: "Waiting for the next fulfillment status",
|
|
14627
|
+
WARN_NO_EDGE: "No outgoing edge matches the requested status",
|
|
14628
|
+
FINALIZE: "Finalizing the fulfillment run",
|
|
14629
|
+
ROLLBACK_PROCESS_STATE_NODE: "Reverting the last fulfillment state",
|
|
14630
|
+
ROLLBACK_ACCEPT: "Reopening the order after a failed accept"
|
|
14631
|
+
};
|
|
14632
|
+
const isoNow = (now) => (now ? now() : /* @__PURE__ */ new Date()).toISOString();
|
|
14633
|
+
const findActiveStepEntry = (steps_logs, step) => {
|
|
14634
|
+
for (let i = steps_logs.length - 1; i >= 0; i -= 1) {
|
|
14635
|
+
const entry = steps_logs[i];
|
|
14636
|
+
if (entry && entry.step === step && !entry.ended_at) return entry;
|
|
14637
|
+
}
|
|
14638
|
+
};
|
|
14639
|
+
const beginEngineStepLog = (steps_logs, step, message = STEP_INFO_MESSAGES[step], now) => {
|
|
14640
|
+
const started_at = isoNow(now);
|
|
14641
|
+
const log = {
|
|
14642
|
+
type: "info",
|
|
14643
|
+
message
|
|
14644
|
+
};
|
|
14645
|
+
steps_logs.push({
|
|
14646
|
+
started_at,
|
|
14647
|
+
ended_at: null,
|
|
14648
|
+
step,
|
|
14649
|
+
logs: [log]
|
|
14650
|
+
});
|
|
14651
|
+
};
|
|
14652
|
+
const appendEngineStepLog = (steps_logs, step, log) => {
|
|
14653
|
+
const entry = findActiveStepEntry(steps_logs, step);
|
|
14654
|
+
if (!entry) throw new Error(`No active step log for ${step}`);
|
|
14655
|
+
entry.logs.push(log);
|
|
14656
|
+
};
|
|
14657
|
+
const completeEngineStepLog = (steps_logs, step, message, now) => {
|
|
14658
|
+
const entry = findActiveStepEntry(steps_logs, step);
|
|
14659
|
+
if (!entry) throw new Error(`No active step log for ${step}`);
|
|
14660
|
+
entry.ended_at = isoNow(now);
|
|
14661
|
+
entry.logs.push({
|
|
14662
|
+
type: "success",
|
|
14663
|
+
message
|
|
14664
|
+
});
|
|
14665
|
+
};
|
|
14666
|
+
const failActiveEngineStepLog = (steps_logs, message, extra) => {
|
|
14667
|
+
const openEntries = steps_logs.filter((row) => !row.ended_at);
|
|
14668
|
+
const lastOpen = openEntries[openEntries.length - 1];
|
|
14669
|
+
let active = void 0;
|
|
14670
|
+
for (let i = openEntries.length - 1; i >= 0; i -= 1) {
|
|
14671
|
+
const row = openEntries[i];
|
|
14672
|
+
if (row && !row.step.startsWith("ROLLBACK_")) {
|
|
14673
|
+
active = row;
|
|
14674
|
+
break;
|
|
14675
|
+
}
|
|
14676
|
+
}
|
|
14677
|
+
const entry = active ?? lastOpen;
|
|
14678
|
+
if (!entry) return;
|
|
14679
|
+
entry.ended_at = isoNow(extra?.now);
|
|
14680
|
+
const base = {
|
|
14681
|
+
type: "error",
|
|
14682
|
+
message
|
|
14683
|
+
};
|
|
14684
|
+
if (extra?.code) base.code = extra.code;
|
|
14685
|
+
if (extra?.details) base.details = extra.details;
|
|
14686
|
+
entry.logs.push(base);
|
|
14687
|
+
};
|
|
14688
|
+
//#endregion
|
|
14689
|
+
//#region src/fulfillment/engine/processStateNode.ts
|
|
14690
|
+
const isInterruptTerminalStatus = (status) => {
|
|
14691
|
+
if (status === "VOIDED" || status === "REVERSED") return true;
|
|
14692
|
+
if (status === "REFUNDED" || status === "CANCELLED") return true;
|
|
14693
|
+
return status === "FAILED";
|
|
14694
|
+
};
|
|
14695
|
+
const defaultIsPaymentCaptured = (order) => {
|
|
14696
|
+
if (order.payment_status === "PAID") return true;
|
|
14697
|
+
return liveTenders(currentIntent(order.payment_intents ?? [])).some((tender) => tender.status === "PAID");
|
|
14698
|
+
};
|
|
14699
|
+
const callbackIdsFromNode = (actions) => {
|
|
14700
|
+
const ids = [];
|
|
14701
|
+
for (const action of actions ?? []) {
|
|
14702
|
+
if (action.type !== "invoke_callback") continue;
|
|
14703
|
+
for (const id of action.callback_ids ?? []) if (!ids.includes(id)) ids.push(id);
|
|
14704
|
+
}
|
|
14705
|
+
return ids;
|
|
14706
|
+
};
|
|
14707
|
+
const callbackJobsForIds = (workflow, nodeIds) => {
|
|
14708
|
+
const jobs = [];
|
|
14709
|
+
for (const nodeId of nodeIds) {
|
|
14710
|
+
const node = findNodeById(workflow, nodeId);
|
|
14711
|
+
if (!node) continue;
|
|
14712
|
+
const callback_ids = callbackIdsFromNode(node.data.actions);
|
|
14713
|
+
if (callback_ids.length === 0) continue;
|
|
14714
|
+
jobs.push({
|
|
14715
|
+
nodeId,
|
|
14716
|
+
callback_ids
|
|
14717
|
+
});
|
|
14718
|
+
}
|
|
14719
|
+
return jobs;
|
|
14720
|
+
};
|
|
14721
|
+
const enterNode = (input) => {
|
|
14722
|
+
const node = enterWorkflowNode(input);
|
|
14723
|
+
if (node && !input.enteredIds.includes(node.id)) input.enteredIds.push(node.id);
|
|
14724
|
+
return node;
|
|
14725
|
+
};
|
|
14726
|
+
const resolveFromEdgeIds = (config) => {
|
|
14727
|
+
const fromEdgeIds = [...config.fromEdgeIds ?? []];
|
|
14728
|
+
if (config.fromEdgeId && !fromEdgeIds.includes(config.fromEdgeId)) fromEdgeIds.push(config.fromEdgeId);
|
|
14729
|
+
return fromEdgeIds;
|
|
14730
|
+
};
|
|
14731
|
+
const incomingToTarget = (workflow, currentNodeIds, targetId, order, execution) => {
|
|
14732
|
+
const mapped = findNodeById(workflow, targetId)?.data.mappedStatus;
|
|
14733
|
+
if (!mapped) return [];
|
|
14734
|
+
return resolveAdvanceEdges({
|
|
14735
|
+
workflow,
|
|
14736
|
+
currentNodeIds,
|
|
14737
|
+
fulfillmentStatus: mapped,
|
|
14738
|
+
order,
|
|
14739
|
+
execution
|
|
14740
|
+
}).filter((edge) => edge.target === targetId);
|
|
14741
|
+
};
|
|
14742
|
+
const alreadyTerminalResult = (order, row) => {
|
|
14743
|
+
const fallback = row.current_node_ids[0] ?? "";
|
|
14744
|
+
const ids = row.current_node_ids;
|
|
14745
|
+
const r1 = {
|
|
14746
|
+
currentNodeId: sittingWorkflowNode(row.workflow, ids, fallback)?.id ?? "",
|
|
14747
|
+
kind: "terminal"
|
|
14748
|
+
};
|
|
14749
|
+
const r2 = {
|
|
14750
|
+
mappedStatus: order.status,
|
|
14751
|
+
entered: true
|
|
14752
|
+
};
|
|
14753
|
+
const r3 = { currentNodeIds: row.current_node_ids };
|
|
14754
|
+
const r4 = {
|
|
14755
|
+
previousNodeIds: row.current_node_ids,
|
|
14756
|
+
callbackJobs: []
|
|
14757
|
+
};
|
|
14758
|
+
const r5 = {
|
|
14759
|
+
successTerminal: null,
|
|
14760
|
+
alreadyTerminal: true
|
|
14761
|
+
};
|
|
14762
|
+
return {
|
|
14763
|
+
...r1,
|
|
14764
|
+
...r2,
|
|
14765
|
+
...r3,
|
|
14766
|
+
...r4,
|
|
14767
|
+
...r5
|
|
14768
|
+
};
|
|
14769
|
+
};
|
|
14770
|
+
const applyTakenTargets = (input) => {
|
|
14771
|
+
const { workflow, order, execution, enteredIds } = input;
|
|
14772
|
+
let currentNodeIds = [...input.currentNodeIds];
|
|
14773
|
+
const takenIds = [];
|
|
14774
|
+
const fromEdgeIds = [];
|
|
14775
|
+
for (const edge of input.edges) {
|
|
14776
|
+
const e1 = {
|
|
14777
|
+
workflow,
|
|
14778
|
+
nodeId: edge.target,
|
|
14779
|
+
fromEdgeId: edge.id
|
|
14780
|
+
};
|
|
14781
|
+
const entered = enterNode({
|
|
14782
|
+
...e1,
|
|
14783
|
+
order,
|
|
14784
|
+
execution,
|
|
14785
|
+
enteredIds
|
|
14786
|
+
});
|
|
14787
|
+
if (!entered) continue;
|
|
14788
|
+
takenIds.push(entered.id);
|
|
14789
|
+
fromEdgeIds.push(edge.id);
|
|
14790
|
+
const n1 = {
|
|
14791
|
+
workflow,
|
|
14792
|
+
currentNodeIds,
|
|
14793
|
+
targetId: entered.id
|
|
14794
|
+
};
|
|
14795
|
+
const n2 = {
|
|
14796
|
+
entered: true,
|
|
14797
|
+
takenSourceIds: [edge.source]
|
|
14798
|
+
};
|
|
14799
|
+
currentNodeIds = nextCurrentNodeIds({
|
|
14800
|
+
...n1,
|
|
14801
|
+
...n2,
|
|
14802
|
+
order,
|
|
14803
|
+
execution
|
|
14804
|
+
});
|
|
14805
|
+
}
|
|
14806
|
+
return {
|
|
14807
|
+
currentNodeIds,
|
|
14808
|
+
enteredIds: takenIds,
|
|
14809
|
+
fromEdgeIds
|
|
14810
|
+
};
|
|
14811
|
+
};
|
|
14812
|
+
/** When nothing is scheduled, sit on the next node before the status write. */
|
|
14813
|
+
const skipEmptySchedule = (input) => {
|
|
14814
|
+
const targetId = input.targetId;
|
|
14815
|
+
const nodes = input.currentNodeIds;
|
|
14816
|
+
const same = {
|
|
14817
|
+
currentNodeIds: nodes,
|
|
14818
|
+
targetId
|
|
14819
|
+
};
|
|
14820
|
+
if (!targetId || input.order.scheduled_at) return same;
|
|
14821
|
+
const seated = sittingWorkflowNode(...[
|
|
14822
|
+
input.workflow,
|
|
14823
|
+
nodes,
|
|
14824
|
+
targetId
|
|
14825
|
+
]);
|
|
14826
|
+
const waiting = seated?.data.mappedStatus === SCHEDULED_STATUS;
|
|
14827
|
+
if (!seated || !waiting) return same;
|
|
14828
|
+
const b1 = {
|
|
14829
|
+
workflow: input.workflow,
|
|
14830
|
+
nodeId: seated.id
|
|
14831
|
+
};
|
|
14832
|
+
const b2 = {
|
|
14833
|
+
order: input.order,
|
|
14834
|
+
execution: input.execution
|
|
14835
|
+
};
|
|
14836
|
+
const edge = matchingPrimaryOutgoing({
|
|
14837
|
+
...b1,
|
|
14838
|
+
...b2
|
|
14839
|
+
})[0];
|
|
14840
|
+
if (!edge) return same;
|
|
14841
|
+
const e1 = {
|
|
14842
|
+
workflow: input.workflow,
|
|
14843
|
+
nodeId: edge.target
|
|
14844
|
+
};
|
|
14845
|
+
const e2 = {
|
|
14846
|
+
fromEdgeIds: [edge.id],
|
|
14847
|
+
order: input.order
|
|
14848
|
+
};
|
|
14849
|
+
const e3 = {
|
|
14850
|
+
execution: input.execution,
|
|
14851
|
+
enteredIds: input.enteredIds
|
|
14852
|
+
};
|
|
14853
|
+
if (!enterNode({
|
|
14854
|
+
...e1,
|
|
14855
|
+
...e2,
|
|
14856
|
+
...e3
|
|
14857
|
+
})) return same;
|
|
14858
|
+
markNodeSkipped(seated);
|
|
14859
|
+
const at = input.enteredIds.indexOf(seated.id);
|
|
14860
|
+
if (at >= 0) input.enteredIds.splice(at, 1);
|
|
14861
|
+
const n1 = {
|
|
14862
|
+
workflow: input.workflow,
|
|
14863
|
+
currentNodeIds: nodes
|
|
14864
|
+
};
|
|
14865
|
+
const n2 = {
|
|
14866
|
+
targetId: edge.target,
|
|
14867
|
+
entered: true
|
|
14868
|
+
};
|
|
14869
|
+
const n3 = {
|
|
14870
|
+
takenSourceIds: [seated.id],
|
|
14871
|
+
order: input.order
|
|
14872
|
+
};
|
|
14873
|
+
return {
|
|
14874
|
+
currentNodeIds: nextCurrentNodeIds({
|
|
14875
|
+
...n1,
|
|
14876
|
+
...n2,
|
|
14877
|
+
...n3,
|
|
14878
|
+
execution: input.execution
|
|
14879
|
+
}),
|
|
14880
|
+
targetId: edge.target
|
|
14881
|
+
};
|
|
14882
|
+
};
|
|
14883
|
+
const formatError = (error) => {
|
|
14884
|
+
return error instanceof Error ? error.message : String(error);
|
|
14885
|
+
};
|
|
14886
|
+
const processStateNode = async (ports, config) => {
|
|
14887
|
+
const { storage, execution: execPort } = ports;
|
|
14888
|
+
const { orderFulfillmentId, orderId } = config;
|
|
14889
|
+
const now = execPort.now;
|
|
14890
|
+
const execCtx = execPort.getExecutionContext();
|
|
14891
|
+
const [row, order] = await Promise.all([storage.getOrderFulfillment(orderFulfillmentId), storage.getOrder(orderId)]);
|
|
14892
|
+
if (!row) throw new Error("Order fulfillment not found");
|
|
14893
|
+
if (!order) throw new Error("Order not found");
|
|
14894
|
+
const steps_logs = row.steps_logs;
|
|
14895
|
+
beginEngineStepLog(steps_logs, "PROCESS_STATE_NODE", void 0, now);
|
|
14896
|
+
if (isInterruptTerminalStatus(order.status)) {
|
|
14897
|
+
completeEngineStepLog(steps_logs, "PROCESS_STATE_NODE", "Already terminal", now);
|
|
14898
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, { steps_logs });
|
|
14899
|
+
const ntf = {
|
|
14900
|
+
orderFulfillmentId,
|
|
14901
|
+
row,
|
|
14902
|
+
order
|
|
14903
|
+
};
|
|
14904
|
+
await execPort.onOrderChanged?.(ntf);
|
|
14905
|
+
return alreadyTerminalResult(order, row);
|
|
14906
|
+
}
|
|
14907
|
+
try {
|
|
14908
|
+
const workflow = row.workflow;
|
|
14909
|
+
let previousNodeIds = [...row.current_node_ids];
|
|
14910
|
+
let targetId = config.nodeId;
|
|
14911
|
+
let fromEdgeIds = resolveFromEdgeIds(config);
|
|
14912
|
+
let fromEdgeId = fromEdgeIds[0];
|
|
14913
|
+
let currentNodeIds = previousNodeIds;
|
|
14914
|
+
let entered = true;
|
|
14915
|
+
const enteredIds = [];
|
|
14916
|
+
if (config.traverseStart || !targetId) {
|
|
14917
|
+
const start = findStartNode(workflow);
|
|
14918
|
+
if (!start) throw new Error("Fulfillment workflow has no start node");
|
|
14919
|
+
const s0 = {
|
|
14920
|
+
workflow,
|
|
14921
|
+
nodeId: start.id,
|
|
14922
|
+
order,
|
|
14923
|
+
execution: execCtx
|
|
14924
|
+
};
|
|
14925
|
+
enterNode({
|
|
14926
|
+
...s0,
|
|
14927
|
+
enteredIds
|
|
14928
|
+
});
|
|
14929
|
+
previousNodeIds = [start.id];
|
|
14930
|
+
currentNodeIds = [start.id];
|
|
14931
|
+
const matches = matchingPrimaryOutgoing({
|
|
14932
|
+
workflow,
|
|
14933
|
+
nodeId: start.id,
|
|
14934
|
+
order,
|
|
14935
|
+
execution: execCtx
|
|
14936
|
+
});
|
|
14937
|
+
if (matches.length > 0) {
|
|
14938
|
+
const edges = matches.map((edge) => {
|
|
14939
|
+
return {
|
|
14940
|
+
id: edge.id,
|
|
14941
|
+
source: edge.source,
|
|
14942
|
+
target: edge.target
|
|
14943
|
+
};
|
|
14944
|
+
});
|
|
14945
|
+
const applied = applyTakenTargets({
|
|
14946
|
+
workflow,
|
|
14947
|
+
currentNodeIds,
|
|
14948
|
+
order,
|
|
14949
|
+
execution: execCtx,
|
|
14950
|
+
edges,
|
|
14951
|
+
enteredIds
|
|
14952
|
+
});
|
|
14953
|
+
currentNodeIds = applied.currentNodeIds;
|
|
14954
|
+
fromEdgeIds = applied.fromEdgeIds;
|
|
14955
|
+
fromEdgeId = fromEdgeIds[0];
|
|
14956
|
+
targetId = applied.enteredIds[0] ?? start.id;
|
|
14957
|
+
} else {
|
|
14958
|
+
const first = findFirstState(workflow);
|
|
14959
|
+
if (!first) throw new Error("Fulfillment workflow has no state");
|
|
14960
|
+
if (first.id !== start.id) {
|
|
14961
|
+
const edge = defaultOutgoingEdge(workflow, start.id);
|
|
14962
|
+
if (edge) fromEdgeIds.push(edge.id);
|
|
14963
|
+
fromEdgeId = edge?.id;
|
|
14964
|
+
const e1 = {
|
|
14965
|
+
workflow,
|
|
14966
|
+
nodeId: first.id,
|
|
14967
|
+
fromEdgeId,
|
|
14968
|
+
order
|
|
14969
|
+
};
|
|
14970
|
+
const next = enterNode({
|
|
14971
|
+
...e1,
|
|
14972
|
+
execution: execCtx,
|
|
14973
|
+
enteredIds
|
|
14974
|
+
});
|
|
14975
|
+
targetId = next?.id ?? start.id;
|
|
14976
|
+
if (next) {
|
|
14977
|
+
const n1 = {
|
|
14978
|
+
workflow,
|
|
14979
|
+
currentNodeIds,
|
|
14980
|
+
targetId: next.id
|
|
14981
|
+
};
|
|
14982
|
+
const n2 = { entered: true };
|
|
14983
|
+
const n3 = { takenSourceIds: edge ? [edge.source] : [] };
|
|
14984
|
+
const n4 = {
|
|
14985
|
+
order,
|
|
14986
|
+
execution: execCtx
|
|
14987
|
+
};
|
|
14988
|
+
currentNodeIds = nextCurrentNodeIds({
|
|
14989
|
+
...n1,
|
|
14990
|
+
...n2,
|
|
14991
|
+
...n3,
|
|
14992
|
+
...n4
|
|
14993
|
+
});
|
|
14994
|
+
}
|
|
14995
|
+
} else targetId = first.id;
|
|
14996
|
+
}
|
|
14997
|
+
} else {
|
|
14998
|
+
if (fromEdgeIds.length === 0 && targetId) {
|
|
14999
|
+
fromEdgeIds = incomingToTarget(...[
|
|
15000
|
+
workflow,
|
|
15001
|
+
previousNodeIds,
|
|
15002
|
+
targetId,
|
|
15003
|
+
order
|
|
15004
|
+
], execCtx).map((edge) => edge.id);
|
|
15005
|
+
fromEdgeId = fromEdgeIds[0];
|
|
15006
|
+
}
|
|
15007
|
+
if (!enterNode({
|
|
15008
|
+
workflow,
|
|
15009
|
+
nodeId: targetId,
|
|
15010
|
+
fromEdgeIds,
|
|
15011
|
+
order,
|
|
15012
|
+
execution: execCtx,
|
|
15013
|
+
enteredIds
|
|
15014
|
+
})) {
|
|
15015
|
+
entered = false;
|
|
15016
|
+
const current = sittingWorkflowNode(...[
|
|
15017
|
+
workflow,
|
|
15018
|
+
previousNodeIds,
|
|
15019
|
+
targetId
|
|
15020
|
+
]);
|
|
15021
|
+
if (!current) throw new Error("Current node not found");
|
|
15022
|
+
completeEngineStepLog(steps_logs, "PROCESS_STATE_NODE", "Join not ready", now);
|
|
15023
|
+
const u1 = {
|
|
15024
|
+
workflow,
|
|
15025
|
+
steps_logs,
|
|
15026
|
+
warning_count: (row.warning_count ?? 0) + 1
|
|
15027
|
+
};
|
|
15028
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, u1);
|
|
15029
|
+
const r1 = {
|
|
15030
|
+
currentNodeId: current.id,
|
|
15031
|
+
kind: current.data.kind
|
|
15032
|
+
};
|
|
15033
|
+
const r2 = {
|
|
15034
|
+
mappedStatus: current.data.mappedStatus,
|
|
15035
|
+
entered: false
|
|
15036
|
+
};
|
|
15037
|
+
const r3 = {
|
|
15038
|
+
currentNodeIds: previousNodeIds,
|
|
15039
|
+
previousNodeIds
|
|
15040
|
+
};
|
|
15041
|
+
const r4 = {
|
|
15042
|
+
fromEdgeId,
|
|
15043
|
+
fromEdgeIds,
|
|
15044
|
+
callbackJobs: []
|
|
15045
|
+
};
|
|
15046
|
+
return {
|
|
15047
|
+
...r1,
|
|
15048
|
+
...r2,
|
|
15049
|
+
...r3,
|
|
15050
|
+
...r4,
|
|
15051
|
+
successTerminal: null
|
|
15052
|
+
};
|
|
15053
|
+
}
|
|
15054
|
+
const takenSourceIds = [];
|
|
15055
|
+
if (fromEdgeIds.length > 0) {
|
|
15056
|
+
const edgesById = new Map(workflow.edges.map((edge) => [edge.id, edge]));
|
|
15057
|
+
for (const edgeId of fromEdgeIds) {
|
|
15058
|
+
const edge = edgesById.get(edgeId);
|
|
15059
|
+
if (edge) takenSourceIds.push(edge.source);
|
|
15060
|
+
}
|
|
15061
|
+
}
|
|
15062
|
+
const n1 = {
|
|
15063
|
+
workflow,
|
|
15064
|
+
currentNodeIds: previousNodeIds,
|
|
15065
|
+
targetId
|
|
15066
|
+
};
|
|
15067
|
+
const n2 = {
|
|
15068
|
+
entered: true,
|
|
15069
|
+
takenSourceIds,
|
|
15070
|
+
order
|
|
15071
|
+
};
|
|
15072
|
+
currentNodeIds = nextCurrentNodeIds({
|
|
15073
|
+
...n1,
|
|
15074
|
+
...n2,
|
|
15075
|
+
execution: execCtx
|
|
15076
|
+
});
|
|
15077
|
+
}
|
|
15078
|
+
const skipped = skipEmptySchedule({
|
|
15079
|
+
workflow,
|
|
15080
|
+
currentNodeIds,
|
|
15081
|
+
targetId,
|
|
15082
|
+
order,
|
|
15083
|
+
execution: execCtx,
|
|
15084
|
+
enteredIds
|
|
15085
|
+
});
|
|
15086
|
+
currentNodeIds = skipped.currentNodeIds;
|
|
15087
|
+
if (skipped.targetId) targetId = skipped.targetId;
|
|
15088
|
+
const current = sittingWorkflowNode(workflow, currentNodeIds, targetId);
|
|
15089
|
+
if (!current) throw new Error(`Node ${targetId} not found`);
|
|
15090
|
+
const latest = await storage.getOrder(orderId);
|
|
15091
|
+
if (isInterruptTerminalStatus(latest?.status)) {
|
|
15092
|
+
completeEngineStepLog(steps_logs, "PROCESS_STATE_NODE", "Already terminal", now);
|
|
15093
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, { steps_logs });
|
|
15094
|
+
const ntf = {
|
|
15095
|
+
orderFulfillmentId,
|
|
15096
|
+
row,
|
|
15097
|
+
order: latest
|
|
15098
|
+
};
|
|
15099
|
+
await execPort.onOrderChanged?.(ntf);
|
|
15100
|
+
return alreadyTerminalResult(latest, row);
|
|
15101
|
+
}
|
|
15102
|
+
const isCaptured = execPort.isPaymentCaptured ?? defaultIsPaymentCaptured;
|
|
15103
|
+
const captured = latest ? isCaptured(latest) : false;
|
|
15104
|
+
const s2 = { fulfillment_status: current.data.mappedStatus };
|
|
15105
|
+
const s3 = orderFieldsFromNode(current, config.terminalStatus, captured);
|
|
15106
|
+
await storage.updateOrderStatusAndSettle(orderId, {
|
|
15107
|
+
...s2,
|
|
15108
|
+
...s3
|
|
15109
|
+
});
|
|
15110
|
+
completeEngineStepLog(steps_logs, "PROCESS_STATE_NODE", `Entered ${current.id}`, now);
|
|
15111
|
+
const p1 = {
|
|
15112
|
+
workflow,
|
|
15113
|
+
current_node_ids: currentNodeIds,
|
|
15114
|
+
steps_logs
|
|
15115
|
+
};
|
|
15116
|
+
const p2 = { step: "PROCESS_STATE_NODE" };
|
|
15117
|
+
const p3 = { status: "PROCESSING" };
|
|
15118
|
+
const p4 = config.runId ? { run_id: config.runId } : {};
|
|
15119
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, {
|
|
15120
|
+
...p1,
|
|
15121
|
+
...p2,
|
|
15122
|
+
...p3,
|
|
15123
|
+
...p4
|
|
15124
|
+
});
|
|
15125
|
+
const baseOrder = latest ?? order;
|
|
15126
|
+
const snapOrder = {
|
|
15127
|
+
...baseOrder,
|
|
15128
|
+
...s2,
|
|
15129
|
+
...s3
|
|
15130
|
+
};
|
|
15131
|
+
const callbackJobs = callbackJobsForIds(workflow, enteredIds);
|
|
15132
|
+
const payment_status = baseOrder.payment_status;
|
|
15133
|
+
const successEdges = resolveSuccessTerminalEdges({
|
|
15134
|
+
workflow,
|
|
15135
|
+
currentNodeIds,
|
|
15136
|
+
order: snapOrder,
|
|
15137
|
+
execution: execCtx
|
|
15138
|
+
});
|
|
15139
|
+
const firstSuccess = successEdges[0];
|
|
15140
|
+
let successTerminal = null;
|
|
15141
|
+
if (firstSuccess) {
|
|
15142
|
+
const edgeIds = successEdges.map((edge) => edge.id);
|
|
15143
|
+
successTerminal = {
|
|
15144
|
+
nodeId: firstSuccess.target,
|
|
15145
|
+
edgeIds
|
|
15146
|
+
};
|
|
15147
|
+
}
|
|
15148
|
+
const r1 = {
|
|
15149
|
+
currentNodeId: current.id,
|
|
15150
|
+
kind: current.data.kind
|
|
15151
|
+
};
|
|
15152
|
+
const r2 = {
|
|
15153
|
+
mappedStatus: current.data.mappedStatus,
|
|
15154
|
+
entered
|
|
15155
|
+
};
|
|
15156
|
+
const r3 = {
|
|
15157
|
+
currentNodeIds,
|
|
15158
|
+
previousNodeIds,
|
|
15159
|
+
fromEdgeId,
|
|
15160
|
+
fromEdgeIds
|
|
15161
|
+
};
|
|
15162
|
+
const r4 = {
|
|
15163
|
+
callbackJobs,
|
|
15164
|
+
payment_status,
|
|
15165
|
+
successTerminal
|
|
15166
|
+
};
|
|
15167
|
+
return {
|
|
15168
|
+
...r1,
|
|
15169
|
+
...r2,
|
|
15170
|
+
...r3,
|
|
15171
|
+
...r4
|
|
15172
|
+
};
|
|
15173
|
+
} catch (error) {
|
|
15174
|
+
failActiveEngineStepLog(steps_logs, formatError(error), { now });
|
|
15175
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, { steps_logs });
|
|
15176
|
+
throw error;
|
|
15177
|
+
}
|
|
15178
|
+
};
|
|
15179
|
+
//#endregion
|
|
15180
|
+
//#region src/fulfillment/engine/pauseForAdvance.ts
|
|
15181
|
+
const WAITING_STEP = "PAUSE_FOR_ADVANCE";
|
|
15182
|
+
const isWaitingPaymentNode = (row) => {
|
|
15183
|
+
for (const id of row.current_node_ids) {
|
|
15184
|
+
const node = findNodeById(row.workflow, id);
|
|
15185
|
+
if (!node) continue;
|
|
15186
|
+
if (fulfillmentStatusesEqual(node.data.mappedStatus, "PAYING")) return true;
|
|
15187
|
+
}
|
|
15188
|
+
return false;
|
|
15189
|
+
};
|
|
15190
|
+
const pauseForAdvance = async (ports, config) => {
|
|
15191
|
+
const { storage, execution: execPort } = ports;
|
|
15192
|
+
const { orderFulfillmentId } = config;
|
|
15193
|
+
const now = execPort.now;
|
|
15194
|
+
const row = await storage.getOrderFulfillment(orderFulfillmentId);
|
|
15195
|
+
if (!row) throw new Error("Order fulfillment not found");
|
|
15196
|
+
if (row.status === "PROCESSING" && row.step === WAITING_STEP) return;
|
|
15197
|
+
const already = row.status === "WAITING" && row.step === WAITING_STEP;
|
|
15198
|
+
const steps_logs = row.steps_logs;
|
|
15199
|
+
let order = null;
|
|
15200
|
+
if (!already) {
|
|
15201
|
+
if (row.status !== "PROCESSING") return;
|
|
15202
|
+
beginEngineStepLog(steps_logs, WAITING_STEP, void 0, now);
|
|
15203
|
+
const at = (now ? now() : /* @__PURE__ */ new Date()).toISOString();
|
|
15204
|
+
markNodesReady({
|
|
15205
|
+
workflow: row.workflow,
|
|
15206
|
+
nodeIds: row.current_node_ids,
|
|
15207
|
+
at
|
|
15208
|
+
});
|
|
15209
|
+
const patch = {
|
|
15210
|
+
steps_logs,
|
|
15211
|
+
workflow: row.workflow
|
|
15212
|
+
};
|
|
15213
|
+
const [paused, loaded] = await Promise.all([storage.casPauseOrderFulfillment(orderFulfillmentId, patch), storage.getOrder(row.order_id)]);
|
|
15214
|
+
if (!paused) return;
|
|
15215
|
+
order = loaded;
|
|
15216
|
+
}
|
|
15217
|
+
const u2 = {
|
|
15218
|
+
status: "WAITING",
|
|
15219
|
+
step: WAITING_STEP
|
|
15220
|
+
};
|
|
15221
|
+
const patched = {
|
|
15222
|
+
...row,
|
|
15223
|
+
...u2,
|
|
15224
|
+
steps_logs
|
|
15225
|
+
};
|
|
15226
|
+
if (order) await execPort.onOrderChanged?.({
|
|
15227
|
+
orderFulfillmentId,
|
|
15228
|
+
row: patched,
|
|
15229
|
+
order
|
|
15230
|
+
});
|
|
15231
|
+
if (isWaitingPaymentNode(patched)) await execPort.onWaitingPayment?.(row.order_id);
|
|
15232
|
+
};
|
|
15233
|
+
const resumeFromAdvance = async (ports, config) => {
|
|
15234
|
+
const { storage, execution: execPort } = ports;
|
|
15235
|
+
const now = execPort.now;
|
|
15236
|
+
const resumedAt = (now ? now() : /* @__PURE__ */ new Date()).toISOString();
|
|
15237
|
+
const { orderFulfillmentId, orderId } = config;
|
|
15238
|
+
const [row, order] = await Promise.all([storage.getOrderFulfillment(orderFulfillmentId), storage.getOrder(orderId)]);
|
|
15239
|
+
if (!row) throw new Error("Order fulfillment not found");
|
|
15240
|
+
const steps_logs = row.steps_logs;
|
|
15241
|
+
if (steps_logs.some((entry) => entry.step === WAITING_STEP && !entry.ended_at)) completeEngineStepLog(steps_logs, WAITING_STEP, "Advance resumed", now);
|
|
15242
|
+
const { fulfillmentStatus, requestedAt } = config;
|
|
15243
|
+
let edges = [];
|
|
15244
|
+
if (order && fulfillmentStatus) {
|
|
15245
|
+
const execCtx = execPort.getExecutionContext();
|
|
15246
|
+
const r1 = {
|
|
15247
|
+
workflow: row.workflow,
|
|
15248
|
+
order,
|
|
15249
|
+
fulfillmentStatus
|
|
15250
|
+
};
|
|
15251
|
+
const r2 = {
|
|
15252
|
+
currentNodeIds: row.current_node_ids,
|
|
15253
|
+
execution: execCtx
|
|
15254
|
+
};
|
|
15255
|
+
edges = resolveAdvanceEdges({
|
|
15256
|
+
...r1,
|
|
15257
|
+
...r2
|
|
15258
|
+
});
|
|
15259
|
+
const nodeIds = edges.map((edge) => edge.source);
|
|
15260
|
+
markNodesAdvance({
|
|
15261
|
+
workflow: row.workflow,
|
|
15262
|
+
nodeIds,
|
|
15263
|
+
resumedAt,
|
|
15264
|
+
requestedAt
|
|
15265
|
+
});
|
|
15266
|
+
}
|
|
15267
|
+
const patch = {
|
|
15268
|
+
steps_logs,
|
|
15269
|
+
status: "PROCESSING",
|
|
15270
|
+
workflow: row.workflow
|
|
15271
|
+
};
|
|
15272
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, patch);
|
|
15273
|
+
if (!order) return { edges: null };
|
|
15274
|
+
if (config.emit === false) return { edges };
|
|
15275
|
+
const patched = {
|
|
15276
|
+
...row,
|
|
15277
|
+
...patch
|
|
15278
|
+
};
|
|
15279
|
+
await execPort.onOrderChanged?.({
|
|
15280
|
+
orderFulfillmentId,
|
|
15281
|
+
row: patched,
|
|
15282
|
+
order
|
|
15283
|
+
});
|
|
15284
|
+
return { edges };
|
|
15285
|
+
};
|
|
15286
|
+
//#endregion
|
|
15287
|
+
//#region src/fulfillment/engine/enterAndPause.ts
|
|
15288
|
+
/**
|
|
15289
|
+
* Nodes with callbacks, a success terminal ahead, or a terminal node keep
|
|
15290
|
+
* the workflow in charge (durable callback retries, ordered webhooks).
|
|
15291
|
+
*/
|
|
15292
|
+
const canPauseNow = (ran) => {
|
|
15293
|
+
if (ran.alreadyTerminal || ran.kind === "terminal") return false;
|
|
15294
|
+
return ran.callbackJobs.length === 0 && !ran.successTerminal;
|
|
15295
|
+
};
|
|
15296
|
+
const enterAndPause = async (ports, config) => {
|
|
15297
|
+
const ran = await processStateNode(ports, config);
|
|
15298
|
+
if (!canPauseNow(ran)) return {
|
|
15299
|
+
ran,
|
|
15300
|
+
paused: false
|
|
15301
|
+
};
|
|
15302
|
+
await pauseForAdvance(ports, { orderFulfillmentId: config.orderFulfillmentId });
|
|
15303
|
+
return {
|
|
15304
|
+
ran,
|
|
15305
|
+
paused: true
|
|
15306
|
+
};
|
|
15307
|
+
};
|
|
15308
|
+
const advanceAndEnter = async (ports, config) => {
|
|
15309
|
+
const { fulfillmentStatus, requestedAt, terminalStatus, ...scope } = config;
|
|
15310
|
+
const { edges } = await resumeFromAdvance(ports, {
|
|
15311
|
+
...scope,
|
|
15312
|
+
fulfillmentStatus,
|
|
15313
|
+
requestedAt,
|
|
15314
|
+
emit: false
|
|
15315
|
+
});
|
|
15316
|
+
if (!edges) throw new Error("Fulfillment or order missing during advance");
|
|
15317
|
+
const target = pickAdvanceTarget(edges);
|
|
15318
|
+
if (!target) return { noEdge: true };
|
|
15319
|
+
const e1 = {
|
|
15320
|
+
...scope,
|
|
15321
|
+
nodeId: target.targetId,
|
|
15322
|
+
terminalStatus
|
|
15323
|
+
};
|
|
15324
|
+
const entered = await enterAndPause(ports, {
|
|
15325
|
+
...e1,
|
|
15326
|
+
fromEdgeIds: target.edgeIds
|
|
15327
|
+
});
|
|
15328
|
+
if (!entered.paused) {
|
|
15329
|
+
const orderFulfillmentId = scope.orderFulfillmentId;
|
|
15330
|
+
await ports.execution.onOrderChanged?.({ orderFulfillmentId }).catch(() => {});
|
|
15331
|
+
}
|
|
15332
|
+
return {
|
|
15333
|
+
noEdge: false,
|
|
15334
|
+
...entered
|
|
15335
|
+
};
|
|
15336
|
+
};
|
|
15337
|
+
//#endregion
|
|
15338
|
+
//#region src/fulfillment/engine/scheduledSuccessor.ts
|
|
15339
|
+
/** Mapped status of the next primary node, or null when the wait must end. */
|
|
15340
|
+
const scheduledSuccessorStatus = async (ports, config) => {
|
|
15341
|
+
const { storage, execution: execPort } = ports;
|
|
15342
|
+
const { orderFulfillmentId, orderId, nodeId } = config;
|
|
15343
|
+
const [row, order] = await Promise.all([storage.getOrderFulfillment(orderFulfillmentId), storage.getOrder(orderId)]);
|
|
15344
|
+
if (!row || !order) return null;
|
|
15345
|
+
if (isInterruptTerminalStatus(order.status)) return null;
|
|
15346
|
+
const workflow = row.workflow;
|
|
15347
|
+
const edge = matchingPrimaryOutgoing({
|
|
15348
|
+
workflow,
|
|
15349
|
+
nodeId,
|
|
15350
|
+
order,
|
|
15351
|
+
execution: execPort.getExecutionContext()
|
|
15352
|
+
})[0];
|
|
15353
|
+
if (!edge) return null;
|
|
15354
|
+
return findNodeById(workflow, edge.target)?.data.mappedStatus ?? null;
|
|
15355
|
+
};
|
|
15356
|
+
//#endregion
|
|
15357
|
+
//#region src/fulfillment/engine/webhooks.ts
|
|
15358
|
+
const DEFAULT_TIMEOUT_S$1 = 5;
|
|
15359
|
+
const ORDER_STATUS_CHANGED_EVENT = "order.status.changed";
|
|
15360
|
+
const WEBHOOK_STATUS_EVENTS = {
|
|
15361
|
+
voided: "order.voided",
|
|
15362
|
+
fulfilled: "order.fulfilled",
|
|
15363
|
+
refunded: "order.refunded",
|
|
15364
|
+
reversed: "order.reversed",
|
|
15365
|
+
failed: "order.failed"
|
|
15366
|
+
};
|
|
15367
|
+
const engineWebhookStatusKey = (status) => {
|
|
15368
|
+
return status.trim().toLowerCase().replace(/-/g, "_");
|
|
15369
|
+
};
|
|
15370
|
+
const defaultWebhookEventsForStatus = (events, metadata, status) => {
|
|
15371
|
+
const key = engineWebhookStatusKey(status);
|
|
15372
|
+
const matched = [];
|
|
15373
|
+
const statuses = Array.isArray(metadata?.statuses) ? metadata.statuses : [];
|
|
15374
|
+
if (events.includes(ORDER_STATUS_CHANGED_EVENT) && statuses.includes(key)) matched.push(ORDER_STATUS_CHANGED_EVENT);
|
|
15375
|
+
const named = WEBHOOK_STATUS_EVENTS[key];
|
|
15376
|
+
if (named && events.includes(named)) matched.push(named);
|
|
15377
|
+
return matched;
|
|
15378
|
+
};
|
|
15379
|
+
const defaultWebhookRetryDelayMs = (failureCount) => {
|
|
15380
|
+
return Math.min(1e3 * 2 ** failureCount, 3e4);
|
|
15381
|
+
};
|
|
15382
|
+
const engineHmacSha256Hex = async (secret, body) => {
|
|
15383
|
+
const raw = new TextEncoder().encode(secret);
|
|
15384
|
+
const key = await crypto.subtle.importKey("raw", raw, {
|
|
15385
|
+
name: "HMAC",
|
|
15386
|
+
hash: "SHA-256"
|
|
15387
|
+
}, false, ["sign"]);
|
|
15388
|
+
const data = new TextEncoder().encode(body);
|
|
15389
|
+
const sig = await crypto.subtle.sign("HMAC", key, data);
|
|
15390
|
+
const bytes = new Uint8Array(sig);
|
|
15391
|
+
let hex = "";
|
|
15392
|
+
for (let i = 0; i < bytes.length; i += 1) hex += (bytes[i] ?? 0).toString(16).padStart(2, "0");
|
|
15393
|
+
return hex;
|
|
15394
|
+
};
|
|
15395
|
+
/** Same webhook, order, type and status → same id, wherever it is sent. */
|
|
15396
|
+
const engineWebhookDeliveryId = (webhookId, orderId, type, status) => {
|
|
15397
|
+
return `wh_${sha256HexOfString([
|
|
15398
|
+
webhookId,
|
|
15399
|
+
orderId,
|
|
15400
|
+
type,
|
|
15401
|
+
status
|
|
15402
|
+
].join("\n")).slice(0, 32)}`;
|
|
15403
|
+
};
|
|
15404
|
+
const isPrimaryPathKind = (pathKind) => {
|
|
15405
|
+
return pathKind === "default" || pathKind === "success" || pathKind == null;
|
|
15406
|
+
};
|
|
15407
|
+
const engineWebhookTransitionStates = (workflow, previousNodeIds, currentNodeIds, order, execution) => {
|
|
15408
|
+
const previous = new Set(previousNodeIds);
|
|
15409
|
+
const nodesById = new Map(workflow.nodes.map((node) => [node.id, node]));
|
|
15410
|
+
const entered_states = [];
|
|
15411
|
+
const next_states = [];
|
|
15412
|
+
const current_states = [];
|
|
15413
|
+
const seenEntered = /* @__PURE__ */ new Set();
|
|
15414
|
+
const seenNext = /* @__PURE__ */ new Set();
|
|
15415
|
+
const seenCurrent = /* @__PURE__ */ new Set();
|
|
15416
|
+
const push = (id, list, seen) => {
|
|
15417
|
+
const raw = nodesById.get(id)?.data.mappedStatus?.trim();
|
|
15418
|
+
if (!raw) return;
|
|
15419
|
+
const key = engineWebhookStatusKey(raw);
|
|
15420
|
+
if (seen.has(key)) return;
|
|
15421
|
+
seen.add(key);
|
|
15422
|
+
list.push(key);
|
|
15423
|
+
};
|
|
15424
|
+
for (const id of currentNodeIds) {
|
|
15425
|
+
push(id, current_states, seenCurrent);
|
|
15426
|
+
if (previous.has(id)) continue;
|
|
15427
|
+
push(id, entered_states, seenEntered);
|
|
15428
|
+
}
|
|
15429
|
+
const edges = workflow.edges ?? [];
|
|
15430
|
+
for (const id of currentNodeIds) {
|
|
15431
|
+
const sitting = nodesById.get(id);
|
|
15432
|
+
if (!sitting || sitting.data.exited_at) continue;
|
|
15433
|
+
let outgoing = edges;
|
|
15434
|
+
if (order) outgoing = matchingPrimaryOutgoing({
|
|
15435
|
+
workflow,
|
|
15436
|
+
nodeId: id,
|
|
15437
|
+
order,
|
|
15438
|
+
execution,
|
|
15439
|
+
nodesById
|
|
15440
|
+
});
|
|
15441
|
+
for (const edge of outgoing) {
|
|
15442
|
+
if (edge.source !== id || edge.data?.taken_at) continue;
|
|
15443
|
+
const target = nodesById.get(edge.target);
|
|
15444
|
+
if (!target || target.data.kind === "terminal") continue;
|
|
15445
|
+
if (target.data.entered_at) continue;
|
|
15446
|
+
const inferred = pathKindForTargetNode(target.data);
|
|
15447
|
+
const pathKind = edge.data?.pathKind ?? inferred;
|
|
15448
|
+
if (!order && !isPrimaryPathKind(pathKind)) continue;
|
|
15449
|
+
const raw = target.data.mappedStatus?.trim();
|
|
15450
|
+
if (!raw) continue;
|
|
15451
|
+
const key = engineWebhookStatusKey(raw);
|
|
15452
|
+
if (seenCurrent.has(key) || seenNext.has(key)) continue;
|
|
15453
|
+
seenNext.add(key);
|
|
15454
|
+
next_states.push(key);
|
|
15455
|
+
}
|
|
15456
|
+
}
|
|
15457
|
+
return {
|
|
15458
|
+
next_states,
|
|
15459
|
+
current_states,
|
|
15460
|
+
entered_states
|
|
15461
|
+
};
|
|
15462
|
+
};
|
|
15463
|
+
const engineWebhookRunsForEnteredNodes = (workflow, currentNodeIds, previousNodeIds, runs) => {
|
|
15464
|
+
const previous = new Set(previousNodeIds);
|
|
15465
|
+
const byStatus = /* @__PURE__ */ new Map();
|
|
15466
|
+
for (const run of runs) {
|
|
15467
|
+
const list = byStatus.get(run.status) ?? [];
|
|
15468
|
+
list.push(run);
|
|
15469
|
+
byStatus.set(run.status, list);
|
|
15470
|
+
}
|
|
15471
|
+
const patches = [];
|
|
15472
|
+
for (const id of currentNodeIds) {
|
|
15473
|
+
if (previous.has(id)) continue;
|
|
15474
|
+
const node = findNodeById(workflow, id);
|
|
15475
|
+
if (!node) continue;
|
|
15476
|
+
const raw = node.data.mappedStatus?.trim();
|
|
15477
|
+
if (!raw) continue;
|
|
15478
|
+
const key = engineWebhookStatusKey(raw);
|
|
15479
|
+
const nodeRuns = byStatus.get(key) ?? [];
|
|
15480
|
+
patches.push({
|
|
15481
|
+
nodeId: id,
|
|
15482
|
+
runs: nodeRuns
|
|
15483
|
+
});
|
|
15484
|
+
}
|
|
15485
|
+
return patches;
|
|
15486
|
+
};
|
|
15487
|
+
const INTERNAL_ORDER_KEYS$1 = [
|
|
15488
|
+
"merchant_id",
|
|
15489
|
+
"env",
|
|
15490
|
+
"created_at",
|
|
15491
|
+
"updated_at",
|
|
15492
|
+
"deleted_at"
|
|
15493
|
+
];
|
|
15494
|
+
const defaultPublicOrder = (order) => {
|
|
15495
|
+
const copy = { ...order };
|
|
15496
|
+
for (const key of INTERNAL_ORDER_KEYS$1) delete copy[key];
|
|
15497
|
+
return copy;
|
|
15498
|
+
};
|
|
15499
|
+
const webhookScope = (order) => {
|
|
15500
|
+
const b0 = order.merchant_id ? { merchant_id: order.merchant_id } : {};
|
|
15501
|
+
const b1 = {
|
|
15502
|
+
order_id: order.id,
|
|
15503
|
+
fulfillment_id: order.fulfillment_id
|
|
15504
|
+
};
|
|
15505
|
+
const b2 = {
|
|
15506
|
+
store_id: order.store_id,
|
|
15507
|
+
channel_id: order.channel_id
|
|
15508
|
+
};
|
|
15509
|
+
const b3 = { brand_id: order.brand_id ?? null };
|
|
15510
|
+
const b4 = { customer_id: order.customer_id };
|
|
15511
|
+
return {
|
|
15512
|
+
...b0,
|
|
15513
|
+
...b1,
|
|
15514
|
+
...b2,
|
|
15515
|
+
...b3,
|
|
15516
|
+
...b4
|
|
15517
|
+
};
|
|
15518
|
+
};
|
|
15519
|
+
/** Target URL for a webhook given cloud / local-online / offline mode. */
|
|
15520
|
+
const resolveWebhookTargetUrl = (webhook, execution) => {
|
|
15521
|
+
const localUrl = webhook.local_url?.trim() || null;
|
|
15522
|
+
if (execution.is_local && execution.is_offline) {
|
|
15523
|
+
if (localUrl) return {
|
|
15524
|
+
url: localUrl,
|
|
15525
|
+
omitted: false
|
|
15526
|
+
};
|
|
15527
|
+
return {
|
|
15528
|
+
url: null,
|
|
15529
|
+
omitted: true
|
|
15530
|
+
};
|
|
15531
|
+
}
|
|
15532
|
+
if (execution.is_local) return {
|
|
15533
|
+
url: localUrl ?? webhook.url,
|
|
15534
|
+
omitted: false
|
|
15535
|
+
};
|
|
15536
|
+
return {
|
|
15537
|
+
url: webhook.url,
|
|
15538
|
+
omitted: false
|
|
15539
|
+
};
|
|
15540
|
+
};
|
|
15541
|
+
const postEngineWebhook = async (input) => {
|
|
15542
|
+
const { url, secret, envelope, fetchImpl, sign, now } = input;
|
|
15543
|
+
const body = JSON.stringify(envelope);
|
|
15544
|
+
const h1 = { "Content-Type": "application/json" };
|
|
15545
|
+
const h2 = { "X-Firespark-Event": envelope.type };
|
|
15546
|
+
const h3 = { "X-Firespark-Delivery": envelope.id };
|
|
15547
|
+
const headers = {
|
|
15548
|
+
...h1,
|
|
15549
|
+
...h2,
|
|
15550
|
+
...h3
|
|
15551
|
+
};
|
|
15552
|
+
if (secret != null) headers["X-Firespark-Signature"] = `sha256=${await sign(secret, body)}`;
|
|
15553
|
+
const seconds = input.timeout || DEFAULT_TIMEOUT_S$1;
|
|
15554
|
+
const req = {
|
|
15555
|
+
method: "POST",
|
|
15556
|
+
headers,
|
|
15557
|
+
body,
|
|
15558
|
+
signal: AbortSignal.timeout(seconds * 1e3)
|
|
15559
|
+
};
|
|
15560
|
+
const started_at = now().toISOString();
|
|
15561
|
+
const t0 = now().getTime();
|
|
15562
|
+
try {
|
|
15563
|
+
const res = await fetchImpl(url, req);
|
|
15564
|
+
const b1 = {
|
|
15565
|
+
started_at,
|
|
15566
|
+
finished_at: now().toISOString(),
|
|
15567
|
+
duration_ms: Math.max(0, now().getTime() - t0)
|
|
15568
|
+
};
|
|
15569
|
+
if (res.ok) return {
|
|
15570
|
+
...b1,
|
|
15571
|
+
ok: true,
|
|
15572
|
+
http_status: res.status
|
|
15573
|
+
};
|
|
15574
|
+
const status = res.status;
|
|
15575
|
+
const error = `HTTP ${status}`;
|
|
15576
|
+
return {
|
|
15577
|
+
...b1,
|
|
15578
|
+
ok: false,
|
|
15579
|
+
http_status: status,
|
|
15580
|
+
error
|
|
15581
|
+
};
|
|
15582
|
+
} catch (error) {
|
|
15583
|
+
const b1 = {
|
|
15584
|
+
started_at,
|
|
15585
|
+
finished_at: now().toISOString(),
|
|
15586
|
+
duration_ms: Math.max(0, now().getTime() - t0)
|
|
15587
|
+
};
|
|
15588
|
+
const raw = error instanceof Error ? error.message : "Webhook failed";
|
|
15589
|
+
return {
|
|
15590
|
+
...b1,
|
|
15591
|
+
ok: false,
|
|
15592
|
+
error: raw.slice(0, 4096)
|
|
15593
|
+
};
|
|
15594
|
+
}
|
|
15595
|
+
};
|
|
15596
|
+
const dispatchOrderWebhooks = async (ports, config) => {
|
|
15597
|
+
const { storage, execution: execPort } = ports;
|
|
15598
|
+
const { orderFulfillmentId, orderId } = config;
|
|
15599
|
+
const { previousNodeIds, currentNodeIds } = config;
|
|
15600
|
+
const now = execPort.now ?? (() => /* @__PURE__ */ new Date());
|
|
15601
|
+
const execCtx = execPort.getExecutionContext();
|
|
15602
|
+
const [row, order] = await Promise.all([storage.getOrderFulfillment(orderFulfillmentId), storage.getOrder(orderId)]);
|
|
15603
|
+
if (!row) throw new Error("Order fulfillment not found");
|
|
15604
|
+
if (!order) throw new Error("Order not found");
|
|
15605
|
+
const p0 = [
|
|
15606
|
+
row.workflow,
|
|
15607
|
+
previousNodeIds,
|
|
15608
|
+
currentNodeIds,
|
|
15609
|
+
order
|
|
15610
|
+
];
|
|
15611
|
+
const { next_states, current_states, entered_states } = engineWebhookTransitionStates(...p0, execCtx);
|
|
15612
|
+
if (entered_states.length === 0) return [];
|
|
15613
|
+
const rows = await execPort.loadWebhooks();
|
|
15614
|
+
const eventsFor = execPort.webhookEventsForStatus ?? defaultWebhookEventsForStatus;
|
|
15615
|
+
const deliveries = [];
|
|
15616
|
+
for (const webhook of rows) {
|
|
15617
|
+
if (webhook.type === "CALLBACK") continue;
|
|
15618
|
+
const subscribed = Array.isArray(webhook.events) ? webhook.events : [];
|
|
15619
|
+
for (const status of entered_states) {
|
|
15620
|
+
const matched = eventsFor(subscribed, webhook.metadata, status);
|
|
15621
|
+
for (const type of matched) deliveries.push({
|
|
15622
|
+
webhook,
|
|
15623
|
+
type,
|
|
15624
|
+
status
|
|
15625
|
+
});
|
|
15626
|
+
}
|
|
15627
|
+
}
|
|
15628
|
+
if (deliveries.length === 0) return [];
|
|
15629
|
+
const publicOrder = (execPort.toPublicWebhookOrder ?? defaultPublicOrder)(order);
|
|
15630
|
+
const ids = webhookScope(order);
|
|
15631
|
+
const created_at = now().toISOString();
|
|
15632
|
+
const fetchImpl = execPort.fetchImpl ?? fetch;
|
|
15633
|
+
const sign = execPort.signPayload ?? engineHmacSha256Hex;
|
|
15634
|
+
const posts = [];
|
|
15635
|
+
const omittedLabels = [];
|
|
15636
|
+
for (const delivery of deliveries) {
|
|
15637
|
+
const { webhook, type, status } = delivery;
|
|
15638
|
+
const data = {
|
|
15639
|
+
...ids,
|
|
15640
|
+
status,
|
|
15641
|
+
current_states,
|
|
15642
|
+
next_states,
|
|
15643
|
+
order: publicOrder
|
|
15644
|
+
};
|
|
15645
|
+
const id = engineWebhookDeliveryId(webhook.id, order.id, type, status);
|
|
15646
|
+
const envelope = {
|
|
15647
|
+
id,
|
|
15648
|
+
type,
|
|
15649
|
+
created_at,
|
|
15650
|
+
data
|
|
15651
|
+
};
|
|
15652
|
+
const alias = webhook.alias ?? null;
|
|
15653
|
+
const target = resolveWebhookTargetUrl(webhook, execCtx);
|
|
15654
|
+
if (target.omitted || !target.url) {
|
|
15655
|
+
const at = now().toISOString();
|
|
15656
|
+
const o1 = {
|
|
15657
|
+
id,
|
|
15658
|
+
webhook_id: webhook.id,
|
|
15659
|
+
alias,
|
|
15660
|
+
url: webhook.url
|
|
15661
|
+
};
|
|
15662
|
+
const o2 = {
|
|
15663
|
+
type,
|
|
15664
|
+
status,
|
|
15665
|
+
started_at: at,
|
|
15666
|
+
finished_at: at
|
|
15667
|
+
};
|
|
15668
|
+
const o3 = {
|
|
15669
|
+
duration_ms: 0,
|
|
15670
|
+
ok: true,
|
|
15671
|
+
omitted: true
|
|
15672
|
+
};
|
|
15673
|
+
const omittedRun = {
|
|
15674
|
+
...o1,
|
|
15675
|
+
...o2,
|
|
15676
|
+
...o3,
|
|
15677
|
+
omitted_reason: OFFLINE_NO_LOCAL_URL
|
|
15678
|
+
};
|
|
15679
|
+
omittedLabels.push(`${alias ?? webhook.id} (${type})`);
|
|
15680
|
+
posts.push(Promise.resolve(omittedRun));
|
|
15681
|
+
continue;
|
|
15682
|
+
}
|
|
15683
|
+
const r1 = {
|
|
15684
|
+
id: envelope.id,
|
|
15685
|
+
webhook_id: webhook.id,
|
|
15686
|
+
alias
|
|
15687
|
+
};
|
|
15688
|
+
const r2 = {
|
|
15689
|
+
url: target.url,
|
|
15690
|
+
type,
|
|
15691
|
+
status
|
|
15692
|
+
};
|
|
15693
|
+
const timeout = webhook.timeout || DEFAULT_TIMEOUT_S$1;
|
|
15694
|
+
const secret = webhook.secret ?? null;
|
|
15695
|
+
const job = postEngineWebhook({
|
|
15696
|
+
url: target.url,
|
|
15697
|
+
secret,
|
|
15698
|
+
timeout,
|
|
15699
|
+
envelope,
|
|
15700
|
+
fetchImpl,
|
|
15701
|
+
sign,
|
|
15702
|
+
now
|
|
15703
|
+
}).then((posted) => {
|
|
15704
|
+
const run = {
|
|
15705
|
+
...r1,
|
|
15706
|
+
...r2,
|
|
15707
|
+
...posted
|
|
15708
|
+
};
|
|
15709
|
+
if (posted.ok) return run;
|
|
15710
|
+
return {
|
|
15711
|
+
...run,
|
|
15712
|
+
payload: envelope
|
|
15713
|
+
};
|
|
15714
|
+
});
|
|
15715
|
+
posts.push(job);
|
|
15716
|
+
}
|
|
15717
|
+
const runs = await Promise.all(posts);
|
|
15718
|
+
const deliveredOnly = runs.filter((run) => !run.omitted);
|
|
15719
|
+
if (deliveredOnly.length > 0) await execPort.onRecordWebhookDeliveries?.({
|
|
15720
|
+
orderId: order.id,
|
|
15721
|
+
runs: deliveredOnly
|
|
15722
|
+
});
|
|
15723
|
+
const failed = runs.filter((run) => !run.ok);
|
|
15724
|
+
await Promise.all(failed.map((run) => {
|
|
15725
|
+
const msg = run.error ?? "Webhook delivery failed";
|
|
15726
|
+
const e1 = {
|
|
15727
|
+
order,
|
|
15728
|
+
message: msg,
|
|
15729
|
+
http_status: run.http_status ?? null
|
|
15730
|
+
};
|
|
15731
|
+
const e2 = {
|
|
15732
|
+
webhook_id: run.webhook_id,
|
|
15733
|
+
url: run.url,
|
|
15734
|
+
alias: run.alias
|
|
15735
|
+
};
|
|
15736
|
+
return execPort.onWebhookFailed?.({
|
|
15737
|
+
...e1,
|
|
15738
|
+
...e2,
|
|
15739
|
+
type: run.type
|
|
15740
|
+
});
|
|
15741
|
+
}));
|
|
15742
|
+
const g1 = [
|
|
15743
|
+
row.workflow,
|
|
15744
|
+
currentNodeIds,
|
|
15745
|
+
previousNodeIds,
|
|
15746
|
+
runs
|
|
15747
|
+
];
|
|
15748
|
+
const patches = engineWebhookRunsForEnteredNodes(...g1);
|
|
15749
|
+
if (omittedLabels.length > 0) {
|
|
15750
|
+
const msg = `Skipped offline webhooks without local_url: ${omittedLabels.join(", ")}`;
|
|
15751
|
+
const lastEntry = row.steps_logs[row.steps_logs.length - 1];
|
|
15752
|
+
if (lastEntry) lastEntry.logs.push({
|
|
15753
|
+
type: "info",
|
|
15754
|
+
message: msg,
|
|
15755
|
+
code: OFFLINE_NO_LOCAL_URL
|
|
15756
|
+
});
|
|
15757
|
+
for (const patch of patches) {
|
|
15758
|
+
const node = findNodeById(row.workflow, patch.nodeId);
|
|
15759
|
+
if (node && patch.runs.some((r) => r.omitted)) appendNodeLog(node, "info", msg);
|
|
15760
|
+
}
|
|
15761
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, {
|
|
15762
|
+
workflow: row.workflow,
|
|
15763
|
+
steps_logs: row.steps_logs
|
|
15764
|
+
});
|
|
15765
|
+
}
|
|
15766
|
+
await Promise.all(patches.map((patch) => {
|
|
15767
|
+
const p = [
|
|
15768
|
+
orderFulfillmentId,
|
|
15769
|
+
patch.nodeId,
|
|
15770
|
+
patch.runs
|
|
15771
|
+
];
|
|
15772
|
+
return storage.persistNodeWebhookRuns(...p);
|
|
15773
|
+
}));
|
|
15774
|
+
return runs;
|
|
15775
|
+
};
|
|
15776
|
+
//#endregion
|
|
15777
|
+
//#region src/fulfillment/engine/callbacks.ts
|
|
15778
|
+
const DEFAULT_TIMEOUT_S = 5;
|
|
15779
|
+
const nodeNameOf = (node) => {
|
|
15780
|
+
const label = node.data.label;
|
|
15781
|
+
if (typeof label === "string" && label.trim()) return label;
|
|
15782
|
+
if (label && typeof label === "object") {
|
|
15783
|
+
const picked = label.en ?? label.es ?? Object.values(label).find(Boolean);
|
|
15784
|
+
if (picked) return picked;
|
|
15785
|
+
}
|
|
15786
|
+
return node.data.mappedStatus || node.id;
|
|
15787
|
+
};
|
|
15788
|
+
const elapsedMs = (started_at, finished_at) => {
|
|
15789
|
+
const startMs = Date.parse(started_at);
|
|
15790
|
+
const endMs = Date.parse(finished_at);
|
|
15791
|
+
if (Number.isNaN(startMs) || Number.isNaN(endMs)) return 0;
|
|
15792
|
+
return Math.max(0, endMs - startMs);
|
|
15793
|
+
};
|
|
15794
|
+
const buildEngineCallbackError = (input) => {
|
|
15795
|
+
const { attempt, started_at, message } = input;
|
|
15796
|
+
const at = (input.now ? input.now() : /* @__PURE__ */ new Date()).toISOString();
|
|
15797
|
+
const b1 = {
|
|
15798
|
+
attempt,
|
|
15799
|
+
at,
|
|
15800
|
+
message,
|
|
15801
|
+
started_at,
|
|
15802
|
+
duration_ms: elapsedMs(started_at, at)
|
|
15803
|
+
};
|
|
15804
|
+
const b2 = {
|
|
15805
|
+
status: input.status,
|
|
15806
|
+
body: input.body
|
|
15807
|
+
};
|
|
15808
|
+
if (input.status != null) return {
|
|
15809
|
+
...b1,
|
|
15810
|
+
...b2
|
|
15811
|
+
};
|
|
15812
|
+
if (input.body !== void 0) return {
|
|
15813
|
+
...b1,
|
|
15814
|
+
body: input.body
|
|
15815
|
+
};
|
|
15816
|
+
return b1;
|
|
15817
|
+
};
|
|
15818
|
+
const buildEngineCallbackRun = (input) => {
|
|
15819
|
+
const finished_at = (input.now ? input.now() : /* @__PURE__ */ new Date()).toISOString();
|
|
15820
|
+
const origin = input.previous?.started_at ?? input.started_at;
|
|
15821
|
+
const duration_ms = elapsedMs(origin, finished_at);
|
|
15822
|
+
const b1 = {
|
|
15823
|
+
attempt: input.attempt,
|
|
15824
|
+
errors: input.errors
|
|
15825
|
+
};
|
|
15826
|
+
const b2 = {
|
|
15827
|
+
started_at: origin,
|
|
15828
|
+
finished_at,
|
|
15829
|
+
duration_ms
|
|
15830
|
+
};
|
|
15831
|
+
if (input.response !== void 0) return {
|
|
15832
|
+
...b1,
|
|
15833
|
+
...b2,
|
|
15834
|
+
response: input.response
|
|
15835
|
+
};
|
|
15836
|
+
return {
|
|
15837
|
+
...b1,
|
|
15838
|
+
...b2
|
|
15839
|
+
};
|
|
15840
|
+
};
|
|
15841
|
+
const injectingMetadataFromCallback = (data) => {
|
|
15842
|
+
if (!data || typeof data !== "object") return null;
|
|
15843
|
+
const row = data;
|
|
15844
|
+
const order_authorization_id = row.order_authorization_id;
|
|
15845
|
+
const injection_order_id = row.injection_order_id;
|
|
15846
|
+
if (typeof order_authorization_id !== "string") return null;
|
|
15847
|
+
if (typeof injection_order_id !== "string") return null;
|
|
15848
|
+
return {
|
|
15849
|
+
order_authorization_id,
|
|
15850
|
+
injection_order_id
|
|
15851
|
+
};
|
|
15852
|
+
};
|
|
15853
|
+
const readJson = async (res) => {
|
|
15854
|
+
const text = await res.text();
|
|
15855
|
+
if (!text.trim()) return void 0;
|
|
15856
|
+
try {
|
|
15857
|
+
return JSON.parse(text);
|
|
15858
|
+
} catch {
|
|
15859
|
+
return text;
|
|
15860
|
+
}
|
|
15861
|
+
};
|
|
15862
|
+
const persistCallbackRun = async (ports, input) => {
|
|
15863
|
+
const { orderFulfillmentId, nodeId } = input;
|
|
15864
|
+
const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
|
|
15865
|
+
if (!row) throw new Error("Order fulfillment not found");
|
|
15866
|
+
const node = findNodeById(row.workflow, nodeId);
|
|
15867
|
+
if (!node) throw new Error(`Node ${nodeId} not found`);
|
|
15868
|
+
node.data.callback_run = input.run;
|
|
15869
|
+
appendNodeLog(node, input.logType, input.logMessage);
|
|
15870
|
+
await ports.storage.updateOrderFulfillment(orderFulfillmentId, { workflow: row.workflow });
|
|
15871
|
+
};
|
|
15872
|
+
const resolveCallbackUrl = (hook, execution) => {
|
|
15873
|
+
const localUrl = hook.local_url?.trim() || null;
|
|
15874
|
+
if (execution.is_local && execution.is_offline) {
|
|
15875
|
+
if (localUrl) return {
|
|
15876
|
+
url: localUrl,
|
|
15877
|
+
missingLocalOffline: false
|
|
15878
|
+
};
|
|
15879
|
+
return {
|
|
15880
|
+
url: null,
|
|
15881
|
+
missingLocalOffline: true
|
|
15882
|
+
};
|
|
15883
|
+
}
|
|
15884
|
+
if (execution.is_local) return {
|
|
15885
|
+
url: localUrl ?? hook.url,
|
|
15886
|
+
missingLocalOffline: false
|
|
15887
|
+
};
|
|
15888
|
+
return {
|
|
15889
|
+
url: hook.url,
|
|
15890
|
+
missingLocalOffline: false
|
|
15891
|
+
};
|
|
15892
|
+
};
|
|
15893
|
+
const INTERNAL_ORDER_KEYS = [
|
|
15894
|
+
"merchant_id",
|
|
15895
|
+
"env",
|
|
15896
|
+
"created_at",
|
|
15897
|
+
"updated_at",
|
|
15898
|
+
"deleted_at"
|
|
15899
|
+
];
|
|
15900
|
+
const invokeCallbackAttempt = async (ports, config) => {
|
|
15901
|
+
const { storage, execution: execPort } = ports;
|
|
15902
|
+
const { orderFulfillmentId, orderId, nodeId } = config;
|
|
15903
|
+
const { callbackId, failureCount } = config;
|
|
15904
|
+
const now = execPort.now ?? (() => /* @__PURE__ */ new Date());
|
|
15905
|
+
const execCtx = execPort.getExecutionContext();
|
|
15906
|
+
const [row, order] = await Promise.all([storage.getOrderFulfillment(orderFulfillmentId), storage.getOrder(orderId)]);
|
|
15907
|
+
if (!row) throw new Error("Order fulfillment not found");
|
|
15908
|
+
if (!order) throw new Error("Order not found");
|
|
15909
|
+
const node = findNodeById(row.workflow, nodeId);
|
|
15910
|
+
if (!node) throw new Error(`Node ${nodeId} not found`);
|
|
15911
|
+
const hook = (await execPort.loadWebhooks()).find((item) => {
|
|
15912
|
+
return item.id === callbackId && item.type === "CALLBACK";
|
|
15913
|
+
});
|
|
15914
|
+
const nodeName = nodeNameOf(node);
|
|
15915
|
+
if (!hook) {
|
|
15916
|
+
if (execCtx.is_local && execCtx.is_offline) {
|
|
15917
|
+
const details = {
|
|
15918
|
+
mode: "offline",
|
|
15919
|
+
node_id: node.id,
|
|
15920
|
+
node_name: nodeName,
|
|
15921
|
+
step: "PROCESS_STATE_NODE",
|
|
15922
|
+
webhook_id: callbackId,
|
|
15923
|
+
webhook_name: callbackId
|
|
15924
|
+
};
|
|
15925
|
+
const message = `${`${CALLBACK_MISSING_LOCAL_URL}:`} ${`node ${node.id} (${nodeName}), step PROCESS_STATE_NODE`}, callback ${callbackId}`;
|
|
15926
|
+
const prev = node.data.callback_run;
|
|
15927
|
+
const errors = [...prev?.errors ?? []];
|
|
15928
|
+
const started_at = now().toISOString();
|
|
15929
|
+
const attempt = failureCount + 1;
|
|
15930
|
+
errors.push(buildEngineCallbackError({
|
|
15931
|
+
attempt,
|
|
15932
|
+
started_at,
|
|
15933
|
+
message,
|
|
15934
|
+
now
|
|
15935
|
+
}));
|
|
15936
|
+
const p1 = {
|
|
15937
|
+
orderFulfillmentId,
|
|
15938
|
+
nodeId,
|
|
15939
|
+
run: buildEngineCallbackRun({
|
|
15940
|
+
attempt,
|
|
15941
|
+
errors,
|
|
15942
|
+
started_at,
|
|
15943
|
+
previous: prev,
|
|
15944
|
+
now
|
|
15945
|
+
})
|
|
15946
|
+
};
|
|
15947
|
+
await persistCallbackRun(ports, {
|
|
15948
|
+
...p1,
|
|
15949
|
+
logType: "error",
|
|
15950
|
+
logMessage: message
|
|
15951
|
+
});
|
|
15952
|
+
return {
|
|
15953
|
+
ok: false,
|
|
15954
|
+
message,
|
|
15955
|
+
retries: 0,
|
|
15956
|
+
code: CALLBACK_MISSING_LOCAL_URL,
|
|
15957
|
+
details,
|
|
15958
|
+
fatal: true
|
|
15959
|
+
};
|
|
15960
|
+
}
|
|
15961
|
+
const message = `Callback ${callbackId} not found`;
|
|
15962
|
+
const prev = node.data.callback_run;
|
|
15963
|
+
const errors = [...prev?.errors ?? []];
|
|
15964
|
+
const started_at = now().toISOString();
|
|
15965
|
+
const attempt = failureCount + 1;
|
|
15966
|
+
errors.push(buildEngineCallbackError({
|
|
15967
|
+
attempt,
|
|
15968
|
+
started_at,
|
|
15969
|
+
message,
|
|
15970
|
+
now
|
|
15971
|
+
}));
|
|
15972
|
+
const p1 = {
|
|
15973
|
+
orderFulfillmentId,
|
|
15974
|
+
nodeId,
|
|
15975
|
+
run: buildEngineCallbackRun({
|
|
15976
|
+
attempt,
|
|
15977
|
+
errors,
|
|
15978
|
+
started_at,
|
|
15979
|
+
previous: prev,
|
|
15980
|
+
now
|
|
15981
|
+
})
|
|
15982
|
+
};
|
|
15983
|
+
await persistCallbackRun(ports, {
|
|
15984
|
+
...p1,
|
|
15985
|
+
logType: "error",
|
|
15986
|
+
logMessage: message
|
|
15987
|
+
});
|
|
15988
|
+
const f1 = {
|
|
15989
|
+
order,
|
|
15990
|
+
message,
|
|
15991
|
+
webhook_id: callbackId,
|
|
15992
|
+
nodeId
|
|
15993
|
+
};
|
|
15994
|
+
await execPort.onWebhookFailed?.({
|
|
15995
|
+
...f1,
|
|
15996
|
+
type: "CALLBACK"
|
|
15997
|
+
});
|
|
15998
|
+
return {
|
|
15999
|
+
ok: false,
|
|
16000
|
+
message,
|
|
16001
|
+
retries: 0
|
|
16002
|
+
};
|
|
16003
|
+
}
|
|
16004
|
+
const target = resolveCallbackUrl(hook, execCtx);
|
|
16005
|
+
if (target.missingLocalOffline || !target.url) {
|
|
16006
|
+
const webhookName = hook.alias || hook.id;
|
|
16007
|
+
const details = {
|
|
16008
|
+
mode: "offline",
|
|
16009
|
+
node_id: node.id,
|
|
16010
|
+
node_name: nodeName,
|
|
16011
|
+
step: "PROCESS_STATE_NODE",
|
|
16012
|
+
webhook_id: hook.id,
|
|
16013
|
+
webhook_name: webhookName
|
|
16014
|
+
};
|
|
16015
|
+
const message = `${`${CALLBACK_MISSING_LOCAL_URL}:`} ${`node ${node.id} (${nodeName}), step PROCESS_STATE_NODE`}, callback ${hook.id} (${webhookName})`;
|
|
16016
|
+
const prev = node.data.callback_run;
|
|
16017
|
+
const errors = [...prev?.errors ?? []];
|
|
16018
|
+
const started_at = now().toISOString();
|
|
16019
|
+
const attempt = failureCount + 1;
|
|
16020
|
+
errors.push(buildEngineCallbackError({
|
|
16021
|
+
attempt,
|
|
16022
|
+
started_at,
|
|
16023
|
+
message,
|
|
16024
|
+
now
|
|
16025
|
+
}));
|
|
16026
|
+
const p1 = {
|
|
16027
|
+
orderFulfillmentId,
|
|
16028
|
+
nodeId,
|
|
16029
|
+
run: buildEngineCallbackRun({
|
|
16030
|
+
attempt,
|
|
16031
|
+
errors,
|
|
16032
|
+
started_at,
|
|
16033
|
+
previous: prev,
|
|
16034
|
+
now
|
|
16035
|
+
})
|
|
16036
|
+
};
|
|
16037
|
+
await persistCallbackRun(ports, {
|
|
16038
|
+
...p1,
|
|
16039
|
+
logType: "error",
|
|
16040
|
+
logMessage: message
|
|
16041
|
+
});
|
|
16042
|
+
return {
|
|
16043
|
+
ok: false,
|
|
16044
|
+
message,
|
|
16045
|
+
retries: 0,
|
|
16046
|
+
code: CALLBACK_MISSING_LOCAL_URL,
|
|
16047
|
+
details,
|
|
16048
|
+
fatal: true
|
|
16049
|
+
};
|
|
16050
|
+
}
|
|
16051
|
+
const retries = hook.retries ?? 0;
|
|
16052
|
+
const timeout = hook.timeout || DEFAULT_TIMEOUT_S;
|
|
16053
|
+
const publicOrder = (execPort.toPublicWebhookOrder ?? ((o) => {
|
|
16054
|
+
const copy = { ...o };
|
|
16055
|
+
for (const k of INTERNAL_ORDER_KEYS) delete copy[k];
|
|
16056
|
+
return copy;
|
|
16057
|
+
}))(order);
|
|
16058
|
+
const b0 = order.merchant_id ? { merchant_id: order.merchant_id } : {};
|
|
16059
|
+
const b1 = {
|
|
16060
|
+
order_id: order.id,
|
|
16061
|
+
fulfillment_id: order.fulfillment_id
|
|
16062
|
+
};
|
|
16063
|
+
const b2 = {
|
|
16064
|
+
store_id: order.store_id,
|
|
16065
|
+
channel_id: order.channel_id
|
|
16066
|
+
};
|
|
16067
|
+
const b3 = {
|
|
16068
|
+
brand_id: order.brand_id ?? null,
|
|
16069
|
+
customer_id: order.customer_id
|
|
16070
|
+
};
|
|
16071
|
+
const ids = {
|
|
16072
|
+
...b0,
|
|
16073
|
+
...b1,
|
|
16074
|
+
...b2,
|
|
16075
|
+
...b3
|
|
16076
|
+
};
|
|
16077
|
+
const { current_states, next_states } = engineWebhookTransitionStates(...[
|
|
16078
|
+
row.workflow,
|
|
16079
|
+
[],
|
|
16080
|
+
row.current_node_ids,
|
|
16081
|
+
order
|
|
16082
|
+
], execCtx);
|
|
16083
|
+
const rawStatus = node.data.mappedStatus?.trim() ?? "";
|
|
16084
|
+
const status = rawStatus ? engineWebhookStatusKey(rawStatus) : "";
|
|
16085
|
+
const created_at = now().toISOString();
|
|
16086
|
+
const envelope = {
|
|
16087
|
+
id: `cb_${randomUUID()}`,
|
|
16088
|
+
type: "order.callback",
|
|
16089
|
+
created_at,
|
|
16090
|
+
data: {
|
|
16091
|
+
...ids,
|
|
16092
|
+
status,
|
|
16093
|
+
current_states,
|
|
16094
|
+
next_states,
|
|
16095
|
+
order: publicOrder
|
|
16096
|
+
}
|
|
16097
|
+
};
|
|
16098
|
+
const body = JSON.stringify(envelope);
|
|
16099
|
+
const h1 = { "Content-Type": "application/json" };
|
|
16100
|
+
const h2 = { "X-Firespark-Event": envelope.type };
|
|
16101
|
+
const h3 = { "X-Firespark-Delivery": envelope.id };
|
|
16102
|
+
const headers = {
|
|
16103
|
+
...h1,
|
|
16104
|
+
...h2,
|
|
16105
|
+
...h3
|
|
16106
|
+
};
|
|
16107
|
+
const sign = execPort.signPayload ?? engineHmacSha256Hex;
|
|
16108
|
+
if (hook.secret != null) headers["X-Firespark-Signature"] = `sha256=${await sign(hook.secret, body)}`;
|
|
16109
|
+
const fetchImpl = execPort.fetchImpl ?? fetch;
|
|
16110
|
+
const req = {
|
|
16111
|
+
method: "POST",
|
|
16112
|
+
headers,
|
|
16113
|
+
body,
|
|
16114
|
+
signal: AbortSignal.timeout(timeout * 1e3)
|
|
16115
|
+
};
|
|
16116
|
+
const prev = node.data.callback_run;
|
|
16117
|
+
const errors = [...prev?.errors ?? []];
|
|
16118
|
+
const started_at = now().toISOString();
|
|
16119
|
+
const attempt = failureCount + 1;
|
|
16120
|
+
try {
|
|
16121
|
+
const res = await fetchImpl(target.url, req);
|
|
16122
|
+
const parsedBody = await readJson(res);
|
|
16123
|
+
if (!res.ok) {
|
|
16124
|
+
const message = `Callback HTTP ${res.status}`;
|
|
16125
|
+
const e1 = {
|
|
16126
|
+
attempt,
|
|
16127
|
+
started_at,
|
|
16128
|
+
message,
|
|
16129
|
+
status: res.status
|
|
16130
|
+
};
|
|
16131
|
+
errors.push(buildEngineCallbackError({
|
|
16132
|
+
...e1,
|
|
16133
|
+
body: parsedBody,
|
|
16134
|
+
now
|
|
16135
|
+
}));
|
|
16136
|
+
const p1 = {
|
|
16137
|
+
orderFulfillmentId,
|
|
16138
|
+
nodeId,
|
|
16139
|
+
run: buildEngineCallbackRun({
|
|
16140
|
+
attempt,
|
|
16141
|
+
errors,
|
|
16142
|
+
started_at,
|
|
16143
|
+
previous: prev,
|
|
16144
|
+
now
|
|
16145
|
+
})
|
|
16146
|
+
};
|
|
16147
|
+
await persistCallbackRun(ports, {
|
|
16148
|
+
...p1,
|
|
16149
|
+
logType: "error",
|
|
16150
|
+
logMessage: message
|
|
16151
|
+
});
|
|
16152
|
+
const c1 = {
|
|
16153
|
+
order,
|
|
16154
|
+
message,
|
|
16155
|
+
webhook_id: hook.id,
|
|
16156
|
+
nodeId
|
|
16157
|
+
};
|
|
16158
|
+
const c2 = {
|
|
16159
|
+
http_status: res.status,
|
|
16160
|
+
url: target.url,
|
|
16161
|
+
type: "CALLBACK"
|
|
16162
|
+
};
|
|
16163
|
+
await execPort.onWebhookFailed?.({
|
|
16164
|
+
...c1,
|
|
16165
|
+
...c2
|
|
16166
|
+
});
|
|
16167
|
+
return {
|
|
16168
|
+
ok: false,
|
|
16169
|
+
message,
|
|
16170
|
+
status: res.status,
|
|
16171
|
+
retries
|
|
16172
|
+
};
|
|
16173
|
+
}
|
|
16174
|
+
const parser = execPort.parseCallbackResponse;
|
|
16175
|
+
const parsed = parser ? parser(rawStatus, parsedBody) : {
|
|
16176
|
+
ok: true,
|
|
16177
|
+
data: parsedBody
|
|
16178
|
+
};
|
|
16179
|
+
if (!parsed.ok) {
|
|
16180
|
+
const message = parsed.message;
|
|
16181
|
+
const e1 = {
|
|
16182
|
+
attempt,
|
|
16183
|
+
started_at,
|
|
16184
|
+
message,
|
|
16185
|
+
status: res.status
|
|
16186
|
+
};
|
|
16187
|
+
errors.push(buildEngineCallbackError({
|
|
16188
|
+
...e1,
|
|
16189
|
+
body: parsedBody,
|
|
16190
|
+
now
|
|
16191
|
+
}));
|
|
16192
|
+
const p1 = {
|
|
16193
|
+
orderFulfillmentId,
|
|
16194
|
+
nodeId,
|
|
16195
|
+
run: buildEngineCallbackRun({
|
|
16196
|
+
attempt,
|
|
16197
|
+
errors,
|
|
16198
|
+
started_at,
|
|
16199
|
+
previous: prev,
|
|
16200
|
+
now
|
|
16201
|
+
})
|
|
16202
|
+
};
|
|
16203
|
+
await persistCallbackRun(ports, {
|
|
16204
|
+
...p1,
|
|
16205
|
+
logType: "error",
|
|
16206
|
+
logMessage: message
|
|
16207
|
+
});
|
|
16208
|
+
const c1 = {
|
|
16209
|
+
order,
|
|
16210
|
+
message,
|
|
16211
|
+
webhook_id: hook.id,
|
|
16212
|
+
nodeId
|
|
16213
|
+
};
|
|
16214
|
+
const c2 = {
|
|
16215
|
+
http_status: res.status,
|
|
16216
|
+
url: target.url,
|
|
16217
|
+
type: "CALLBACK"
|
|
16218
|
+
};
|
|
16219
|
+
await execPort.onWebhookFailed?.({
|
|
16220
|
+
...c1,
|
|
16221
|
+
...c2
|
|
16222
|
+
});
|
|
16223
|
+
return {
|
|
16224
|
+
ok: false,
|
|
16225
|
+
message,
|
|
16226
|
+
status: res.status,
|
|
16227
|
+
retries
|
|
16228
|
+
};
|
|
16229
|
+
}
|
|
16230
|
+
const response = parsedBody ?? parsed.data;
|
|
16231
|
+
const run = buildEngineCallbackRun({
|
|
16232
|
+
attempt,
|
|
16233
|
+
errors,
|
|
16234
|
+
started_at,
|
|
16235
|
+
previous: prev,
|
|
16236
|
+
response,
|
|
16237
|
+
now
|
|
16238
|
+
});
|
|
16239
|
+
const okMsg = `Callback ${callbackId} succeeded`;
|
|
16240
|
+
await persistCallbackRun(ports, {
|
|
16241
|
+
orderFulfillmentId,
|
|
16242
|
+
nodeId,
|
|
16243
|
+
run,
|
|
16244
|
+
logType: "success",
|
|
16245
|
+
logMessage: okMsg
|
|
16246
|
+
});
|
|
16247
|
+
const injecting = injectingMetadataFromCallback(parsed.data);
|
|
16248
|
+
if (injecting) await storage.mergeOrderMetadata(orderId, injecting);
|
|
16249
|
+
return {
|
|
16250
|
+
ok: true,
|
|
16251
|
+
status: res.status,
|
|
16252
|
+
retries
|
|
16253
|
+
};
|
|
16254
|
+
} catch (error) {
|
|
16255
|
+
const message = (error instanceof Error ? error.message : "Callback failed").slice(0, 4096);
|
|
16256
|
+
errors.push(buildEngineCallbackError({
|
|
16257
|
+
attempt,
|
|
16258
|
+
started_at,
|
|
16259
|
+
message,
|
|
16260
|
+
now
|
|
16261
|
+
}));
|
|
16262
|
+
const p1 = {
|
|
16263
|
+
orderFulfillmentId,
|
|
16264
|
+
nodeId,
|
|
16265
|
+
run: buildEngineCallbackRun({
|
|
16266
|
+
attempt,
|
|
16267
|
+
errors,
|
|
16268
|
+
started_at,
|
|
16269
|
+
previous: prev,
|
|
16270
|
+
now
|
|
16271
|
+
})
|
|
16272
|
+
};
|
|
16273
|
+
await persistCallbackRun(ports, {
|
|
16274
|
+
...p1,
|
|
16275
|
+
logType: "error",
|
|
16276
|
+
logMessage: message
|
|
16277
|
+
});
|
|
16278
|
+
const c1 = {
|
|
16279
|
+
order,
|
|
16280
|
+
message,
|
|
16281
|
+
webhook_id: hook.id,
|
|
16282
|
+
nodeId
|
|
16283
|
+
};
|
|
16284
|
+
await execPort.onWebhookFailed?.({
|
|
16285
|
+
...c1,
|
|
16286
|
+
url: target.url,
|
|
16287
|
+
type: "CALLBACK"
|
|
16288
|
+
});
|
|
16289
|
+
return {
|
|
16290
|
+
ok: false,
|
|
16291
|
+
message,
|
|
16292
|
+
retries
|
|
16293
|
+
};
|
|
16294
|
+
}
|
|
16295
|
+
};
|
|
16296
|
+
const runNodeCallbacks = async (ports, scope, next) => {
|
|
16297
|
+
const retryDelay = ports.execution.webhookRetryDelayMs ?? defaultWebhookRetryDelayMs;
|
|
16298
|
+
const sleepFn = ports.execution.sleep;
|
|
16299
|
+
for (const job of next.callbackJobs) for (const callbackId of job.callback_ids) {
|
|
16300
|
+
let failureCount = 0;
|
|
16301
|
+
let retries = 0;
|
|
16302
|
+
while (true) {
|
|
16303
|
+
const a1 = {
|
|
16304
|
+
...scope,
|
|
16305
|
+
nodeId: job.nodeId,
|
|
16306
|
+
callbackId,
|
|
16307
|
+
failureCount
|
|
16308
|
+
};
|
|
16309
|
+
const attempt = await invokeCallbackAttempt(ports, a1);
|
|
16310
|
+
retries = attempt.retries;
|
|
16311
|
+
if (attempt.ok) break;
|
|
16312
|
+
if (attempt.fatal) return {
|
|
16313
|
+
ok: false,
|
|
16314
|
+
fatal: true,
|
|
16315
|
+
code: attempt.code,
|
|
16316
|
+
message: attempt.message,
|
|
16317
|
+
details: attempt.details
|
|
16318
|
+
};
|
|
16319
|
+
if (failureCount < retries) {
|
|
16320
|
+
const delay = retryDelay(failureCount);
|
|
16321
|
+
if (sleepFn) await sleepFn(delay);
|
|
16322
|
+
failureCount += 1;
|
|
16323
|
+
continue;
|
|
16324
|
+
}
|
|
16325
|
+
return {
|
|
16326
|
+
ok: false,
|
|
16327
|
+
message: attempt.message
|
|
16328
|
+
};
|
|
16329
|
+
}
|
|
16330
|
+
}
|
|
16331
|
+
return { ok: true };
|
|
16332
|
+
};
|
|
16333
|
+
const NEEDS_REVIEW_STEP = "WARN_NO_EDGE";
|
|
16334
|
+
const resolveCallbackFailTerminal = async (ports, config) => {
|
|
16335
|
+
const { storage, execution: execPort } = ports;
|
|
16336
|
+
const { orderFulfillmentId } = config;
|
|
16337
|
+
const now = execPort.now;
|
|
16338
|
+
const row = await storage.getOrderFulfillment(orderFulfillmentId);
|
|
16339
|
+
if (!row) throw new Error("Order fulfillment not found");
|
|
16340
|
+
const order = await storage.getOrder(row.order_id);
|
|
16341
|
+
if (!order) throw new Error("Order not found");
|
|
16342
|
+
const execution = execPort.getExecutionContext();
|
|
16343
|
+
const match = resolveFailureTerminalEdge({
|
|
16344
|
+
workflow: row.workflow,
|
|
16345
|
+
currentNodeIds: row.current_node_ids,
|
|
16346
|
+
order,
|
|
16347
|
+
execution
|
|
16348
|
+
});
|
|
16349
|
+
if (match) {
|
|
16350
|
+
const mapped = match.target.data.mappedStatus;
|
|
16351
|
+
const mappedStatus = normalizeFulfillmentStatus(mapped);
|
|
16352
|
+
return {
|
|
16353
|
+
nodeId: match.target.id,
|
|
16354
|
+
edgeId: match.edge.id,
|
|
16355
|
+
mappedStatus
|
|
16356
|
+
};
|
|
16357
|
+
}
|
|
16358
|
+
const message = "Callbacks failed and no cancel/refund edge applies";
|
|
16359
|
+
const steps_logs = row.steps_logs;
|
|
16360
|
+
beginEngineStepLog(steps_logs, NEEDS_REVIEW_STEP, void 0, now);
|
|
16361
|
+
appendEngineStepLog(steps_logs, NEEDS_REVIEW_STEP, {
|
|
16362
|
+
type: "warning",
|
|
16363
|
+
message
|
|
16364
|
+
});
|
|
16365
|
+
completeEngineStepLog(steps_logs, NEEDS_REVIEW_STEP, "Needs review", now);
|
|
16366
|
+
const warning_count = (row.warning_count ?? 0) + 1;
|
|
16367
|
+
await storage.updateOrderFulfillment(row.id, {
|
|
16368
|
+
steps_logs,
|
|
16369
|
+
warning_count
|
|
16370
|
+
});
|
|
16371
|
+
const key = `${row.id}:callback-fail`;
|
|
16372
|
+
await storage.flagOrderForReview?.({
|
|
16373
|
+
order,
|
|
16374
|
+
key,
|
|
16375
|
+
message
|
|
16376
|
+
});
|
|
16377
|
+
return null;
|
|
16378
|
+
};
|
|
16379
|
+
//#endregion
|
|
16380
|
+
//#region src/fulfillment/engine/finalize.ts
|
|
16381
|
+
const HARD_FAILED_CODES = /* @__PURE__ */ new Set([CALLBACK_MISSING_LOCAL_URL, WORKFLOW_TIMEOUT]);
|
|
16382
|
+
const engineOrderStatusForFailedRun = (order, isPaymentCaptured = defaultIsPaymentCaptured) => {
|
|
16383
|
+
if (!order) return null;
|
|
16384
|
+
if (isInterruptTerminalStatus(order.status) || order.status === "COMPLETED") return null;
|
|
16385
|
+
return isPaymentCaptured(order) ? "REVERSED" : "VOIDED";
|
|
16386
|
+
};
|
|
16387
|
+
const syncOrderFromSittingTerminal = async (ports, orderFulfillmentId) => {
|
|
16388
|
+
const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
|
|
16389
|
+
if (!row) return;
|
|
16390
|
+
const sitting = sittingWorkflowNode(row.workflow, row.current_node_ids);
|
|
16391
|
+
if (!sitting || sitting.data.kind !== "terminal") return;
|
|
16392
|
+
const order = await ports.storage.getOrder(row.order_id);
|
|
16393
|
+
const isCaptured = ports.execution.isPaymentCaptured ?? defaultIsPaymentCaptured;
|
|
16394
|
+
const fields = orderFieldsFromNode(sitting, void 0, order ? isCaptured(order) : false);
|
|
16395
|
+
const patch = {
|
|
16396
|
+
fulfillment_status: sitting.data.mappedStatus,
|
|
16397
|
+
...fields
|
|
16398
|
+
};
|
|
16399
|
+
await ports.storage.updateOrderStatusAndSettle(row.order_id, patch);
|
|
16400
|
+
};
|
|
16401
|
+
const emitFinalizeChanged = async (ports, orderFulfillmentId, error) => {
|
|
16402
|
+
const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
|
|
16403
|
+
const orderId = row?.order_id;
|
|
16404
|
+
const order = orderId ? await ports.storage.getOrder(orderId) : null;
|
|
16405
|
+
if (row && order) {
|
|
16406
|
+
await ports.execution.onOrderChanged?.({
|
|
16407
|
+
orderFulfillmentId,
|
|
16408
|
+
row,
|
|
16409
|
+
order,
|
|
16410
|
+
error
|
|
16411
|
+
});
|
|
16412
|
+
return;
|
|
16413
|
+
}
|
|
16414
|
+
await ports.execution.onOrderChanged?.({
|
|
16415
|
+
orderFulfillmentId,
|
|
16416
|
+
error
|
|
16417
|
+
});
|
|
16418
|
+
};
|
|
16419
|
+
const finalizePlaceOrder = async (ports, config) => {
|
|
16420
|
+
const { storage, execution: execPort } = ports;
|
|
16421
|
+
const { orderFulfillmentId, status, failureMessage } = config;
|
|
16422
|
+
const { errorCode, errorDetails } = config;
|
|
16423
|
+
const now = execPort.now;
|
|
16424
|
+
const row = await storage.getOrderFulfillment(orderFulfillmentId);
|
|
16425
|
+
const steps_logs = row?.steps_logs ?? [];
|
|
16426
|
+
const isHardFailed = Boolean(errorCode && HARD_FAILED_CODES.has(errorCode));
|
|
16427
|
+
if (status === "FAILED" && failureMessage) failActiveEngineStepLog(steps_logs, failureMessage, {
|
|
16428
|
+
code: errorCode,
|
|
16429
|
+
details: errorDetails,
|
|
16430
|
+
now
|
|
16431
|
+
});
|
|
16432
|
+
beginEngineStepLog(steps_logs, "FINALIZE", void 0, now);
|
|
16433
|
+
if (status === "FAILED" && isHardFailed && failureMessage) appendEngineStepLog(steps_logs, "FINALIZE", {
|
|
16434
|
+
type: "error",
|
|
16435
|
+
message: failureMessage,
|
|
16436
|
+
code: errorCode,
|
|
16437
|
+
details: errorDetails
|
|
16438
|
+
});
|
|
16439
|
+
completeEngineStepLog(steps_logs, "FINALIZE", status === "SUCCESS" ? "Fulfillment completed" : "Fulfillment failed", now);
|
|
16440
|
+
if (status === "FAILED") {
|
|
16441
|
+
const peekOrderId = (row ?? await storage.getOrderFulfillment(orderFulfillmentId))?.order_id;
|
|
16442
|
+
const peekOrder = peekOrderId ? await storage.getOrder(peekOrderId) : null;
|
|
16443
|
+
if (!isHardFailed && isInterruptTerminalStatus(peekOrder?.status)) {
|
|
16444
|
+
const ok = {
|
|
16445
|
+
steps_logs,
|
|
16446
|
+
step: "FINALIZE",
|
|
16447
|
+
status: "SUCCESS"
|
|
16448
|
+
};
|
|
16449
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, ok);
|
|
16450
|
+
await syncOrderFromSittingTerminal(ports, orderFulfillmentId);
|
|
16451
|
+
await emitFinalizeChanged(ports, orderFulfillmentId);
|
|
16452
|
+
return { failed: false };
|
|
16453
|
+
}
|
|
16454
|
+
if (isHardFailed && peekOrder) {
|
|
16455
|
+
const resolvedAt = (now ? now() : /* @__PURE__ */ new Date()).toISOString();
|
|
16456
|
+
await storage.updateOrderStatusAndSettle(peekOrder.id, {
|
|
16457
|
+
fulfillment_status: "FAILED",
|
|
16458
|
+
status: "FAILED",
|
|
16459
|
+
resolved_at: resolvedAt
|
|
16460
|
+
});
|
|
16461
|
+
const key = `${orderFulfillmentId}:${errorCode}`;
|
|
16462
|
+
const reviewMsg = failureMessage ?? `${errorCode}: Fulfillment failed`;
|
|
16463
|
+
await storage.flagOrderForReview?.({
|
|
16464
|
+
order: peekOrder,
|
|
16465
|
+
key,
|
|
16466
|
+
message: reviewMsg
|
|
16467
|
+
});
|
|
16468
|
+
} else if (peekOrder) {
|
|
16469
|
+
const isCaptured = execPort.isPaymentCaptured ?? defaultIsPaymentCaptured;
|
|
16470
|
+
const closed = engineOrderStatusForFailedRun(peekOrder, isCaptured);
|
|
16471
|
+
if (closed) await storage.updateOrderStatusAndSettle(peekOrder.id, {
|
|
16472
|
+
fulfillment_status: closed,
|
|
16473
|
+
status: closed
|
|
16474
|
+
});
|
|
16475
|
+
}
|
|
16476
|
+
}
|
|
16477
|
+
const errorFields = status === "FAILED" ? {
|
|
16478
|
+
error_code: errorCode ?? null,
|
|
16479
|
+
error_message: failureMessage ?? "Fulfillment failed"
|
|
16480
|
+
} : {};
|
|
16481
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, {
|
|
16482
|
+
steps_logs,
|
|
16483
|
+
step: "FINALIZE",
|
|
16484
|
+
status,
|
|
16485
|
+
...errorFields
|
|
16486
|
+
});
|
|
16487
|
+
if (status !== "FAILED") {
|
|
16488
|
+
await syncOrderFromSittingTerminal(ports, orderFulfillmentId);
|
|
16489
|
+
await emitFinalizeChanged(ports, orderFulfillmentId);
|
|
16490
|
+
return { failed: false };
|
|
16491
|
+
}
|
|
16492
|
+
const raw = failureMessage ?? "Fulfillment failed";
|
|
16493
|
+
await emitFinalizeChanged(ports, orderFulfillmentId, errorCode ? {
|
|
16494
|
+
message: raw,
|
|
16495
|
+
code: errorCode
|
|
16496
|
+
} : { message: raw });
|
|
16497
|
+
if (row?.order_id) await execPort.onInjectionFailed?.({
|
|
16498
|
+
orderId: row.order_id,
|
|
16499
|
+
message: raw,
|
|
16500
|
+
code: errorCode
|
|
16501
|
+
});
|
|
16502
|
+
return { failed: true };
|
|
16503
|
+
};
|
|
16504
|
+
const warnNoEdge = async (ports, config) => {
|
|
16505
|
+
const { storage, execution: execPort } = ports;
|
|
16506
|
+
const { orderFulfillmentId, fulfillmentStatus } = config;
|
|
16507
|
+
const now = execPort.now;
|
|
16508
|
+
const row = await storage.getOrderFulfillment(orderFulfillmentId);
|
|
16509
|
+
if (!row || row.current_node_ids.length === 0) return;
|
|
16510
|
+
const orderPromise = storage.getOrder(row.order_id);
|
|
16511
|
+
const message = `No outgoing edge matches ${fulfillmentStatus}`;
|
|
16512
|
+
const nodesById = new Map(row.workflow.nodes.map((node) => [node.id, node]));
|
|
16513
|
+
for (const id of row.current_node_ids) {
|
|
16514
|
+
const node = nodesById.get(id) ?? findNodeById(row.workflow, id);
|
|
16515
|
+
if (node) appendNodeLog(node, "warning", message);
|
|
16516
|
+
}
|
|
16517
|
+
const steps_logs = row.steps_logs;
|
|
16518
|
+
beginEngineStepLog(steps_logs, "WARN_NO_EDGE", void 0, now);
|
|
16519
|
+
appendEngineStepLog(steps_logs, "WARN_NO_EDGE", {
|
|
16520
|
+
type: "warning",
|
|
16521
|
+
message
|
|
16522
|
+
});
|
|
16523
|
+
completeEngineStepLog(steps_logs, "WARN_NO_EDGE", "Kept waiting", now);
|
|
16524
|
+
const warning_count = (row.warning_count ?? 0) + 1;
|
|
16525
|
+
const patch = {
|
|
16526
|
+
workflow: row.workflow,
|
|
16527
|
+
steps_logs,
|
|
16528
|
+
warning_count,
|
|
16529
|
+
status: "WAITING"
|
|
16530
|
+
};
|
|
16531
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, patch);
|
|
16532
|
+
const order = await orderPromise;
|
|
16533
|
+
if (!order) return;
|
|
16534
|
+
const patched = {
|
|
16535
|
+
...row,
|
|
16536
|
+
...patch
|
|
16537
|
+
};
|
|
16538
|
+
await execPort.onOrderChanged?.({
|
|
16539
|
+
orderFulfillmentId,
|
|
16540
|
+
row: patched,
|
|
16541
|
+
order
|
|
16542
|
+
});
|
|
16543
|
+
};
|
|
16544
|
+
//#endregion
|
|
16545
|
+
//#region src/fulfillment/engine/runner.ts
|
|
16546
|
+
const pendingWebhooksOf = (next) => {
|
|
16547
|
+
if (!next.entered || next.alreadyTerminal) return null;
|
|
16548
|
+
return {
|
|
16549
|
+
previousNodeIds: next.previousNodeIds ?? [],
|
|
16550
|
+
currentNodeIds: next.currentNodeIds
|
|
16551
|
+
};
|
|
16552
|
+
};
|
|
16553
|
+
const dispatchPendingWebhooks = async (ports, scope, pending) => {
|
|
16554
|
+
if (!pending) return;
|
|
16555
|
+
const d1 = {
|
|
16556
|
+
...scope,
|
|
16557
|
+
previousNodeIds: pending.previousNodeIds
|
|
16558
|
+
};
|
|
16559
|
+
const d2 = { currentNodeIds: pending.currentNodeIds };
|
|
16560
|
+
await dispatchOrderWebhooks(ports, {
|
|
16561
|
+
...d1,
|
|
16562
|
+
...d2
|
|
16563
|
+
});
|
|
16564
|
+
};
|
|
16565
|
+
/** Callbacks (durable retries) and the callback-fail terminal for a node. */
|
|
16566
|
+
const settleEnter = async (ports, scope, next) => {
|
|
16567
|
+
if (!next.entered || next.alreadyTerminal) return {
|
|
16568
|
+
next,
|
|
16569
|
+
failed: false,
|
|
16570
|
+
pending: null
|
|
16571
|
+
};
|
|
16572
|
+
const callbacks = await runNodeCallbacks(ports, scope, next);
|
|
16573
|
+
if (callbacks.ok) return {
|
|
16574
|
+
next,
|
|
16575
|
+
failed: false,
|
|
16576
|
+
pending: pendingWebhooksOf(next)
|
|
16577
|
+
};
|
|
16578
|
+
if (callbacks.fatal) return {
|
|
16579
|
+
next,
|
|
16580
|
+
failed: true,
|
|
16581
|
+
fatalCode: callbacks.code,
|
|
16582
|
+
fatalMessage: callbacks.message,
|
|
16583
|
+
fatalDetails: callbacks.details,
|
|
16584
|
+
pending: null
|
|
16585
|
+
};
|
|
16586
|
+
const msg = callbacks.message ?? "Order callbacks failed";
|
|
16587
|
+
await ports.execution.onInjectionFailed?.({
|
|
16588
|
+
orderId: scope.orderId,
|
|
16589
|
+
message: msg
|
|
16590
|
+
});
|
|
16591
|
+
const terminal = await resolveCallbackFailTerminal(ports, { orderFulfillmentId: scope.orderFulfillmentId });
|
|
16592
|
+
if (!terminal) return {
|
|
16593
|
+
next: {
|
|
16594
|
+
...next,
|
|
16595
|
+
successTerminal: null
|
|
16596
|
+
},
|
|
16597
|
+
failed: false,
|
|
16598
|
+
pending: null
|
|
16599
|
+
};
|
|
16600
|
+
const fail = await processStateNode(ports, {
|
|
16601
|
+
...scope,
|
|
16602
|
+
nodeId: terminal.nodeId,
|
|
16603
|
+
fromEdgeIds: [terminal.edgeId]
|
|
16604
|
+
});
|
|
16605
|
+
if (fail.alreadyTerminal) return {
|
|
16606
|
+
next: fail,
|
|
16607
|
+
failed: true,
|
|
16608
|
+
pending: null
|
|
16609
|
+
};
|
|
16610
|
+
if (!fail.entered) throw new Error("Callback fail terminal was not entered");
|
|
16611
|
+
const failCb = await runNodeCallbacks(ports, scope, fail);
|
|
16612
|
+
if (!failCb.ok && failCb.fatal) return {
|
|
16613
|
+
next: fail,
|
|
16614
|
+
failed: true,
|
|
16615
|
+
fatalCode: failCb.code,
|
|
16616
|
+
fatalMessage: failCb.message,
|
|
16617
|
+
fatalDetails: failCb.details,
|
|
16618
|
+
pending: null
|
|
16619
|
+
};
|
|
16620
|
+
return {
|
|
16621
|
+
next: fail,
|
|
16622
|
+
failed: true,
|
|
16623
|
+
pending: pendingWebhooksOf(fail)
|
|
16624
|
+
};
|
|
16625
|
+
};
|
|
16626
|
+
const autoEnterSuccessTerminal = async (ports, scope, ran, terminalStatus) => {
|
|
16627
|
+
if (ran.failed || !ran.next.entered) return ran;
|
|
16628
|
+
if (ran.next.kind === "terminal") return ran;
|
|
16629
|
+
const resolved = ran.next.successTerminal;
|
|
16630
|
+
if (!resolved) return ran;
|
|
16631
|
+
await dispatchPendingWebhooks(ports, scope, ran.pending);
|
|
16632
|
+
const n1 = {
|
|
16633
|
+
...scope,
|
|
16634
|
+
nodeId: resolved.nodeId
|
|
16635
|
+
};
|
|
16636
|
+
const n2 = {
|
|
16637
|
+
fromEdgeIds: resolved.edgeIds,
|
|
16638
|
+
terminalStatus
|
|
16639
|
+
};
|
|
16640
|
+
const next = await processStateNode(ports, {
|
|
16641
|
+
...n1,
|
|
16642
|
+
...n2
|
|
16643
|
+
});
|
|
16644
|
+
return settleEnter(ports, scope, next);
|
|
16645
|
+
};
|
|
16646
|
+
const runIsTerminal = (ran) => {
|
|
16647
|
+
if (ran.failed) return true;
|
|
16648
|
+
return ran.next.kind === "terminal" && ran.next.entered;
|
|
16649
|
+
};
|
|
16650
|
+
const finalizeOrPause = async (ports, scope, settled) => {
|
|
16651
|
+
if (settled.fatalCode) {
|
|
16652
|
+
const f1 = { orderFulfillmentId: scope.orderFulfillmentId };
|
|
16653
|
+
const f2 = {
|
|
16654
|
+
status: "FAILED",
|
|
16655
|
+
failureMessage: settled.fatalMessage
|
|
16656
|
+
};
|
|
16657
|
+
const f3 = {
|
|
16658
|
+
errorCode: settled.fatalCode,
|
|
16659
|
+
errorDetails: settled.fatalDetails ? { ...settled.fatalDetails } : void 0
|
|
16660
|
+
};
|
|
16661
|
+
await finalizePlaceOrder(ports, {
|
|
16662
|
+
...f1,
|
|
16663
|
+
...f2,
|
|
16664
|
+
...f3
|
|
16665
|
+
});
|
|
16666
|
+
return {
|
|
16667
|
+
status: "FAILED",
|
|
16668
|
+
errorCode: settled.fatalCode,
|
|
16669
|
+
errorMessage: settled.fatalMessage
|
|
16670
|
+
};
|
|
16671
|
+
}
|
|
16672
|
+
if (runIsTerminal(settled)) {
|
|
16673
|
+
await finalizePlaceOrder(ports, {
|
|
16674
|
+
orderFulfillmentId: scope.orderFulfillmentId,
|
|
16675
|
+
status: "SUCCESS"
|
|
16676
|
+
});
|
|
16677
|
+
await dispatchPendingWebhooks(ports, scope, settled.pending);
|
|
16678
|
+
return { status: "SUCCESS" };
|
|
16679
|
+
}
|
|
16680
|
+
await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
|
|
16681
|
+
await dispatchPendingWebhooks(ports, scope, settled.pending);
|
|
16682
|
+
return { status: "WAITING" };
|
|
16683
|
+
};
|
|
16684
|
+
const handlePausedNode = async (ports, scope, ran, terminalStatus) => {
|
|
16685
|
+
await dispatchPendingWebhooks(ports, scope, pendingWebhooksOf(ran));
|
|
16686
|
+
if (ran.mappedStatus !== "AWAITING_SCHEDULED_TIME") return { status: "WAITING" };
|
|
16687
|
+
const until = await ports.execution.readScheduledInstant?.(scope.orderId);
|
|
16688
|
+
if (until) {
|
|
16689
|
+
await ports.storage.updateOrderFulfillment(scope.orderFulfillmentId, { scheduled_wake_at: until });
|
|
16690
|
+
return {
|
|
16691
|
+
status: "SCHEDULED_WAIT",
|
|
16692
|
+
scheduledWakeAt: until
|
|
16693
|
+
};
|
|
16694
|
+
}
|
|
16695
|
+
return executeScheduledWake(ports, scope, ran.currentNodeId, terminalStatus);
|
|
16696
|
+
};
|
|
16697
|
+
/** Starts a workflow run from the start node up to the first pause or terminal. */
|
|
16698
|
+
const executeStart = async (ports, scope, runId = "") => {
|
|
16699
|
+
const first = await enterAndPause(ports, {
|
|
16700
|
+
...scope,
|
|
16701
|
+
traverseStart: true,
|
|
16702
|
+
runId
|
|
16703
|
+
});
|
|
16704
|
+
if (first.paused) return handlePausedNode(ports, scope, first.ran);
|
|
16705
|
+
const settled = await settleEnter(ports, scope, first.ran);
|
|
16706
|
+
const auto = await autoEnterSuccessTerminal(ports, scope, settled);
|
|
16707
|
+
return finalizeOrPause(ports, scope, auto);
|
|
16708
|
+
};
|
|
16709
|
+
/** Advances a waiting workflow run by one status event. */
|
|
16710
|
+
const executeAdvance = async (ports, scope, event) => {
|
|
16711
|
+
await ports.storage.updateOrderFulfillment(scope.orderFulfillmentId, { scheduled_wake_at: null });
|
|
16712
|
+
const advanced = await advanceAndEnter(ports, {
|
|
16713
|
+
...scope,
|
|
16714
|
+
fulfillmentStatus: event.fulfillment_status,
|
|
16715
|
+
requestedAt: event.requested_at,
|
|
16716
|
+
terminalStatus: event.status
|
|
16717
|
+
});
|
|
16718
|
+
if (advanced.noEdge) {
|
|
16719
|
+
await warnNoEdge(ports, {
|
|
16720
|
+
orderFulfillmentId: scope.orderFulfillmentId,
|
|
16721
|
+
fulfillmentStatus: event.fulfillment_status
|
|
16722
|
+
});
|
|
16723
|
+
await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
|
|
16724
|
+
return { status: "WAITING" };
|
|
16725
|
+
}
|
|
16726
|
+
if (advanced.paused) return handlePausedNode(ports, scope, advanced.ran, event.status);
|
|
16727
|
+
const settled = await settleEnter(ports, scope, advanced.ran);
|
|
16728
|
+
const auto = await autoEnterSuccessTerminal(ports, scope, settled, event.status);
|
|
16729
|
+
return finalizeOrPause(ports, scope, auto);
|
|
16730
|
+
};
|
|
16731
|
+
/** Wakes a workflow run that was paused on `AWAITING_SCHEDULED_TIME`. */
|
|
16732
|
+
const executeScheduledWake = async (ports, scope, nodeId, terminalStatus) => {
|
|
16733
|
+
await ports.storage.updateOrderFulfillment(scope.orderFulfillmentId, { scheduled_wake_at: null });
|
|
16734
|
+
const successor = await scheduledSuccessorStatus(ports, {
|
|
16735
|
+
...scope,
|
|
16736
|
+
nodeId
|
|
16737
|
+
});
|
|
16738
|
+
if (!successor) {
|
|
16739
|
+
await warnNoEdge(ports, {
|
|
16740
|
+
orderFulfillmentId: scope.orderFulfillmentId,
|
|
16741
|
+
fulfillmentStatus: SCHEDULED_STATUS
|
|
16742
|
+
});
|
|
16743
|
+
await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
|
|
16744
|
+
return { status: "WAITING" };
|
|
16745
|
+
}
|
|
16746
|
+
return executeAdvance(ports, scope, {
|
|
16747
|
+
fulfillment_status: successor,
|
|
16748
|
+
status: terminalStatus
|
|
16749
|
+
});
|
|
16750
|
+
};
|
|
16751
|
+
//#endregion
|
|
12931
16752
|
//#region src/shared/locale.ts
|
|
12932
16753
|
const DEFAULT_LOCALE = "en";
|
|
12933
16754
|
const normalizeLocaleKey = (raw) => {
|
|
@@ -13550,4 +17371,4 @@ const hpkeOpen = async (input) => {
|
|
|
13550
17371
|
return new Uint8Array(opened);
|
|
13551
17372
|
};
|
|
13552
17373
|
//#endregion
|
|
13553
|
-
export { CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_RECOMMENDATION_TYPES, DelegatedSessionExpiredError, HPKE_ALG, ID_HASH_FORMATS, LosslessNumber, ORIGIN_HEADER, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RecurringDateCron, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, TokenExchangeError, addLines, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, auth, base64UrlDecode, base64UrlEncode, buildCustomerSnapshot, buildRulesEngineFromOrder, buildScheduleSlots, canEnterJoin, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, computeStartingPrice, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultOutgoingEdge, detectCardBrand, enterWorkflowNode, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLogContext, getOrigin, getScheduleWindow, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeviceCharged, isDeviceNotLinked, isExpiryComplete, isGenId, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isScheduleSlot, isScheduledAtError, isStateHash, isStorefrontNotFound, isTerminalMappedStatus, isVariantBase, linePayableTotal, listMenusStream, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizePickupName, normalizeStateScope, onOriginChange, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, paymentMatchesClientConditions, pickAdvanceTarget, pickMultiLanguageText, placeCartLines, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCheckout, resolveFailureTerminalEdge, resolveModifierImageUrl, resolveSchedulePrepMinutes, resolveSuccessTerminalEdges, reversePayment, reversedWhenCaptured, roundFeeAmount, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyWebhookSignature, visitedStates };
|
|
17374
|
+
export { CALLBACK_MISSING_LOCAL_URL, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_MAX_INCOMPLETE_MINUTES, DEFAULT_MAX_SNAPSHOT_AGE_MS, DEFAULT_RECOMMENDATION_TYPES, DEFAULT_ROUTE_COOLDOWN_MS, DEFAULT_WEBHOOK_TIMEOUT_S, DelegatedSessionExpiredError, FULFILLMENT_WORKFLOW_TERMINAL_STATUSES, HPKE_ALG, ID_HASH_FORMATS, LosslessNumber, MAX_MAX_INCOMPLETE_MINUTES, MAX_SUPPORTED_WORKFLOW_SCHEMA_VERSION, MIN_MAX_INCOMPLETE_MINUTES, MODE_HINT_HEADER, OFFLINE_NO_LOCAL_URL, ORIGIN_HEADER, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderRouteUnavailableError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RESERVED_FULFILLMENT_STATUSES, RecurringDateCron, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, SCHEDULED_STATUS, SDK_PAYMENT_ELIGIBILITY_CEILINGS, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, TLS_FINGERPRINT_RESPONSE_HEADER, TLS_PIN_HEADER, TlsFingerprintMismatchError, TokenExchangeError, WORKFLOW_SCHEMA_VERSION, WORKFLOW_TIMEOUT, WorkflowSchemaVersionError, addLines, advanceAndEnter, appendEngineStepLog, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, assertSupportedWorkflowSchemaVersion, auth, autoEnterSuccessTerminal, base64UrlDecode, base64UrlEncode, beginEngineStepLog, buildCustomerSnapshot, buildEngineCallbackError, buildEngineCallbackRun, buildRouteHttpOptions, buildRulesEngineFromOrder, buildScheduleSlots, buildWorkflowTimeoutDetails, callbackIdsFromNode, canEnterJoin, canPauseNow, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, certFingerprintsMatch, certMatchesAnyPin, classifyRouteFailure, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, completeEngineStepLog, computeOrderExpiresAt, computeStartingPrice, configureLocalTlsPinning, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createNodePinnedFetch, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultIsPaymentCaptured, defaultOutgoingEdge, defaultWebhookEventsForStatus, defaultWebhookRetryDelayMs, detectCardBrand, dispatchOrderWebhooks, dispatchPendingWebhooks, engineHmacSha256Hex, engineOrderStatusForFailedRun, engineWebhookDeliveryId, engineWebhookRunsForEnteredNodes, engineWebhookStatusKey, engineWebhookTransitionStates, enterAndPause, enterWorkflowNode, executeAdvance, executeScheduledWake, executeStart, failActiveEngineStepLog, finalizePlaceOrder, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatLocalServerUrl, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLocalTlsPinning, getLogContext, getOrigin, getRouteHealth, getScheduleWindow, hasInFlightPayment, hasLocalTlsPinning, hasSmartRouting, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, injectingMetadataFromCallback, invokeCallbackAttempt, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeviceCharged, isDeviceNotLinked, isExpiredFulfillment, isExpiryComplete, isGenId, isInterruptTerminalStatus, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isNodeRuntime, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderRouteUnavailableError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isReservedFulfillmentStatus, isRouteCircuitOpen, isScheduleSlot, isScheduledAtError, isStateHash, isStorefrontNotFound, isSupportedWorkflowSchemaVersion, isTerminalFulfillmentStatus, isTerminalMappedStatus, isTlsFingerprintMismatchError, isVariantBase, linePayableTotal, listMenusStream, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, markRouteDown, markRouteHealthy, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCertFingerprint, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizeMaxIncompleteMinutes, normalizePickupName, normalizeStateScope, onOriginChange, onRouteHealth, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, pauseForAdvance, paymentMatchesClientConditions, pendingWebhooksOf, pickAdvanceTarget, pickMultiLanguageText, placeCartLines, probeLocalRouteHealth, processStateNode, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCallbackFailTerminal, resolveCheckout, resolveFailureTerminalEdge, resolveLocalPins, resolveLocalRouteUrl, resolveModifierImageUrl, resolveOrderRouteEligibility, resolvePaymentEligibility, resolveSchedulePrepMinutes, resolveSdkPaymentEligibilityCeiling, resolveSuccessTerminalEdges, resolveWebhookTargetUrl, resumeFromAdvance, reversePayment, reversedWhenCaptured, roundFeeAmount, runIsTerminal, runNodeCallbacks, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, scheduledSuccessorStatus, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, settleEnter, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, workflowSchemaVersionOf };
|