@adobe/aio-commerce-lib-auth 0.8.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1,765 @@
1
- const require_chunk=require(`./chunk-YD6SZpHm.cjs`);let _adobe_aio_commerce_lib_core_headers=require(`@adobe/aio-commerce-lib-core/headers`),valibot=require(`valibot`);valibot=require_chunk.n(valibot);let _adobe_aio_commerce_lib_core_error=require(`@adobe/aio-commerce-lib-core/error`),_adobe_aio_lib_ims=require(`@adobe/aio-lib-ims`);_adobe_aio_lib_ims=require_chunk.n(_adobe_aio_lib_ims);let crypto=require(`crypto`);crypto=require_chunk.n(crypto);let oauth_1_0a=require(`oauth-1.0a`);oauth_1_0a=require_chunk.n(oauth_1_0a);let _adobe_aio_commerce_lib_core_params=require(`@adobe/aio-commerce-lib-core/params`);function stringValueSchema(name){return valibot.string(`Expected a string value for '${name}'`)}function parseOrThrow(schema,input,message){let result=valibot.safeParse(schema,input);if(!result.success)throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(message??`Invalid input`,{issues:result.issues});return result.output}const imsAuthParameter=name=>(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the IMS auth parameter ${name}`),(0,valibot.nonEmpty)(`Expected a non-empty string value for the IMS auth parameter ${name}`)),stringArray=(name,minimumLength)=>(0,valibot.pipe)((0,valibot.array)((0,valibot.string)(),`Expected a string array value for the IMS auth parameter ${name}`),(0,valibot.minLength)(minimumLength,`Expected at least ${minimumLength} items for the IMS auth parameter ${name}`)),StringArrayTransformSchema=name=>(0,valibot.pipe)((0,valibot.union)([stringArray(name,1),(0,valibot.pipe)((0,valibot.string)(),(0,valibot.rawTransform)(({dataset:{value:v},addIssue,NEVER})=>{if(v.startsWith(`[`)&&v.endsWith(`]`))try{let parsed=JSON.parse(v);return Array.isArray(parsed)?parsed:(addIssue({received:v,message:`Expected a valid JSON array for the IMS auth parameter ${name}: ${v}`}),NEVER)}catch(error){let errorMessage=error.message;return addIssue({received:v,message:`Expected a valid JSON array for the IMS auth parameter ${name}: ${errorMessage}`}),NEVER}return[v]}))]),stringArray(`value`,1)),ImsAuthEnvSchema=(0,valibot.picklist)([`prod`,`stage`]),ImsAuthParamsSchema=(0,valibot.object)({clientId:imsAuthParameter(`clientId`),clientSecrets:stringArray(`clientSecrets`,1),technicalAccountId:imsAuthParameter(`technicalAccountId`),technicalAccountEmail:(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the IMS auth parameter technicalAccountEmail`),(0,valibot.email)(`Expected a valid email format for technicalAccountEmail`)),imsOrgId:imsAuthParameter(`imsOrgId`),environment:(0,valibot.pipe)((0,valibot.optional)(ImsAuthEnvSchema)),context:(0,valibot.pipe)((0,valibot.optional)((0,valibot.string)())),scopes:stringArray(`scopes`,1)});function __transformStringArray(name,value){if(value===void 0)return;let result=(0,valibot.safeParse)(StringArrayTransformSchema(name),value);if(!result.success)throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid ImsAuthProvider configuration`,{issues:result.issues});return result.output}function __parseImsAuthParams(config){let result=(0,valibot.safeParse)(ImsAuthParamsSchema,config);if(!result.success)throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid ImsAuthProvider configuration`,{issues:result.issues});return result.output}function assertImsAuthParams(config){__parseImsAuthParams(config)}function resolveImsAuthParams(params){return __parseImsAuthParams({clientId:params.AIO_COMMERCE_AUTH_IMS_CLIENT_ID,clientSecrets:__transformStringArray(`AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS`,params.AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS),technicalAccountId:params.AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID,technicalAccountEmail:params.AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL,imsOrgId:params.AIO_COMMERCE_AUTH_IMS_ORG_ID,scopes:__transformStringArray(`AIO_COMMERCE_AUTH_IMS_SCOPES`,params.AIO_COMMERCE_AUTH_IMS_SCOPES),environment:params.AIO_COMMERCE_AUTH_IMS_ENVIRONMENT,context:params.AIO_COMMERCE_AUTH_IMS_CONTEXT})}function buildImsHeaders(accessToken,apiKey){let imsHeaders={Authorization:`Bearer ${accessToken}`};return apiKey&&(imsHeaders[`x-api-key`]=apiKey),imsHeaders}const IMS_AUTH_TOKEN_PARAM=`AIO_COMMERCE_AUTH_IMS_TOKEN`,IMS_AUTH_API_KEY_PARAM=`AIO_COMMERCE_AUTH_IMS_API_KEY`,ImsAuthParamsInputSchema=valibot.looseObject({[IMS_AUTH_TOKEN_PARAM]:stringValueSchema(IMS_AUTH_TOKEN_PARAM),[IMS_AUTH_API_KEY_PARAM]:valibot.optional(stringValueSchema(IMS_AUTH_API_KEY_PARAM))}),ForwardedImsAuthSourceSchema=valibot.variant(`from`,[valibot.object({from:valibot.literal(`headers`),headers:valibot.record(valibot.string(),valibot.optional(valibot.string()))}),valibot.object({from:valibot.literal(`getter`),getHeaders:valibot.custom(input=>typeof input==`function`,`Expected a function for getHeaders`)}),valibot.object({from:valibot.literal(`params`),params:ImsAuthParamsInputSchema})]);function getForwardedImsAuthProvider(source){let validatedSource=parseOrThrow(ForwardedImsAuthSourceSchema,source,`Invalid forwarded IMS auth source`);switch(validatedSource.from){case`headers`:{let{authorization}=(0,_adobe_aio_commerce_lib_core_headers.createHeaderAccessor)(validatedSource.headers,[`Authorization`]),apiKey=(0,_adobe_aio_commerce_lib_core_headers.getHeader)(validatedSource.headers,`x-api-key`),{token}=(0,_adobe_aio_commerce_lib_core_headers.parseBearerToken)(authorization);return{getAccessToken:()=>token,getHeaders:()=>buildImsHeaders(token,apiKey)}}case`getter`:return{getHeaders:validatedSource.getHeaders,getAccessToken:async()=>{let{token}=(0,_adobe_aio_commerce_lib_core_headers.parseBearerToken)((await validatedSource.getHeaders()).Authorization);return token}};case`params`:{let{params}=validatedSource,accessToken=params[IMS_AUTH_TOKEN_PARAM],apiKey=params[IMS_AUTH_API_KEY_PARAM];return{getAccessToken:()=>accessToken,getHeaders:()=>buildImsHeaders(accessToken,apiKey)}}}}function forwardImsAuthProviderFromRequest(params){return getForwardedImsAuthProvider({from:`headers`,headers:(0,_adobe_aio_commerce_lib_core_headers.getHeadersFromParams)(params)})}function forwardImsAuthProviderFromParams(params){return getForwardedImsAuthProvider({from:`params`,params:parseOrThrow(ImsAuthParamsInputSchema,params,`Missing AIO_COMMERCE_AUTH_IMS_TOKEN in params`)})}function forwardImsAuthProvider(params){try{return forwardImsAuthProviderFromParams(params)}catch{}try{return forwardImsAuthProviderFromRequest(params)}catch{}throw Error(`Can't forward IMS authentication from the given params. Make sure your params contain an AIO_COMMERCE_AUTH_IMS_TOKEN input or an Authorization header with an IMS token.`)}const{context,getToken}=_adobe_aio_lib_ims.default;function toImsAuthConfig(config){return{scopes:config.scopes,env:config?.environment??`prod`,context:config.context??`aio-commerce-lib-auth-creds`,client_id:config.clientId,client_secrets:config.clientSecrets,technical_account_id:config.technicalAccountId,technical_account_email:config.technicalAccountEmail,ims_org_id:config.imsOrgId}}function isImsAuthProvider(provider){return typeof provider==`object`&&!!provider&&`getAccessToken`in provider&&`getHeaders`in provider&&typeof provider.getAccessToken==`function`&&typeof provider.getHeaders==`function`}function getImsAuthProvider(authParams){let getAccessToken=async()=>{let imsAuthConfig=toImsAuthConfig(authParams);return await context.set(imsAuthConfig.context,imsAuthConfig),getToken(imsAuthConfig.context,{})};return{getAccessToken,getHeaders:async()=>buildImsHeaders(await getAccessToken(),authParams.clientId)}}const integrationAuthParameter=name=>(0,valibot.pipe)((0,valibot.string)(`Expected a string value for the Commerce Integration parameter ${name}`),(0,valibot.nonEmpty)(`Expected a non-empty string value for the Commerce Integration parameter ${name}`)),BaseUrlSchema=(0,valibot.pipe)((0,valibot.string)(`Expected a string for the Adobe Commerce endpoint`),(0,valibot.nonEmpty)(`Expected a non-empty string for the Adobe Commerce endpoint`),(0,valibot.url)(`Expected a valid url for the Adobe Commerce endpoint`)),UrlSchema=(0,valibot.pipe)((0,valibot.union)([BaseUrlSchema,(0,valibot.instance)(URL)]),(0,valibot.transform)(url=>url instanceof URL?url.toString():url)),IntegrationAuthParamsSchema=(0,valibot.nonOptional)((0,valibot.object)({consumerKey:integrationAuthParameter(`consumerKey`),consumerSecret:integrationAuthParameter(`consumerSecret`),accessToken:integrationAuthParameter(`accessToken`),accessTokenSecret:integrationAuthParameter(`accessTokenSecret`)}));function isIntegrationAuthProvider(provider){return typeof provider==`object`&&!!provider&&`getHeaders`in provider&&typeof provider.getHeaders==`function`}function getIntegrationAuthProvider(authParams){let oauth=new oauth_1_0a.default({consumer:{key:authParams.consumerKey,secret:authParams.consumerSecret},signature_method:`HMAC-SHA256`,hash_function:(baseString,key)=>crypto.default.createHmac(`sha256`,key).update(baseString).digest(`base64`)}),oauthToken={key:authParams.accessToken,secret:authParams.accessTokenSecret};return{getHeaders:(method,url)=>{let urlString=(0,valibot.parse)(UrlSchema,url);return oauth.toHeader(oauth.authorize({url:urlString,method},oauthToken))}}}function __parseIntegrationAuthParams(config){let result=(0,valibot.safeParse)(IntegrationAuthParamsSchema,config);if(!result.success)throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid IntegrationAuthProvider configuration`,{issues:result.issues});return result.output}function assertIntegrationAuthParams(config){__parseIntegrationAuthParams(config)}function resolveIntegrationAuthParams(params){return __parseIntegrationAuthParams({consumerKey:params.AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_KEY,consumerSecret:params.AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_SECRET,accessToken:params.AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN,accessTokenSecret:params.AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN_SECRET})}const IMS_AUTH_PARAMS=[`AIO_COMMERCE_AUTH_IMS_CLIENT_ID`,`AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS`,`AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID`,`AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL`,`AIO_COMMERCE_AUTH_IMS_ORG_ID`,`AIO_COMMERCE_AUTH_IMS_SCOPES`],INTEGRATION_AUTH_PARAMS=[`AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_KEY`,`AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_SECRET`,`AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN`,`AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN_SECRET`];function resolveAuthParams(params){if((0,_adobe_aio_commerce_lib_core_params.allNonEmpty)(params,IMS_AUTH_PARAMS))return{...resolveImsAuthParams(params),strategy:`ims`};if((0,_adobe_aio_commerce_lib_core_params.allNonEmpty)(params,INTEGRATION_AUTH_PARAMS))return{...resolveIntegrationAuthParams(params),strategy:`integration`};throw Error(`Can't resolve authentication options for the given params. Please provide either IMS options (${IMS_AUTH_PARAMS.join(`, `)}) or Commerce integration options (${INTEGRATION_AUTH_PARAMS.join(`, `)}).`)}exports.assertImsAuthParams=assertImsAuthParams,exports.assertIntegrationAuthParams=assertIntegrationAuthParams,exports.forwardImsAuthProvider=forwardImsAuthProvider,exports.getForwardedImsAuthProvider=getForwardedImsAuthProvider,exports.getImsAuthProvider=getImsAuthProvider,exports.getIntegrationAuthProvider=getIntegrationAuthProvider,exports.isImsAuthProvider=isImsAuthProvider,exports.isIntegrationAuthProvider=isIntegrationAuthProvider,exports.resolveAuthParams=resolveAuthParams;
1
+ /**
2
+ * @license
3
+ *
4
+ * Copyright 2026 Adobe. All rights reserved.
5
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License. You may obtain a copy
7
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software distributed under
10
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
11
+ * OF ANY KIND, either express or implied. See the License for the specific language
12
+ * governing permissions and limitations under the License.
13
+ */
14
+
15
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
16
+ const require_chunk = require('./chunk-DS2yp5vX.cjs');
17
+ let _adobe_aio_commerce_lib_core_headers = require("@adobe/aio-commerce-lib-core/headers");
18
+ let valibot = require("valibot");
19
+ valibot = require_chunk.__toESM(valibot);
20
+ let _adobe_aio_commerce_lib_core_error = require("@adobe/aio-commerce-lib-core/error");
21
+ let _adobe_aio_lib_ims = require("@adobe/aio-lib-ims");
22
+ _adobe_aio_lib_ims = require_chunk.__toESM(_adobe_aio_lib_ims);
23
+ let crypto = require("crypto");
24
+ crypto = require_chunk.__toESM(crypto);
25
+ let oauth_1_0a = require("oauth-1.0a");
26
+ oauth_1_0a = require_chunk.__toESM(oauth_1_0a);
27
+ let _adobe_aio_commerce_lib_core_params = require("@adobe/aio-commerce-lib-core/params");
28
+
29
+ //#region ../../packages-private/common-utils/source/valibot/schemas.ts
30
+ /**
31
+ * A schema for a string value.
32
+ * @param name The name of the field this schema refers to.
33
+ */
34
+ function stringValueSchema(name) {
35
+ return valibot.string(`Expected a string value for '${name}'`);
36
+ }
37
+
38
+ //#endregion
39
+ //#region ../../packages-private/common-utils/source/valibot/utils.ts
40
+ /**
41
+ * Parses the input using the provided schema and throws a {@link CommerceSdkValidationError} error if the input is invalid.
42
+ * @param schema - The schema to use for parsing.
43
+ * @param input - The input to parse.
44
+ * @param message - Optional custom error message for the validation error.
45
+ */
46
+ function parseOrThrow(schema, input, message) {
47
+ const result = valibot.safeParse(schema, input);
48
+ if (!result.success) throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(message ?? "Invalid input", { issues: result.issues });
49
+ return result.output;
50
+ }
51
+
52
+ //#endregion
53
+ //#region source/lib/ims-auth/schema.ts
54
+ /**
55
+ * Creates a validation schema for a required IMS auth string parameter.
56
+ * @param name The name of the parameter for error messages.
57
+ * @returns A validation pipeline that ensures the parameter is a non-empty string.
58
+ */
59
+ const imsAuthParameter = (name) => (0, valibot.pipe)((0, valibot.string)(`Expected a string value for the IMS auth parameter ${name}`), (0, valibot.nonEmpty)(`Expected a non-empty string value for the IMS auth parameter ${name}`));
60
+ /**
61
+ * Creates a validation schema for an IMS auth string array parameter.
62
+ * @param name The name of the parameter for error messages.
63
+ * @param minimumLength The minimum length of the array.
64
+ * @returns A validation pipeline that ensures the parameter is an array of strings.
65
+ */
66
+ const stringArray = (name, minimumLength) => {
67
+ return (0, valibot.pipe)((0, valibot.array)((0, valibot.string)(), `Expected a string array value for the IMS auth parameter ${name}`), (0, valibot.minLength)(minimumLength, `Expected at least ${minimumLength} items for the IMS auth parameter ${name}`));
68
+ };
69
+ /**
70
+ * Schema for transforming a value that may be a JSON string array or a single string into an array.
71
+ * This schema handles the transformation of App Builder action inputs that may come as JSON strings.
72
+ */
73
+ const StringArrayTransformSchema = (name) => (0, valibot.pipe)((0, valibot.union)([stringArray(name, 1), (0, valibot.pipe)((0, valibot.string)(), (0, valibot.rawTransform)(({ dataset: { value: v }, addIssue, NEVER }) => {
74
+ if (v.startsWith("[") && v.endsWith("]")) try {
75
+ const parsed = JSON.parse(v);
76
+ if (!Array.isArray(parsed)) {
77
+ addIssue({
78
+ received: v,
79
+ message: `Expected a valid JSON array for the IMS auth parameter ${name}: ${v}`
80
+ });
81
+ return NEVER;
82
+ }
83
+ return parsed;
84
+ } catch (error) {
85
+ const errorMessage = error.message;
86
+ addIssue({
87
+ received: v,
88
+ message: `Expected a valid JSON array for the IMS auth parameter ${name}: ${errorMessage}`
89
+ });
90
+ return NEVER;
91
+ }
92
+ return [v];
93
+ }))]), stringArray("value", 1));
94
+ /** Validation schema for IMS auth environment values. */
95
+ const ImsAuthEnvSchema = (0, valibot.picklist)(["prod", "stage"]);
96
+ /** Defines the schema to validate the necessary parameters for the IMS auth service. */
97
+ const ImsAuthParamsSchema = (0, valibot.object)({
98
+ clientId: imsAuthParameter("clientId"),
99
+ clientSecrets: stringArray("clientSecrets", 1),
100
+ technicalAccountId: imsAuthParameter("technicalAccountId"),
101
+ technicalAccountEmail: (0, valibot.pipe)((0, valibot.string)("Expected a string value for the IMS auth parameter technicalAccountEmail"), (0, valibot.email)("Expected a valid email format for technicalAccountEmail")),
102
+ imsOrgId: imsAuthParameter("imsOrgId"),
103
+ environment: (0, valibot.pipe)((0, valibot.optional)(ImsAuthEnvSchema)),
104
+ context: (0, valibot.pipe)((0, valibot.optional)((0, valibot.string)())),
105
+ scopes: stringArray("scopes", 1)
106
+ });
107
+
108
+ //#endregion
109
+ //#region source/lib/ims-auth/utils.ts
110
+ /**
111
+ * Transforms a value using the string array transformation schema.
112
+ * @param value - The value to transform (may be a JSON string, single string, or array).
113
+ * @throws {CommerceSdkValidationError} If the transformation fails.
114
+ *
115
+ * @internal
116
+ */
117
+ function __transformStringArray(name, value) {
118
+ if (value === void 0) return;
119
+ const result = (0, valibot.safeParse)(StringArrayTransformSchema(name), value);
120
+ if (!result.success) throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError("Invalid ImsAuthProvider configuration", { issues: result.issues });
121
+ return result.output;
122
+ }
123
+ /**
124
+ * Parses the provided configuration for an {@link ImsAuthProvider}.
125
+ * @param config - The configuration to parse.
126
+ * @throws {CommerceSdkValidationError} If the configuration is invalid.
127
+ *
128
+ * @internal
129
+ */
130
+ function __parseImsAuthParams(config) {
131
+ const result = (0, valibot.safeParse)(ImsAuthParamsSchema, config);
132
+ if (!result.success) throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError("Invalid ImsAuthProvider configuration", { issues: result.issues });
133
+ return result.output;
134
+ }
135
+ /**
136
+ * Asserts the provided configuration for an {@link ImsAuthProvider}.
137
+ * @param config The configuration to validate.
138
+ * @throws {CommerceSdkValidationError} If the configuration is invalid.
139
+ * @example
140
+ * ```typescript
141
+ * const config = {
142
+ * clientId: "your-client-id",
143
+ * clientSecrets: ["your-client-secret"],
144
+ * technicalAccountId: "your-technical-account-id",
145
+ * technicalAccountEmail: "your-account@example.com",
146
+ * imsOrgId: "your-ims-org-id@AdobeOrg",
147
+ * scopes: ["AdobeID", "openid"],
148
+ * environment: "prod", // or "stage"
149
+ * context: "my-app-context"
150
+ * };
151
+ *
152
+ * // This will validate the config and throw if invalid
153
+ * assertImsAuthParams(config);
154
+ *```
155
+ * @example
156
+ * ```typescript
157
+ * // Example of a failing assert:
158
+ * try {
159
+ * assertImsAuthParams({
160
+ * clientId: "valid-client-id",
161
+ * // Missing required fields like clientSecrets, technicalAccountId, etc.
162
+ * });
163
+ * } catch (error) {
164
+ * console.error(error.message); // "Invalid ImsAuthProvider configuration"
165
+ * console.error(error.issues); // Array of validation issues
166
+ * }
167
+ * ```
168
+ */
169
+ function assertImsAuthParams(config) {
170
+ __parseImsAuthParams(config);
171
+ }
172
+ /**
173
+ * Resolves an {@link ImsAuthParams} from the given App Builder action inputs.
174
+ * @param params The App Builder action inputs to resolve the IMS authentication parameters from.
175
+ * @throws {CommerceSdkValidationError} If the parameters are invalid and cannot be resolved.
176
+ *
177
+ * @example
178
+ * ```typescript
179
+ * // Some App Builder runtime action that needs IMS authentication
180
+ * export function main(params) {
181
+ * const imsAuthProvider = getImsAuthProvider(resolveImsAuthParams(params));
182
+ *
183
+ * // Get headers for API requests
184
+ * const headers = await authProvider.getHeaders();
185
+ * const response = await fetch('https://api.adobe.io/some-endpoint', {
186
+ * headers: await authProvider.getHeaders()
187
+ * });
188
+ * }
189
+ * ```
190
+ */
191
+ function resolveImsAuthParams(params) {
192
+ return __parseImsAuthParams({
193
+ clientId: params.AIO_COMMERCE_AUTH_IMS_CLIENT_ID,
194
+ clientSecrets: __transformStringArray("AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS", params.AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS),
195
+ technicalAccountId: params.AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID,
196
+ technicalAccountEmail: params.AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL,
197
+ imsOrgId: params.AIO_COMMERCE_AUTH_IMS_ORG_ID,
198
+ scopes: __transformStringArray("AIO_COMMERCE_AUTH_IMS_SCOPES", params.AIO_COMMERCE_AUTH_IMS_SCOPES),
199
+ environment: params.AIO_COMMERCE_AUTH_IMS_ENVIRONMENT,
200
+ context: params.AIO_COMMERCE_AUTH_IMS_CONTEXT
201
+ });
202
+ }
203
+ /**
204
+ * Shorthand to build IMS authentication headers.
205
+ * @param accessToken - The token to use in the Authorization header.
206
+ * @param apiKey - The API key to include in the x-api-key header (optional).
207
+ */
208
+ function buildImsHeaders(accessToken, apiKey) {
209
+ const imsHeaders = { Authorization: `Bearer ${accessToken}` };
210
+ if (apiKey) imsHeaders["x-api-key"] = apiKey;
211
+ return imsHeaders;
212
+ }
213
+
214
+ //#endregion
215
+ //#region source/lib/ims-auth/forwarding.ts
216
+ const IMS_AUTH_TOKEN_PARAM = "AIO_COMMERCE_AUTH_IMS_TOKEN";
217
+ const IMS_AUTH_API_KEY_PARAM = "AIO_COMMERCE_AUTH_IMS_API_KEY";
218
+ const ImsAuthParamsInputSchema = valibot.looseObject({
219
+ [IMS_AUTH_TOKEN_PARAM]: stringValueSchema(IMS_AUTH_TOKEN_PARAM),
220
+ [IMS_AUTH_API_KEY_PARAM]: valibot.optional(stringValueSchema(IMS_AUTH_API_KEY_PARAM))
221
+ });
222
+ const ForwardedImsAuthSourceSchema = valibot.variant("from", [
223
+ valibot.object({
224
+ from: valibot.literal("headers"),
225
+ headers: valibot.record(valibot.string(), valibot.optional(valibot.string()))
226
+ }),
227
+ valibot.object({
228
+ from: valibot.literal("getter"),
229
+ getHeaders: valibot.custom((input) => typeof input === "function", "Expected a function for getHeaders")
230
+ }),
231
+ valibot.object({
232
+ from: valibot.literal("params"),
233
+ params: ImsAuthParamsInputSchema
234
+ })
235
+ ]);
236
+ /**
237
+ * Creates an {@link ImsAuthProvider} by forwarding authentication credentials from various sources.
238
+ *
239
+ * @param source The source of the credentials to forward, as a {@link ForwardedImsAuthSource}.
240
+ * @returns An {@link ImsAuthProvider} instance that returns the forwarded access token and headers.
241
+ *
242
+ * @throws {CommerceSdkValidationError} If the source object is invalid.
243
+ * @throws {CommerceSdkValidationError} If `from: "headers"` is used and the `Authorization` header is missing.
244
+ * @throws {CommerceSdkValidationError} If `from: "headers"` is used and the `Authorization` header is not in Bearer token format.
245
+ * @throws {CommerceSdkValidationError} If `from: "params"` is used and `AIO_COMMERCE_AUTH_IMS_TOKEN` is missing or empty.
246
+ *
247
+ * @example
248
+ * ```typescript
249
+ * import { getForwardedImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
250
+ *
251
+ * // From raw headers (e.g. from an HTTP request).
252
+ * const provider1 = getForwardedImsAuthProvider({
253
+ * from: "headers",
254
+ * headers: params.__ow_headers,
255
+ * });
256
+ *
257
+ * // From async getter (e.g. fetch from secret manager)
258
+ * const provider2 = getForwardedImsAuthProvider({
259
+ * from: "getter",
260
+ * getHeaders: async () => {
261
+ * const token = await secretManager.getSecret("ims-token");
262
+ * return { Authorization: `Bearer ${token}` };
263
+ * },
264
+ * });
265
+ *
266
+ * // From a params object (using AIO_COMMERCE_AUTH_IMS_TOKEN and AIO_COMMERCE_AUTH_IMS_API_KEY keys)
267
+ * const provider3 = getForwardedImsAuthProvider({
268
+ * from: "params",
269
+ * params: actionParams,
270
+ * });
271
+ *
272
+ * // Use the provider
273
+ * const token = await provider1.getAccessToken();
274
+ * const headers = await provider1.getHeaders();
275
+ * ```
276
+ */
277
+ function getForwardedImsAuthProvider(source) {
278
+ const validatedSource = parseOrThrow(ForwardedImsAuthSourceSchema, source, "Invalid forwarded IMS auth source");
279
+ switch (validatedSource.from) {
280
+ case "headers": {
281
+ const { authorization } = (0, _adobe_aio_commerce_lib_core_headers.createHeaderAccessor)(validatedSource.headers, ["Authorization"]);
282
+ const apiKey = (0, _adobe_aio_commerce_lib_core_headers.getHeader)(validatedSource.headers, "x-api-key");
283
+ const { token } = (0, _adobe_aio_commerce_lib_core_headers.parseBearerToken)(authorization);
284
+ return {
285
+ getAccessToken: () => token,
286
+ getHeaders: () => buildImsHeaders(token, apiKey)
287
+ };
288
+ }
289
+ case "getter": return {
290
+ getHeaders: validatedSource.getHeaders,
291
+ getAccessToken: async () => {
292
+ const { token } = (0, _adobe_aio_commerce_lib_core_headers.parseBearerToken)((await validatedSource.getHeaders()).Authorization);
293
+ return token;
294
+ }
295
+ };
296
+ case "params": {
297
+ const { params } = validatedSource;
298
+ const accessToken = params[IMS_AUTH_TOKEN_PARAM];
299
+ const apiKey = params[IMS_AUTH_API_KEY_PARAM];
300
+ return {
301
+ getAccessToken: () => accessToken,
302
+ getHeaders: () => buildImsHeaders(accessToken, apiKey)
303
+ };
304
+ }
305
+ }
306
+ }
307
+ /**
308
+ * Creates an {@link ImsAuthProvider} by forwarding authentication credentials from incoming
309
+ * runtime action request headers.
310
+ *
311
+ * This is a convenience wrapper around {@link getForwardedImsAuthProvider} for the common case
312
+ * of forwarding credentials from Adobe I/O Runtime action parameters.
313
+ *
314
+ * @param params The runtime action parameters containing the `__ow_headers` object with authentication headers.
315
+ * @returns An {@link ImsAuthProvider} instance that returns the forwarded access token and headers.
316
+ *
317
+ * @throws {Error} If the `Authorization` header is missing from the request headers.
318
+ * @throws {Error} If the `Authorization` header is not in the correct Bearer token format.
319
+ *
320
+ * @example
321
+ * ```typescript
322
+ * import { forwardImsAuthProviderFromRequest } from "@adobe/aio-commerce-lib-auth";
323
+ *
324
+ * // In an Adobe I/O Runtime action
325
+ * async function main(params) {
326
+ * // params.__ow_headers contains: { Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..."}
327
+ *
328
+ * // Forward the authentication from the incoming request
329
+ * const authProvider = forwardImsAuthProviderFromRequest(params);
330
+ *
331
+ * // Get the forwarded access token
332
+ * const token = await authProvider.getAccessToken();
333
+ * console.log(token); // "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..."
334
+ *
335
+ * // Get headers for downstream API requests
336
+ * const headers = await authProvider.getHeaders();
337
+ * console.log(headers);
338
+ * // {
339
+ * // Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
340
+ * // "x-api-key": "client-id-from-request" // Only if present in original request
341
+ * // }
342
+ *
343
+ * // Use the forwarded credentials in downstream API calls
344
+ * const response = await fetch('...', {
345
+ * headers: await authProvider.getHeaders()
346
+ * });
347
+ *
348
+ * return { statusCode: 200, body: await response.json() };
349
+ * }
350
+ * ```
351
+ */
352
+ function forwardImsAuthProviderFromRequest(params) {
353
+ return getForwardedImsAuthProvider({
354
+ from: "headers",
355
+ headers: (0, _adobe_aio_commerce_lib_core_headers.getHeadersFromParams)(params)
356
+ });
357
+ }
358
+ /**
359
+ * Creates an {@link ImsAuthProvider} by forwarding authentication credentials from a params object.
360
+ *
361
+ * This is a convenience wrapper around {@link getForwardedImsAuthProvider} for the common case
362
+ * of forwarding credentials from runtime action parameters. It reads:
363
+ * - `AIO_COMMERCE_AUTH_IMS_TOKEN` for the access token (required)
364
+ * - `AIO_COMMERCE_AUTH_IMS_API_KEY` for the API key (optional)
365
+ *
366
+ * @param params The params object containing the authentication credentials.
367
+ * @returns An {@link ImsAuthProvider} instance that returns the access token and headers from the params.
368
+ *
369
+ * @throws {CommerceSdkValidationError} If `AIO_COMMERCE_AUTH_IMS_TOKEN` is not set or is empty.
370
+ *
371
+ * @example
372
+ * ```typescript
373
+ * import { forwardImsAuthProviderFromParams } from "@adobe/aio-commerce-lib-auth";
374
+ *
375
+ * // In an Adobe I/O Runtime action
376
+ * async function main(params) {
377
+ * // params contains: { AIO_COMMERCE_AUTH_IMS_TOKEN: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..." }
378
+ * const authProvider = forwardImsAuthProviderFromParams(params);
379
+ *
380
+ * // Get the access token
381
+ * const token = await authProvider.getAccessToken();
382
+ *
383
+ * // Get headers for downstream API requests
384
+ * const headers = await authProvider.getHeaders();
385
+ * // {
386
+ * // Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
387
+ * // "x-api-key": "my-api-key" // Only if AIO_COMMERCE_AUTH_IMS_API_KEY is set
388
+ * // }
389
+ * }
390
+ * ```
391
+ */
392
+ function forwardImsAuthProviderFromParams(params) {
393
+ return getForwardedImsAuthProvider({
394
+ from: "params",
395
+ params: parseOrThrow(ImsAuthParamsInputSchema, params, "Missing AIO_COMMERCE_AUTH_IMS_TOKEN in params")
396
+ });
397
+ }
398
+ /**
399
+ * Creates an {@link ImsAuthProvider} by forwarding authentication credentials from runtime action parameters.
400
+ *
401
+ * This function automatically detects the source of credentials by trying multiple strategies in order:
402
+ * 1. **Params token** - Looks for `AIO_COMMERCE_AUTH_IMS_TOKEN` (and optionally `AIO_COMMERCE_AUTH_IMS_API_KEY`) in the params object
403
+ * 2. **HTTP headers** - Falls back to extracting the `Authorization` header from `__ow_headers`
404
+ *
405
+ * Use this function when building actions that receive authenticated requests and need to forward
406
+ * those credentials to downstream services (proxy pattern).
407
+ *
408
+ * @param params The runtime action parameters object. Can contain either:
409
+ * - `AIO_COMMERCE_AUTH_IMS_TOKEN` and optionally `AIO_COMMERCE_AUTH_IMS_API_KEY` for direct token forwarding
410
+ * - `__ow_headers` with an `Authorization` header for HTTP request forwarding
411
+ * @returns An {@link ImsAuthProvider} instance that returns the forwarded access token and headers.
412
+ *
413
+ * @throws {Error} If neither a valid token param nor Authorization header is found.
414
+ *
415
+ * @example
416
+ * ```typescript
417
+ * import { forwardImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
418
+ *
419
+ * export async function main(params: Record<string, unknown>) {
420
+ * // Automatically detects credentials from params or headers
421
+ * const authProvider = forwardImsAuthProvider(params);
422
+ *
423
+ * // Get the access token
424
+ * const token = await authProvider.getAccessToken();
425
+ *
426
+ * // Get headers for downstream API requests
427
+ * const headers = await authProvider.getHeaders();
428
+ * // {
429
+ * // Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
430
+ * // "x-api-key": "my-api-key" // Only if available
431
+ * // }
432
+ *
433
+ * // Use the forwarded credentials in downstream API calls
434
+ * const response = await fetch("https://api.adobe.io/some-endpoint", {
435
+ * headers,
436
+ * });
437
+ *
438
+ * return { statusCode: 200, body: await response.json() };
439
+ * }
440
+ * ```
441
+ */
442
+ function forwardImsAuthProvider(params) {
443
+ try {
444
+ return forwardImsAuthProviderFromParams(params);
445
+ } catch {}
446
+ try {
447
+ return forwardImsAuthProviderFromRequest(params);
448
+ } catch {}
449
+ throw new Error("Can't forward IMS authentication from the given params. Make sure your params contain an AIO_COMMERCE_AUTH_IMS_TOKEN input or an Authorization header with an IMS token.");
450
+ }
451
+
452
+ //#endregion
453
+ //#region source/lib/ims-auth/provider.ts
454
+ const { context, getToken } = _adobe_aio_lib_ims.default;
455
+ /**
456
+ * Converts IMS auth configuration properties to snake_case format.
457
+ * @param config The IMS auth configuration with camelCase properties.
458
+ * @returns The configuration with snake_case properties.
459
+ */
460
+ function toImsAuthConfig(config) {
461
+ return {
462
+ scopes: config.scopes,
463
+ env: config?.environment ?? "prod",
464
+ context: config.context ?? "aio-commerce-lib-auth-creds",
465
+ client_id: config.clientId,
466
+ client_secrets: config.clientSecrets,
467
+ technical_account_id: config.technicalAccountId,
468
+ technical_account_email: config.technicalAccountEmail,
469
+ ims_org_id: config.imsOrgId
470
+ };
471
+ }
472
+ /**
473
+ * Type guard to check if a value is an ImsAuthProvider instance.
474
+ *
475
+ * @param provider The value to check.
476
+ * @returns `true` if the value is an ImsAuthProvider, `false` otherwise.
477
+ *
478
+ * @example
479
+ * ```typescript
480
+ * import { getImsAuthProvider, isImsAuthProvider } from "@adobe/aio-commerce-lib-auth";
481
+ *
482
+ * // Imagine you have an object that it's not strictly typed as ImsAuthProvider.
483
+ * const provider = getImsAuthProvider({ ... }) as unknown;
484
+ *
485
+ * if (isImsAuthProvider(provider)) {
486
+ * // TypeScript knows provider is ImsAuthProvider
487
+ * const token = await provider.getAccessToken();
488
+ * }
489
+ * ```
490
+ */
491
+ function isImsAuthProvider(provider) {
492
+ return typeof provider === "object" && provider !== null && "getAccessToken" in provider && "getHeaders" in provider && typeof provider.getAccessToken === "function" && typeof provider.getHeaders === "function";
493
+ }
494
+ /**
495
+ * Creates an {@link ImsAuthProvider} based on the provided configuration.
496
+ * @param authParams An {@link ImsAuthParams} parameter that contains the configuration for the {@link ImsAuthProvider}.
497
+ * @returns An {@link ImsAuthProvider} instance that can be used to get access token and auth headers.
498
+ * @example
499
+ * ```typescript
500
+ * const config = {
501
+ * clientId: "your-client-id",
502
+ * clientSecrets: ["your-client-secret"],
503
+ * technicalAccountId: "your-technical-account-id",
504
+ * technicalAccountEmail: "your-account@example.com",
505
+ * imsOrgId: "your-ims-org-id@AdobeOrg",
506
+ * scopes: ["AdobeID", "openid"],
507
+ * environment: "prod",
508
+ * context: "my-app-context"
509
+ * };
510
+ *
511
+ * const authProvider = getImsAuthProvider(config);
512
+ *
513
+ * // Get access token
514
+ * const token = await authProvider.getAccessToken();
515
+ * console.log(token); // "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9..."
516
+ *
517
+ * // Get headers for API requests
518
+ * const headers = await authProvider.getHeaders();
519
+ * console.log(headers);
520
+ * // {
521
+ * // Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
522
+ * // "x-api-key": "your-client-id"
523
+ * // }
524
+ *
525
+ * // Use headers in API calls
526
+ * const response = await fetch('https://api.adobe.io/some-endpoint', {
527
+ * headers: await authProvider.getHeaders()
528
+ * });
529
+ * ```
530
+ */
531
+ function getImsAuthProvider(authParams) {
532
+ const getAccessToken = async () => {
533
+ const imsAuthConfig = toImsAuthConfig(authParams);
534
+ await context.set(imsAuthConfig.context, imsAuthConfig);
535
+ return getToken(imsAuthConfig.context, {});
536
+ };
537
+ const getHeaders = async () => {
538
+ return buildImsHeaders(await getAccessToken(), authParams.clientId);
539
+ };
540
+ return {
541
+ getAccessToken,
542
+ getHeaders
543
+ };
544
+ }
545
+
546
+ //#endregion
547
+ //#region source/lib/integration-auth/schema.ts
548
+ /**
549
+ * Creates a validation schema for a required Commerce Integration string parameter.
550
+ * @param name The name of the parameter for error messages.
551
+ * @returns A validation pipeline that ensures the parameter is a non-empty string.
552
+ */
553
+ const integrationAuthParameter = (name) => (0, valibot.pipe)((0, valibot.string)(`Expected a string value for the Commerce Integration parameter ${name}`), (0, valibot.nonEmpty)(`Expected a non-empty string value for the Commerce Integration parameter ${name}`));
554
+ /** Validation schema for the Adobe Commerce endpoint base URL. */
555
+ const BaseUrlSchema = (0, valibot.pipe)((0, valibot.string)("Expected a string for the Adobe Commerce endpoint"), (0, valibot.nonEmpty)("Expected a non-empty string for the Adobe Commerce endpoint"), (0, valibot.url)("Expected a valid url for the Adobe Commerce endpoint"));
556
+ /** Validation schema that accepts either a URL string or URL instance and normalizes to string. */
557
+ const UrlSchema = (0, valibot.pipe)((0, valibot.union)([BaseUrlSchema, (0, valibot.instance)(URL)]), (0, valibot.transform)((url) => {
558
+ if (url instanceof URL) return url.toString();
559
+ return url;
560
+ }));
561
+ /**
562
+ * The schema for the Commerce Integration parameters.
563
+ * This is used to validate the parameters passed to the Commerce Integration provider.
564
+ */
565
+ const IntegrationAuthParamsSchema = (0, valibot.nonOptional)((0, valibot.object)({
566
+ consumerKey: integrationAuthParameter("consumerKey"),
567
+ consumerSecret: integrationAuthParameter("consumerSecret"),
568
+ accessToken: integrationAuthParameter("accessToken"),
569
+ accessTokenSecret: integrationAuthParameter("accessTokenSecret")
570
+ }));
571
+
572
+ //#endregion
573
+ //#region source/lib/integration-auth/provider.ts
574
+ /**
575
+ * Type guard to check if a value is an IntegrationAuthProvider instance.
576
+ *
577
+ * @param provider The value to check.
578
+ * @returns `true` if the value is an IntegrationAuthProvider, `false` otherwise.
579
+ *
580
+ * @example
581
+ * ```typescript
582
+ * import { getIntegrationAuthProvider, isIntegrationAuthProvider } from "@adobe/aio-commerce-lib-auth";
583
+ *
584
+ * // Imagine you have an object that it's not strictly typed as IntegrationAuthProvider.
585
+ * const provider = getIntegrationAuthProvider({ ... }) as unknown;
586
+ *
587
+ * if (isIntegrationAuthProvider(provider)) {
588
+ * // TypeScript knows provider is IntegrationAuthProvider
589
+ * const headers = provider.getHeaders("GET", "https://api.example.com");
590
+ * }
591
+ * ```
592
+ */
593
+ function isIntegrationAuthProvider(provider) {
594
+ return typeof provider === "object" && provider !== null && "getHeaders" in provider && typeof provider.getHeaders === "function";
595
+ }
596
+ /**
597
+ * Creates an {@link IntegrationAuthProvider} based on the provided configuration.
598
+ * @param authParams The configuration for the integration.
599
+ * @returns An {@link IntegrationAuthProvider} instance that can be used to get auth headers.
600
+ * @example
601
+ * ```typescript
602
+ * const config = {
603
+ * consumerKey: "your-consumer-key",
604
+ * consumerSecret: "your-consumer-secret",
605
+ * accessToken: "your-access-token",
606
+ * accessTokenSecret: "your-access-token-secret"
607
+ * };
608
+ *
609
+ * const authProvider = getIntegrationAuthProvider(config);
610
+ *
611
+ * // Get OAuth headers for a REST API call
612
+ * const headers = authProvider.getHeaders("GET", "https://your-store.com/rest/V1/products");
613
+ * console.log(headers); // { Authorization: "OAuth oauth_consumer_key=..., oauth_signature=..." }
614
+ *
615
+ * // Can also be used with URL objects
616
+ * const url = new URL("https://your-store.com/rest/V1/customers");
617
+ * const postHeaders = authProvider.getHeaders("POST", url);
618
+ * ```
619
+ */
620
+ function getIntegrationAuthProvider(authParams) {
621
+ const oauth = new oauth_1_0a.default({
622
+ consumer: {
623
+ key: authParams.consumerKey,
624
+ secret: authParams.consumerSecret
625
+ },
626
+ signature_method: "HMAC-SHA256",
627
+ hash_function: (baseString, key) => crypto.default.createHmac("sha256", key).update(baseString).digest("base64")
628
+ });
629
+ const oauthToken = {
630
+ key: authParams.accessToken,
631
+ secret: authParams.accessTokenSecret
632
+ };
633
+ return { getHeaders: (method, url) => {
634
+ const urlString = (0, valibot.parse)(UrlSchema, url);
635
+ return oauth.toHeader(oauth.authorize({
636
+ url: urlString,
637
+ method
638
+ }, oauthToken));
639
+ } };
640
+ }
641
+
642
+ //#endregion
643
+ //#region source/lib/integration-auth/utils.ts
644
+ /**
645
+ * Parses the provided configuration for an {@link IntegrationAuthProvider}.
646
+ * @param config - The configuration to parse.
647
+ * @throws {CommerceSdkValidationError} If the configuration is invalid.
648
+ *
649
+ * @internal
650
+ */
651
+ function __parseIntegrationAuthParams(config) {
652
+ const result = (0, valibot.safeParse)(IntegrationAuthParamsSchema, config);
653
+ if (!result.success) throw new _adobe_aio_commerce_lib_core_error.CommerceSdkValidationError("Invalid IntegrationAuthProvider configuration", { issues: result.issues });
654
+ return result.output;
655
+ }
656
+ /**
657
+ * Asserts the provided configuration for an Adobe Commerce {@link IntegrationAuthProvider}.
658
+ * @param config The configuration to validate.
659
+ * @throws {CommerceSdkValidationError} If the configuration is invalid.
660
+ * @example
661
+ * ```typescript
662
+ * const config = {
663
+ * consumerKey: "your-consumer-key",
664
+ * consumerSecret: "your-consumer-secret",
665
+ * accessToken: "your-access-token",
666
+ * accessTokenSecret: "your-access-token-secret"
667
+ * };
668
+ *
669
+ * // This will validate the config and throw if invalid
670
+ * assertIntegrationAuthParams(config);
671
+ * ```
672
+ * @example
673
+ * ```typescript
674
+ * // Example of a failing assert:
675
+ * try {
676
+ * assertIntegrationAuthParams({
677
+ * consumerKey: "valid-consumer-key",
678
+ * // Missing required fields like consumerSecret, accessToken, accessTokenSecret
679
+ * });
680
+ * } catch (error) {
681
+ * console.error(error.message); // "Invalid IntegrationAuthProvider configuration"
682
+ * console.error(error.issues); // Array of validation issues
683
+ * }
684
+ * ```
685
+ */
686
+ function assertIntegrationAuthParams(config) {
687
+ __parseIntegrationAuthParams(config);
688
+ }
689
+ /**
690
+ * Resolves an {@link IntegrationAuthParams} from the given App Builder action inputs.
691
+ * @param params The App Builder action inputs to resolve the Integration authentication parameters from.
692
+ * @throws {CommerceSdkValidationError} If the parameters are invalid and cannot be resolved.
693
+ *
694
+ * @example
695
+ * ```typescript
696
+ * export function main(params) {
697
+ * const resolvedParams = resolveIntegrationAuthParams(params);
698
+ * console.log(resolvedParams); // { consumerKey: "your-consumer-key", consumerSecret: "your-consumer-secret", accessToken: "your-access-token", accessTokenSecret: "your-access-token-secret" }
699
+ * }
700
+ * ```
701
+ */
702
+ function resolveIntegrationAuthParams(params) {
703
+ return __parseIntegrationAuthParams({
704
+ consumerKey: params.AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_KEY,
705
+ consumerSecret: params.AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_SECRET,
706
+ accessToken: params.AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN,
707
+ accessTokenSecret: params.AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN_SECRET
708
+ });
709
+ }
710
+
711
+ //#endregion
712
+ //#region source/lib/utils.ts
713
+ const IMS_AUTH_PARAMS = [
714
+ "AIO_COMMERCE_AUTH_IMS_CLIENT_ID",
715
+ "AIO_COMMERCE_AUTH_IMS_CLIENT_SECRETS",
716
+ "AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_ID",
717
+ "AIO_COMMERCE_AUTH_IMS_TECHNICAL_ACCOUNT_EMAIL",
718
+ "AIO_COMMERCE_AUTH_IMS_ORG_ID",
719
+ "AIO_COMMERCE_AUTH_IMS_SCOPES"
720
+ ];
721
+ const INTEGRATION_AUTH_PARAMS = [
722
+ "AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_KEY",
723
+ "AIO_COMMERCE_AUTH_INTEGRATION_CONSUMER_SECRET",
724
+ "AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN",
725
+ "AIO_COMMERCE_AUTH_INTEGRATION_ACCESS_TOKEN_SECRET"
726
+ ];
727
+ /**
728
+ * Automatically detects and resolves authentication parameters from App Builder action inputs.
729
+ * Attempts to resolve IMS authentication first, then falls back to Integration authentication.
730
+ *
731
+ * @param params The App Builder action inputs containing authentication parameters.
732
+ * @throws {CommerceSdkValidationError} If the parameters are invalid.
733
+ * @throws {Error} If neither IMS nor Integration authentication parameters can be resolved.
734
+ * @example
735
+ * ```typescript
736
+ * // Automatic detection (will use IMS if IMS params are present, otherwise Integration)
737
+ * export function main(params) {
738
+ * const authProvider = resolveAuthParams(params);
739
+ * console.log(authProvider.strategy); // "ims" or "integration"
740
+ * }
741
+ * ```
742
+ */
743
+ function resolveAuthParams(params) {
744
+ if ((0, _adobe_aio_commerce_lib_core_params.allNonEmpty)(params, IMS_AUTH_PARAMS)) return {
745
+ ...resolveImsAuthParams(params),
746
+ strategy: "ims"
747
+ };
748
+ if ((0, _adobe_aio_commerce_lib_core_params.allNonEmpty)(params, INTEGRATION_AUTH_PARAMS)) return {
749
+ ...resolveIntegrationAuthParams(params),
750
+ strategy: "integration"
751
+ };
752
+ throw new Error(`Can't resolve authentication options for the given params. Please provide either IMS options (${IMS_AUTH_PARAMS.join(", ")}) or Commerce integration options (${INTEGRATION_AUTH_PARAMS.join(", ")}).`);
753
+ }
754
+
755
+ //#endregion
756
+ exports.assertImsAuthParams = assertImsAuthParams;
757
+ exports.assertIntegrationAuthParams = assertIntegrationAuthParams;
758
+ exports.forwardImsAuthProvider = forwardImsAuthProvider;
759
+ exports.getForwardedImsAuthProvider = getForwardedImsAuthProvider;
760
+ exports.getImsAuthProvider = getImsAuthProvider;
761
+ exports.getIntegrationAuthProvider = getIntegrationAuthProvider;
762
+ exports.isImsAuthProvider = isImsAuthProvider;
763
+ exports.isIntegrationAuthProvider = isIntegrationAuthProvider;
764
+ exports.resolveAuthParams = resolveAuthParams;
765
+ exports.resolveImsAuthParams = resolveImsAuthParams;