import express from 'express';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { h as closeConnection, i as handler$1 } from './api/admin/create-upload-progress-table/POST-C-OoiMoW.js';
import 'mysql2/promise';
import path from 'path';
import { fileURLToPath } from 'url';
import { h as handler$2 } from './api/admin/reset-database/POST-D8YiZje3.js';
import { h as handler$3 } from './api/admin/setup-database/POST-Dl4OLjKJ.js';
import { h as handler$4 } from './api/auth/check-admin/GET-zBNiPDKV.js';
import { h as handler$5 } from './api/auth/current-user/GET-ClfS11M5.js';
import { h as handler$6 } from './api/auth/login/POST-DtvZoPxO.js';
import { h as handler$7 } from './api/auth/logout/POST-DFT0d3Nh.js';
import { h as handler$8 } from './api/auth/setup/POST-DYMc2GPx.js';
import { h as handler$9 } from './api/backup/delete/_backupId_/DELETE-CSeC5rJf.js';
import { h as handler$a } from './api/backup/download/_backupId_/GET-lvzGmOga.js';
import { h as handler$b } from './api/backup/download-decrypted/_backupId_/GET-D4n5HIiX.js';
import { h as handler$c } from './api/backup/list/GET-CNL7vGCK.js';
import { h as handler$d } from './api/backup/progress/GET-BxPiaqMg.js';
import { h as handler$e } from './api/backup/progress/_backupId_/GET-hKxr92Ul.js';
import { h as handler$f } from './api/backup/start/POST-CjputTaS.js';
import { h as handler$g } from './api/backup/upload/POST-yynPqibf.js';
import { h as handler$h } from './api/backup/upload-chunk/POST-7YMKNIbZ.js';
import { h as handler$i } from './api/backup/upload-encrypted/POST-CK3RHV5H.js';
import { h as handler$j } from './api/backup/verify/_backupId_/POST-CwrjXgbS.js';
import { h as handler$k } from './api/backup/_backupId_/GET-CsDlHD41.js';
import { h as handler$l } from './api/commerce/create-checkout-session/POST-vy5ncz3K.js';
import { h as handler$m } from './api/communication/command/POST-ui_yqQAe.js';
import { h as handler$n } from './api/communication/commands/_deviceId_/GET-BYyPE68j.js';
import { h as handler$o } from './api/communication/messages/GET-5e13has_.js';
import { h as handler$p } from './api/communication/notify/POST-mX5YSm-N.js';
import { h as handler$q } from './api/communication/send/POST-Dh2gYnW6.js';
import { h as handler$r } from './api/devices/GET-BLYWoh18.js';
import handler$s from './api/devices/generate-token/POST-Dc5FOr6V.js';
import { h as handler$t } from './api/devices/pair/POST-F5wrq3Z4.js';
import { h as handler$u } from './api/devices/_deviceId_/GET-CRFYQdXK.js';
import { h as handler$v } from './api/devices/_deviceId_/DELETE-DR2iHsIO.js';
import { h as handler$w } from './api/devices/_deviceId_/backup-status/GET-CdhHjwGn.js';
import { h as handler$x } from './api/download/package/GET-C7l-R_ED.js';
import { h as handler$y } from './api/encryption/generate-key/POST-DLDjwZHK.js';
import { h as handler$z } from './api/health/GET-BZW5-h5w.js';
import { h as handler$A } from './api/schedules/GET-BjmvmEKz.js';
import { h as handler$B } from './api/schedules/POST-BkjWJje3.js';
import { h as handler$C } from './api/servers/GET-ycyKdfid.js';
import { h as handler$D } from './api/servers/register/POST-J1lga3sB.js';
import { h as handler$E } from './api/servers/_serverId_/GET-BFYKjws5.js';
import { h as handler$F } from './api/servers/_serverId_/allocate/POST-CYUCjMf-.js';
import { h as handler$G } from './api/servers/_serverId_/ping/POST-QR4UAR6q.js';
import { h as handler$H } from './api/setup/complete/POST-DdXbvhvo.js';
import { h as handler$I } from './api/setup/reset/POST-PZWBQW2B.js';
import { h as handler$J } from './api/setup/status/GET-BzgU-9Gs.js';
import { h as handler$K } from './api/storage/config/GET-Dflu_nCq.js';
import { h as handler$L } from './api/storage/config/POST-CLUQM3oz.js';
import { h as handler$M } from './api/storage/disk-space/GET-zAIvJcZS.js';
import { h as handler$N } from './api/storage/drives/GET-BhXCKrcb.js';
import { h as handler$O } from './api/storage/limits/GET-Yimaixn0.js';
import { h as handler$P } from './api/storage/limits/POST-Cf4xW1Lz.js';
import { h as handler$Q } from './api/storage/test/POST-CAh1_2yz.js';
import { h as handler$R } from './api/version/GET-rV9lXEPv.js';

function loadEnvFile() {
  const envPath = join(process.cwd(), ".env");
  if (!existsSync(envPath)) {
    console.warn("Warning: .env file not found at", envPath);
    return;
  }
  const envContent = readFileSync(envPath, "utf-8");
  let loadedCount = 0;
  envContent.split("\n").forEach((line) => {
    const match = line.match(/^([^=:#]+)=(.*)$/);
    if (match) {
      const key = match[1].trim();
      const value = match[2].trim().replace(/^["']|["']$/g, "");
      if (!process.env[key]) {
        process.env[key] = value;
        loadedCount++;
      }
    }
  });
  if (loadedCount > 0) {
    console.log(`Loaded ${loadedCount} environment variables from .env`);
  }
}
loadEnvFile();

// Load environment variables FIRST before any other imports

const __filename$1 = fileURLToPath(import.meta.url);
path.dirname(__filename$1);

// ---------------------------------------------------------------------------
// Structured request logger
// ---------------------------------------------------------------------------
function requestLogger(req, res, next) {
  const start = Date.now();
  res.on('finish', () => {
    const ms = Date.now() - start;
    const level = res.statusCode >= 500 ? 'ERROR' : res.statusCode >= 400 ? 'WARN' : 'INFO';
    process.stdout.write(JSON.stringify({
      level,
      time: new Date().toISOString(),
      method: req.method,
      url: req.url,
      status: res.statusCode,
      duration_ms: ms,
      ip: req.ip || req.socket?.remoteAddress || 'unknown'
    }) + '\n');
  });
  next();
}

// ---------------------------------------------------------------------------
// In-memory rate limiter (no external dependencies required)
// ---------------------------------------------------------------------------
function createRateLimiter({ windowMs, max, message }) {
  const store = new Map();
  // Periodic GC so the map doesn't grow unbounded
  const gc = setInterval(() => {
    const now = Date.now();
    for (const [key, data] of store.entries()) {
      if (now > data.resetTime) store.delete(key);
    }
  }, windowMs);
  if (gc.unref) gc.unref(); // don't keep the process alive for cleanup alone

  return (req, res, next) => {
    const ip = req.ip || req.socket?.remoteAddress || 'unknown';
    const key = ip + ':' + req.path;
    const now = Date.now();
    const entry = store.get(key);

    if (!entry || now > entry.resetTime) {
      store.set(key, { count: 1, resetTime: now + windowMs });
      return next();
    }
    if (entry.count >= max) {
      const retryAfter = Math.ceil((entry.resetTime - now) / 1000);
      res.setHeader('Retry-After', String(retryAfter));
      return res.status(429).json({ success: false, error: message });
    }
    entry.count++;
    next();
  };
}

const authLoginLimiter = createRateLimiter({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 10,
  message: 'Too many login attempts. Please try again in 15 minutes.'
});

const authSetupLimiter = createRateLimiter({
  windowMs: 60 * 60 * 1000, // 1 hour
  max: 5,
  message: 'Too many setup attempts. Please try again in 1 hour.'
});

const devicePairLimiter = createRateLimiter({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 20,
  message: 'Too many pairing attempts. Please try again in 15 minutes.'
});

// ServerHook - runs when API server starts
const serverBefore = async (server) => {
  // DISABLED: Auto-setup removed to allow manual installation control
  // Users must run the installer (install/fresh-install.sh or npm run install-cloudvault)
  // This prevents automatic directory/table creation that bypasses the installer
  
  // Storage directories are created by the installer, not on server startup
  // Database tables are created by the installer, not on server startup
  
  // console.log('[Auto-Setup] Initializing storage directories...');
  // try {
  //   initializeDirectories();
  //   const pathInfo = getPathInfo();
  //   console.log('[Auto-Setup] ✓ Storage directories initialized:');
  //   console.log(`[Auto-Setup]   - App Data: ${pathInfo.appDataDir}`);
  //   console.log(`[Auto-Setup]   - Backups: ${pathInfo.backupsDir}`);
  //   console.log(`[Auto-Setup]   - Temp: ${pathInfo.tempDir}`);
  //   console.log(`[Auto-Setup]   - Logs: ${pathInfo.logsDir}`);
  // } catch (error) {
  //   console.error('[Auto-Setup] ✗ Failed to initialize directories:', error.message);
  // }
  
  // configureDatabase().catch(err => {
  //   console.error('[Auto-Setup] Database configuration failed, but server will continue:', err.message);
  // });

  const shutdown = async (signal) => {
    console.log(`Got ${signal}, shutting down gracefully...`);

    try {
      // Close database connection pool before exiting
      await closeConnection();
      console.log('Database connections closed');
    } catch (error) {
      console.error('Error closing database connections:', error);
    }

    process.exit(0);
  };

  ['SIGTERM', 'SIGINT'].forEach((signal) => {
    process.on(signal, shutdown);
  });

  server.use(express.json());
  server.use(express.urlencoded({ extended: true }));

  // Structured request logging (every request)
  server.use(requestLogger);

  // Route-specific rate limiters
  server.post('/auth/login/', authLoginLimiter);
  server.post('/auth/setup/', authSetupLimiter);
  server.post('/devices/pair/', devicePairLimiter);
};

const serverAfter = (server) => {
  const errorHandler = (err, req, res, next) => {
    if (err instanceof Error) {
      res.status(500).json({ error: err.message });
    } else {
      next(err);
    }
  };
  server.use(errorHandler);
};

// Public RESTful API Methods and Paths
// This section describes the available HTTP methods and their corresponding endpoints (paths).
// POST   /api/admin/create-upload-progress-table/     src/server/api/admin/create-upload-progress-table/POST.ts
// POST   /api/admin/reset-database/                   src/server/api/admin/reset-database/POST.ts
// POST   /api/admin/setup-database/                   src/server/api/admin/setup-database/POST.ts
// GET    /api/auth/check-admin/                       src/server/api/auth/check-admin/GET.ts
// GET    /api/auth/current-user/                      src/server/api/auth/current-user/GET.ts
// POST   /api/auth/login/                             src/server/api/auth/login/POST.ts
// POST   /api/auth/logout/                            src/server/api/auth/logout/POST.ts
// POST   /api/auth/setup/                             src/server/api/auth/setup/POST.ts
// DELETE /api/backup/delete/:backupId/                src/server/api/backup/delete/[backupId]/DELETE.ts
// GET    /api/backup/download/:backupId/              src/server/api/backup/download/[backupId]/GET.ts
// GET    /api/backup/download-decrypted/:backupId/    src/server/api/backup/download-decrypted/[backupId]/GET.ts
// GET    /api/backup/list/                            src/server/api/backup/list/GET.ts
// GET    /api/backup/progress/                        src/server/api/backup/progress/GET.ts
// GET    /api/backup/progress/:backupId/              src/server/api/backup/progress/[backupId]/GET.ts
// POST   /api/backup/start/                           src/server/api/backup/start/POST.ts
// POST   /api/backup/upload/                          src/server/api/backup/upload/POST.ts
// POST   /api/backup/upload-chunk/                    src/server/api/backup/upload-chunk/POST.ts
// POST   /api/backup/upload-encrypted/                src/server/api/backup/upload-encrypted/POST.ts
// POST   /api/backup/verify/:backupId/                src/server/api/backup/verify/[backupId]/POST.ts
// GET    /api/backup/:backupId/                       src/server/api/backup/[backupId]/GET.ts
// POST   /api/commerce/create-checkout-session/       src/server/api/commerce/create-checkout-session/POST.ts
// POST   /api/communication/command/                  src/server/api/communication/command/POST.ts
// GET    /api/communication/commands/:deviceId/       src/server/api/communication/commands/[deviceId]/GET.ts
// GET    /api/communication/messages/                 src/server/api/communication/messages/GET.ts
// POST   /api/communication/notify/                   src/server/api/communication/notify/POST.ts
// POST   /api/communication/send/                     src/server/api/communication/send/POST.ts
// GET    /api/devices/                                src/server/api/devices/GET.ts
// POST   /api/devices/generate-token/                 src/server/api/devices/generate-token/POST.ts
// POST   /api/devices/pair/                           src/server/api/devices/pair/POST.ts
// GET    /api/devices/:deviceId/                      src/server/api/devices/[deviceId]/GET.ts
// DELETE /api/devices/:deviceId/                      src/server/api/devices/[deviceId]/DELETE.ts
// GET    /api/devices/:deviceId/backup-status/        src/server/api/devices/[deviceId]/backup-status/GET.ts
// GET    /api/download/package/                       src/server/api/download/package/GET.ts
// POST   /api/encryption/generate-key/                src/server/api/encryption/generate-key/POST.ts
// GET    /api/health/                                 src/server/api/health/GET.ts
// GET    /api/schedules/                              src/server/api/schedules/GET.ts
// POST   /api/schedules/                              src/server/api/schedules/POST.ts
// GET    /api/servers/                                src/server/api/servers/GET.ts
// POST   /api/servers/register/                       src/server/api/servers/register/POST.ts
// GET    /api/servers/:serverId/                      src/server/api/servers/[serverId]/GET.ts
// POST   /api/servers/:serverId/allocate/             src/server/api/servers/[serverId]/allocate/POST.ts
// POST   /api/servers/:serverId/ping/                 src/server/api/servers/[serverId]/ping/POST.ts
// POST   /api/setup/complete/                         src/server/api/setup/complete/POST.ts
// POST   /api/setup/reset/                            src/server/api/setup/reset/POST.ts
// GET    /api/setup/status/                           src/server/api/setup/status/GET.ts
// GET    /api/storage/config/                         src/server/api/storage/config/GET.ts
// POST   /api/storage/config/                         src/server/api/storage/config/POST.ts
// GET    /api/storage/disk-space/                     src/server/api/storage/disk-space/GET.ts
// GET    /api/storage/drives/                         src/server/api/storage/drives/GET.ts
// GET    /api/storage/limits/                         src/server/api/storage/limits/GET.ts
// POST   /api/storage/limits/                         src/server/api/storage/limits/POST.ts
// POST   /api/storage/test/                           src/server/api/storage/test/POST.ts
// GET    /api/version/                                src/server/api/version/GET.ts

const internal  = [
  handler$1  && { cb: handler$1 , method: "post"   , route: "/admin/create-upload-progress-table/"  , url: "/api/admin/create-upload-progress-table/"  , source: "src/server/api/admin/create-upload-progress-table/POST.ts"  },
  handler$2  && { cb: handler$2 , method: "post"   , route: "/admin/reset-database/"                , url: "/api/admin/reset-database/"                , source: "src/server/api/admin/reset-database/POST.ts"                },
  handler$3  && { cb: handler$3 , method: "post"   , route: "/admin/setup-database/"                , url: "/api/admin/setup-database/"                , source: "src/server/api/admin/setup-database/POST.ts"                },
  handler$4  && { cb: handler$4 , method: "get"    , route: "/auth/check-admin/"                    , url: "/api/auth/check-admin/"                    , source: "src/server/api/auth/check-admin/GET.ts"                     },
  handler$5  && { cb: handler$5 , method: "get"    , route: "/auth/current-user/"                   , url: "/api/auth/current-user/"                   , source: "src/server/api/auth/current-user/GET.ts"                    },
  handler$6  && { cb: handler$6 , method: "post"   , route: "/auth/login/"                          , url: "/api/auth/login/"                          , source: "src/server/api/auth/login/POST.ts"                          },
  handler$7  && { cb: handler$7 , method: "post"   , route: "/auth/logout/"                         , url: "/api/auth/logout/"                         , source: "src/server/api/auth/logout/POST.ts"                         },
  handler$8  && { cb: handler$8 , method: "post"   , route: "/auth/setup/"                          , url: "/api/auth/setup/"                          , source: "src/server/api/auth/setup/POST.ts"                          },
  handler$9  && { cb: handler$9 , method: "delete" , route: "/backup/delete/:backupId/"             , url: "/api/backup/delete/:backupId/"             , source: "src/server/api/backup/delete/[backupId]/DELETE.ts"          },
  handler$a  && { cb: handler$a , method: "get"    , route: "/backup/download/:backupId/"           , url: "/api/backup/download/:backupId/"           , source: "src/server/api/backup/download/[backupId]/GET.ts"           },
  handler$b  && { cb: handler$b , method: "get"    , route: "/backup/download-decrypted/:backupId/" , url: "/api/backup/download-decrypted/:backupId/" , source: "src/server/api/backup/download-decrypted/[backupId]/GET.ts" },
  handler$c  && { cb: handler$c , method: "get"    , route: "/backup/list/"                         , url: "/api/backup/list/"                         , source: "src/server/api/backup/list/GET.ts"                          },
  handler$d  && { cb: handler$d , method: "get"    , route: "/backup/progress/"                     , url: "/api/backup/progress/"                     , source: "src/server/api/backup/progress/GET.ts"                      },
  handler$e  && { cb: handler$e , method: "get"    , route: "/backup/progress/:backupId/"           , url: "/api/backup/progress/:backupId/"           , source: "src/server/api/backup/progress/[backupId]/GET.ts"           },
  handler$f  && { cb: handler$f , method: "post"   , route: "/backup/start/"                        , url: "/api/backup/start/"                        , source: "src/server/api/backup/start/POST.ts"                        },
  handler$g  && { cb: handler$g , method: "post"   , route: "/backup/upload/"                       , url: "/api/backup/upload/"                       , source: "src/server/api/backup/upload/POST.ts"                       },
  handler$h  && { cb: handler$h , method: "post"   , route: "/backup/upload-chunk/"                 , url: "/api/backup/upload-chunk/"                 , source: "src/server/api/backup/upload-chunk/POST.ts"                 },
  handler$i  && { cb: handler$i , method: "post"   , route: "/backup/upload-encrypted/"             , url: "/api/backup/upload-encrypted/"             , source: "src/server/api/backup/upload-encrypted/POST.ts"             },
  handler$j  && { cb: handler$j , method: "post"   , route: "/backup/verify/:backupId/"             , url: "/api/backup/verify/:backupId/"             , source: "src/server/api/backup/verify/[backupId]/POST.ts"            },
  handler$k  && { cb: handler$k , method: "get"    , route: "/backup/:backupId/"                    , url: "/api/backup/:backupId/"                    , source: "src/server/api/backup/[backupId]/GET.ts"                    },
  handler$l  && { cb: handler$l , method: "post"   , route: "/commerce/create-checkout-session/"    , url: "/api/commerce/create-checkout-session/"    , source: "src/server/api/commerce/create-checkout-session/POST.ts"    },
  handler$m  && { cb: handler$m , method: "post"   , route: "/communication/command/"               , url: "/api/communication/command/"               , source: "src/server/api/communication/command/POST.ts"               },
  handler$n  && { cb: handler$n , method: "get"    , route: "/communication/commands/:deviceId/"    , url: "/api/communication/commands/:deviceId/"    , source: "src/server/api/communication/commands/[deviceId]/GET.ts"    },
  handler$o  && { cb: handler$o , method: "get"    , route: "/communication/messages/"              , url: "/api/communication/messages/"              , source: "src/server/api/communication/messages/GET.ts"               },
  handler$p  && { cb: handler$p , method: "post"   , route: "/communication/notify/"                , url: "/api/communication/notify/"                , source: "src/server/api/communication/notify/POST.ts"                },
  handler$q  && { cb: handler$q , method: "post"   , route: "/communication/send/"                  , url: "/api/communication/send/"                  , source: "src/server/api/communication/send/POST.ts"                  },
  handler$r  && { cb: handler$r , method: "get"    , route: "/devices/"                             , url: "/api/devices/"                             , source: "src/server/api/devices/GET.ts"                              },
  handler$s  && { cb: handler$s , method: "post"   , route: "/devices/generate-token/"              , url: "/api/devices/generate-token/"              , source: "src/server/api/devices/generate-token/POST.ts"              },
  handler$t  && { cb: handler$t , method: "post"   , route: "/devices/pair/"                        , url: "/api/devices/pair/"                        , source: "src/server/api/devices/pair/POST.ts"                        },
  handler$u  && { cb: handler$u , method: "get"    , route: "/devices/:deviceId/"                   , url: "/api/devices/:deviceId/"                   , source: "src/server/api/devices/[deviceId]/GET.ts"                   },
  handler$v  && { cb: handler$v , method: "delete" , route: "/devices/:deviceId/"                   , url: "/api/devices/:deviceId/"                   , source: "src/server/api/devices/[deviceId]/DELETE.ts"                },
  handler$w  && { cb: handler$w , method: "get"    , route: "/devices/:deviceId/backup-status/"     , url: "/api/devices/:deviceId/backup-status/"     , source: "src/server/api/devices/[deviceId]/backup-status/GET.ts"     },
  handler$x  && { cb: handler$x , method: "get"    , route: "/download/package/"                    , url: "/api/download/package/"                    , source: "src/server/api/download/package/GET.ts"                     },
  handler$y  && { cb: handler$y , method: "post"   , route: "/encryption/generate-key/"             , url: "/api/encryption/generate-key/"             , source: "src/server/api/encryption/generate-key/POST.ts"             },
  handler$z  && { cb: handler$z , method: "get"    , route: "/health/"                              , url: "/api/health/"                              , source: "src/server/api/health/GET.ts"                               },
  handler$A  && { cb: handler$A , method: "get"    , route: "/schedules/"                           , url: "/api/schedules/"                           , source: "src/server/api/schedules/GET.ts"                            },
  handler$B  && { cb: handler$B , method: "post"   , route: "/schedules/"                           , url: "/api/schedules/"                           , source: "src/server/api/schedules/POST.ts"                           },
  handler$C  && { cb: handler$C , method: "get"    , route: "/servers/"                             , url: "/api/servers/"                             , source: "src/server/api/servers/GET.ts"                              },
  handler$D  && { cb: handler$D , method: "post"   , route: "/servers/register/"                    , url: "/api/servers/register/"                    , source: "src/server/api/servers/register/POST.ts"                    },
  handler$E  && { cb: handler$E , method: "get"    , route: "/servers/:serverId/"                   , url: "/api/servers/:serverId/"                   , source: "src/server/api/servers/[serverId]/GET.ts"                   },
  handler$F  && { cb: handler$F , method: "post"   , route: "/servers/:serverId/allocate/"          , url: "/api/servers/:serverId/allocate/"          , source: "src/server/api/servers/[serverId]/allocate/POST.ts"         },
  handler$G  && { cb: handler$G , method: "post"   , route: "/servers/:serverId/ping/"              , url: "/api/servers/:serverId/ping/"              , source: "src/server/api/servers/[serverId]/ping/POST.ts"             },
  handler$H  && { cb: handler$H , method: "post"   , route: "/setup/complete/"                      , url: "/api/setup/complete/"                      , source: "src/server/api/setup/complete/POST.ts"                      },
  handler$I  && { cb: handler$I , method: "post"   , route: "/setup/reset/"                         , url: "/api/setup/reset/"                         , source: "src/server/api/setup/reset/POST.ts"                         },
  handler$J  && { cb: handler$J , method: "get"    , route: "/setup/status/"                        , url: "/api/setup/status/"                        , source: "src/server/api/setup/status/GET.ts"                         },
  handler$K  && { cb: handler$K , method: "get"    , route: "/storage/config/"                      , url: "/api/storage/config/"                      , source: "src/server/api/storage/config/GET.ts"                       },
  handler$L  && { cb: handler$L , method: "post"   , route: "/storage/config/"                      , url: "/api/storage/config/"                      , source: "src/server/api/storage/config/POST.ts"                      },
  handler$M  && { cb: handler$M , method: "get"    , route: "/storage/disk-space/"                  , url: "/api/storage/disk-space/"                  , source: "src/server/api/storage/disk-space/GET.ts"                   },
  handler$N  && { cb: handler$N , method: "get"    , route: "/storage/drives/"                      , url: "/api/storage/drives/"                      , source: "src/server/api/storage/drives/GET.ts"                       },
  handler$O  && { cb: handler$O , method: "get"    , route: "/storage/limits/"                      , url: "/api/storage/limits/"                      , source: "src/server/api/storage/limits/GET.ts"                       },
  handler$P  && { cb: handler$P , method: "post"   , route: "/storage/limits/"                      , url: "/api/storage/limits/"                      , source: "src/server/api/storage/limits/POST.ts"                      },
  handler$Q  && { cb: handler$Q , method: "post"   , route: "/storage/test/"                        , url: "/api/storage/test/"                        , source: "src/server/api/storage/test/POST.ts"                        },
  handler$R  && { cb: handler$R , method: "get"    , route: "/version/"                             , url: "/api/version/"                             , source: "src/server/api/version/GET.ts"                              }
].filter(it => it);

internal.map((it) => {
  const { method, route, url, source } = it;
  return { method, url, route, source };
});

internal.map(
  (it) => it.method?.toUpperCase() + "\t" + it.url
);

const applyRouters = (applyRouter) => {
  internal.forEach((it) => {
    it.cb = it.cb;
    applyRouter(it);
  });
};

// src/api-server/handler.ts
var handler = express();
applyRouters((props) => {
  const { method, route, path, cb } = props;
  if (handler[method]) {
    if (Array.isArray(cb)) {
      handler[method](route, ...cb);
    } else {
      handler[method](route, cb);
    }
  } else {
    console.log("Not Support", method, "for", route, "in", handler);
  }
});

export { serverAfter as a, handler as h, serverBefore as s };
