@igstack/app-catalog-backend-core 0.3.1-alpha-20260306003829 → 0.3.1-alpha-20260310051005
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/db/client.mjs +1 -1
- package/dist/db/client.mjs.map +1 -1
- package/dist/db/syncAppCatalog.d.mts.map +1 -1
- package/dist/db/syncAppCatalog.mjs +4 -3
- package/dist/db/syncAppCatalog.mjs.map +1 -1
- package/dist/index.d.mts +16 -17
- package/dist/index.mjs +5 -6
- package/dist/middleware/backendResolver.mjs.map +1 -1
- package/dist/middleware/createAcMiddleware.d.mts +7 -0
- package/dist/middleware/createAcMiddleware.d.mts.map +1 -0
- package/dist/middleware/{createEhMiddleware.mjs → createAcMiddleware.mjs} +23 -43
- package/dist/middleware/createAcMiddleware.mjs.map +1 -0
- package/dist/middleware/database.d.mts +4 -4
- package/dist/middleware/database.mjs +2 -2
- package/dist/middleware/database.mjs.map +1 -1
- package/dist/middleware/featureRegistry.mjs +17 -30
- package/dist/middleware/featureRegistry.mjs.map +1 -1
- package/dist/middleware/index.d.mts +3 -3
- package/dist/middleware/types.d.mts +31 -44
- package/dist/middleware/types.d.mts.map +1 -1
- package/dist/modules/auth/auth.d.mts +4 -38
- package/dist/modules/auth/auth.d.mts.map +1 -1
- package/dist/modules/auth/auth.mjs +3 -18
- package/dist/modules/auth/auth.mjs.map +1 -1
- package/dist/modules/auth/authRouter.d.mts +4 -3
- package/dist/modules/auth/authRouter.d.mts.map +1 -1
- package/dist/modules/auth/authRouter.mjs +2 -1
- package/dist/modules/auth/authRouter.mjs.map +1 -1
- package/dist/modules/auth/devMockUserUtils.mjs +4 -5
- package/dist/modules/auth/devMockUserUtils.mjs.map +1 -1
- package/dist/modules/auth/registerAuthRoutes.d.mts +7 -2
- package/dist/modules/auth/registerAuthRoutes.d.mts.map +1 -1
- package/dist/modules/auth/registerAuthRoutes.mjs +17 -3
- package/dist/modules/auth/registerAuthRoutes.mjs.map +1 -1
- package/dist/server/acStaticControllerContract.d.mts +17 -0
- package/dist/server/acStaticControllerContract.d.mts.map +1 -0
- package/dist/server/{ehStaticControllerContract.mjs → acStaticControllerContract.mjs} +2 -2
- package/dist/server/acStaticControllerContract.mjs.map +1 -0
- package/dist/server/acTrpcContext.d.mts +22 -0
- package/dist/server/acTrpcContext.d.mts.map +1 -0
- package/dist/server/acTrpcContext.mjs +12 -0
- package/dist/server/acTrpcContext.mjs.map +1 -0
- package/dist/server/controller.d.mts +4 -10
- package/dist/server/controller.d.mts.map +1 -1
- package/dist/server/controller.mjs +0 -3
- package/dist/server/controller.mjs.map +1 -1
- package/dist/server/trpcSetup.mjs +3 -14
- package/dist/server/trpcSetup.mjs.map +1 -1
- package/dist/types/backend/api.d.mts +25 -25
- package/dist/types/backend/common.d.mts +3 -3
- package/dist/types/backend/dataSources.d.mts +7 -7
- package/dist/types/backend/deployments.d.mts +12 -12
- package/dist/types/common/app/appTypes.d.mts +6 -6
- package/dist/types/common/app/ui/appUiTypes.d.mts +4 -4
- package/dist/types/common/env/envTypes.d.mts +4 -4
- package/dist/types/common/resourceTypes.d.mts +2 -2
- package/dist/types/common/sharedTypes.d.mts +2 -2
- package/dist/utils/naturalSort.mjs +23 -0
- package/dist/utils/naturalSort.mjs.map +1 -0
- package/package.json +3 -3
- package/src/__tests__/utils/naturalSort.test.ts +20 -0
- package/src/db/client.ts +1 -1
- package/src/db/syncAppCatalog.ts +4 -69
- package/src/index.ts +16 -30
- package/src/middleware/backendResolver.ts +2 -2
- package/src/middleware/{createEhMiddleware.ts → createAcMiddleware.ts} +24 -54
- package/src/middleware/database.ts +5 -5
- package/src/middleware/featureRegistry.ts +21 -42
- package/src/middleware/index.ts +11 -11
- package/src/middleware/types.ts +31 -43
- package/src/modules/auth/auth.ts +7 -42
- package/src/modules/auth/authRouter.ts +4 -4
- package/src/modules/auth/devMockUserUtils.ts +4 -12
- package/src/modules/auth/registerAuthRoutes.ts +23 -4
- package/src/server/{ehStaticControllerContract.ts → acStaticControllerContract.ts} +3 -3
- package/src/server/{ehTrpcContext.ts → acTrpcContext.ts} +8 -12
- package/src/server/controller.ts +0 -6
- package/src/server/trpcSetup.ts +5 -21
- package/src/types/backend/api.ts +27 -27
- package/src/types/backend/common.ts +2 -2
- package/src/types/backend/dataSources.ts +7 -7
- package/src/types/backend/deployments.ts +11 -11
- package/src/types/common/app/appTypes.ts +5 -5
- package/src/types/common/app/ui/appUiTypes.ts +3 -3
- package/src/types/common/env/envTypes.ts +3 -3
- package/src/types/common/resourceTypes.ts +1 -1
- package/src/types/common/sharedTypes.ts +1 -1
- package/src/utils/naturalSort.ts +18 -0
- package/dist/middleware/createEhMiddleware.d.mts +0 -7
- package/dist/middleware/createEhMiddleware.d.mts.map +0 -1
- package/dist/middleware/createEhMiddleware.mjs.map +0 -1
- package/dist/modules/auth/authorizationUtils.d.mts +0 -56
- package/dist/modules/auth/authorizationUtils.d.mts.map +0 -1
- package/dist/modules/auth/authorizationUtils.mjs +0 -64
- package/dist/modules/auth/authorizationUtils.mjs.map +0 -1
- package/dist/server/ehStaticControllerContract.d.mts +0 -17
- package/dist/server/ehStaticControllerContract.d.mts.map +0 -1
- package/dist/server/ehStaticControllerContract.mjs.map +0 -1
- package/dist/server/ehTrpcContext.d.mts +0 -22
- package/dist/server/ehTrpcContext.d.mts.map +0 -1
- package/dist/server/ehTrpcContext.mjs +0 -12
- package/dist/server/ehTrpcContext.mjs.map +0 -1
- package/src/modules/auth/authProviders.ts +0 -40
- package/src/modules/auth/authorizationUtils.ts +0 -132
package/dist/db/client.mjs
CHANGED
|
@@ -12,7 +12,7 @@ let pool = null;
|
|
|
12
12
|
function getDbClient() {
|
|
13
13
|
if (!prismaClient) {
|
|
14
14
|
const databaseUrl = process.env.AC_CORE_DATABASE_URL;
|
|
15
|
-
if (!databaseUrl) throw new Error("PrismaClient not initialized. You must call
|
|
15
|
+
if (!databaseUrl) throw new Error("PrismaClient not initialized. You must call createAcMiddleware() before using database functions, or set AC_CORE_DATABASE_URL environment variable for standalone usage.");
|
|
16
16
|
pool = new pg.Pool({ connectionString: databaseUrl });
|
|
17
17
|
prismaClient = new PrismaClient({ adapter: new PrismaPg(pool) });
|
|
18
18
|
}
|
package/dist/db/client.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.mjs","names":[],"sources":["../../src/db/client.ts"],"sourcesContent":["import { PrismaClient } from '../generated/prisma/client'\nimport { PrismaPg } from '@prisma/adapter-pg'\nimport pg from 'pg'\n\nlet prismaClient: PrismaClient | null = null\nlet pool: pg.Pool | null = null\n\n/**\n * Gets the internal Prisma client instance.\n * Creates one if it doesn't exist.\n */\nexport function getDbClient(): PrismaClient {\n if (!prismaClient) {\n const databaseUrl = process.env.AC_CORE_DATABASE_URL\n if (!databaseUrl) {\n throw new Error(\n 'PrismaClient not initialized. You must call
|
|
1
|
+
{"version":3,"file":"client.mjs","names":[],"sources":["../../src/db/client.ts"],"sourcesContent":["import { PrismaClient } from '../generated/prisma/client'\nimport { PrismaPg } from '@prisma/adapter-pg'\nimport pg from 'pg'\n\nlet prismaClient: PrismaClient | null = null\nlet pool: pg.Pool | null = null\n\n/**\n * Gets the internal Prisma client instance.\n * Creates one if it doesn't exist.\n */\nexport function getDbClient(): PrismaClient {\n if (!prismaClient) {\n const databaseUrl = process.env.AC_CORE_DATABASE_URL\n if (!databaseUrl) {\n throw new Error(\n 'PrismaClient not initialized. You must call createAcMiddleware() before using database functions, ' +\n 'or set AC_CORE_DATABASE_URL environment variable for standalone usage.',\n )\n }\n\n // Prisma 7 with adapter: Create pg pool and wrap with adapter\n pool = new pg.Pool({ connectionString: databaseUrl })\n const adapter = new PrismaPg(pool)\n\n prismaClient = new PrismaClient({ adapter })\n }\n return prismaClient\n}\n\n/**\n * Sets the internal Prisma client instance.\n * Used by middleware to bridge with existing getDbClient() usage.\n */\nexport function setDbClient(client: PrismaClient): void {\n prismaClient = client\n}\n\n/**\n * Connects to the database.\n * Call this before performing database operations.\n */\nexport async function connectDb(): Promise<void> {\n const client = getDbClient()\n await client.$connect()\n}\n\n/**\n * Disconnects from the database.\n * Call this when done with database operations (e.g., in scripts).\n */\nexport async function disconnectDb(): Promise<void> {\n if (prismaClient) {\n await prismaClient.$disconnect()\n prismaClient = null\n }\n if (pool) {\n await pool.end()\n pool = null\n }\n}\n"],"mappings":";;;;;AAIA,IAAI,eAAoC;AACxC,IAAI,OAAuB;;;;;AAM3B,SAAgB,cAA4B;AAC1C,KAAI,CAAC,cAAc;EACjB,MAAM,cAAc,QAAQ,IAAI;AAChC,MAAI,CAAC,YACH,OAAM,IAAI,MACR,2KAED;AAIH,SAAO,IAAI,GAAG,KAAK,EAAE,kBAAkB,aAAa,CAAC;AAGrD,iBAAe,IAAI,aAAa,EAAE,SAFlB,IAAI,SAAS,KAAK,EAES,CAAC;;AAE9C,QAAO;;;;;;AAOT,SAAgB,YAAY,QAA4B;AACtD,gBAAe;;;;;;AAOjB,eAAsB,YAA2B;AAE/C,OADe,aAAa,CACf,UAAU;;;;;;AAOzB,eAAsB,eAA8B;AAClD,KAAI,cAAc;AAChB,QAAM,aAAa,aAAa;AAChC,iBAAe;;AAEjB,KAAI,MAAM;AACR,QAAM,KAAK,KAAK;AAChB,SAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncAppCatalog.d.mts","names":[],"sources":["../../src/db/syncAppCatalog.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"syncAppCatalog.d.mts","names":[],"sources":["../../src/db/syncAppCatalog.ts"],"mappings":";;;;UAciB,oBAAA;EACf,OAAA;EACA,OAAA;EACA,OAAA;EACA,KAAA;AAAA;;;;;;;iBA0JoB,cAAA,CACpB,IAAA,EAAM,KAAA,CAAM,aAAA,GACZ,eAAA,EAAiB,KAAA,CAAM,qBAAA,GACvB,eAAA,EAAiB,KAAA,CAAM,cAAA,GACvB,cAAA,YACC,OAAA,CAAQ,oBAAA"}
|
|
@@ -2,6 +2,7 @@ import { getDbClient } from "./client.mjs";
|
|
|
2
2
|
import { tableSyncPrisma } from "./tableSyncPrismaAdapter.mjs";
|
|
3
3
|
import { TABLE_SYNC_MAGAZINE } from "./tableSyncMagazine.mjs";
|
|
4
4
|
import { upsertAsset } from "../modules/assets/upsertAsset.mjs";
|
|
5
|
+
import { naturalSort } from "../utils/naturalSort.mjs";
|
|
5
6
|
import { group } from "radashi";
|
|
6
7
|
import { readFile, readdir, stat } from "node:fs/promises";
|
|
7
8
|
|
|
@@ -11,10 +12,10 @@ function isFileNotFoundError(error) {
|
|
|
11
12
|
}
|
|
12
13
|
async function processAssetDirectory(dirPath, appSlug, assetType, prisma) {
|
|
13
14
|
try {
|
|
14
|
-
const
|
|
15
|
+
const sortedFiles = naturalSort(await readdir(dirPath));
|
|
15
16
|
const assetIds = [];
|
|
16
|
-
for (let i = 0; i <
|
|
17
|
-
const fileName =
|
|
17
|
+
for (let i = 0; i < sortedFiles.length; i++) {
|
|
18
|
+
const fileName = sortedFiles[i];
|
|
18
19
|
if (!fileName) continue;
|
|
19
20
|
const assetName = assetType === "screenshot" ? `${appSlug}-screenshot-${i + 1}` : `${appSlug}-icon`;
|
|
20
21
|
const id = await upsertAsset({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncAppCatalog.mjs","names":[],"sources":["../../src/db/syncAppCatalog.ts"],"sourcesContent":["import type {\n AppForCatalog,\n GroupingTagDefinition,\n} from '../types/common/appCatalogTypes'\nimport { getDbClient } from './client'\nimport { TABLE_SYNC_MAGAZINE } from './tableSyncMagazine'\nimport { tableSyncPrisma } from './tableSyncPrismaAdapter'\nimport { readFile, readdir, stat } from 'node:fs/promises'\nimport { group } from 'radashi'\nimport { upsertAsset } from '../modules/assets/upsertAsset'\nimport type { ApprovalMethod } from '../types'\nimport type { PrismaClient } from '../generated/prisma/client'\n\nexport interface SyncAppCatalogResult {\n created: number\n updated: number\n deleted: number\n total: number\n}\n\ninterface AssetSyncResult {\n screenshotIds: Array<string>\n iconName: string | null\n}\n\nfunction isFileNotFoundError(error: unknown): boolean {\n return (\n error instanceof Error &&\n 'code' in error &&\n (error as NodeJS.ErrnoException).code === 'ENOENT'\n )\n}\n\nasync function processAssetDirectory(\n dirPath: string,\n appSlug: string,\n assetType: 'screenshot' | 'icon',\n prisma: PrismaClient,\n): Promise<Array<string>> {\n try {\n const files = await readdir(dirPath)\n const assetIds: Array<string> = []\n\n for (let i = 0; i < files.length; i++) {\n const fileName = files[i]\n if (!fileName) continue\n\n const assetName =\n assetType === 'screenshot'\n ? `${appSlug}-screenshot-${i + 1}`\n : `${appSlug}-icon`\n\n const id = await upsertAsset({\n prisma,\n buffer: await readFile(`${dirPath}/${fileName}`),\n originalFilename: fileName,\n name: assetName,\n assetType,\n })\n assetIds.push(id)\n\n // For icons, only process the first file\n if (assetType === 'icon') {\n break\n }\n }\n\n return assetIds\n } catch (error: unknown) {\n if (isFileNotFoundError(error)) {\n return []\n }\n throw error\n }\n}\n\nasync function syncAppAssets(\n appSlug: string,\n appPath: string,\n prisma: PrismaClient,\n): Promise<AssetSyncResult> {\n const screenshotIds = await processAssetDirectory(\n `${appPath}/screenshots`,\n appSlug,\n 'screenshot',\n prisma,\n )\n\n const iconIds = await processAssetDirectory(\n `${appPath}/icons`,\n appSlug,\n 'icon',\n prisma,\n )\n\n return {\n screenshotIds,\n iconName: iconIds.length > 0 ? `${appSlug}-icon` : null,\n }\n}\n\nasync function syncAssetsFromFileSystem(\n apps: Array<AppForCatalog>,\n allAppsAssetsPath: string,\n) {\n const appDirectories = await readdir(allAppsAssetsPath)\n const prisma = getDbClient()\n const bySlug = group(apps, (a) => a.slug)\n\n for (const appDirName of appDirectories) {\n try {\n const stats = await stat(`${allAppsAssetsPath}/${appDirName}`)\n if (!stats.isDirectory()) {\n continue\n }\n } catch (error: unknown) {\n if (isFileNotFoundError(error)) {\n continue\n }\n throw error\n }\n\n const appSlug = appDirName\n if (!bySlug[appSlug]) {\n throw new Error(\n `App '${appSlug}' does not exist in the app catalog. Existing apps: ${Object.keys(bySlug).join(', ')}`,\n )\n }\n\n try {\n const { screenshotIds, iconName } = await syncAppAssets(\n appSlug,\n `${allAppsAssetsPath}/${appDirName}`,\n prisma,\n )\n\n const updateData: {\n screenshotIds?: Array<string>\n iconName?: string | null\n } = {}\n\n if (screenshotIds.length > 0) {\n updateData.screenshotIds = screenshotIds\n }\n if (iconName !== null) {\n updateData.iconName = iconName\n }\n\n if (Object.keys(updateData).length > 0) {\n await prisma.dbAppForCatalog.update({\n where: { slug: appSlug },\n data: updateData,\n })\n }\n } catch (error: unknown) {\n const errorMessage =\n error instanceof Error ? error.message : String(error)\n throw new Error(\n `Error while upserting assets for app '${appSlug}': ${errorMessage}`,\n )\n }\n }\n // private async syncScreenshots(apps: AppForCatalog[], screenshotsPath: string): Promise<void> {\n // const db = getDbClient();\n //\n // for (const app of apps) {\n // const dirPath = join(screenshotsPath, `${app.slug}-screenshots`);\n //\n // try {\n // const files = await readdir(dirPath);\n // const imageFiles = files.filter(f => /\\.(png|jpg|jpeg|gif|webp)$/i.test(f)).sort();\n //\n // if (imageFiles.length === 0) continue;\n //\n // const screenshotIds: string[] = [];\n //\n // for (const filename of imageFiles) {\n // const filePath = join(dirPath, filename);\n // const content = await readFile(filePath);\n // const buffer = Buffer.from(content);\n // const checksum = generateChecksum(buffer);\n // const { width, height } = await getImageDimensions(buffer);\n //\n // const ext = filename.split('.').pop()?.toLowerCase();\n // const mimeType = {\n // png: 'image/png',\n // jpg: 'image/jpeg',\n // jpeg: 'image/jpeg',\n // gif: 'image/gif',\n // webp: 'image/webp',\n // }[ext || ''] || 'application/octet-stream';\n //\n // const asset = await db.dbAsset.upsert({\n // where: { checksum },\n // create: {\n // name: `${app.slug}/${filename}`,\n // assetType: 'screenshot',\n // content: new Uint8Array(buffer),\n // checksum,\n // mimeType,\n // fileSize: buffer.length,\n // width,\n // height,\n // },\n // update: {\n // name: `${app.slug}/${filename}`,\n // content: new Uint8Array(buffer),\n // mimeType,\n // fileSize: buffer.length,\n // width,\n // height,\n // },\n // });\n //\n // screenshotIds.push(asset.id);\n // }\n //\n // await db.dbAppForCatalog.update({\n // where: { slug: app.slug },\n // data: { screenshotIds },\n // });\n //\n // logger.info(`Synced ${screenshotIds.length} screenshots for ${app.slug}`);\n // } catch (error: any) {\n // if (error.code === 'ENOENT') continue; // Skip if directory doesn't exist\n // throw error;\n // }\n // }\n // }\n}\n\n/**\n * Syncs app catalog data to the database using table sync.\n * This will create new apps, update existing ones, and delete any that are no longer in the input.\n *\n * Note: Call connectDb() before and disconnectDb() after if running in a script.\n */\nexport async function syncAppCatalog(\n apps: Array<AppForCatalog>,\n tagsDefinitions: Array<GroupingTagDefinition>,\n approvalMethods: Array<ApprovalMethod>,\n sreenshotsPath?: string,\n): Promise<SyncAppCatalogResult> {\n try {\n const prisma = getDbClient()\n\n await tableSyncPrisma({\n prisma,\n ...TABLE_SYNC_MAGAZINE.DbApprovalMethod,\n }).sync(approvalMethods)\n\n const sync = tableSyncPrisma({\n prisma,\n ...TABLE_SYNC_MAGAZINE.DbAppForCatalog,\n })\n\n await tableSyncPrisma({\n prisma,\n ...TABLE_SYNC_MAGAZINE.DbAppTagDefinition,\n }).sync(tagsDefinitions)\n\n // Transform AppForCatalog to DbAppForCatalog format\n const dbApps = apps.map((app) => {\n const slug =\n app.slug ||\n app.displayName\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n\n return {\n slug,\n displayName: app.displayName,\n description: app.description,\n teams: app.teams ?? [],\n accessRequest: app.accessRequest ?? null,\n notes: app.notes ?? null,\n tags: app.tags ?? [],\n appUrl: app.appUrl ?? null,\n links: app.links ?? null,\n iconName: app.iconName ?? null,\n screenshotIds: app.screenshotIds ?? [],\n sources: app.sources ?? [],\n deprecated: app.deprecated ?? null,\n }\n })\n\n const result = await sync.sync(dbApps)\n\n // Get actual synced data to calculate stats\n const actual = result.getActual()\n\n if (sreenshotsPath) {\n await syncAssetsFromFileSystem(apps, sreenshotsPath)\n } else {\n console.warn('Do not sync screenhots')\n }\n\n return {\n created: actual.length - apps.length + (apps.length - actual.length),\n updated: 0, // TableSync doesn't expose this directly\n deleted: 0, // TableSync doesn't expose this directly\n total: actual.length,\n }\n } catch (error) {\n // Wrap error with context\n const errorMessage = error instanceof Error ? error.message : String(error)\n const errorStack = error instanceof Error ? error.stack : undefined\n\n throw new Error(\n `Error syncing app catalog: ${errorMessage}\\n\\nDetails:\\n${errorStack || 'No stack trace available'}`,\n )\n }\n}\n"],"mappings":";;;;;;;;AAyBA,SAAS,oBAAoB,OAAyB;AACpD,QACE,iBAAiB,SACjB,UAAU,SACT,MAAgC,SAAS;;AAI9C,eAAe,sBACb,SACA,SACA,WACA,QACwB;AACxB,KAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,QAAQ;EACpC,MAAM,WAA0B,EAAE;AAElC,OAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;GACrC,MAAM,WAAW,MAAM;AACvB,OAAI,CAAC,SAAU;GAEf,MAAM,YACJ,cAAc,eACV,GAAG,QAAQ,cAAc,IAAI,MAC7B,GAAG,QAAQ;GAEjB,MAAM,KAAK,MAAM,YAAY;IAC3B;IACA,QAAQ,MAAM,SAAS,GAAG,QAAQ,GAAG,WAAW;IAChD,kBAAkB;IAClB,MAAM;IACN;IACD,CAAC;AACF,YAAS,KAAK,GAAG;AAGjB,OAAI,cAAc,OAChB;;AAIJ,SAAO;UACA,OAAgB;AACvB,MAAI,oBAAoB,MAAM,CAC5B,QAAO,EAAE;AAEX,QAAM;;;AAIV,eAAe,cACb,SACA,SACA,QAC0B;AAe1B,QAAO;EACL,eAfoB,MAAM,sBAC1B,GAAG,QAAQ,eACX,SACA,cACA,OACD;EAWC,WATc,MAAM,sBACpB,GAAG,QAAQ,SACX,SACA,QACA,OACD,EAImB,SAAS,IAAI,GAAG,QAAQ,SAAS;EACpD;;AAGH,eAAe,yBACb,MACA,mBACA;CACA,MAAM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A,IAAI,QACJ,IAAI,YACD,aAAa,CACb,QAAQ,eAAe,IAAI,CAC3B,QAAQ,YAAY,GAAG;IAI1B,aAAa,IAAI;IACjB,aAAa,IAAI;IACjB,OAAO,IAAI,SAAS,EAAE;IACtB,eAAe,IAAI,iBAAiB;IACpC,OAAO,IAAI,SAAS;IACpB,MAAM,IAAI,QAAQ,EAAE;IACpB,QAAQ,IAAI,UAAU;IACtB,OAAO,IAAI,SAAS;IACpB,UAAU,IAAI,YAAY;IAC1B,eAAe,IAAI,iBAAiB,EAAE;IACtC,SAAS,IAAI,WAAW,EAAE;IAC1B,YAAY,IAAI,cAAc;IAC/B;IACD;EAKF,MAAM,UAHS,MAAM,KAAK,KAAK,OAAO,EAGhB,WAAW;AAEjC,MAAI,eACF,OAAM,yBAAyB,MAAM,eAAe;MAEpD,SAAQ,KAAK,yBAAyB;AAGxC,SAAO;GACL,SAAS,OAAO,SAAS,KAAK,UAAU,KAAK,SAAS,OAAO;GAC7D,SAAS;GACT,SAAS;GACT,OAAO,OAAO;GACf;UACM,OAAO;EAEd,MAAM,eAAe,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;EAC3E,MAAM,aAAa,iBAAiB,QAAQ,MAAM,QAAQ;AAE1D,QAAM,IAAI,MACR,8BAA8B,aAAa,gBAAgB,cAAc,6BAC1E"}
|
|
1
|
+
{"version":3,"file":"syncAppCatalog.mjs","names":[],"sources":["../../src/db/syncAppCatalog.ts"],"sourcesContent":["import type {\n AppForCatalog,\n GroupingTagDefinition,\n} from '../types/common/appCatalogTypes'\nimport { getDbClient } from './client'\nimport { TABLE_SYNC_MAGAZINE } from './tableSyncMagazine'\nimport { tableSyncPrisma } from './tableSyncPrismaAdapter'\nimport { readFile, readdir, stat } from 'node:fs/promises'\nimport { group } from 'radashi'\nimport { upsertAsset } from '../modules/assets/upsertAsset'\nimport type { ApprovalMethod } from '../types'\nimport type { PrismaClient } from '../generated/prisma/client'\nimport { naturalSort } from '../utils/naturalSort'\n\nexport interface SyncAppCatalogResult {\n created: number\n updated: number\n deleted: number\n total: number\n}\n\ninterface AssetSyncResult {\n screenshotIds: Array<string>\n iconName: string | null\n}\n\nfunction isFileNotFoundError(error: unknown): boolean {\n return (\n error instanceof Error &&\n 'code' in error &&\n (error as NodeJS.ErrnoException).code === 'ENOENT'\n )\n}\n\nasync function processAssetDirectory(\n dirPath: string,\n appSlug: string,\n assetType: 'screenshot' | 'icon',\n prisma: PrismaClient,\n): Promise<Array<string>> {\n try {\n const files = await readdir(dirPath)\n const sortedFiles = naturalSort(files)\n const assetIds: Array<string> = []\n\n for (let i = 0; i < sortedFiles.length; i++) {\n const fileName = sortedFiles[i]\n if (!fileName) continue\n\n const assetName =\n assetType === 'screenshot'\n ? `${appSlug}-screenshot-${i + 1}`\n : `${appSlug}-icon`\n\n const id = await upsertAsset({\n prisma,\n buffer: await readFile(`${dirPath}/${fileName}`),\n originalFilename: fileName,\n name: assetName,\n assetType,\n })\n assetIds.push(id)\n\n // For icons, only process the first file\n if (assetType === 'icon') {\n break\n }\n }\n\n return assetIds\n } catch (error: unknown) {\n if (isFileNotFoundError(error)) {\n return []\n }\n throw error\n }\n}\n\nasync function syncAppAssets(\n appSlug: string,\n appPath: string,\n prisma: PrismaClient,\n): Promise<AssetSyncResult> {\n const screenshotIds = await processAssetDirectory(\n `${appPath}/screenshots`,\n appSlug,\n 'screenshot',\n prisma,\n )\n\n const iconIds = await processAssetDirectory(\n `${appPath}/icons`,\n appSlug,\n 'icon',\n prisma,\n )\n\n return {\n screenshotIds,\n iconName: iconIds.length > 0 ? `${appSlug}-icon` : null,\n }\n}\n\nasync function syncAssetsFromFileSystem(\n apps: Array<AppForCatalog>,\n allAppsAssetsPath: string,\n) {\n const appDirectories = await readdir(allAppsAssetsPath)\n const prisma = getDbClient()\n const bySlug = group(apps, (a) => a.slug)\n\n for (const appDirName of appDirectories) {\n try {\n const stats = await stat(`${allAppsAssetsPath}/${appDirName}`)\n if (!stats.isDirectory()) {\n continue\n }\n } catch (error: unknown) {\n if (isFileNotFoundError(error)) {\n continue\n }\n throw error\n }\n\n const appSlug = appDirName\n if (!bySlug[appSlug]) {\n throw new Error(\n `App '${appSlug}' does not exist in the app catalog. Existing apps: ${Object.keys(bySlug).join(', ')}`,\n )\n }\n\n try {\n const { screenshotIds, iconName } = await syncAppAssets(\n appSlug,\n `${allAppsAssetsPath}/${appDirName}`,\n prisma,\n )\n\n const updateData: {\n screenshotIds?: Array<string>\n iconName?: string | null\n } = {}\n\n if (screenshotIds.length > 0) {\n updateData.screenshotIds = screenshotIds\n }\n if (iconName !== null) {\n updateData.iconName = iconName\n }\n\n if (Object.keys(updateData).length > 0) {\n await prisma.dbAppForCatalog.update({\n where: { slug: appSlug },\n data: updateData,\n })\n }\n } catch (error: unknown) {\n const errorMessage =\n error instanceof Error ? error.message : String(error)\n throw new Error(\n `Error while upserting assets for app '${appSlug}': ${errorMessage}`,\n )\n }\n }\n}\n\n/**\n * Syncs app catalog data to the database using table sync.\n * This will create new apps, update existing ones, and delete any that are no longer in the input.\n *\n * Note: Call connectDb() before and disconnectDb() after if running in a script.\n */\nexport async function syncAppCatalog(\n apps: Array<AppForCatalog>,\n tagsDefinitions: Array<GroupingTagDefinition>,\n approvalMethods: Array<ApprovalMethod>,\n sreenshotsPath?: string,\n): Promise<SyncAppCatalogResult> {\n try {\n const prisma = getDbClient()\n\n await tableSyncPrisma({\n prisma,\n ...TABLE_SYNC_MAGAZINE.DbApprovalMethod,\n }).sync(approvalMethods)\n\n const sync = tableSyncPrisma({\n prisma,\n ...TABLE_SYNC_MAGAZINE.DbAppForCatalog,\n })\n\n await tableSyncPrisma({\n prisma,\n ...TABLE_SYNC_MAGAZINE.DbAppTagDefinition,\n }).sync(tagsDefinitions)\n\n // Transform AppForCatalog to DbAppForCatalog format\n const dbApps = apps.map((app) => {\n const slug =\n app.slug ||\n app.displayName\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n\n return {\n slug,\n displayName: app.displayName,\n description: app.description,\n teams: app.teams ?? [],\n accessRequest: app.accessRequest ?? null,\n notes: app.notes ?? null,\n tags: app.tags ?? [],\n appUrl: app.appUrl ?? null,\n links: app.links ?? null,\n iconName: app.iconName ?? null,\n screenshotIds: app.screenshotIds ?? [],\n sources: app.sources ?? [],\n deprecated: app.deprecated ?? null,\n }\n })\n\n const result = await sync.sync(dbApps)\n\n // Get actual synced data to calculate stats\n const actual = result.getActual()\n\n if (sreenshotsPath) {\n await syncAssetsFromFileSystem(apps, sreenshotsPath)\n } else {\n console.warn('Do not sync screenhots')\n }\n\n return {\n created: actual.length - apps.length + (apps.length - actual.length),\n updated: 0, // TableSync doesn't expose this directly\n deleted: 0, // TableSync doesn't expose this directly\n total: actual.length,\n }\n } catch (error) {\n // Wrap error with context\n const errorMessage = error instanceof Error ? error.message : String(error)\n const errorStack = error instanceof Error ? error.stack : undefined\n\n throw new Error(\n `Error syncing app catalog: ${errorMessage}\\n\\nDetails:\\n${errorStack || 'No stack trace available'}`,\n )\n }\n}\n"],"mappings":";;;;;;;;;AA0BA,SAAS,oBAAoB,OAAyB;AACpD,QACE,iBAAiB,SACjB,UAAU,SACT,MAAgC,SAAS;;AAI9C,eAAe,sBACb,SACA,SACA,WACA,QACwB;AACxB,KAAI;EAEF,MAAM,cAAc,YADN,MAAM,QAAQ,QAAQ,CACE;EACtC,MAAM,WAA0B,EAAE;AAElC,OAAK,IAAI,IAAI,GAAG,IAAI,YAAY,QAAQ,KAAK;GAC3C,MAAM,WAAW,YAAY;AAC7B,OAAI,CAAC,SAAU;GAEf,MAAM,YACJ,cAAc,eACV,GAAG,QAAQ,cAAc,IAAI,MAC7B,GAAG,QAAQ;GAEjB,MAAM,KAAK,MAAM,YAAY;IAC3B;IACA,QAAQ,MAAM,SAAS,GAAG,QAAQ,GAAG,WAAW;IAChD,kBAAkB;IAClB,MAAM;IACN;IACD,CAAC;AACF,YAAS,KAAK,GAAG;AAGjB,OAAI,cAAc,OAChB;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
import {
|
|
1
|
+
import { AcMetaDictionary, Tag } from "./types/common/sharedTypes.mjs";
|
|
2
|
+
import { AcResourceIndexed } from "./types/common/resourceTypes.mjs";
|
|
3
3
|
import { AppAccessRequest, AppRole, ApprovalMethod, ApprovalMethodConfig, ApprovalMethodType, ApprovalUrl, ApproverContact, CreateApprovalMethodInput, CustomConfig, PersonTeamConfig, ReachOutContact, ServiceConfig, UpdateApprovalMethodInput } from "./types/common/approvalMethodTypes.mjs";
|
|
4
4
|
import { AppApprovalMethod, AppCatalogData, AppCategory, AppForCatalog, GroupingTagDefinition, GroupingTagValue } from "./types/common/appCatalogTypes.mjs";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
5
|
+
import { AcEnvIndexed } from "./types/common/env/envTypes.mjs";
|
|
6
|
+
import { AcAppPageIndexed, AcAppUiIndexed } from "./types/common/app/ui/appUiTypes.mjs";
|
|
7
|
+
import { AcAppIndexed } from "./types/common/app/appTypes.mjs";
|
|
8
|
+
import { AcBackendCredentialInput, AcBackendUiDefaultsInput } from "./types/backend/common.mjs";
|
|
9
|
+
import { AcBackendDataSourceInput, AcBackendDataSourceInputCommon, AcBackendDataSourceInputDb, AcBackendDataSourceInputKafka } from "./types/backend/dataSources.mjs";
|
|
10
|
+
import { AcAppsMeta, AcBackendAppDto, AcBackendAppInput, AcBackendAppUIBaseInput, AcBackendAppUIInput, AcBackendPageInput, AcBackendTagDescriptionDataIndexed, AcBackendTagFixedTagValue, AcBackendTagsDescriptionDataIndexed, AcBackendVersionsRequestParams, AcBackendVersionsReturn, AcContextIndexed } from "./types/backend/api.mjs";
|
|
11
11
|
import { AppCatalogCompanySpecificBackend } from "./types/backend/companySpecificBackend.mjs";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
12
|
+
import { AcBackendDataFreshness, AcBackendDataVersion, AcBackendDeployableInput, AcBackendDeployment, AcBackendDeploymentInput, AcBackendEnvironmentInput } from "./types/backend/deployments.mjs";
|
|
13
|
+
import { AcTrpcContext, AcTrpcContextOptions, createAcTrpcContext } from "./server/acTrpcContext.mjs";
|
|
14
|
+
import { BetterAuth, createAuth } from "./modules/auth/auth.mjs";
|
|
15
15
|
import { TRPCRouter, createTrpcRouter } from "./server/controller.mjs";
|
|
16
|
-
import {
|
|
16
|
+
import { AcStaticControllerContract, staticControllerContract } from "./server/acStaticControllerContract.mjs";
|
|
17
17
|
import { registerAuthRoutes } from "./modules/auth/registerAuthRoutes.mjs";
|
|
18
18
|
import { AuthRouter, createAuthRouter } from "./modules/auth/authRouter.mjs";
|
|
19
|
-
import { UserWithGroups, getUserGroups, isAdmin, isMemberOfAllGroups, isMemberOfAnyGroup, requireAdmin, requireGroups } from "./modules/auth/authorizationUtils.mjs";
|
|
20
19
|
import { IconRestControllerConfig, registerIconRestController } from "./modules/icons/iconRestController.mjs";
|
|
21
20
|
import { UpsertIconInput, getAssetByName, upsertIcon, upsertIcons } from "./modules/icons/iconService.mjs";
|
|
22
21
|
import { AssetRestControllerConfig, registerAssetRestController } from "./modules/assets/assetRestController.mjs";
|
|
@@ -27,8 +26,8 @@ import { connectDb, disconnectDb, getDbClient, setDbClient } from "./db/client.m
|
|
|
27
26
|
import { MakeTFromPrismaModel, ObjectKeys, ScalarFilter, ScalarKeys, TableSyncParamsPrisma, tableSyncPrisma } from "./db/tableSyncPrismaAdapter.mjs";
|
|
28
27
|
import { TABLE_SYNC_MAGAZINE, TableSyncMagazine, TableSyncMagazineModelNameKey } from "./db/tableSyncMagazine.mjs";
|
|
29
28
|
import { SyncAppCatalogResult, syncAppCatalog } from "./db/syncAppCatalog.mjs";
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
32
|
-
import {
|
|
29
|
+
import { AcAuthConfig, AcBackendProvider, AcDatabaseConfig, AcFeatureToggles, AcLifecycleHooks, AcMiddlewareOptions, AcMiddlewareResult, MiddlewareContext } from "./middleware/types.mjs";
|
|
30
|
+
import { createAcMiddleware } from "./middleware/createAcMiddleware.mjs";
|
|
31
|
+
import { AcDatabaseManager } from "./middleware/database.mjs";
|
|
33
32
|
import { injectCustomScripts } from "./middleware/htmlInjection.mjs";
|
|
34
|
-
export {
|
|
33
|
+
export { AcAppIndexed, AcAppPageIndexed, AcAppUiIndexed, AcAppsMeta, type AcAuthConfig, AcBackendAppDto, AcBackendAppInput, AcBackendAppUIBaseInput, AcBackendAppUIInput, AcBackendCredentialInput, AcBackendDataFreshness, AcBackendDataSourceInput, AcBackendDataSourceInputCommon, AcBackendDataSourceInputDb, AcBackendDataSourceInputKafka, AcBackendDataVersion, AcBackendDeployableInput, AcBackendDeployment, AcBackendDeploymentInput, AcBackendEnvironmentInput, AcBackendPageInput, type AcBackendProvider, AcBackendTagDescriptionDataIndexed, AcBackendTagFixedTagValue, AcBackendTagsDescriptionDataIndexed, AcBackendUiDefaultsInput, AcBackendVersionsRequestParams, AcBackendVersionsReturn, AcContextIndexed, type AcDatabaseConfig, AcDatabaseManager, AcEnvIndexed, type AcFeatureToggles, type AcLifecycleHooks, AcMetaDictionary, type AcMiddlewareOptions, type AcMiddlewareResult, AcResourceIndexed, type AcStaticControllerContract, type AcTrpcContext, type AcTrpcContextOptions, AppAccessRequest, AppApprovalMethod, AppCatalogCompanySpecificBackend, AppCatalogData, AppCategory, type AppForCatalog, AppRole, ApprovalMethod, ApprovalMethodConfig, ApprovalMethodType, ApprovalUrl, ApproverContact, type AssetRestControllerConfig, type AuthRouter, type BetterAuth, CreateApprovalMethodInput, CustomConfig, GroupingTagDefinition, GroupingTagValue, type IconRestControllerConfig, type MakeTFromPrismaModel, type MiddlewareContext, type ObjectKeys, PersonTeamConfig, ReachOutContact, type ScalarFilter, type ScalarKeys, type ScreenshotRestControllerConfig, ServiceConfig, type SyncAppCatalogResult, type SyncAssetsConfig, TABLE_SYNC_MAGAZINE, type TRPCRouter, type TableSyncMagazine, type TableSyncMagazineModelNameKey, type TableSyncParamsPrisma, Tag, UpdateApprovalMethodInput, type UpsertIconInput, checkAllLinks, connectDb, createAcMiddleware, createAcTrpcContext, createAuth, createAuthRouter, createTrpcRouter, disconnectDb, getAssetByName, getDbClient, injectCustomScripts, printLinkCheckReport, registerAssetRestController, registerAuthRoutes, registerIconRestController, registerScreenshotRestController, setDbClient, staticControllerContract, syncAppCatalog, syncAssets, tableSyncPrisma, upsertIcon, upsertIcons };
|
package/dist/index.mjs
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { connectDb, disconnectDb, getDbClient, setDbClient } from "./db/client.mjs";
|
|
2
2
|
import { createAuthRouter } from "./modules/auth/authRouter.mjs";
|
|
3
|
-
import { getUserGroups, isAdmin, isMemberOfAllGroups, isMemberOfAnyGroup, requireAdmin, requireGroups } from "./modules/auth/authorizationUtils.mjs";
|
|
4
3
|
import { createTrpcRouter } from "./server/controller.mjs";
|
|
5
|
-
import {
|
|
6
|
-
import { staticControllerContract } from "./server/
|
|
4
|
+
import { createAcTrpcContext } from "./server/acTrpcContext.mjs";
|
|
5
|
+
import { staticControllerContract } from "./server/acStaticControllerContract.mjs";
|
|
7
6
|
import { tableSyncPrisma } from "./db/tableSyncPrismaAdapter.mjs";
|
|
8
7
|
import { TABLE_SYNC_MAGAZINE } from "./db/tableSyncMagazine.mjs";
|
|
9
8
|
import { syncAppCatalog } from "./db/syncAppCatalog.mjs";
|
|
@@ -15,8 +14,8 @@ import { registerAssetRestController } from "./modules/assets/assetRestControlle
|
|
|
15
14
|
import { registerScreenshotRestController } from "./modules/assets/screenshotRestController.mjs";
|
|
16
15
|
import { syncAssets } from "./modules/assets/syncAssets.mjs";
|
|
17
16
|
import { checkAllLinks, printLinkCheckReport } from "./modules/appCatalog/checkLinks.mjs";
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
17
|
+
import { AcDatabaseManager } from "./middleware/database.mjs";
|
|
18
|
+
import { createAcMiddleware } from "./middleware/createAcMiddleware.mjs";
|
|
20
19
|
import { injectCustomScripts } from "./middleware/htmlInjection.mjs";
|
|
21
20
|
|
|
22
|
-
export {
|
|
21
|
+
export { AcDatabaseManager, TABLE_SYNC_MAGAZINE, checkAllLinks, connectDb, createAcMiddleware, createAcTrpcContext, createAuth, createAuthRouter, createTrpcRouter, disconnectDb, getAssetByName, getDbClient, injectCustomScripts, printLinkCheckReport, registerAssetRestController, registerAuthRoutes, registerIconRestController, registerScreenshotRestController, setDbClient, staticControllerContract, syncAppCatalog, syncAssets, tableSyncPrisma, upsertIcon, upsertIcons };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"backendResolver.mjs","names":[],"sources":["../../src/middleware/backendResolver.ts"],"sourcesContent":["import type { AppCatalogCompanySpecificBackend } from '../types/backend/companySpecificBackend'\nimport type {
|
|
1
|
+
{"version":3,"file":"backendResolver.mjs","names":[],"sources":["../../src/middleware/backendResolver.ts"],"sourcesContent":["import type { AppCatalogCompanySpecificBackend } from '../types/backend/companySpecificBackend'\nimport type { AcBackendProvider } from './types'\n\n/**\n * Type guard to check if an object implements AppCatalogCompanySpecificBackend.\n */\nfunction isBackendInstance(\n obj: unknown,\n): obj is AppCatalogCompanySpecificBackend {\n return typeof obj === 'object' && obj !== null\n}\n\n/**\n * Normalizes different backend provider types into a consistent async factory function.\n * Supports:\n * - Direct object implementing AppCatalogCompanySpecificBackend\n * - Sync factory function that returns the backend\n * - Async factory function that returns the backend\n */\nexport function createBackendResolver(\n provider: AcBackendProvider,\n): () => Promise<AppCatalogCompanySpecificBackend> {\n // If it's already an object with the required methods, wrap it\n if (isBackendInstance(provider)) {\n return async () => provider\n }\n\n // If it's a function, call it and handle both sync and async results\n if (typeof provider === 'function') {\n return async () => {\n const result = (\n provider as () =>\n | AppCatalogCompanySpecificBackend\n | Promise<AppCatalogCompanySpecificBackend>\n )()\n return result instanceof Promise ? await result : result\n }\n }\n\n throw new Error(\n 'Invalid backend provider: must be an object implementing AppCatalogCompanySpecificBackend or a factory function',\n )\n}\n"],"mappings":";;;;AAMA,SAAS,kBACP,KACyC;AACzC,QAAO,OAAO,QAAQ,YAAY,QAAQ;;;;;;;;;AAU5C,SAAgB,sBACd,UACiD;AAEjD,KAAI,kBAAkB,SAAS,CAC7B,QAAO,YAAY;AAIrB,KAAI,OAAO,aAAa,WACtB,QAAO,YAAY;EACjB,MAAM,SACJ,UAGC;AACH,SAAO,kBAAkB,UAAU,MAAM,SAAS;;AAItD,OAAM,IAAI,MACR,kHACD"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { AcMiddlewareOptions, AcMiddlewareResult } from "./types.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/middleware/createAcMiddleware.d.ts
|
|
4
|
+
declare function createAcMiddleware(options: AcMiddlewareOptions): Promise<AcMiddlewareResult>;
|
|
5
|
+
//#endregion
|
|
6
|
+
export { createAcMiddleware };
|
|
7
|
+
//# sourceMappingURL=createAcMiddleware.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createAcMiddleware.d.mts","names":[],"sources":["../../src/middleware/createAcMiddleware.ts"],"mappings":";;;iBAesB,kBAAA,CACpB,OAAA,EAAS,mBAAA,GACR,OAAA,CAAQ,kBAAA"}
|
|
@@ -1,68 +1,51 @@
|
|
|
1
1
|
import { createTrpcRouter } from "../server/controller.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { createAcTrpcContext } from "../server/acTrpcContext.mjs";
|
|
3
3
|
import { createAuth } from "../modules/auth/auth.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import { AcDatabaseManager } from "./database.mjs";
|
|
5
5
|
import { createBackendResolver } from "./backendResolver.mjs";
|
|
6
6
|
import { createMockUserFromDevConfig } from "../modules/auth/devMockUserUtils.mjs";
|
|
7
7
|
import { registerFeatures } from "./featureRegistry.mjs";
|
|
8
8
|
import express, { Router } from "express";
|
|
9
9
|
import * as trpcExpress from "@trpc/server/adapters/express";
|
|
10
10
|
|
|
11
|
-
//#region src/middleware/
|
|
12
|
-
async function
|
|
11
|
+
//#region src/middleware/createAcMiddleware.ts
|
|
12
|
+
async function createAcMiddleware(options) {
|
|
13
13
|
const basePath = options.basePath ?? "/api";
|
|
14
14
|
const normalizedOptions = {
|
|
15
15
|
...options,
|
|
16
16
|
basePath
|
|
17
17
|
};
|
|
18
|
-
const dbManager = new
|
|
18
|
+
const dbManager = new AcDatabaseManager(options.database);
|
|
19
19
|
dbManager.getClient();
|
|
20
|
-
const auth = createAuth(
|
|
21
|
-
appName: options.auth.appName,
|
|
22
|
-
baseURL: options.auth.baseURL,
|
|
23
|
-
secret: options.auth.secret,
|
|
24
|
-
providers: options.auth.providers,
|
|
25
|
-
plugins: options.auth.plugins,
|
|
26
|
-
sessionExpiresIn: options.auth.sessionExpiresIn,
|
|
27
|
-
sessionUpdateAge: options.auth.sessionUpdateAge
|
|
28
|
-
});
|
|
20
|
+
const auth = createAuth(options.auth.betterAuthOptions);
|
|
29
21
|
const trpcRouter = createTrpcRouter(auth);
|
|
30
22
|
const resolveBackend = createBackendResolver(options.backend);
|
|
31
|
-
const adminGroups = options.auth.adminGroups ?? ["env_hopper_ui_super_admins"];
|
|
32
23
|
const createContext = async ({ req }) => {
|
|
33
24
|
const companySpecificBackend = await resolveBackend();
|
|
34
25
|
let user = null;
|
|
35
|
-
let
|
|
26
|
+
let isAdmin = false;
|
|
36
27
|
if (options.auth.devMockUser) {
|
|
37
28
|
user = createMockUserFromDevConfig(options.auth.devMockUser);
|
|
38
|
-
|
|
29
|
+
isAdmin = true;
|
|
39
30
|
} else try {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
31
|
+
const session = await auth.api.getSession({ headers: req.headers });
|
|
32
|
+
user = session?.user ?? null;
|
|
33
|
+
if (user && session && options.auth.isAdmin) try {
|
|
34
|
+
isAdmin = !!await options.auth.isAdmin(user, session.session, {
|
|
35
|
+
request: req,
|
|
36
|
+
auth
|
|
45
37
|
});
|
|
46
|
-
if (tokenResult.accessToken) {
|
|
47
|
-
const parts = tokenResult.accessToken.split(".");
|
|
48
|
-
if (parts.length === 3 && parts[1]) {
|
|
49
|
-
const groups = JSON.parse(Buffer.from(parts[1], "base64").toString())[options.auth.oktaGroupsClaim];
|
|
50
|
-
userGroups = Array.isArray(groups) ? groups : [];
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
38
|
} catch (error) {
|
|
54
|
-
console.error("[tRPC Context]
|
|
39
|
+
console.error("[tRPC Context] isAdmin callback failed:", error);
|
|
40
|
+
isAdmin = false;
|
|
55
41
|
}
|
|
56
42
|
} catch (error) {
|
|
57
43
|
console.error("[tRPC Context] Failed to get session:", error);
|
|
58
44
|
}
|
|
59
|
-
return
|
|
45
|
+
return createAcTrpcContext({
|
|
60
46
|
companySpecificBackend,
|
|
61
|
-
user
|
|
62
|
-
|
|
63
|
-
groups: userGroups
|
|
64
|
-
} : null,
|
|
65
|
-
adminGroups
|
|
47
|
+
user,
|
|
48
|
+
isAdmin
|
|
66
49
|
});
|
|
67
50
|
};
|
|
68
51
|
const router = Router();
|
|
@@ -71,12 +54,9 @@ async function createEhMiddleware(options) {
|
|
|
71
54
|
auth,
|
|
72
55
|
trpcRouter,
|
|
73
56
|
createContext: async () => {
|
|
74
|
-
return
|
|
75
|
-
companySpecificBackend: await resolveBackend(),
|
|
76
|
-
adminGroups
|
|
77
|
-
});
|
|
57
|
+
return createAcTrpcContext({ companySpecificBackend: await resolveBackend() });
|
|
78
58
|
},
|
|
79
|
-
|
|
59
|
+
isAdmin: options.auth.isAdmin
|
|
80
60
|
};
|
|
81
61
|
if (normalizedOptions.features?.trpc !== false) router.use(`${basePath}/trpc`, trpcExpress.createExpressMiddleware({
|
|
82
62
|
router: trpcRouter,
|
|
@@ -103,5 +83,5 @@ async function createEhMiddleware(options) {
|
|
|
103
83
|
}
|
|
104
84
|
|
|
105
85
|
//#endregion
|
|
106
|
-
export {
|
|
107
|
-
//# sourceMappingURL=
|
|
86
|
+
export { createAcMiddleware };
|
|
87
|
+
//# sourceMappingURL=createAcMiddleware.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createAcMiddleware.mjs","names":[],"sources":["../../src/middleware/createAcMiddleware.ts"],"sourcesContent":["import express, { Router } from 'express'\nimport * as trpcExpress from '@trpc/server/adapters/express'\nimport type {\n AcMiddlewareOptions,\n AcMiddlewareResult,\n MiddlewareContext,\n} from './types'\nimport { AcDatabaseManager } from './database'\nimport { createBackendResolver } from './backendResolver'\nimport { registerFeatures } from './featureRegistry'\nimport { createTrpcRouter } from '../server/controller'\nimport { createAcTrpcContext } from '../server/acTrpcContext'\nimport { createAuth } from '../modules/auth/auth'\nimport { createMockUserFromDevConfig } from '../modules/auth/devMockUserUtils'\n\nexport async function createAcMiddleware(\n options: AcMiddlewareOptions,\n): Promise<AcMiddlewareResult> {\n // Normalize options with defaults\n const basePath = options.basePath ?? '/api'\n const normalizedOptions = { ...options, basePath }\n\n // Initialize database manager\n const dbManager = new AcDatabaseManager(options.database)\n // Initialize the client (which also sets the global singleton)\n dbManager.getClient()\n\n // Create auth instance\n const auth = createAuth(options.auth.betterAuthOptions)\n\n // Create tRPC router\n const trpcRouter = createTrpcRouter(auth)\n\n // Normalize backend provider to async factory function\n const resolveBackend = createBackendResolver(options.backend)\n\n // Create tRPC context factory\n const createContext = async ({\n req,\n }: trpcExpress.CreateExpressContextOptions) => {\n const companySpecificBackend = await resolveBackend()\n\n let user = null\n let isAdmin = false\n\n // Check if dev mock user is configured\n if (options.auth.devMockUser) {\n user = createMockUserFromDevConfig(options.auth.devMockUser)\n isAdmin = true // dev mock always admin\n } else {\n // Extract user from session\n try {\n const session = await auth.api.getSession({\n headers: req.headers as HeadersInit,\n })\n user = session?.user ?? null\n\n // Compute isAdmin via callback\n if (user && session && options.auth.isAdmin) {\n try {\n isAdmin = !!(await options.auth.isAdmin(user, session.session, {\n request: req,\n auth,\n }))\n } catch (error) {\n console.error('[tRPC Context] isAdmin callback failed:', error)\n isAdmin = false\n }\n }\n } catch (error) {\n console.error('[tRPC Context] Failed to get session:', error)\n }\n }\n\n return createAcTrpcContext({\n companySpecificBackend,\n user,\n isAdmin,\n })\n }\n\n // Create Express router\n const router = Router()\n router.use(express.json())\n\n // Build middleware context for feature registration\n const middlewareContext: MiddlewareContext = {\n auth,\n trpcRouter,\n createContext: async () => {\n const companySpecificBackend = await resolveBackend()\n return createAcTrpcContext({\n companySpecificBackend,\n })\n },\n isAdmin: options.auth.isAdmin,\n }\n\n // Register tRPC middleware (if enabled)\n if (normalizedOptions.features?.trpc !== false) {\n router.use(\n `${basePath}/trpc`,\n trpcExpress.createExpressMiddleware({\n router: trpcRouter,\n createContext,\n }),\n )\n }\n\n // Register all enabled features\n registerFeatures(router, normalizedOptions, middlewareContext)\n\n // Call onRoutesRegistered hook if provided\n if (options.hooks?.onRoutesRegistered) {\n await options.hooks.onRoutesRegistered(router)\n }\n\n return {\n router,\n auth,\n trpcRouter,\n\n async connect(): Promise<void> {\n await dbManager.connect()\n if (options.hooks?.onDatabaseConnected) {\n await options.hooks.onDatabaseConnected()\n }\n },\n\n async disconnect(): Promise<void> {\n if (options.hooks?.onDatabaseDisconnecting) {\n await options.hooks.onDatabaseDisconnecting()\n }\n await dbManager.disconnect()\n },\n\n addRoutes(callback: (router: Router) => void): void {\n callback(router)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;AAeA,eAAsB,mBACpB,SAC6B;CAE7B,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,oBAAoB;EAAE,GAAG;EAAS;EAAU;CAGlD,MAAM,YAAY,IAAI,kBAAkB,QAAQ,SAAS;AAEzD,WAAU,WAAW;CAGrB,MAAM,OAAO,WAAW,QAAQ,KAAK,kBAAkB;CAGvD,MAAM,aAAa,iBAAiB,KAAK;CAGzC,MAAM,iBAAiB,sBAAsB,QAAQ,QAAQ;CAG7D,MAAM,gBAAgB,OAAO,EAC3B,UAC6C;EAC7C,MAAM,yBAAyB,MAAM,gBAAgB;EAErD,IAA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EAEnB"}
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import { PrismaClient } from "../generated/prisma/client.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { AcDatabaseConfig } from "./types.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/middleware/database.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Internal database manager used by the middleware.
|
|
7
7
|
* Handles connection URL formatting and lifecycle.
|
|
8
8
|
*/
|
|
9
|
-
declare class
|
|
9
|
+
declare class AcDatabaseManager {
|
|
10
10
|
private client;
|
|
11
11
|
private pool;
|
|
12
12
|
private config;
|
|
13
|
-
constructor(config:
|
|
13
|
+
constructor(config: AcDatabaseConfig);
|
|
14
14
|
/**
|
|
15
15
|
* Get or create the Prisma client instance.
|
|
16
16
|
* Uses lazy initialization for flexibility.
|
|
@@ -20,5 +20,5 @@ declare class EhDatabaseManager {
|
|
|
20
20
|
disconnect(): Promise<void>;
|
|
21
21
|
}
|
|
22
22
|
//#endregion
|
|
23
|
-
export {
|
|
23
|
+
export { AcDatabaseManager };
|
|
24
24
|
//# sourceMappingURL=database.d.mts.map
|
|
@@ -16,7 +16,7 @@ function formatConnectionUrl(config) {
|
|
|
16
16
|
* Internal database manager used by the middleware.
|
|
17
17
|
* Handles connection URL formatting and lifecycle.
|
|
18
18
|
*/
|
|
19
|
-
var
|
|
19
|
+
var AcDatabaseManager = class {
|
|
20
20
|
constructor(config) {
|
|
21
21
|
this.client = null;
|
|
22
22
|
this.pool = null;
|
|
@@ -54,5 +54,5 @@ var EhDatabaseManager = class {
|
|
|
54
54
|
};
|
|
55
55
|
|
|
56
56
|
//#endregion
|
|
57
|
-
export {
|
|
57
|
+
export { AcDatabaseManager };
|
|
58
58
|
//# sourceMappingURL=database.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database.mjs","names":[],"sources":["../../src/middleware/database.ts"],"sourcesContent":["import { PrismaClient } from '../generated/prisma/client'\nimport { PrismaPg } from '@prisma/adapter-pg'\nimport pg from 'pg'\nimport type {
|
|
1
|
+
{"version":3,"file":"database.mjs","names":[],"sources":["../../src/middleware/database.ts"],"sourcesContent":["import { PrismaClient } from '../generated/prisma/client'\nimport { PrismaPg } from '@prisma/adapter-pg'\nimport pg from 'pg'\nimport type { AcDatabaseConfig } from './types'\nimport { setDbClient } from '../db/client'\n\n/**\n * Formats a database connection URL from structured config.\n */\nfunction formatConnectionUrl(config: AcDatabaseConfig): string {\n if ('url' in config) {\n return config.url\n }\n\n const { host, port, database, username, password, schema = 'public' } = config\n return `postgresql://${username}:${encodeURIComponent(password)}@${host}:${port}/${database}?schema=${schema}`\n}\n\n/**\n * Internal database manager used by the middleware.\n * Handles connection URL formatting and lifecycle.\n */\nexport class AcDatabaseManager {\n private client: PrismaClient | null = null\n private pool: pg.Pool | null = null\n private config: AcDatabaseConfig\n\n constructor(config: AcDatabaseConfig) {\n this.config = config\n }\n\n /**\n * Get or create the Prisma client instance.\n * Uses lazy initialization for flexibility.\n */\n getClient(): PrismaClient {\n if (!this.client) {\n const datasourceUrl = formatConnectionUrl(this.config)\n\n // Prisma 7 with adapter: Create pg pool and wrap with adapter\n this.pool = new pg.Pool({ connectionString: datasourceUrl })\n const adapter = new PrismaPg(this.pool)\n\n this.client = new PrismaClient({\n adapter,\n log:\n process.env.NODE_ENV === 'development'\n ? ['warn', 'error']\n : ['warn', 'error'],\n })\n\n // Bridge with existing backend-core getDbClient() usage\n setDbClient(this.client)\n }\n return this.client\n }\n\n async connect(): Promise<void> {\n const client = this.getClient()\n await client.$connect()\n }\n\n async disconnect(): Promise<void> {\n if (this.client) {\n await this.client.$disconnect()\n this.client = null\n }\n if (this.pool) {\n await this.pool.end()\n this.pool = null\n }\n }\n}\n"],"mappings":";;;;;;;;;AASA,SAAS,oBAAoB,QAAkC;AAC7D,KAAI,SAAS,OACX,QAAO,OAAO;CAGhB,MAAM,EAAE,MAAM,MAAM,UAAU,UAAU,UAAU,SAAS,aAAa;AACxE,QAAO,gBAAgB,SAAS,GAAG,mBAAmB,SAAS,CAAC,GAAG,KAAK,GAAG,KAAK,GAAG,SAAS,UAAU;;;;;;AAOxG,IAAa,oBAAb,MAA+B;CAK7B,YAAY,QAA0B;gBAJA;cACP;AAI7B,OAAK,SAAS;;;;;;CAOhB,YAA0B;AACxB,MAAI,CAAC,KAAK,QAAQ;GAChB,MAAM,gBAAgB,oBAAoB,KAAK,OAAO;AAGtD,QAAK,OAAO,IAAI,GAAG,KAAK,EAAE,kBAAkB,eAAe,CAAC;AAG5D,QAAK,SAAS,IAAI,aAAa;IAC7B,SAHc,IAAI,SAAS,KAAK,KAAK;IAIrC,KACE,QAAQ,IAAI,aAAa,gBACrB,CAAC,QAAQ,QAAQ,GACjB,CAAC,QAAQ,QAAQ;IACxB,CAAC;AAGF,eAAY,KAAK,OAAO;;AAE1B,SAAO,KAAK;;CAGd,MAAM,UAAyB;AAE7B,QADe,KAAK,WAAW,CAClB,UAAU;;CAGzB,MAAM,aAA4B;AAChC,MAAI,KAAK,QAAQ;AACf,SAAM,KAAK,OAAO,aAAa;AAC/B,QAAK,SAAS;;AAEhB,MAAI,KAAK,MAAM;AACb,SAAM,KAAK,KAAK,KAAK;AACrB,QAAK,OAAO"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { registerIconRestController } from "../modules/icons/iconRestController.mjs";
|
|
2
|
-
import { getAssetByName } from "../modules/icons/iconService.mjs";
|
|
3
2
|
import { registerAssetRestController } from "../modules/assets/assetRestController.mjs";
|
|
4
3
|
import { registerScreenshotRestController } from "../modules/assets/screenshotRestController.mjs";
|
|
5
4
|
import { createMockSessionResponse } from "../modules/auth/devMockUserUtils.mjs";
|
|
@@ -13,13 +12,26 @@ const FEATURES = [{
|
|
|
13
12
|
const basePath = options.basePath;
|
|
14
13
|
router.get(`${basePath}/auth/session`, async (req, res) => {
|
|
15
14
|
try {
|
|
16
|
-
if (
|
|
17
|
-
res.json(createMockSessionResponse(
|
|
15
|
+
if (options.auth.devMockUser) {
|
|
16
|
+
res.json(createMockSessionResponse(options.auth.devMockUser));
|
|
18
17
|
return;
|
|
19
18
|
}
|
|
20
19
|
const session = await ctx.auth.api.getSession({ headers: req.headers });
|
|
21
|
-
if (session)
|
|
22
|
-
|
|
20
|
+
if (session) {
|
|
21
|
+
let admin = false;
|
|
22
|
+
if (ctx.isAdmin) try {
|
|
23
|
+
admin = !!await ctx.isAdmin(session.user, session.session, {
|
|
24
|
+
request: req,
|
|
25
|
+
auth: ctx.auth
|
|
26
|
+
});
|
|
27
|
+
} catch {
|
|
28
|
+
admin = false;
|
|
29
|
+
}
|
|
30
|
+
res.json({
|
|
31
|
+
...session,
|
|
32
|
+
isAdmin: admin
|
|
33
|
+
});
|
|
34
|
+
} else res.status(401).json({ error: "Not authenticated" });
|
|
23
35
|
} catch (error) {
|
|
24
36
|
console.error("[Auth Session Error]", error);
|
|
25
37
|
res.status(500).json({ error: "Internal server error" });
|
|
@@ -28,31 +40,6 @@ const FEATURES = [{
|
|
|
28
40
|
const authHandler = toNodeHandler(ctx.auth);
|
|
29
41
|
router.all(`${basePath}/auth/{*any}`, authHandler);
|
|
30
42
|
}
|
|
31
|
-
}, {
|
|
32
|
-
name: "legacyIconEndpoint",
|
|
33
|
-
defaultEnabled: false,
|
|
34
|
-
register: (router) => {
|
|
35
|
-
router.get("/static/icon/:icon", async (req, res) => {
|
|
36
|
-
const { icon } = req.params;
|
|
37
|
-
if (!icon || !/^[a-z0-9-]+$/i.test(icon)) {
|
|
38
|
-
res.status(400).send("Invalid icon name");
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
try {
|
|
42
|
-
const dbIcon = await getAssetByName(icon);
|
|
43
|
-
if (!dbIcon) {
|
|
44
|
-
res.status(404).send("Icon not found");
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
res.setHeader("Content-Type", dbIcon.mimeType);
|
|
48
|
-
res.setHeader("Cache-Control", "public, max-age=86400");
|
|
49
|
-
res.send(dbIcon.content);
|
|
50
|
-
} catch (error) {
|
|
51
|
-
console.error("Error fetching icon:", error);
|
|
52
|
-
res.status(404).send("Icon not found");
|
|
53
|
-
}
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
43
|
}];
|
|
57
44
|
/**
|
|
58
45
|
* Registers all enabled features on the router.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"featureRegistry.mjs","names":[],"sources":["../../src/middleware/featureRegistry.ts"],"sourcesContent":["import type { Router } from 'express'\nimport { toNodeHandler } from 'better-auth/node'\nimport type {\n
|
|
1
|
+
{"version":3,"file":"featureRegistry.mjs","names":[],"sources":["../../src/middleware/featureRegistry.ts"],"sourcesContent":["import type { Router } from 'express'\nimport { toNodeHandler } from 'better-auth/node'\nimport type {\n AcFeatureToggles,\n AcMiddlewareOptions,\n MiddlewareContext,\n} from './types'\nimport { registerIconRestController } from '../modules/icons/iconRestController'\nimport { registerAssetRestController } from '../modules/assets/assetRestController'\nimport { registerScreenshotRestController } from '../modules/assets/screenshotRestController'\nimport { createMockSessionResponse } from '../modules/auth/devMockUserUtils'\n\ninterface FeatureRegistration {\n name: keyof AcFeatureToggles\n defaultEnabled: boolean\n register: (\n router: Router,\n options: Required<Pick<AcMiddlewareOptions, 'basePath'>> &\n AcMiddlewareOptions,\n context: MiddlewareContext,\n ) => void\n}\n\n// Optional features that can be toggled\nconst FEATURES: Array<FeatureRegistration> = [\n {\n name: 'auth',\n defaultEnabled: true,\n register: (router, options, ctx) => {\n const basePath = options.basePath\n\n // Explicit session endpoint handler\n router.get(\n `${basePath}/auth/session`,\n async (req, res): Promise<void> => {\n try {\n // Check if dev mock user is configured\n if (options.auth.devMockUser) {\n res.json(createMockSessionResponse(options.auth.devMockUser))\n return\n }\n\n const session = await ctx.auth.api.getSession({\n headers: req.headers as HeadersInit,\n })\n if (session) {\n let admin = false\n if (ctx.isAdmin) {\n try {\n admin = !!(await ctx.isAdmin(session.user, session.session, {\n request: req,\n auth: ctx.auth,\n }))\n } catch {\n admin = false\n }\n }\n res.json({ ...session, isAdmin: admin })\n } else {\n res.status(401).json({ error: 'Not authenticated' })\n }\n } catch (error) {\n console.error('[Auth Session Error]', error)\n res.status(500).json({ error: 'Internal server error' })\n }\n },\n )\n\n // Use toNodeHandler to adapt better-auth for Express/Node.js\n const authHandler = toNodeHandler(ctx.auth)\n router.all(`${basePath}/auth/{*any}`, authHandler)\n },\n },\n]\n\n/**\n * Registers all enabled features on the router.\n */\nexport function registerFeatures(\n router: Router,\n options: Required<Pick<AcMiddlewareOptions, 'basePath'>> &\n AcMiddlewareOptions,\n context: MiddlewareContext,\n): void {\n const basePath = options.basePath\n\n // Always-on features (required for core functionality)\n\n // Icons\n registerIconRestController(router, {\n basePath: `${basePath}/icons`,\n })\n\n // Assets\n registerAssetRestController(router, {\n basePath: `${basePath}/assets`,\n })\n\n // Screenshots\n registerScreenshotRestController(router, {\n basePath: `${basePath}/screenshots`,\n })\n\n // Optional toggleable features\n const toggles = options.features || {}\n\n for (const feature of FEATURES) {\n const isEnabled = toggles[feature.name] ?? feature.defaultEnabled\n\n if (isEnabled) {\n feature.register(router, options, context)\n }\n }\n}\n"],"mappings":";;;;;;;AAwBA,MAAM,WAAuC,CAC3C;CACE,MAAM;CACN,gBAAgB;CAChB,WAAW,QAAQ,SAAS,QAAQ;EAClC,MAAM,WAAW,QAAQ;AAGzB,SAAO,IACL,GAAG,SAAS,gBACZ,OAAO,KAAK,QAAuB;AACjC,OAAI;AAEF,QAAI,QAAQ,KAAK,aAAa;AAC5B,SAAI,KAAK,0BAA0B,QAAQ,KAAK,YAAY,CAAC;AAC7D;;IAGF,MAAM,UAAU,MAAM,IAAI,KAAK,IAAI,WAAW,EAC5C,SAAS,IAAI,SACd,CAAC;AACF,QAAI,SAAS;KACX,IAAI,QAAQ;AACZ,SAAI,IAAI,QACN,KAAI;AACF,cAAQ,CAAC,CAAE,MAAM,IAAI,QAAQ,QAAQ,MAAM,QAAQ,SAAS;OAC1D,SAAS;OACT,MAAM,IAAI;OACX,CAAC;aACI;AACN,cAAQ;;AAGZ,SAAI,KAAK;MAAE,GAAG;MAAS,SAAS;MAAO,CAAC;UAExC,KAAI,OAAO,IAAI,CAAC,KAAK,EAAE,OAAO,qBAAqB,CAAC;YAE/C,OAAO;AACd,YAAQ,MAAM,wBAAwB,MAAM;AAC5C,QAAI,OAAO,IAAI,CAAC,KAAK,EAAE,OAAO,yBAAyB,CAAC;;IAG7D;EAGD,MAAM,cAAc,cAAc,IAAI,KAAK;AAC3C,SAAO,IAAI,GAAG,SAAS,eAAe,YAAY;;CAErD,CACF;;;;AAKD,SAAgB,iBACd,QACA,SAEA,SACM;CACN,MAAM,WAAW,QAAQ;AAKzB,4BAA2B,QAAQ,EACjC,UAAU,GAAG,SAAS,SACvB,CAAC;AAGF,6BAA4B,QAAQ,EAClC,UAAU,GAAG,SAAS,UACvB,CAAC;AAGF,kCAAiC,QAAQ,EACvC,UAAU,GAAG,SAAS,eACvB,CAAC;CAGF,MAAM,UAAU,QAAQ,YAAY,EAAE;AAEtC,MAAK,MAAM,WAAW,SAGpB,KAFkB,QAAQ,QAAQ,SAAS,QAAQ,eAGjD,SAAQ,SAAS,QAAQ,SAAS,QAAQ"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { AcAdminChatConfig, AcAuthConfig, AcBackendProvider, AcDatabaseConfig, AcFeatureToggles, AcLifecycleHooks, AcMiddlewareOptions, AcMiddlewareResult, MiddlewareContext } from "./types.mjs";
|
|
2
|
+
import { createAcMiddleware } from "./createAcMiddleware.mjs";
|
|
3
|
+
import { AcDatabaseManager } from "./database.mjs";
|
|
4
4
|
import { injectCustomScripts } from "./htmlInjection.mjs";
|