qarpeo 0.1.10 → 0.1.11

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.
@@ -1,15 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import { defineCommand, runMain } from 'citty';
3
3
  import { spawnSync } from 'node:child_process';
4
- import { existsSync, mkdirSync, writeFileSync, readdirSync, statSync, readFileSync } from 'node:fs';
4
+ import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, statSync } from 'node:fs';
5
5
  import { loadNuxtConfig } from '@nuxt/kit';
6
6
  import { resolve, join } from 'pathe';
7
- import { f as findSchemaFiles, r as resolveBinaryPath, e as ensurePackage, g as getLocalDatabaseContext, a as getJiti, b as resolveProjectName, c as checkDrizzleVersion, d as findLocalD1Database } from '../chunks/wrangler.mjs';
7
+ import { h as findSchemaFiles, i as resolveBinaryPath, j as ensurePackage, k as getLocalDatabaseContext, l as getJiti, b as resolveProjectName, a as checkDrizzleVersion, m as findLocalD1Database } from '../chunks/wrangler.mjs';
8
8
  import { reset, seed } from 'drizzle-seed';
9
+ import { stdin, stdout } from 'node:process';
10
+ import readline from 'node:readline/promises';
11
+ import { homedir } from 'node:os';
9
12
  import 'node:module';
10
13
  import 'drizzle-orm/node-sqlite';
11
- import 'node:process';
12
- import 'node:readline/promises';
13
14
  import 'node:url';
14
15
  import 'node:fs/promises';
15
16
  import 'defu';
@@ -168,6 +169,276 @@ const cleanCommand = defineCommand({
168
169
  }
169
170
  });
170
171
 
172
+ function getWranglerBin$4(cwd) {
173
+ return resolveBinaryPath("wrangler", cwd) || resolveBinaryPath("wrangler") || (process.platform === "win32" ? "wrangler.cmd" : "wrangler");
174
+ }
175
+ function loadDotEnv$6(cwd) {
176
+ const envPath = join(cwd, ".env");
177
+ if (!existsSync(envPath)) return;
178
+ try {
179
+ const raw = readFileSync(envPath, "utf8");
180
+ for (const line of raw.split(/\r?\n/)) {
181
+ const trimmed = line.trim();
182
+ if (!trimmed || trimmed.startsWith("#")) continue;
183
+ const eqIdx = trimmed.indexOf("=");
184
+ if (eqIdx === -1) continue;
185
+ const key = trimmed.slice(0, eqIdx).trim();
186
+ let val = trimmed.slice(eqIdx + 1).trim();
187
+ if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
188
+ val = val.slice(1, -1);
189
+ }
190
+ if (process.env[key] === void 0) {
191
+ process.env[key] = val;
192
+ }
193
+ }
194
+ } catch {
195
+ }
196
+ }
197
+ const create = defineCommand({
198
+ meta: {
199
+ name: "create",
200
+ description: "Create a new Cloudflare D1 database in your account"
201
+ },
202
+ args: {
203
+ name: {
204
+ type: "positional",
205
+ description: "Name of the new D1 database (e.g. my-app-prod or my-app-preview)",
206
+ required: false
207
+ },
208
+ location: {
209
+ type: "string",
210
+ description: "Primary location for the database (wnam, enam, weur, eeur, apac, oc)"
211
+ },
212
+ cwd: {
213
+ type: "string",
214
+ description: "Working directory",
215
+ default: "."
216
+ }
217
+ },
218
+ async run({ args }) {
219
+ const cwd = resolve(process.cwd(), args.cwd);
220
+ loadDotEnv$6(cwd);
221
+ let dbName = args.name;
222
+ if (!dbName && stdin.isTTY) {
223
+ const rl = readline.createInterface({ input: stdin, output: stdout });
224
+ const answer = await rl.question("\u{1F5C4}\uFE0F [qarpeo] Enter a name for the new D1 database: ");
225
+ rl.close();
226
+ dbName = answer.trim();
227
+ }
228
+ if (!dbName) {
229
+ console.error("\n\u274C [qarpeo] Database name is required.");
230
+ console.error(" Usage: qp db create <name> [options]");
231
+ console.error(" Example: qp db create my-app-prod\n");
232
+ process.exit(1);
233
+ }
234
+ await ensurePackage("wrangler", {
235
+ cwd,
236
+ purpose: "creating Cloudflare D1 database"
237
+ });
238
+ const wrangler = getWranglerBin$4(cwd);
239
+ console.log(`
240
+ \u26A1 [qarpeo] Creating D1 database "${dbName}" on Cloudflare...
241
+ `);
242
+ const wranglerArgs = ["d1", "create", dbName];
243
+ if (args.location) {
244
+ wranglerArgs.push("--location", args.location);
245
+ }
246
+ const result = spawnSync(wrangler, wranglerArgs, {
247
+ cwd,
248
+ stdio: "inherit",
249
+ env: process.env,
250
+ shell: process.platform === "win32"
251
+ });
252
+ if (result.status !== 0) {
253
+ console.error(`
254
+ \u274C [qarpeo] Failed to create D1 database "${dbName}".`);
255
+ process.exit(result.status ?? 1);
256
+ }
257
+ console.log(`
258
+ \u{1F389} [qarpeo] D1 database "${dbName}" created successfully!`);
259
+ console.log(" Copy the `database_id` UUID from the output above and add it to your `.env`:");
260
+ console.log(" QARPEO_DB_ID=<database_id>\n");
261
+ }
262
+ });
263
+
264
+ function getWranglerBin$3(cwd) {
265
+ return resolveBinaryPath("wrangler", cwd) || resolveBinaryPath("wrangler") || (process.platform === "win32" ? "wrangler.cmd" : "wrangler");
266
+ }
267
+ function loadDotEnv$5(cwd) {
268
+ const envPath = join(cwd, ".env");
269
+ if (!existsSync(envPath)) return;
270
+ try {
271
+ const raw = readFileSync(envPath, "utf8");
272
+ for (const line of raw.split(/\r?\n/)) {
273
+ const trimmed = line.trim();
274
+ if (!trimmed || trimmed.startsWith("#")) continue;
275
+ const eqIdx = trimmed.indexOf("=");
276
+ if (eqIdx === -1) continue;
277
+ const key = trimmed.slice(0, eqIdx).trim();
278
+ let val = trimmed.slice(eqIdx + 1).trim();
279
+ if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
280
+ val = val.slice(1, -1);
281
+ }
282
+ if (process.env[key] === void 0) {
283
+ process.env[key] = val;
284
+ }
285
+ }
286
+ } catch {
287
+ }
288
+ }
289
+ const deleteDb = defineCommand({
290
+ meta: {
291
+ name: "delete",
292
+ description: "Delete a Cloudflare D1 database from your account"
293
+ },
294
+ args: {
295
+ name: {
296
+ type: "positional",
297
+ description: "Name of the D1 database to delete",
298
+ required: false
299
+ },
300
+ yes: {
301
+ type: "boolean",
302
+ alias: "y",
303
+ description: "Skip confirmation prompt",
304
+ default: false
305
+ },
306
+ cwd: {
307
+ type: "string",
308
+ description: "Working directory",
309
+ default: "."
310
+ }
311
+ },
312
+ async run({ args }) {
313
+ const cwd = resolve(process.cwd(), args.cwd);
314
+ loadDotEnv$5(cwd);
315
+ let dbName = args.name;
316
+ if (!dbName && stdin.isTTY) {
317
+ const rl = readline.createInterface({ input: stdin, output: stdout });
318
+ const answer = await rl.question("\u{1F5D1}\uFE0F [qarpeo] Enter the name of the D1 database to delete: ");
319
+ rl.close();
320
+ dbName = answer.trim();
321
+ }
322
+ if (!dbName) {
323
+ console.error("\n\u274C [qarpeo] Database name is required.");
324
+ console.error(" Usage: qp db delete <name> [options]\n");
325
+ process.exit(1);
326
+ }
327
+ if (!args.yes && stdin.isTTY) {
328
+ const rl = readline.createInterface({ input: stdin, output: stdout });
329
+ const answer = await rl.question(
330
+ `
331
+ \u26A0\uFE0F [qarpeo] Are you sure you want to permanently delete D1 database "${dbName}"? (y/N): `
332
+ );
333
+ rl.close();
334
+ const confirmed = answer.trim().toLowerCase();
335
+ if (confirmed !== "y" && confirmed !== "yes") {
336
+ console.log("\u{1F6AB} [qarpeo] Deletion cancelled.\n");
337
+ return;
338
+ }
339
+ }
340
+ await ensurePackage("wrangler", {
341
+ cwd,
342
+ purpose: "deleting Cloudflare D1 database"
343
+ });
344
+ const wrangler = getWranglerBin$3(cwd);
345
+ console.log(`
346
+ \u{1F5D1}\uFE0F [qarpeo] Deleting D1 database "${dbName}" on Cloudflare...
347
+ `);
348
+ const wranglerArgs = ["d1", "delete", dbName];
349
+ if (args.yes) {
350
+ wranglerArgs.push("--skip-empty");
351
+ }
352
+ const result = spawnSync(wrangler, wranglerArgs, {
353
+ cwd,
354
+ stdio: "inherit",
355
+ env: process.env,
356
+ shell: process.platform === "win32"
357
+ });
358
+ if (result.status !== 0) {
359
+ console.error(`
360
+ \u274C [qarpeo] Failed to delete D1 database "${dbName}".`);
361
+ process.exit(result.status ?? 1);
362
+ }
363
+ console.log(`
364
+ \u2705 [qarpeo] D1 database "${dbName}" deleted successfully!
365
+ `);
366
+ }
367
+ });
368
+
369
+ function getWranglerBin$2(cwd) {
370
+ return resolveBinaryPath("wrangler", cwd) || resolveBinaryPath("wrangler") || (process.platform === "win32" ? "wrangler.cmd" : "wrangler");
371
+ }
372
+ function loadDotEnv$4(cwd) {
373
+ const envPath = join(cwd, ".env");
374
+ if (!existsSync(envPath)) return;
375
+ try {
376
+ const raw = readFileSync(envPath, "utf8");
377
+ for (const line of raw.split(/\r?\n/)) {
378
+ const trimmed = line.trim();
379
+ if (!trimmed || trimmed.startsWith("#")) continue;
380
+ const eqIdx = trimmed.indexOf("=");
381
+ if (eqIdx === -1) continue;
382
+ const key = trimmed.slice(0, eqIdx).trim();
383
+ let val = trimmed.slice(eqIdx + 1).trim();
384
+ if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
385
+ val = val.slice(1, -1);
386
+ }
387
+ if (process.env[key] === void 0) {
388
+ process.env[key] = val;
389
+ }
390
+ }
391
+ } catch {
392
+ }
393
+ }
394
+ const list = defineCommand({
395
+ meta: {
396
+ name: "list",
397
+ description: "List all Cloudflare D1 databases in your account with their UUIDs"
398
+ },
399
+ args: {
400
+ json: {
401
+ type: "boolean",
402
+ description: "Output in JSON format",
403
+ default: false
404
+ },
405
+ cwd: {
406
+ type: "string",
407
+ description: "Working directory",
408
+ default: "."
409
+ }
410
+ },
411
+ async run({ args }) {
412
+ const cwd = resolve(process.cwd(), args.cwd);
413
+ loadDotEnv$4(cwd);
414
+ await ensurePackage("wrangler", {
415
+ cwd,
416
+ purpose: "listing Cloudflare D1 databases"
417
+ });
418
+ const wrangler = getWranglerBin$2(cwd);
419
+ console.log("\u{1F50D} [qarpeo] Fetching D1 databases from Cloudflare...\n");
420
+ const wranglerArgs = ["d1", "list"];
421
+ if (args.json) {
422
+ wranglerArgs.push("--json");
423
+ }
424
+ const result = spawnSync(wrangler, wranglerArgs, {
425
+ cwd,
426
+ stdio: "inherit",
427
+ env: process.env,
428
+ shell: process.platform === "win32"
429
+ });
430
+ if (result.status !== 0) {
431
+ console.error("\n\u274C [qarpeo] Failed to list D1 databases. Make sure you are logged in (`qp login`) or have CLOUDFLARE_API_TOKEN set in .env.");
432
+ process.exit(result.status ?? 1);
433
+ }
434
+ if (!args.json) {
435
+ console.log("\n\u{1F4A1} [qarpeo] Tip: Copy the database `uuid` above into your `.env`:");
436
+ console.log(" QARPEO_DB_ID=<uuid> # for production (`qp deploy`)");
437
+ console.log(" QARPEO_PREVIEW_DB_ID=<uuid> # for preview (`qp deploy --preview`)\n");
438
+ }
439
+ }
440
+ });
441
+
171
442
  const migrate = defineCommand({
172
443
  meta: {
173
444
  name: "migrate",
@@ -383,110 +654,795 @@ const seedCommand = defineCommand({
383
654
  args: {
384
655
  clean: {
385
656
  type: "boolean",
386
- description: "Clean/truncate existing records before seeding",
387
- default: false
657
+ description: "Clean/truncate existing records before seeding",
658
+ default: false
659
+ },
660
+ reset: {
661
+ type: "boolean",
662
+ description: "Alias for --clean",
663
+ default: false
664
+ },
665
+ count: {
666
+ type: "string",
667
+ description: "Number of mock rows to generate per table (defaults to 10)",
668
+ default: "10"
669
+ },
670
+ seedNumber: {
671
+ type: "string",
672
+ description: "Optional deterministic seed number for reproducible data"
673
+ },
674
+ remote: {
675
+ type: "boolean",
676
+ description: "Restricted \u2014 seeding is blocked on production to prevent data loss",
677
+ default: false
678
+ },
679
+ cwd: {
680
+ type: "string",
681
+ description: "Working directory",
682
+ default: "."
683
+ }
684
+ },
685
+ async run({ args }) {
686
+ if (args.remote) {
687
+ console.error(
688
+ "\u274C [qarpeo] `qp db:seed` is restricted to local development to protect production data (Decision 15)."
689
+ );
690
+ process.exit(1);
691
+ }
692
+ const cwd = resolve(process.cwd(), args.cwd);
693
+ const nuxtConfig = await loadNuxtConfig({ cwd });
694
+ console.log("\u{1F331} [qarpeo] Preparing database for seeding...");
695
+ let ctx;
696
+ try {
697
+ ctx = await getLocalDatabaseContext(cwd, nuxtConfig);
698
+ } catch (err) {
699
+ console.error(`\u274C [qarpeo] ${err?.message || err}`);
700
+ process.exit(1);
701
+ }
702
+ const { db, schema, customSeedPath, sqlitePath } = ctx;
703
+ const shouldClean = Boolean(args.clean || args.reset);
704
+ if (shouldClean) {
705
+ console.log("\u23F3 [qarpeo] Resetting existing records...");
706
+ await reset(db, schema);
707
+ console.log("\u2714 [qarpeo] Existing tables cleanly truncated.");
708
+ }
709
+ if (customSeedPath) {
710
+ console.log(`\u{1F680} [qarpeo] Running custom seed script: ${customSeedPath}`);
711
+ try {
712
+ const jiti = await getJiti(cwd);
713
+ const userSeed = await jiti.import(customSeedPath);
714
+ const seedFn = userSeed.default || userSeed.seed || userSeed;
715
+ if (typeof seedFn === "function") {
716
+ await seedFn({ db, schema, seed, reset });
717
+ console.log("\u2705 [qarpeo] Custom seed script completed successfully!");
718
+ return;
719
+ } else {
720
+ console.log(
721
+ "\u2139 [qarpeo] Custom seed script does not export a default function. Falling back to drizzle-seed."
722
+ );
723
+ }
724
+ } catch (err) {
725
+ console.error(`\u274C [qarpeo] Error running custom seed script: ${err?.message || err}`);
726
+ process.exit(1);
727
+ }
728
+ }
729
+ const count = parseInt(args.count || "10", 10);
730
+ const seedNumber = args.seedNumber ? parseInt(args.seedNumber, 10) : void 0;
731
+ console.log(`\u{1F331} [qarpeo] Generating mock data with drizzle-seed (${count} rows per table)...`);
732
+ try {
733
+ await seed(db, schema, {
734
+ count,
735
+ seed: seedNumber
736
+ });
737
+ console.log(`\u2705 [qarpeo] Successfully seeded local D1 database: ${sqlitePath}`);
738
+ } catch (err) {
739
+ console.error(`\u274C [qarpeo] Error during drizzle-seed: ${err?.message || err}`);
740
+ process.exit(1);
741
+ }
742
+ }
743
+ });
744
+
745
+ const db = defineCommand({
746
+ meta: {
747
+ name: "db",
748
+ description: "Manage Cloudflare D1 database, Drizzle ORM migrations, and seeding"
749
+ },
750
+ subCommands: {
751
+ list,
752
+ ls: list,
753
+ create,
754
+ delete: deleteDb,
755
+ drop: deleteDb,
756
+ generate,
757
+ migrate,
758
+ push,
759
+ seed: seedCommand,
760
+ clean: cleanCommand,
761
+ reset: cleanCommand
762
+ }
763
+ });
764
+
765
+ function findWranglerDefaultToml() {
766
+ const candidates = [
767
+ join(homedir(), "AppData", "Roaming", "xdg.config", ".wrangler", "config", "default.toml"),
768
+ join(homedir(), ".config", ".wrangler", "config", "default.toml"),
769
+ join(homedir(), ".wrangler", "config", "default.toml"),
770
+ join(homedir(), ".wrangler", "config.toml")
771
+ ];
772
+ for (const p of candidates) {
773
+ if (existsSync(p)) return p;
774
+ }
775
+ return null;
776
+ }
777
+ function parseOAuthTokenFromToml(filePath) {
778
+ try {
779
+ const raw = readFileSync(filePath, "utf8");
780
+ const match = raw.match(/oauth_token\s*=\s*"([^"]+)"/);
781
+ return match ? match[1] : null;
782
+ } catch {
783
+ return null;
784
+ }
785
+ }
786
+ async function getCloudflareAuth(cwd = process.cwd()) {
787
+ let token = process.env.CLOUDFLARE_API_TOKEN;
788
+ let accountId = process.env.CLOUDFLARE_ACCOUNT_ID;
789
+ if (!token) {
790
+ const tomlPath = findWranglerDefaultToml();
791
+ if (tomlPath) {
792
+ token = parseOAuthTokenFromToml(tomlPath);
793
+ }
794
+ }
795
+ if (!token) {
796
+ return null;
797
+ }
798
+ if (!accountId) {
799
+ try {
800
+ let res = await fetch("https://api.cloudflare.com/client/v4/accounts", {
801
+ headers: { Authorization: `Bearer ${token}` }
802
+ });
803
+ if (res.status === 401) {
804
+ const wrangler = resolveBinaryPath("wrangler", cwd) || (process.platform === "win32" ? "wrangler.cmd" : "wrangler");
805
+ spawnSync(wrangler, ["whoami"], {
806
+ cwd,
807
+ stdio: "ignore",
808
+ shell: process.platform === "win32"
809
+ });
810
+ const tomlPath = findWranglerDefaultToml();
811
+ if (tomlPath) {
812
+ const freshToken = parseOAuthTokenFromToml(tomlPath);
813
+ if (freshToken) {
814
+ token = freshToken;
815
+ res = await fetch("https://api.cloudflare.com/client/v4/accounts", {
816
+ headers: { Authorization: `Bearer ${token}` }
817
+ });
818
+ }
819
+ }
820
+ }
821
+ if (res.ok) {
822
+ const data = await res.json();
823
+ if (data.result && data.result.length > 0) {
824
+ accountId = data.result[0].id;
825
+ }
826
+ }
827
+ } catch {
828
+ }
829
+ }
830
+ if (!token || !accountId) return null;
831
+ return { token, accountId };
832
+ }
833
+ async function listCloudflareWorkers(auth) {
834
+ const url = `https://api.cloudflare.com/client/v4/accounts/${auth.accountId}/workers/scripts`;
835
+ const res = await fetch(url, {
836
+ headers: { Authorization: `Bearer ${auth.token}` }
837
+ });
838
+ if (!res.ok) {
839
+ const errText = await res.text();
840
+ throw new Error(`Failed to list Cloudflare Workers (HTTP ${res.status}): ${errText}`);
841
+ }
842
+ const data = await res.json();
843
+ return data.result || [];
844
+ }
845
+
846
+ function getWranglerBin$1(cwd) {
847
+ return resolveBinaryPath("wrangler", cwd) || resolveBinaryPath("wrangler") || (process.platform === "win32" ? "wrangler.cmd" : "wrangler");
848
+ }
849
+ function loadDotEnv$3(cwd) {
850
+ const envPath = join(cwd, ".env");
851
+ if (!existsSync(envPath)) return;
852
+ try {
853
+ const raw = readFileSync(envPath, "utf8");
854
+ for (const line of raw.split(/\r?\n/)) {
855
+ const trimmed = line.trim();
856
+ if (!trimmed || trimmed.startsWith("#")) continue;
857
+ const eqIdx = trimmed.indexOf("=");
858
+ if (eqIdx === -1) continue;
859
+ const key = trimmed.slice(0, eqIdx).trim();
860
+ let val = trimmed.slice(eqIdx + 1).trim();
861
+ if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
862
+ val = val.slice(1, -1);
863
+ }
864
+ if (process.env[key] === void 0) {
865
+ process.env[key] = val;
866
+ }
867
+ }
868
+ } catch {
869
+ }
870
+ }
871
+ const deleteCommand = defineCommand({
872
+ meta: {
873
+ name: "delete",
874
+ description: "Delete a deployed Worker service from Cloudflare"
875
+ },
876
+ args: {
877
+ name: {
878
+ type: "positional",
879
+ description: "Name of the Cloudflare Worker service to delete (e.g. qarpeo-starter)",
880
+ required: false
881
+ },
882
+ force: {
883
+ type: "boolean",
884
+ alias: "f",
885
+ description: "Delete even if other Workers or routes depend on it",
886
+ default: false
887
+ },
888
+ yes: {
889
+ type: "boolean",
890
+ alias: "y",
891
+ description: "Skip interactive confirmation prompt",
892
+ default: false
893
+ },
894
+ dryRun: {
895
+ type: "boolean",
896
+ description: "Dry run validation without actually deleting from Cloudflare",
897
+ default: false
898
+ },
899
+ env: {
900
+ type: "string",
901
+ description: "Target Cloudflare environment (if configured)"
902
+ },
903
+ cwd: {
904
+ type: "string",
905
+ description: "Working directory",
906
+ default: "."
907
+ }
908
+ },
909
+ async run({ args }) {
910
+ const cwd = resolve(process.cwd(), args.cwd);
911
+ loadDotEnv$3(cwd);
912
+ let workerName = args.name;
913
+ if (!workerName) {
914
+ const nameFlagIdx = process.argv.indexOf("--name");
915
+ if (nameFlagIdx !== -1 && process.argv[nameFlagIdx + 1]) {
916
+ workerName = process.argv[nameFlagIdx + 1];
917
+ }
918
+ }
919
+ if (!workerName && stdin.isTTY) {
920
+ try {
921
+ const auth = await getCloudflareAuth(cwd);
922
+ if (auth) {
923
+ process.stdout.write("\u{1F50D} [qarpeo] Fetching deployed Workers from Cloudflare...\n");
924
+ const workers = await listCloudflareWorkers(auth);
925
+ if (workers.length > 0) {
926
+ console.log("\n\u{1F4E6} Select a Worker to delete from your Cloudflare account:\n");
927
+ workers.forEach((w, idx) => {
928
+ const modified = w.modified_on ? ` (modified: ${w.modified_on.slice(0, 10)})` : "";
929
+ console.log(` [${idx + 1}] ${w.id}${modified}`);
930
+ });
931
+ console.log("");
932
+ const rl = readline.createInterface({ input: stdin, output: stdout });
933
+ const answer = await rl.question(
934
+ `Enter number (1-${workers.length}) or Worker name [q to cancel]: `
935
+ );
936
+ rl.close();
937
+ const trimmed = answer.trim();
938
+ if (!trimmed || trimmed.toLowerCase() === "q") {
939
+ console.log("\u{1F6AB} [qarpeo] Operation cancelled.\n");
940
+ return;
941
+ }
942
+ const num = parseInt(trimmed, 10);
943
+ if (!isNaN(num) && num >= 1 && num <= workers.length) {
944
+ workerName = workers[num - 1].id;
945
+ } else {
946
+ workerName = trimmed;
947
+ }
948
+ }
949
+ }
950
+ } catch {
951
+ }
952
+ }
953
+ if (!workerName) {
954
+ workerName = process.env.QARPEO_WORKER_NAME || process.env.WORKER_NAME;
955
+ }
956
+ if (!workerName && stdin.isTTY) {
957
+ const rl = readline.createInterface({ input: stdin, output: stdout });
958
+ const answer = await rl.question("\u{1F5D1}\uFE0F [qarpeo] Enter the name of the Worker to delete: ");
959
+ rl.close();
960
+ workerName = answer.trim();
961
+ }
962
+ if (!workerName) {
963
+ console.error("\n\u274C [qarpeo] Worker name is required.");
964
+ console.error(" Usage: qp delete <worker-name> [options]");
965
+ console.error(" Example: qp delete qarpeo-starter\n");
966
+ process.exit(1);
967
+ }
968
+ if (!args.yes && !args.force && !args.dryRun) {
969
+ if (stdin.isTTY) {
970
+ const rl = readline.createInterface({ input: stdin, output: stdout });
971
+ const answer = await rl.question(
972
+ `
973
+ \u26A0\uFE0F [qarpeo] Are you sure you want to permanently delete Worker "${workerName}" from Cloudflare? (y/N): `
974
+ );
975
+ rl.close();
976
+ const confirmed = answer.trim().toLowerCase();
977
+ if (confirmed !== "y" && confirmed !== "yes") {
978
+ console.log("\u{1F6AB} [qarpeo] Deletion cancelled.\n");
979
+ return;
980
+ }
981
+ }
982
+ }
983
+ await ensurePackage("wrangler", {
984
+ cwd,
985
+ purpose: "deleting Cloudflare Worker"
986
+ });
987
+ const wrangler = getWranglerBin$1(cwd);
988
+ console.log(`
989
+ \u{1F5D1}\uFE0F [qarpeo] Deleting Worker "${workerName}" from Cloudflare...`);
990
+ const wranglerArgs = ["delete", workerName];
991
+ if (args.dryRun) {
992
+ wranglerArgs.push("--dry-run");
993
+ }
994
+ if (args.force) {
995
+ wranglerArgs.push("--force");
996
+ }
997
+ if (args.env) {
998
+ wranglerArgs.push("--env", args.env);
999
+ }
1000
+ const result = spawnSync(wrangler, wranglerArgs, {
1001
+ cwd,
1002
+ stdio: "inherit",
1003
+ env: process.env,
1004
+ shell: process.platform === "win32"
1005
+ });
1006
+ if (result.status !== 0) {
1007
+ console.error(`
1008
+ \u274C [qarpeo] Failed to delete Worker "${workerName}".`);
1009
+ process.exit(result.status ?? 1);
1010
+ }
1011
+ if (args.dryRun) {
1012
+ console.log(`
1013
+ \u{1F50D} [qarpeo] Dry-run completed. Worker "${workerName}" was not deleted.
1014
+ `);
1015
+ } else {
1016
+ console.log(`
1017
+ \u2705 [qarpeo] Successfully deleted Worker "${workerName}" from Cloudflare!
1018
+ `);
1019
+ }
1020
+ }
1021
+ });
1022
+
1023
+ function loadDotEnv$2(cwd) {
1024
+ const envPath = join(cwd, ".env");
1025
+ if (!existsSync(envPath)) return;
1026
+ try {
1027
+ const raw = readFileSync(envPath, "utf8");
1028
+ for (const line of raw.split(/\r?\n/)) {
1029
+ const trimmed = line.trim();
1030
+ if (!trimmed || trimmed.startsWith("#")) continue;
1031
+ const eqIdx = trimmed.indexOf("=");
1032
+ if (eqIdx === -1) continue;
1033
+ const key = trimmed.slice(0, eqIdx).trim();
1034
+ let val = trimmed.slice(eqIdx + 1).trim();
1035
+ if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
1036
+ val = val.slice(1, -1);
1037
+ }
1038
+ if (process.env[key] === void 0) {
1039
+ process.env[key] = val;
1040
+ }
1041
+ }
1042
+ } catch {
1043
+ }
1044
+ }
1045
+ function getGitBranch(cwd) {
1046
+ if (process.env.GITHUB_HEAD_REF) return process.env.GITHUB_HEAD_REF;
1047
+ if (process.env.GITHUB_REF_NAME) return process.env.GITHUB_REF_NAME;
1048
+ try {
1049
+ const res = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
1050
+ cwd,
1051
+ encoding: "utf8"
1052
+ });
1053
+ if (res.status === 0 && res.stdout.trim()) {
1054
+ return res.stdout.trim();
1055
+ }
1056
+ } catch {
1057
+ }
1058
+ return null;
1059
+ }
1060
+ async function promptWorkerName(defaultName) {
1061
+ if (!stdin.isTTY) {
1062
+ return defaultName;
1063
+ }
1064
+ const rl = readline.createInterface({ input: stdin, output: stdout });
1065
+ try {
1066
+ const answer = await rl.question(`
1067
+ \u{1F3F7}\uFE0F Cloudflare Worker Name [${defaultName}]: `);
1068
+ const trimmed = answer.trim();
1069
+ return trimmed || defaultName;
1070
+ } finally {
1071
+ rl.close();
1072
+ }
1073
+ }
1074
+ function sanitizeSuffix(raw) {
1075
+ const clean = raw.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
1076
+ return clean.slice(0, 20) || "preview";
1077
+ }
1078
+ const deploy = defineCommand({
1079
+ meta: {
1080
+ name: "deploy",
1081
+ description: "Build and deploy full-stack Nuxt application directly to Cloudflare Workers"
1082
+ },
1083
+ args: {
1084
+ cwd: {
1085
+ type: "string",
1086
+ description: "Working directory",
1087
+ default: "."
1088
+ },
1089
+ name: {
1090
+ type: "string",
1091
+ description: "Cloudflare Worker service name (overrides package.json and config)"
1092
+ },
1093
+ build: {
1094
+ type: "boolean",
1095
+ description: "Build the Nuxt application before deploying (pass --no-build to skip)",
1096
+ default: true
388
1097
  },
389
- reset: {
1098
+ preview: {
390
1099
  type: "boolean",
391
- description: "Alias for --clean",
1100
+ description: "Deploy to an isolated preview environment (does not affect production)",
392
1101
  default: false
393
1102
  },
394
- count: {
395
- type: "string",
396
- description: "Number of mock rows to generate per table (defaults to 10)",
397
- default: "10"
1103
+ migrate: {
1104
+ type: "boolean",
1105
+ description: "Apply pending D1 database migrations before deploy",
1106
+ default: true
398
1107
  },
399
- seedNumber: {
400
- type: "string",
401
- description: "Optional deterministic seed number for reproducible data"
1108
+ provision: {
1109
+ type: "boolean",
1110
+ description: "Auto-provision missing remote Cloudflare resources (D1, KV, R2)",
1111
+ default: true
402
1112
  },
403
- remote: {
1113
+ dryRun: {
404
1114
  type: "boolean",
405
- description: "Restricted \u2014 seeding is blocked on production to prevent data loss",
1115
+ description: "Verify configuration and build without executing remote deployment",
406
1116
  default: false
407
1117
  },
408
- cwd: {
1118
+ env: {
409
1119
  type: "string",
410
- description: "Working directory",
411
- default: "."
1120
+ description: "Cloudflare environment name (e.g. production, staging, preview)"
412
1121
  }
413
1122
  },
414
1123
  async run({ args }) {
415
- if (args.remote) {
1124
+ const cwd = resolve(process.cwd(), args.cwd);
1125
+ loadDotEnv$2(cwd);
1126
+ const isPreview = Boolean(args.preview);
1127
+ const branch = getGitBranch(cwd);
1128
+ const previewSuffix = branch && branch !== "main" && branch !== "master" && branch !== "HEAD" ? sanitizeSuffix(branch) : "preview";
1129
+ if (isPreview) {
1130
+ console.log(`
1131
+ \u26A1 [qarpeo] Starting Cloudflare Workers PREVIEW deployment (${previewSuffix})...
1132
+ `);
1133
+ } else {
1134
+ console.log(`
1135
+ \u26A1 [qarpeo] Starting Cloudflare Workers edge deployment...
1136
+ `);
1137
+ }
1138
+ let wranglerBin = resolveBinaryPath("wrangler", cwd);
1139
+ if (!wranglerBin) {
1140
+ const ok = await ensurePackage("wrangler", {
1141
+ cwd,
1142
+ dev: true,
1143
+ purpose: "deploying to Cloudflare Workers"
1144
+ });
1145
+ if (!ok) {
1146
+ console.error("\u274C [qarpeo] Failed to install or resolve wrangler. Aborting deployment.");
1147
+ process.exit(1);
1148
+ }
1149
+ wranglerBin = resolveBinaryPath("wrangler", cwd) || (process.platform === "win32" ? "wrangler.cmd" : "wrangler");
1150
+ }
1151
+ const hasEnvAuth = Boolean(
1152
+ process.env.CLOUDFLARE_API_TOKEN || process.env.CF_API_TOKEN || process.env.CLOUDFLARE_EMAIL && process.env.CLOUDFLARE_API_KEY
1153
+ );
1154
+ if (!hasEnvAuth && !args.dryRun) {
1155
+ const whoamiRes = spawnSync(wranglerBin, ["whoami"], {
1156
+ cwd,
1157
+ encoding: "utf8",
1158
+ shell: process.platform === "win32"
1159
+ });
1160
+ if (whoamiRes.status !== 0) {
1161
+ console.error("\u274C [qarpeo] Not authenticated with Cloudflare.");
1162
+ console.error("\u{1F449} Run 'npx qp login' or set CLOUDFLARE_API_TOKEN in your environment.\n");
1163
+ process.exit(1);
1164
+ }
1165
+ }
1166
+ if (args.build) {
1167
+ console.log("\u{1F4E6} [qarpeo] Building Nuxt application for Cloudflare Workers...");
1168
+ const buildEnv = {
1169
+ ...process.env,
1170
+ NITRO_PRESET: "cloudflare-module"
1171
+ };
1172
+ const nuxtBin = resolveBinaryPath("nuxt", cwd);
1173
+ let buildRes;
1174
+ if (nuxtBin) {
1175
+ buildRes = spawnSync(nuxtBin, ["build"], {
1176
+ cwd,
1177
+ stdio: "inherit",
1178
+ shell: process.platform === "win32",
1179
+ env: buildEnv
1180
+ });
1181
+ } else {
1182
+ const pnpmBin = process.platform === "win32" ? "pnpm.cmd" : "pnpm";
1183
+ buildRes = spawnSync(pnpmBin, ["nuxt", "build"], {
1184
+ cwd,
1185
+ stdio: "inherit",
1186
+ shell: process.platform === "win32",
1187
+ env: buildEnv
1188
+ });
1189
+ if (buildRes.status !== 0) {
1190
+ const npxBin = process.platform === "win32" ? "npx.cmd" : "npx";
1191
+ buildRes = spawnSync(npxBin, ["nuxt", "build"], {
1192
+ cwd,
1193
+ stdio: "inherit",
1194
+ shell: process.platform === "win32",
1195
+ env: buildEnv
1196
+ });
1197
+ }
1198
+ }
1199
+ if (buildRes.status !== 0) {
1200
+ console.error("\u274C [qarpeo] Nuxt build failed. Aborting deployment.");
1201
+ process.exit(buildRes.status ?? 1);
1202
+ }
1203
+ console.log("\u2705 [qarpeo] Build completed successfully.\n");
1204
+ }
1205
+ const candidateConfigs = [
1206
+ resolve(cwd, ".output/server/wrangler.json"),
1207
+ resolve(cwd, "wrangler.jsonc"),
1208
+ resolve(cwd, "wrangler.json"),
1209
+ resolve(cwd, ".nuxt/wrangler.json")
1210
+ ];
1211
+ let wranglerConfigPath = candidateConfigs.find((p) => existsSync(p)) || null;
1212
+ if (!wranglerConfigPath) {
416
1213
  console.error(
417
- "\u274C [qarpeo] `qp db:seed` is restricted to local development to protect production data (Decision 15)."
1214
+ "\u274C [qarpeo] Could not find wrangler.json output in .output/server/. Make sure nitro.preset is set to 'cloudflare-module'."
418
1215
  );
419
1216
  process.exit(1);
420
1217
  }
421
- const cwd = resolve(process.cwd(), args.cwd);
422
- const nuxtConfig = await loadNuxtConfig({ cwd });
423
- console.log("\u{1F331} [qarpeo] Preparing database for seeding...");
424
- let ctx;
1218
+ let config = {};
425
1219
  try {
426
- ctx = await getLocalDatabaseContext(cwd, nuxtConfig);
427
- } catch (err) {
428
- console.error(`\u274C [qarpeo] ${err?.message || err}`);
429
- process.exit(1);
1220
+ config = JSON.parse(readFileSync(wranglerConfigPath, "utf8"));
1221
+ } catch {
430
1222
  }
431
- const { db, schema, customSeedPath, sqlitePath } = ctx;
432
- const shouldClean = Boolean(args.clean || args.reset);
433
- if (shouldClean) {
434
- console.log("\u23F3 [qarpeo] Resetting existing records...");
435
- await reset(db, schema);
436
- console.log("\u2714 [qarpeo] Existing tables cleanly truncated.");
1223
+ const defaultName = config.name || "qarpeo";
1224
+ let baseWorkerName = args.name || process.env.QARPEO_WORKER_NAME || process.env.WORKER_NAME;
1225
+ if (!baseWorkerName) {
1226
+ if (!args.dryRun) {
1227
+ baseWorkerName = await promptWorkerName(defaultName);
1228
+ } else {
1229
+ baseWorkerName = defaultName;
1230
+ }
437
1231
  }
438
- if (customSeedPath) {
439
- console.log(`\u{1F680} [qarpeo] Running custom seed script: ${customSeedPath}`);
1232
+ const originalName = baseWorkerName;
1233
+ if (isPreview) {
1234
+ config.name = `${baseWorkerName}-${previewSuffix}`;
1235
+ console.log(`\u{1F3F7}\uFE0F [qarpeo] Preview Worker Name: ${config.name}`);
1236
+ } else {
1237
+ config.name = baseWorkerName;
1238
+ console.log(`\u{1F3F7}\uFE0F [qarpeo] Worker Name: ${config.name}`);
1239
+ }
1240
+ if (config.name !== defaultName) {
1241
+ writeFileSync(wranglerConfigPath, JSON.stringify(config, null, 2), "utf8");
1242
+ }
1243
+ if (args.provision && !args.dryRun && wranglerConfigPath.endsWith(".json")) {
440
1244
  try {
441
- const jiti = await getJiti(cwd);
442
- const userSeed = await jiti.import(customSeedPath);
443
- const seedFn = userSeed.default || userSeed.seed || userSeed;
444
- if (typeof seedFn === "function") {
445
- await seedFn({ db, schema, seed, reset });
446
- console.log("\u2705 [qarpeo] Custom seed script completed successfully!");
447
- return;
448
- } else {
449
- console.log(
450
- "\u2139 [qarpeo] Custom seed script does not export a default function. Falling back to drizzle-seed."
451
- );
1245
+ let modified = isPreview;
1246
+ if (Array.isArray(config.d1_databases) && config.d1_databases.length > 0) {
1247
+ const listRes = spawnSync(wranglerBin, ["d1", "list", "--json"], {
1248
+ cwd,
1249
+ encoding: "utf8",
1250
+ shell: process.platform === "win32"
1251
+ });
1252
+ let existingDbs = [];
1253
+ try {
1254
+ existingDbs = JSON.parse(listRes.stdout || "[]");
1255
+ } catch {
1256
+ }
1257
+ for (const d1 of config.d1_databases) {
1258
+ const explicitId = isPreview ? process.env.QARPEO_PREVIEW_DB_ID || process.env.PREVIEW_DB_ID || process.env.PREVIEW_DATABASE_ID : process.env.QARPEO_PROD_DB_ID || process.env.QARPEO_DB_ID || process.env.DB_ID || process.env.DATABASE_ID;
1259
+ const explicitName = isPreview ? process.env.QARPEO_PREVIEW_DB_NAME || process.env.PREVIEW_DB_NAME : process.env.QARPEO_PROD_DB_NAME || process.env.QARPEO_DB_NAME || process.env.DB_NAME;
1260
+ const targetDbName = explicitName || (isPreview ? `${d1.database_name}_preview` : d1.database_name);
1261
+ if (explicitId) {
1262
+ console.log(`\u{1F517} [qarpeo] Using explicit ${isPreview ? "preview" : "production"} D1 database: ${targetDbName} (${explicitId})`);
1263
+ d1.database_id = explicitId;
1264
+ d1.database_name = targetDbName;
1265
+ modified = true;
1266
+ continue;
1267
+ }
1268
+ const isPlaceholder = isPreview || !d1.database_id || d1.database_id === "DB_PROD" || d1.database_id.includes("LOCAL");
1269
+ if (isPlaceholder) {
1270
+ const match = existingDbs.find((db) => db.name === targetDbName);
1271
+ if (match) {
1272
+ console.log(`\u{1F517} [qarpeo] Linked ${isPreview ? "preview" : "remote"} D1 database: ${targetDbName} (${match.uuid})`);
1273
+ d1.database_id = match.uuid;
1274
+ d1.database_name = targetDbName;
1275
+ modified = true;
1276
+ } else {
1277
+ console.log(`\u{1F528} [qarpeo] Creating ${isPreview ? "preview" : "remote"} D1 database: ${targetDbName}...`);
1278
+ const createRes = spawnSync(
1279
+ wranglerBin,
1280
+ ["d1", "create", targetDbName, "--json"],
1281
+ { cwd, encoding: "utf8", shell: process.platform === "win32" }
1282
+ );
1283
+ try {
1284
+ const created = JSON.parse(createRes.stdout);
1285
+ if (created.uuid) {
1286
+ d1.database_id = created.uuid;
1287
+ d1.database_name = targetDbName;
1288
+ modified = true;
1289
+ console.log(`\u2705 [qarpeo] Created ${isPreview ? "preview" : "remote"} D1 database: ${created.uuid}`);
1290
+ }
1291
+ } catch {
1292
+ const matchUuid = createRes.stdout.match(/database_id\s*=\s*"([^"]+)"/);
1293
+ if (matchUuid?.[1]) {
1294
+ d1.database_id = matchUuid[1];
1295
+ d1.database_name = targetDbName;
1296
+ modified = true;
1297
+ console.log(`\u2705 [qarpeo] Created ${isPreview ? "preview" : "remote"} D1 database: ${matchUuid[1]}`);
1298
+ }
1299
+ }
1300
+ }
1301
+ }
1302
+ }
1303
+ }
1304
+ if (Array.isArray(config.kv_namespaces) && config.kv_namespaces.length > 0) {
1305
+ const listRes = spawnSync(wranglerBin, ["kv", "namespace", "list", "--json"], {
1306
+ cwd,
1307
+ encoding: "utf8",
1308
+ shell: process.platform === "win32"
1309
+ });
1310
+ let existingKvs = [];
1311
+ try {
1312
+ existingKvs = JSON.parse(listRes.stdout || "[]");
1313
+ } catch {
1314
+ }
1315
+ for (const kv of config.kv_namespaces) {
1316
+ const explicitKvId = isPreview ? process.env.QARPEO_PREVIEW_KV_ID || process.env.PREVIEW_KV_ID : process.env.QARPEO_PROD_KV_ID || process.env.QARPEO_KV_ID || process.env.KV_ID;
1317
+ if (explicitKvId) {
1318
+ console.log(`\u{1F517} [qarpeo] Using explicit ${isPreview ? "preview" : "production"} KV namespace for ${kv.binding}: (${explicitKvId})`);
1319
+ kv.id = explicitKvId;
1320
+ modified = true;
1321
+ continue;
1322
+ }
1323
+ const expectedTitle = isPreview ? `${originalName}-${previewSuffix}-${kv.binding}` : `${originalName}-${kv.binding}`;
1324
+ const isPlaceholder = isPreview || !kv.id || kv.id === "KV_LOCAL_DEV" || kv.id.includes("LOCAL");
1325
+ if (isPlaceholder) {
1326
+ const match = existingKvs.find(
1327
+ (k) => k.title === expectedTitle || k.title === kv.binding
1328
+ );
1329
+ if (match) {
1330
+ console.log(`\u{1F517} [qarpeo] Linked ${isPreview ? "preview" : "remote"} KV namespace: ${expectedTitle} (${match.id})`);
1331
+ kv.id = match.id;
1332
+ modified = true;
1333
+ } else {
1334
+ console.log(`\u{1F528} [qarpeo] Creating ${isPreview ? "preview" : "remote"} KV namespace: ${expectedTitle}...`);
1335
+ const createRes = spawnSync(
1336
+ wranglerBin,
1337
+ ["kv", "namespace", "create", expectedTitle],
1338
+ { cwd, encoding: "utf8", shell: process.platform === "win32" }
1339
+ );
1340
+ const matchId = createRes.stdout.match(/id\s*=\s*"([^"]+)"/);
1341
+ if (matchId?.[1]) {
1342
+ kv.id = matchId[1];
1343
+ modified = true;
1344
+ console.log(`\u2705 [qarpeo] Created ${isPreview ? "preview" : "remote"} KV namespace: ${matchId[1]}`);
1345
+ }
1346
+ }
1347
+ }
1348
+ }
1349
+ }
1350
+ if (Array.isArray(config.r2_buckets) && config.r2_buckets.length > 0) {
1351
+ for (const r2 of config.r2_buckets) {
1352
+ if (r2.bucket_name) {
1353
+ spawnSync(wranglerBin, ["r2", "bucket", "create", r2.bucket_name], {
1354
+ cwd,
1355
+ stdio: "pipe",
1356
+ shell: process.platform === "win32"
1357
+ });
1358
+ }
1359
+ }
1360
+ }
1361
+ if (modified) {
1362
+ writeFileSync(wranglerConfigPath, JSON.stringify(config, null, 2), "utf8");
452
1363
  }
453
1364
  } catch (err) {
454
- console.error(`\u274C [qarpeo] Error running custom seed script: ${err?.message || err}`);
455
- process.exit(1);
1365
+ console.warn(`\u26A0\uFE0F [qarpeo] Auto-provision notice: ${err?.message ?? String(err)}`);
456
1366
  }
457
1367
  }
458
- const count = parseInt(args.count || "10", 10);
459
- const seedNumber = args.seedNumber ? parseInt(args.seedNumber, 10) : void 0;
460
- console.log(`\u{1F331} [qarpeo] Generating mock data with drizzle-seed (${count} rows per table)...`);
461
- try {
462
- await seed(db, schema, {
463
- count,
464
- seed: seedNumber
465
- });
466
- console.log(`\u2705 [qarpeo] Successfully seeded local D1 database: ${sqlitePath}`);
467
- } catch (err) {
468
- console.error(`\u274C [qarpeo] Error during drizzle-seed: ${err?.message || err}`);
469
- process.exit(1);
1368
+ if (args.migrate && !args.dryRun) {
1369
+ try {
1370
+ const candidateMigDirs = [
1371
+ resolve(cwd, "server/db/migrations"),
1372
+ resolve(cwd, "migrations"),
1373
+ resolve(cwd, ".output/server/migrations")
1374
+ ];
1375
+ const migDir = candidateMigDirs.find((d) => existsSync(d));
1376
+ if (migDir && Array.isArray(config.d1_databases) && config.d1_databases.length > 0) {
1377
+ for (const d1 of config.d1_databases) {
1378
+ const hasId = d1.database_id && !d1.database_id.includes("LOCAL");
1379
+ if (hasId && d1.database_name) {
1380
+ console.log(
1381
+ `
1382
+ \u26A1 [qarpeo] Applying D1 migrations for ${d1.database_name} (${isPreview ? "preview" : "remote"})...`
1383
+ );
1384
+ const migArgs = [
1385
+ "d1",
1386
+ "migrations",
1387
+ "apply",
1388
+ d1.database_name,
1389
+ "--remote",
1390
+ "-c",
1391
+ wranglerConfigPath
1392
+ ];
1393
+ spawnSync(wranglerBin, migArgs, {
1394
+ cwd,
1395
+ stdio: "inherit",
1396
+ shell: process.platform === "win32"
1397
+ });
1398
+ }
1399
+ }
1400
+ }
1401
+ } catch {
1402
+ }
1403
+ }
1404
+ if (args.dryRun) {
1405
+ console.log(
1406
+ `
1407
+ \u{1F50D} [qarpeo] Dry-run complete. Validated configuration for ${isPreview ? "PREVIEW" : "PRODUCTION"}.`
1408
+ );
1409
+ console.log(`\u{1F4C1} Target config: ${wranglerConfigPath}`);
1410
+ if (isPreview) {
1411
+ console.log(`\u{1F3F7}\uFE0F Preview Worker: ${config.name}`);
1412
+ }
1413
+ return;
1414
+ }
1415
+ console.log(
1416
+ `
1417
+ \u{1F680} [qarpeo] Deploying ${isPreview ? "PREVIEW" : "PRODUCTION"} to Cloudflare Workers network...`
1418
+ );
1419
+ const deployArgs = ["deploy", "--config", wranglerConfigPath];
1420
+ if (args.env) {
1421
+ deployArgs.push("--env", args.env);
1422
+ }
1423
+ const deployRes = spawnSync(wranglerBin, deployArgs, {
1424
+ cwd,
1425
+ stdio: "inherit",
1426
+ shell: process.platform === "win32"
1427
+ });
1428
+ if (deployRes.status !== 0) {
1429
+ console.error(`
1430
+ \u274C [qarpeo] Deployment failed with exit code ${deployRes.status}.`);
1431
+ process.exit(deployRes.status ?? 1);
1432
+ }
1433
+ if (isPreview) {
1434
+ console.log(`
1435
+ \u{1F389} [qarpeo] Preview deployment successful!`);
1436
+ console.log(`\u{1F3F7}\uFE0F Preview Worker: ${config.name}`);
1437
+ console.log(`\u{1F6E1}\uFE0F Isolated from production traffic and production database.`);
1438
+ } else {
1439
+ console.log(`
1440
+ \u{1F389} [qarpeo] Successfully deployed to Cloudflare Workers production!`);
470
1441
  }
471
1442
  }
472
1443
  });
473
1444
 
474
- const db = defineCommand({
475
- meta: {
476
- name: "db",
477
- description: "Manage Cloudflare D1 database, Drizzle ORM migrations, and seeding"
478
- },
479
- subCommands: {
480
- generate,
481
- migrate,
482
- push,
483
- seed: seedCommand,
484
- clean: cleanCommand,
485
- reset: cleanCommand
486
- }
487
- });
488
-
489
- function loadDotEnv(cwd) {
1445
+ function loadDotEnv$1(cwd) {
490
1446
  const envPath = join(cwd, ".env");
491
1447
  if (!existsSync(envPath)) return;
492
1448
  try {
@@ -527,7 +1483,7 @@ const doctor = defineCommand({
527
1483
  },
528
1484
  async run({ args }) {
529
1485
  const cwd = resolve(process.cwd(), args.cwd);
530
- loadDotEnv(cwd);
1486
+ loadDotEnv$1(cwd);
531
1487
  const isRemote = Boolean(args.remote);
532
1488
  const categories = [];
533
1489
  console.log(`
@@ -1068,18 +2024,193 @@ ${cat.icon} ${cat.title}`);
1068
2024
  }
1069
2025
  });
1070
2026
 
2027
+ function loadDotEnv(cwd) {
2028
+ const envPath = join(cwd, ".env");
2029
+ if (!existsSync(envPath)) return;
2030
+ try {
2031
+ const raw = readFileSync(envPath, "utf8");
2032
+ for (const line of raw.split(/\r?\n/)) {
2033
+ const trimmed = line.trim();
2034
+ if (!trimmed || trimmed.startsWith("#")) continue;
2035
+ const eqIdx = trimmed.indexOf("=");
2036
+ if (eqIdx === -1) continue;
2037
+ const key = trimmed.slice(0, eqIdx).trim();
2038
+ let val = trimmed.slice(eqIdx + 1).trim();
2039
+ if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
2040
+ val = val.slice(1, -1);
2041
+ }
2042
+ if (process.env[key] === void 0) {
2043
+ process.env[key] = val;
2044
+ }
2045
+ }
2046
+ } catch {
2047
+ }
2048
+ }
2049
+ const listCommand = defineCommand({
2050
+ meta: {
2051
+ name: "list",
2052
+ description: "List all deployed Worker services in your Cloudflare account"
2053
+ },
2054
+ args: {
2055
+ json: {
2056
+ type: "boolean",
2057
+ description: "Output in JSON format",
2058
+ default: false
2059
+ },
2060
+ cwd: {
2061
+ type: "string",
2062
+ description: "Working directory",
2063
+ default: "."
2064
+ }
2065
+ },
2066
+ async run({ args }) {
2067
+ const cwd = resolve(process.cwd(), args.cwd);
2068
+ loadDotEnv(cwd);
2069
+ const auth = await getCloudflareAuth(cwd);
2070
+ if (!auth) {
2071
+ console.error("\n\u274C [qarpeo] Not authenticated with Cloudflare.");
2072
+ console.error(" Run `qp login` to authenticate or set CLOUDFLARE_API_TOKEN in .env\n");
2073
+ process.exit(1);
2074
+ }
2075
+ console.log("\u{1F50D} [qarpeo] Fetching deployed Workers from Cloudflare...\n");
2076
+ try {
2077
+ const workers = await listCloudflareWorkers(auth);
2078
+ if (args.json) {
2079
+ console.log(JSON.stringify(workers, null, 2));
2080
+ return;
2081
+ }
2082
+ if (workers.length === 0) {
2083
+ console.log("\u2139\uFE0F No Workers found in this Cloudflare account.\n");
2084
+ return;
2085
+ }
2086
+ const tableData = workers.map((w) => ({
2087
+ "Worker Name": w.id,
2088
+ "Created": w.created_on ? w.created_on.slice(0, 19).replace("T", " ") : "-",
2089
+ "Last Modified": w.modified_on ? w.modified_on.slice(0, 19).replace("T", " ") : "-",
2090
+ "Assets": w.has_assets ? "Yes" : "No"
2091
+ }));
2092
+ console.table(tableData);
2093
+ console.log(`
2094
+ \u{1F4E6} Total Workers: ${workers.length}`);
2095
+ console.log("\u{1F4A1} Tip: Run `qp delete <worker-name>` or simply `qp delete` to interactively select and delete.\n");
2096
+ } catch (err) {
2097
+ console.error(`
2098
+ \u274C [qarpeo] ${err?.message || err}
2099
+ `);
2100
+ process.exit(1);
2101
+ }
2102
+ }
2103
+ });
2104
+
2105
+ function getWranglerBin() {
2106
+ return resolveBinaryPath("wrangler") || (process.platform === "win32" ? "wrangler.cmd" : "wrangler");
2107
+ }
2108
+ const login = defineCommand({
2109
+ meta: {
2110
+ name: "login",
2111
+ description: "Authenticate with Cloudflare via browser OAuth (powered by Wrangler)"
2112
+ },
2113
+ args: {},
2114
+ async run() {
2115
+ console.log("\u{1F510} [qarpeo] Opening browser to authenticate with Cloudflare...");
2116
+ console.log(
2117
+ " After login, your credentials will be stored in ~/.wrangler/config/\n"
2118
+ );
2119
+ await ensurePackage("wrangler", {
2120
+ purpose: "authenticating with Cloudflare"
2121
+ });
2122
+ const wrangler = getWranglerBin();
2123
+ const result = spawnSync(wrangler, ["login"], {
2124
+ stdio: "inherit",
2125
+ env: process.env,
2126
+ shell: process.platform === "win32"
2127
+ });
2128
+ if (result.status !== 0) {
2129
+ console.error(
2130
+ "\n\u274C [qarpeo] Login failed. Please try again or check your network connection."
2131
+ );
2132
+ process.exit(result.status ?? 1);
2133
+ }
2134
+ console.log("\n\u2705 [qarpeo] Successfully authenticated with Cloudflare!");
2135
+ console.log(" Run `qp whoami` to verify your account.\n");
2136
+ }
2137
+ });
2138
+ const logout = defineCommand({
2139
+ meta: {
2140
+ name: "logout",
2141
+ description: "Log out of Cloudflare and revoke OAuth credentials"
2142
+ },
2143
+ args: {},
2144
+ async run() {
2145
+ console.log("\u{1F513} [qarpeo] Logging out of Cloudflare...");
2146
+ await ensurePackage("wrangler", {
2147
+ purpose: "logging out of Cloudflare"
2148
+ });
2149
+ const wrangler = getWranglerBin();
2150
+ const result = spawnSync(wrangler, ["logout"], {
2151
+ stdio: "inherit",
2152
+ env: process.env,
2153
+ shell: process.platform === "win32"
2154
+ });
2155
+ if (result.status !== 0) {
2156
+ console.error(
2157
+ "\n\u274C [qarpeo] Logout failed. You may not have been logged in."
2158
+ );
2159
+ process.exit(result.status ?? 1);
2160
+ }
2161
+ console.log("\n\u2705 [qarpeo] Successfully logged out of Cloudflare.");
2162
+ console.log(
2163
+ " To re-authenticate, run `qp login` or set CLOUDFLARE_API_TOKEN in .env\n"
2164
+ );
2165
+ }
2166
+ });
2167
+ const whoami = defineCommand({
2168
+ meta: {
2169
+ name: "whoami",
2170
+ description: "Show the currently authenticated Cloudflare account"
2171
+ },
2172
+ args: {},
2173
+ async run() {
2174
+ await ensurePackage("wrangler", {
2175
+ purpose: "checking Cloudflare account status"
2176
+ });
2177
+ const wrangler = getWranglerBin();
2178
+ const result = spawnSync(wrangler, ["whoami"], {
2179
+ stdio: "inherit",
2180
+ env: process.env,
2181
+ shell: process.platform === "win32"
2182
+ });
2183
+ if (result.status !== 0) {
2184
+ console.error(
2185
+ "\n\u274C [qarpeo] Not authenticated. Run `qp login` or set CLOUDFLARE_API_TOKEN in .env\n"
2186
+ );
2187
+ process.exit(result.status ?? 1);
2188
+ }
2189
+ }
2190
+ });
2191
+
1071
2192
  const main = defineCommand({
1072
2193
  meta: {
1073
2194
  name: "qp",
1074
- version: "0.1.10",
2195
+ version: "0.1.11",
1075
2196
  description: "Cloudflare-native powerhouse module for Nuxt"
1076
2197
  },
1077
2198
  subCommands: {
2199
+ d1: db,
1078
2200
  db,
2201
+ delete: deleteCommand,
2202
+ deploy,
2203
+ destroy: deleteCommand,
1079
2204
  doctor,
1080
2205
  generate,
2206
+ list: listCommand,
2207
+ login,
2208
+ logout,
2209
+ ls: listCommand,
1081
2210
  migrate,
1082
- push
2211
+ push,
2212
+ whoami,
2213
+ workers: listCommand
1083
2214
  }
1084
2215
  });
1085
2216
  void runMain(main);