-
-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathModule.cfc
More file actions
8032 lines (7289 loc) · 303 KB
/
Copy pathModule.cfc
File metadata and controls
8032 lines (7289 loc) · 303 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Wheels CLI Module for LuCLI
*
* Provides code generation, migrations, testing, and server management
* for Wheels applications. Each public function is a subcommand:
*
* wheels new myapp
* wheels create app myapp --port=3000
* wheels generate model User name email
* wheels migrate latest
* wheels test --filter=models
* wheels start
*
* hint: Wheels framework CLI - create, generate, migrate, test, and manage your app
*/
component extends="modules.BaseModule" {
function init(
boolean verboseEnabled = false,
boolean timingEnabled = false,
string cwd = "",
any timer = nullValue(),
struct moduleConfig = {}
) {
super.init(argumentCollection = arguments);
// Normalize cwd to forward slashes. Lucee 7 on Windows fails to
// distinguish a drive-letter path (e.g. `C:\Users\cy/blog`, where
// the backslash came from `user.dir` and the forward slash from
// `cwd & "/" & appName`) from a URI like `http:/...`. The mixed-
// slash form trips ResourceUtil's scheme-detection regex, which
// extracts "c" as the scheme and throws "no Resource provider
// available with the name [c]" before any module code runs. All-
// forward-slash paths are accepted by both Lucee and the JDK on
// every platform, so we normalize once here and again on every
// canonical-path concatenation downstream.
variables.cwd = $normalizePath(variables.cwd);
// Resolve project root (where lucee.json / vendor/wheels lives)
variables.projectRoot = resolveProjectRoot(variables.cwd);
// Module root for template resolution
variables.moduleRoot = $normalizePath(getDirectoryFromPath(getCurrentTemplatePath()));
// Lazy-init service instances
variables.services = {};
return this;
}
/**
* Bootstrap-safe wrapper around `Helpers.normalizePath()` — the single
* source of truth for path normalisation (GH #2841). Collapses Windows
* backslashes to forward slashes so a mixed-slash path like
* `C:\Users\cy/blog` can't trip Lucee's Resource API into reading `c:`
* as a URI scheme (see init() comment).
*
* Helpers is instantiated directly rather than via `getService()`
* because `$normalizePath()` runs inside `init()` before
* `variables.services` exists. Helpers is a dependency-free leaf
* utility, so constructing it at bootstrap is cheap and safe.
*/
private string function $normalizePath(required string p) {
return new services.Helpers().normalizePath(arguments.p);
}
/**
* Java-backed directoryExists() — bypasses Lucee's path resolver so
* paths starting with a Windows drive letter (`C:\…`) never reach
* ResourceUtil's scheme detection. The defensive `try/catch` honors
* Lucee's built-in first (in case mappings or symlinks matter) and
* only falls back to `java.io.File.isDirectory()` when Lucee throws.
*
* Use this in any path-existence check that runs early in `wheels
* new` (before the framework source is located) or in any code that
* constructs paths from `variables.cwd` / `File.getCanonicalPath()`.
*/
private boolean function $safeDirExists(required string p) {
try {
return directoryExists(arguments.p);
} catch (any e) {
return createObject("java", "java.io.File").init(arguments.p).isDirectory();
}
}
/**
* Source the structured argument collection LuCLI handed this command.
*
* LuCLI parses the command line once and invokes the subcommand as
* `module.cmd(argumentCollection = argsMap)`, so the function's `arguments`
* scope already IS the structured map (positionals as `arg1..argN`, named
* options as `key=value`, and `--no-X` normalized to `key=false`). Commands
* migrated to ArgSpec consume that directly — no flatten to argv, no
* re-parse, no lossy `false` round trip (the #2855 root cause, see #2861).
*
* The fallback covers direct invocation where a caller stashed a raw argv
* array in the instance-level `__arguments` (internal delegation such as
* `create` → `new`, and unit tests). That array is reconstructed into the
* same structured shape LuCLI would have produced, so a command behaves
* identically whether LuCLI dispatched it or another command delegated to it.
*
* `__arguments` is consume-once: it is cleared on every call so a stale
* stash can never replay. One-shot CLI runs hid the leak, but the stdio
* MCP server (`wheels mcp wheels`) is a persistent process — after any
* delegating call (create/generate app → new) a later zero-arg tool call
* (e.g. wheels_test()) would otherwise re-parse the stale argv and turn
* into a completely different invocation.
*/
private struct function structuredArgs(struct callerArgs = {}) {
var raw = __arguments ?: [];
__arguments = [];
if (!structIsEmpty(arguments.callerArgs)) {
return arguments.callerArgs;
}
return argvToCollection(isArray(raw) ? raw : []);
}
/**
* Reconstruct LuCLI's structured argCollection from a raw argv array.
*
* Mirrors LuCLI's own `parseArguments()` normalization so the fallback path
* is indistinguishable from a live dispatch: `--no-X` → `X=false`, bare
* `--X` → `X=true`, `--key=value` → `key=value` (leading dashes stripped),
* and bare tokens → `arg<n>` keyed by their global position (a flag between
* two positionals leaves a numbering gap, exactly as LuCLI produces).
*/
private struct function argvToCollection(required array argv) {
var coll = {};
var count = 0;
for (var raw in arguments.argv) {
count++;
if (left(raw, 5) == "--no-" && !find("=", raw) && len(raw) > 5) {
coll[mid(raw, 6, len(raw))] = "false";
} else if (left(raw, 2) == "--" && !find("=", raw) && len(raw) > 2) {
coll[mid(raw, 3, len(raw))] = "true";
} else {
var eq = find("=", raw);
if (eq > 1) {
var key = trim(left(raw, eq - 1));
if (left(key, 2) == "--") {
key = mid(key, 3, len(key));
} else if (left(key, 1) == "-") {
key = mid(key, 2, len(key));
}
coll[key] = mid(raw, eq + 1, len(raw));
} else {
coll["arg" & count] = raw;
}
}
}
return coll;
}
// ─────────────────────────────────────────────────
// MCP framework convention — hide CLI-only commands
// ─────────────────────────────────────────────────
/**
* hint: Declare public functions to hide from MCP tools/list.
*
* These remain reachable as CLI subcommands. Hidden because they are
* stateful (start/stop), destructive (new scaffolds a whole project),
* interactive (console), meta (mcp), alias (d), or don't translate to
* single-call MCP semantics (browser). Read by LuCLI >= 0.3.4 per the
* mcpHiddenTools() convention.
*
* Defense-in-depth (#2963 / wave-2 §5.2): every public function whose
* name starts with `$` is appended structurally via `getMetaData(this)`.
* These are the "public for specs" carve-out helpers documented in
* cli/CLAUDE.md — kept public only so TestBox can reach them — and must
* never appear in MCP `tools/list`. Without this structural sweep, a
* future `$publicHelperFour` added without a denylist update would leak
* as a callable tool. The literal `$normalizeTestFilter` /
* `$resolveAppTestDataSource` entries below are retained for clarity
* and the case where LuCLI consults the list before metadata is fully
* populated; the structural pass de-duplicates and catches additions.
*/
public array function mcpHiddenTools() {
var hidden = [
"main", // bare `wheels` no-args dispatch target — not an MCP tool
"mcp", // meta command — prints MCP setup instructions
"d", // alias for destroy
"g", // alias for generate
"new", // scaffolds a whole new Wheels project
"console", // interactive CFML REPL — not usable over stdio
"start", // dev server lifecycle (stateful)
"stop", // dev server lifecycle (stateful)
"browser", // multi-step browser testing flow
"jobs", // `jobs work` is a long-lived poll loop — no single-call MCP semantics (like start/stop)
"mcpToolSpecs", // per-tool inputSchema registry read by LuCLI — not itself a tool
// $-prefixed internal helpers. Public ONLY so TestCommandSpec can
// unit-test them directly (the cli/CLAUDE.md "public for specs"
// carve-out) — they are not commands and must never surface as MCP
// tools. LuCLI matches these case-insensitively (McpCommand lowercases
// both the entry and the discovered function name).
"$normalizeTestFilter",
"$resolveAppTestDataSource"
];
// Structural sweep — discover every $-prefixed PUBLIC function on
// this module via getMetaData(this).functions and add anything not
// already listed. Defense-in-depth so a future $-helper added without
// a denylist update can't accidentally leak as an MCP tool.
try {
var meta = getMetaData(this);
if (structKeyExists(meta, "functions") && isArray(meta.functions)) {
for (var fn in meta.functions) {
if (
structKeyExists(fn, "name")
&& structKeyExists(fn, "access")
&& fn.access == "public"
&& left(fn.name, 1) == "$"
&& !arrayContainsNoCase(hidden, fn.name)
) {
arrayAppend(hidden, fn.name);
}
}
}
} catch (any e) {
// Reflection failure: fall through to the literal denylist.
// The hard-coded $-entries above still cover the two known cases.
}
return hidden;
}
/**
* MCP tool input schemas, keyed by tool name. Read by LuCLI's MCP server
* per the same optional-convention mechanism as mcpHiddenTools(), so the
* stdio `tools/list` advertisement carries a populated inputSchema.
*
* Why this exists (#2963): Module command functions declare no formal
* parameters — they consume LuCLI's structured argCollection — so the
* runtime's signature-derived schema is `{properties: {}}` with
* `additionalProperties: false`, which tells MCP clients the tools take
* no arguments at all. Each entry below is built from the SAME ArgSpec
* builder the command's parse helper uses, so the CLI parse surface and
* the MCP advertisement cannot drift.
*
* Commands still on hand-rolled token parsing (generate, migrate, db,
* deploy, routes, info, reload, validate, create — tracked by #2861)
* gain entries here as they migrate to ArgSpec.
*/
public struct function mcpToolSpecs() {
return {
"analyze" = analyzeArgSpec().toInputSchema(),
"destroy" = destroyArgSpec().toInputSchema(),
"doctor" = verboseFlagSpec().toInputSchema(),
"notes" = notesArgSpec().toInputSchema(),
"seed" = seedArgSpec().toInputSchema(),
"stats" = verboseFlagSpec().toInputSchema(),
"test" = testArgSpec().toInputSchema(),
"upgrade" = upgradeArgSpec().toInputSchema()
};
}
// ─────────────────────────────────────────────────
// ArgSpec builders — one per command, shared by the
// command's parse helper and mcpToolSpecs() so the
// CLI parse surface and the MCP tools/list schema
// cannot drift (#2963). Descriptions flow into the
// schema via ArgSpec.toInputSchema().
// ─────────────────────────────────────────────────
private any function seedArgSpec() {
return new services.ArgSpec()
.option(name = "environment", default = "", description = "Environment whose seed files run (defaults to the app's current environment)")
.option(name = "mode", default = "auto", description = "Seeding mode: auto (detect), convention (app/db/seeds.cfm), or generate (random test data)")
.flag(name = "generate", default = false, description = "Shorthand for --mode=generate");
}
private any function testArgSpec() {
return new services.ArgSpec()
.option(name = "filter", default = "", description = "Spec filter — a dotted directory or bundle path (e.g. tests.specs.models)")
.option(name = "directory", default = "", description = "Documented alias for --filter")
.option(name = "reporter", default = "simple", description = "Output format: simple, json, or tap")
.option(name = "db", default = "sqlite", description = "Database the suite runs against")
.option(name = "base-path", default = "", description = "URL prefix the app is mounted under (e.g. /myapp). Auto-derived from WHEELS_SUBPATH or set(subpath=...) when omitted.")
.flag(name = "verbose", default = false, description = "Print per-spec detail instead of the summary rollup")
.flag(name = "ci", default = false, description = "CI mode output")
.flag(name = "core", default = false, description = "Run the framework core suite (vendor/wheels/tests) instead of the app suite")
.flag(name = "test-db", default = true, description = "Swap to the dedicated test datasource for the run (disable with --no-test-db)");
}
private any function analyzeArgSpec() {
return new services.ArgSpec()
.positional(name = "target", default = "all", description = "Analysis target (default: all)");
}
private any function destroyArgSpec() {
return new services.ArgSpec()
.positional(name = "type", default = "", description = "What to remove: resource, model, controller, or view")
.positional(name = "name", default = "", description = "Name of the artifact to remove")
.flag(name = "force", default = false, description = "Skip the confirmation prompt");
}
private any function verboseFlagSpec() {
return new services.ArgSpec()
.flag(name = "verbose", default = false, description = "Print detailed output");
}
private any function notesArgSpec() {
return new services.ArgSpec()
.option(name = "annotations", default = "TODO,FIXME,OPTIMIZE", description = "Comma-delimited annotation markers to scan for")
.option(name = "custom", default = "", description = "Additional custom annotation markers (comma-delimited)");
}
private any function upgradeArgSpec() {
return new services.ArgSpec()
.positional(name = "subcommand", default = "", description = "Explicit verb required: `check` scans for breaking changes (read-only); `apply` swaps vendor/wheels/ with the CLI's bundled framework (backup first). Omitted/empty prints usage and never modifies files")
.option(name = "to", default = "", description = "Target Wheels version. check: version to scan against (default: latest). apply: must match the CLI's bundled framework version")
.option(name = "format", default = "", description = "check only: set to json for machine-readable output")
.flag(name = "strict", default = false, description = "check only: escalate advisory findings to a hard failure (non-zero exit) so CI can gate on them")
.flag(name = "nobackup", default = false, description = "apply only: skip the vendor/wheels.bak-<timestamp> backup of the existing framework");
}
private any function jobsArgSpec() {
return new services.ArgSpec()
.positional(name = "action", default = "status", description = "work (long-lived worker loop) or status (queue snapshot). Defaults to status")
.option(name = "queue", default = "", description = "work: comma-delimited queue names to process in order. status: single queue to filter by. Empty = all queues")
.option(name = "interval", default = 5, type = "numeric", description = "work only: seconds to wait between polls when no job is available")
.option(name = "max-jobs", default = 0, type = "numeric", description = "work only: stop after this many jobs (successes + failures count). 0 = run until stopped")
.flag(name = "quiet", default = false, description = "work only: suppress per-job completion output, only print failures")
.option(name = "format", default = "table", description = "status only: output format, table or json");
}
// ─────────────────────────────────────────────────
// version / help — banner + command listing
// ─────────────────────────────────────────────────
// Emits the three-line `wheels --version` format the installation guide
// documents (Wheels Module + LuCLI runtime + JVM). See
// web/sites/guides/.../command-line-tools/installation.mdx for the
// canonical output shape; issue #2431 tracked the prior banner output
// drifting from the doc.
/**
* hint: Show Wheels Module, LuCLI runtime, and JVM versions
*/
public string function version() {
var nl = chr(10);
var moduleVersion = super.version();
var channel = new services.ReleaseChannel().classify(moduleVersion);
var channelTag = len(channel) ? " (" & channel & ")" : "";
var lines = ["Wheels " & moduleVersion & channelTag];
var lucliVersion = $detectLucliVersion();
if (len(lucliVersion)) {
arrayAppend(lines, "LuCLI " & lucliVersion);
}
var javaVersion = $detectJavaVersion();
if (len(javaVersion)) {
arrayAppend(lines, "Java " & javaVersion);
}
return arrayToList(lines, nl);
}
private string function $detectLucliVersion() {
try {
var sys = createObject("java", "java.lang.System");
var v = sys.getProperty("lucli.version");
if (!isNull(v) && len(v)) {
return v;
}
v = sys.getenv("LUCLI_VERSION");
if (!isNull(v) && len(v)) {
return v;
}
} catch (any e) {
// fall through
}
return "";
}
private string function $detectJavaVersion() {
try {
var sys = createObject("java", "java.lang.System");
var v = sys.getProperty("java.version");
if (!isNull(v) && len(v)) {
return v;
}
} catch (any e) {
// fall through
}
return "";
}
// LuCLI dispatches a bare `wheels` invocation (no subcommand) to a
// `main()` function on the module. Without it, picocli surfaces:
// Component [modules.wheels.Module] has no function with name [main]
// Delegate to showHelp() so the no-args entry point lands on something useful.
/**
* hint: No-args dispatch target — delegates to showHelp()
*/
public string function main() {
return showHelp();
}
// Hand-written replacement for BaseModule's auto-discovered help. Grouped by
// task instead of alphabetical, mirrors what `wheels --help` emits from the
// wrapper. `wheels help` and `wheels --help` (rewritten by LuCLI's
// preprocessModuleHelp) both reach this.
/**
* hint: Show this help
*/
public string function showHelp() {
var nl = chr(10);
// Per-subcommand help. LuCLI (>= bpamiri/LuCLI#5) forwards
// `wheels <cmd> --help` as `showHelp <cmd>`, which arrives as the raw
// __arguments argv (`arg1`) — the same dispatch every other command uses.
// Read `arg1` first; fall back to the CFML positional key "1" so a direct
// function invocation (showHelp("migrate")) also resolves it. Unknown
// commands fall through to the global listing below (also the bare
// `wheels help` / `wheels --help` path, where there is no subcommand).
var coll = structuredArgs(arguments);
var sub = coll.arg1 ?: (coll["1"] ?: "");
if (len(sub)) {
var cmdHelp = $commandHelp(sub);
if (len(cmdHelp)) {
return cmdHelp;
}
}
var v = super.version();
var help = "Wheels CLI " & v & nl;
help &= " CFML MVC framework — code generation, migrations, testing, server management" & nl & nl;
help &= "Usage:" & nl;
help &= " wheels <command> [options]" & nl & nl;
help &= "Getting Started:" & nl;
help &= " new <name> Scaffold a new Wheels application" & nl;
help &= " create app <name> Alias for new — scaffold a new Wheels application" & nl;
help &= " start Start the dev server" & nl;
help &= " stop Stop the dev server" & nl;
help &= " reload Reload the running app" & nl & nl;
help &= "Code Generation:" & nl;
help &= " generate Generate model, controller, scaffold, migration, etc." & nl;
help &= " destroy (or d) Remove generated files" & nl & nl;
help &= "Database:" & nl;
help &= " migrate Run database migrations (latest, up, down, info, doctor, forget, pretend, rename-system-tables)" & nl;
help &= " seed Run database seeds" & nl;
help &= " db Database management (reset, status, version)" & nl & nl;
help &= "Background Jobs:" & nl;
help &= " jobs Job queue worker and stats (work, status)" & nl & nl;
help &= "Testing & Inspection:" & nl;
help &= " test Run the test suite" & nl;
help &= " browser Browser-based tests (Playwright)" & nl;
help &= " console Open an interactive CFML REPL connected to your app" & nl;
help &= " routes Print the route table" & nl;
help &= " info Show framework version, environment, configuration" & nl;
help &= " doctor Diagnose project setup issues" & nl;
help &= " validate Validate project structure and configuration" & nl;
help &= " analyze Static analysis of project code" & nl;
help &= " stats Project statistics (lines of code, model counts, etc.)" & nl;
help &= " notes Find TODO / FIXME / OPTIMIZE comments (--annotations to customize)" & nl & nl;
help &= "Packages & Deployment:" & nl;
help &= " packages Add, update, search Wheels packages (verb is `add`, not `install`)" & nl;
help &= " upgrade Upgrade the Wheels framework in your app (vendor/wheels/); `check` scans, `apply` swaps" & nl;
help &= " deploy Deploy your app (Kamal-compatible)" & nl & nl;
help &= "Other:" & nl;
help &= " mcp Configure Wheels MCP server for AI assistants" & nl;
help &= " version Show Wheels CLI version" & nl;
help &= " help Show this help" & nl & nl;
help &= "For command-specific help: wheels <command> --help" & nl & nl;
help &= "More info: https://guides.wheels.dev";
return help;
}
/**
* Render per-command help for `wheels <cmd> --help` from the command function's
* metadata hint. Returns "" for an unknown command so showHelp() falls back to
* the global listing. Private so it isn't exposed as an MCP tool.
*/
private string function $commandHelp(required string subcommand) {
var nl = chr(10);
// Resolve aliases to the implementing function.
var fnName = lCase(trim(arguments.subcommand));
if (fnName == "g") { fnName = "generate"; }
if (fnName == "d") { fnName = "destroy"; }
var hint = "";
var meta = getMetaData(this);
for (var fn in (meta.functions ?: [])) {
if (lCase(fn.name ?: "") == fnName && (fn.access ?: "public") == "public") {
hint = trim(fn.hint ?: "");
// The `/** hint: ... */` convention surfaces the value with the
// literal "hint:" key prefix on Lucee — strip it for clean output.
hint = trim(reReplaceNoCase(hint, "^hint\s*:\s*", ""));
break;
}
}
if (!len(hint)) {
return "";
}
var help = "wheels " & lCase(trim(arguments.subcommand)) & nl & nl;
help &= " " & hint & nl & nl;
help &= "Run 'wheels help' for the full command list." & nl;
help &= "More info: https://guides.wheels.dev";
return help;
}
// ─────────────────────────────────────────────────
// generate — Code generation
// ─────────────────────────────────────────────────
/**
* hint: Generate Wheels components (model, controller, view, migration, scaffold, route, test, property, api-resource, helper, snippets)
*/
public string function generate() {
var args = new services.ArgSpec().toArgv(structuredArgs(arguments));
if (!arrayLen(args)) {
out("Usage: wheels generate <type> <name> [attributes...]", "yellow");
out("");
out("Types:", "bold");
out(" app Create a new Wheels application (alias for 'wheels new')");
out(" model Generate a model CFC");
out(" controller Generate a controller CFC");
out(" view Generate a view template");
out(" migration Generate a database migration");
out(" scaffold Generate model + controller + views + migration + tests + routes");
out(" api-resource Generate API-only model + controller + migration + tests + routes (no views)");
out(" route Add a resource route to config/routes.cfm");
out(" test Generate a test spec file");
out(" property Generate an add-column migration for a model property");
out(" helper Generate a helper file in app/helpers/");
out(" snippets Generate common code pattern snippets (auth, soft-delete, api, etc.)");
out(" admin Generate admin CRUD interface for an existing model");
out("");
out("Examples:", "bold");
out(" wheels generate app myapp");
out(" wheels generate model User name email:string active:boolean");
out(" wheels generate controller Users index show create");
out(" wheels generate migration CreateUsers");
out(" wheels generate scaffold Post title body:text publishedAt:datetime");
out(" wheels generate api-resource Product name price:decimal sku:string");
out(" wheels generate route posts");
out(" wheels generate test model User");
out(" wheels generate property User email:string");
out(" wheels generate helper formatting");
out(" wheels generate snippets auth");
out(" wheels generate admin User");
return "";
}
var type = args[1];
var remaining = args.len() > 1 ? args.slice(2) : [];
switch (lCase(type)) {
case "app":
case "a":
// Delegate to wheels new — pass remaining args as __arguments
__arguments = remaining;
return new();
case "model":
case "m":
return generateModel(remaining);
case "controller":
case "c":
return generateController(remaining);
case "view":
case "v":
return generateView(remaining);
case "migration":
case "migrate":
return generateMigration(remaining);
case "scaffold":
case "s":
return generateScaffold(remaining);
case "api-resource":
case "api":
return generateApiResource(remaining);
case "route":
case "r":
return generateRoute(remaining);
case "test":
return generateTest(remaining);
case "property":
case "prop":
return generateProperty(remaining);
case "helper":
case "h":
return generateHelper(remaining);
case "snippets":
return generateSnippets(remaining);
case "admin":
return generateAdmin(remaining);
default:
out("Unknown generator type: #type#", "red");
out("Run 'wheels generate' for available types.");
// throw maps to non-zero exit; return "" would silently succeed.
throw(type = "Wheels.InvalidArguments", message = "Unknown generator type: #type#");
}
}
// ─────────────────────────────────────────────────
// migrate — Database migration management
// ─────────────────────────────────────────────────
/**
* hint: Run database migrations (latest, up, down, info, doctor, forget, pretend, rename-system-tables)
*/
public string function migrate() {
var args = new services.ArgSpec().toArgv(structuredArgs(arguments));
var action = arrayLen(args) ? lCase(args[1]) : "latest";
switch (action) {
case "latest":
case "up":
case "down":
case "info":
try {
return runMigration(action);
} catch (MigrationError e) {
out("Migration failed: #e.message#", "red");
// rethrow maps to non-zero exit; return "" would silently succeed.
rethrow;
}
case "doctor":
try {
return runMigration("doctor");
} catch (MigrationError e) {
out("Doctor failed: #e.message#", "red");
rethrow;
}
case "forget":
return runForgetOrPretend("forgetVersion", args);
case "pretend":
return runForgetOrPretend("pretendVersion", args);
case "rename-system-tables":
// F15 Phase 2: opt-in one-shot rename of legacy c_o_r_e_*
// system tables to wheels_*. Idempotent (no-op when nothing
// to rename); refuses to run on a partial-rename state.
var dryRun = false;
for (var i = 2; i <= arrayLen(args); i++) {
if (args[i] == "--dry-run") dryRun = true;
}
try {
return runRenameSystemTables(dryRun);
} catch (MigrationError e) {
out("Rename failed: #e.message#", "red");
rethrow;
}
default:
out("Unknown migration action: #action#", "red");
out("Usage: wheels migrate [latest|up|down|info|doctor|forget|pretend|rename-system-tables]");
throw(type = "Wheels.InvalidArguments", message = "Unknown migration action: #action#");
}
}
// ─────────────────────────────────────────────────
// seed — Database seeding
// ─────────────────────────────────────────────────
/**
* Parse `wheels seed` arguments. All options are named (no positional), so
* before the ArgSpec migration the legacy getArgs() arg1-gate dropped them
* entirely — `wheels seed --environment=production` silently ran with
* defaults. ArgSpec consumes the named keys directly. `--generate` is a
* shorthand for `--mode=generate`.
*/
private struct function parseSeedArgs(required struct coll) {
var parsed = seedArgSpec().parse(arguments.coll);
return {
environment = parsed.environment,
mode = parsed.generate ? "generate" : parsed.mode
};
}
/**
* hint: Run database seeds (convention-based or generated)
*/
public string function seed() {
var opts = parseSeedArgs(structuredArgs(arguments));
return runSeed(opts.mode, opts.environment);
}
// ─────────────────────────────────────────────────
// test — Run test suite
// ─────────────────────────────────────────────────
/**
* Parse `wheels test` arguments. `--filter` and its `--directory` alias set
* the spec filter; `--reporter` and `--db` are options (`--db` is also tracked
* as explicit so the runner can tell an implicit default from a chosen one);
* `--verbose`/`--ci`/`--core` are flags; `--no-test-db` (test-db=false) maps to
* useTestDB. A bare positional is the filter, and `-v` arrives as a positional
* (LuCLI only normalizes --x/--no-x) and toggles verbose. The space-separated
* option forms (`--filter x`) are dropped for `--filter=x` — LuCLI delivers the
* space form as a bare flag + a separate positional, not a named value (#2861).
*/
private struct function parseTestArgs(required struct coll) {
var parsed = testArgSpec().parse(arguments.coll);
// `--directory` is a documented alias for `--filter` (tutorial ch. 7).
var filter = len(parsed.directory) ? parsed.directory : parsed.filter;
// Walk positionals in LuCLI's global-index order: `-v` is the short
// verbose flag (delivered as a positional, not normalized), and the
// first remaining bare token is the filter when no --filter/--directory
// option was supplied.
var verbose = parsed.verbose;
var indices = [];
for (var key in arguments.coll) {
if (reFindNoCase("^arg\d+$", key)) {
arrayAppend(indices, val(mid(key, 4, len(key))));
}
}
arraySort(indices, "numeric");
for (var idx in indices) {
var token = trim(arguments.coll["arg" & idx]);
if (token == "-v") {
verbose = true;
} else if (len(token) && left(token, 2) != "--" && !len(filter)) {
filter = token;
}
}
return {
filter = filter,
reporter = parsed.reporter,
format = "json",
verbose = verbose,
ci = parsed.ci,
core = parsed.core,
db = parsed.db,
dbExplicit = structKeyExists(arguments.coll, "db"),
useTestDB = parsed["test-db"],
basePath = parsed["base-path"]
};
}
/**
* hint: Run test suite with optional filter and reporter
*/
public string function test() {
var opts = parseTestArgs(structuredArgs(arguments));
var filter = opts.filter;
var reporter = opts.reporter;
var format = opts.format;
var verboseOutput = opts.verbose;
var ciMode = opts.ci;
var coreTests = opts.core;
var db = opts.db;
var dbExplicit = opts.dbExplicit;
var useTestDB = opts.useTestDB;
var basePath = opts.basePath;
// Default to APP mode unless --core is set explicitly. The previous
// auto-detection ("if vendor/wheels/tests/ exists, default to core")
// always picked core mode for user apps because every Wheels app has
// the framework's tests vendored at vendor/wheels/tests/. That meant
// `wheels test` from a user's app pointed at framework specs instead
// of the user's own tests/specs/, producing "0 passed" silently with
// no spec discovery.
// Normalize short filter names to dotted paths the test runner
// accepts. The app-runner regex (`^tests(\.[a-zA-Z0-9_]+)*$`) and
// core-runner regex (`^(wheels\.tests|vendor\.<pkg>\.tests)...$`)
// both reject bare names like "browser" or "models" and silently
// fall back to the default scope, running the entire suite. The
// CLI normalizes here so `--filter=browser` does what the user
// expects. Onboarding finding #2.
filter = $normalizeTestFilter(filter, coreTests);
return runTests(filter, reporter, format, verboseOutput, coreTests, db, ciMode, useTestDB, dbExplicit, basePath);
}
/**
* Normalize a short filter name to a path the test runner's directory
* regex will accept. App mode prepends `tests.specs.`; core mode
* prepends `wheels.tests.specs.`. Already-qualified inputs pass through
* unchanged. Empty input stays empty (server applies its default).
*
* Examples:
* "" → "" (default scope)
* "browser" → "tests.specs.browser" (app mode)
* "browser" → "wheels.tests.specs.browser" (core mode)
* "tests.specs.browser" → "tests.specs.browser"
* "wheels.tests.specs.model" → "wheels.tests.specs.model"
* "vendor.wheels-sentry.tests" → "vendor.wheels-sentry.tests"
*/
public string function $normalizeTestFilter(
required string filter,
boolean coreTests = false
) {
var f = trim(arguments.filter);
if (!len(f)) return "";
if (arguments.coreTests) {
// Core runner accepts wheels.tests.* or vendor.<pkg>.tests.*
if (reFindNoCase("^(wheels\.tests|vendor\.[a-z0-9][a-z0-9\-]*\.tests)(\.[a-zA-Z0-9_]+)*$", f)) {
return f;
}
return "wheels.tests.specs." & f;
}
// App runner accepts tests.* (and treats `tests` alone as a valid root)
if (reFindNoCase("^tests(\.[a-zA-Z0-9_]+)*$", f)) {
return f;
}
return "tests.specs." & f;
}
// ─────────────────────────────────────────────────
// reload — Reload application
// ─────────────────────────────────────────────────
/**
* hint: Reload the running Wheels application. The reload password
* gates the HTTP `?reload=true` endpoint against remote attackers;
* the CLI reads it from `.env` or `config/settings.cfm` and forwards
* it because it runs locally with filesystem access. This matches
* how Rails, Laravel, Symfony, etc. treat CLI-vs-HTTP — the CLI is
* already trusted at the same level as the project on disk. See
* issue #2477 and `deployment/security-hardening.mdx`.
*/
public string function reload() {
// Write-side guard: reload mutates the running app's state, so it must
// target the server bound to THIS project — never a sibling app squatting
// a common port. Without lucee.json/.env port config we refuse the
// common-port fallback and error loudly.
var serverPort = $requireRunningServer(
hints = [
"Reload requires a running server bound to this project.",
"Set 'port' in lucee.json (or PORT in .env), then start with: wheels start"
],
requireProjectConfig = true
);
// Auto-detect the reload password from .env / config, but let an explicit
// `--password=<value>` override it (parity with `wheels console`). The
// auto-detect default is unchanged when no flag is given.
var reloadOpts = parseConsoleArgs(structuredArgs(arguments));
var password = len(reloadOpts.password) ? reloadOpts.password : detectReloadPassword();
// F5 fix: physically wipe the Lucee compiled-class cache before
// triggering the framework reload. Lucee Express's default
// `inspectTemplate=once` means Lucee compiles each CFC once, caches
// the .class on disk, and never re-checks the source timestamp.
// `?reload=true` resets Wheels application state via applicationStop()
// but does not invalidate Lucee's template cache, so edits to models,
// controllers, and config silently miss until cfclasses is wiped.
// See onboarding finding F5.
$purgeServerCfclasses();
// Response honesty (#3059): a SUCCESSFUL reload is ALWAYS a 302 — the
// framework's reload gate restarts the app and then location()-redirects
// (public/Application.cfc :: $handleRestartAppRequest). Redirects stay
// OFF so the raw status is the verdict: following the success-redirect
// would collapse a real reload (302 -> 200 at `/`) into the same 200 a
// wrong-password page render produces. Failures print-then-throw per
// the #2941 exit-code convention so `wheels reload && ...` gates work.
var reloadUrl = "http://localhost:#serverPort#/?reload=true&password=#password#";
var reloadState = { statusCode = 0 };
try {
reloadState.statusCode = makeHttpRequestWithStatus(reloadUrl, false).statusCode;
} catch (any e) {
out("Failed to reload: #e.message#", "red");
if (!len(password)) {
out("Hint: Set WHEELS_RELOAD_PASSWORD in .env or config/settings.cfm", "yellow");
}
throw(
type = "Wheels.ReloadFailed",
message = "Reload request to localhost:#serverPort# failed: #e.message#"
);
}
var verdict = $evaluateReloadResponse(reloadState.statusCode);
if (!verdict.success) {
out(verdict.message, "red");
if (!len(password)) {
out("Hint: Set WHEELS_RELOAD_PASSWORD in .env or config/settings.cfm", "yellow");
}
verbose("URL: http://localhost:#serverPort#/?reload=true&password=***");
throw(type = "Wheels.ReloadFailed", message = verdict.message);
}
out("Application reloaded successfully.", "green");
// Surface the hot-vs-cold reload contract — Wheels does NOT
// re-fire onApplicationStart on `?reload=true`. Users editing
// app/events/onapplicationstart.cfm or config/services.cfm need
// a full restart. See finding #8 in the 2026-04-29 fresh-VM
// triage.
out("Note: onApplicationStart does NOT re-fire. For init-code edits, run `wheels stop && wheels start`.", "cyan");
verbose("URL: http://localhost:#serverPort#/?reload=true&password=***");
return "";
}
/**
* Verdict for a `?reload=true` response status (#3059).
*
* The framework's reload gate restarts the app and then redirects via
* location(), so a successful reload is always a 3xx (302 in practice).
* A 2xx means the warm-path gate fell through and the page was served
* normally — the reload password didn't match, nothing restarted (404
* is the same fall-through on an app without a root route). 4xx/5xx
* means the endpoint itself errored (e.g. the #3053 Adobe regression).
*
* Public ONLY so ReloadCommandSpec can unit-test it (the cli/CLAUDE.md
* "public for specs" carve-out) — hidden from MCP via the structural
* $-prefix sweep in mcpHiddenTools().
*/
public struct function $evaluateReloadResponse(required numeric statusCode) {
if (arguments.statusCode >= 300 && arguments.statusCode < 400) {
return { success = true, message = "" };
}
if (arguments.statusCode >= 400) {
return {
success = false,
message = "Reload failed: the server returned HTTP #arguments.statusCode#. The application was NOT reloaded — check the server's error output."
};
}
return {
success = false,
message = "Reload was not triggered: the server served the page normally (HTTP #arguments.statusCode#) instead of answering with the reload redirect (302). The application was NOT reloaded — check the reload password."
};
}
// ─────────────────────────────────────────────────
// start / stop — Dev server management
// ─────────────────────────────────────────────────
/**
* hint: Start the Wheels development server via LuCLI
*/
public string function start() {
var args = new services.ArgSpec().toArgv(structuredArgs(arguments));
// Refuse to start from a non-Wheels-project directory. LuCLI's
// `server start` derives the server name from the cwd basename and
// silently registers a new context — running `wheels start` in the
// wrong directory leaves orphan registrations like `ws` or
// `Downloads`. Onboarding finding F6.
if (!$isWheelsProjectDir(variables.projectRoot)) {
out("This directory does not look like a Wheels project.", "yellow");
out(" Expected: config/settings.cfm under the current directory.", "yellow");
out("");
out("Tip: cd into your project directory, or run `wheels new <appname>`", "cyan");
out(" to scaffold one.", "cyan");
return "";
}
// Detect a stale `<lucliHome>/servers/<basename>/` registration before
// delegating to LuCLI. Without this intercept, LuCLI emits a numbered
// recovery prompt referencing `lucli server start --force`, but `lucli`
// isn't on PATH after `brew install wheels` — the user gets an
// unactionable error from a fresh `wheels start`. Onboarding F1/F2.
var force = false;
var passThrough = [];
for (var a in args) {
if (a == "--force") { force = true; }
else { arrayAppend(passThrough, a); }
}
var registry = getService("serverRegistry");
var serverName = registry.serverNameFor(variables.projectRoot);
var reg = registry.inspect(serverName, variables.projectRoot);
if (reg.alive) {
out("Server '" & serverName & "' is already running.", "yellow");
out("To restart: wheels stop && wheels start", "cyan");
return "";
}
if (reg.exists && !reg.ours && !force) {
out("");
out("Server name '" & serverName & "' is registered to a different project:", "yellow");
out(" registered: " & (len(reg.registeredPath) ? reg.registeredPath : "<unknown>"), "yellow");
out(" this dir: " & variables.projectRoot, "yellow");
out("");
out("Options:", "bold");
out(" - Pass --force to replace the registration:");
out(" wheels start --force", "cyan");
out(" - Or rename your project directory so it gets a unique server name.");
return "";
}
// Stale-but-ours, or --force was passed: wipe the dead registration so
// LuCLI's `server start` doesn't trip its "already exists" prompt.
if (reg.exists) {
registry.clean(serverName);
}
// Defense in depth for the IPv4-blind port check. LuCLI's own
// LuceeServerConfig.isPortAvailable() probes with a wildcard ServerSocket
// that binds IPv6 on a dual-stack JVM, so it never sees a port held by an
// IPv4-only listener (python http.server, Django runserver on 8000,
// 127.0.0.1-bound databases) and `wheels start` would boot on top of it.
// That is fixed upstream, but older LuCLI binaries still ship the bug, so
// when lucee.json pins a port we connect-probe it (both address families)
// and warn before delegating. We only reach here when our own server is
// NOT already running (the reg.alive early-return above), so an in-use
// pinned port is a genuine foreign collision.
var pinnedPort = $readPinnedPort(variables.projectRoot);
if (pinnedPort > 0 && getService("portProbe").portInUse(pinnedPort)) {
out("");
out("Warning: port " & pinnedPort & " (configured in lucee.json) is already in use", "yellow");