import { ao as listAvailableAddonIds, ac as getRegistryAddonConfig, aK as readStackSecretEnv, aI as readStackEnv, bb as writeStackSecretEnv, az as patchSecretsEnvFile, H as createLogger } from './src-CidJbygh.js';
import { g as getState } from './state-fxN45gBp.js';
import { d as getRequestId, r as requireAdmin, e as errorResponse, k as jsonResponse, p as parseJsonBody, j as jsonBodyError } from './helpers-kzwksNq1.js';
import './chunk-CLZ62Ad-.js';
import 'node:module';
import './provider-constants-DPrj3yBX.js';
import './dist-DOFcG0Zp.js';
import 'node:fs';
import 'node:path';
import 'buffer';
import 'fs';
import 'path';
import 'node:child_process';
import 'node:url';
import 'node:crypto';
import 'events';
import 'node:events';
import 'node:stream';
import 'node:string_decoder';
import 'assert';
import 'zlib';
import 'node:assert';
import 'node:fs/promises';
import 'node:os';
import './endpoints-UdQGgKsR.js';

//#region src/routes/admin/addons/[name]/credentials/+server.ts
var logger = createLogger("addons.name.credentials");
/**
* Parse a `.env.schema` file into structured fields.
*
* Schema conventions:
*   - Lines starting with `#` are comments; consecutive comment lines
*     accumulate as the *description* of the next KEY=VALUE line.
*   - `# @sensitive` marks the next field as sensitive (renders as a
*     password input and is masked on GET).
*   - `# ---` resets the accumulator (used as a section separator).
*   - `KEY=DEFAULT` declares the field; default may be empty.
*/
function parseEnvSchema(text) {
	const fields = [];
	let commentBuffer = [];
	let sensitive = false;
	for (const rawLine of text.split(/\r?\n/)) {
		const line = rawLine.trim();
		if (!line) continue;
		if (line.startsWith("#")) {
			const body = line.slice(1).trim();
			if (body === "---") {
				commentBuffer = [];
				sensitive = false;
				continue;
			}
			if (body.startsWith("@")) {
				if (/\B@sensitive\b/.test(body)) sensitive = true;
				continue;
			}
			commentBuffer.push(body);
			continue;
		}
		const eq = line.indexOf("=");
		if (eq <= 0) continue;
		const key = line.slice(0, eq).trim();
		if (!key) continue;
		const def = line.slice(eq + 1).trim();
		fields.push({
			key,
			sensitive,
			description: commentBuffer.join(" ").trim(),
			default: def
		});
		commentBuffer = [];
		sensitive = false;
	}
	return fields;
}
var GET = async (event) => {
	const requestId = getRequestId(event);
	const authErr = requireAdmin(event, requestId);
	if (authErr) return authErr;
	const state = getState();
	const name = event.params.name;
	if (!listAvailableAddonIds().includes(name)) return errorResponse(404, "not_found", `Addon "${name}" is not available`, { name }, requestId);
	let config;
	try {
		config = getRegistryAddonConfig(name);
	} catch (error) {
		logger.error("schema read failed", {
			name,
			error: String(error),
			requestId
		});
		return errorResponse(500, "internal_error", `Addon "${name}" schema is unavailable`, {}, requestId);
	}
	const schemaFields = parseEnvSchema(config.envSchema);
	const secretEnv = readStackSecretEnv(state.stackDir);
	const stackEnv = readStackEnv(state.stackDir);
	return jsonResponse(200, {
		name,
		fields: schemaFields.map((f) => {
			const set = ((f.sensitive ? secretEnv[f.key] : stackEnv[f.key]) ?? "").length > 0;
			return {
				key: f.key,
				sensitive: f.sensitive,
				description: f.description,
				default: f.default,
				set,
				secret: {
					envKey: f.key,
					present: set
				},
				value: ""
			};
		})
	}, requestId);
};
var POST = async (event) => {
	const requestId = getRequestId(event);
	const authErr = requireAdmin(event, requestId);
	if (authErr) return authErr;
	const state = getState();
	const name = event.params.name;
	if (!listAvailableAddonIds().includes(name)) return errorResponse(404, "not_found", `Addon "${name}" is not available`, { name }, requestId);
	const parsed = await parseJsonBody(event.request);
	if ("error" in parsed) return jsonBodyError(parsed, requestId);
	const valuesRaw = parsed.data.values ?? {};
	let config;
	try {
		config = getRegistryAddonConfig(name);
	} catch (error) {
		logger.error("schema read failed (post)", {
			name,
			error: String(error),
			requestId
		});
		return errorResponse(500, "internal_error", `Addon "${name}" schema is unavailable`, {}, requestId);
	}
	const schemaFields = parseEnvSchema(config.envSchema);
	const sensitiveKeys = new Set(schemaFields.filter((f) => f.sensitive).map((f) => f.key));
	const allowedKeys = new Set(schemaFields.map((f) => f.key));
	const sensitiveUpdates = {};
	const configUpdates = {};
	for (const [k, v] of Object.entries(valuesRaw)) {
		if (!allowedKeys.has(k)) continue;
		const val = typeof v === "string" ? v : "";
		if (sensitiveKeys.has(k)) sensitiveUpdates[k] = val;
		else configUpdates[k] = val;
	}
	if (Object.keys(sensitiveUpdates).length === 0 && Object.keys(configUpdates).length === 0) return errorResponse(400, "bad_request", "no schema-declared keys supplied", {}, requestId);
	try {
		if (Object.keys(sensitiveUpdates).length > 0) writeStackSecretEnv(state, sensitiveUpdates);
		if (Object.keys(configUpdates).length > 0) patchSecretsEnvFile(state.stackDir, configUpdates);
	} catch (err) {
		logger.error("write failed", {
			name,
			error: String(err),
			requestId
		});
		return errorResponse(500, "internal_error", err instanceof Error ? err.message : "write failed", {}, requestId);
	}
	return jsonResponse(200, {
		ok: true,
		name,
		updated: [...Object.keys(sensitiveUpdates), ...Object.keys(configUpdates)].sort()
	}, requestId);
};

export { GET, POST };
//# sourceMappingURL=_server.ts-CsUb-Aja.js.map
