Repository navigation
Expand file tree
/
Copy pathspe-tutorial-prototype.jsx
More file actions
2951 lines (2759 loc) · 116 KB
/
Copy pathspe-tutorial-prototype.jsx
File metadata and controls
2951 lines (2759 loc) · 116 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
import { useState, useEffect, useRef, useCallback } from "react";
// ============================================================================
// VIRTUAL SITECORE CONTENT TREE
// ============================================================================
const VIRTUAL_TREE = {
sitecore: {
_id: "{11111111-1111-1111-1111-111111111111}",
_template: "Root",
_templateFullName: "System/Root",
_version: 1,
_fields: {},
_children: {
content: {
_id: "{0DE95AE4-41AB-4D01-9EB0-67441B7C2450}",
_template: "Node",
_templateFullName: "System/Node",
_version: 1,
_fields: {},
_children: {
Home: {
_id: "{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}",
_template: "Sample Item",
_templateFullName: "Sample/Sample Item",
_version: 2,
_fields: {
Title: "Welcome to Sitecore",
Text: "<p>This is the home page content.</p>",
__Updated: "20250315T103000Z",
__Created: "20240601T080000Z",
"__Updated by": "sitecore\\admin",
},
_children: {
About: {
_id: "{A2B3C4D5-E6F7-8901-2345-678901234567}",
_template: "Sample Item",
_templateFullName: "Sample/Sample Item",
_version: 1,
_fields: {
Title: "About Us",
Text: "<p>Learn more about our company.</p>",
__Updated: "20250220T140000Z",
__Created: "20240710T090000Z",
"__Updated by": "sitecore\\author1",
},
_children: {
Team: {
_id: "{B1111111-1111-1111-1111-111111111111}",
_template: "Sample Item",
_templateFullName: "Sample/Sample Item",
_version: 1,
_fields: {
Title: "Our Team",
Text: "<p>Meet the team behind the product.</p>",
__Updated: "20250110T110000Z",
__Created: "20240815T100000Z",
"__Updated by": "sitecore\\author1",
},
_children: {},
},
History: {
_id: "{B2222222-2222-2222-2222-222222222222}",
_template: "Sample Item",
_templateFullName: "Sample/Sample Item",
_version: 1,
_fields: {
Title: "Our History",
Text: "<p>Founded in 2003.</p>",
__Updated: "20250105T090000Z",
__Created: "20240815T103000Z",
"__Updated by": "sitecore\\admin",
},
_children: {},
},
},
},
Products: {
_id: "{C3D4E5F6-7890-1234-5678-901234567890}",
_template: "Folder",
_templateFullName: "Common/Folder",
_version: 1,
_fields: {
__Updated: "20250301T080000Z",
__Created: "20240615T120000Z",
"__Updated by": "sitecore\\admin",
},
_children: {
"Product A": {
_id: "{D1111111-1111-1111-1111-111111111111}",
_template: "Sample Item",
_templateFullName: "Sample/Sample Item",
_version: 1,
_fields: {
Title: "Product A",
Text: "<p>Our flagship product.</p>",
__Updated: "20250310T160000Z",
__Created: "20240901T080000Z",
"__Updated by": "sitecore\\author2",
},
_children: {},
},
"Product B": {
_id: "{D2222222-2222-2222-2222-222222222222}",
_template: "Sample Item",
_templateFullName: "Sample/Sample Item",
_version: 1,
_fields: {
Title: "Product B",
Text: "<p>Enterprise solution.</p>",
__Updated: "20250228T120000Z",
__Created: "20240915T100000Z",
"__Updated by": "sitecore\\author2",
},
_children: {},
},
"Product C": {
_id: "{D3333333-3333-3333-3333-333333333333}",
_template: "Sample Item",
_templateFullName: "Sample/Sample Item",
_version: 1,
_fields: {
Title: "Product C",
Text: "<p>Developer toolkit.</p>",
__Updated: "20250120T143000Z",
__Created: "20241001T090000Z",
"__Updated by": "sitecore\\admin",
},
_children: {},
},
},
},
News: {
_id: "{E4F5A6B7-C8D9-0123-4567-890123456789}",
_template: "Folder",
_templateFullName: "Common/Folder",
_version: 1,
_fields: {
__Updated: "20250312T090000Z",
__Created: "20240701T080000Z",
"__Updated by": "sitecore\\admin",
},
_children: {
"2025 Roadmap": {
_id: "{E1111111-1111-1111-1111-111111111111}",
_template: "Sample Item",
_templateFullName: "Sample/Sample Item",
_version: 1,
_fields: {
Title: "2025 Product Roadmap",
Text: "<p>Exciting things ahead.</p>",
__Updated: "20250312T090000Z",
__Created: "20250105T080000Z",
"__Updated by": "sitecore\\author1",
},
_children: {},
},
"Sitecore Launch": {
_id: "{E2222222-2222-2222-2222-222222222222}",
_template: "Sample Item",
_templateFullName: "Sample/Sample Item",
_version: 1,
_fields: {
Title: "New Sitecore Features",
Text: "<p>Latest platform updates.</p>",
__Updated: "20250215T110000Z",
__Created: "20241120T100000Z",
"__Updated by": "sitecore\\author2",
},
_children: {},
},
},
},
},
},
},
},
},
},
};
// ============================================================================
// SIMULATION ENGINE
// ============================================================================
// The current working directory — matches real SPE ISE default
const CWD = "/sitecore/content/Home";
function resolvePath(pathStr) {
let clean = pathStr.replace(/['"]/g, "").trim();
// Handle "master:\" (with backslash) → root of drive (the sitecore node)
if (/^(master|core|web):[\\/]$/i.test(clean)) {
return { node: VIRTUAL_TREE.sitecore, name: "sitecore", path: "/sitecore" };
}
// Handle "master:" (bare, no backslash) → current location (same as ".")
if (/^(master|core|web):$/i.test(clean)) {
return resolveAbsolutePath(CWD);
}
// Strip drive prefix: master:\content\Home → content\Home
clean = clean.replace(/^(master|core|web):[\\/]?/i, "");
clean = clean.replace(/\\/g, "/");
// Handle dot-paths relative to CWD
if (clean === "." || clean === "") {
return resolveAbsolutePath(CWD);
} else if (clean.startsWith("./")) {
clean = CWD + clean.substring(1);
} else if (clean.startsWith("/sitecore")) {
// Already absolute with /sitecore prefix — keep as-is
} else if (clean.startsWith("sitecore/") || clean.toLowerCase() === "sitecore") {
clean = "/" + clean;
} else {
// Relative path segment (e.g. "content/Home") — resolve from /sitecore
clean = "/sitecore/" + clean;
}
return resolveAbsolutePath(clean);
}
function resolveAbsolutePath(cleanPath) {
// Remove trailing slash
const clean = cleanPath.replace(/\/$/, "");
const parts = clean.split("/").filter(Boolean);
let current = null;
let currentName = "";
for (const part of parts) {
if (!current) {
if (part.toLowerCase() === "sitecore") {
current = VIRTUAL_TREE.sitecore;
currentName = "sitecore";
} else return null;
} else {
const children = current._children || {};
const match = Object.keys(children).find(
(k) => k.toLowerCase() === part.toLowerCase()
);
if (match) {
current = children[match];
currentName = match;
} else return null;
}
}
return current ? { node: current, name: currentName, path: clean } : null;
}
function getChildren(node) {
if (!node || !node._children) return [];
return Object.entries(node._children).map(([name, child]) => ({
name,
node: child,
}));
}
function getAllDescendants(node, parentPath = "") {
const results = [];
const children = node._children || {};
for (const [name, child] of Object.entries(children)) {
const path = parentPath + "/" + name;
results.push({ name, node: child, path });
results.push(...getAllDescendants(child, path));
}
return results;
}
function formatItemTable(items) {
if (items.length === 0) return "";
// Match real SPE table format from Sitecore_Views.ps1xml:
// Name(32) Children/HasChildren(8) Language(8) Version(7) Id/ID(38) TemplateName(32)
const headers = ["Name", "Children", "Language", "Version", "Id", "TemplateName"];
const rows = items.map((item) => [
item.name,
Object.keys(item.node._children || {}).length > 0 ? "True" : "False",
"en",
String(item.node._version || 1),
item.node._id || "-",
item.node._template || "-",
]);
// Fixed widths from Sitecore_Views.ps1xml TableColumnHeader definitions
const fixedWidths = [32, 8, 8, 7, 38, 32];
const colWidths = headers.map((h, i) => {
const dataMax = Math.max(h.length, ...rows.map((r) => String(r[i]).length));
return fixedWidths[i] > 0 ? Math.max(fixedWidths[i], dataMax) : dataMax;
});
const sep = colWidths.map((w) => "-".repeat(w)).join(" ");
const headerLine = headers
.map((h, i) => h.padEnd(colWidths[i]))
.join(" ");
const rowLines = rows.map((r) =>
r.map((c, i) => String(c).padEnd(colWidths[i])).join(" ")
);
return [headerLine, sep, ...rowLines].join("\n");
}
function formatPropertyTable(items, properties) {
if (items.length === 0) return "";
// Normalize property names to match real SPE behavior
// "Id" always displays as "ID" in headers (property name is ID)
const displayHeaders = properties.map((p) => {
if (p.toLowerCase() === "id") return "ID";
return p;
});
const rows = items.map((item) =>
properties.map((p) => getItemProperty(item, p) || "-")
);
const colWidths = displayHeaders.map((h, i) =>
Math.max(h.length, ...rows.map((r) => String(r[i]).length))
);
const sep = colWidths.map((w) => "-".repeat(w)).join(" ");
const headerLine = displayHeaders
.map((h, i) => h.padEnd(colWidths[i]))
.join(" ");
const rowLines = rows.map((r) =>
r.map((c, i) => String(c).padEnd(colWidths[i])).join(" ")
);
return [headerLine, sep, ...rowLines].join("\n");
}
function parseCommand(input) {
const trimmed = input.trim();
// Split on pipe, respecting quoted strings AND braces
const rawStages = [];
let current = "";
let inQuote = false;
let quoteChar = "";
let braceDepth = 0;
for (let i = 0; i < trimmed.length; i++) {
const ch = trimmed[i];
if (inQuote) {
current += ch;
if (ch === quoteChar) inQuote = false;
} else if (ch === '"' || ch === "'") {
inQuote = true;
quoteChar = ch;
current += ch;
} else if (ch === "{") {
braceDepth++;
current += ch;
} else if (ch === "}") {
braceDepth = Math.max(0, braceDepth - 1);
current += ch;
} else if (ch === "|" && braceDepth === 0) {
rawStages.push(current.trim());
current = "";
} else {
current += ch;
}
}
if (current.trim()) rawStages.push(current.trim());
return { raw: rawStages, parsed: rawStages.map(parseSingleCommand) };
}
function parseSingleCommand(cmdStr) {
const tokens = [];
let current = "";
let inQuote = false;
let quoteChar = "";
for (let i = 0; i < cmdStr.length; i++) {
const ch = cmdStr[i];
if (inQuote) {
if (ch === quoteChar) {
inQuote = false;
} else {
current += ch;
}
} else if (ch === '"' || ch === "'") {
inQuote = true;
quoteChar = ch;
} else if (ch === " " || ch === "\t") {
if (current) {
tokens.push(current);
current = "";
}
} else {
current += ch;
}
}
if (current) tokens.push(current);
const cmdlet = tokens[0] || "";
const params = {};
const switches = [];
let currentParam = null;
for (let i = 1; i < tokens.length; i++) {
const t = tokens[i];
if (t.startsWith("-")) {
if (currentParam) switches.push(currentParam);
currentParam = t.substring(1);
} else {
if (currentParam) {
params[currentParam] = t;
currentParam = null;
} else {
// Positional param
if (!params._positional) params._positional = [];
params._positional.push(t);
}
}
}
if (currentParam) switches.push(currentParam);
return { cmdlet, params, switches };
}
// Shared property resolver — case-insensitive, matches real SPE behavior
function getItemProperty(item, prop) {
const p = prop.toLowerCase();
if (p === "name") return item.name;
if (p === "id") return item.node._id || "";
if (p === "templatename") return item.node._template || "";
if (p === "templateid") return "{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}";
if (p === "itempath") return item.path || "/" + item.name;
if (p === "version") return String(item.node._version || 1);
if (p === "haschildren") return Object.keys(item.node._children || {}).length > 0 ? "True" : "False";
if (p === "database") return "master";
if (p === "displayname") return item.name;
if (p === "language") return "en";
// Check fields (case-sensitive for field names like __Updated, __Created by)
if (item.node._fields && prop in item.node._fields) return item.node._fields[prop];
// Case-insensitive field fallback
if (item.node._fields) {
const fieldKey = Object.keys(item.node._fields).find(k => k.toLowerCase() === p);
if (fieldKey) return item.node._fields[fieldKey];
}
return "";
}
// Script execution context — holds variable scope across lines
class ScriptContext {
constructor() {
this.variables = {};
this.outputs = [];
this.errors = [];
this.dialogRequests = []; // For Read-Variable, Show-Alert
}
setVar(name, value) {
this.variables[name.replace(/^\$/, "")] = value;
}
getVar(name) {
const clean = name.replace(/^\$/, "");
return this.variables[clean];
}
// Expand $variable references in a string
expandVars(str) {
if (!str) return str;
return str.replace(/\$(\w+)/g, (match, varName) => {
const val = this.variables[varName];
if (val === undefined) return match;
if (Array.isArray(val)) return `[Array: ${val.length} items]`;
if (typeof val === "object" && val.name) return val.name;
return String(val);
});
}
}
// Execute a multi-line script with shared variable scope
function executeScript(script) {
const ctx = new ScriptContext();
const lines = script.split("\n");
// Pre-process: join continuation lines (ending with |, `, or opening {)
const joined = [];
let buffer = "";
for (const rawLine of lines) {
const trimmed = rawLine.trim();
if (!trimmed || trimmed.startsWith("#")) {
if (buffer) {
joined.push(buffer);
buffer = "";
}
continue;
}
if (buffer) {
buffer += " " + trimmed;
} else {
buffer = trimmed;
}
// Continue accumulating if line ends with | or backtick
if (trimmed.endsWith("|") || trimmed.endsWith("`")) {
buffer = buffer.replace(/[`]$/, "");
continue;
}
// Check for balanced braces
const openBraces = (buffer.match(/\{/g) || []).length;
const closeBraces = (buffer.match(/\}/g) || []).length;
if (openBraces > closeBraces) continue;
joined.push(buffer);
buffer = "";
}
if (buffer) joined.push(buffer);
for (const line of joined) {
executeLine(line, ctx);
}
return {
output: ctx.outputs.join("\n\n"),
error: ctx.errors.length > 0 ? ctx.errors.join("\n") : null,
dialogRequests: ctx.dialogRequests,
};
}
function executeLine(line, ctx) {
const trimmed = line.trim();
// Variable assignment: $varName = <expression>
const assignMatch = trimmed.match(/^\$(\w+)\s*=\s*(.+)$/);
if (assignMatch) {
const [, varName, expr] = assignMatch;
// Execute the RHS as a command
const result = executeCommandWithContext(expr, ctx);
if (result.error) {
ctx.errors.push(result.error);
} else if (result.pipelineData) {
ctx.setVar(varName, result.pipelineData);
} else if (result.output) {
// Primitive value assignment (string/number)
ctx.setVar(varName, result.output);
}
return;
}
// Foreach loop: foreach($var in $collection) { ... }
const foreachMatch = trimmed.match(/^foreach\s*\(\s*\$(\w+)\s+in\s+\$(\w+)\s*\)\s*\{(.+)\}$/i);
if (foreachMatch) {
const [, iterVar, collectionVar, body] = foreachMatch;
const collection = ctx.getVar(collectionVar);
if (Array.isArray(collection)) {
for (const item of collection) {
ctx.setVar(iterVar, item);
const bodyLines = body.split(";").map(s => s.trim()).filter(Boolean);
for (const bl of bodyLines) {
executeLine(bl, ctx);
}
}
}
return;
}
// Regular command execution
const result = executeCommandWithContext(trimmed, ctx);
if (result.error) ctx.errors.push(result.error);
if (result.output) ctx.outputs.push(result.output);
}
// Core command execution with variable context
function executeCommandWithContext(input, ctx) {
// Expand variables in the input
let expanded = input;
// Expand $var.Property access patterns
expanded = expanded.replace(/\$(\w+)\.(\w+)/g, (match, varName, prop) => {
if (varName === "_") return match; // Leave $_ alone for pipeline
const val = ctx.getVar(varName);
if (!val) return match;
// Single item
if (val.node) {
return getItemProperty(val, prop);
}
// Array — return count for .Count/.Length
if (Array.isArray(val)) {
if (prop.toLowerCase() === "count" || prop.toLowerCase() === "length") return String(val.length);
}
return match;
});
// Expand simple $var references in quoted strings
expanded = expanded.replace(/"([^"]*\$\w+[^"]*)"/g, (match) => {
return '"' + match.slice(1, -1).replace(/\$(\w+)/g, (m, varName) => {
if (varName === "_") return m;
const val = ctx.getVar(varName);
if (val === undefined) return m;
if (typeof val === "string") return val;
if (Array.isArray(val)) return `[Array: ${val.length} items]`;
if (val.name) return val.name;
return String(val);
}) + '"';
});
// Check if the input is just a variable reference (to pipe variable contents)
const bareVarMatch = expanded.trim().match(/^\$(\w+)$/);
if (bareVarMatch) {
const val = ctx.getVar(bareVarMatch[1]);
if (val !== undefined) {
if (Array.isArray(val)) {
return { output: formatItemTable(val), error: null, pipelineData: val };
}
return { output: String(val), error: null, pipelineData: val };
}
}
// Parse and execute the pipeline
const { raw: rawStages, parsed: stages } = parseCommand(expanded);
if (stages.length === 0) return { output: "", error: null };
let pipelineData = null;
for (let i = 0; i < stages.length; i++) {
const stage = stages[i];
const cmdLower = stage.cmdlet.toLowerCase();
// Check if the first stage is a variable reference (e.g., $items | Where-Object)
if (i === 0 && stage.cmdlet.startsWith("$")) {
const varVal = ctx.getVar(stage.cmdlet.substring(1));
if (Array.isArray(varVal)) {
pipelineData = varVal;
continue;
} else if (varVal && varVal.node) {
pipelineData = [varVal];
continue;
}
}
try {
if (cmdLower === "get-item") {
const path =
stage.params.Path || stage.params.path || (stage.params._positional && stage.params._positional[0]) || ".";
const resolved = resolvePath(path);
if (!resolved) return { output: "", error: `Get-Item : Cannot find path '${path}' because it does not exist.` };
pipelineData = [{ name: resolved.name, node: resolved.node, path: resolved.path }];
} else if (cmdLower === "get-childitem") {
const path =
stage.params.Path || stage.params.path || (stage.params._positional && stage.params._positional[0]);
let items = [];
const recurse = stage.switches.some((s) => s.toLowerCase() === "recurse");
if (pipelineData) {
for (const item of pipelineData) {
if (recurse) {
items.push(...getAllDescendants(item.node, item.path || item.name));
} else {
items.push(
...getChildren(item.node).map((c) => ({
...c,
path: (item.path || item.name) + "/" + c.name,
}))
);
}
}
} else {
const resolved = resolvePath(path || ".");
if (!resolved) return { output: "", error: `Get-ChildItem : Cannot find path '${path}'` };
if (recurse) {
items = getAllDescendants(resolved.node, resolved.path);
} else {
items = getChildren(resolved.node).map((c) => ({
...c,
path: resolved.path + "/" + c.name,
}));
}
}
pipelineData = items;
} else if (cmdLower === "where-object" || cmdLower === "where" || cmdLower === "?") {
if (!pipelineData) return { output: "", error: "Where-Object : No pipeline input." };
const rawCmd = rawStages[i] || "";
const braceStart = rawCmd.indexOf("{");
const braceEnd = rawCmd.lastIndexOf("}");
let filterExpr = "";
if (braceStart !== -1 && braceEnd > braceStart) {
filterExpr = rawCmd.substring(braceStart + 1, braceEnd).trim();
} else {
const allTokens = [
...(stage.params._positional || []),
...Object.values(stage.params).filter(v => typeof v === "string"),
...stage.switches
].join(" ").replace(/[{}]/g, "").trim();
filterExpr = allTokens;
}
if (!filterExpr) {
return { output: "", error: "Where-Object : Missing filter expression." };
}
const filterMatch = filterExpr.match(
/\$_\.(\w+)\s+-(eq|ne|like|notlike|match|gt|lt|ge|le)\s+(?:"([^"]+)"|'([^']+)'|(\S+))/i
);
if (filterMatch) {
const prop = filterMatch[1];
const op = filterMatch[2];
const val = filterMatch[3] || filterMatch[4] || filterMatch[5] || "";
pipelineData = pipelineData.filter((item) => {
const itemVal = getItemProperty(item, prop);
switch (op.toLowerCase()) {
case "eq": return String(itemVal).toLowerCase() === val.toLowerCase();
case "ne": return String(itemVal).toLowerCase() !== val.toLowerCase();
case "like": {
const regex = new RegExp("^" + val.replace(/\*/g, ".*").replace(/\?/g, ".") + "$", "i");
return regex.test(String(itemVal));
}
case "match": return new RegExp(val, "i").test(String(itemVal));
default: return true;
}
});
}
} else if (cmdLower === "foreach-object" || cmdLower === "foreach" || cmdLower === "%") {
if (!pipelineData) return { output: "", error: "ForEach-Object : No pipeline input." };
const rawCmd = rawStages[i] || "";
const braceStart = rawCmd.indexOf("{");
const braceEnd = rawCmd.lastIndexOf("}");
if (braceStart !== -1 && braceEnd > braceStart) {
const body = rawCmd.substring(braceStart + 1, braceEnd).trim();
const results = [];
for (const item of pipelineData) {
// Set $_ in context for the loop body
ctx.setVar("_", item);
// Handle property access: $_.PropertyName
let expandedBody = body.replace(/\$_\.(\w+)/g, (_, prop) => {
return getItemProperty(item, prop);
});
// Handle Write-Host or simple expression output
if (expandedBody.toLowerCase().startsWith("write-host")) {
const msg = expandedBody.replace(/^write-host\s*/i, "").replace(/^["']|["']$/g, "");
results.push(msg);
} else if (expandedBody.startsWith('"') || expandedBody.startsWith("'")) {
// String expression — expand and output
results.push(expandedBody.replace(/^["']|["']$/g, ""));
} else {
// Try executing as a command
const innerResult = executeCommandWithContext(expandedBody, ctx);
if (innerResult.output) results.push(innerResult.output);
if (innerResult.error) ctx.errors.push(innerResult.error);
}
}
if (results.length > 0) {
return { output: results.join("\n"), error: null };
}
}
// If no brace block, ForEach-Object just passes through
// (real PS supports -Process but we simplify)
} else if (cmdLower === "select-object" || cmdLower === "select") {
if (!pipelineData) return { output: "", error: "Select-Object : No pipeline input." };
const propParam = stage.params.Property || stage.params.property;
if (propParam) {
const props = propParam.split(",").map((p) => p.trim());
pipelineData._selectedProperties = props;
}
const first = stage.params.First || stage.params.first;
if (first) pipelineData = pipelineData.slice(0, parseInt(first));
const last = stage.params.Last || stage.params.last;
if (last) pipelineData = pipelineData.slice(-parseInt(last));
} else if (cmdLower === "sort-object" || cmdLower === "sort") {
if (!pipelineData) return { output: "", error: "Sort-Object : No pipeline input." };
const sortProp = stage.params.Property || stage.params.property || (stage.params._positional && stage.params._positional[0]);
const desc = stage.switches.some((s) => s.toLowerCase() === "descending");
if (sortProp) {
pipelineData.sort((a, b) => {
const aVal = getItemProperty(a, sortProp);
const bVal = getItemProperty(b, sortProp);
const cmp = String(aVal).localeCompare(String(bVal));
return desc ? -cmp : cmp;
});
}
} else if (cmdLower === "group-object" || cmdLower === "group") {
if (!pipelineData) return { output: "", error: "Group-Object : No pipeline input." };
const groupProp = stage.params.Property || stage.params.property || (stage.params._positional && stage.params._positional[0]);
if (groupProp) {
const groups = {};
for (const item of pipelineData) {
const key = getItemProperty(item, groupProp) || "(none)";
if (!groups[key]) groups[key] = [];
groups[key].push(item);
}
const headers = ["Count", "Name", "Group"];
const rows = Object.entries(groups).map(([name, items]) => [
String(items.length).padStart(5),
name,
`{${items.slice(0, 3).map(i => i.name).join(", ")}${items.length > 3 ? "..." : ""}}`,
]);
const colWidths = headers.map((h, idx) =>
Math.max(h.length, ...rows.map(r => r[idx].length))
);
const sep = colWidths.map(w => "-".repeat(w)).join(" ");
const headerLine = headers.map((h, idx) => h.padEnd(colWidths[idx])).join(" ");
const rowLines = rows.map(r => r.map((c, idx) => c.padEnd(colWidths[idx])).join(" "));
return { output: [headerLine, sep, ...rowLines].join("\n"), error: null };
}
} else if (cmdLower === "measure-object" || cmdLower === "measure") {
if (!pipelineData) return { output: "", error: "Measure-Object : No pipeline input." };
const count = Array.isArray(pipelineData) ? pipelineData.length : 0;
return { output: `\nCount : ${count}\nAverage : \nSum : \nMaximum : \nMinimum : \nProperty :`, error: null };
} else if (cmdLower === "get-member" || cmdLower === "gm") {
if (!pipelineData || pipelineData.length === 0) {
return { output: "", error: "Get-Member : No input object." };
}
const members = [
" TypeName: Sitecore.Data.Items.Item",
"",
"Name MemberType Definition",
"---- ---------- ----------",
"Access Property Sitecore.Data.Items.ItemAccess Access {get;}",
"Appearance Property Sitecore.Data.Items.ItemAppearance Appearance {get;}",
"Axes Property Sitecore.Data.Items.ItemAxes Axes {get;}",
"Branch Property Sitecore.Data.Items.BranchItem Branch {get;}",
"Branches Property Sitecore.Data.Items.BranchItem[] Branches {get;}",
"BranchId Property Sitecore.Data.ID BranchId {get; set;}",
"Children Property Sitecore.Collections.ChildList Children {get;}",
"Created Property System.DateTime Created {get;}",
"Database Property Sitecore.Data.Database Database {get;}",
"DisplayName Property string DisplayName {get; set;}",
"Editing Property Sitecore.Data.Items.ItemEditing Editing {get;}",
"Empty Property bool Empty {get;}",
"Fields Property Sitecore.Data.Fields.FieldCollection Fields {get;}",
"HasChildren Property bool HasChildren {get;}",
"Help Property Sitecore.Data.Items.ItemHelp Help {get;}",
"ID Property Sitecore.Data.ID ID {get;}",
"InnerData Property Sitecore.Data.Items.ItemData InnerData {get;}",
"IsClone Property bool IsClone {get;}",
"IsFallback Property bool IsFallback {get;}",
"IsItemClone Property bool IsItemClone {get;}",
"Key Property string Key {get;}",
"Language Property Sitecore.Globalization.Language Language {get;}",
"Languages Property Sitecore.Globalization.Language[] Languages {get;}",
"Links Property Sitecore.Links.ItemLinks Links {get;}",
"Locking Property Sitecore.Data.Locking.ItemLocking Locking {get;}",
"Modified Property System.DateTime Modified {get;}",
"Name Property string Name {get; set;}",
"OriginalLanguage Property Sitecore.Globalization.Language OriginalLanguage {get;}",
"OriginatorId Property Sitecore.Data.ID OriginatorId {get; set;}",
"Parent Property Sitecore.Data.Items.Item Parent {get;}",
"ParentID Property Sitecore.Data.ID ParentID {get;}",
"Paths Property Sitecore.Data.ItemPath Paths {get;}",
"Publishing Property Sitecore.Data.Items.ItemPublishing Publishing {get;}",
"Security Property Sitecore.Data.Items.ItemSecurity Security {get;}",
"Source Property object Source {get;}",
"SourceUri Property Sitecore.Data.DataUri SourceUri {get;}",
"State Property Sitecore.Data.Items.ItemState State {get;}",
"Statistics Property Sitecore.Data.Items.ItemStatistics Statistics {get;}",
"Template Property Sitecore.Data.Items.TemplateItem Template {get;}",
"TemplateID Property Sitecore.Data.ID TemplateID {get; set;}",
"TemplateName Property string TemplateName {get;}",
"Uri Property Sitecore.Data.DataUri Uri {get;}",
"Version Property Sitecore.Data.Version Version {get;}",
"Versions Property Sitecore.Data.Items.ItemVersions Versions {get;}",
"Visualization Property Sitecore.Data.Items.ItemVisualization Visualization {get;}",
];
return { output: members.join("\n"), error: null };
} else if (cmdLower === "get-location" || cmdLower === "gl" || cmdLower === "pwd") {
return { output: "\nPath \n---- \nmaster:\\content\\Home\n", error: null };
} else if (cmdLower === "show-listview") {
if (!pipelineData || pipelineData.length === 0) {
return { output: "", error: "Show-ListView : No pipeline input." };
}
const propParam = stage.params.Property || stage.params.property;
const title = stage.params.Title || stage.params.title || "List View";
let props = null;
if (propParam) {
props = propParam.split(",").map((p) => p.trim());
}
let output = `\n ${title}\n ${"─".repeat(title.length)}\n\n`;
if (props) {
output += formatPropertyTable(pipelineData, props);
} else {
output += formatItemTable(pipelineData);
}
output += `\n\n ${pipelineData.length} item(s) displayed.`;
return { output, error: null };
} else if (cmdLower === "show-alert") {
const msg = stage.params.Title || stage.params.title ||
(stage.params._positional && stage.params._positional[0]) || "";
ctx.dialogRequests.push({ type: "alert", message: msg });
return { output: `⚠ Alert: ${msg}`, error: null };
} else if (cmdLower === "read-variable") {
// Simulate Read-Variable by capturing parameters and showing them as form output
const title = stage.params.Title || stage.params.title || "Input";
const desc = stage.params.Description || stage.params.description || "";
ctx.dialogRequests.push({ type: "read-variable", title, description: desc });
return { output: `📋 Dialog: ${title}${desc ? " — " + desc : ""}\n (In real SPE, this opens an interactive parameter dialog)`, error: null };
} else if (cmdLower === "close-window") {
return { output: "", error: null }; // No-op in simulation
} else if (cmdLower === "write-host" || cmdLower === "write-output") {
const msg = [
...(stage.params._positional || []),
...(Object.entries(stage.params)
.filter(([k]) => k !== "_positional" && k !== "ForegroundColor" && k !== "foregroundcolor")
.map(([, v]) => v))
].join(" ");
return { output: msg || "", error: null };
} else if (cmdLower === "new-item") {
const parentPath = stage.params.Path || stage.params.path || (stage.params._positional && stage.params._positional[0]);
const name = stage.params.Name || stage.params.name;
const itemType = stage.params.ItemType || stage.params.itemtype;
if (!parentPath || !name) {
return { output: "", error: "New-Item : Missing -Path and/or -Name parameter." };
}
const resolved = resolvePath(parentPath);
if (!resolved) return { output: "", error: `New-Item : Cannot find path '${parentPath}'` };
// Add to virtual tree
const newId = `{${crypto.randomUUID ? crypto.randomUUID().toUpperCase() : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"}}`;
const templateShort = itemType ? itemType.split("/").pop() : "Item";
const newNode = {
_id: newId,
_template: templateShort,
_templateFullName: itemType || "System/Item",
_version: 1,
_fields: {
__Updated: new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d+/, ""),
__Created: new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d+/, ""),
"__Updated by": "sitecore\\admin",
},
_children: {},
};
resolved.node._children[name] = newNode;
const newItem = { name, node: newNode, path: resolved.path + "/" + name };
pipelineData = [newItem];
} else if (cmdLower === "remove-item") {
const targetPath = stage.params.Path || stage.params.path || (stage.params._positional && stage.params._positional[0]);
if (!targetPath && pipelineData) {
// Remove from pipeline input
for (const item of pipelineData) {
removeFromTree(item.path);
}
return { output: "", error: null };
}
if (targetPath) {
const resolved = resolvePath(targetPath);
if (!resolved) return { output: "", error: `Remove-Item : Cannot find path '${targetPath}'` };
removeFromTree(resolved.path);
}
return { output: "", error: null };
} else if (cmdLower === "move-item") {
// Move-Item -Path <source> -Destination <target>
const sourcePath = stage.params.Path || stage.params.path || (stage.params._positional && stage.params._positional[0]);
const destPath = stage.params.Destination || stage.params.destination || (stage.params._positional && stage.params._positional[1]);
if (!sourcePath || !destPath) {
return { output: "", error: "Move-Item : Missing -Path and/or -Destination parameter." };
}
const sourceResolved = resolvePath(sourcePath);
if (!sourceResolved) return { output: "", error: `Move-Item : Cannot find path '${sourcePath}'` };
const destResolved = resolvePath(destPath);
if (!destResolved) return { output: "", error: `Move-Item : Cannot find destination '${destPath}'` };
// Clone node to destination, remove from source
destResolved.node._children[sourceResolved.name] = sourceResolved.node;
removeFromTree(sourceResolved.path);
pipelineData = [{ name: sourceResolved.name, node: sourceResolved.node, path: destResolved.path + "/" + sourceResolved.name }];
} else if (cmdLower === "copy-item") {
// Copy-Item -Path <source> -Destination <target>
const sourcePath = stage.params.Path || stage.params.path || (stage.params._positional && stage.params._positional[0]);
const destPath = stage.params.Destination || stage.params.destination || (stage.params._positional && stage.params._positional[1]);
if (!sourcePath || !destPath) {
return { output: "", error: "Copy-Item : Missing -Path and/or -Destination parameter." };
}
const sourceResolved = resolvePath(sourcePath);
if (!sourceResolved) return { output: "", error: `Copy-Item : Cannot find path '${sourcePath}'` };
const destResolved = resolvePath(destPath);
if (!destResolved) return { output: "", error: `Copy-Item : Cannot find destination '${destPath}'` };
// Deep clone the source node
const cloned = JSON.parse(JSON.stringify(sourceResolved.node));
cloned._id = `{${crypto.randomUUID ? crypto.randomUUID().toUpperCase() : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"}}`;
destResolved.node._children[sourceResolved.name] = cloned;
pipelineData = [{ name: sourceResolved.name, node: cloned, path: destResolved.path + "/" + sourceResolved.name }];
} else if (cmdLower === "rename-item") {
// Rename-Item -Path <source> -NewName <name>
const sourcePath = stage.params.Path || stage.params.path || (stage.params._positional && stage.params._positional[0]);
const newName = stage.params.NewName || stage.params.newname || (stage.params._positional && stage.params._positional[1]);
if (!newName) {
return { output: "", error: "Rename-Item : Missing -NewName parameter." };
}
// Support pipeline input: Get-Item ... | Rename-Item -NewName "..."
let targetItem = null;
let targetPath = null;
if (pipelineData && pipelineData.length > 0 && !sourcePath) {
targetItem = pipelineData[0];