sfmc-language-lsp 3.16.0 → 3.17.0

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,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SSJS_ESLINT_DUPLICATE_DIAG_CODES = exports.DIAG_CODE_SSJS_NONFUNCTIONAL_METHOD = exports.DIAG_CODE_SSJS_INVALID_ARITY = exports.DIAG_CODE_SSJS_DEPRECATED = exports.DIAG_CODE_SSJS_NONEXISTENT_GLOBAL = exports.DIAG_CODE_SSJS_INVALID_PROPERTY_ACCESS = exports.DIAG_CODE_SSJS_INVALID_HTTP_PROPERTY = exports.DIAG_CODE_SSJS_CLR_CONTENT_ACCESS = exports.DIAG_CODE_SSJS_CLR_HEADER_ACCESS = exports.DIAG_CODE_SSJS_UNSUPPORTED_SYNTAX = exports.DIAG_CODE_SSJS_PLATFORM_LOAD_VERSION = exports.DIAG_CODE_SSJS_REQUIRE_PLATFORM_LOAD = exports.DIAG_CODE_SSJS_REPLACE_WITH_PLATFORM_FUNCTION = exports.DIAG_CODE_SSJS_MCN_NOT_SUPPORTED = exports.DIAG_CODE_SSJS_POLYFILL_REQUIRED = void 0;
3
+ exports.SSJS_ESLINT_DUPLICATE_DIAG_CODES = exports.DIAG_CODE_SSJS_CROSS_BLOCK_FORWARD_REF = exports.DIAG_CODE_SSJS_NEW_OBJECT_RETURN = exports.DIAG_CODE_SSJS_SWITCH_FALLTHROUGH = exports.DIAG_CODE_SSJS_NONFUNCTIONAL_METHOD = exports.DIAG_CODE_SSJS_INVALID_ARITY = exports.DIAG_CODE_SSJS_DEPRECATED = exports.DIAG_CODE_SSJS_NONEXISTENT_GLOBAL = exports.DIAG_CODE_SSJS_INVALID_PROPERTY_ACCESS = exports.DIAG_CODE_SSJS_INVALID_HTTP_PROPERTY = exports.DIAG_CODE_SSJS_CLR_CONTENT_ACCESS = exports.DIAG_CODE_SSJS_CLR_HEADER_ACCESS = exports.DIAG_CODE_SSJS_UNSUPPORTED_SYNTAX = exports.DIAG_CODE_SSJS_PLATFORM_LOAD_VERSION = exports.DIAG_CODE_SSJS_REQUIRE_PLATFORM_LOAD = exports.DIAG_CODE_SSJS_REPLACE_WITH_PLATFORM_FUNCTION = exports.DIAG_CODE_SSJS_MCN_NOT_SUPPORTED = exports.DIAG_CODE_SSJS_POLYFILL_REQUIRED = void 0;
4
4
  exports.validateSsjs = validateSsjs;
5
5
  const types_js_1 = require("../types.cjs");
6
6
  const types_js_2 = require("../types.cjs");
@@ -75,6 +75,24 @@ exports.DIAG_CODE_SSJS_INVALID_ARITY = 'ssjs/invalid-arity';
75
75
  // Error (every tested invocation fails at runtime). Mirrors the
76
76
  // `ssjs-no-nonfunctional-method` rule.
77
77
  exports.DIAG_CODE_SSJS_NONFUNCTIONAL_METHOD = 'ssjs/nonfunctional-method';
78
+ // Reliance on switch fall-through, which the SFMC SSJS engine does not implement:
79
+ // an empty leading `case` label does not share the next label's body, and a
80
+ // break-less case body does not cascade into the following case. Each case runs
81
+ // only its own statements up to the next case/default. Mirrors the
82
+ // `ssjs-no-switch-fallthrough` rule.
83
+ exports.DIAG_CODE_SSJS_SWITCH_FALLTHROUGH = 'ssjs/switch-fallthrough';
84
+ // `new X()` where X is a user-defined constructor whose body `return`s an object
85
+ // literal. The SFMC engine returns the empty `this` and silently discards the
86
+ // returned object, so the members the caller expects are `undefined`; calling
87
+ // one of them as a function then aborts the CloudPage. LSP-only (no eslint
88
+ // mirror) — the whole-document function map is needed to resolve the callee.
89
+ exports.DIAG_CODE_SSJS_NEW_OBJECT_RETURN = 'ssjs/new-object-returning-constructor';
90
+ // A call in one `<script runat="server">` block to a function whose only
91
+ // declaration is in a LATER block. SSJS executes server blocks in document order
92
+ // over one shared global scope, so a forward cross-block reference throws
93
+ // "Object expected" at runtime. LSP-only — ESLint sees a single block at a time
94
+ // and cannot detect a cross-block forward reference.
95
+ exports.DIAG_CODE_SSJS_CROSS_BLOCK_FORWARD_REF = 'ssjs/cross-block-forward-reference';
78
96
  /**
79
97
  * SSJS diagnostic codes that duplicate eslint-plugin-sfmc rules and can be
80
98
  * suppressed via the `disableLspDiagnosticsForEslintRules` setting:
@@ -91,6 +109,7 @@ exports.DIAG_CODE_SSJS_NONFUNCTIONAL_METHOD = 'ssjs/nonfunctional-method';
91
109
  * - deprecated → `ssjs-no-deprecated-function`
92
110
  * - invalid-arity → `ssjs-platform-function-arity`
93
111
  * - nonfunctional-method → `ssjs-no-nonfunctional-method`
112
+ * - switch-fallthrough → `ssjs-no-switch-fallthrough`
94
113
  */
95
114
  exports.SSJS_ESLINT_DUPLICATE_DIAG_CODES = new Set([
96
115
  exports.DIAG_CODE_SSJS_POLYFILL_REQUIRED,
@@ -107,6 +126,7 @@ exports.SSJS_ESLINT_DUPLICATE_DIAG_CODES = new Set([
107
126
  exports.DIAG_CODE_SSJS_DEPRECATED,
108
127
  exports.DIAG_CODE_SSJS_INVALID_ARITY,
109
128
  exports.DIAG_CODE_SSJS_NONFUNCTIONAL_METHOD,
129
+ exports.DIAG_CODE_SSJS_SWITCH_FALLTHROUGH,
110
130
  ]);
111
131
  /**
112
132
  * Build the `ssjs/polyfill-required` diagnostic message, tailored to whether the
@@ -1019,6 +1039,485 @@ function collectDeprecatedMethodDiagnostics(text, commentRanges, remaining) {
1019
1039
  }
1020
1040
  return diagnostics;
1021
1041
  }
1042
+ /**
1043
+ * Find the matching closing brace for the `{` at `openIndex` in the sanitized
1044
+ * text (strings/comments already blanked so braces inside them do not count).
1045
+ * @param sanitized - String/comment-blanked copy of the document.
1046
+ * @param openIndex - Index of the opening `{`.
1047
+ * @returns Index of the matching `}`, or -1 when unbalanced.
1048
+ */
1049
+ function findMatchingBrace(sanitized, openIndex) {
1050
+ let depth = 0;
1051
+ for (let index = openIndex; index < sanitized.length; index++) {
1052
+ const ch = sanitized[index];
1053
+ if (ch === '{')
1054
+ depth++;
1055
+ else if (ch === '}') {
1056
+ depth--;
1057
+ if (depth === 0)
1058
+ return index;
1059
+ }
1060
+ }
1061
+ return -1;
1062
+ }
1063
+ /**
1064
+ * Split a switch body (the text between its braces) into its top-level
1065
+ * `case`/`default` clauses. Only depth-0 `case`/`default` keywords count, so
1066
+ * labels inside a nested switch/block are not treated as clauses of this one.
1067
+ * @param sanitized - String/comment-blanked copy of the document.
1068
+ * @param bodyStart - Offset just after the switch body's opening `{`.
1069
+ * @param bodyEnd - Offset of the switch body's closing `}`.
1070
+ * @returns The clauses in source order (empty when the switch has none).
1071
+ */
1072
+ function splitSwitchClauses(sanitized, bodyStart, bodyEnd) {
1073
+ const clausePattern = /\b(case|default)\b/g;
1074
+ clausePattern.lastIndex = bodyStart;
1075
+ const keywordOffsets = [];
1076
+ let depth = 0;
1077
+ let index = bodyStart;
1078
+ // Walk char by char, tracking brace depth, and record clause keywords found
1079
+ // only at depth 0 (i.e. directly inside this switch, not a nested block).
1080
+ while (index < bodyEnd) {
1081
+ const ch = sanitized[index];
1082
+ if (ch === '{') {
1083
+ depth++;
1084
+ index++;
1085
+ continue;
1086
+ }
1087
+ if (ch === '}') {
1088
+ depth--;
1089
+ index++;
1090
+ continue;
1091
+ }
1092
+ if (depth === 0 && (ch === 'c' || ch === 'd')) {
1093
+ clausePattern.lastIndex = index;
1094
+ const match = clausePattern.exec(sanitized);
1095
+ if (match && match.index === index) {
1096
+ keywordOffsets.push(index);
1097
+ index += match[0].length;
1098
+ continue;
1099
+ }
1100
+ }
1101
+ index++;
1102
+ }
1103
+ return keywordOffsets.map((keywordOffset, order) => {
1104
+ // The body of a clause starts after its label's colon.
1105
+ const colon = sanitized.indexOf(':', keywordOffset);
1106
+ const bodyStartOffset = colon === -1 ? keywordOffset : colon + 1;
1107
+ const bodyEndOffset = order + 1 < keywordOffsets.length ? keywordOffsets[order + 1] : bodyEnd;
1108
+ return {
1109
+ keywordOffset,
1110
+ bodyStart: bodyStartOffset,
1111
+ bodyEnd: bodyEndOffset,
1112
+ };
1113
+ });
1114
+ }
1115
+ /**
1116
+ * Scan the document for `switch` statements that rely on fall-through, which the
1117
+ * SFMC SSJS engine never performs. Two broken shapes are flagged on every clause
1118
+ * except the last (which has nothing to fall into):
1119
+ * - an EMPTY `case`/`default` label immediately followed by another clause
1120
+ * (stacked-label fall-through), and
1121
+ * - a NON-EMPTY body that does not end in a terminating statement
1122
+ * (`break`/`return`/`throw`/`continue`) before the next clause (cascade
1123
+ * fall-through).
1124
+ * Mirrors the eslint-plugin-sfmc `ssjs-no-switch-fallthrough` rule.
1125
+ * @param text - Full document text.
1126
+ * @param commentRanges - Comment ranges to skip.
1127
+ * @param budget - Maximum number of diagnostics still allowed.
1128
+ * @returns Diagnostics for switch fall-through reliance (length ≤ budget).
1129
+ */
1130
+ function collectSwitchFallthroughDiagnostics(text, commentRanges, budget) {
1131
+ const diagnostics = [];
1132
+ if (budget <= 0)
1133
+ return diagnostics;
1134
+ // Blank strings/comments so braces, colons and keywords inside them are
1135
+ // ignored; offsets stay aligned 1:1 with the original text.
1136
+ const sanitized = blankStringsAndComments(text);
1137
+ const switchPattern = /\bswitch\s*\(/g;
1138
+ let sm;
1139
+ while ((sm = switchPattern.exec(sanitized)) !== null && diagnostics.length < budget) {
1140
+ if ((0, comments_js_1.isInCommentRange)(sm.index, commentRanges))
1141
+ continue;
1142
+ // Find the `{` that opens the switch body (skip the discriminant parens).
1143
+ const braceOpen = sanitized.indexOf('{', sm.index + sm[0].length);
1144
+ if (braceOpen === -1)
1145
+ continue;
1146
+ const braceClose = findMatchingBrace(sanitized, braceOpen);
1147
+ if (braceClose === -1)
1148
+ continue;
1149
+ const clauses = splitSwitchClauses(sanitized, braceOpen + 1, braceClose);
1150
+ const remaining = budget - diagnostics.length;
1151
+ diagnostics.push(...clauseFallthroughDiagnostics(text, sanitized, clauses, remaining));
1152
+ }
1153
+ return diagnostics;
1154
+ }
1155
+ /**
1156
+ * Build fall-through diagnostics for the clauses of a single `switch` body.
1157
+ * Every clause except the last is checked (the last has nothing to fall into).
1158
+ * @param text - Full document text (for offset→position mapping).
1159
+ * @param sanitized - Strings/comments-blanked text (for body inspection).
1160
+ * @param clauses - Clauses of one switch body, in source order.
1161
+ * @param budget - Maximum number of diagnostics to emit.
1162
+ * @returns Diagnostics for clauses relying on fall-through (length ≤ budget).
1163
+ */
1164
+ function clauseFallthroughDiagnostics(text, sanitized, clauses, budget) {
1165
+ const diagnostics = [];
1166
+ // Every clause except the last (nothing follows it to fall into).
1167
+ const nonTerminalClauses = clauses.slice(0, -1);
1168
+ for (const clause of nonTerminalClauses) {
1169
+ if (diagnostics.length >= budget)
1170
+ break;
1171
+ const body = sanitized.slice(clause.bodyStart, clause.bodyEnd);
1172
+ const isEmpty = body.trim().length === 0;
1173
+ const terminates = /\b(?:break|return|throw|continue)\b[^;]*;?\s*$/.test(body.trim());
1174
+ // A non-empty, properly terminated body does not rely on fall-through.
1175
+ if (!isEmpty && terminates)
1176
+ continue;
1177
+ diagnostics.push({
1178
+ severity: types_js_1.DiagnosticSeverity.Warning,
1179
+ range: {
1180
+ start: (0, positions_js_1.offsetToPosition)(text, clause.keywordOffset),
1181
+ end: (0, positions_js_1.offsetToPosition)(text, clause.bodyStart),
1182
+ },
1183
+ message: isEmpty
1184
+ ? 'This empty case relies on fall-through into the next label, but SFMC SSJS ' +
1185
+ 'has no fall-through — the shared body never runs. Give this case its own ' +
1186
+ 'break-terminated body, or use if / a lookup map.'
1187
+ : 'This case body has no terminating break/return/throw, so it relies on ' +
1188
+ 'cascading into the next case — but SFMC SSJS has no fall-through and each ' +
1189
+ 'case runs only its own statements. End every case with break, or use if / ' +
1190
+ 'a lookup map.',
1191
+ source: 'ssjs',
1192
+ code: exports.DIAG_CODE_SSJS_SWITCH_FALLTHROUGH,
1193
+ });
1194
+ }
1195
+ return diagnostics;
1196
+ }
1197
+ /**
1198
+ * Names of the built-in / host constructors that are legitimately used with
1199
+ * `new` and must never be flagged by the object-returning-constructor check,
1200
+ * even in the unlikely event a same-named local function exists.
1201
+ */
1202
+ const NEW_SAFE_BUILTINS = new Set([
1203
+ 'Object',
1204
+ 'Array',
1205
+ 'String',
1206
+ 'Number',
1207
+ 'Boolean',
1208
+ 'Date',
1209
+ 'RegExp',
1210
+ 'Error',
1211
+ 'Function',
1212
+ ]);
1213
+ /**
1214
+ * Determine whether the body of a function declaration/expression contains a
1215
+ * top-level `return { ... }` (a ReturnStatement whose argument is an object
1216
+ * literal). Only the function's own body is inspected — `return {}` inside a
1217
+ * nested function is ignored by tracking brace depth relative to the body.
1218
+ * @param sanitized - String/comment-blanked copy of the document.
1219
+ * @param bodyOpen - Offset of the function body's opening `{`.
1220
+ * @param bodyClose - Offset of the function body's matching `}`.
1221
+ * @returns True when a depth-1 `return {` is found in the body.
1222
+ */
1223
+ function bodyReturnsObjectLiteral(sanitized, bodyOpen, bodyClose) {
1224
+ // Walk the body looking for `return` keywords that sit directly in the
1225
+ // function body (depth 1 relative to bodyOpen), whose next non-space token
1226
+ // is `{`. A `return {` nested inside another function/block is at a deeper
1227
+ // depth and is skipped so we only judge THIS constructor's return value.
1228
+ const returnPattern = /\breturn\b/g;
1229
+ returnPattern.lastIndex = bodyOpen + 1;
1230
+ let match;
1231
+ while ((match = returnPattern.exec(sanitized)) !== null) {
1232
+ if (match.index >= bodyClose)
1233
+ break;
1234
+ // Compute brace depth between bodyOpen and this return.
1235
+ let depth = 0;
1236
+ for (let index = bodyOpen; index < match.index; index++) {
1237
+ const ch = sanitized[index];
1238
+ if (ch === '{')
1239
+ depth++;
1240
+ else if (ch === '}')
1241
+ depth--;
1242
+ }
1243
+ // depth 1 === directly inside the function body (not a nested block/fn).
1244
+ if (depth !== 1)
1245
+ continue;
1246
+ // Next non-whitespace character after `return` must be `{` (object literal).
1247
+ let cursor = match.index + 'return'.length;
1248
+ while (cursor < bodyClose && /\s/.test(sanitized[cursor]))
1249
+ cursor++;
1250
+ if (sanitized[cursor] === '{')
1251
+ return true;
1252
+ }
1253
+ return false;
1254
+ }
1255
+ /**
1256
+ * Collect the names of user-defined functions whose body `return`s an object
1257
+ * literal. Matches both `function Name(...) { ... }` declarations and
1258
+ * `var Name = function (...) { ... }` expressions. Uses the sanitized text so
1259
+ * that braces/keywords inside strings and comments are ignored.
1260
+ * @param text - Full document text.
1261
+ * @param sanitized - String/comment-blanked copy of the document.
1262
+ * @param commentRanges - Comment ranges to skip.
1263
+ * @returns Set of function names that return an object literal.
1264
+ */
1265
+ function collectObjectReturningFunctionNames(text, sanitized, commentRanges) {
1266
+ const names = new Set();
1267
+ // `function Name(` (declaration) or `var Name = function(` (expression).
1268
+ const fnPattern = /\bfunction\s+([A-Za-z_$][\w$]*)\s*\(|\b([A-Za-z_$][\w$]*)\s*=\s*function\s*(?:[A-Za-z_$][\w$]*\s*)?\(/g;
1269
+ let match;
1270
+ while ((match = fnPattern.exec(text)) !== null) {
1271
+ if ((0, comments_js_1.isInCommentRange)(match.index, commentRanges))
1272
+ continue;
1273
+ const name = match[1] ?? match[2];
1274
+ if (!name)
1275
+ continue;
1276
+ // Find the function body's opening `{` after the parameter list.
1277
+ const parenOpen = sanitized.indexOf('(', match.index);
1278
+ if (parenOpen === -1)
1279
+ continue;
1280
+ const parenClose = findMatchingParen(sanitized, parenOpen);
1281
+ if (parenClose === -1)
1282
+ continue;
1283
+ const bodyOpen = sanitized.indexOf('{', parenClose);
1284
+ if (bodyOpen === -1)
1285
+ continue;
1286
+ const bodyClose = findMatchingBrace(sanitized, bodyOpen);
1287
+ if (bodyClose === -1)
1288
+ continue;
1289
+ if (bodyReturnsObjectLiteral(sanitized, bodyOpen, bodyClose)) {
1290
+ names.add(name);
1291
+ }
1292
+ }
1293
+ return names;
1294
+ }
1295
+ /**
1296
+ * Find the matching closing paren for the `(` at `openIndex` in sanitized text.
1297
+ * @param sanitized - String/comment-blanked copy of the document.
1298
+ * @param openIndex - Index of the opening `(`.
1299
+ * @returns Index of the matching `)`, or -1 when unbalanced.
1300
+ */
1301
+ function findMatchingParen(sanitized, openIndex) {
1302
+ let depth = 0;
1303
+ for (let index = openIndex; index < sanitized.length; index++) {
1304
+ const ch = sanitized[index];
1305
+ if (ch === '(')
1306
+ depth++;
1307
+ else if (ch === ')') {
1308
+ depth--;
1309
+ if (depth === 0)
1310
+ return index;
1311
+ }
1312
+ }
1313
+ return -1;
1314
+ }
1315
+ /**
1316
+ * Scan the document for `new X(...)` expressions where `X` is a user-defined
1317
+ * function whose body `return`s an object literal.
1318
+ *
1319
+ * In the SFMC SSJS engine, `new` on such a constructor returns the empty `this`
1320
+ * and silently discards the returned object literal, so the members the caller
1321
+ * expects are `undefined` — and calling one of them as a function later aborts
1322
+ * the page. Built-in constructors (`new Date()` etc.) and constructors that do
1323
+ * not return an object literal are deliberately NOT flagged.
1324
+ * @param text - Full document text.
1325
+ * @param sanitized - String/comment-blanked copy of the document.
1326
+ * @param commentRanges - Comment ranges to skip.
1327
+ * @param budget - Maximum number of diagnostics still allowed.
1328
+ * @returns Diagnostics for object-returning-constructor `new` calls (length ≤ budget).
1329
+ */
1330
+ function collectNewObjectReturnDiagnostics(text, sanitized, commentRanges, budget) {
1331
+ const diagnostics = [];
1332
+ if (budget <= 0)
1333
+ return diagnostics;
1334
+ const objectReturningNames = collectObjectReturningFunctionNames(text, sanitized, commentRanges);
1335
+ if (objectReturningNames.size === 0)
1336
+ return diagnostics;
1337
+ // `new X(` where X is one of the object-returning user functions.
1338
+ const newPattern = /\bnew\s+([A-Za-z_$][\w$]*)\s*\(/g;
1339
+ let match;
1340
+ while ((match = newPattern.exec(text)) !== null && diagnostics.length < budget) {
1341
+ if ((0, comments_js_1.isInCommentRange)(match.index, commentRanges))
1342
+ continue;
1343
+ const calleeName = match[1];
1344
+ if (NEW_SAFE_BUILTINS.has(calleeName))
1345
+ continue;
1346
+ if (!objectReturningNames.has(calleeName))
1347
+ continue;
1348
+ // Highlight the callee name for a focused squiggle.
1349
+ const nameStart = match.index + match[0].indexOf(calleeName);
1350
+ diagnostics.push({
1351
+ severity: types_js_1.DiagnosticSeverity.Warning,
1352
+ range: {
1353
+ start: (0, positions_js_1.offsetToPosition)(text, nameStart),
1354
+ end: (0, positions_js_1.offsetToPosition)(text, nameStart + calleeName.length),
1355
+ },
1356
+ message: `'new ${calleeName}()' calls a constructor that returns an object literal, which the ` +
1357
+ 'SFMC SSJS engine discards — the engine returns the empty `this`, so the returned ' +
1358
+ 'members will be undefined and calling one of them aborts the page. Call ' +
1359
+ `'${calleeName}(...)' without 'new', or assign to 'this.<member>' inside the ` +
1360
+ 'constructor instead of returning an object.',
1361
+ source: 'ssjs',
1362
+ code: exports.DIAG_CODE_SSJS_NEW_OBJECT_RETURN,
1363
+ });
1364
+ }
1365
+ return diagnostics;
1366
+ }
1367
+ /**
1368
+ * Find every `<script runat="server">` block in document order and return the
1369
+ * offsets of each block's body. When the document contains no such tag it is
1370
+ * treated as a single implicit block spanning the whole text (the pure-`.ssjs`
1371
+ * case), so callers can always assume ≥ 1 block.
1372
+ * @param text - Full document text.
1373
+ * @returns Server-script blocks in document order (at least one).
1374
+ */
1375
+ function findServerScriptBlocks(text) {
1376
+ const blocks = [];
1377
+ // `<script ... runat="server" ...>` … `</script>`, case-insensitive, tolerant
1378
+ // of attribute order and single/double quotes around the runat value.
1379
+ const blockPattern = /<script\b[^>]*\brunat\s*=\s*["']server["'][^>]*>([\s\S]*?)<\/script\s*>/gi;
1380
+ let match;
1381
+ while ((match = blockPattern.exec(text)) !== null) {
1382
+ const bodyStart = match.index + match[0].indexOf(match[1], match[0].indexOf('>'));
1383
+ blocks.push({ bodyStart, bodyEnd: bodyStart + match[1].length });
1384
+ }
1385
+ // No explicit tag → the whole document is one implicit SSJS block.
1386
+ if (blocks.length === 0) {
1387
+ blocks.push({ bodyStart: 0, bodyEnd: text.length });
1388
+ }
1389
+ return blocks;
1390
+ }
1391
+ /**
1392
+ * Collect the top-level `function Name(...)` declarations inside a single block
1393
+ * body. Only depth-0 declarations count (a function nested inside another
1394
+ * function is not hoisted to the shared global scope for cross-block use).
1395
+ * @param sanitized - String/comment-blanked copy of the document.
1396
+ * @param block - The block whose body is scanned.
1397
+ * @returns Set of function names declared at the block's top level.
1398
+ */
1399
+ function collectBlockFunctionNames(sanitized, block) {
1400
+ const names = new Set();
1401
+ const fnPattern = /\bfunction\s+([A-Za-z_$][\w$]*)\s*\(/g;
1402
+ fnPattern.lastIndex = block.bodyStart;
1403
+ let match;
1404
+ while ((match = fnPattern.exec(sanitized)) !== null) {
1405
+ if (match.index >= block.bodyEnd)
1406
+ break;
1407
+ // Depth of this declaration relative to the block body start.
1408
+ let depth = 0;
1409
+ for (let index = block.bodyStart; index < match.index; index++) {
1410
+ const ch = sanitized[index];
1411
+ if (ch === '{')
1412
+ depth++;
1413
+ else if (ch === '}')
1414
+ depth--;
1415
+ }
1416
+ if (depth === 0)
1417
+ names.add(match[1]);
1418
+ }
1419
+ return names;
1420
+ }
1421
+ /**
1422
+ * Scan a multi-block SSJS document for a call in one `<script runat="server">`
1423
+ * block to a function whose ONLY declaration lives in a LATER block.
1424
+ *
1425
+ * SSJS executes server blocks in document order over one shared global scope.
1426
+ * A function declared in an earlier block, or in the same block (intra-block
1427
+ * hoisting), resolves fine; a forward cross-block reference throws
1428
+ * "Object expected" at runtime. Only documents with ≥ 2 server blocks can
1429
+ * exhibit this, so single-block (pure `.ssjs`) files never flag.
1430
+ * @param text - Full document text.
1431
+ * @param sanitized - String/comment-blanked copy of the document.
1432
+ * @param commentRanges - Comment ranges to skip.
1433
+ * @param budget - Maximum number of diagnostics still allowed.
1434
+ * @returns Diagnostics for forward cross-block references (length ≤ budget).
1435
+ */
1436
+ function collectCrossBlockForwardRefDiagnostics(text, sanitized, commentRanges, budget) {
1437
+ const diagnostics = [];
1438
+ if (budget <= 0)
1439
+ return diagnostics;
1440
+ const blocks = findServerScriptBlocks(text);
1441
+ // A cross-block forward reference requires at least two blocks.
1442
+ if (blocks.length < 2)
1443
+ return diagnostics;
1444
+ // Per-block top-level function declarations, plus the union of names declared
1445
+ // in THIS block or any EARLIER block (the set that resolves at each block).
1446
+ const perBlockNames = blocks.map((block) => collectBlockFunctionNames(sanitized, block));
1447
+ const declaredUpToBlock = [];
1448
+ const seen = new Set();
1449
+ for (const blockNames of perBlockNames) {
1450
+ for (const name of blockNames)
1451
+ seen.add(name);
1452
+ declaredUpToBlock.push(new Set(seen));
1453
+ }
1454
+ // Names declared anywhere in the document (to distinguish a forward
1455
+ // cross-block ref from an unknown global/local, which we do not flag).
1456
+ const declaredAnywhere = seen;
1457
+ // Scan each block for forward cross-block references, one block at a time.
1458
+ for (const [blockIndex, block] of blocks.entries()) {
1459
+ if (diagnostics.length >= budget)
1460
+ break;
1461
+ const blockDiagnostics = collectBlockForwardRefDiagnostics(text, sanitized, commentRanges, block, declaredUpToBlock[blockIndex], declaredAnywhere, budget - diagnostics.length);
1462
+ diagnostics.push(...blockDiagnostics);
1463
+ }
1464
+ return diagnostics;
1465
+ }
1466
+ /**
1467
+ * Keyword tokens that look like a call (`name(`) but are language constructs,
1468
+ * never a user-function reference, so they must never be flagged.
1469
+ */
1470
+ const FORWARD_REF_SKIP_KEYWORDS = new Set(['function', 'if', 'for', 'while', 'switch']);
1471
+ /**
1472
+ * Scan a single `<script runat="server">` block body for calls whose callee is
1473
+ * declared only in a LATER block. Extracted from
1474
+ * `collectCrossBlockForwardRefDiagnostics` so its `break`/`continue` live in a
1475
+ * single (non-nested) loop.
1476
+ * @param text - Full document text.
1477
+ * @param sanitized - String/comment-blanked copy of the document.
1478
+ * @param commentRanges - Comment ranges to skip.
1479
+ * @param block - The block whose body is scanned.
1480
+ * @param resolvableHere - Function names declared in this or any earlier block.
1481
+ * @param declaredAnywhere - Function names declared anywhere in the document.
1482
+ * @param budget - Maximum number of diagnostics to emit.
1483
+ * @returns Diagnostics for this block's forward references (length ≤ budget).
1484
+ */
1485
+ function collectBlockForwardRefDiagnostics(text, sanitized, commentRanges, block, resolvableHere, declaredAnywhere, budget) {
1486
+ const diagnostics = [];
1487
+ // Match `name(` call sites. A call is flagged only when the callee is a
1488
+ // user function declared somewhere later — never in this or an earlier block.
1489
+ const callPattern = /(?<![.\w$])([A-Za-z_$][\w$]*)\s*\(/g;
1490
+ callPattern.lastIndex = block.bodyStart;
1491
+ let match;
1492
+ while ((match = callPattern.exec(sanitized)) !== null && diagnostics.length < budget) {
1493
+ if (match.index >= block.bodyEnd)
1494
+ break;
1495
+ const name = match[1];
1496
+ // Skip language keywords, calls that resolve here, comments, and names
1497
+ // that are not declared as a user function anywhere in the document.
1498
+ const isForwardRef = !FORWARD_REF_SKIP_KEYWORDS.has(name) &&
1499
+ !(0, comments_js_1.isInCommentRange)(match.index, commentRanges) &&
1500
+ declaredAnywhere.has(name) &&
1501
+ !resolvableHere.has(name);
1502
+ if (!isForwardRef)
1503
+ continue;
1504
+ const nameStart = match.index + match[0].indexOf(name);
1505
+ diagnostics.push({
1506
+ severity: types_js_1.DiagnosticSeverity.Error,
1507
+ range: {
1508
+ start: (0, positions_js_1.offsetToPosition)(text, nameStart),
1509
+ end: (0, positions_js_1.offsetToPosition)(text, nameStart + name.length),
1510
+ },
1511
+ message: `'${name}()' is declared in a later <script runat="server"> block. SSJS ` +
1512
+ 'executes server blocks in document order over one shared scope, so this ' +
1513
+ 'forward reference throws "Object expected" at runtime. Move the declaration ' +
1514
+ 'to this block or an earlier one.',
1515
+ source: 'ssjs',
1516
+ code: exports.DIAG_CODE_SSJS_CROSS_BLOCK_FORWARD_REF,
1517
+ });
1518
+ }
1519
+ return diagnostics;
1520
+ }
1022
1521
  /**
1023
1522
  * Validate an SSJS document and return LSP Diagnostics.
1024
1523
  * @param text - Full document text.
@@ -1471,6 +1970,31 @@ function validateSsjs(text, settings = types_js_2.DEFAULT_SETTINGS) {
1471
1970
  problems += nonFunctionalDiagnostics.length;
1472
1971
  diagnostics.push(...nonFunctionalDiagnostics);
1473
1972
  }
1973
+ // 4h. switch statements that rely on fall-through, which the SFMC SSJS engine
1974
+ // never performs (empty stacked labels and break-less bodies both fail).
1975
+ // Reported as a Warning. Skipped in MCN (SSJS unsupported there anyway).
1976
+ if (settings.targetPlatform !== 'next' && problems < max) {
1977
+ const switchDiagnostics = collectSwitchFallthroughDiagnostics(text, commentRanges, max - problems);
1978
+ problems += switchDiagnostics.length;
1979
+ diagnostics.push(...switchDiagnostics);
1980
+ }
1981
+ // 4i. `new X()` where X is a user constructor that returns an object literal
1982
+ // (the engine discards the returned object and returns the empty `this`), and
1983
+ // 4j. a call to a function whose only declaration is in a LATER
1984
+ // `<script runat="server">` block (a forward cross-block reference). Both need
1985
+ // the string/comment-blanked copy so braces/keywords inside strings and
1986
+ // comments are ignored. Skipped in MCN (SSJS unsupported there anyway).
1987
+ if (settings.targetPlatform !== 'next' && problems < max) {
1988
+ const sanitizedForScope = blankStringsAndComments(text);
1989
+ const newObjectReturnDiagnostics = collectNewObjectReturnDiagnostics(text, sanitizedForScope, commentRanges, max - problems);
1990
+ problems += newObjectReturnDiagnostics.length;
1991
+ diagnostics.push(...newObjectReturnDiagnostics);
1992
+ if (problems < max) {
1993
+ const forwardRefDiagnostics = collectCrossBlockForwardRefDiagnostics(text, sanitizedForScope, commentRanges, max - problems);
1994
+ problems += forwardRefDiagnostics.length;
1995
+ diagnostics.push(...forwardRefDiagnostics);
1996
+ }
1997
+ }
1474
1998
  // MCN compatibility — SSJS is not supported in Marketing Cloud Next.
1475
1999
  // Emit one document-level diagnostic covering the first non-empty line.
1476
2000
  if (settings.targetPlatform === 'next' && problems < max) {
@@ -14,6 +14,9 @@ export declare const DIAG_CODE_SSJS_NONEXISTENT_GLOBAL = "ssjs/nonexistent-globa
14
14
  export declare const DIAG_CODE_SSJS_DEPRECATED = "ssjs/deprecated";
15
15
  export declare const DIAG_CODE_SSJS_INVALID_ARITY = "ssjs/invalid-arity";
16
16
  export declare const DIAG_CODE_SSJS_NONFUNCTIONAL_METHOD = "ssjs/nonfunctional-method";
17
+ export declare const DIAG_CODE_SSJS_SWITCH_FALLTHROUGH = "ssjs/switch-fallthrough";
18
+ export declare const DIAG_CODE_SSJS_NEW_OBJECT_RETURN = "ssjs/new-object-returning-constructor";
19
+ export declare const DIAG_CODE_SSJS_CROSS_BLOCK_FORWARD_REF = "ssjs/cross-block-forward-reference";
17
20
  /**
18
21
  * SSJS diagnostic codes that duplicate eslint-plugin-sfmc rules and can be
19
22
  * suppressed via the `disableLspDiagnosticsForEslintRules` setting:
@@ -30,6 +33,7 @@ export declare const DIAG_CODE_SSJS_NONFUNCTIONAL_METHOD = "ssjs/nonfunctional-m
30
33
  * - deprecated → `ssjs-no-deprecated-function`
31
34
  * - invalid-arity → `ssjs-platform-function-arity`
32
35
  * - nonfunctional-method → `ssjs-no-nonfunctional-method`
36
+ * - switch-fallthrough → `ssjs-no-switch-fallthrough`
33
37
  */
34
38
  export declare const SSJS_ESLINT_DUPLICATE_DIAG_CODES: Set<string>;
35
39
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"ssjs.d.ts","sourceRoot":"","sources":["../../../src/validators/ssjs.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAkChD,eAAO,MAAM,gCAAgC,2BAA2B,CAAC;AACzE,eAAO,MAAM,gCAAgC,2BAA2B,CAAC;AAIzE,eAAO,MAAM,6CAA6C,wCAAwC,CAAC;AAGnG,eAAO,MAAM,oCAAoC,+BAA+B,CAAC;AAGjF,eAAO,MAAM,oCAAoC,+BAA+B,CAAC;AAIjF,eAAO,MAAM,iCAAiC,4BAA4B,CAAC;AAK3E,eAAO,MAAM,gCAAgC,2BAA2B,CAAC;AAMzE,eAAO,MAAM,iCAAiC,4BAA4B,CAAC;AAK3E,eAAO,MAAM,oCAAoC,qCAAqC,CAAC;AAMvF,eAAO,MAAM,sCAAsC,iCAAiC,CAAC;AAIrF,eAAO,MAAM,iCAAiC,4BAA4B,CAAC;AAI3E,eAAO,MAAM,yBAAyB,oBAAoB,CAAC;AAM3D,eAAO,MAAM,4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