'use strict';

var path = require('path');
var url = require('url');
var deployer = require('@mastra/deployer');
var esm = require('fs-extra/esm');
var os = require('os');
var fs = require('fs');
var error = require('@mastra/core/error');
var stream = require('stream');
var execa = require('execa');
var logger$1 = require('@mastra/core/logger');
var loggers = require('@mastra/loggers');
var redis = require('redis');

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var os__default = /*#__PURE__*/_interopDefault(os);
var fs__namespace = /*#__PURE__*/_interopNamespace(fs);

// src/index.ts

// src/utils/auth.ts
function getAuthEntrypoint() {
  const tokensObject = {};
  if (process.env.PLAYGROUND_JWT_TOKEN) {
    tokensObject[process.env.PLAYGROUND_JWT_TOKEN] = { id: "business-api", role: "api" };
  }
  if (process.env.BUSINESS_JWT_TOKEN) {
    tokensObject[process.env.BUSINESS_JWT_TOKEN] = { id: "business-api", role: "api" };
  }
  return `
  import { SimpleAuth, CompositeAuth } from '@mastra/core/server';
  import { MastraCloudAuthProvider, MastraRBACCloud } from '@mastra/auth-cloud';

  // Service token auth (for business-api, playground internal calls)
  class MastraCloudServiceAuth extends SimpleAuth {
    constructor() {
      super({
        tokens: ${JSON.stringify(tokensObject)}
      });
    }

    async authorizeUser(user, request) {
      // Allow access to /api path
      if (request && request.url && new URL(request.url).pathname === '/api') {
        return true;
      }
      // Allow access for business-api users
      if (user && user.id === 'business-api') {
        return true;
      }
      return false;
    }
  }

  const serviceAuth = new MastraCloudServiceAuth();

  // Cloud user auth (for end users via OAuth)
  // Only enabled if MASTRA_CLOUD_API_URL is set
  let cloudUserAuth = null;
  if (process.env.MASTRA_CLOUD_API_URL) {
    cloudUserAuth = new MastraCloudAuthProvider({
      projectId: process.env.PROJECT_ID,
      cloudBaseUrl: process.env.MASTRA_CLOUD_API_URL,
      callbackUrl: process.env.MASTRA_CLOUD_CALLBACK_URL || \`\${process.env.MASTRA_CLOUD_API_URL}/auth/callback\`,
    });
  }

  const serverConfig = mastra.getServer();
  const userAuth = serverConfig?.auth;

  // Only enable auth if cloudUserAuth or userAuth are defined
  if (serverConfig && (cloudUserAuth || userAuth)) {
    // Build provider list: service auth first, then cloud user auth, then user's custom auth
    const providers = [serviceAuth];
    if (cloudUserAuth) {
      providers.push(cloudUserAuth);
    }
    if (userAuth) {
      providers.push(userAuth);
    }

    serverConfig.auth = new CompositeAuth(providers);

    // If cloud auth is enabled but no RBAC is configured, add default cloud RBAC
    if (cloudUserAuth && !serverConfig.rbac) {
      serverConfig.rbac = new MastraRBACCloud({
        roleMapping: {
          owner: ['*'],
          admin: ['*:read', '*:write', '*:execute'],
          api: ['*:read', '*:write', '*:execute'],
          member: ['*:read', '*:execute'],
          viewer: ['*:read'],
          _default: [],
        },
      });
    }
  }
  `;
}
var LOCAL = process.env.LOCAL === "true";
var TEAM_ID = process.env.TEAM_ID ?? "";
var PROJECT_ID = process.env.PROJECT_ID ?? "";
var BUILD_ID = process.env.BUILD_ID ?? "";
var BUILD_URL = process.env.BUILD_URL ?? "";
var LOG_REDIS_URL = process.env.LOG_REDIS_URL ?? "redis://localhost:6379";
var USER_IP_ADDRESS = process.env.USER_IP_ADDRESS ?? "";
var MASTRA_DIRECTORY = process.env.MASTRA_DIRECTORY ?? "src/mastra";
var PROJECT_ENV_VARS = safelyParseJson(process.env.PROJECT_ENV_VARS ?? "{}");
LOCAL ? os__default.default.tmpdir() + "/project" : process.env.PROJECT_ROOT ?? "/project";
function safelyParseJson(json) {
  try {
    return JSON.parse(json);
  } catch {
    return {};
  }
}
var redisClient = redis.createClient({
  url: LOG_REDIS_URL
});
var RedisTransport = class extends logger$1.LoggerTransport {
  _transform(chunk, _encoding, callback) {
    chunk = chunk.toString();
    const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;
    const ttl = 2 * 24 * 60 * 60;
    const logData = typeof chunk === "string" ? chunk : JSON.stringify(chunk);
    process.nextTick(async () => {
      try {
        if (!redisClient.isOpen) {
          await redisClient.connect().catch((err) => {
            console.error("Redis connection error:", err);
          });
        }
        const pipeline = redisClient.multi();
        pipeline.rPush(logKey, logData);
        pipeline.expire(logKey, ttl);
        await pipeline.exec();
      } catch (err) {
        console.error("Redis logging error:", err);
      }
    });
    callback(null, chunk);
  }
  _write(chunk, encoding, callback) {
    if (typeof callback === "function") {
      this._transform(chunk, encoding || "utf8", callback);
      return true;
    }
    this._transform(chunk, encoding || "utf8", (error) => {
      if (error) console.error("Transform error in write:", error);
    });
    return true;
  }
  async _flush() {
    await new Promise((resolve2) => setTimeout(resolve2, 10));
  }
  async _destroy(err, cb) {
    await closeLogger();
    cb(err);
  }
  listLogs(_args) {
    return Promise.resolve({
      logs: [],
      total: 0,
      page: _args?.page ?? 1,
      perPage: _args?.perPage ?? 100,
      hasMore: false
    });
  }
  listLogsByRunId(_args) {
    return Promise.resolve({
      logs: [],
      total: 0,
      page: _args?.page ?? 1,
      perPage: _args?.perPage ?? 100,
      hasMore: false
    });
  }
};
var transport = new RedisTransport();
var closeLogger = async () => {
  if (redisClient.isOpen) {
    setTimeout(async () => {
      await redisClient.quit();
    }, 10);
  }
};
var logger = new loggers.PinoLogger({
  level: "info",
  transports: {
    redis: transport
  }
});

// src/utils/execa.ts
var createPinoStream = () => {
  return new stream.Writable({
    write(chunk, _encoding, callback) {
      const line = chunk.toString().trim();
      if (line) {
        logger.info(line);
      }
      callback();
    }
  });
};
async function runWithExeca({
  cmd,
  args,
  cwd = process.cwd(),
  env = PROJECT_ENV_VARS
}) {
  const pinoStream = createPinoStream();
  try {
    const subprocess = execa.execa(cmd, args, {
      cwd,
      stdin: "ignore",
      env: {
        ...process.env,
        ...env
      }
    });
    subprocess.stdout?.pipe(pinoStream, { end: false });
    subprocess.stderr?.pipe(pinoStream, { end: false });
    const { stdout, stderr, exitCode } = await subprocess;
    pinoStream.end();
    return { stdout, stderr, success: exitCode === 0 };
  } catch (error) {
    pinoStream.end();
    logger.error("Process failed", { error });
    return { success: false, error: error instanceof Error ? error : new Error(String(error)) };
  }
}

// src/utils/deps.ts
var MEMOIZED = /* @__PURE__ */ new Map();
function findLockFile(dir) {
  const lockFiles = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "bun.lock"];
  for (const file of lockFiles) {
    if (fs__namespace.existsSync(path.join(dir, file))) {
      return file;
    }
  }
  const parentDir = path.resolve(dir, "..");
  if (parentDir !== dir) {
    return findLockFile(parentDir);
  }
  return null;
}
function detectPm({ path }) {
  const cached = MEMOIZED.get(path);
  if (cached) {
    return cached;
  }
  const lockFile = findLockFile(path);
  let pm = "npm";
  switch (lockFile) {
    case "pnpm-lock.yaml":
      pm = "pnpm";
      break;
    case "package-lock.json":
      pm = "npm";
      break;
    case "yarn.lock":
      pm = "yarn";
      break;
    case "bun.lock":
      pm = "bun";
      break;
    default:
      pm = "npm";
  }
  MEMOIZED.set(path, pm);
  return pm;
}
async function installDeps({ path, pm }) {
  pm = pm ?? detectPm({ path });
  logger.info("Installing dependencies", { pm, path });
  const args = ["install", "--legacy-peer-deps=false", "--force"];
  const { success, error: error$1 } = await runWithExeca({ cmd: pm, args, cwd: path });
  if (!success) {
    throw new error.MastraError(
      {
        id: "FAIL_INSTALL_DEPS",
        category: "USER",
        domain: "DEPLOYER"
      },
      error$1
    );
  }
}
function getMastraEntryFile(mastraDir) {
  try {
    const fileService = new deployer.FileService();
    return fileService.getFirstExistingFile([
      path.join(mastraDir, MASTRA_DIRECTORY, "index.ts"),
      path.join(mastraDir, MASTRA_DIRECTORY, "index.js")
    ]);
  } catch (error$1) {
    throw new error.MastraError(
      {
        id: "MASTRA_ENTRY_FILE_NOT_FOUND",
        category: "USER",
        domain: "DEPLOYER"
      },
      error$1
    );
  }
}

// src/utils/report.ts
function successEntrypoint() {
  return `
  if (process.env.CI !== 'true') {
    await fetch('${process.env.REPORTER_API_URL}', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ${process.env.REPORTER_API_URL_AUTH_TOKEN}',
      },
      body: JSON.stringify(${JSON.stringify({
    projectId: PROJECT_ID,
    buildId: BUILD_ID,
    status: "success",
    url: BUILD_URL,
    userIpAddress: USER_IP_ADDRESS
  })}),
    }).catch(err => {
      console.error('Failed to report build status to monitoring service', {
        error: err,
      });
    })
  }
  `;
}

// src/index.ts
var CloudDeployer = class extends deployer.Deployer {
  studio;
  constructor({ studio } = {}) {
    super({ name: "cloud" });
    this.studio = studio ?? false;
  }
  async getUserBundlerOptions(mastraEntryFile, outputDirectory) {
    const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);
    return {
      ...bundlerOptions,
      externals: true
    };
  }
  async deploy(_outputDirectory) {
  }
  async prepare(outputDirectory) {
    await super.prepare(outputDirectory);
    if (this.studio) {
      const __filename = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
      const __dirname = path.dirname(__filename);
      const studioServePath = path.join(outputDirectory, this.outputDir, "studio");
      await esm.copy(path.join(path.dirname(__dirname), path.join("dist", "studio")), studioServePath, {
        overwrite: true
      });
    }
  }
  async writePackageJson(outputDirectory, dependencies) {
    const versions = await esm.readJSON(path.join(path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))), "../versions.json"));
    for (const [pkgName, version] of Object.entries(versions || {})) {
      dependencies.set(pkgName, version);
    }
    return super.writePackageJson(outputDirectory, dependencies);
  }
  async lint() {
  }
  async installDependencies(outputDirectory, _rootDir = process.cwd()) {
    await installDeps({ path: path.join(outputDirectory, "output"), pm: "npm" });
  }
  async bundle(mastraDir, outputDirectory) {
    const currentCwd = process.cwd();
    process.chdir(mastraDir);
    const mastraEntryFile = getMastraEntryFile(mastraDir);
    const mastraAppDir = path.join(mastraDir, MASTRA_DIRECTORY);
    const discoveredTools = this.getAllToolPaths(mastraAppDir);
    await this.prepare(outputDirectory);
    await this._bundle(
      this.getEntry(),
      mastraEntryFile,
      {
        outputDirectory,
        projectRoot: mastraDir
      },
      discoveredTools
    );
    process.chdir(currentCwd);
  }
  getAuthEntrypoint() {
    return getAuthEntrypoint();
  }
  getEntry() {
    return `
import { createNodeServer, getToolExports } from '#server';
import { tools } from '#tools';
import { mastra } from '#mastra';
import { MultiLogger } from '@mastra/core/logger';
import { PinoLogger } from '@mastra/loggers';
import { HttpTransport } from '@mastra/loggers/http';
import { LibSQLStore, LibSQLVector } from '@mastra/libsql';
import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';

const startTime = process.env.RUNNER_START_TIME ? new Date(process.env.RUNNER_START_TIME).getTime() : Date.now();
const createNodeServerStartTime = Date.now();

console.log(JSON.stringify({
  message: "Server starting",
  operation: 'builder.createNodeServer',
  operation_startTime: createNodeServerStartTime,
  type: "READINESS",
  startTime,
  metadata: {
    teamId: "${TEAM_ID}",
    projectId: "${PROJECT_ID}",
    buildId: "${BUILD_ID}",
  },
}));

const transports = {}
if (process.env.CI !== 'true') {
  if (process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT) {
    transports.default = new HttpTransport({
      url: process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT,
      headers: {
        Authorization: 'Bearer ' + process.env.BUSINESS_JWT_TOKEN,
      },
    });
  }
}

const logger = new PinoLogger({
  name: 'MastraCloud',
  transports,
  level: 'debug',
});
const existingLogger = mastra?.getLogger();
const combinedLogger = existingLogger ? new MultiLogger([logger, existingLogger]) : logger;

mastra.setLogger({ logger: combinedLogger });

if (process.env.MASTRA_STORAGE_URL && process.env.MASTRA_STORAGE_AUTH_TOKEN) {
  const { MastraStorage } = await import('@mastra/core/storage');
  logger.info('Using Mastra Cloud Storage: ' + process.env.MASTRA_STORAGE_URL)
  const storage = new LibSQLStore({
    id: 'mastra-cloud-storage-libsql',
    url: process.env.MASTRA_STORAGE_URL,
    authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,
  })
  const vector = new LibSQLVector({
    id: 'mastra-cloud-storage-libsql-vector',
    url: process.env.MASTRA_STORAGE_URL,
    authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,
  })

  await storage.init()
  mastra?.setStorage(storage)
} else {
  const userStorage = mastra?.getStorage();
  if (userStorage && !userStorage.disableInit) {
    userStorage.init();
  }
}

if (mastra?.getStorage()) {
  mastra.__registerInternalWorkflow(scoreTracesWorkflow);
}

${getAuthEntrypoint()}

await createNodeServer(mastra, { studio: ${this.studio}, swaggerUI: false, tools: getToolExports(tools) });

${successEntrypoint()}

console.log(JSON.stringify({
  message: "Server started",
  operation: 'builder.createNodeServer',
  operation_startTime: createNodeServerStartTime,
  operation_durationMs: Date.now() - createNodeServerStartTime,
  type: "READINESS",
  startTime,
  metadata: {
    teamId: "${TEAM_ID}",
    projectId: "${PROJECT_ID}",
    buildId: "${BUILD_ID}",
  },
}));


console.log(JSON.stringify({
  message: "Runner Initialized",
  type: "READINESS",
  startTime,
  durationMs: Date.now() - startTime,
  metadata: {
    teamId: "${TEAM_ID}",
    projectId: "${PROJECT_ID}",
    buildId: "${BUILD_ID}",
  },
}));
`;
  }
};

exports.CloudDeployer = CloudDeployer;
//# sourceMappingURL=index.cjs.map
//# sourceMappingURL=index.cjs.map