@adobe/aio-commerce-lib-core 0.6.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/README.md +1 -4
- package/dist/cjs/error/index.cjs +5 -1
- package/dist/cjs/headers/index.cjs +432 -1
- package/dist/cjs/headers/index.d.cts +1 -2
- package/dist/cjs/params/index.cjs +27 -1
- package/dist/cjs/params/index.d.cts +1 -1
- package/dist/cjs/responses/index.cjs +195 -1
- package/dist/cjs/{index-2lCdMqhT.d.cts → types-CfxNboCU.d.cts} +4 -9
- package/dist/cjs/validation-error-DuipISU5.cjs +214 -0
- package/dist/es/error/index.mjs +3 -1
- package/dist/es/headers/index.d.mts +1 -2
- package/dist/es/headers/index.mjs +419 -1
- package/dist/es/params/index.d.mts +1 -1
- package/dist/es/params/index.mjs +24 -1
- package/dist/es/responses/index.mjs +168 -1
- package/dist/es/{index-CPYhPt8X.d.mts → types-CMBSX5l-.d.mts} +4 -9
- package/dist/es/validation-error-DT4-Oa0Z.mjs +169 -0
- package/package.json +6 -4
- package/dist/cjs/error-LUQPfUfP.cjs +0 -2
- package/dist/es/error-LySQb5Bh.mjs +0 -2
|
@@ -1 +1,419 @@
|
|
|
1
|
-
import{t as CommerceSdkValidationError
|
|
1
|
+
import { t as CommerceSdkValidationError } from "../validation-error-DT4-Oa0Z.mjs";
|
|
2
|
+
import { literal, nonEmpty, object, pipe, rawCheck, rawTransform, record, safeParse, string, trim, undefined as undefined$1, union } from "valibot";
|
|
3
|
+
import camelcase from "camelcase";
|
|
4
|
+
|
|
5
|
+
//#region source/headers/helpers.ts
|
|
6
|
+
/**
|
|
7
|
+
* Extracts a header value from an object with case-insensitive lookup.
|
|
8
|
+
* This is useful for handling HTTP headers which can be case-insensitive per RFC 7230.
|
|
9
|
+
*
|
|
10
|
+
* When enabled via options, comma-separated header values (per RFC 9110) can be
|
|
11
|
+
* automatically split into an array. This is useful when multiple header values
|
|
12
|
+
* are combined into a single comma-separated string.
|
|
13
|
+
*
|
|
14
|
+
* @param headers The headers object to search in.
|
|
15
|
+
* @param name The header name to look for (case-insensitive).
|
|
16
|
+
* @param options Optional settings to control header value processing.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```typescript
|
|
20
|
+
* const headers = { authorization: "Bearer token123" };
|
|
21
|
+
* const auth = getHeader(headers, "Authorization"); // "Bearer token123"
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```typescript
|
|
26
|
+
* // Comma-separated string can be split when enabled (per RFC 9110)
|
|
27
|
+
* const headers = { "Example-Field": "Foo, Bar" };
|
|
28
|
+
* const value = getHeader(headers, "Example-Field", { splitCommaSeparated: true }); // ["Foo", "Bar"]
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @see https://datatracker.ietf.org/doc/html/rfc7230 - HTTP/1.1 Message Syntax and Routing
|
|
32
|
+
* @see https://datatracker.ietf.org/doc/html/rfc9110#name-field-lines-and-combined-fi - HTTP Semantics: Field Lines and Combined Field Values
|
|
33
|
+
*/
|
|
34
|
+
function getHeader(headers, name, options) {
|
|
35
|
+
const { splitCommaSeparated = false } = options ?? {};
|
|
36
|
+
let value;
|
|
37
|
+
if (Object.hasOwn(headers, name)) value = headers[name];
|
|
38
|
+
else {
|
|
39
|
+
const lowerName = name.toLowerCase();
|
|
40
|
+
for (const key in headers) if (Object.hasOwn(headers, key) && key.toLowerCase() === lowerName) {
|
|
41
|
+
value = headers[key];
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (splitCommaSeparated && typeof value === "string" && value.includes(",")) value = value.split(",").map((v) => v.trim());
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Extracts the `__ow_headers` object from App Builder runtime action parameters.
|
|
50
|
+
*
|
|
51
|
+
* @param params The action parameters from App Builder runtime.
|
|
52
|
+
* @throws {CommerceSdkValidationError} If `__ow_headers` is missing or not an object.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```typescript
|
|
56
|
+
* export async function main(params) {
|
|
57
|
+
* const headers = getHeadersFromParams(params);
|
|
58
|
+
* const apiKey = headers["x-api-key"];
|
|
59
|
+
* }
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
62
|
+
function getHeadersFromParams(params) {
|
|
63
|
+
const parsed = safeParse(object({ __ow_headers: record(string(), union([string(), undefined$1()])) }), params);
|
|
64
|
+
if (!parsed.success) throw new CommerceSdkValidationError("Missing __ow_headers in action params", { issues: parsed.issues });
|
|
65
|
+
return parsed.output.__ow_headers;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region source/headers/validation.ts
|
|
70
|
+
/**
|
|
71
|
+
* Returns an array of missing or empty headers using Valibot validation.
|
|
72
|
+
* Case-insensitive by default.
|
|
73
|
+
*
|
|
74
|
+
* Unlike {@link assertRequiredHeaders}, this function does not throw an error.
|
|
75
|
+
* Instead, it returns an array of header names that are missing or empty.
|
|
76
|
+
* This is useful when you need to check headers without immediately failing.
|
|
77
|
+
*
|
|
78
|
+
* @param headers The headers object to validate.
|
|
79
|
+
* @param requiredHeaders Array of required header names.
|
|
80
|
+
* @returns Array of header names that are missing or empty. Empty array if all headers are present and non-empty.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```typescript
|
|
84
|
+
* const headers = { "x-api-key": "key123" };
|
|
85
|
+
* const missing = getMissingOrEmptyHeaders(headers, ["x-api-key", "Authorization"]);
|
|
86
|
+
* // Returns: ["Authorization"]
|
|
87
|
+
* ```
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* ```typescript
|
|
91
|
+
* const headers = { "x-api-key": "", "Authorization": "Bearer token" };
|
|
92
|
+
* const missing = getMissingOrEmptyHeaders(headers, ["x-api-key", "Authorization"]);
|
|
93
|
+
* // Returns: ["x-api-key"] (empty string is considered missing)
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
function getMissingOrEmptyHeaders(headers, requiredHeaders) {
|
|
97
|
+
const normalized = {};
|
|
98
|
+
if (headers && typeof headers === "object" && !Array.isArray(headers)) for (const key of Object.keys(headers)) {
|
|
99
|
+
const value = headers[key];
|
|
100
|
+
if (value !== void 0 && value !== null) normalized[key.toLowerCase()] = value;
|
|
101
|
+
}
|
|
102
|
+
const parsed = safeParse(buildHeadersSchema(requiredHeaders.map((h) => literal(h))), normalized);
|
|
103
|
+
if (parsed.success) return [];
|
|
104
|
+
const lookup = new Map(requiredHeaders.map((h) => [h.toLowerCase(), h]));
|
|
105
|
+
return parsed.issues.flatMap((issue) => {
|
|
106
|
+
const key = issue.path?.[0]?.key;
|
|
107
|
+
const original = typeof key === "string" ? lookup.get(key.toLowerCase()) : null;
|
|
108
|
+
return original ? [original] : [];
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Builds a Valibot schema that checks:
|
|
113
|
+
* - Required headers exist (case-insensitive)
|
|
114
|
+
* - Each required header has a non-empty string value
|
|
115
|
+
*/
|
|
116
|
+
function buildHeadersSchema(requiredHeaders) {
|
|
117
|
+
const buildSchema = () => pipe(string("Expected a string value for the header"), rawCheck(({ dataset, addIssue }) => {
|
|
118
|
+
if (!dataset.typed) return;
|
|
119
|
+
const value = dataset.value;
|
|
120
|
+
if (value.trim() === "") {
|
|
121
|
+
addIssue({
|
|
122
|
+
expected: "a non-empty string value",
|
|
123
|
+
received: `"${value}"`,
|
|
124
|
+
message: "Header value cannot be empty or contain only whitespace"
|
|
125
|
+
});
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (value.includes(",")) {
|
|
129
|
+
const parts = value.split(",").map((part) => part.trim());
|
|
130
|
+
if (!parts.some((part) => part !== "")) addIssue({
|
|
131
|
+
expected: "at least one non-empty value in comma-separated list",
|
|
132
|
+
received: `[${parts.join(", ")}]`,
|
|
133
|
+
message: "Header value contains only empty or whitespace values when split by comma"
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
}));
|
|
137
|
+
const shape = {};
|
|
138
|
+
for (const schema of requiredHeaders) shape[schema.literal.toLowerCase()] = buildSchema();
|
|
139
|
+
return object(shape);
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Validates that required headers are present in the headers object.
|
|
143
|
+
* Case-insensitive by default (HTTP standard).
|
|
144
|
+
*
|
|
145
|
+
* This is an advanced validation function that accepts Valibot `LiteralSchema` objects
|
|
146
|
+
* instead of plain strings. Use {@link assertRequiredHeaders} for the simpler string-based API.
|
|
147
|
+
*
|
|
148
|
+
* @param headers The headers object to validate.
|
|
149
|
+
* @param requiredHeaders Array of required header names as Valibot `LiteralSchema` objects.
|
|
150
|
+
* @throws {CommerceSdkValidationError} If validation fails.
|
|
151
|
+
*
|
|
152
|
+
* @example
|
|
153
|
+
* ```typescript
|
|
154
|
+
* import { literal } from "valibot";
|
|
155
|
+
* import { assertRequiredHeadersSchema } from "@adobe/aio-commerce-lib-core/headers";
|
|
156
|
+
*
|
|
157
|
+
* const headers = getHeadersFromParams(params);
|
|
158
|
+
* assertRequiredHeadersSchema(headers, [
|
|
159
|
+
* literal("x-api-key"),
|
|
160
|
+
* literal("Authorization"),
|
|
161
|
+
* ]);
|
|
162
|
+
* ```
|
|
163
|
+
*/
|
|
164
|
+
function assertRequiredHeadersSchema(headers, requiredHeaders) {
|
|
165
|
+
const normalized = {};
|
|
166
|
+
if (headers && typeof headers === "object" && !Array.isArray(headers)) for (const key of Object.keys(headers)) {
|
|
167
|
+
const value = headers[key];
|
|
168
|
+
if (value !== void 0 && value !== null) normalized[key.toLowerCase()] = value;
|
|
169
|
+
}
|
|
170
|
+
const parsed = safeParse(buildHeadersSchema(requiredHeaders), normalized);
|
|
171
|
+
if (!parsed.success) throw new CommerceSdkValidationError("The headers object does not match the required headers (case-insensitive)", { issues: parsed.issues });
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Validates that required headers are present and non-empty in the headers object.
|
|
175
|
+
* Performs case-insensitive validation with {@link getHeader}.
|
|
176
|
+
*
|
|
177
|
+
* @param headers The headers object to validate.
|
|
178
|
+
* @param requiredHeaders Array of required header names.
|
|
179
|
+
* @throws {CommerceSdkValidationError} If any required headers are missing or empty.
|
|
180
|
+
*
|
|
181
|
+
* @example
|
|
182
|
+
* ```typescript
|
|
183
|
+
* const headers = { "x-api-key": "key123", "Authorization": "Bearer token" };
|
|
184
|
+
* assertRequiredHeaders(headers, ["x-api-key", "Authorization"]);
|
|
185
|
+
* // Headers are validated, use getHeader() for safe access
|
|
186
|
+
* const apiKey = getHeader(headers, "x-api-key")!;
|
|
187
|
+
* ```
|
|
188
|
+
*
|
|
189
|
+
* @example
|
|
190
|
+
* ```typescript
|
|
191
|
+
* try {
|
|
192
|
+
* assertRequiredHeaders({}, ["x-api-key", "Authorization"]);
|
|
193
|
+
* } catch (error) {
|
|
194
|
+
* console.error(error.display());
|
|
195
|
+
* // "The headers object does not match the required headers (case-insensitive)"
|
|
196
|
+
* // ├── Schema validation error at x-api-key → Expected a non-empty string value
|
|
197
|
+
* // └── Schema validation error at Authorization → Expected a non-empty string value
|
|
198
|
+
* }
|
|
199
|
+
* ```
|
|
200
|
+
*/
|
|
201
|
+
function assertRequiredHeaders(headers, requiredHeaders) {
|
|
202
|
+
assertRequiredHeadersSchema(headers, requiredHeaders.map((header) => literal(header)));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
//#endregion
|
|
206
|
+
//#region source/headers/accessor.ts
|
|
207
|
+
/**
|
|
208
|
+
* Creates a type-safe header accessor object with validated required headers.
|
|
209
|
+
* Header names are normalized to camelCase for consistent access.
|
|
210
|
+
*
|
|
211
|
+
* @param headers The headers object from runtime params.
|
|
212
|
+
* @param requiredHeaders Array of required header names.
|
|
213
|
+
* @param options Optional settings to control header value processing (e.g., `splitCommaSeparated`).
|
|
214
|
+
* @throws {CommerceSdkValidationError} If any required headers are missing or empty.
|
|
215
|
+
*
|
|
216
|
+
* @example
|
|
217
|
+
* ```typescript
|
|
218
|
+
* const headers = getHeadersFromParams(params);
|
|
219
|
+
* const accessor = createHeaderAccessor(headers, ["x-api-key", "Authorization"]);
|
|
220
|
+
*
|
|
221
|
+
* // TypeScript knows these are non-empty strings (normalized to camelCase)
|
|
222
|
+
* const apiKey = accessor.xApiKey; // string
|
|
223
|
+
* const auth = accessor.authorization; // string
|
|
224
|
+
* ```
|
|
225
|
+
*
|
|
226
|
+
* @example
|
|
227
|
+
* ```typescript
|
|
228
|
+
* // With options to enable comma-separated value splitting
|
|
229
|
+
* const accessor = createHeaderAccessor(
|
|
230
|
+
* headers,
|
|
231
|
+
* ["cache-control"],
|
|
232
|
+
* { splitCommaSeparated: true }
|
|
233
|
+
* );
|
|
234
|
+
* // accessor.cacheControl may be string | string[] depending on comma presence
|
|
235
|
+
* ```
|
|
236
|
+
*/
|
|
237
|
+
function createHeaderAccessor(headers, requiredHeaders, options) {
|
|
238
|
+
assertRequiredHeaders(headers, requiredHeaders);
|
|
239
|
+
const accessor = {};
|
|
240
|
+
for (const header of requiredHeaders) {
|
|
241
|
+
const camelKey = camelcase(header);
|
|
242
|
+
accessor[camelKey] = getHeader(headers, header, options);
|
|
243
|
+
}
|
|
244
|
+
return accessor;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
//#endregion
|
|
248
|
+
//#region source/headers/auth.ts
|
|
249
|
+
/**
|
|
250
|
+
* Type guard to check if authorization is Bearer type.
|
|
251
|
+
*/
|
|
252
|
+
function isBearerAuth(auth) {
|
|
253
|
+
return auth.scheme === "Bearer";
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Type guard to check if authorization is Basic type.
|
|
257
|
+
*/
|
|
258
|
+
function isBasicAuth(auth) {
|
|
259
|
+
return auth.scheme === "Basic";
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Type guard to check if authorization is OAuth type.
|
|
263
|
+
*/
|
|
264
|
+
function isOAuth(auth) {
|
|
265
|
+
return auth.scheme === "OAuth";
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Parses key="value" or key=value parameters from a string.
|
|
269
|
+
* Used for OAuth and other schemes with comma-separated key-value pairs.
|
|
270
|
+
*
|
|
271
|
+
* @param parametersString The parameters string.
|
|
272
|
+
*/
|
|
273
|
+
function parseKeyValueParameters(parametersString) {
|
|
274
|
+
const params = {};
|
|
275
|
+
const paramPattern = /(\w+)=(?:"([^"]*)"|([^,\s]+))/g;
|
|
276
|
+
let match = paramPattern.exec(parametersString);
|
|
277
|
+
while (match !== null) {
|
|
278
|
+
const [, key, quotedValue, unquotedValue] = match;
|
|
279
|
+
params[key] = quotedValue !== void 0 ? quotedValue : unquotedValue;
|
|
280
|
+
match = paramPattern.exec(parametersString);
|
|
281
|
+
}
|
|
282
|
+
return params;
|
|
283
|
+
}
|
|
284
|
+
const authorizationSchema = pipe(string("Expected a string value"), trim(), nonEmpty("Expected a non-empty string value"), rawTransform(({ dataset: { value: authorization }, addIssue, NEVER }) => {
|
|
285
|
+
const spaceIndex = authorization.indexOf(" ");
|
|
286
|
+
if (spaceIndex === -1) {
|
|
287
|
+
addIssue({ message: "Invalid Authorization header format" });
|
|
288
|
+
return NEVER;
|
|
289
|
+
}
|
|
290
|
+
return {
|
|
291
|
+
scheme: authorization.slice(0, spaceIndex),
|
|
292
|
+
parameters: authorization.slice(spaceIndex + 1).trim()
|
|
293
|
+
};
|
|
294
|
+
}));
|
|
295
|
+
/**
|
|
296
|
+
* Parses an Authorization header value into its scheme and parameters.
|
|
297
|
+
*
|
|
298
|
+
* @param authorization The Authorization header value.
|
|
299
|
+
* @throws {CommerceSdkValidationError} If the authorization header is malformed.
|
|
300
|
+
*
|
|
301
|
+
* @example
|
|
302
|
+
* ```typescript
|
|
303
|
+
* const auth = parseAuthorization("Bearer token123");
|
|
304
|
+
* // { scheme: "Bearer", token: "token123" }
|
|
305
|
+
* ```
|
|
306
|
+
*
|
|
307
|
+
* @example
|
|
308
|
+
* ```typescript
|
|
309
|
+
* const auth = parseAuthorization("Basic dXNlcjpwYXNz");
|
|
310
|
+
* // { scheme: "Basic", credentials: "dXNlcjpwYXNz" }
|
|
311
|
+
* ```
|
|
312
|
+
*
|
|
313
|
+
* @example
|
|
314
|
+
* ```typescript
|
|
315
|
+
* const auth = parseAuthorization('OAuth oauth_consumer_key="key", oauth_token="token"');
|
|
316
|
+
* // { scheme: "OAuth", parameters: { oauth_consumer_key: "key", oauth_token: "token" } }
|
|
317
|
+
* ```
|
|
318
|
+
*
|
|
319
|
+
* @example
|
|
320
|
+
* ```typescript
|
|
321
|
+
* const auth = parseAuthorization('Digest realm="Example", nonce="abc"');
|
|
322
|
+
* // { scheme: "Digest", rawParameters: 'realm="Example", nonce="abc"' }
|
|
323
|
+
*
|
|
324
|
+
* const parameters = auth.parseParameters();
|
|
325
|
+
* // { realm: "Example", nonce: "abc" }
|
|
326
|
+
* ```
|
|
327
|
+
*/
|
|
328
|
+
function parseAuthorization(authorization) {
|
|
329
|
+
const parsed = safeParse(authorizationSchema, authorization);
|
|
330
|
+
if (!parsed.success) throw new CommerceSdkValidationError("Invalid Authorization header format", { issues: parsed.issues });
|
|
331
|
+
const { scheme, parameters } = parsed.output;
|
|
332
|
+
if (scheme === "Bearer") return {
|
|
333
|
+
scheme: "Bearer",
|
|
334
|
+
token: parameters
|
|
335
|
+
};
|
|
336
|
+
if (scheme === "Basic") return {
|
|
337
|
+
scheme: "Basic",
|
|
338
|
+
credentials: parameters
|
|
339
|
+
};
|
|
340
|
+
if (scheme === "OAuth") return {
|
|
341
|
+
scheme: "OAuth",
|
|
342
|
+
parameters: parseKeyValueParameters(parameters)
|
|
343
|
+
};
|
|
344
|
+
return {
|
|
345
|
+
scheme,
|
|
346
|
+
rawParameters: parameters,
|
|
347
|
+
parseParameters: () => parseKeyValueParameters(parameters)
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
const bearerSchema = object({ scheme: literal("Bearer") });
|
|
351
|
+
/**
|
|
352
|
+
* Parses and validates a Bearer authorization header.
|
|
353
|
+
*
|
|
354
|
+
* @param authorization The Authorization header value.
|
|
355
|
+
* @throws {CommerceSdkValidationError} If the authorization header is not a Bearer token or if the token is empty.
|
|
356
|
+
*
|
|
357
|
+
* @example
|
|
358
|
+
* ```typescript
|
|
359
|
+
* const auth = parseBearerToken("Bearer eyJhbGci...");
|
|
360
|
+
* console.log(auth.token); // "eyJhbGci..."
|
|
361
|
+
* ```
|
|
362
|
+
*
|
|
363
|
+
* @example
|
|
364
|
+
* ```typescript
|
|
365
|
+
* try {
|
|
366
|
+
* parseBearerToken("Basic dXNlcjpwYXNz");
|
|
367
|
+
* } catch (error) {
|
|
368
|
+
* console.error(error.message); // "Authorization header must be a Bearer token"
|
|
369
|
+
* }
|
|
370
|
+
* ```
|
|
371
|
+
*/
|
|
372
|
+
function parseBearerToken(authorization) {
|
|
373
|
+
const auth = parseAuthorization(authorization);
|
|
374
|
+
const parsed = safeParse(bearerSchema, auth);
|
|
375
|
+
if (!parsed.success) throw new CommerceSdkValidationError("Authorization header must be a Bearer token", { issues: parsed.issues });
|
|
376
|
+
return auth;
|
|
377
|
+
}
|
|
378
|
+
const basicSchema = object({ scheme: literal("Basic") });
|
|
379
|
+
/**
|
|
380
|
+
* Parses and validates a Basic authorization header.
|
|
381
|
+
*
|
|
382
|
+
* @param authorization The Authorization header value.
|
|
383
|
+
* @throws {CommerceSdkValidationError} If the authorization header is not Basic auth.
|
|
384
|
+
*
|
|
385
|
+
* @example
|
|
386
|
+
* ```typescript
|
|
387
|
+
* const auth = parseBasicToken("Basic dXNlcjpwYXNz");
|
|
388
|
+
* console.log(auth.credentials); // "dXNlcjpwYXNz"
|
|
389
|
+
* ```
|
|
390
|
+
*/
|
|
391
|
+
function parseBasicToken(authorization) {
|
|
392
|
+
const auth = parseAuthorization(authorization);
|
|
393
|
+
const parsed = safeParse(basicSchema, auth);
|
|
394
|
+
if (!parsed.success) throw new CommerceSdkValidationError("Authorization header must be Basic authentication", { issues: parsed.issues });
|
|
395
|
+
return auth;
|
|
396
|
+
}
|
|
397
|
+
const oauthSchema = object({ scheme: literal("OAuth") });
|
|
398
|
+
/**
|
|
399
|
+
* Parses and validates an OAuth 1.0 authorization header.
|
|
400
|
+
*
|
|
401
|
+
* @param authorization The Authorization header value.
|
|
402
|
+
* @throws {CommerceSdkValidationError} If the authorization header is not OAuth.
|
|
403
|
+
*
|
|
404
|
+
* @example
|
|
405
|
+
* ```typescript
|
|
406
|
+
* const auth = parseOAuthToken('OAuth oauth_consumer_key="key", oauth_token="token"');
|
|
407
|
+
* console.log(auth.parameters.oauth_consumer_key); // "key"
|
|
408
|
+
* console.log(auth.parameters.oauth_token); // "token"
|
|
409
|
+
* ```
|
|
410
|
+
*/
|
|
411
|
+
function parseOAuthToken(authorization) {
|
|
412
|
+
const auth = parseAuthorization(authorization);
|
|
413
|
+
const parsed = safeParse(oauthSchema, auth);
|
|
414
|
+
if (!parsed.success) throw new CommerceSdkValidationError("Authorization header must be OAuth", { issues: parsed.issues });
|
|
415
|
+
return auth;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
//#endregion
|
|
419
|
+
export { assertRequiredHeaders, createHeaderAccessor, getHeader, getHeadersFromParams, getMissingOrEmptyHeaders, isBasicAuth, isBearerAuth, isOAuth, parseAuthorization, parseBasicToken, parseBearerToken, parseOAuthToken };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as nonEmpty, i as allNonEmpty, n as HttpMethodLowercase, r as RuntimeActionParams, t as HttpMethod } from "../
|
|
1
|
+
import { a as nonEmpty, i as allNonEmpty, n as HttpMethodLowercase, r as RuntimeActionParams, t as HttpMethod } from "../types-CMBSX5l-.mjs";
|
|
2
2
|
export { HttpMethod, HttpMethodLowercase, RuntimeActionParams, allNonEmpty, nonEmpty };
|
package/dist/es/params/index.mjs
CHANGED
|
@@ -1 +1,24 @@
|
|
|
1
|
-
|
|
1
|
+
//#region source/params/helpers.ts
|
|
2
|
+
/**
|
|
3
|
+
* Checks if the given runtime action input value is non-empty.
|
|
4
|
+
*
|
|
5
|
+
* @param name - The name of the parameter. Required because of `aio app dev` compatibility: inputs mapped to undefined env vars come as $<input_name> in dev mode, but as '' in prod mode.
|
|
6
|
+
* @param value - The value of the parameter.
|
|
7
|
+
*/
|
|
8
|
+
function nonEmpty(name, value) {
|
|
9
|
+
if (value === void 0 || value === null) return false;
|
|
10
|
+
const v = String(value)?.trim();
|
|
11
|
+
return !!v && v !== `$${name}`;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Checks if all required parameters are non-empty.
|
|
15
|
+
*
|
|
16
|
+
* @param params - The action input parameters.
|
|
17
|
+
* @param required - The list of required parameter names.
|
|
18
|
+
*/
|
|
19
|
+
function allNonEmpty(params, required) {
|
|
20
|
+
return required.every((name) => nonEmpty(name, params[name]));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
//#endregion
|
|
24
|
+
export { allNonEmpty, nonEmpty };
|
|
@@ -1 +1,168 @@
|
|
|
1
|
-
|
|
1
|
+
//#region source/responses/helpers.ts
|
|
2
|
+
/**
|
|
3
|
+
* Creates a standardized error response for runtime actions
|
|
4
|
+
* @see https://developer.adobe.com/app-builder/docs/guides/runtime_guides/creating-actions#unsuccessful-response
|
|
5
|
+
*
|
|
6
|
+
* @template TBody - Additional error body properties beyond the required message field
|
|
7
|
+
* @template THeaders - Custom response headers
|
|
8
|
+
*
|
|
9
|
+
* @param statusCode - HTTP status code (e.g., 400, 404, 500)
|
|
10
|
+
* @param payload - Error response configuration
|
|
11
|
+
* @param payload.message - Human-readable error message (required)
|
|
12
|
+
* @param payload.body - Optional additional error details to include in the response body
|
|
13
|
+
* @param payload.headers - Optional custom response headers
|
|
14
|
+
*
|
|
15
|
+
* @returns Standardized error response object with type discriminator
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```typescript
|
|
19
|
+
* // Simple error with just a message
|
|
20
|
+
* const error = buildErrorResponse(404, {
|
|
21
|
+
* message: 'Resource not found'
|
|
22
|
+
* });
|
|
23
|
+
*
|
|
24
|
+
* // Error with additional body data
|
|
25
|
+
* const error = buildErrorResponse(400, {
|
|
26
|
+
* message: 'Invalid request',
|
|
27
|
+
* body: { field: 'email', code: 'INVALID_FORMAT' }
|
|
28
|
+
* });
|
|
29
|
+
*
|
|
30
|
+
* // Error with custom headers
|
|
31
|
+
* const error = buildErrorResponse(429, {
|
|
32
|
+
* message: 'Rate limit exceeded',
|
|
33
|
+
* headers: { 'Retry-After': '60' }
|
|
34
|
+
* });
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
function buildErrorResponse(statusCode, payload) {
|
|
38
|
+
return {
|
|
39
|
+
type: "error",
|
|
40
|
+
error: {
|
|
41
|
+
...payload?.headers && { headers: payload.headers },
|
|
42
|
+
statusCode,
|
|
43
|
+
body: payload.body
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Creates a standardized success response for runtime actions
|
|
49
|
+
* @see https://developer.adobe.com/app-builder/docs/guides/runtime_guides/creating-actions#successful-response
|
|
50
|
+
*
|
|
51
|
+
* @template TBody - Response body properties
|
|
52
|
+
* @template THeaders - Custom response headers
|
|
53
|
+
*
|
|
54
|
+
* @param statusCode - HTTP status code (typically 200, 201, 204, etc.)
|
|
55
|
+
* @param payload - Success response configuration
|
|
56
|
+
* @param payload.message - Human-readable success message (required)
|
|
57
|
+
* @param payload.body - Optional additional response data to include in the response body
|
|
58
|
+
* @param payload.headers - Optional custom response headers
|
|
59
|
+
*
|
|
60
|
+
* @returns Standardized success response object with type discriminator
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* ```typescript
|
|
64
|
+
* // Simple success response
|
|
65
|
+
* const response = buildSuccessResponse(200, {
|
|
66
|
+
* message: 'Operation successful'
|
|
67
|
+
* });
|
|
68
|
+
*
|
|
69
|
+
* // Success with additional body data
|
|
70
|
+
* const response = buildSuccessResponse(201, {
|
|
71
|
+
* message: 'Resource created',
|
|
72
|
+
* body: { id: '456', created: true },
|
|
73
|
+
* headers: { 'Location': '/api/resources/456' }
|
|
74
|
+
* });
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
function buildSuccessResponse(statusCode, payload) {
|
|
78
|
+
return {
|
|
79
|
+
type: "success",
|
|
80
|
+
statusCode,
|
|
81
|
+
...payload?.headers && { headers: payload.headers },
|
|
82
|
+
...payload?.body && { body: payload.body }
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
//#endregion
|
|
87
|
+
//#region source/responses/presets.ts
|
|
88
|
+
const HTTP_OK = 200;
|
|
89
|
+
const HTTP_CREATED = 201;
|
|
90
|
+
const HTTP_ACCEPTED = 202;
|
|
91
|
+
const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
|
|
92
|
+
const HTTP_NO_CONTENT = 204;
|
|
93
|
+
const HTTP_BAD_REQUEST = 400;
|
|
94
|
+
const HTTP_UNAUTHORIZED = 401;
|
|
95
|
+
const HTTP_FORBIDDEN = 403;
|
|
96
|
+
const HTTP_NOT_FOUND = 404;
|
|
97
|
+
const HTTP_METHOD_NOT_ALLOWED = 405;
|
|
98
|
+
const HTTP_CONFLICT = 409;
|
|
99
|
+
const HTTP_INTERNAL_SERVER_ERROR = 500;
|
|
100
|
+
function curryBuildSuccessResponse(code) {
|
|
101
|
+
return (payload) => buildSuccessResponse(code, typeof payload === "string" ? { body: { message: payload } } : payload);
|
|
102
|
+
}
|
|
103
|
+
function curryBuildErrorResponse(code) {
|
|
104
|
+
return (payload) => buildErrorResponse(code, typeof payload === "string" ? { body: { message: payload } } : payload);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Creates a success response with the HTTP status code 200.
|
|
108
|
+
* See {@link buildSuccessResponse} for details on the response payload.
|
|
109
|
+
*/
|
|
110
|
+
const ok = curryBuildSuccessResponse(HTTP_OK);
|
|
111
|
+
/**
|
|
112
|
+
* Creates a success response with the HTTP status code 201.
|
|
113
|
+
* See {@link buildSuccessResponse} for details on the response payload.
|
|
114
|
+
*/
|
|
115
|
+
const created = curryBuildSuccessResponse(HTTP_CREATED);
|
|
116
|
+
/**
|
|
117
|
+
* Creates a success response with the HTTP status code 202.
|
|
118
|
+
* See {@link buildSuccessResponse} for details on the response payload.
|
|
119
|
+
*/
|
|
120
|
+
const accepted = curryBuildSuccessResponse(HTTP_ACCEPTED);
|
|
121
|
+
/**
|
|
122
|
+
* Creates a success response with the HTTP status code 203.
|
|
123
|
+
* See {@link buildSuccessResponse} for details on the response payload.
|
|
124
|
+
*/
|
|
125
|
+
const nonAuthoritativeInformation = curryBuildSuccessResponse(HTTP_NON_AUTHORITATIVE_INFORMATION);
|
|
126
|
+
/**
|
|
127
|
+
* Creates a success response with the HTTP status code 204 (No Content).
|
|
128
|
+
* This response has no body.
|
|
129
|
+
*/
|
|
130
|
+
const noContent = () => buildSuccessResponse(HTTP_NO_CONTENT);
|
|
131
|
+
/**
|
|
132
|
+
* Creates an error response with the HTTP status code 400.
|
|
133
|
+
* See {@link buildErrorResponse} for details on the response payload.
|
|
134
|
+
*/
|
|
135
|
+
const badRequest = curryBuildErrorResponse(HTTP_BAD_REQUEST);
|
|
136
|
+
/**
|
|
137
|
+
* Creates an error response with the HTTP status code 401.
|
|
138
|
+
* See {@link buildErrorResponse} for details on the response payload.
|
|
139
|
+
*/
|
|
140
|
+
const unauthorized = curryBuildErrorResponse(HTTP_UNAUTHORIZED);
|
|
141
|
+
/**
|
|
142
|
+
* Creates an error response with the HTTP status code 403.
|
|
143
|
+
* See {@link buildErrorResponse} for details on the response payload.
|
|
144
|
+
*/
|
|
145
|
+
const forbidden = curryBuildErrorResponse(HTTP_FORBIDDEN);
|
|
146
|
+
/**
|
|
147
|
+
* Creates an error response with the HTTP status code 404.
|
|
148
|
+
* See {@link buildErrorResponse} for details on the response payload.
|
|
149
|
+
*/
|
|
150
|
+
const notFound = curryBuildErrorResponse(HTTP_NOT_FOUND);
|
|
151
|
+
/**
|
|
152
|
+
* Creates an error response with the HTTP status code 405.
|
|
153
|
+
* See {@link buildErrorResponse} for details on the response payload.
|
|
154
|
+
*/
|
|
155
|
+
const methodNotAllowed = curryBuildErrorResponse(HTTP_METHOD_NOT_ALLOWED);
|
|
156
|
+
/**
|
|
157
|
+
* Creates an error response with the HTTP status code 409.
|
|
158
|
+
* See {@link buildErrorResponse} for details on the response payload.
|
|
159
|
+
*/
|
|
160
|
+
const conflict = curryBuildErrorResponse(HTTP_CONFLICT);
|
|
161
|
+
/**
|
|
162
|
+
* Creates an error response with the HTTP status code 500.
|
|
163
|
+
* See {@link buildErrorResponse} for details on the response payload.
|
|
164
|
+
*/
|
|
165
|
+
const internalServerError = curryBuildErrorResponse(HTTP_INTERNAL_SERVER_ERROR);
|
|
166
|
+
|
|
167
|
+
//#endregion
|
|
168
|
+
export { HTTP_ACCEPTED, HTTP_BAD_REQUEST, HTTP_CONFLICT, HTTP_CREATED, HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR, HTTP_METHOD_NOT_ALLOWED, HTTP_NON_AUTHORITATIVE_INFORMATION, HTTP_NOT_FOUND, HTTP_NO_CONTENT, HTTP_OK, HTTP_UNAUTHORIZED, accepted, badRequest, buildErrorResponse, buildSuccessResponse, conflict, created, forbidden, internalServerError, methodNotAllowed, noContent, nonAuthoritativeInformation, notFound, ok, unauthorized };
|
|
@@ -27,15 +27,10 @@ type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTION
|
|
|
27
27
|
type HttpMethodLowercase = Lowercase<HttpMethod>;
|
|
28
28
|
/** The type of the runtime action parameters. */
|
|
29
29
|
type RuntimeActionParams = {
|
|
30
|
-
/** If the runtime action is invoked via HTTP, this will be the headers of the request. */
|
|
31
|
-
|
|
32
|
-
/** If the runtime action is invoked via HTTP, this will be the
|
|
33
|
-
|
|
34
|
-
/** If the runtime action is invoked via HTTP, this will be the unmatched path of the request (matching stops after consuming the action extension) */
|
|
35
|
-
__ow_path?: string;
|
|
36
|
-
/** If the runtime action is invoked via HTTP, this will be the request body entity, as a base64-encoded string when its content is binary or JSON object/array, or as a plain string otherwise */
|
|
37
|
-
__ow_body?: string;
|
|
38
|
-
/** If the runtime action is invoked via HTTP, this will be the query parameters of the request, as an unparsed string. */
|
|
30
|
+
/** If the runtime action is invoked via HTTP, this will be the headers of the request. */__ow_headers?: Record<string, string | undefined>; /** If the runtime action is invoked via HTTP, this will be the HTTP method of the request. */
|
|
31
|
+
__ow_method?: HttpMethodLowercase; /** If the runtime action is invoked via HTTP, this will be the unmatched path of the request (matching stops after consuming the action extension) */
|
|
32
|
+
__ow_path?: string; /** If the runtime action is invoked via HTTP, this will be the request body entity, as a base64-encoded string when its content is binary or JSON object/array, or as a plain string otherwise */
|
|
33
|
+
__ow_body?: string; /** If the runtime action is invoked via HTTP, this will be the query parameters of the request, as an unparsed string. */
|
|
39
34
|
__ow_query?: string;
|
|
40
35
|
[key: string]: unknown;
|
|
41
36
|
};
|