@adobe/aio-commerce-lib-app 0.1.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.
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @license
3
+ *
4
+ * Copyright 2025 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
+ var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJSMin=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports),__copyProps=(to,from,except,desc)=>{if(from&&typeof from==`object`||typeof from==`function`)for(var keys=__getOwnPropNames(from),i=0,n=keys.length,key;i<n;i++)key=keys[i],!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:(k=>from[k]).bind(null,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM=(mod,isNodeMode,target)=>(target=mod==null?{}:__create(__getProtoOf(mod)),__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,`default`,{value:mod,enumerable:!0}):target,mod));let fs_promises=require(`fs/promises`),path=require(`path`),__adobe_aio_commerce_lib_core_error=require(`@adobe/aio-commerce-lib-core/error`),fs=require(`fs`),jiti=require(`jiti`),valibot=require(`valibot`);valibot=__toESM(valibot);function stringifyError(error){return error instanceof __adobe_aio_commerce_lib_core_error.CommerceSdkValidationError?error.display():error instanceof Error?error.message:String(error)}async function findUp(name,options={}){let names=Array.isArray(name)?name:[name],cwd=options.cwd||process.cwd(),{root}=(0,path.parse)(cwd),stopAt=options.stopAt||root,currentDir=cwd;for(;;){for(let fileName of names){let filePath=(0,path.join)(currentDir,fileName);try{return await(0,fs_promises.access)(filePath),filePath}catch{}}if(currentDir===stopAt||currentDir===root)return;currentDir=(0,path.dirname)(currentDir)}}async function findNearestPackageJson(cwd=process.cwd()){return await findUp(`package.json`,{cwd})||null}async function getProjectRootDirectory(cwd=process.cwd()){let packageJsonPath=await findNearestPackageJson(cwd);if(!packageJsonPath)throw Error("Could not find a the root directory of the project. `package.json` file not found.");return(0,path.dirname)(packageJsonPath)}async function makeOutputDirFor(fileOrFolder){let outputDir=(0,path.join)(await getProjectRootDirectory(),fileOrFolder);return(0,fs.existsSync)(outputDir)||await(0,fs_promises.mkdir)(outputDir,{recursive:!0}),outputDir}async function detectPackageManager(cwd=process.cwd()){let rootDirectory=await getProjectRootDirectory(cwd),lockFileMap={"bun.lockb":`bun`,"pnpm-lock.yaml":`pnpm`,"yarn.lock":`yarn`,"package-lock.json":`npm`},lockFileName=Object.keys(lockFileMap).find(name=>(0,fs.existsSync)((0,path.join)(rootDirectory,name)));return lockFileName?lockFileMap[lockFileName]:`npm`}function getExecCommand(packageManager){return{pnpm:`pnpx`,yarn:`yarn dlx`,bun:`bunx`,npm:`npx`}[packageManager]}const BaseOptionSchema=valibot.object({name:valibot.pipe(valibot.string(`Expected a string for the field name`),valibot.nonEmpty(`The field name must not be empty`)),label:valibot.optional(valibot.string(`Expected a string for the field label`)),description:valibot.optional(valibot.string(`Expected a string for the field description`))}),ListOptionSchema=valibot.object({label:valibot.string(`Expected a string for the option label`),value:valibot.string(`Expected a string for the option value`)}),SingleListSchema=valibot.object({...BaseOptionSchema.entries,type:valibot.literal(`list`,`Expected the type to be 'list'`),selectionMode:valibot.literal(`single`,`Expected the selectionMode to be 'single'`),options:valibot.array(ListOptionSchema,`Expected an array of list options`),default:valibot.pipe(valibot.string(`Expected a string for the default value`),valibot.nonEmpty(`The default value must not be empty`))}),MultipleListSchema=valibot.object({...BaseOptionSchema.entries,type:valibot.literal(`list`,`Expected the type to be 'list'`),selectionMode:valibot.literal(`multiple`,`Expected the selectionMode to be 'multiple'`),options:valibot.array(ListOptionSchema,`Expected an array of list options`),default:valibot.optional(valibot.array(valibot.pipe(valibot.string(`Expected a string for each default value`),valibot.nonEmpty(`Each default value must not be empty`)),`Expected an array of default values`),[])}),ListSchema=valibot.variant(`selectionMode`,[SingleListSchema,MultipleListSchema]),TextSchema=valibot.object({...BaseOptionSchema.entries,type:valibot.literal(`text`,`Expected the type to be 'text'`),default:valibot.optional(valibot.string(`Expected a string for the default value`))}),PasswordSchema=valibot.object({...BaseOptionSchema.entries,type:valibot.literal(`password`,`Expected the type to be 'password'`),default:valibot.optional(valibot.string(`Expected a string for the default value`))}),EmailSchema=valibot.object({...BaseOptionSchema.entries,type:valibot.literal(`email`,`Expected the type to be 'email'`),default:valibot.optional(valibot.pipe(valibot.string(`Expected a string for the default email value`),valibot.email(`The email must be a valid email address`)))}),UrlSchema=valibot.object({...BaseOptionSchema.entries,type:valibot.literal(`url`,`Expected the type to be 'url'`),default:valibot.optional(valibot.pipe(valibot.string(`Expected a string for the default URL value`),valibot.url(`The URL must be a valid URL`)))}),PhoneSchema=valibot.object({...BaseOptionSchema.entries,type:valibot.literal(`tel`,`Expected the type to be 'tel'`),default:valibot.optional(valibot.pipe(valibot.string(`Expected a string for the default phone number value`),valibot.regex(/^\+?[0-9\s\-()]+$/,`The phone number must contain only numbers and/or country codes`)))}),FieldSchema=valibot.variant(`type`,[ListSchema,TextSchema,PasswordSchema,EmailSchema,UrlSchema,PhoneSchema]),SchemaBusinessConfigSchema=valibot.pipe(valibot.array(FieldSchema,`Expected an array of configuration fields`),valibot.minLength(1,`At least one configuration parameter is required`)),SchemaBusinessConfig=valibot.object({schema:valibot.optional(SchemaBusinessConfigSchema,[])}),MAX_DESCRIPTION_LENGTH=255,MAX_DISPLAY_NAME_LENGTH=50,NUMERIC_IDENTIFIER=`(0|[1-9]\\d*)`,SEMVER_REGEX=RegExp(`^${NUMERIC_IDENTIFIER}\\.${NUMERIC_IDENTIFIER}\\.${NUMERIC_IDENTIFIER}$`);function nonEmptyString(fieldName){return valibot.pipe(valibot.string(`Expected a string for the ${fieldName}`),valibot.nonEmpty(`The ${fieldName} must not be empty`))}const MetadataSchema=valibot.object({id:valibot.pipe(nonEmptyString(`application id`),valibot.regex(/^[a-zA-Z0-9-]+$/,`The application id must contain only alphanumeric characters and dashes`)),displayName:valibot.pipe(nonEmptyString(`application display name`),valibot.maxLength(50,`The application display name must not be longer than 50 characters`)),description:valibot.pipe(nonEmptyString(`metadata description`),valibot.maxLength(255,`The metadata description must not be longer than 255 characters`)),version:valibot.pipe(nonEmptyString(`version`),valibot.regex(SEMVER_REGEX,`The version must follow semantic versioning (semver) format`))}),CommerceAppConfigSchemas={metadata:MetadataSchema,businessConfig:SchemaBusinessConfig,"businessConfig.schema":SchemaBusinessConfigSchema},CommerceAppConfigSchema=valibot.object({metadata:MetadataSchema,businessConfig:valibot.optional(SchemaBusinessConfig)}),commerceAppConfigDomainsSchema=valibot.picklist(Object.keys(CommerceAppConfigSchemas));function validateCommerceAppConfig(config){let validatedConfig=valibot.safeParse(CommerceAppConfigSchema,config);if(!validatedConfig.success)throw new __adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid commerce app config`,{issues:validatedConfig.issues});return validatedConfig.output}function validateCommerceAppConfigDomain(config,domain){let domainSchema=valibot.safeParse(commerceAppConfigDomainsSchema,domain);if(!domainSchema.success)throw new __adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid commerce app config domain`,{issues:domainSchema.issues});let domainConfigSchema=CommerceAppConfigSchemas[domain],validatedConfig=valibot.safeParse(domainConfigSchema,config);if(!validatedConfig.success)throw new __adobe_aio_commerce_lib_core_error.CommerceSdkValidationError(`Invalid commerce app config: ${domain}`,{issues:validatedConfig.issues});return validatedConfig.output}const jiti$1=(0,jiti.createJiti)(require(`url`).pathToFileURL(__filename).href),BUNDLED_APP_COMMERCE_CONFIG_PATH=`app-management/app.commerce.manifest.json`,configPaths=Object.freeze([`app.commerce.config.js`,`app.commerce.config.ts`,`app.commerce.config.cjs`,`app.commerce.config.mjs`,`app.commerce.config.mts`,`app.commerce.config.cts`]);async function resolveCommerceAppConfig(cwd=process.cwd()){let packageJsonPath=await findNearestPackageJson(cwd);if(!packageJsonPath)return null;let rootDirectory=(0,path.dirname)(packageJsonPath);for(let configPath of configPaths){let configFilePath=await findUp(configPath,{cwd,stopAt:rootDirectory});if(configFilePath)return configFilePath}return null}async function readCommerceAppConfig(cwd=process.cwd()){let configFilePath=await resolveCommerceAppConfig(cwd);if(!configFilePath)throw Error(`Could not find a commerce app config file in the current working directory or its parents.`);let config=null;try{config=await jiti$1.import(configFilePath)}catch(error){let message=stringifyError(error);throw Error(`Failed to read commerce app config file at ${configFilePath}: ${message}`,{cause:error})}if(!(config&&`default`in config)||config.default===void 0||config.default===null||typeof config.default==`object`&&Object.keys(config.default).length===0)throw Error("Commerce app config file does not export a default export. Make sure you use `export default` or `module.exports = { /* your config */ }`");return config.default}async function parseCommerceAppConfig(cwd=process.cwd()){return validateCommerceAppConfig(await readCommerceAppConfig(cwd))}async function readBundledCommerceAppConfig(){try{let fileContents=await(0,fs_promises.readFile)(`app-management/app.commerce.manifest.json`,`utf-8`);return validateCommerceAppConfig(JSON.parse(fileContents))}catch(error){let message=stringifyError(error);throw Error(`Failed to read bundled commerce app config file: ${message}`,{cause:error})}}Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return validateCommerceAppConfig}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return getExecCommand}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return __commonJSMin}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return __toESM}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return resolveCommerceAppConfig}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return makeOutputDirFor}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return readBundledCommerceAppConfig}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return validateCommerceAppConfigDomain}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return readCommerceAppConfig}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return detectPackageManager}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return parseCommerceAppConfig}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return stringifyError}});
@@ -0,0 +1,61 @@
1
+ /*
2
+ * Copyright 2025 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ // This file has been auto-generated by `@adobe/aio-commerce-lib-app`
14
+ // Do not modify this file directly
15
+
16
+ import util from "node:util";
17
+
18
+ import { readBundledCommerceAppConfig } from "@adobe/aio-commerce-lib-app/config";
19
+ import {
20
+ internalServerError,
21
+ ok,
22
+ } from "@adobe/aio-commerce-sdk/core/responses";
23
+ import AioLogger from "@adobe/aio-lib-core-logging";
24
+
25
+ // Shorthand to inspect an object.
26
+ const inspect = (obj) => util.inspect(obj, { depth: null });
27
+
28
+ /**
29
+ * Get the app config.
30
+ * @returns The response object containing the app config.
31
+ */
32
+ export async function main(params) {
33
+ const logger = AioLogger("get-app-config", {
34
+ level: params.LOG_LEVEL || "info",
35
+ });
36
+
37
+ try {
38
+ logger.debug("Retrieving app config...");
39
+ const appConfig = await readBundledCommerceAppConfig();
40
+
41
+ logger.debug(
42
+ "Successfully retrieved and validated the app config",
43
+ );
44
+
45
+ return ok({
46
+ body: appConfig,
47
+ });
48
+ } catch (error) {
49
+ logger.error(
50
+ `Something wen't wrong while retrieving app config: ${inspect(error)}`,
51
+ );
52
+
53
+ return internalServerError({
54
+ body: {
55
+ code: "INTERNAL_ERROR",
56
+ details: error instanceof Error ? error.message : "Unknown error",
57
+ message: "An internal server error occurred",
58
+ },
59
+ });
60
+ }
61
+ }
@@ -0,0 +1 @@
1
+ export { };