@dz9systems/vibeinfra 0.0.0-stage → 0.0.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.
- package/README.md +129 -2
- package/TERMS.md +19 -0
- package/dist/bin.js +841 -0
- package/dist/chunks/chunk-ZDFLQZGF.js +1452 -0
- package/dist/chunks/src-AV3FZUMU.js +794 -0
- package/package.json +46 -4
|
@@ -0,0 +1,1452 @@
|
|
|
1
|
+
// packages/core/src/constants.ts
|
|
2
|
+
var PHASE1_APIS = ["firebase.googleapis.com", "firebasehosting.googleapis.com"];
|
|
3
|
+
var PUBLIC_ENV_KEYS = [
|
|
4
|
+
"VITE_FIREBASE_API_KEY",
|
|
5
|
+
"VITE_FIREBASE_AUTH_DOMAIN",
|
|
6
|
+
"VITE_FIREBASE_PROJECT_ID",
|
|
7
|
+
"VITE_FIREBASE_STORAGE_BUCKET",
|
|
8
|
+
"VITE_FIREBASE_MESSAGING_SENDER_ID",
|
|
9
|
+
"VITE_FIREBASE_APP_ID",
|
|
10
|
+
"VITE_FIREBASE_MEASUREMENT_ID"
|
|
11
|
+
];
|
|
12
|
+
var DEFAULT_HOSTING_IGNORE = ["firebase.json", "**/.*", "**/node_modules/**"];
|
|
13
|
+
var STRIPPED_BUILD_ENV = [
|
|
14
|
+
"GOOGLE_APPLICATION_CREDENTIALS",
|
|
15
|
+
"FIREBASE_TOKEN",
|
|
16
|
+
"GOOGLE_OAUTH_ACCESS_TOKEN",
|
|
17
|
+
"CLOUDSDK_AUTH_ACCESS_TOKEN"
|
|
18
|
+
];
|
|
19
|
+
var ADC_LOGIN_COMMAND = "gcloud auth application-default login";
|
|
20
|
+
var IAM_NOTE = "Creating a project requires resourcemanager.projects.create. Adding Firebase requires Editor or Owner, including firebase.projects.update, resourcemanager.projects.get, serviceusage.services.enable, and serviceusage.services.get. Registering a web app requires firebase.clients.create. Deploying Hosting requires firebasehosting.sites.update. This plan does not change billing.";
|
|
21
|
+
|
|
22
|
+
// packages/core/src/redact.ts
|
|
23
|
+
var REPLACEMENTS = [
|
|
24
|
+
[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "[REDACTED_PRIVATE_KEY]"],
|
|
25
|
+
[/ya29\.[0-9A-Za-z\-_]+/g, "[REDACTED_ACCESS_TOKEN]"],
|
|
26
|
+
[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi, "Bearer [REDACTED]"],
|
|
27
|
+
[/"private_key"\s*:\s*"(?:\\.|[^"\\])*"/g, '"private_key":"[REDACTED]"'],
|
|
28
|
+
[/"refresh_token"\s*:\s*"(?:\\.|[^"\\])*"/g, '"refresh_token":"[REDACTED]"'],
|
|
29
|
+
[/"client_secret"\s*:\s*"(?:\\.|[^"\\])*"/g, '"client_secret":"[REDACTED]"'],
|
|
30
|
+
[/\bsk_live_[0-9a-zA-Z]+\b/g, "[REDACTED_STRIPE_KEY]"],
|
|
31
|
+
[/\bxox[baprs]-[A-Za-z0-9-]+\b/g, "[REDACTED_SLACK_TOKEN]"]
|
|
32
|
+
];
|
|
33
|
+
function redact(value) {
|
|
34
|
+
return REPLACEMENTS.reduce((current, [pattern, replacement]) => current.replace(pattern, replacement), value);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// packages/core/src/errors.ts
|
|
38
|
+
var VibeInfraError = class extends Error {
|
|
39
|
+
code;
|
|
40
|
+
remediation;
|
|
41
|
+
retryable;
|
|
42
|
+
category;
|
|
43
|
+
httpStatus;
|
|
44
|
+
constructor(input) {
|
|
45
|
+
super(redact(input.message), input.cause !== void 0 ? { cause: input.cause } : void 0);
|
|
46
|
+
this.name = "VibeInfraError";
|
|
47
|
+
this.code = input.code;
|
|
48
|
+
this.remediation = redact(input.remediation);
|
|
49
|
+
this.retryable = input.retryable ?? false;
|
|
50
|
+
this.category = input.category ?? "user";
|
|
51
|
+
if (input.httpStatus !== void 0) {
|
|
52
|
+
this.httpStatus = input.httpStatus;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
toJSON() {
|
|
56
|
+
return {
|
|
57
|
+
code: this.code,
|
|
58
|
+
message: this.message,
|
|
59
|
+
remediation: this.remediation,
|
|
60
|
+
retryable: this.retryable,
|
|
61
|
+
category: this.category,
|
|
62
|
+
...this.httpStatus !== void 0 ? { httpStatus: this.httpStatus } : {}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
function toVibeInfraError(error) {
|
|
67
|
+
if (error instanceof VibeInfraError) {
|
|
68
|
+
return error;
|
|
69
|
+
}
|
|
70
|
+
const message = error instanceof Error ? error.message : "Unexpected failure.";
|
|
71
|
+
return new VibeInfraError({
|
|
72
|
+
code: "internal",
|
|
73
|
+
message,
|
|
74
|
+
remediation: "Retry the command. If it fails again, inspect the redacted details and confirm Application Default Credentials are available.",
|
|
75
|
+
category: "provider",
|
|
76
|
+
cause: error
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// packages/core/src/journal.ts
|
|
81
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
82
|
+
import path from "node:path";
|
|
83
|
+
var JOURNAL_DIRECTORY = ".vibeinfra";
|
|
84
|
+
function journalPath(projectPath) {
|
|
85
|
+
return path.join(projectPath, JOURNAL_DIRECTORY, "journal.json");
|
|
86
|
+
}
|
|
87
|
+
async function readJournal(projectPath) {
|
|
88
|
+
return readJournalFile(journalPath(projectPath));
|
|
89
|
+
}
|
|
90
|
+
async function readJournalFile(file) {
|
|
91
|
+
try {
|
|
92
|
+
const text = await readFile(file, "utf8");
|
|
93
|
+
const parsed = JSON.parse(text);
|
|
94
|
+
if (parsed.version !== 1) {
|
|
95
|
+
throw new VibeInfraError({
|
|
96
|
+
code: "journal_incompatible",
|
|
97
|
+
message: "The deployment journal was written by a different VibeInfra version.",
|
|
98
|
+
remediation: "Deploy without --resume to write a new journal. Existing cloud resources will be reconciled and nothing will be deleted."
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
return parsed;
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (error instanceof VibeInfraError) {
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
if (isNotFound(error)) {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
if (error instanceof SyntaxError) {
|
|
110
|
+
throw new VibeInfraError({
|
|
111
|
+
code: "journal_corrupt",
|
|
112
|
+
message: "The deployment journal is not valid JSON.",
|
|
113
|
+
remediation: `Inspect ${file}. Deploy without --resume after fixing or removing it.`
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
async function writeJournal(projectPath, journal) {
|
|
120
|
+
const serialized = JSON.stringify(journal, null, 2);
|
|
121
|
+
if (redact(serialized) !== serialized) {
|
|
122
|
+
throw new VibeInfraError({
|
|
123
|
+
code: "journal_secret",
|
|
124
|
+
message: "Refusing to write a deployment journal that contains credential material.",
|
|
125
|
+
remediation: "This is a VibeInfra bug. Retry only after the journal contents are redacted.",
|
|
126
|
+
category: "provider"
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
const file = journalPath(projectPath);
|
|
130
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
131
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
132
|
+
await writeFile(temporary, `${serialized}
|
|
133
|
+
`, "utf8");
|
|
134
|
+
await rename(temporary, file);
|
|
135
|
+
}
|
|
136
|
+
function isNotFound(error) {
|
|
137
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// packages/core/src/project-id.ts
|
|
141
|
+
var PROJECT_ID = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;
|
|
142
|
+
var PARENT = /^(organizations|folders)\/[0-9]+$/;
|
|
143
|
+
var RESERVED = /* @__PURE__ */ new Set(["null", "undefined", "ssl"]);
|
|
144
|
+
function assertProjectId(projectId) {
|
|
145
|
+
if (!PROJECT_ID.test(projectId) || projectId.includes("google") || RESERVED.has(projectId)) {
|
|
146
|
+
throw new VibeInfraError({
|
|
147
|
+
code: "invalid_project_id",
|
|
148
|
+
message: `Project id "${projectId}" is not a valid Google Cloud project id.`,
|
|
149
|
+
remediation: "Use 6 to 30 lowercase letters, digits, or hyphens. Start with a letter, do not end with a hyphen, and avoid reserved words such as google, null, undefined, and ssl."
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function assertParent(parent) {
|
|
154
|
+
if (!PARENT.test(parent)) {
|
|
155
|
+
throw new VibeInfraError({
|
|
156
|
+
code: "invalid_parent",
|
|
157
|
+
message: `Parent "${parent}" is not an organization or folder resource.`,
|
|
158
|
+
remediation: "Pass --parent organizations/ORGANIZATION_NUMBER or --parent folders/FOLDER_NUMBER. VibeInfra does not choose a parent for you."
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
function assertWebAppId(appId) {
|
|
163
|
+
if (!/^[0-9]+:[0-9]+:web:[A-Za-z0-9]+$/.test(appId)) {
|
|
164
|
+
throw new VibeInfraError({
|
|
165
|
+
code: "invalid_app_id",
|
|
166
|
+
message: `Web app id "${appId}" is not a Firebase web app id.`,
|
|
167
|
+
remediation: "Pass the appId from `vibeinfra doctor --project PROJECT` or the Firebase console. It looks like 1:123456:web:abc."
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function assertServiceId(serviceId) {
|
|
172
|
+
if (!/^[a-z0-9.-]+\.googleapis\.com$/.test(serviceId)) {
|
|
173
|
+
throw new VibeInfraError({
|
|
174
|
+
code: "invalid_service_id",
|
|
175
|
+
message: `Service id "${serviceId}" is not a Google API service name.`,
|
|
176
|
+
remediation: "Use a service name such as firebase.googleapis.com.",
|
|
177
|
+
category: "provider"
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
var OPERATION_SEGMENT = /^[A-Za-z0-9._~-]+$/;
|
|
182
|
+
function assertOperationName(name) {
|
|
183
|
+
const segments = name.split("/");
|
|
184
|
+
const body = segments.slice(1);
|
|
185
|
+
const accepted = segments[0] === "operations" && body.length > 0 && body.every((segment) => OPERATION_SEGMENT.test(segment) && segment !== "." && segment !== "..");
|
|
186
|
+
if (!accepted) {
|
|
187
|
+
throw new VibeInfraError({
|
|
188
|
+
code: "invalid_operation",
|
|
189
|
+
message: `The Google API returned an operation name VibeInfra will not poll (${operationShape(name)}).`,
|
|
190
|
+
remediation: "Retry the command. If it happens again, wait a minute and resume so existing resources can be reconciled.",
|
|
191
|
+
category: "provider"
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
function operationShape(name) {
|
|
196
|
+
const shaped = name.replace(/[A-Za-z0-9]/g, "x").slice(0, 160);
|
|
197
|
+
return shaped.length > 0 ? shaped : "empty";
|
|
198
|
+
}
|
|
199
|
+
function assertHostingSiteId(siteId) {
|
|
200
|
+
if (!/^[a-z0-9-]{4,30}$/.test(siteId) || siteId.startsWith("-") || siteId.endsWith("-")) {
|
|
201
|
+
throw new VibeInfraError({
|
|
202
|
+
code: "invalid_site_id",
|
|
203
|
+
message: `Hosting site "${siteId}" cannot be used in a verification URL.`,
|
|
204
|
+
remediation: "Use a default Hosting site id made of lowercase letters, digits, and hyphens.",
|
|
205
|
+
category: "provider"
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
function cleanDisplayName(value, fallback) {
|
|
210
|
+
const cleaned = (value ?? "").replace(/[\u0000-\u001F\u007F]/g, " ").replace(/\s+/g, " ").trim();
|
|
211
|
+
return (cleaned || fallback).slice(0, 80);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// packages/core/src/plan.ts
|
|
215
|
+
import { randomUUID } from "node:crypto";
|
|
216
|
+
import { access } from "node:fs/promises";
|
|
217
|
+
import path4 from "node:path";
|
|
218
|
+
|
|
219
|
+
// packages/core/src/local-files.ts
|
|
220
|
+
import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "node:fs/promises";
|
|
221
|
+
import path2 from "node:path";
|
|
222
|
+
var SPA_REWRITE = { source: "**", destination: "/index.html" };
|
|
223
|
+
var GITIGNORE_LINES = [".env", ".env.local", ".env.*.local", ".vibeinfra/", ".vibedeploy/"];
|
|
224
|
+
function mergeFirebaseJson(existing, input) {
|
|
225
|
+
if (!existing) {
|
|
226
|
+
const hosting2 = {
|
|
227
|
+
public: input.outputDirectory,
|
|
228
|
+
ignore: [...DEFAULT_HOSTING_IGNORE]
|
|
229
|
+
};
|
|
230
|
+
if (input.spaRewrite) {
|
|
231
|
+
hosting2.rewrites = [SPA_REWRITE];
|
|
232
|
+
}
|
|
233
|
+
return { next: { hosting: hosting2 }, action: "create", warnings: [] };
|
|
234
|
+
}
|
|
235
|
+
const next = structuredClone(existing);
|
|
236
|
+
if (Array.isArray(next.hosting)) {
|
|
237
|
+
return {
|
|
238
|
+
next,
|
|
239
|
+
action: "unchanged",
|
|
240
|
+
warnings: [
|
|
241
|
+
"firebase.json contains multiple Hosting sites. VibeInfra will not edit that array. Deploy runs Firebase CLI with --only hosting, which publishes every site in the file."
|
|
242
|
+
]
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
if (next.hosting?.source) {
|
|
246
|
+
return {
|
|
247
|
+
next,
|
|
248
|
+
action: "unchanged",
|
|
249
|
+
warnings: [],
|
|
250
|
+
blocked: {
|
|
251
|
+
code: "framework_hosting_config",
|
|
252
|
+
message: "firebase.json hosting.source uses Firebase web frameworks. Phase 1 only deploys a static public directory and will not rewrite that configuration."
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
const warnings = [];
|
|
257
|
+
const hosting = { ...next.hosting ?? {} };
|
|
258
|
+
if (!hosting.public) {
|
|
259
|
+
hosting.public = input.outputDirectory;
|
|
260
|
+
} else if (hosting.public !== input.outputDirectory) {
|
|
261
|
+
warnings.push(
|
|
262
|
+
`firebase.json hosting.public is "${hosting.public}", which does not match the detected output "${input.outputDirectory}". The existing public directory was kept.`
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
if (!hosting.ignore) {
|
|
266
|
+
hosting.ignore = [...DEFAULT_HOSTING_IGNORE];
|
|
267
|
+
}
|
|
268
|
+
if (input.spaRewrite) {
|
|
269
|
+
const rewrites = [...hosting.rewrites ?? []];
|
|
270
|
+
if (!rewrites.some((rewrite) => rewrite.source === "**")) {
|
|
271
|
+
rewrites.push(SPA_REWRITE);
|
|
272
|
+
hosting.rewrites = rewrites;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
next.hosting = hosting;
|
|
276
|
+
const action = stable(existing) === stable(next) ? "unchanged" : "update";
|
|
277
|
+
return { next, action, warnings };
|
|
278
|
+
}
|
|
279
|
+
function mergeFirebaserc(existing, projectId) {
|
|
280
|
+
const next = structuredClone(existing ?? {});
|
|
281
|
+
const projects = { ...next.projects ?? {} };
|
|
282
|
+
projects.default = projectId;
|
|
283
|
+
next.projects = projects;
|
|
284
|
+
if (!existing) {
|
|
285
|
+
return { next, action: "create", warnings: [] };
|
|
286
|
+
}
|
|
287
|
+
const action = stable(existing) === stable(next) ? "unchanged" : "update";
|
|
288
|
+
const warnings = existing.projects?.default && existing.projects.default !== projectId ? [`The Firebase alias "default" will change from "${existing.projects.default}" to "${projectId}". Other aliases are preserved.`] : [];
|
|
289
|
+
return { next, action, warnings };
|
|
290
|
+
}
|
|
291
|
+
function mergeGitignore(existing) {
|
|
292
|
+
const lines = existing ? existing.split(/\r?\n/) : ["# Private env files and local VibeInfra state."];
|
|
293
|
+
const present = new Set(lines.map((line) => line.trim()));
|
|
294
|
+
const added = GITIGNORE_LINES.filter((line) => !present.has(line));
|
|
295
|
+
if (added.length === 0 && existing !== null) {
|
|
296
|
+
return { next: existing, action: "unchanged", warnings: [] };
|
|
297
|
+
}
|
|
298
|
+
const body = [...lines.filter((line, index) => line !== "" || index !== lines.length - 1), ...added].join("\n");
|
|
299
|
+
return {
|
|
300
|
+
next: body.endsWith("\n") ? body : `${body}
|
|
301
|
+
`,
|
|
302
|
+
action: existing === null ? "create" : "update",
|
|
303
|
+
warnings: []
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
function referencedPublicEnvKeys(references) {
|
|
307
|
+
const wanted = new Set(references);
|
|
308
|
+
return PUBLIC_ENV_KEYS.filter((key) => wanted.has(key));
|
|
309
|
+
}
|
|
310
|
+
function renderEnvFile(existing, assignments) {
|
|
311
|
+
const keys = Object.keys(assignments);
|
|
312
|
+
if (keys.length === 0) {
|
|
313
|
+
return { next: existing ?? "", action: "unchanged", warnings: [] };
|
|
314
|
+
}
|
|
315
|
+
const lines = existing ? existing.split(/\r?\n/) : [];
|
|
316
|
+
const seen = /* @__PURE__ */ new Set();
|
|
317
|
+
const nextLines = lines.map((line) => {
|
|
318
|
+
const match = /^([A-Za-z_][A-Za-z0-9_]*)=/.exec(line);
|
|
319
|
+
if (!match || !(match[1] in assignments)) {
|
|
320
|
+
return line;
|
|
321
|
+
}
|
|
322
|
+
seen.add(match[1]);
|
|
323
|
+
return `${match[1]}=${assignments[match[1]]}`;
|
|
324
|
+
});
|
|
325
|
+
for (const key of keys) {
|
|
326
|
+
if (!seen.has(key)) {
|
|
327
|
+
nextLines.push(`${key}=${assignments[key]}`);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
const trimmed = nextLines.filter((line, index) => line !== "" || index !== nextLines.length - 1);
|
|
331
|
+
const next = `${trimmed.join("\n")}
|
|
332
|
+
`;
|
|
333
|
+
if (existing !== null && existing === next) {
|
|
334
|
+
return { next, action: "unchanged", warnings: [] };
|
|
335
|
+
}
|
|
336
|
+
return { next, action: existing === null ? "create" : "update", warnings: [] };
|
|
337
|
+
}
|
|
338
|
+
function envAssignments(keys, config, includeValues) {
|
|
339
|
+
const values = config ? {
|
|
340
|
+
VITE_FIREBASE_API_KEY: config.apiKey,
|
|
341
|
+
VITE_FIREBASE_AUTH_DOMAIN: config.authDomain,
|
|
342
|
+
VITE_FIREBASE_PROJECT_ID: config.projectId,
|
|
343
|
+
VITE_FIREBASE_STORAGE_BUCKET: config.storageBucket,
|
|
344
|
+
VITE_FIREBASE_MESSAGING_SENDER_ID: config.messagingSenderId,
|
|
345
|
+
VITE_FIREBASE_APP_ID: config.appId,
|
|
346
|
+
VITE_FIREBASE_MEASUREMENT_ID: config.measurementId
|
|
347
|
+
} : {};
|
|
348
|
+
const assignments = {};
|
|
349
|
+
for (const key of keys) {
|
|
350
|
+
const value = includeValues ? values[key] ?? "" : "";
|
|
351
|
+
if (value.includes("\n") || value.includes("\r") || value.includes("\0")) {
|
|
352
|
+
throw new VibeInfraError({
|
|
353
|
+
code: "unsafe_env_value",
|
|
354
|
+
message: `Refusing to write ${key} because the Firebase web config value is not a single line.`,
|
|
355
|
+
remediation: "Retrieve the web app config from the Firebase console and inspect it before writing environment files.",
|
|
356
|
+
category: "provider"
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
assignments[key] = value;
|
|
360
|
+
}
|
|
361
|
+
return assignments;
|
|
362
|
+
}
|
|
363
|
+
function describeFileChanges(input) {
|
|
364
|
+
const changes = [];
|
|
365
|
+
if (input.firebase) {
|
|
366
|
+
changes.push({
|
|
367
|
+
path: "firebase.json",
|
|
368
|
+
action: input.firebase.action,
|
|
369
|
+
description: input.firebase.action === "unchanged" ? "Existing Hosting configuration is preserved." : "Merge the static Hosting public directory, ignore list, and SPA rewrite when those fields are absent."
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
if (input.firebaserc) {
|
|
373
|
+
changes.push({
|
|
374
|
+
path: ".firebaserc",
|
|
375
|
+
action: input.firebaserc.action,
|
|
376
|
+
description: "Set the default project alias. Other aliases and targets are preserved."
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
changes.push({
|
|
380
|
+
path: ".gitignore",
|
|
381
|
+
action: input.gitignore.action,
|
|
382
|
+
description: "Ensure .env files and the local VibeInfra directory are ignored."
|
|
383
|
+
});
|
|
384
|
+
if (input.envKeys.length > 0) {
|
|
385
|
+
changes.push({
|
|
386
|
+
path: ".env.example",
|
|
387
|
+
action: input.envExampleExists ? "update" : "create",
|
|
388
|
+
description: `Add empty placeholders for ${input.envKeys.join(", ")}.`
|
|
389
|
+
});
|
|
390
|
+
changes.push({
|
|
391
|
+
path: ".env.local",
|
|
392
|
+
action: input.envLocalExists ? "update" : "create",
|
|
393
|
+
description: "Write the public Firebase web config for the referenced VITE_FIREBASE_* variables. Values are not secrets, and they are not printed in the plan."
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
return changes;
|
|
397
|
+
}
|
|
398
|
+
async function applyApprovedFiles(input) {
|
|
399
|
+
const firebasePath = path2.join(input.projectPath, "firebase.json");
|
|
400
|
+
const rcPath = path2.join(input.projectPath, ".firebaserc");
|
|
401
|
+
const gitignorePath = path2.join(input.projectPath, ".gitignore");
|
|
402
|
+
const examplePath = path2.join(input.projectPath, ".env.example");
|
|
403
|
+
const localPath = path2.join(input.projectPath, ".env.local");
|
|
404
|
+
const existingJson = await readOptionalJson(firebasePath);
|
|
405
|
+
if (existingJson.error) {
|
|
406
|
+
throw new VibeInfraError({
|
|
407
|
+
code: "invalid_firebase_json",
|
|
408
|
+
message: `firebase.json could not be parsed: ${existingJson.error}`,
|
|
409
|
+
remediation: "Fix firebase.json before deploying. VibeInfra will not overwrite a file it cannot parse."
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
const firebase = mergeFirebaseJson(existingJson.value, input);
|
|
413
|
+
if (firebase.blocked) {
|
|
414
|
+
throw new VibeInfraError({
|
|
415
|
+
code: firebase.blocked.code,
|
|
416
|
+
message: firebase.blocked.message,
|
|
417
|
+
remediation: "Adjust firebase.json yourself, then run the command again."
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
const existingRc = await readOptionalJson(rcPath);
|
|
421
|
+
if (existingRc.error) {
|
|
422
|
+
throw new VibeInfraError({
|
|
423
|
+
code: "invalid_firebaserc",
|
|
424
|
+
message: `.firebaserc could not be parsed: ${existingRc.error}`,
|
|
425
|
+
remediation: "Fix .firebaserc before deploying. VibeInfra will not overwrite a file it cannot parse."
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
const firebaserc = mergeFirebaserc(existingRc.value, input.projectId);
|
|
429
|
+
const gitignore = mergeGitignore(await readOptionalText(gitignorePath));
|
|
430
|
+
const example = renderEnvFile(await readOptionalText(examplePath), envAssignments(input.envKeys, null, false));
|
|
431
|
+
const local = renderEnvFile(await readOptionalText(localPath), envAssignments(input.envKeys, input.webConfig, true));
|
|
432
|
+
await writeIfChanged(firebasePath, firebase.action, `${JSON.stringify(firebase.next, null, 2)}
|
|
433
|
+
`);
|
|
434
|
+
await writeIfChanged(rcPath, firebaserc.action, `${JSON.stringify(firebaserc.next, null, 2)}
|
|
435
|
+
`);
|
|
436
|
+
await writeIfChanged(gitignorePath, gitignore.action, gitignore.next);
|
|
437
|
+
await writeIfChanged(examplePath, example.action, example.next);
|
|
438
|
+
await writeIfChanged(localPath, local.action, local.next);
|
|
439
|
+
return describeFileChanges({
|
|
440
|
+
firebase,
|
|
441
|
+
firebaserc,
|
|
442
|
+
gitignore,
|
|
443
|
+
envKeys: input.envKeys,
|
|
444
|
+
envExampleExists: example.action !== "create",
|
|
445
|
+
envLocalExists: local.action !== "create"
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
async function writeIfChanged(file, action, contents) {
|
|
449
|
+
if (action === "unchanged") {
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
await mkdir2(path2.dirname(file), { recursive: true });
|
|
453
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
454
|
+
await writeFile2(temporary, contents, "utf8");
|
|
455
|
+
const { rename: rename2 } = await import("node:fs/promises");
|
|
456
|
+
await rename2(temporary, file);
|
|
457
|
+
}
|
|
458
|
+
async function readOptionalText(file) {
|
|
459
|
+
try {
|
|
460
|
+
return await readFile2(file, "utf8");
|
|
461
|
+
} catch (error) {
|
|
462
|
+
if (isNotFound2(error)) {
|
|
463
|
+
return null;
|
|
464
|
+
}
|
|
465
|
+
throw error;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
async function readOptionalJson(file) {
|
|
469
|
+
const text = await readOptionalText(file);
|
|
470
|
+
if (text === null) {
|
|
471
|
+
return { value: null, error: null };
|
|
472
|
+
}
|
|
473
|
+
try {
|
|
474
|
+
return { value: JSON.parse(text), error: null };
|
|
475
|
+
} catch (error) {
|
|
476
|
+
return { value: null, error: error instanceof Error ? error.message : "Invalid JSON." };
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
function stable(value) {
|
|
480
|
+
return JSON.stringify(sortKeys(value));
|
|
481
|
+
}
|
|
482
|
+
function sortKeys(value) {
|
|
483
|
+
if (Array.isArray(value)) {
|
|
484
|
+
return value.map(sortKeys);
|
|
485
|
+
}
|
|
486
|
+
if (value && typeof value === "object") {
|
|
487
|
+
return Object.fromEntries(
|
|
488
|
+
Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => [key, sortKeys(entry)])
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
return value;
|
|
492
|
+
}
|
|
493
|
+
function isNotFound2(error) {
|
|
494
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// packages/core/src/output-path.ts
|
|
498
|
+
import path3 from "node:path";
|
|
499
|
+
function assertSafeOutputDirectory(projectPath, outputDirectory) {
|
|
500
|
+
if (outputDirectory.trim() === "" || outputDirectory === ".") {
|
|
501
|
+
throw unsafe("The Hosting public directory is the project root.");
|
|
502
|
+
}
|
|
503
|
+
if (path3.isAbsolute(outputDirectory)) {
|
|
504
|
+
throw unsafe("The Hosting public directory is absolute.");
|
|
505
|
+
}
|
|
506
|
+
const root = path3.resolve(projectPath);
|
|
507
|
+
const resolved = path3.resolve(root, outputDirectory);
|
|
508
|
+
const relative = path3.relative(root, resolved);
|
|
509
|
+
if (relative === "" || relative.startsWith("..") || path3.isAbsolute(relative)) {
|
|
510
|
+
throw unsafe("The Hosting public directory escapes the project.");
|
|
511
|
+
}
|
|
512
|
+
return relative.split(path3.sep).join("/");
|
|
513
|
+
}
|
|
514
|
+
function unsafe(message) {
|
|
515
|
+
return new VibeInfraError({
|
|
516
|
+
code: "unsafe_output_directory",
|
|
517
|
+
message: `${message} VibeInfra will not deploy it.`,
|
|
518
|
+
remediation: "Point hosting.public, or --output, at a relative build directory such as dist. Deploying the project root can publish env files and credentials."
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// packages/core/src/plan.ts
|
|
523
|
+
var PACKAGE_MANAGERS = /* @__PURE__ */ new Set(["npm", "pnpm", "yarn", "bun"]);
|
|
524
|
+
function createDeploymentPlan(analysis, options, context = {}) {
|
|
525
|
+
const blockers = [];
|
|
526
|
+
const warnings = [...analysis.warnings];
|
|
527
|
+
const now = context.now ?? (() => /* @__PURE__ */ new Date());
|
|
528
|
+
const projectId = options.projectId ?? null;
|
|
529
|
+
if (projectId) {
|
|
530
|
+
try {
|
|
531
|
+
assertProjectId(projectId);
|
|
532
|
+
} catch (error) {
|
|
533
|
+
if (error instanceof VibeInfraError) {
|
|
534
|
+
blockers.push({ code: error.code, message: error.message });
|
|
535
|
+
} else {
|
|
536
|
+
throw error;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
if (options.parent) {
|
|
541
|
+
try {
|
|
542
|
+
assertParent(options.parent);
|
|
543
|
+
} catch (error) {
|
|
544
|
+
if (error instanceof VibeInfraError) {
|
|
545
|
+
blockers.push({ code: error.code, message: error.message });
|
|
546
|
+
} else {
|
|
547
|
+
throw error;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
if (options.appId) {
|
|
552
|
+
try {
|
|
553
|
+
assertWebAppId(options.appId);
|
|
554
|
+
} catch (error) {
|
|
555
|
+
if (error instanceof VibeInfraError) {
|
|
556
|
+
blockers.push({ code: error.code, message: error.message });
|
|
557
|
+
} else {
|
|
558
|
+
throw error;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
if (!analysis.supported && analysis.unsupportedReason) {
|
|
563
|
+
blockers.push({ code: "unsupported_framework", message: analysis.unsupportedReason });
|
|
564
|
+
}
|
|
565
|
+
if (analysis.firebaseJsonError) {
|
|
566
|
+
blockers.push({
|
|
567
|
+
code: "invalid_firebase_json",
|
|
568
|
+
message: `firebase.json could not be parsed: ${analysis.firebaseJsonError}`
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
if (analysis.firebasercError) {
|
|
572
|
+
blockers.push({
|
|
573
|
+
code: "invalid_firebaserc",
|
|
574
|
+
message: `.firebaserc could not be parsed: ${analysis.firebasercError}`
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
if (analysis.hostingKind === "framework-source") {
|
|
578
|
+
blockers.push({
|
|
579
|
+
code: "framework_hosting_config",
|
|
580
|
+
message: "firebase.json hosting.source uses Firebase web frameworks. Phase 1 only deploys a static public directory."
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
if (analysis.hostingKind === "array") {
|
|
584
|
+
blockers.push({
|
|
585
|
+
code: "multi_site_config",
|
|
586
|
+
message: "firebase.json contains multiple Hosting sites. Phase 1 does not choose one and does not deploy every site. Keep the array unchanged and split it into one static site before deploying."
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
const packageManager = resolvePackageManager(analysis, options, blockers);
|
|
590
|
+
const buildScript = resolveBuildScript(analysis, options, blockers);
|
|
591
|
+
const outputDirectory = resolveOutput(analysis, options, blockers, warnings);
|
|
592
|
+
const projectAction = resolveProjectAction(options, context.inspection ?? null, projectId, blockers);
|
|
593
|
+
const envKeys = referencedPublicEnvKeys(analysis.envReferences);
|
|
594
|
+
const spaRewrite = analysis.spaRewrite && analysis.hostingKind !== "array";
|
|
595
|
+
if (analysis.secretFindings.length > 0) {
|
|
596
|
+
warnings.push(
|
|
597
|
+
`Possible secrets were found in ${analysis.secretFindings.map((finding) => `${finding.path} (${finding.id})`).join(", ")}. This is not a complete security audit.`
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
for (const rules of analysis.rules.filter((finding) => finding.permissive)) {
|
|
601
|
+
warnings.push(
|
|
602
|
+
`${rules.path} allows unauthenticated access. Phase 1 does not deploy rules and will not replace this file. Review it before storing data.`
|
|
603
|
+
);
|
|
604
|
+
}
|
|
605
|
+
if (analysis.hasFunctionsDirectory) {
|
|
606
|
+
warnings.push("A functions directory exists. Phase 1 deploys Hosting only and will not deploy Cloud Functions.");
|
|
607
|
+
}
|
|
608
|
+
if (analysis.scanTruncated) {
|
|
609
|
+
warnings.push("Source inspection stopped after the file limit. Detection may be incomplete.");
|
|
610
|
+
}
|
|
611
|
+
warnings.push("Firebase Hosting is global. Phase 1 does not choose a Firestore or default Cloud resource location.");
|
|
612
|
+
warnings.push("Package scripts run on this machine. Cloud credential environment variables are removed from the build subprocess, but other local environment variables remain.");
|
|
613
|
+
warnings.push("Firebase web config is public client configuration. Security rules, not the config object, protect data.");
|
|
614
|
+
warnings.push(IAM_NOTE);
|
|
615
|
+
if (!context.inspection && projectId) {
|
|
616
|
+
warnings.push("Remote project state was not checked. Deploy reconciles the project before changing anything.");
|
|
617
|
+
}
|
|
618
|
+
if (context.identity?.credentialKind === "service-account") {
|
|
619
|
+
warnings.push("A service account credential is active. The supported local workflow is `gcloud auth application-default login`, not a downloaded service account key.");
|
|
620
|
+
}
|
|
621
|
+
const firebaseMerge = analysis.firebaseJsonError || !outputDirectory ? null : mergeFirebaseJson(analysis.firebaseJson, { outputDirectory, spaRewrite });
|
|
622
|
+
if (firebaseMerge?.blocked) {
|
|
623
|
+
blockers.push(firebaseMerge.blocked);
|
|
624
|
+
}
|
|
625
|
+
if (firebaseMerge) {
|
|
626
|
+
warnings.push(...firebaseMerge.warnings);
|
|
627
|
+
}
|
|
628
|
+
const firebasercMerge = projectId && !analysis.firebasercError ? mergeFirebaserc(analysis.firebaserc, projectId) : null;
|
|
629
|
+
if (firebasercMerge) {
|
|
630
|
+
warnings.push(...firebasercMerge.warnings);
|
|
631
|
+
}
|
|
632
|
+
const gitignoreMerge = mergeGitignore(context.gitignore ?? null);
|
|
633
|
+
const displayName = projectId ? cleanDisplayName(options.displayName, projectId) : null;
|
|
634
|
+
const requiredPermissions = permissionsFor(projectAction);
|
|
635
|
+
const plan = {
|
|
636
|
+
id: (context.id ?? randomUUID)(),
|
|
637
|
+
createdAt: now().toISOString(),
|
|
638
|
+
path: analysis.path,
|
|
639
|
+
supported: analysis.supported,
|
|
640
|
+
appReady: blockers.length === 0,
|
|
641
|
+
blockers,
|
|
642
|
+
framework: analysis.framework,
|
|
643
|
+
frameworkLabel: analysis.frameworkLabel,
|
|
644
|
+
packageManager,
|
|
645
|
+
buildCommand: packageManager && buildScript ? `${packageManager} run ${buildScript}` : null,
|
|
646
|
+
buildScript,
|
|
647
|
+
outputDirectory,
|
|
648
|
+
projectId,
|
|
649
|
+
projectAction,
|
|
650
|
+
displayName,
|
|
651
|
+
parent: options.parent ?? null,
|
|
652
|
+
services: ["hosting"],
|
|
653
|
+
tier: "starter",
|
|
654
|
+
region: null,
|
|
655
|
+
requiredPermissions,
|
|
656
|
+
requiredApis: [...PHASE1_APIS],
|
|
657
|
+
billing: {
|
|
658
|
+
tier: "starter",
|
|
659
|
+
attachesBilling: false,
|
|
660
|
+
requiresBlaze: false,
|
|
661
|
+
summary: "Firebase Hosting on the Spark plan. No billing account will be attached.",
|
|
662
|
+
notes: [
|
|
663
|
+
"Spark includes a free Hosting usage allowance. Exceeding the published quota requires the Blaze plan.",
|
|
664
|
+
"Budget alerts are not spending caps and are not configured in this phase.",
|
|
665
|
+
"This plan does not call the Cloud Billing API."
|
|
666
|
+
]
|
|
667
|
+
},
|
|
668
|
+
fileChanges: describeFileChanges({
|
|
669
|
+
firebase: firebaseMerge,
|
|
670
|
+
firebaserc: firebasercMerge,
|
|
671
|
+
gitignore: gitignoreMerge,
|
|
672
|
+
envKeys,
|
|
673
|
+
envExampleExists: context.envExampleExists ?? false,
|
|
674
|
+
envLocalExists: context.envLocalExists ?? false
|
|
675
|
+
}),
|
|
676
|
+
warnings: unique(warnings),
|
|
677
|
+
steps: phase1Steps(),
|
|
678
|
+
identity: context.identity ?? null,
|
|
679
|
+
hostingSite: analysis.hostingSite,
|
|
680
|
+
webAppDisplayName: cleanDisplayName(analysis.packageName ? `${analysis.packageName} web` : void 0, "web"),
|
|
681
|
+
spaRewrite,
|
|
682
|
+
dryRun: options.dryRun ?? false,
|
|
683
|
+
referencedEnvKeys: envKeys,
|
|
684
|
+
appId: options.appId ?? null
|
|
685
|
+
};
|
|
686
|
+
return plan;
|
|
687
|
+
}
|
|
688
|
+
async function loadPlanContext(projectPath) {
|
|
689
|
+
const [gitignore, envExampleExists, envLocalExists] = await Promise.all([
|
|
690
|
+
readOptionalText(path4.join(projectPath, ".gitignore")),
|
|
691
|
+
exists(path4.join(projectPath, ".env.example")),
|
|
692
|
+
exists(path4.join(projectPath, ".env.local"))
|
|
693
|
+
]);
|
|
694
|
+
return { gitignore, envExampleExists, envLocalExists };
|
|
695
|
+
}
|
|
696
|
+
function resolvePackageManager(analysis, options, blockers) {
|
|
697
|
+
if (options.packageManager) {
|
|
698
|
+
if (!PACKAGE_MANAGERS.has(options.packageManager)) {
|
|
699
|
+
blockers.push({ code: "invalid_package_manager", message: `Unsupported package manager "${options.packageManager}".` });
|
|
700
|
+
return null;
|
|
701
|
+
}
|
|
702
|
+
return options.packageManager;
|
|
703
|
+
}
|
|
704
|
+
if (analysis.packageManagers.length === 1) {
|
|
705
|
+
return analysis.packageManagers[0] ?? null;
|
|
706
|
+
}
|
|
707
|
+
blockers.push({
|
|
708
|
+
code: "ambiguous_package_manager",
|
|
709
|
+
message: analysis.packageManagers.length === 0 ? "No lockfile or packageManager field identifies the package manager." : `Multiple package manager signals were found: ${analysis.packageManagers.join(", ")}.`
|
|
710
|
+
});
|
|
711
|
+
return null;
|
|
712
|
+
}
|
|
713
|
+
function resolveBuildScript(analysis, options, blockers) {
|
|
714
|
+
const script = options.buildScript ?? analysis.buildScript;
|
|
715
|
+
if (!script) {
|
|
716
|
+
blockers.push({ code: "missing_build_script", message: "package.json has no build script." });
|
|
717
|
+
return null;
|
|
718
|
+
}
|
|
719
|
+
if (!/^[A-Za-z0-9:_-]+$/.test(script)) {
|
|
720
|
+
blockers.push({ code: "invalid_build_script", message: `Build script "${script}" contains unsupported characters.` });
|
|
721
|
+
return null;
|
|
722
|
+
}
|
|
723
|
+
if (!analysis.scripts.includes(script)) {
|
|
724
|
+
blockers.push({ code: "missing_build_script", message: `package.json does not define a "${script}" script.` });
|
|
725
|
+
return null;
|
|
726
|
+
}
|
|
727
|
+
return script;
|
|
728
|
+
}
|
|
729
|
+
function resolveOutput(analysis, options, blockers, warnings) {
|
|
730
|
+
const detected = analysis.viteOutDirAmbiguous ? null : analysis.viteOutDir;
|
|
731
|
+
if (analysis.viteOutDirAmbiguous && !options.outputDirectory && !analysis.hostingPublic) {
|
|
732
|
+
blockers.push({
|
|
733
|
+
code: "ambiguous_output",
|
|
734
|
+
message: "The Vite output directory is dynamic or conflicting. Pass --output to choose one."
|
|
735
|
+
});
|
|
736
|
+
return null;
|
|
737
|
+
}
|
|
738
|
+
if (analysis.hostingPublic && detected && analysis.hostingPublic !== detected && options.outputDirectory !== analysis.hostingPublic) {
|
|
739
|
+
blockers.push({
|
|
740
|
+
code: "ambiguous_output",
|
|
741
|
+
message: `Vite builds to "${detected}" but firebase.json hosting.public is "${analysis.hostingPublic}". Pass --output ${analysis.hostingPublic} only after the build writes that directory. VibeInfra will not change hosting.public.`
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
if (analysis.hostingPublic && detected && analysis.hostingPublic !== detected && options.outputDirectory === analysis.hostingPublic) {
|
|
745
|
+
warnings.push(`Vite's detected output is "${detected}". The build must write "${analysis.hostingPublic}" because that is the existing hosting.public directory.`);
|
|
746
|
+
}
|
|
747
|
+
if (analysis.hostingPublic && options.outputDirectory && options.outputDirectory !== analysis.hostingPublic) {
|
|
748
|
+
blockers.push({
|
|
749
|
+
code: "output_conflict",
|
|
750
|
+
message: `Refusing to replace hosting.public "${analysis.hostingPublic}" with "${options.outputDirectory}".`
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
const chosen = options.outputDirectory && options.outputDirectory === analysis.hostingPublic ? analysis.hostingPublic : options.outputDirectory && !analysis.hostingPublic ? options.outputDirectory : analysis.hostingPublic ?? detected ?? options.outputDirectory ?? null;
|
|
754
|
+
if (!chosen) {
|
|
755
|
+
blockers.push({ code: "missing_output", message: "No Hosting public directory or Vite output directory was found." });
|
|
756
|
+
return null;
|
|
757
|
+
}
|
|
758
|
+
try {
|
|
759
|
+
return assertSafeOutputDirectory(analysis.path, chosen);
|
|
760
|
+
} catch (error) {
|
|
761
|
+
if (error instanceof VibeInfraError) {
|
|
762
|
+
blockers.push({ code: error.code, message: error.message });
|
|
763
|
+
return null;
|
|
764
|
+
}
|
|
765
|
+
throw error;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
function resolveProjectAction(options, inspection, projectId, blockers) {
|
|
769
|
+
if (!projectId) {
|
|
770
|
+
return "unresolved";
|
|
771
|
+
}
|
|
772
|
+
if (!inspection) {
|
|
773
|
+
return options.createProject ? "create" : "reuse";
|
|
774
|
+
}
|
|
775
|
+
if (inspection.firebase) {
|
|
776
|
+
if (inspection.firebase.state && inspection.firebase.state !== "ACTIVE") {
|
|
777
|
+
blockers.push({
|
|
778
|
+
code: "project_unavailable",
|
|
779
|
+
message: `Firebase project ${projectId} is ${inspection.firebase.state}.`
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
return "reuse";
|
|
783
|
+
}
|
|
784
|
+
if (inspection.cloud) {
|
|
785
|
+
if (inspection.cloud.state && inspection.cloud.state !== "ACTIVE") {
|
|
786
|
+
blockers.push({
|
|
787
|
+
code: "project_unavailable",
|
|
788
|
+
message: `Google Cloud project ${projectId} is ${inspection.cloud.state}.`
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
return "add-firebase";
|
|
792
|
+
}
|
|
793
|
+
if (options.createProject) {
|
|
794
|
+
return "create";
|
|
795
|
+
}
|
|
796
|
+
blockers.push({
|
|
797
|
+
code: "project_not_found",
|
|
798
|
+
message: `Project ${projectId} was not found. Pass --create-project ${projectId} to create it. VibeInfra will not create a project from --project alone.`
|
|
799
|
+
});
|
|
800
|
+
return "missing";
|
|
801
|
+
}
|
|
802
|
+
function permissionsFor(action) {
|
|
803
|
+
const permissions = [
|
|
804
|
+
"firebase.projects.get",
|
|
805
|
+
"resourcemanager.projects.get",
|
|
806
|
+
"serviceusage.services.get",
|
|
807
|
+
"serviceusage.services.enable",
|
|
808
|
+
"firebase.clients.list",
|
|
809
|
+
"firebase.clients.get",
|
|
810
|
+
"firebase.clients.create",
|
|
811
|
+
"firebasehosting.sites.update",
|
|
812
|
+
"firebasehosting.sites.create"
|
|
813
|
+
];
|
|
814
|
+
if (action === "create") {
|
|
815
|
+
permissions.unshift("resourcemanager.projects.create");
|
|
816
|
+
}
|
|
817
|
+
if (action === "create" || action === "add-firebase") {
|
|
818
|
+
permissions.push("firebase.projects.update");
|
|
819
|
+
}
|
|
820
|
+
return unique(permissions);
|
|
821
|
+
}
|
|
822
|
+
function phase1Steps() {
|
|
823
|
+
return [
|
|
824
|
+
{ id: "resolve-project", title: "Resolve the Google Cloud and Firebase project", status: "pending", remote: true },
|
|
825
|
+
{ id: "enable-apis", title: "Enable the Firebase Management and Hosting APIs", status: "pending", remote: true },
|
|
826
|
+
{ id: "register-web-app", title: "Register or reuse the Firebase web app", status: "pending", remote: true },
|
|
827
|
+
{ id: "write-config", title: "Merge Firebase config and local env files", status: "pending", remote: false },
|
|
828
|
+
{ id: "validate-rules", title: "Inspect existing security rules", status: "pending", remote: false },
|
|
829
|
+
{ id: "install", title: "Install dependencies when node_modules is missing", status: "pending", remote: false },
|
|
830
|
+
{ id: "build", title: "Build the application locally", status: "pending", remote: false },
|
|
831
|
+
{ id: "validate-output", title: "Validate the build output", status: "pending", remote: false },
|
|
832
|
+
{ id: "deploy-hosting", title: "Deploy Firebase Hosting", status: "pending", remote: true },
|
|
833
|
+
{ id: "verify-url", title: "Verify the Hosting URL", status: "pending", remote: false }
|
|
834
|
+
];
|
|
835
|
+
}
|
|
836
|
+
function unique(values) {
|
|
837
|
+
return [...new Set(values)];
|
|
838
|
+
}
|
|
839
|
+
async function exists(file) {
|
|
840
|
+
try {
|
|
841
|
+
await access(file);
|
|
842
|
+
return true;
|
|
843
|
+
} catch {
|
|
844
|
+
return false;
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// packages/core/src/engine.ts
|
|
849
|
+
import { access as access2, readdir, readFile as readFile3 } from "node:fs/promises";
|
|
850
|
+
import path5 from "node:path";
|
|
851
|
+
|
|
852
|
+
// packages/core/src/build.ts
|
|
853
|
+
import { spawn } from "node:child_process";
|
|
854
|
+
function packageManagerInvocation(packageManager, script, buildScript = "build") {
|
|
855
|
+
const command = process.platform === "win32" ? `${packageManager}.cmd` : packageManager;
|
|
856
|
+
if (script === "install") {
|
|
857
|
+
return { command, args: ["install"] };
|
|
858
|
+
}
|
|
859
|
+
return { command, args: ["run", buildScript] };
|
|
860
|
+
}
|
|
861
|
+
function sanitizeBuildEnv(source) {
|
|
862
|
+
const env = { ...source };
|
|
863
|
+
for (const key of STRIPPED_BUILD_ENV) {
|
|
864
|
+
delete env[key];
|
|
865
|
+
}
|
|
866
|
+
return env;
|
|
867
|
+
}
|
|
868
|
+
async function runLocalCommand(request) {
|
|
869
|
+
await new Promise((resolve, reject) => {
|
|
870
|
+
const child = spawn(request.command, request.args, {
|
|
871
|
+
cwd: request.cwd,
|
|
872
|
+
env: request.env,
|
|
873
|
+
stdio: request.stdio,
|
|
874
|
+
shell: process.platform === "win32"
|
|
875
|
+
});
|
|
876
|
+
child.once("error", (error) => {
|
|
877
|
+
if (isNotFound3(error)) {
|
|
878
|
+
reject(new VibeInfraError({
|
|
879
|
+
code: request.label === "install" ? "install_failed" : "build_failed",
|
|
880
|
+
message: `Could not start ${request.command}.`,
|
|
881
|
+
remediation: `Install ${request.command} and rerun the deployment. Package scripts execute on this machine.`
|
|
882
|
+
}));
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
reject(error);
|
|
886
|
+
});
|
|
887
|
+
child.once("close", (code) => {
|
|
888
|
+
if (code === 0) {
|
|
889
|
+
resolve();
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
reject(new VibeInfraError({
|
|
893
|
+
code: request.label === "install" ? "install_failed" : "build_failed",
|
|
894
|
+
message: `${request.command} ${request.args.join(" ")} exited with code ${code ?? "unknown"}.`,
|
|
895
|
+
remediation: request.label === "install" ? "Fix the dependency install, then resume. Cloud resources that were already created will be reused." : "Fix the build, then resume. VibeInfra does not deploy an output directory that failed to build."
|
|
896
|
+
}));
|
|
897
|
+
});
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
function isNotFound3(error) {
|
|
901
|
+
return error.code === "ENOENT";
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
// packages/core/src/secrets.ts
|
|
905
|
+
var PATTERNS = [
|
|
906
|
+
{ id: "private-key", pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
|
|
907
|
+
{ id: "service-account", pattern: /"type"\s*:\s*"service_account"/ },
|
|
908
|
+
{ id: "aws-access-key", pattern: /AKIA[0-9A-Z]{16}/ },
|
|
909
|
+
{ id: "slack-token", pattern: /xox[baprs]-[A-Za-z0-9-]{10,}/ },
|
|
910
|
+
{ id: "stripe-secret", pattern: /sk_live_[0-9a-zA-Z]{10,}/ },
|
|
911
|
+
{ id: "refresh-token", pattern: /"refresh_token"\s*:/ }
|
|
912
|
+
];
|
|
913
|
+
function findSecretIds(text) {
|
|
914
|
+
return PATTERNS.filter((candidate) => candidate.pattern.test(text)).map((candidate) => candidate.id);
|
|
915
|
+
}
|
|
916
|
+
function isPermissiveRules(source) {
|
|
917
|
+
const compact = source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "");
|
|
918
|
+
return /allow\s+(?:read\s*,\s*write|write\s*,\s*read|read|write)\s*:\s*if\s+true\b/i.test(compact) || /allow\s+(?:read\s*,\s*write|write\s*,\s*read|read|write)\s*:\s*if\s+request\.auth\s*==\s*null\b/i.test(compact);
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
// packages/core/src/verify.ts
|
|
922
|
+
var DELAYS_MS = [2e3, 3e3, 5e3, 8e3, 1e4];
|
|
923
|
+
function hostingUrl(siteId) {
|
|
924
|
+
assertHostingSiteId(siteId);
|
|
925
|
+
return `https://${siteId}.web.app`;
|
|
926
|
+
}
|
|
927
|
+
async function verifyHostingUrl(url, deps = {}) {
|
|
928
|
+
const parsed = new URL(url);
|
|
929
|
+
if (parsed.protocol !== "https:" || !parsed.hostname.endsWith(".web.app") && !parsed.hostname.endsWith(".firebaseapp.com")) {
|
|
930
|
+
throw new VibeInfraError({
|
|
931
|
+
code: "invalid_verification_url",
|
|
932
|
+
message: "Refusing to verify a URL that is not a Firebase Hosting hostname.",
|
|
933
|
+
remediation: "Verification is limited to the web.app or firebaseapp.com hostname produced from the Hosting site id.",
|
|
934
|
+
category: "provider"
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
const fetchImpl = deps.fetch ?? fetch;
|
|
938
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
939
|
+
let last = { url, statusCode: null, ok: false, error: "Hosting did not respond." };
|
|
940
|
+
for (let attempt = 0; attempt < DELAYS_MS.length; attempt += 1) {
|
|
941
|
+
try {
|
|
942
|
+
const response = await fetchImpl(url, { method: "GET", redirect: "follow", signal: AbortSignal.timeout(15e3) });
|
|
943
|
+
last = { url, statusCode: response.status, ok: response.status >= 200 && response.status < 300 };
|
|
944
|
+
if (last.ok) {
|
|
945
|
+
return last;
|
|
946
|
+
}
|
|
947
|
+
} catch (error) {
|
|
948
|
+
last = {
|
|
949
|
+
url,
|
|
950
|
+
statusCode: null,
|
|
951
|
+
ok: false,
|
|
952
|
+
error: error instanceof Error ? error.message : "The HTTP check failed."
|
|
953
|
+
};
|
|
954
|
+
}
|
|
955
|
+
if (attempt < DELAYS_MS.length - 1) {
|
|
956
|
+
await sleep(DELAYS_MS[attempt] ?? 2e3);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
return last;
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
// packages/core/src/engine.ts
|
|
963
|
+
var SUCCESS_NOTE = "The HTTP check only shows that Hosting returned a response. It does not prove that application features work.";
|
|
964
|
+
async function deployApplication(options, deps) {
|
|
965
|
+
const analysis = await deps.analyzer.analyze(options.path);
|
|
966
|
+
const fileContext = await loadPlanContext(analysis.path);
|
|
967
|
+
const localPlan = createDeploymentPlan(analysis, options, { ...fileContext, now: deps.now, id: deps.id });
|
|
968
|
+
if (!localPlan.appReady) {
|
|
969
|
+
return blockedResult(localPlan);
|
|
970
|
+
}
|
|
971
|
+
if (options.dryRun) {
|
|
972
|
+
return dryResult(localPlan);
|
|
973
|
+
}
|
|
974
|
+
if (!options.projectId) {
|
|
975
|
+
throw new VibeInfraError({
|
|
976
|
+
code: "project_required",
|
|
977
|
+
message: "A Firebase project id is required before VibeInfra can deploy.",
|
|
978
|
+
remediation: "Pass --project PROJECT_ID, or run interactively and enter an id. Use --create-project PROJECT_ID only when a new project should be created."
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
if (options.nonInteractive && !options.yes) {
|
|
982
|
+
throw new VibeInfraError({
|
|
983
|
+
code: "approval_required",
|
|
984
|
+
message: "Noninteractive deployment requires --yes after you review the plan.",
|
|
985
|
+
remediation: "Run `vibeinfra plan --project PROJECT_ID`, review the services and billing statement, then rerun deploy with --yes. --yes does not attach billing."
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
const identity = await deps.provider.authenticate();
|
|
989
|
+
const inspection = await inspectProject(deps.provider, options.projectId);
|
|
990
|
+
const plan = createDeploymentPlan(analysis, options, {
|
|
991
|
+
...fileContext,
|
|
992
|
+
inspection,
|
|
993
|
+
identity,
|
|
994
|
+
now: deps.now,
|
|
995
|
+
id: deps.id
|
|
996
|
+
});
|
|
997
|
+
if (!plan.appReady) {
|
|
998
|
+
return blockedResult(plan);
|
|
999
|
+
}
|
|
1000
|
+
const approved = await deps.confirm(plan);
|
|
1001
|
+
if (!approved) {
|
|
1002
|
+
throw new VibeInfraError({
|
|
1003
|
+
code: "approval_denied",
|
|
1004
|
+
message: "The deployment plan was not approved.",
|
|
1005
|
+
remediation: "No local files or cloud resources were changed. Run the command again and type yes, or pass --yes in noninteractive mode."
|
|
1006
|
+
});
|
|
1007
|
+
}
|
|
1008
|
+
return execute(plan, analysis, deps);
|
|
1009
|
+
}
|
|
1010
|
+
async function inspectProject(provider, projectId) {
|
|
1011
|
+
const firebase = await provider.getFirebaseProject(projectId);
|
|
1012
|
+
if (firebase) {
|
|
1013
|
+
return { firebase, cloud: null };
|
|
1014
|
+
}
|
|
1015
|
+
const cloud = await provider.getCloudProject(projectId);
|
|
1016
|
+
return { firebase: null, cloud };
|
|
1017
|
+
}
|
|
1018
|
+
async function execute(plan, analysis, deps) {
|
|
1019
|
+
const steps = plan.steps.map((step) => ({ ...step }));
|
|
1020
|
+
const resourceIds = {};
|
|
1021
|
+
const warnings = [...plan.warnings];
|
|
1022
|
+
const httpChecks = [];
|
|
1023
|
+
let verifiedUrl = null;
|
|
1024
|
+
let remoteMutation = false;
|
|
1025
|
+
let localMutation = false;
|
|
1026
|
+
const now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
1027
|
+
const runCommand = deps.runCommand ?? runLocalCommand;
|
|
1028
|
+
const checkpoint = async (status) => {
|
|
1029
|
+
await writeJournal(analysis.path, {
|
|
1030
|
+
version: 1,
|
|
1031
|
+
updatedAt: now().toISOString(),
|
|
1032
|
+
projectPath: analysis.path,
|
|
1033
|
+
projectId: plan.projectId,
|
|
1034
|
+
status,
|
|
1035
|
+
steps,
|
|
1036
|
+
resourceIds,
|
|
1037
|
+
verifiedUrl,
|
|
1038
|
+
httpChecks,
|
|
1039
|
+
warnings
|
|
1040
|
+
});
|
|
1041
|
+
};
|
|
1042
|
+
const fail = async (error) => {
|
|
1043
|
+
const vibe = toVibeInfraError(error);
|
|
1044
|
+
const current = steps.find((step) => step.status === "running");
|
|
1045
|
+
if (current) {
|
|
1046
|
+
current.status = "failed";
|
|
1047
|
+
current.detail = vibe.message;
|
|
1048
|
+
current.error = vibe.toJSON();
|
|
1049
|
+
}
|
|
1050
|
+
const status = remoteMutation ? "partial" : "failed";
|
|
1051
|
+
await checkpoint(status);
|
|
1052
|
+
return {
|
|
1053
|
+
status,
|
|
1054
|
+
plan,
|
|
1055
|
+
steps,
|
|
1056
|
+
verifiedUrl,
|
|
1057
|
+
httpChecks,
|
|
1058
|
+
resourceIds,
|
|
1059
|
+
journalPath: journalPath(analysis.path),
|
|
1060
|
+
remediation: [
|
|
1061
|
+
vibe.remediation,
|
|
1062
|
+
remoteMutation ? "Cloud resources were changed. Nothing was deleted. Run `vibeinfra deploy --resume` after fixing the failure; existing resources will be reused." : localMutation ? "Local files may have been written. No cloud resources were changed." : "No cloud resources were changed."
|
|
1063
|
+
],
|
|
1064
|
+
warnings,
|
|
1065
|
+
error: vibe.toJSON()
|
|
1066
|
+
};
|
|
1067
|
+
};
|
|
1068
|
+
try {
|
|
1069
|
+
await run("resolve-project", async () => {
|
|
1070
|
+
const resolved = await resolveProject(plan, deps.provider);
|
|
1071
|
+
resourceIds.projectId = resolved.project.projectId;
|
|
1072
|
+
if (resolved.project.projectNumber) {
|
|
1073
|
+
resourceIds.projectNumber = resolved.project.projectNumber;
|
|
1074
|
+
}
|
|
1075
|
+
if (resolved.project.hostingSite) {
|
|
1076
|
+
resourceIds.hostingSite = resolved.project.hostingSite;
|
|
1077
|
+
}
|
|
1078
|
+
if (resolved.createdProject || resolved.addedFirebase) {
|
|
1079
|
+
remoteMutation = true;
|
|
1080
|
+
}
|
|
1081
|
+
return resolved.createdProject ? `Created Google Cloud project ${resolved.project.projectId} and added Firebase. No billing account was attached.` : resolved.addedFirebase ? `Added Firebase to existing Google Cloud project ${resolved.project.projectId}.` : `Reusing Firebase project ${resolved.project.projectId}.`;
|
|
1082
|
+
});
|
|
1083
|
+
await checkpoint("in_progress");
|
|
1084
|
+
await run("enable-apis", async () => {
|
|
1085
|
+
const enabled = await deps.provider.enableServices(plan.projectId, plan.requiredApis);
|
|
1086
|
+
if (enabled.changed) {
|
|
1087
|
+
remoteMutation = true;
|
|
1088
|
+
}
|
|
1089
|
+
return enabled.changed ? `Enabled ${enabled.enabled.join(", ")}.` : `Already enabled: ${enabled.alreadyEnabled.join(", ")}.`;
|
|
1090
|
+
});
|
|
1091
|
+
await checkpoint("in_progress");
|
|
1092
|
+
await run("register-web-app", async () => {
|
|
1093
|
+
const app = await ensureWebApp(plan, deps.provider);
|
|
1094
|
+
resourceIds.appId = app.app.appId;
|
|
1095
|
+
if (app.created) {
|
|
1096
|
+
remoteMutation = true;
|
|
1097
|
+
}
|
|
1098
|
+
return app.created ? `Created web app ${app.app.appId}.` : `Reusing web app ${app.app.appId}.`;
|
|
1099
|
+
});
|
|
1100
|
+
await checkpoint("in_progress");
|
|
1101
|
+
await run("write-config", async () => {
|
|
1102
|
+
localMutation = true;
|
|
1103
|
+
const config = await deps.provider.getWebAppConfig(plan.projectId, resourceIds.appId);
|
|
1104
|
+
await applyApprovedFiles({
|
|
1105
|
+
projectPath: analysis.path,
|
|
1106
|
+
outputDirectory: plan.outputDirectory,
|
|
1107
|
+
spaRewrite: plan.spaRewrite,
|
|
1108
|
+
projectId: plan.projectId,
|
|
1109
|
+
envKeys: plan.referencedEnvKeys,
|
|
1110
|
+
webConfig: config
|
|
1111
|
+
});
|
|
1112
|
+
return plan.referencedEnvKeys.length > 0 ? "Merged Firebase files and wrote public web config into .env.local." : "Merged Firebase files. The app does not reference VITE_FIREBASE_* variables, so no env file was required.";
|
|
1113
|
+
});
|
|
1114
|
+
await checkpoint("in_progress");
|
|
1115
|
+
await run("validate-rules", async () => {
|
|
1116
|
+
const findings = [];
|
|
1117
|
+
for (const rules of analysis.rules) {
|
|
1118
|
+
const source = await readFile3(path5.join(analysis.path, rules.path), "utf8");
|
|
1119
|
+
if (isPermissiveRules(source)) {
|
|
1120
|
+
const message = `${rules.path} still allows broad access. It was not modified or deployed.`;
|
|
1121
|
+
warnings.push(message);
|
|
1122
|
+
findings.push(message);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
return findings.length > 0 ? findings.join(" ") : "No permissive rules were found in existing rules files. Rules were not deployed.";
|
|
1126
|
+
});
|
|
1127
|
+
const modules = path5.join(analysis.path, "node_modules");
|
|
1128
|
+
if (await pathExists(modules)) {
|
|
1129
|
+
mark(steps, "install", "skipped", "node_modules already exists.");
|
|
1130
|
+
} else {
|
|
1131
|
+
await run("install", async () => {
|
|
1132
|
+
const invocation = packageManagerInvocation(plan.packageManager, "install");
|
|
1133
|
+
await runCommand({
|
|
1134
|
+
...invocation,
|
|
1135
|
+
cwd: analysis.path,
|
|
1136
|
+
env: sanitizeBuildEnv(process.env),
|
|
1137
|
+
stdio: "inherit",
|
|
1138
|
+
label: "install"
|
|
1139
|
+
});
|
|
1140
|
+
return `${plan.packageManager} install completed locally. Cloud credential variables were removed from the subprocess.`;
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
await checkpoint("in_progress");
|
|
1144
|
+
await run("build", async () => {
|
|
1145
|
+
const invocation = packageManagerInvocation(plan.packageManager, "build", plan.buildScript);
|
|
1146
|
+
await runCommand({
|
|
1147
|
+
...invocation,
|
|
1148
|
+
cwd: analysis.path,
|
|
1149
|
+
env: sanitizeBuildEnv(process.env),
|
|
1150
|
+
stdio: "inherit",
|
|
1151
|
+
label: "build"
|
|
1152
|
+
});
|
|
1153
|
+
return `${plan.buildCommand} completed locally.`;
|
|
1154
|
+
});
|
|
1155
|
+
await checkpoint("in_progress");
|
|
1156
|
+
await run("validate-output", async () => {
|
|
1157
|
+
const output = path5.join(analysis.path, plan.outputDirectory);
|
|
1158
|
+
await assertBuildOutput(output, plan.spaRewrite);
|
|
1159
|
+
const secrets = await scanDirectory(output);
|
|
1160
|
+
if (secrets.length > 0) {
|
|
1161
|
+
throw new VibeInfraError({
|
|
1162
|
+
code: "secret_in_output",
|
|
1163
|
+
message: `Refusing to deploy because the build output contains ${secrets.join(", ")}.`,
|
|
1164
|
+
remediation: "Remove the credential from the build output and source, rebuild, and resume. The Hosting upload was not started."
|
|
1165
|
+
});
|
|
1166
|
+
}
|
|
1167
|
+
return `Build output ${plan.outputDirectory} contains the expected files.`;
|
|
1168
|
+
});
|
|
1169
|
+
await run("deploy-hosting", async () => {
|
|
1170
|
+
const deployed = await deps.provider.deployHosting({
|
|
1171
|
+
projectPath: analysis.path,
|
|
1172
|
+
projectId: plan.projectId
|
|
1173
|
+
});
|
|
1174
|
+
remoteMutation = true;
|
|
1175
|
+
if (deployed.versionName) {
|
|
1176
|
+
resourceIds.hostingVersion = deployed.versionName;
|
|
1177
|
+
}
|
|
1178
|
+
return deployed.versionName ? `Firebase CLI published Hosting version ${deployed.versionName}.` : "Firebase CLI published Hosting.";
|
|
1179
|
+
});
|
|
1180
|
+
await checkpoint("in_progress");
|
|
1181
|
+
await run("verify-url", async () => {
|
|
1182
|
+
const site = resourceIds.hostingSite || analysis.hostingSite || plan.projectId;
|
|
1183
|
+
const checks = analysis.hostingSites.length > 0 ? analysis.hostingSites : [site];
|
|
1184
|
+
for (const siteId of checks) {
|
|
1185
|
+
const check = await verifyHostingUrl(hostingUrl(siteId), { fetch: deps.fetch, sleep: deps.sleep });
|
|
1186
|
+
httpChecks.push(check);
|
|
1187
|
+
}
|
|
1188
|
+
const primary = httpChecks[0];
|
|
1189
|
+
verifiedUrl = primary?.ok ? primary.url : null;
|
|
1190
|
+
if (httpChecks.some((check) => !check.ok)) {
|
|
1191
|
+
throw new VibeInfraError({
|
|
1192
|
+
code: "verification_failed",
|
|
1193
|
+
message: "Hosting deploy returned, but the URL check did not receive a successful response.",
|
|
1194
|
+
remediation: "Wait briefly and run `vibeinfra deploy --resume`. A failed HTTP check does not roll back the Hosting release.",
|
|
1195
|
+
category: "provider",
|
|
1196
|
+
retryable: true
|
|
1197
|
+
});
|
|
1198
|
+
}
|
|
1199
|
+
warnings.push(SUCCESS_NOTE);
|
|
1200
|
+
return `Verified ${verifiedUrl}. ${SUCCESS_NOTE}`;
|
|
1201
|
+
});
|
|
1202
|
+
await checkpoint("succeeded");
|
|
1203
|
+
return {
|
|
1204
|
+
status: "succeeded",
|
|
1205
|
+
plan,
|
|
1206
|
+
steps,
|
|
1207
|
+
verifiedUrl,
|
|
1208
|
+
httpChecks,
|
|
1209
|
+
resourceIds,
|
|
1210
|
+
journalPath: journalPath(analysis.path),
|
|
1211
|
+
remediation: [],
|
|
1212
|
+
warnings
|
|
1213
|
+
};
|
|
1214
|
+
} catch (error) {
|
|
1215
|
+
return fail(error);
|
|
1216
|
+
}
|
|
1217
|
+
async function run(id, action) {
|
|
1218
|
+
const step = mark(steps, id, "running");
|
|
1219
|
+
step.detail = await action();
|
|
1220
|
+
step.status = "succeeded";
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
async function resolveProject(plan, provider) {
|
|
1224
|
+
const projectId = plan.projectId;
|
|
1225
|
+
const existing = await provider.getFirebaseProject(projectId);
|
|
1226
|
+
if (existing) {
|
|
1227
|
+
return { project: existing, createdProject: false, addedFirebase: false };
|
|
1228
|
+
}
|
|
1229
|
+
const cloud = await provider.getCloudProject(projectId);
|
|
1230
|
+
if (cloud) {
|
|
1231
|
+
if (plan.projectAction === "reuse") {
|
|
1232
|
+
throw new VibeInfraError({
|
|
1233
|
+
code: "project_not_firebase",
|
|
1234
|
+
message: `Project ${projectId} exists in Google Cloud but Firebase is not enabled. The approved plan expected an existing Firebase project.`,
|
|
1235
|
+
remediation: "Run deploy again so the reconciled plan can show Add Firebase, then approve that plan."
|
|
1236
|
+
});
|
|
1237
|
+
}
|
|
1238
|
+
const added2 = await provider.addFirebase(projectId);
|
|
1239
|
+
return { project: added2, createdProject: false, addedFirebase: true };
|
|
1240
|
+
}
|
|
1241
|
+
if (plan.projectAction !== "create") {
|
|
1242
|
+
throw new VibeInfraError({
|
|
1243
|
+
code: "project_not_found",
|
|
1244
|
+
message: `Project ${projectId} was not found.`,
|
|
1245
|
+
remediation: `Pass --create-project ${projectId} to create it. Nothing was created.`
|
|
1246
|
+
});
|
|
1247
|
+
}
|
|
1248
|
+
const created = await provider.createCloudProject({
|
|
1249
|
+
projectId,
|
|
1250
|
+
displayName: plan.displayName ?? projectId,
|
|
1251
|
+
...plan.parent ? { parent: plan.parent } : {}
|
|
1252
|
+
});
|
|
1253
|
+
const added = await provider.addFirebase(created.projectId);
|
|
1254
|
+
return { project: added, createdProject: true, addedFirebase: true };
|
|
1255
|
+
}
|
|
1256
|
+
async function ensureWebApp(plan, provider) {
|
|
1257
|
+
const projectId = plan.projectId;
|
|
1258
|
+
const selected = await selectWebApp(plan, provider);
|
|
1259
|
+
if (selected) {
|
|
1260
|
+
return { app: selected, created: false };
|
|
1261
|
+
}
|
|
1262
|
+
const created = await provider.createWebApp(projectId, plan.webAppDisplayName);
|
|
1263
|
+
return { app: created, created: true };
|
|
1264
|
+
}
|
|
1265
|
+
async function selectWebApp(plan, provider) {
|
|
1266
|
+
const projectId = plan.projectId;
|
|
1267
|
+
if (plan.appId) {
|
|
1268
|
+
const app = await provider.getWebApp(projectId, plan.appId);
|
|
1269
|
+
if (!app) {
|
|
1270
|
+
throw new VibeInfraError({
|
|
1271
|
+
code: "web_app_not_found",
|
|
1272
|
+
message: `Web app ${plan.appId} was not found in project ${projectId}.`,
|
|
1273
|
+
remediation: "Run doctor to list web apps, then pass --app with one of those ids. A missing id will not create a replacement automatically."
|
|
1274
|
+
});
|
|
1275
|
+
}
|
|
1276
|
+
return app;
|
|
1277
|
+
}
|
|
1278
|
+
const apps = await provider.listWebApps(projectId);
|
|
1279
|
+
if (apps.length === 0) {
|
|
1280
|
+
return null;
|
|
1281
|
+
}
|
|
1282
|
+
if (apps.length === 1) {
|
|
1283
|
+
return apps[0] ?? null;
|
|
1284
|
+
}
|
|
1285
|
+
const named = apps.filter((app) => app.displayName === plan.webAppDisplayName);
|
|
1286
|
+
if (named.length === 1) {
|
|
1287
|
+
return named[0] ?? null;
|
|
1288
|
+
}
|
|
1289
|
+
throw new VibeInfraError({
|
|
1290
|
+
code: "ambiguous_web_apps",
|
|
1291
|
+
message: `Project ${projectId} has ${apps.length} web apps and none is an exact display-name match.`,
|
|
1292
|
+
remediation: `Pass --app with one of: ${apps.map((app) => app.appId).join(", ")}. VibeInfra will not guess or create another app.`
|
|
1293
|
+
});
|
|
1294
|
+
}
|
|
1295
|
+
async function assertBuildOutput(directory, spa) {
|
|
1296
|
+
if (!await pathExists(directory)) {
|
|
1297
|
+
throw new VibeInfraError({
|
|
1298
|
+
code: "missing_build_output",
|
|
1299
|
+
message: `Build output ${directory} does not exist.`,
|
|
1300
|
+
remediation: "Confirm the build script writes the public directory shown in the plan, then resume."
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
if (spa && !await pathExists(path5.join(directory, "index.html"))) {
|
|
1304
|
+
throw new VibeInfraError({
|
|
1305
|
+
code: "missing_build_output",
|
|
1306
|
+
message: "The SPA build output does not contain index.html.",
|
|
1307
|
+
remediation: "Check the Vite build. Hosting was not deployed."
|
|
1308
|
+
});
|
|
1309
|
+
}
|
|
1310
|
+
const entries = await readdir(directory);
|
|
1311
|
+
if (entries.length === 0) {
|
|
1312
|
+
throw new VibeInfraError({
|
|
1313
|
+
code: "missing_build_output",
|
|
1314
|
+
message: "The build output directory is empty.",
|
|
1315
|
+
remediation: "Check the build script. An empty directory will not be deployed."
|
|
1316
|
+
});
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
async function scanDirectory(directory) {
|
|
1320
|
+
const findings = [];
|
|
1321
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
1322
|
+
for (const entry of entries) {
|
|
1323
|
+
const full = path5.join(directory, entry.name);
|
|
1324
|
+
if (entry.isDirectory()) {
|
|
1325
|
+
findings.push(...await scanDirectory(full));
|
|
1326
|
+
continue;
|
|
1327
|
+
}
|
|
1328
|
+
if (!entry.isFile() || !isTextExtension(entry.name)) {
|
|
1329
|
+
continue;
|
|
1330
|
+
}
|
|
1331
|
+
const text = await readFile3(full, "utf8");
|
|
1332
|
+
for (const id of findSecretIds(text)) {
|
|
1333
|
+
findings.push(`${entry.name} (${id})`);
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
return findings;
|
|
1337
|
+
}
|
|
1338
|
+
function isTextExtension(name) {
|
|
1339
|
+
return /\.(html?|js|css|json|txt|map|svg)$/i.test(name);
|
|
1340
|
+
}
|
|
1341
|
+
function mark(steps, id, status, detail) {
|
|
1342
|
+
const step = steps.find((candidate) => candidate.id === id);
|
|
1343
|
+
if (!step) {
|
|
1344
|
+
throw new VibeInfraError({
|
|
1345
|
+
code: "internal",
|
|
1346
|
+
message: `Deployment step ${id} is missing.`,
|
|
1347
|
+
remediation: "This is a VibeInfra bug.",
|
|
1348
|
+
category: "provider"
|
|
1349
|
+
});
|
|
1350
|
+
}
|
|
1351
|
+
step.status = status;
|
|
1352
|
+
if (detail) {
|
|
1353
|
+
step.detail = detail;
|
|
1354
|
+
}
|
|
1355
|
+
return step;
|
|
1356
|
+
}
|
|
1357
|
+
function blockedResult(plan) {
|
|
1358
|
+
const first = plan.blockers[0];
|
|
1359
|
+
return {
|
|
1360
|
+
status: "failed",
|
|
1361
|
+
plan,
|
|
1362
|
+
steps: plan.steps,
|
|
1363
|
+
verifiedUrl: null,
|
|
1364
|
+
httpChecks: [],
|
|
1365
|
+
resourceIds: {},
|
|
1366
|
+
journalPath: null,
|
|
1367
|
+
remediation: plan.blockers.map((blocker) => blocker.message),
|
|
1368
|
+
warnings: plan.warnings,
|
|
1369
|
+
error: {
|
|
1370
|
+
code: first?.code ?? "not_deployable",
|
|
1371
|
+
message: plan.blockers.map((blocker) => blocker.message).join(" "),
|
|
1372
|
+
remediation: "Resolve the blockers in the plan. Nothing was changed.",
|
|
1373
|
+
retryable: false,
|
|
1374
|
+
category: "user"
|
|
1375
|
+
}
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
function dryResult(plan) {
|
|
1379
|
+
return {
|
|
1380
|
+
status: "dry-run",
|
|
1381
|
+
plan,
|
|
1382
|
+
steps: plan.steps.map((step) => ({ ...step, status: "skipped", detail: "Dry run does not execute this step." })),
|
|
1383
|
+
verifiedUrl: null,
|
|
1384
|
+
httpChecks: [],
|
|
1385
|
+
resourceIds: {},
|
|
1386
|
+
journalPath: null,
|
|
1387
|
+
remediation: [],
|
|
1388
|
+
warnings: [...plan.warnings, "Dry run did not contact Google and did not write local files."]
|
|
1389
|
+
};
|
|
1390
|
+
}
|
|
1391
|
+
async function pathExists(file) {
|
|
1392
|
+
try {
|
|
1393
|
+
await access2(file);
|
|
1394
|
+
return true;
|
|
1395
|
+
} catch {
|
|
1396
|
+
return false;
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
function exitCodeFor(result) {
|
|
1400
|
+
if (result.status === "succeeded" || result.status === "dry-run") {
|
|
1401
|
+
return 0;
|
|
1402
|
+
}
|
|
1403
|
+
if (result.status === "partial") {
|
|
1404
|
+
return 3;
|
|
1405
|
+
}
|
|
1406
|
+
return result.error?.category === "provider" ? 2 : 1;
|
|
1407
|
+
}
|
|
1408
|
+
async function resumeOptions(options) {
|
|
1409
|
+
if (!options.resume) {
|
|
1410
|
+
return options;
|
|
1411
|
+
}
|
|
1412
|
+
const journal = await readJournal(options.path);
|
|
1413
|
+
if (!journal) {
|
|
1414
|
+
throw new VibeInfraError({
|
|
1415
|
+
code: "nothing_to_resume",
|
|
1416
|
+
message: "There is no deployment journal in this project.",
|
|
1417
|
+
remediation: "Run deploy without --resume. If cloud resources were created earlier, the new deploy reconciles them."
|
|
1418
|
+
});
|
|
1419
|
+
}
|
|
1420
|
+
if (options.projectId && journal.projectId && options.projectId !== journal.projectId) {
|
|
1421
|
+
throw new VibeInfraError({
|
|
1422
|
+
code: "resume_project_mismatch",
|
|
1423
|
+
message: `The journal is for ${journal.projectId}, not ${options.projectId}.`,
|
|
1424
|
+
remediation: "Resume without a different --project, or start a new deploy with the project you intend to use."
|
|
1425
|
+
});
|
|
1426
|
+
}
|
|
1427
|
+
return {
|
|
1428
|
+
...options,
|
|
1429
|
+
projectId: options.projectId ?? journal.projectId ?? void 0
|
|
1430
|
+
};
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
export {
|
|
1434
|
+
ADC_LOGIN_COMMAND,
|
|
1435
|
+
redact,
|
|
1436
|
+
VibeInfraError,
|
|
1437
|
+
toVibeInfraError,
|
|
1438
|
+
readJournal,
|
|
1439
|
+
readOptionalJson,
|
|
1440
|
+
assertProjectId,
|
|
1441
|
+
assertParent,
|
|
1442
|
+
assertWebAppId,
|
|
1443
|
+
assertServiceId,
|
|
1444
|
+
assertOperationName,
|
|
1445
|
+
createDeploymentPlan,
|
|
1446
|
+
loadPlanContext,
|
|
1447
|
+
findSecretIds,
|
|
1448
|
+
isPermissiveRules,
|
|
1449
|
+
deployApplication,
|
|
1450
|
+
exitCodeFor,
|
|
1451
|
+
resumeOptions
|
|
1452
|
+
};
|