@gadicc/loom 1.32.0 → 1.33.1

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.
@@ -54,6 +54,7 @@ exports.usePublishedDevPackage = usePublishedDevPackage;
54
54
  exports.syncDbSchemas = syncDbSchemas;
55
55
  exports.configureFilesIdGeneration = configureFilesIdGeneration;
56
56
  exports.buildVercelFilesEnvProbeArgs = buildVercelFilesEnvProbeArgs;
57
+ exports.setupLocalFiles = setupLocalFiles;
57
58
  exports.setupCloudflareR2 = setupCloudflareR2;
58
59
  exports.buildVercelNeonSetupCommand = buildVercelNeonSetupCommand;
59
60
  exports.setupVercelNeon = setupVercelNeon;
@@ -76,6 +77,8 @@ const promises_1 = require("node:fs/promises");
76
77
  const node_module_1 = require("node:module");
77
78
  const node_path_1 = require("node:path");
78
79
  const node_process_1 = __importDefault(require("node:process"));
80
+ const promises_2 = require("node:readline/promises");
81
+ const node_os_1 = require("node:os");
79
82
  const node_util_1 = require("node:util");
80
83
  const filesR2Policy_js_1 = require("./filesR2Policy.js");
81
84
  const releaseConfig_js_1 = require("./releaseConfig.js");
@@ -246,7 +249,7 @@ const DB_DEFAULT_DEPENDENCIES = {
246
249
  "valibot": "^1.4.2",
247
250
  };
248
251
  const DB_DEFAULT_DEV_DEPENDENCIES = {
249
- "@electric-sql/pglite": "^0.3.15",
252
+ "@electric-sql/pglite": "^0.5.8",
250
253
  "drizzle-kit": "^0.31.10",
251
254
  "drizzle-valibot": "^0.4.2",
252
255
  "tsx": "^4.23.1",
@@ -280,6 +283,7 @@ const FILES_S3_NON_SECRET_ENV_VALUES = {
280
283
  };
281
284
  const FILES_R2_ENVIRONMENTS = ["production", "preview"];
282
285
  const DEFAULT_MINIO_ENDPOINT = "http://127.0.0.1:9000";
286
+ const FILES_LOCAL_ENV_NAMES = FILES_S3_REQUIRED_ENV_NAMES;
283
287
  const API_KEY_AUDIT_SCHEMA_BLUEPRINT_VERSION = 3;
284
288
  const API_KEY_AUDIT_SCHEMA_DEFAULT_EXPORT = "loomApiKeyAuditEventsTable";
285
289
  const API_KEY_AUDIT_SCHEMA_DEFAULT_TABLE = "loom_api_key_audit_events";
@@ -5843,17 +5847,31 @@ async function configureFilesIdGeneration(cwd, idGeneration) {
5843
5847
  }
5844
5848
  function parseEnvValue(rawValue) {
5845
5849
  const trimmed = rawValue.trim();
5846
- if (trimmed.length >= 2 &&
5847
- ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
5848
- (trimmed.startsWith("'") && trimmed.endsWith("'")))) {
5849
- return trimmed.slice(1, -1);
5850
+ const quote = trimmed[0];
5851
+ if (quote === '"' || quote === "'" || quote === "`") {
5852
+ for (let index = 1; index < trimmed.length; index++) {
5853
+ if (trimmed[index] === "\\") {
5854
+ index++;
5855
+ continue;
5856
+ }
5857
+ if (trimmed[index] !== quote)
5858
+ continue;
5859
+ const trailing = trimmed.slice(index + 1).trim();
5860
+ if (!trailing || trailing.startsWith("#")) {
5861
+ const value = trimmed.slice(1, index);
5862
+ return quote === '"'
5863
+ ? value.replaceAll("\\n", "\n").replaceAll("\\r", "\r")
5864
+ : value;
5865
+ }
5866
+ break;
5867
+ }
5850
5868
  }
5851
- return trimmed;
5869
+ return trimmed.split("#", 1)[0].trim();
5852
5870
  }
5853
5871
  function readEnvAssignments(text) {
5854
5872
  const assignments = new Map();
5855
5873
  for (const [lineIndex, line] of normalizeText(text).split("\n").entries()) {
5856
- const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
5874
+ const match = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
5857
5875
  if (!match)
5858
5876
  continue;
5859
5877
  assignments.set(match[1], {
@@ -6040,32 +6058,66 @@ async function promptForVercelSecret(cwd, commandRunner, env, vercelCommand, nam
6040
6058
  }
6041
6059
  const VERCEL_FILES_ENV_PROBE_SCRIPT = "process.stdout.write(JSON.stringify({FILES_S3_BUCKET:process.env.FILES_S3_BUCKET,FILES_S3_ENDPOINT:process.env.FILES_S3_ENDPOINT,FILES_S3_FORCE_PATH_STYLE:process.env.FILES_S3_FORCE_PATH_STYLE,FILES_S3_REGION:process.env.FILES_S3_REGION,FILES_STORAGE_PROVIDER:process.env.FILES_STORAGE_PROVIDER}))";
6042
6060
  /** Builds the Vercel env-run probe that prints only non-secret Files values. */
6043
- function buildVercelFilesEnvProbeArgs(environment) {
6061
+ function buildVercelFilesEnvProbeArgs(environment, project) {
6044
6062
  return [
6063
+ ...(project ? ["--scope", project.orgId] : []),
6045
6064
  "env",
6046
6065
  "run",
6047
6066
  "-e",
6048
6067
  environment,
6068
+ ...(project ? ["--project", project.projectId] : []),
6049
6069
  "--",
6050
6070
  "node",
6051
6071
  "-e",
6052
6072
  VERCEL_FILES_ENV_PROBE_SCRIPT,
6053
6073
  ];
6054
6074
  }
6075
+ function buildVercelFilesEnvListArgs(environment, project) {
6076
+ return [
6077
+ "--scope",
6078
+ project.orgId,
6079
+ "env",
6080
+ "ls",
6081
+ environment,
6082
+ "--project",
6083
+ project.projectId,
6084
+ ];
6085
+ }
6086
+ function withoutInheritedVercelProject(env) {
6087
+ const result = { ...env };
6088
+ delete result.VERCEL_ORG_ID;
6089
+ delete result.VERCEL_PROJECT_ID;
6090
+ return result;
6091
+ }
6055
6092
  async function readVercelFilesNonSecretValues(cwd, commandRunner, env, vercelCommand, environment) {
6056
- const result = await commandRunner(vercelCommand, buildVercelFilesEnvProbeArgs(environment), { cwd, env, stdio: "pipe" });
6057
- if (result.code !== 0)
6058
- return null;
6059
- const jsonLine = normalizeText(result.stdout).split("\n").findLast((line) => line.trim().startsWith("{"));
6060
- if (!jsonLine)
6093
+ const link = await readVercelProjectLink(cwd);
6094
+ if (!link.linked || !link.orgId || !link.projectId)
6061
6095
  return null;
6096
+ const probeEnv = withoutInheritedVercelProject(env);
6097
+ for (const name of Object.keys(probeEnv)) {
6098
+ if (name.startsWith("FILES_"))
6099
+ delete probeEnv[name];
6100
+ }
6101
+ const probeCwd = await (0, promises_1.mkdtemp)((0, node_path_1.join)((0, node_os_1.tmpdir)(), "loom-vercel-files-probe-"));
6062
6102
  try {
6103
+ // Vercel env run loads .env.local from cwd and preserves inherited values.
6104
+ // Probe the linked project from an empty directory so local MinIO cannot
6105
+ // masquerade as remote R2 drift.
6106
+ const result = await commandRunner(vercelCommand, buildVercelFilesEnvProbeArgs(environment, link), { cwd: probeCwd, env: probeEnv, stdio: "pipe" });
6107
+ if (result.code !== 0)
6108
+ return null;
6109
+ const jsonLine = normalizeText(result.stdout).split("\n").findLast((line) => line.trim().startsWith("{"));
6110
+ if (!jsonLine)
6111
+ return null;
6063
6112
  const parsed = JSON.parse(jsonLine);
6064
6113
  return isJsonObject(parsed) ? parsed : null;
6065
6114
  }
6066
6115
  catch {
6067
6116
  return null;
6068
6117
  }
6118
+ finally {
6119
+ await (0, promises_1.rm)(probeCwd, { recursive: true, force: true });
6120
+ }
6069
6121
  }
6070
6122
  async function detectMinioClient(cwd, commandRunner, env) {
6071
6123
  for (const command of ["mcli", "mc"]) {
@@ -6114,6 +6166,420 @@ async function ensureMinioBucket(cwd, commandRunner, env, endpoint, bucket, acce
6114
6166
  ok: false,
6115
6167
  };
6116
6168
  }
6169
+ async function promptForLocalFilesValue(question, secret = false) {
6170
+ if (!node_process_1.default.stdin.isTTY) {
6171
+ throw new Error("MinIO admin credentials are required. Run interactively or set MINIO_ROOT_USER and MINIO_ROOT_PASSWORD in the command environment.");
6172
+ }
6173
+ if (!secret) {
6174
+ const input = (0, promises_2.createInterface)({
6175
+ input: node_process_1.default.stdin,
6176
+ output: node_process_1.default.stderr,
6177
+ });
6178
+ try {
6179
+ return (await input.question(question)).trim();
6180
+ }
6181
+ finally {
6182
+ input.close();
6183
+ }
6184
+ }
6185
+ node_process_1.default.stderr.write(question);
6186
+ const stdin = node_process_1.default.stdin;
6187
+ const wasRaw = stdin.isRaw;
6188
+ stdin.setRawMode(true);
6189
+ stdin.resume();
6190
+ try {
6191
+ return await new Promise((resolvePromise, rejectPromise) => {
6192
+ let value = "";
6193
+ const onData = (chunk) => {
6194
+ for (const character of new TextDecoder().decode(chunk)) {
6195
+ if (character === "\r" || character === "\n") {
6196
+ stdin.off("data", onData);
6197
+ node_process_1.default.stderr.write("\n");
6198
+ resolvePromise(value);
6199
+ return;
6200
+ }
6201
+ if (character === "\u0003") {
6202
+ stdin.off("data", onData);
6203
+ rejectPromise(new Error("MinIO setup was cancelled."));
6204
+ return;
6205
+ }
6206
+ if (character === "\u007f" || character === "\b") {
6207
+ value = value.slice(0, -1);
6208
+ }
6209
+ else {
6210
+ value += character;
6211
+ }
6212
+ }
6213
+ };
6214
+ stdin.on("data", onData);
6215
+ });
6216
+ }
6217
+ finally {
6218
+ stdin.setRawMode(wasRaw);
6219
+ stdin.pause();
6220
+ }
6221
+ }
6222
+ function minioHostEnv(env, endpoint, accessKey, secretKey) {
6223
+ const url = new URL(endpoint);
6224
+ url.username = accessKey;
6225
+ url.password = secretKey;
6226
+ return { ...env, MC_HOST_loomlocal: url.toString() };
6227
+ }
6228
+ async function checkMinioAdmin(cwd, runner, command, env, endpoint, user, password) {
6229
+ const result = await runner(command, ["admin", "info", "loomlocal"], {
6230
+ cwd,
6231
+ env: minioHostEnv(env, endpoint, user, password),
6232
+ stdio: "pipe",
6233
+ });
6234
+ return result.code === 0;
6235
+ }
6236
+ function filesBucketPolicy(bucket) {
6237
+ return {
6238
+ Version: "2012-10-17",
6239
+ Statement: [
6240
+ {
6241
+ Effect: "Allow",
6242
+ Action: ["s3:GetBucketLocation", "s3:ListBucket"],
6243
+ Resource: [`arn:aws:s3:::${bucket}`],
6244
+ },
6245
+ {
6246
+ Effect: "Allow",
6247
+ Action: ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
6248
+ Resource: [`arn:aws:s3:::${bucket}/*`],
6249
+ },
6250
+ ],
6251
+ };
6252
+ }
6253
+ async function verifyMinioReadWrite(cwd, runner, command, env, endpoint, bucket, accessKey, secretKey) {
6254
+ const target = `loomlocal/${bucket}/.loom-setup-${(0, node_crypto_1.randomUUID)()}`;
6255
+ const keyEnv = minioHostEnv(env, endpoint, accessKey, secretKey);
6256
+ const payload = "loom-files-local-check\n";
6257
+ const put = await runner(command, ["pipe", target], {
6258
+ cwd,
6259
+ env: keyEnv,
6260
+ input: payload,
6261
+ stdio: "pipe",
6262
+ });
6263
+ if (put.code !== 0) {
6264
+ throw new Error("The MinIO access key cannot write to its bucket.");
6265
+ }
6266
+ let readOk = false;
6267
+ let removeOk = false;
6268
+ try {
6269
+ const get = await runner(command, ["cat", target], {
6270
+ cwd,
6271
+ env: keyEnv,
6272
+ stdio: "pipe",
6273
+ });
6274
+ readOk = get.code === 0 && get.stdout === payload;
6275
+ }
6276
+ finally {
6277
+ const remove = await runner(command, ["rm", target], {
6278
+ cwd,
6279
+ env: keyEnv,
6280
+ stdio: "pipe",
6281
+ });
6282
+ removeOk = remove.code === 0;
6283
+ }
6284
+ if (!removeOk) {
6285
+ throw new Error("The MinIO access key could not remove its setup verification object.");
6286
+ }
6287
+ if (!readOk) {
6288
+ throw new Error("The MinIO access key cannot read from its bucket.");
6289
+ }
6290
+ }
6291
+ /**
6292
+ * Configures Files against local MinIO, preserving any existing app key and
6293
+ * verifying a newly created bucket-scoped key before writing it to .env.local.
6294
+ */
6295
+ async function setupLocalFiles(cwd, options = {}) {
6296
+ const runner = options.commandRunner ?? defaultCommandRunner;
6297
+ const env = options.env ?? node_process_1.default.env;
6298
+ const prompt = options.prompt ?? promptForLocalFilesValue;
6299
+ const manifestPath = (0, node_path_1.join)(cwd, "loom.json");
6300
+ const manifestText = await readTextIfExists(manifestPath);
6301
+ if (!manifestText) {
6302
+ throw new Error("Missing loom.json. Run `loom add files` first.");
6303
+ }
6304
+ const manifest = parseJson(manifestText, "loom.json");
6305
+ const feature = manifest.features.files;
6306
+ if (feature?.status !== "active") {
6307
+ throw new Error("The files feature is not active. Run `loom add files` first.");
6308
+ }
6309
+ const { packageJson } = await readProjectPackageJson(cwd);
6310
+ const framework = await detectFramework(cwd, packageJson);
6311
+ const dbFeature = manifest.features.db;
6312
+ if (dbFeature?.status !== "active") {
6313
+ throw new Error("The files feature requires the active DB feature.");
6314
+ }
6315
+ const config = getFilesConfig(framework, mergeDbConfig(framework, dbFeature.config), feature.config);
6316
+ if (config.storage.provider?.localDevelopment.kind === "none") {
6317
+ throw new Error("Files local storage is disabled in loom.json. Change the provider policy before running local setup.");
6318
+ }
6319
+ if (config.storage.provider?.localDevelopment.kind === "r2") {
6320
+ throw new Error("Files local storage is set to R2. Change the local provider policy to MinIO before running local setup.");
6321
+ }
6322
+ const storagePath = (0, node_path_1.join)(cwd, config.modules.storageModule);
6323
+ const storageText = await readTextIfExists(storagePath);
6324
+ if (storageText && !isGeneratedFilesStorageStub(storageText) &&
6325
+ config.storage.adapter !== "s3") {
6326
+ throw new Error(`Files uses a custom storage adapter at ${config.modules.storageModule}; configure it locally without replacing it.`);
6327
+ }
6328
+ const envPath = (0, node_path_1.join)(cwd, ".env.local");
6329
+ const envText = await readTextIfExists(envPath);
6330
+ const tracked = await runner("git", [
6331
+ "ls-files",
6332
+ "--error-unmatch",
6333
+ "--",
6334
+ ".env.local",
6335
+ ], { cwd, env, stdio: "pipe" });
6336
+ if (tracked.code === 0) {
6337
+ throw new Error(".env.local is tracked by Git. Remove it from the index before Loom writes Files credentials.");
6338
+ }
6339
+ try {
6340
+ if ((await (0, promises_1.lstat)(envPath)).isSymbolicLink()) {
6341
+ throw new Error(".env.local is a symlink; Loom will not write credentials through it.");
6342
+ }
6343
+ }
6344
+ catch (error) {
6345
+ if (!isNodeErrorCode(error, "ENOENT"))
6346
+ throw error;
6347
+ }
6348
+ const assignments = readEnvAssignments(envText ?? "");
6349
+ const bucket = normalizeBucketName(options.localBucket ??
6350
+ assignments.get("FILES_S3_BUCKET")?.value ??
6351
+ config.storage.provider?.localDevelopment.bucket ??
6352
+ `${getDefaultFilesBucketBase(cwd, packageJson, manifest)}-dev`, "--local-bucket");
6353
+ let endpoint = options.localEndpoint ??
6354
+ assignments.get("FILES_S3_ENDPOINT")?.value ??
6355
+ config.storage.provider?.localDevelopment.endpoint ??
6356
+ DEFAULT_MINIO_ENDPOINT;
6357
+ function validateEndpoint(value) {
6358
+ let url;
6359
+ try {
6360
+ url = new URL(value);
6361
+ }
6362
+ catch {
6363
+ throw new Error("--local-endpoint must be an HTTP(S) origin without credentials or a path.");
6364
+ }
6365
+ if (!["http:", "https:"].includes(url.protocol) || url.username ||
6366
+ url.password || url.pathname !== "/" || url.search || url.hash) {
6367
+ throw new Error("--local-endpoint must be an HTTP(S) origin without credentials or a path.");
6368
+ }
6369
+ return url.origin;
6370
+ }
6371
+ endpoint = validateEndpoint(endpoint);
6372
+ const client = await detectMinioClient(cwd, runner, env);
6373
+ if (!client) {
6374
+ throw new Error("MinIO Client is unavailable. Install `mcli` (Arch: `sudo pacman -S minio-client`) or `mc`, then rerun `loom files local setup`.");
6375
+ }
6376
+ const existingAccess = assignments.get("FILES_S3_ACCESS_KEY_ID")?.value;
6377
+ const existingSecret = assignments.get("FILES_S3_SECRET_ACCESS_KEY")?.value;
6378
+ if ((assignments.has("FILES_S3_ACCESS_KEY_ID") && !existingAccess) ||
6379
+ (assignments.has("FILES_S3_SECRET_ACCESS_KEY") && !existingSecret)) {
6380
+ throw new Error(".env.local contains an empty Files credential. Remove the empty assignment before local setup.");
6381
+ }
6382
+ if (Boolean(existingAccess) !== Boolean(existingSecret)) {
6383
+ throw new Error(".env.local has only one Files access credential. Restore the matching key and secret before local setup; Loom will not replace either one.");
6384
+ }
6385
+ let bucketStatus = existingAccess && existingSecret
6386
+ ? await ensureMinioBucket(cwd, runner, env, endpoint, bucket, existingAccess, existingSecret, { create: false })
6387
+ : null;
6388
+ if (bucketStatus?.ok && existingAccess && existingSecret) {
6389
+ await verifyMinioReadWrite(cwd, runner, client, env, endpoint, bucket, existingAccess, existingSecret);
6390
+ }
6391
+ let createdKey = null;
6392
+ if (!bucketStatus?.ok) {
6393
+ if (Boolean(env.MINIO_ROOT_USER) !== Boolean(env.MINIO_ROOT_PASSWORD)) {
6394
+ throw new Error("Set both MINIO_ROOT_USER and MINIO_ROOT_PASSWORD, or leave both unset for interactive MinIO setup.");
6395
+ }
6396
+ let adminUser = env.MINIO_ROOT_USER || "minioadmin";
6397
+ let adminPassword = env.MINIO_ROOT_PASSWORD || "minioadmin";
6398
+ let authenticated = await checkMinioAdmin(cwd, runner, client, env, endpoint, adminUser, adminPassword);
6399
+ if (!authenticated) {
6400
+ const promptedEndpoint = (await prompt(`MinIO endpoint [${endpoint}]: `)).trim();
6401
+ if (promptedEndpoint)
6402
+ endpoint = validateEndpoint(promptedEndpoint);
6403
+ adminUser = (await prompt("MinIO admin user: ")).trim();
6404
+ adminPassword = await prompt("MinIO admin password: ", true);
6405
+ authenticated = await checkMinioAdmin(cwd, runner, client, env, endpoint, adminUser, adminPassword);
6406
+ }
6407
+ if (!authenticated) {
6408
+ throw new Error("Could not authenticate to MinIO. Check the server endpoint and admin credentials, then rerun local setup.");
6409
+ }
6410
+ const adminEnv = minioHostEnv(env, endpoint, adminUser, adminPassword);
6411
+ bucketStatus = await ensureMinioBucket(cwd, runner, env, endpoint, bucket, adminUser, adminPassword);
6412
+ if (!bucketStatus.ok) {
6413
+ throw new Error(`Could not create or reuse MinIO bucket \`${bucket}\`. Check admin permissions and the endpoint.`);
6414
+ }
6415
+ if (existingAccess && existingSecret) {
6416
+ const existingCheck = await ensureMinioBucket(cwd, runner, env, endpoint, bucket, existingAccess, existingSecret, { create: false });
6417
+ if (!existingCheck.ok) {
6418
+ throw new Error("Existing FILES_S3 credentials cannot access the bucket. Loom preserved them; repair or remove them manually before rerunning setup.");
6419
+ }
6420
+ await verifyMinioReadWrite(cwd, runner, client, env, endpoint, bucket, existingAccess, existingSecret);
6421
+ }
6422
+ else {
6423
+ const policyDir = await (0, promises_1.mkdtemp)((0, node_path_1.join)((0, node_os_1.tmpdir)(), "loom-files-policy-"));
6424
+ const policyPath = (0, node_path_1.join)(policyDir, "bucket.json");
6425
+ try {
6426
+ await (0, promises_1.writeFile)(policyPath, `${JSON.stringify(filesBucketPolicy(bucket))}\n`, { mode: 0o600 });
6427
+ const result = await runner(client, [
6428
+ "--json",
6429
+ "admin",
6430
+ "accesskey",
6431
+ "create",
6432
+ "loomlocal/",
6433
+ "--policy",
6434
+ policyPath,
6435
+ ], { cwd, env: adminEnv, stdio: "pipe" });
6436
+ if (result.code !== 0) {
6437
+ throw new Error("MinIO could not create a bucket-scoped access key. Check that the client supports `admin accesskey create` and the admin account has permission.");
6438
+ }
6439
+ let parsed = {};
6440
+ try {
6441
+ parsed = JSON.parse(result.stdout.trim());
6442
+ }
6443
+ catch {
6444
+ throw new Error("MinIO returned malformed JSON while creating a local access key.");
6445
+ }
6446
+ if (typeof parsed.accessKey !== "string" ||
6447
+ typeof parsed.secretKey !== "string") {
6448
+ throw new Error("MinIO did not return an access key and secret key in JSON output.");
6449
+ }
6450
+ createdKey = {
6451
+ accessKey: parsed.accessKey,
6452
+ secretKey: parsed.secretKey,
6453
+ };
6454
+ }
6455
+ finally {
6456
+ await (0, promises_1.rm)(policyDir, { recursive: true, force: true });
6457
+ }
6458
+ try {
6459
+ const keyCheck = await ensureMinioBucket(cwd, runner, env, endpoint, bucket, createdKey.accessKey, createdKey.secretKey, { create: false });
6460
+ if (!keyCheck.ok) {
6461
+ throw new Error("The new MinIO access key could not read its bucket. Check the MinIO policy before rerunning setup.");
6462
+ }
6463
+ await verifyMinioReadWrite(cwd, runner, client, env, endpoint, bucket, createdKey.accessKey, createdKey.secretKey);
6464
+ }
6465
+ catch (error) {
6466
+ const cleanup = await runner(client, ["admin", "accesskey", "remove", "loomlocal/", createdKey.accessKey], { cwd, env: adminEnv, stdio: "pipe" });
6467
+ if (cleanup.code !== 0) {
6468
+ throw new Error("The new MinIO key failed verification and could not be removed automatically. Remove the newly created key in MinIO before retrying.");
6469
+ }
6470
+ throw error;
6471
+ }
6472
+ }
6473
+ }
6474
+ const desired = {
6475
+ FILES_S3_BUCKET: bucket,
6476
+ FILES_S3_ENDPOINT: endpoint,
6477
+ FILES_S3_FORCE_PATH_STYLE: "true",
6478
+ FILES_S3_REGION: "auto",
6479
+ FILES_STORAGE_PROVIDER: "minio",
6480
+ FILES_S3_ACCESS_KEY_ID: existingAccess ?? createdKey?.accessKey ?? "",
6481
+ FILES_S3_SECRET_ACCESS_KEY: existingSecret ?? createdKey?.secretKey ?? "",
6482
+ };
6483
+ const merged = mergeEnvValues(envText, desired, {
6484
+ neverReplace: new Set([
6485
+ "FILES_S3_ACCESS_KEY_ID",
6486
+ "FILES_S3_SECRET_ACCESS_KEY",
6487
+ ]),
6488
+ repair: true,
6489
+ });
6490
+ if (merged.conflicts.length) {
6491
+ throw new Error(`Could not preserve existing Files credentials: ${merged.conflicts.join(", ")}.`);
6492
+ }
6493
+ const changedFiles = [];
6494
+ const notes = [];
6495
+ const gitignorePath = (0, node_path_1.join)(cwd, ".gitignore");
6496
+ const gitignore = await readTextIfExists(gitignorePath) ?? "";
6497
+ const lastIgnoreRule = normalizeText(gitignore).split("\n")
6498
+ .map((line) => line.trim()).filter(Boolean).at(-1);
6499
+ if (lastIgnoreRule !== ".env.local" && lastIgnoreRule !== "/.env.local") {
6500
+ if (await writeTextIfChanged(gitignorePath, `${gitignore && !gitignore.endsWith("\n") ? `${gitignore}\n` : gitignore}.env.local\n`))
6501
+ changedFiles.push(".gitignore");
6502
+ }
6503
+ if (envText !== merged.text) {
6504
+ await (0, promises_1.writeFile)(envPath, merged.text, { mode: 0o600 });
6505
+ await (0, promises_1.chmod)(envPath, 0o600);
6506
+ changedFiles.push(".env.local");
6507
+ }
6508
+ const tooling = await getProjectTooling(cwd, manifest);
6509
+ const dependencyUpdate = await (0, projectTooling_js_1.mutateProjectDependencies)(cwd, tooling.dependencies, { dependencies: FILES_S3_DEPENDENCIES });
6510
+ if (dependencyUpdate.changed) {
6511
+ changedFiles.push(dependencyUpdate.config);
6512
+ notes.push(`Run ${tooling.dependencies.manager} install to update the dependency lockfile.`);
6513
+ }
6514
+ if (!storageText || isGeneratedFilesStorageStub(storageText)) {
6515
+ if (await writeTextIfChanged(storagePath, filesS3StorageTemplate())) {
6516
+ changedFiles.push(config.modules.storageModule);
6517
+ }
6518
+ }
6519
+ config.storage.adapter = "s3";
6520
+ if (config.storage.provider) {
6521
+ config.storage.provider.localDevelopment = {
6522
+ kind: "minio",
6523
+ bucket,
6524
+ endpoint,
6525
+ };
6526
+ }
6527
+ feature.config = config;
6528
+ if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
6529
+ changedFiles.push("loom.json");
6530
+ }
6531
+ return {
6532
+ changedFiles,
6533
+ notes: [
6534
+ bucketStatus?.detail ?? `MinIO bucket \`${bucket}\` is ready.`,
6535
+ createdKey
6536
+ ? "Created a bucket-scoped MinIO access key and saved it to .env.local."
6537
+ : "Reused existing Files access credentials.",
6538
+ ...notes,
6539
+ ],
6540
+ };
6541
+ }
6542
+ async function checkLocalFilesEnvironment(cwd, options = {}) {
6543
+ const issues = [];
6544
+ const suggestions = [];
6545
+ const warnings = [];
6546
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, ".env.local"));
6547
+ const assignments = readEnvAssignments(text ?? "");
6548
+ const missing = FILES_LOCAL_ENV_NAMES.filter((name) => !assignments.get(name)?.value);
6549
+ if (!text || missing.length) {
6550
+ issues.push(!text
6551
+ ? "Files local storage is missing .env.local."
6552
+ : `Files .env.local is missing ${missing.join(", ")}.`);
6553
+ suggestions.push("Run `loom files local setup` to configure local MinIO.");
6554
+ suggestions.push("Install and start a MinIO server with `mcli` or `mc`, or configure another S3-compatible service with the canonical FILES_S3_* variables.");
6555
+ return { issues, suggestions, warnings };
6556
+ }
6557
+ const endpoint = assignments.get("FILES_S3_ENDPOINT")?.value ?? "";
6558
+ try {
6559
+ const url = new URL(endpoint);
6560
+ if (!["http:", "https:"].includes(url.protocol) || url.username ||
6561
+ url.password)
6562
+ throw new Error("invalid");
6563
+ }
6564
+ catch {
6565
+ issues.push("FILES_S3_ENDPOINT in .env.local must be an HTTP(S) URL without credentials.");
6566
+ }
6567
+ if (assignments.get("FILES_S3_FORCE_PATH_STYLE")?.value !== "true" &&
6568
+ assignments.get("FILES_STORAGE_PROVIDER")?.value === "minio") {
6569
+ issues.push("Local MinIO requires FILES_S3_FORCE_PATH_STYLE=true.");
6570
+ }
6571
+ if (options.verifyBucket && !issues.length) {
6572
+ const verified = await ensureMinioBucket(cwd, options.commandRunner ?? defaultCommandRunner, options.env ?? node_process_1.default.env, endpoint, assignments.get("FILES_S3_BUCKET")?.value ?? "", assignments.get("FILES_S3_ACCESS_KEY_ID")?.value ?? "", assignments.get("FILES_S3_SECRET_ACCESS_KEY")?.value ?? "", { create: false });
6573
+ if (!verified.ok) {
6574
+ issues.push("Files local bucket or credentials could not be verified.");
6575
+ suggestions.push("Start the configured storage server and check its endpoint, bucket, and credentials; use `loom files local setup` for MinIO.");
6576
+ if (verified.detail.includes("not available")) {
6577
+ suggestions.push("Install MinIO Client as `mcli` (Arch: `sudo pacman -S minio-client`) or `mc`.");
6578
+ }
6579
+ }
6580
+ }
6581
+ return { issues, suggestions, warnings };
6582
+ }
6117
6583
  function filesR2ProviderMatches(existing, desired) {
6118
6584
  if (!existing)
6119
6585
  return true;
@@ -6278,7 +6744,7 @@ async function setupCloudflareR2(cwd, options = {}) {
6278
6744
  const envLocalText = await readTextIfExists(envLocalPath);
6279
6745
  const localAssignments = readEnvAssignments(envLocalText ?? "");
6280
6746
  const localBucket = normalizeBucketName(options.localBucket ?? existingProvider?.localDevelopment.bucket ??
6281
- localAssignments.get("FILES_S3_BUCKET")?.value ?? `${baseName}-files`, "--local-bucket");
6747
+ localAssignments.get("FILES_S3_BUCKET")?.value ?? `${baseName}-dev`, "--local-bucket");
6282
6748
  const localEndpoint = options.localEndpoint ??
6283
6749
  existingProvider?.localDevelopment.endpoint ??
6284
6750
  localAssignments.get("FILES_S3_ENDPOINT")?.value ??
@@ -6360,13 +6826,6 @@ async function setupCloudflareR2(cwd, options = {}) {
6360
6826
  ? "minio"
6361
6827
  : "cloudflare-r2",
6362
6828
  };
6363
- if (!localAssignments.has("FILES_S3_ACCESS_KEY_ID") && env.MINIO_ROOT_USER) {
6364
- desiredLocalValues.FILES_S3_ACCESS_KEY_ID = env.MINIO_ROOT_USER;
6365
- }
6366
- if (!localAssignments.has("FILES_S3_SECRET_ACCESS_KEY") &&
6367
- env.MINIO_ROOT_PASSWORD) {
6368
- desiredLocalValues.FILES_S3_SECRET_ACCESS_KEY = env.MINIO_ROOT_PASSWORD;
6369
- }
6370
6829
  const localMerge = mergeEnvValues(envLocalText, desiredLocalValues, {
6371
6830
  neverReplace: new Set([
6372
6831
  "FILES_S3_ACCESS_KEY_ID",
@@ -6390,7 +6849,7 @@ async function setupCloudflareR2(cwd, options = {}) {
6390
6849
  notes.push(minio.detail);
6391
6850
  }
6392
6851
  else if (!localAccessKey || !localSecretKey) {
6393
- notes.push("Local storage credentials were not found. Add FILES_S3_ACCESS_KEY_ID and FILES_S3_SECRET_ACCESS_KEY to gitignored .env.local; Loom did not synthesize credentials.");
6852
+ notes.push("Local storage credentials were not found. Run `loom files local setup` to create a bucket-scoped MinIO key, or add credentials for another S3-compatible provider to gitignored .env.local.");
6394
6853
  }
6395
6854
  }
6396
6855
  const envListings = new Map();
@@ -7222,6 +7681,7 @@ function checkFilesNetworkFeature(context) {
7222
7681
  accountAvailable: false,
7223
7682
  vercelCommand: null,
7224
7683
  vercelLinked: false,
7684
+ vercelProject: null,
7225
7685
  wranglerCommand: null,
7226
7686
  };
7227
7687
  const providerEnv = {
@@ -7371,6 +7831,9 @@ function checkFilesNetworkFeature(context) {
7371
7831
  state.vercelCommand = detected.command;
7372
7832
  const link = await readVercelProjectLink(context.cwd);
7373
7833
  state.vercelLinked = link.linked;
7834
+ state.vercelProject = link.linked && link.orgId && link.projectId
7835
+ ? { orgId: link.orgId, projectId: link.projectId }
7836
+ : null;
7374
7837
  if (!state.vercelCommand || !state.vercelLinked) {
7375
7838
  return networkCheckResult("issue", !state.vercelCommand ? "Vercel CLI is unavailable." : link.detail, {
7376
7839
  issues: [
@@ -7400,10 +7863,14 @@ function checkFilesNetworkFeature(context) {
7400
7863
  steps.push({
7401
7864
  label: `Vercel ${environment} has all Files R2 variables`,
7402
7865
  run: async () => {
7403
- if (!state.vercelCommand || !state.vercelLinked) {
7866
+ if (!state.vercelCommand || !state.vercelLinked || !state.vercelProject) {
7404
7867
  return networkCheckResult("skipped", "Skipped until Vercel CLI/link checks pass.");
7405
7868
  }
7406
- const result = await context.commandRunner(state.vercelCommand, ["env", "ls", environment], { cwd: context.cwd, env: context.env, stdio: "pipe" });
7869
+ const result = await context.commandRunner(state.vercelCommand, buildVercelFilesEnvListArgs(environment, state.vercelProject), {
7870
+ cwd: context.cwd,
7871
+ env: withoutInheritedVercelProject(context.env),
7872
+ stdio: "pipe",
7873
+ });
7407
7874
  if (result.code !== 0) {
7408
7875
  return networkCheckResult("warning", `Could not list Vercel ${environment} env vars.`, {
7409
7876
  warnings: [
@@ -7431,7 +7898,7 @@ function checkFilesNetworkFeature(context) {
7431
7898
  `Could not inspect non-secret Files values in Vercel ${environment}.`,
7432
7899
  ],
7433
7900
  suggestions: [
7434
- `Run \`vercel env run -e ${environment} -- node -e '<inspect only FILES_S3_BUCKET/ENDPOINT/provider settings>'\` manually without printing credentials.`,
7901
+ `Run a non-secret Files probe from a temporary directory with \`vercel env run -e ${environment} --project <linked-project> --scope <linked-scope> -- node -e '<inspect only FILES_S3_BUCKET/ENDPOINT/provider settings>'\`.`,
7435
7902
  ],
7436
7903
  });
7437
7904
  }
@@ -7458,10 +7925,14 @@ function checkFilesNetworkFeature(context) {
7458
7925
  steps.push({
7459
7926
  label: "Vercel Development has no R2 Files credentials",
7460
7927
  run: async () => {
7461
- if (!state.vercelCommand || !state.vercelLinked) {
7928
+ if (!state.vercelCommand || !state.vercelLinked || !state.vercelProject) {
7462
7929
  return networkCheckResult("skipped", "Skipped until Vercel CLI/link checks pass.");
7463
7930
  }
7464
- const result = await context.commandRunner(state.vercelCommand, ["env", "ls", "development"], { cwd: context.cwd, env: context.env, stdio: "pipe" });
7931
+ const result = await context.commandRunner(state.vercelCommand, buildVercelFilesEnvListArgs("development", state.vercelProject), {
7932
+ cwd: context.cwd,
7933
+ env: withoutInheritedVercelProject(context.env),
7934
+ stdio: "pipe",
7935
+ });
7465
7936
  if (result.code !== 0) {
7466
7937
  return networkCheckResult("warning", "Could not list Vercel Development env vars.");
7467
7938
  }
@@ -7486,7 +7957,7 @@ function checkFilesNetworkFeature(context) {
7486
7957
  if (!text) {
7487
7958
  return networkCheckResult("issue", "Gitignored .env.local is missing.", {
7488
7959
  issues: ["Local MinIO Files configuration is missing."],
7489
- suggestions: ["Run `loom files r2 setup`."],
7960
+ suggestions: ["Run `loom files local setup`."],
7490
7961
  });
7491
7962
  }
7492
7963
  const assignments = readEnvAssignments(text);
@@ -7497,7 +7968,7 @@ function checkFilesNetworkFeature(context) {
7497
7968
  `Local MinIO Files variables are incomplete: ${missing.join(", ")}.`,
7498
7969
  ],
7499
7970
  suggestions: [
7500
- "Add the existing MinIO credentials to .env.local; Loom never synthesizes or replaces them.",
7971
+ "Run `loom files local setup` to create a scoped MinIO key, or add an existing credential pair to .env.local.",
7501
7972
  ],
7502
7973
  });
7503
7974
  }
@@ -7511,7 +7982,7 @@ function checkFilesNetworkFeature(context) {
7511
7982
  "Local MinIO is configured but the bucket could not be verified.",
7512
7983
  ],
7513
7984
  suggestions: [
7514
- "Start MinIO or correct FILES_S3_ENDPOINT, then rerun `loom files r2 check`.",
7985
+ "Start MinIO or correct FILES_S3_ENDPOINT, then rerun `loom files local check`.",
7515
7986
  ],
7516
7987
  });
7517
7988
  },
@@ -9113,6 +9584,17 @@ async function checkFilesFeature(cwd, framework, manifest, options) {
9113
9584
  : "Rerun `loom files r2 setup`; existing buckets and working credentials will be reused.");
9114
9585
  }
9115
9586
  }
9587
+ if (!options.production && provider?.localDevelopment.kind !== "none" &&
9588
+ (config.storage.adapter === "s3" ||
9589
+ (storageText !== null && isGeneratedFilesStorageStub(storageText)))) {
9590
+ const local = await checkLocalFilesEnvironment(cwd);
9591
+ if (config.storage.adapter === "s3")
9592
+ issues.push(...local.issues);
9593
+ else
9594
+ warnings.push(...local.issues);
9595
+ for (const suggestion of local.suggestions)
9596
+ suggestions.add(suggestion);
9597
+ }
9116
9598
  const routeText = await readTextIfExists((0, node_path_1.join)(cwd, config.entrypoints.routeHandler));
9117
9599
  if (!routeText) {
9118
9600
  issues.push(`Files route handler is missing: ${config.entrypoints.routeHandler}`);
@@ -10845,8 +11327,9 @@ function printHelp({ out }) {
10845
11327
  out(" init Set up package/Deno config, loom.json, managed AGENTS.md guidance, first-party links, and package skills.");
10846
11328
  out(" add <feature> Activate a shared feature. Run `loom add` to list available features.");
10847
11329
  out(" files id-generation uuid-v4|uuid-v7 Select the managed Files schema ID default.");
10848
- out(" files r2 setup Create/reuse private Cloudflare R2 buckets, configure Vercel Production/Preview, and configure local MinIO by default.");
10849
- out(" files r2 check Verify R2 buckets/account/privacy, Vercel env scoping, local MinIO, and Files adapter wiring.");
11330
+ out(" files local setup|check Provision or verify local MinIO and .env.local without R2/Vercel.");
11331
+ out(" files r2 setup Create/reuse private Cloudflare R2 buckets and configure Vercel Production/Preview.");
11332
+ out(" files r2 check Verify R2 buckets/account/privacy, Vercel env scoping, local storage, and Files adapter wiring.");
10850
11333
  out(" api-keys integrate jobs Record an explicit API-key jobs integration after the route has session/admin authorization.");
10851
11334
  out(" api-keys retention enable|disable Record API-key audit cleanup policy; scheduling remains app-owned.");
10852
11335
  out(" status Show the Loom package, manifest, active features, local-dev state, and project skill state.");
@@ -10960,8 +11443,53 @@ async function runFiles(cwd, command, target, options, io) {
10960
11443
  io.out(`Note: ${note}`);
10961
11444
  return 0;
10962
11445
  }
11446
+ if (command === "local") {
11447
+ if (target === "setup") {
11448
+ const result = await setupLocalFiles(cwd, {
11449
+ localBucket: options.localBucket,
11450
+ localEndpoint: options.localEndpoint,
11451
+ });
11452
+ io.out(result.changedFiles.length
11453
+ ? `Updated ${result.changedFiles.join(", ")}.`
11454
+ : "Files local storage already matches the configuration.");
11455
+ for (const note of result.notes)
11456
+ io.out(`Note: ${note}`);
11457
+ return 0;
11458
+ }
11459
+ if (target === "check") {
11460
+ const manifestText = await readTextIfExists((0, node_path_1.join)(cwd, "loom.json"));
11461
+ const manifest = manifestText
11462
+ ? parseJson(manifestText, "loom.json")
11463
+ : null;
11464
+ if (manifest?.features.files?.status !== "active") {
11465
+ io.err("The files feature is not active. Run `loom add files` first.");
11466
+ return 1;
11467
+ }
11468
+ const filesConfig = manifest.features.files.config;
11469
+ if (filesConfig?.storage?.provider?.localDevelopment.kind === "none") {
11470
+ io.out("Files local storage is disabled in loom.json.");
11471
+ return 0;
11472
+ }
11473
+ const result = await checkLocalFilesEnvironment(cwd, {
11474
+ verifyBucket: true,
11475
+ });
11476
+ if (result.issues.length) {
11477
+ io.err("loom files local check found setup issues:");
11478
+ for (const issue of result.issues)
11479
+ io.err(`- ${issue}`);
11480
+ for (const suggestion of result.suggestions) {
11481
+ io.err(`Suggestion: ${suggestion}`);
11482
+ }
11483
+ return 1;
11484
+ }
11485
+ io.out("loom files local check: setup looks good.");
11486
+ return 0;
11487
+ }
11488
+ io.err("Usage: loom files local setup|check [--local-endpoint <url>] [--local-bucket <name>]");
11489
+ return 1;
11490
+ }
10963
11491
  if (command !== "r2" || !target) {
10964
- io.err("Usage: loom files id-generation uuid-v4|uuid-v7\n or: loom files r2 setup|check [R2 options]");
11492
+ io.err("Usage: loom files id-generation uuid-v4|uuid-v7\n or: loom files local setup|check\n or: loom files r2 setup|check [R2 options]");
10965
11493
  return 1;
10966
11494
  }
10967
11495
  const jurisdiction = options.jurisdiction;