@onlyflows/servicenow-mcp 2.3.0-rc.3 → 2.4.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/CHANGELOG.md +138 -0
  2. package/README.md +206 -22
  3. package/dist/atf-result-cache.d.ts +2 -2
  4. package/dist/call-metrics.d.ts +11 -1
  5. package/dist/call-metrics.d.ts.map +1 -1
  6. package/dist/call-metrics.js +2 -0
  7. package/dist/call-metrics.js.map +1 -1
  8. package/dist/client.d.ts +10 -0
  9. package/dist/client.d.ts.map +1 -1
  10. package/dist/client.js +31 -3
  11. package/dist/client.js.map +1 -1
  12. package/dist/execution-context.d.ts +3 -3
  13. package/dist/execution-context.d.ts.map +1 -1
  14. package/dist/execution-context.js +7 -2
  15. package/dist/execution-context.js.map +1 -1
  16. package/dist/field-policy.d.ts +8 -0
  17. package/dist/field-policy.d.ts.map +1 -1
  18. package/dist/field-policy.js +239 -46
  19. package/dist/field-policy.js.map +1 -1
  20. package/dist/hidden-values.d.ts +368 -21
  21. package/dist/hidden-values.d.ts.map +1 -1
  22. package/dist/hidden-values.js +1050 -101
  23. package/dist/hidden-values.js.map +1 -1
  24. package/dist/http-observability.js +3 -1
  25. package/dist/http-observability.js.map +1 -1
  26. package/dist/inert-text.d.ts +27 -0
  27. package/dist/inert-text.d.ts.map +1 -0
  28. package/dist/inert-text.js +57 -0
  29. package/dist/inert-text.js.map +1 -0
  30. package/dist/policy-card.d.ts +1 -1
  31. package/dist/policy-card.d.ts.map +1 -1
  32. package/dist/policy-card.js +3 -1
  33. package/dist/policy-card.js.map +1 -1
  34. package/dist/setup-prompts.js +1 -0
  35. package/dist/setup-prompts.js.map +1 -1
  36. package/dist/setup.js +6 -0
  37. package/dist/setup.js.map +1 -1
  38. package/dist/tool-error.d.ts +39 -3
  39. package/dist/tool-error.d.ts.map +1 -1
  40. package/dist/tool-error.js +101 -2
  41. package/dist/tool-error.js.map +1 -1
  42. package/dist/tool-table-access.d.ts.map +1 -1
  43. package/dist/tool-table-access.js +5 -0
  44. package/dist/tool-table-access.js.map +1 -1
  45. package/dist/tools/aggregate.d.ts +8 -0
  46. package/dist/tools/aggregate.d.ts.map +1 -1
  47. package/dist/tools/aggregate.js +70 -11
  48. package/dist/tools/aggregate.js.map +1 -1
  49. package/dist/tools/atf-contracts.d.ts +9 -9
  50. package/dist/tools/catalog.d.ts +2 -2
  51. package/dist/tools/catalog.d.ts.map +1 -1
  52. package/dist/tools/catalog.js +9 -0
  53. package/dist/tools/catalog.js.map +1 -1
  54. package/dist/tools/envelope-text-fit.d.ts +20 -0
  55. package/dist/tools/envelope-text-fit.d.ts.map +1 -0
  56. package/dist/tools/envelope-text-fit.js +33 -0
  57. package/dist/tools/envelope-text-fit.js.map +1 -0
  58. package/dist/tools/flow-view-mermaid.d.ts.map +1 -1
  59. package/dist/tools/flow-view-mermaid.js +6 -13
  60. package/dist/tools/flow-view-mermaid.js.map +1 -1
  61. package/dist/tools/flow-view-module.js +1 -1
  62. package/dist/tools/get-module.js +1 -1
  63. package/dist/tools/history-contracts.d.ts +198 -0
  64. package/dist/tools/history-contracts.d.ts.map +1 -0
  65. package/dist/tools/history-contracts.js +317 -0
  66. package/dist/tools/history-contracts.js.map +1 -0
  67. package/dist/tools/history-module.d.ts +158 -0
  68. package/dist/tools/history-module.d.ts.map +1 -0
  69. package/dist/tools/history-module.js +937 -0
  70. package/dist/tools/history-module.js.map +1 -0
  71. package/dist/tools/history-renderers.d.ts +32 -0
  72. package/dist/tools/history-renderers.d.ts.map +1 -0
  73. package/dist/tools/history-renderers.js +154 -0
  74. package/dist/tools/history-renderers.js.map +1 -0
  75. package/dist/tools/index.d.ts +3 -3
  76. package/dist/tools/index.d.ts.map +1 -1
  77. package/dist/tools/index.js +31 -14
  78. package/dist/tools/index.js.map +1 -1
  79. package/dist/tools/platform-view-contracts.d.ts +4 -4
  80. package/dist/tools/platform-view-contracts.d.ts.map +1 -1
  81. package/dist/tools/platform-view-contracts.js +3 -0
  82. package/dist/tools/platform-view-contracts.js.map +1 -1
  83. package/dist/tools/platform-view-evaluate.d.ts +7 -2
  84. package/dist/tools/platform-view-evaluate.d.ts.map +1 -1
  85. package/dist/tools/platform-view-evaluate.js +44 -130
  86. package/dist/tools/platform-view-evaluate.js.map +1 -1
  87. package/dist/tools/platform-view-module.d.ts +12 -3
  88. package/dist/tools/platform-view-module.d.ts.map +1 -1
  89. package/dist/tools/platform-view-module.js +61 -16
  90. package/dist/tools/platform-view-module.js.map +1 -1
  91. package/dist/tools/platform-view-payload.d.ts +101 -0
  92. package/dist/tools/platform-view-payload.d.ts.map +1 -0
  93. package/dist/tools/platform-view-payload.js +302 -0
  94. package/dist/tools/platform-view-payload.js.map +1 -0
  95. package/dist/tools/platform-view-update-sets.d.ts +129 -0
  96. package/dist/tools/platform-view-update-sets.d.ts.map +1 -0
  97. package/dist/tools/platform-view-update-sets.js +1060 -0
  98. package/dist/tools/platform-view-update-sets.js.map +1 -0
  99. package/dist/tools/query-module.js +1 -1
  100. package/dist/tools/relationships-map.d.ts +59 -0
  101. package/dist/tools/relationships-map.d.ts.map +1 -0
  102. package/dist/tools/relationships-map.js +162 -0
  103. package/dist/tools/relationships-map.js.map +1 -0
  104. package/dist/tools/relationships-renderer.d.ts +22 -0
  105. package/dist/tools/relationships-renderer.d.ts.map +1 -0
  106. package/dist/tools/relationships-renderer.js +90 -0
  107. package/dist/tools/relationships-renderer.js.map +1 -0
  108. package/dist/tools/relationships.d.ts +37 -2
  109. package/dist/tools/relationships.d.ts.map +1 -1
  110. package/dist/tools/relationships.js +602 -183
  111. package/dist/tools/relationships.js.map +1 -1
  112. package/dist/tools/result-envelope.d.ts +314 -15
  113. package/dist/tools/result-envelope.d.ts.map +1 -1
  114. package/dist/tools/result-envelope.js +120 -19
  115. package/dist/tools/result-envelope.js.map +1 -1
  116. package/dist/tools/syslog.d.ts +1 -1
  117. package/dist/tools/table-hierarchy.d.ts +17 -0
  118. package/dist/tools/table-hierarchy.d.ts.map +1 -1
  119. package/dist/tools/table-hierarchy.js +41 -0
  120. package/dist/tools/table-hierarchy.js.map +1 -1
  121. package/dist/version.d.ts +1 -1
  122. package/dist/version.js +1 -1
  123. package/docs/CLIENT-SETUP.md +2 -2
  124. package/docs/CROSS-CLIENT-RELEASE-MATRIX.md +2 -2
  125. package/docs/PRODUCTION-SECURITY.md +145 -2
  126. package/docs/RELEASE-VALIDATION.md +2 -2
  127. package/docs/TESTING-OAUTH.md +1 -1
  128. package/package.json +2 -2
  129. package/server.json +2 -2
@@ -14,6 +14,9 @@
14
14
  * ONE instance-wide `sys_dictionary` read (fields of those types only),
15
15
  * projected over each table's extension chain, with database views
16
16
  * resolved to the tables they join;
17
+ * - {@link loadFieldTypesInPlan}, the same answer from reads a tool declares
18
+ * in its own plan (`sys_db_object` one level at a time, and
19
+ * `sys_dictionary`), for tools whose type lookup must stay inside it;
17
20
  * - {@link classifyField}, the per-field verdict (including dot-walks) with a
18
21
  * reason, for tools that show a value-hidden marker instead of dropping;
19
22
  * - {@link withoutFields}, whole-field removal for every response shape;
@@ -21,7 +24,10 @@
21
24
  *
22
25
  * The loader never returns an empty map for "could not read": an unreadable
23
26
  * dictionary is the explicit `unavailable` state, and a table it could not
24
- * resolve has no entry (so every field on it is `unknown_type`).
27
+ * resolve has no entry (so every field on it is `unknown_type`). A table
28
+ * resolves only when its whole extension chain is known ({@link TableChain}):
29
+ * a chain that may stop short could hide that the table inherits a
30
+ * hidden-typed field.
25
31
  *
26
32
  * The scope at the bottom carries one call's resolved sets to field policy,
27
33
  * which enforces them; see `field-policy.ts`.
@@ -29,18 +35,30 @@
29
35
  * @module hidden-values
30
36
  */
31
37
  Object.defineProperty(exports, "__esModule", { value: true });
32
- exports.FieldTypesConfigurationError = exports.FIELD_TYPES_UNAVAILABLE_MESSAGE = exports.MAX_HIDDEN_DICTIONARY_ROWS = exports.FIELD_TYPES_UNAVAILABLE_TTL_MS = exports.FIELD_TYPES_TTL_MS = exports.FIELD_TYPES_UNAVAILABLE = exports.HIDDEN_FIELD_TYPES = void 0;
38
+ exports.FieldTypesConfigurationError = exports.FIELD_TYPES_UNAVAILABLE_MESSAGE = exports.PLAN_CHAIN_LEVELS = exports.PLAN_FIELD_TYPE_DOT_WALKS = exports.PLAN_FIELD_TYPE_FIELDS = exports.FIELD_TYPES_RETRY_PAUSE_MS = exports.MAX_HIDDEN_DICTIONARY_ROWS = exports.FIELD_TYPES_UNAVAILABLE_TTL_MS = exports.FIELD_TYPES_TTL_MS = exports.FIELD_TYPES_UNAVAILABLE = exports.HIDDEN_FIELD_TYPES = void 0;
33
39
  exports.isHiddenFieldType = isHiddenFieldType;
40
+ exports.fieldTypesUnavailable = fieldTypesUnavailable;
34
41
  exports.hiddenTypedFields = hiddenTypedFields;
35
42
  exports.classifyField = classifyField;
36
43
  exports.fieldTypesFromRows = fieldTypesFromRows;
37
44
  exports.withoutFields = withoutFields;
38
45
  exports.rowValueRule = rowValueRule;
39
46
  exports.rowValueHidden = rowValueHidden;
47
+ exports.tableChainFields = tableChainFields;
48
+ exports.tableChainFromRow = tableChainFromRow;
49
+ exports.classifyReadFailure = classifyReadFailure;
50
+ exports.retryTransientOnce = retryTransientOnce;
40
51
  exports.loadFieldTypes = loadFieldTypes;
52
+ exports.loadFieldTypesInPlan = loadFieldTypesInPlan;
53
+ exports.planChainOf = planChainOf;
41
54
  exports.runWithHiddenFieldScope = runWithHiddenFieldScope;
42
55
  exports.currentHiddenFieldScope = currentHiddenFieldScope;
43
56
  exports.hiddenFieldScope = hiddenFieldScope;
57
+ exports.fieldTypesPlanDenialText = fieldTypesPlanDenialText;
58
+ exports.fieldTypesProblemText = fieldTypesProblemText;
59
+ exports.planHierarchyProblem = planHierarchyProblem;
60
+ exports.planTypesProblem = planTypesProblem;
61
+ exports.fieldTypesRefusal = fieldTypesRefusal;
44
62
  exports.validateFieldTypesConfig = validateFieldTypesConfig;
45
63
  exports.fieldTypesConfigFromEnvironment = fieldTypesConfigFromEnvironment;
46
64
  exports.dictionaryNotRequired = dictionaryNotRequired;
@@ -49,6 +67,7 @@ const node_async_hooks_1 = require("node:async_hooks");
49
67
  const client_js_1 = require("./client.js");
50
68
  const credential_tables_js_1 = require("./credential-tables.js");
51
69
  const metadata_cache_js_1 = require("./metadata-cache.js");
70
+ const tool_error_js_1 = require("./tool-error.js");
52
71
  /**
53
72
  * Internal types whose stored values are never returned. `password` and
54
73
  * `password2` are the ones found on instances; `masked` and `encrypted_text`
@@ -65,7 +84,18 @@ const HIDDEN_TYPE_SET = new Set(exports.HIDDEN_FIELD_TYPES);
65
84
  function isHiddenFieldType(type) {
66
85
  return typeof type === "string" && HIDDEN_TYPE_SET.has(type.trim().toLowerCase());
67
86
  }
87
+ /** The cause-less unavailable state: a loader (or a test double) that does not say why. */
68
88
  exports.FIELD_TYPES_UNAVAILABLE = Object.freeze({ state: "unavailable" });
89
+ /** The unavailable state with its cause. */
90
+ function fieldTypesUnavailable(cause, problems) {
91
+ if (cause === undefined && (problems === undefined || problems.size === 0))
92
+ return exports.FIELD_TYPES_UNAVAILABLE;
93
+ return Object.freeze({
94
+ state: "unavailable",
95
+ ...(cause === undefined ? {} : { cause }),
96
+ ...(problems === undefined || problems.size === 0 ? {} : { problems }),
97
+ });
98
+ }
69
99
  /**
70
100
  * The hidden-typed fields of `table`, or undefined when `table` could not be
71
101
  * resolved (or the types are unavailable). Undefined means unknown: a caller
@@ -82,7 +112,9 @@ function hiddenTypedFields(types, table) {
82
112
  * A dot-walked path (`caller_id.user_password`) is decided on the table it
83
113
  * ends at, for both the type and the credential-table check; each hop's
84
114
  * target comes from `referenceTarget`, and a hop it cannot resolve makes the
85
- * path `unknown_type`. Field policy rejects dot-walked names outright today;
115
+ * path `unknown_type`, as does a table that is not in `types` (a loader or
116
+ * {@link fieldTypesFromRows} leaves out every table whose chain is not
117
+ * complete). Field policy rejects dot-walked names outright today;
86
118
  * this is for tools that read paths from the instance (history, payloads).
87
119
  */
88
120
  function classifyField(types, table, path, options = {}) {
@@ -134,9 +166,11 @@ function classifyField(types, table, path, options = {}) {
134
166
  /**
135
167
  * Field types from dictionary rows the caller has already read, so the read
136
168
  * stays inside that caller's own declared plan. `hierarchies` maps each table
137
- * the caller will ask about to its chain (the table first). With
138
- * `complete: true` the rows are every field of those chains, so a field with
139
- * no row is `unknown_type`; otherwise only hidden-typed rows matter.
169
+ * the caller will ask about to its chain (the table first) and whether that
170
+ * chain is complete; a table whose chain is not complete is left unresolved,
171
+ * so every field on it is `unknown_type`. With `complete: true` the rows are
172
+ * every field of those chains, so a field with no row is `unknown_type`;
173
+ * otherwise only hidden-typed rows matter.
140
174
  */
141
175
  function fieldTypesFromRows(rows, hierarchies, options = {}) {
142
176
  const byTable = new Map();
@@ -155,8 +189,10 @@ function fieldTypesFromRows(rows, hierarchies, options = {}) {
155
189
  const tables = new Map();
156
190
  for (const [name, chain] of Object.entries(hierarchies)) {
157
191
  const table = normalizeName(name);
158
- const hierarchy = chain.map(normalizeName);
159
- if (table === undefined || hierarchy.length === 0 || hierarchy.some((entry) => entry === undefined)) {
192
+ if (table === undefined || chain?.complete !== true || !Array.isArray(chain.tables))
193
+ continue;
194
+ const hierarchy = chain.tables.map(normalizeName);
195
+ if (hierarchy.length === 0 || hierarchy.some((entry) => entry === undefined)) {
160
196
  continue;
161
197
  }
162
198
  const all = new Map();
@@ -251,6 +287,90 @@ function typeText(candidate) {
251
287
  }
252
288
  return undefined;
253
289
  }
290
+ /** The stored parent reference of the table `hops` levels up a `sys_db_object` row's chain. */
291
+ function parentLinkField(hops) {
292
+ return `${"super_class.".repeat(hops)}super_class`;
293
+ }
294
+ /** That parent's name, dot-walked. */
295
+ function parentNameField(hops) {
296
+ return `${"super_class.".repeat(hops)}super_class.name`;
297
+ }
298
+ /**
299
+ * The `sys_db_object` fields that give a chain of up to `maxTables` tables in
300
+ * one read of the table's own row: its name, then, for each table of the
301
+ * chain, its stored parent reference and that parent's name (dot-walked).
302
+ * The last table's reference is read without a name, to tell a chain that
303
+ * ends there from one that goes on past the read.
304
+ */
305
+ function tableChainFields(maxTables) {
306
+ const fields = ["name"];
307
+ for (let hops = 0; hops < maxTables; hops += 1) {
308
+ fields.push(parentLinkField(hops));
309
+ if (hops < maxTables - 1)
310
+ fields.push(parentNameField(hops));
311
+ }
312
+ return fields;
313
+ }
314
+ /**
315
+ * The chain of `table` from its `sys_db_object` row, read with
316
+ * {@link tableChainFields}`(maxTables)`. Only an empty reference with an
317
+ * empty name ends a chain; see {@link TableChain.complete}.
318
+ */
319
+ function tableChainFromRow(row, table, maxTables) {
320
+ const tables = [table];
321
+ const chain = (complete, gap) => Object.freeze({
322
+ tables: Object.freeze(tables),
323
+ complete,
324
+ ...(complete || gap === undefined ? {} : { gap }),
325
+ });
326
+ for (let hops = 0; hops < maxTables; hops += 1) {
327
+ if (hops === maxTables - 1) {
328
+ // The last table read: its reference alone says whether the chain ends
329
+ // there or goes on past the read.
330
+ const link = fieldText(row, parentLinkField(hops));
331
+ if (link === undefined)
332
+ return chain(false, "malformed");
333
+ return link.trim() === "" ? chain(true) : chain(false, "too_long");
334
+ }
335
+ const step = parentStepOf(row, parentLinkField(hops), parentNameField(hops));
336
+ if ("gap" in step)
337
+ return chain(false, step.gap);
338
+ if (step.parent === null)
339
+ return chain(true);
340
+ // A loop.
341
+ if (tables.includes(step.parent))
342
+ return chain(false, "malformed");
343
+ tables.push(step.parent);
344
+ }
345
+ return chain(false, "too_long");
346
+ }
347
+ /**
348
+ * One parent link of a `sys_db_object` row: the parent's name, `null` when
349
+ * the table extends nothing, or the gap when the row does not say. Both
350
+ * fields must be present: an absent one is unknown, never empty.
351
+ */
352
+ function parentStepOf(row, linkField, nameField) {
353
+ const link = fieldText(row, linkField);
354
+ const name = fieldText(row, nameField);
355
+ if (link === undefined || name === undefined)
356
+ return { gap: "malformed" };
357
+ const linkEmpty = link.trim() === "";
358
+ const parent = name.trim().toLowerCase();
359
+ if (linkEmpty && parent === "")
360
+ return { parent: null };
361
+ // A name with no reference is unknown.
362
+ if (linkEmpty)
363
+ return { gap: "malformed" };
364
+ // A reference whose name did not come back: the parent's row is hidden from
365
+ // this account.
366
+ if (parent === "")
367
+ return { gap: "parent_unreadable" };
368
+ return FIELD_NAME.test(parent) ? { parent } : { gap: "malformed" };
369
+ }
370
+ /** A field's stored text, or undefined when the row does not carry it as text. */
371
+ function fieldText(row, field) {
372
+ return Object.hasOwn(row, field) ? storedText(row[field]) : undefined;
373
+ }
254
374
  // ── Loader ─────────────────────────────────────────────────────────
255
375
  /**
256
376
  * How long a loaded map serves without any request. A field that becomes
@@ -259,10 +379,19 @@ function typeText(candidate) {
259
379
  * profile's metadata-cache TTL.
260
380
  */
261
381
  exports.FIELD_TYPES_TTL_MS = 60 * 60 * 1000;
262
- /** How long an unreadable dictionary is remembered before it is retried. */
382
+ /**
383
+ * How long a refused or cut-short dictionary, or a chain that does not show
384
+ * where it ends, is remembered before it is read again. A transient failure
385
+ * (a timeout, a 5xx, a network error) is never remembered.
386
+ */
263
387
  exports.FIELD_TYPES_UNAVAILABLE_TTL_MS = 30 * 1000;
264
388
  /** A read that returns this many rows may be cut short, so it is unavailable. */
265
389
  exports.MAX_HIDDEN_DICTIONARY_ROWS = 10_000;
390
+ /**
391
+ * The pause before the one retry of a read that timed out or returned a 5xx
392
+ * the client does not retry itself. Short: the retry is for a blip, not an outage.
393
+ */
394
+ exports.FIELD_TYPES_RETRY_PAUSE_MS = 300;
266
395
  const MAX_HIERARCHY_DEPTH = 12;
267
396
  const MAX_VIEW_SOURCE_ROWS = 1_000;
268
397
  const MAX_DOT_WALK_HOPS = 8;
@@ -270,24 +399,171 @@ const FIELD_NAME = /^[a-z][a-z0-9_]{0,79}$/u;
270
399
  const DICTIONARY_MEMO_KEY = "hidden-values:dictionary:v1";
271
400
  const TABLE_MEMO_PREFIX = "hidden-values:table:v1:";
272
401
  const CHAIN_FLIGHT_PREFIX = "hidden-values:chain-read:v1:";
402
+ /**
403
+ * The table every chain read also asks for: the row of `sys_db_object`
404
+ * itself. When it comes back, the read could see the table's rows, so a table
405
+ * with no row is absent; when it does not, the read showed this user nothing.
406
+ */
407
+ const CHAIN_ANCHOR_TABLE = "sys_db_object";
408
+ function dictionaryUnavailable(cause) {
409
+ return Object.freeze({ unavailable: cause });
410
+ }
411
+ /** What the dictionary memo keeps for a refusal or a full page: the cause, for 30 seconds. */
412
+ function isKeptUnavailable(candidate) {
413
+ if (typeof candidate !== "object" || candidate === null || candidate instanceof Map)
414
+ return false;
415
+ const cause = candidate.unavailable;
416
+ return isReadFailure(cause) && (cause.kind === "refused" || cause.kind === "incomplete");
417
+ }
418
+ function isReadFailure(candidate) {
419
+ if (typeof candidate !== "object" || candidate === null)
420
+ return false;
421
+ const kind = candidate.kind;
422
+ return kind === "policy" || kind === "refused" || kind === "transient" || kind === "incomplete" || kind === "failed";
423
+ }
424
+ function isKnownChain(chain) {
425
+ return Array.isArray(chain);
426
+ }
427
+ /** No row, whether or not the anchor came back: a view may still be behind the name. */
428
+ function hasNoRow(chain) {
429
+ return chain === null || (chain !== undefined && !Array.isArray(chain) && chain.kind === "unconfirmed");
430
+ }
431
+ function incompleteChain(chain) {
432
+ return chain !== undefined && chain !== null && !Array.isArray(chain) && chain.kind === "incomplete"
433
+ ? chain
434
+ : undefined;
435
+ }
436
+ // ── Reading failures ───────────────────────────────────────────────
437
+ /** Errors whose read was tried twice: the classifier then says so. */
438
+ const RETRIED_ERRORS = new WeakSet();
439
+ /**
440
+ * Say why a metadata read threw, from what only this server issued: the
441
+ * trusted error category and reason, and the HTTP status the client recorded.
442
+ * No message or text of the error is read. A cancellation is not a failure to
443
+ * classify: callers rethrow it before they get here.
444
+ */
445
+ function classifyReadFailure(error) {
446
+ const descriptor = (0, tool_error_js_1.trustedToolErrorDescriptor)(error);
447
+ const status = (0, tool_error_js_1.trustedHttpStatus)(error);
448
+ if (descriptor === undefined)
449
+ return Object.freeze({ kind: "failed" });
450
+ // Read again before giving up: by the loader (see retryTransientOnce), or by
451
+ // the client itself, which tries a 502, 503, 504 and a network failure on a
452
+ // GET three times.
453
+ const loaderRetried = typeof error === "object" && error !== null && RETRIED_ERRORS.has(error);
454
+ const clientRetried = descriptor.category === "upstream" &&
455
+ descriptor.reason === undefined &&
456
+ (status === undefined ? descriptor.retry === "retry_if_safe_and_idempotent" : status !== 429 && client_js_1.CLIENT_RETRIED_STATUSES.includes(status));
457
+ const retried = loaderRetried || clientRetried;
458
+ const transient = (extra) => Object.freeze({ kind: "transient", ...extra, ...(retried ? { retried: true } : {}) });
459
+ switch (descriptor.category) {
460
+ case "authentication":
461
+ return Object.freeze({ kind: "refused", status: status ?? 401 });
462
+ case "authorization":
463
+ return Object.freeze({ kind: "refused", status: status ?? 403 });
464
+ case "timeout":
465
+ return transient({ timeout: true });
466
+ case "rate_limit":
467
+ return transient({ status: status ?? 429 });
468
+ case "upstream":
469
+ if (descriptor.reason === "instance_hibernating")
470
+ return transient({});
471
+ if (descriptor.reason !== undefined)
472
+ return Object.freeze({ kind: "failed", ...(status === undefined ? {} : { status }) });
473
+ if (status === undefined) {
474
+ // No status, no reason: the request got no answer, but only a read its
475
+ // issuer allows to be sent again is read as a network failure.
476
+ return descriptor.retry === "retry_if_safe_and_idempotent"
477
+ ? transient({})
478
+ : Object.freeze({ kind: "failed" });
479
+ }
480
+ return status >= 500 ? transient({ status }) : Object.freeze({ kind: "failed", status });
481
+ default:
482
+ return Object.freeze({ kind: "failed", ...(status === undefined ? {} : { status }) });
483
+ }
484
+ }
485
+ /**
486
+ * A read the loader tries once more: it timed out, or returned a 5xx the
487
+ * client does not already retry (500, 501, 505 and above). The client tries a
488
+ * 502, 503, 504 and a network failure three times, so a fourth try 300 ms
489
+ * later is not a blip retry. Never a 429 (the client waits for its
490
+ * Retry-After), a hibernating instance, or anything a retry cannot change (a
491
+ * refusal, a 4xx).
492
+ */
493
+ function isRetryableFailure(error) {
494
+ const failure = classifyReadFailure(error);
495
+ if (failure.kind !== "transient")
496
+ return false;
497
+ if (failure.timeout === true)
498
+ return true;
499
+ const status = failure.status;
500
+ return status !== undefined && status >= 500 && !client_js_1.CLIENT_RETRIED_STATUSES.includes(status);
501
+ }
502
+ /**
503
+ * Run `read`; if it fails the way a blip fails (a timeout, or a 5xx the client
504
+ * does not retry itself: see {@link isRetryableFailure}), wait a short pause
505
+ * and run it once more. A cancellation, an aborted signal, a 429, a 502, 503
506
+ * or 504, a network failure and any 4xx are never retried here, and a
507
+ * cancellation during the pause rethrows.
508
+ *
509
+ * The retry sits inside a single-flight read, so concurrent waiters share one
510
+ * retry. Worst case for one read is two attempts of the client's timeout plus
511
+ * the pause, inside the call's signal: the call's own deadline aborts it, so a
512
+ * retry never outlives the call.
513
+ */
514
+ async function retryTransientOnce(read, options = {}) {
515
+ try {
516
+ return await read();
517
+ }
518
+ catch (error) {
519
+ const signal = options.signal ?? (0, client_js_1.currentServiceNowRequestSignal)();
520
+ if ((0, client_js_1.isServiceNowRequestCancellation)(error) || signal?.aborted === true)
521
+ throw error;
522
+ if (options.budget?.spent === true || !isRetryableFailure(error))
523
+ throw error;
524
+ if (options.budget !== undefined)
525
+ options.budget.spent = true;
526
+ await (0, client_js_1.pauseUnlessServiceNowRequestCancelled)(options.pauseMs ?? exports.FIELD_TYPES_RETRY_PAUSE_MS, signal);
527
+ try {
528
+ return await read();
529
+ }
530
+ catch (second) {
531
+ if (typeof second === "object" && second !== null)
532
+ RETRIED_ERRORS.add(second);
533
+ throw second;
534
+ }
535
+ }
536
+ }
273
537
  /**
274
538
  * Resolve the hidden-typed fields of every table in `tables`.
275
539
  *
276
540
  * Requests, made with the call's own credentials and no table grant (the
277
541
  * implicit metadata path the all-fields projection uses): one instance-wide
278
542
  * `sys_dictionary` read of the hidden types, one `sys_db_object` read for the
279
- * chains of all the tables not yet known, and, only for a name with no
280
- * `sys_db_object` row, one `sys_db_view_table` read (plus the joined tables'
281
- * chains). Each result is kept in the metadata cache's per-credential memo
282
- * (`derivedMetadataMemo`), so a later call that finds everything there makes
283
- * no request at all; the reads skip the cache's watermark, since the memo is
284
- * their cache. The dictionary and chain reads run in parallel, and concurrent
285
- * calls in one scope share each read in flight (one per key). `forceRecache`
286
- * skips the memo.
543
+ * chains of all the tables not yet known (it also asks for `sys_db_object`'s
544
+ * own row, to tell a table that does not exist from a read that showed
545
+ * nothing), and, only for a name with no `sys_db_object` row, one
546
+ * `sys_db_view_table` read (plus the joined tables' chains). Each result is
547
+ * kept in the metadata cache's per-credential memo (`derivedMetadataMemo`), so
548
+ * a later call that finds everything there makes no request at all; the reads
549
+ * skip the cache's watermark, since the memo is their cache. The dictionary
550
+ * and chain reads run in parallel, and concurrent calls in one scope share
551
+ * each read in flight (one per key). `forceRecache` skips the memo.
287
552
  *
288
- * The dictionary read failing, returning no rows, or returning a full page
289
- * gives `unavailable`. A table whose chain or view cannot be resolved is left
290
- * out of `tables`, so its fields are `unknown_type`. A cancelled read rethrows.
553
+ * A dictionary read that fails, returns no rows, or returns a full page gives
554
+ * `unavailable`, with the cause ({@link FieldTypesReadFailure}). A timeout or
555
+ * a 5xx the client does not retry itself (the client tries a 502, 503, 504 and
556
+ * a network failure three times) is read once more after a short pause
557
+ * ({@link retryTransientOnce}); no such failure is ever remembered; a refusal or a full
558
+ * page is remembered for {@link FIELD_TYPES_UNAVAILABLE_TTL_MS}, with its
559
+ * cause. A table whose chain or view cannot be resolved is left out of
560
+ * `tables`, so its fields are `unknown_type`, and `problems` says why: it does
561
+ * not exist, its chain is not complete ({@link TableChain}, such as a parent
562
+ * reference whose name did not come back, or a chain longer than 12 tables),
563
+ * or the read failed. A complete chain is kept in the memo for the hour; an
564
+ * incomplete one for {@link FIELD_TYPES_UNAVAILABLE_TTL_MS}, so a table whose
565
+ * parent cannot be read is not read again on every call. A cancelled read
566
+ * rethrows.
291
567
  */
292
568
  async function loadFieldTypes(client, tablesCandidate, options = {}) {
293
569
  const memo = (0, metadata_cache_js_1.derivedMetadataMemo)(client);
@@ -299,38 +575,64 @@ async function loadFieldTypes(client, tablesCandidate, options = {}) {
299
575
  const requested = [...new Set([...tablesCandidate].map(normalizeName))].filter((name) => name !== undefined);
300
576
  const chains = new Map();
301
577
  const views = new Map();
302
- const remember = (table, entry) => memo?.set(TABLE_MEMO_PREFIX + table, entry, 128 + JSON.stringify(entry).length, exports.FIELD_TYPES_TTL_MS);
578
+ const remember = (table, entry) => memo?.set(TABLE_MEMO_PREFIX + table, entry, 128 + JSON.stringify(entry).length, entry.kind === "incomplete" ? exports.FIELD_TYPES_UNAVAILABLE_TTL_MS : exports.FIELD_TYPES_TTL_MS);
579
+ /** What a read found for `table`, kept: a complete chain for the hour, an incomplete one briefly. */
580
+ const rememberChain = (table, chain) => {
581
+ if (isKnownChain(chain))
582
+ remember(table, Object.freeze({ kind: "table", chain }));
583
+ else {
584
+ const incomplete = incompleteChain(chain);
585
+ if (incomplete !== undefined) {
586
+ remember(table, Object.freeze({ kind: "incomplete", at: incomplete.at, gap: incomplete.gap }));
587
+ }
588
+ }
589
+ };
303
590
  const recall = (table) => {
304
591
  const known = force ? undefined : memo?.get(TABLE_MEMO_PREFIX + table);
305
592
  if (!isTableShape(known))
306
593
  return false;
307
594
  if (known.kind === "table")
308
595
  chains.set(table, known.chain);
596
+ else if (known.kind === "incomplete")
597
+ chains.set(table, Object.freeze({ kind: "incomplete", at: known.at, gap: known.gap }));
309
598
  else {
310
599
  chains.set(table, null);
311
600
  views.set(table, known.sources);
312
601
  }
313
602
  return true;
314
603
  };
604
+ // One retry of the sys_db_object read for the whole lookup, however many
605
+ // reads (the tables', then a view's joined tables') it makes.
606
+ const chainRetry = { spent: false };
315
607
  const pending = requested.filter((table) => !recall(table));
316
608
  // The dictionary and the chains do not depend on each other: one round trip.
317
609
  const [dictionary, read] = await Promise.all([
318
610
  hiddenDictionary(reader, memo, force),
319
611
  pending.length === 0
320
612
  ? Promise.resolve(new Map())
321
- : sharedChains(reader, memo, pending),
613
+ : sharedChains(reader, memo, pending, chainRetry),
322
614
  ]);
323
- if (dictionary === "unavailable")
324
- return exports.FIELD_TYPES_UNAVAILABLE;
615
+ // What the chain read found is kept whether or not the dictionary was read:
616
+ // a refused dictionary must not cost a discarded sys_db_object read on every
617
+ // call. Only a complete chain and an incomplete one are kept, never a failed
618
+ // read, and only for the tables asked for.
619
+ for (const [table, chain] of read) {
620
+ chains.set(table, chain);
621
+ rememberChain(table, chain);
622
+ }
623
+ if (!(dictionary instanceof Map)) {
624
+ return fieldTypesUnavailable(dictionary.unavailable);
625
+ }
626
+ let viewFailure;
627
+ const brokenViews = new Set();
325
628
  if (pending.length > 0) {
326
- for (const [table, chain] of read) {
327
- chains.set(table, chain);
328
- if (chain !== null)
329
- remember(table, Object.freeze({ kind: "table", chain }));
330
- }
331
- const absent = pending.filter((table) => read.get(table) === null);
629
+ const absent = pending.filter((table) => hasNoRow(read.get(table)));
332
630
  if (absent.length > 0) {
333
- for (const [view, sources] of await viewSources(reader, absent)) {
631
+ const found = await viewSources(reader, absent);
632
+ viewFailure = found.failure;
633
+ for (const view of found.broken)
634
+ brokenViews.add(view);
635
+ for (const [view, sources] of found.views) {
334
636
  views.set(view, sources);
335
637
  remember(view, Object.freeze({ kind: "view", sources: Object.freeze(sources) }));
336
638
  }
@@ -339,52 +641,114 @@ async function loadFieldTypes(client, tablesCandidate, options = {}) {
339
641
  // The tables joined by a view need their own chains.
340
642
  const joined = [...new Set([...views.values()].flat().map((source) => source.table))].filter((table) => !chains.has(table) && !recall(table));
341
643
  if (joined.length > 0) {
342
- for (const [table, chain] of await sharedChains(reader, memo, joined)) {
644
+ for (const [table, chain] of await sharedChains(reader, memo, joined, chainRetry)) {
343
645
  chains.set(table, chain);
344
- if (chain !== null)
345
- remember(table, Object.freeze({ kind: "table", chain }));
646
+ rememberChain(table, chain);
346
647
  }
347
648
  }
348
649
  const tables = new Map();
650
+ const problems = new Map();
349
651
  for (const table of requested) {
350
652
  const resolved = resolveTable(table, chains, views, dictionary);
351
- if (resolved !== undefined)
653
+ if (resolved !== undefined) {
352
654
  tables.set(table, resolved);
655
+ continue;
656
+ }
657
+ problems.set(table, problemOf(table, chains, views, viewFailure, brokenViews));
353
658
  }
354
- return Object.freeze({ state: "available", tables });
659
+ return Object.freeze({
660
+ state: "available",
661
+ tables,
662
+ ...(problems.size === 0 ? {} : { problems }),
663
+ });
355
664
  }
665
+ /** Why `table` did not resolve, from what the lookup read. */
666
+ function problemOf(table, chains, views, viewFailure, brokenViews) {
667
+ const chain = chains.get(table);
668
+ if (chain === undefined)
669
+ return Object.freeze({ kind: "read", failure: Object.freeze({ kind: "failed" }) });
670
+ if (!Array.isArray(chain) && chain !== null) {
671
+ const state = chain;
672
+ if (state.kind === "failed")
673
+ return Object.freeze({ kind: "read", failure: state.failure });
674
+ if (state.kind === "incomplete")
675
+ return Object.freeze({ kind: "chain", at: state.at, gap: state.gap });
676
+ }
677
+ if (Array.isArray(chain)) {
678
+ // A complete chain always resolves.
679
+ return Object.freeze({ kind: "read", failure: Object.freeze({ kind: "failed" }) });
680
+ }
681
+ // No sys_db_object row: only a database view resolves.
682
+ const sources = views.get(table);
683
+ if (sources !== undefined && sources.length > 0) {
684
+ for (const source of sources) {
685
+ const sourceChain = chains.get(source.table);
686
+ if (isKnownChain(sourceChain))
687
+ continue;
688
+ const incomplete = incompleteChain(sourceChain);
689
+ if (incomplete !== undefined)
690
+ return Object.freeze({ kind: "chain", at: incomplete.at, gap: incomplete.gap });
691
+ if (sourceChain !== undefined && sourceChain !== null && sourceChain.kind === "failed") {
692
+ return Object.freeze({ kind: "read", failure: sourceChain.failure });
693
+ }
694
+ return Object.freeze({ kind: "chain", at: source.table, gap: "no_row" });
695
+ }
696
+ return Object.freeze({ kind: "read", failure: Object.freeze({ kind: "failed" }) });
697
+ }
698
+ if (brokenViews.has(table)) {
699
+ return Object.freeze({ kind: "read", read: "sys_db_view_table", failure: Object.freeze({ kind: "failed" }) });
700
+ }
701
+ if (viewFailure !== undefined)
702
+ return Object.freeze({ kind: "read", read: "sys_db_view_table", failure: viewFailure });
703
+ // The read showed rows and found neither a table nor a view of this name.
704
+ if (chain === null)
705
+ return Object.freeze({ kind: "not_found" });
706
+ return Object.freeze({
707
+ kind: "read",
708
+ read: "sys_db_object",
709
+ failure: Object.freeze({ kind: "refused", status: 200 }),
710
+ });
711
+ }
712
+ const CHAIN_GAPS = new Set(["parent_unreadable", "too_long", "malformed", "no_row"]);
356
713
  function isTableShape(candidate) {
357
714
  if (typeof candidate !== "object" || candidate === null)
358
715
  return false;
359
716
  const shape = candidate;
360
717
  return ((shape.kind === "table" && Array.isArray(shape.chain)) ||
361
- (shape.kind === "view" && Array.isArray(shape.sources)));
718
+ (shape.kind === "view" && Array.isArray(shape.sources)) ||
719
+ (shape.kind === "incomplete" &&
720
+ typeof shape.at === "string" &&
721
+ FIELD_NAME.test(shape.at) &&
722
+ typeof shape.gap === "string" &&
723
+ CHAIN_GAPS.has(shape.gap)));
362
724
  }
363
725
  function resolveTable(table, chains, views, dictionary) {
364
726
  const chain = chains.get(table);
365
- if (chain === undefined)
366
- return undefined;
367
- if (chain !== null)
727
+ if (isKnownChain(chain))
368
728
  return resolvedTable(chain, inheritedHidden(chain, dictionary));
369
- // No sys_db_object row: only a database view resolves; a view column is
370
- // `<prefix>_<field>` of the table joined under that prefix.
729
+ // Only a table with no sys_db_object row can be a database view; a view
730
+ // column is `<prefix>_<field>` of the table joined under that prefix.
731
+ if (!hasNoRow(chain))
732
+ return undefined;
371
733
  const sources = views.get(table);
372
734
  if (sources === undefined || sources.length === 0)
373
735
  return undefined;
374
736
  const hidden = new Map();
375
737
  const hierarchy = [table];
738
+ const viewSources = [];
376
739
  for (const source of sources) {
377
740
  const sourceChain = chains.get(source.table);
378
- if (sourceChain === undefined || sourceChain === null)
741
+ if (!isKnownChain(sourceChain))
379
742
  return undefined;
380
743
  hierarchy.push(...sourceChain.filter((entry) => !hierarchy.includes(entry)));
744
+ viewSources.push(Object.freeze({ prefix: source.prefix, hierarchy: Object.freeze([...sourceChain]) }));
381
745
  for (const [element, type] of inheritedHidden(sourceChain, dictionary)) {
382
746
  const column = `${source.prefix}_${element}`;
383
747
  if (FIELD_NAME.test(column))
384
748
  hidden.set(column, type);
385
749
  }
386
750
  }
387
- return resolvedTable(hierarchy, hidden);
751
+ return resolvedTable(hierarchy, hidden, undefined, viewSources);
388
752
  }
389
753
  function inheritedHidden(chain, dictionary) {
390
754
  const hidden = new Map();
@@ -396,12 +760,13 @@ function inheritedHidden(chain, dictionary) {
396
760
  }
397
761
  return hidden;
398
762
  }
399
- function resolvedTable(hierarchy, hidden, allTypes) {
763
+ function resolvedTable(hierarchy, hidden, allTypes, viewSources) {
400
764
  return Object.freeze({
401
765
  hierarchy: Object.freeze([...hierarchy]),
402
766
  hidden,
403
767
  hiddenNames: new Set(hidden.keys()),
404
768
  ...(allTypes === undefined ? {} : { allTypes }),
769
+ ...(viewSources === undefined ? {} : { viewSources: Object.freeze([...viewSources]) }),
405
770
  });
406
771
  }
407
772
  /**
@@ -411,8 +776,14 @@ function resolvedTable(hierarchy, hidden, allTypes) {
411
776
  */
412
777
  async function hiddenDictionary(client, memo, force) {
413
778
  const known = force ? undefined : memo?.get(DICTIONARY_MEMO_KEY);
414
- if (known === "unavailable" || known instanceof Map)
779
+ if (known instanceof Map)
780
+ return known;
781
+ // A refusal or a full page kept 30 seconds, with its cause (an older entry
782
+ // without one reads as no cause).
783
+ if (isKeptUnavailable(known))
415
784
  return known;
785
+ if (known === "unavailable")
786
+ return dictionaryUnavailable();
416
787
  return singleFlight(memo, DICTIONARY_MEMO_KEY, () => readDictionary(client, memo));
417
788
  }
418
789
  /**
@@ -443,7 +814,7 @@ async function singleFlight(memo, key, start) {
443
814
  * calls: tables another call is reading are waited for, the rest are read
444
815
  * together in one request.
445
816
  */
446
- async function sharedChains(client, memo, tables) {
817
+ async function sharedChains(client, memo, tables, retry) {
447
818
  const waiting = [];
448
819
  const own = [];
449
820
  for (const table of tables) {
@@ -455,14 +826,14 @@ async function sharedChains(client, memo, tables) {
455
826
  }
456
827
  const chains = new Map();
457
828
  if (own.length > 0) {
458
- const batch = tableChains(client, own);
829
+ const batch = tableChains(client, own, retry);
459
830
  for (const table of own) {
460
831
  memo?.track(CHAIN_FLIGHT_PREFIX + table, batch.then((read) => read.get(table)));
461
832
  }
462
833
  for (const [table, chain] of await batch)
463
834
  chains.set(table, chain);
464
835
  }
465
- const retry = [];
836
+ const rereads = [];
466
837
  for (const [table, pending] of waiting) {
467
838
  try {
468
839
  const chain = await pending;
@@ -470,37 +841,50 @@ async function sharedChains(client, memo, tables) {
470
841
  chains.set(table, chain);
471
842
  }
472
843
  catch {
473
- retry.push(table);
844
+ rereads.push(table);
474
845
  }
475
846
  }
476
- if (retry.length > 0) {
477
- for (const [table, chain] of await tableChains(client, retry))
847
+ if (rereads.length > 0) {
848
+ for (const [table, chain] of await tableChains(client, rereads, retry))
478
849
  chains.set(table, chain);
479
850
  }
480
851
  return chains;
481
852
  }
853
+ /** The failure to keep for a dictionary read that gave no map, and whether it is kept 30 seconds. */
854
+ function rememberedUnavailable(failure) {
855
+ return failure.kind === "refused" || failure.kind === "incomplete";
856
+ }
482
857
  async function readDictionary(client, memo) {
858
+ const unavailable = (failure) => {
859
+ // A refusal or a full page does not change in a moment: kept briefly, with
860
+ // its cause. A transient failure or any other is read again on the next call.
861
+ if (rememberedUnavailable(failure)) {
862
+ memo?.set(DICTIONARY_MEMO_KEY, Object.freeze({ unavailable: failure }), 96, exports.FIELD_TYPES_UNAVAILABLE_TTL_MS);
863
+ }
864
+ return dictionaryUnavailable(failure);
865
+ };
483
866
  let rows;
484
867
  try {
485
- const response = await client.getWithMeta("/api/now/table/sys_dictionary", {
486
- sysparm_query: `internal_typeIN${exports.HIDDEN_FIELD_TYPES.join(",")}` + "^ORDERBYname^ORDERBYelement",
868
+ const response = await retryTransientOnce(() => client.getWithMeta("/api/now/table/sys_dictionary", {
869
+ sysparm_query: `internal_typeIN${exports.HIDDEN_FIELD_TYPES.join(",")}`,
487
870
  sysparm_fields: "name,element,internal_type",
488
871
  sysparm_limit: String(exports.MAX_HIDDEN_DICTIONARY_ROWS),
489
872
  sysparm_display_value: "false",
490
873
  sysparm_exclude_reference_link: "true",
491
- });
492
- rows = response.status === 200 ? response.data?.result : undefined;
874
+ }));
875
+ if (response.status !== 200)
876
+ return unavailable(failedStatus(response.status));
877
+ rows = response.data?.result;
493
878
  }
494
879
  catch (error) {
495
880
  if ((0, client_js_1.isServiceNowRequestCancellation)(error))
496
881
  throw error;
497
- memo?.set(DICTIONARY_MEMO_KEY, "unavailable", 64, exports.FIELD_TYPES_UNAVAILABLE_TTL_MS);
498
- return "unavailable";
882
+ return unavailable(classifyReadFailure(error));
499
883
  }
500
884
  const parsed = parseDictionaryRows(rows);
501
- if (parsed === "unavailable") {
502
- memo?.set(DICTIONARY_MEMO_KEY, "unavailable", 64, exports.FIELD_TYPES_UNAVAILABLE_TTL_MS);
503
- return parsed;
885
+ if (!(parsed instanceof Map)) {
886
+ const cause = parsed.unavailable;
887
+ return unavailable(cause ?? Object.freeze({ kind: "failed" }));
504
888
  }
505
889
  let bytes = 256;
506
890
  for (const [table, fields] of parsed) {
@@ -511,15 +895,25 @@ async function readDictionary(client, memo) {
511
895
  memo?.set(DICTIONARY_MEMO_KEY, parsed, bytes, exports.FIELD_TYPES_TTL_MS);
512
896
  return parsed;
513
897
  }
898
+ /** A response that was not a 200 and not an error: the status, when it is one. */
899
+ function failedStatus(status) {
900
+ return Object.freeze({
901
+ kind: "failed",
902
+ ...(validStatus(status) ? { status } : {}),
903
+ });
904
+ }
514
905
  /**
515
906
  * Rows to a frozen map. No rows at all means the rows were hidden from this
516
907
  * user (every instance has hidden-typed fields, `sys_user.user_password`
517
908
  * among them), and a full page may be cut short: both are unavailable.
518
909
  */
519
910
  function parseDictionaryRows(rows) {
520
- if (!Array.isArray(rows) || rows.length === 0 || rows.length >= exports.MAX_HIDDEN_DICTIONARY_ROWS) {
521
- return "unavailable";
522
- }
911
+ if (!Array.isArray(rows))
912
+ return dictionaryUnavailable(Object.freeze({ kind: "failed" }));
913
+ if (rows.length === 0)
914
+ return dictionaryUnavailable(NO_ROWS_READABLE);
915
+ if (rows.length >= exports.MAX_HIDDEN_DICTIONARY_ROWS)
916
+ return dictionaryUnavailable(Object.freeze({ kind: "incomplete" }));
523
917
  const byTable = new Map();
524
918
  for (const row of rows) {
525
919
  if (typeof row !== "object" || row === null)
@@ -536,56 +930,82 @@ function parseDictionaryRows(rows) {
536
930
  fields.set(element, type);
537
931
  }
538
932
  if (byTable.size === 0)
539
- return "unavailable";
933
+ return dictionaryUnavailable(NO_ROWS_READABLE);
540
934
  return byTable;
541
935
  }
542
- /** Chains for `tables`, in one read. Unread tables are left out of the map. */
543
- async function tableChains(client, tables) {
936
+ /** HTTP 200 with no row this user can read: the instance hides the table's rows from them. */
937
+ const NO_ROWS_READABLE = Object.freeze({ kind: "refused", status: 200 });
938
+ /**
939
+ * Chains for `tables`, in one read of their own `sys_db_object` rows with the
940
+ * stored parent references and the parents' names up to 12 tables, and, in the
941
+ * same request, the row of `sys_db_object` itself (one more row). Every table
942
+ * is in the map: a read that failed says so for all of them, and a table with
943
+ * no row is `null` when the anchor row came back, otherwise unconfirmed.
944
+ */
945
+ async function tableChains(client, tables, retry) {
544
946
  const chains = new Map();
545
- const ancestorFields = Array.from({ length: MAX_HIERARCHY_DEPTH - 1 }, (_, index) => `${"super_class.".repeat(index + 1)}name`);
947
+ const failAll = (failure) => {
948
+ const state = Object.freeze({ kind: "failed", failure });
949
+ for (const table of tables)
950
+ chains.set(table, state);
951
+ return chains;
952
+ };
953
+ const anchored = !tables.includes(CHAIN_ANCHOR_TABLE);
546
954
  let rows;
547
955
  try {
548
- const response = await client.getWithMeta("/api/now/table/sys_db_object", {
549
- sysparm_query: `nameIN${tables.join(",")}`,
550
- sysparm_fields: ["name", ...ancestorFields].join(","),
551
- sysparm_limit: String(tables.length),
956
+ const response = await retryTransientOnce(() => client.getWithMeta("/api/now/table/sys_db_object", {
957
+ sysparm_query: `nameIN${[...tables, ...(anchored ? [CHAIN_ANCHOR_TABLE] : [])].join(",")}`,
958
+ sysparm_fields: tableChainFields(MAX_HIERARCHY_DEPTH).join(","),
959
+ sysparm_limit: String(tables.length + (anchored ? 1 : 0)),
552
960
  sysparm_display_value: "false",
553
961
  sysparm_exclude_reference_link: "true",
554
- });
555
- rows = response.status === 200 ? response.data?.result : undefined;
962
+ }), { budget: retry });
963
+ if (response.status !== 200)
964
+ return failAll(failedStatus(response.status));
965
+ rows = response.data?.result;
556
966
  }
557
967
  catch (error) {
558
968
  if ((0, client_js_1.isServiceNowRequestCancellation)(error))
559
969
  throw error;
560
- return chains;
970
+ return failAll(classifyReadFailure(error));
561
971
  }
562
972
  if (!Array.isArray(rows))
563
- return chains;
973
+ return failAll(Object.freeze({ kind: "failed" }));
974
+ let anchorSeen = false;
564
975
  for (const row of rows) {
565
976
  if (typeof row !== "object" || row === null)
566
977
  continue;
567
978
  const record = row;
568
979
  const table = normalizeName(storedText(record.name));
980
+ if (table === CHAIN_ANCHOR_TABLE)
981
+ anchorSeen = true;
569
982
  if (table === undefined || !tables.includes(table))
570
983
  continue;
571
- const chain = [table];
572
- for (const field of ancestorFields) {
573
- const ancestor = normalizeName(storedText(record[field]));
574
- if (ancestor === undefined || chain.includes(ancestor))
575
- break;
576
- chain.push(ancestor);
577
- }
578
- chains.set(table, Object.freeze(chain));
984
+ const chain = tableChainFromRow(record, table, MAX_HIERARCHY_DEPTH);
985
+ chains.set(table, chain.complete
986
+ ? chain.tables
987
+ : Object.freeze({
988
+ kind: "incomplete",
989
+ at: chain.tables[chain.tables.length - 1] ?? table,
990
+ gap: chain.gap ?? "malformed",
991
+ }));
579
992
  }
580
993
  // The read succeeded: a table it did not return has no sys_db_object row.
994
+ const absent = anchorSeen ? null : Object.freeze({ kind: "unconfirmed" });
581
995
  for (const table of tables)
582
996
  if (!chains.has(table))
583
- chains.set(table, null);
997
+ chains.set(table, absent);
584
998
  return chains;
585
999
  }
586
- /** Joined tables of the database views among `tables`. Unread views are left out. */
1000
+ /**
1001
+ * Joined tables of the database views among `tables`. A view with no row, or
1002
+ * whose read did not complete, is left out, with `failure` saying why when the
1003
+ * read itself failed and `broken` naming a view with a joined table that has
1004
+ * no name or prefix.
1005
+ */
587
1006
  async function viewSources(client, tables) {
588
1007
  const views = new Map();
1008
+ const broken = new Set();
589
1009
  let rows;
590
1010
  try {
591
1011
  const response = await client.getWithMeta("/api/now/table/sys_db_view_table", {
@@ -595,16 +1015,19 @@ async function viewSources(client, tables) {
595
1015
  sysparm_display_value: "false",
596
1016
  sysparm_exclude_reference_link: "true",
597
1017
  });
598
- rows = response.status === 200 ? response.data?.result : undefined;
1018
+ if (response.status !== 200)
1019
+ return { views, broken, failure: failedStatus(response.status) };
1020
+ rows = response.data?.result;
599
1021
  }
600
1022
  catch (error) {
601
1023
  if ((0, client_js_1.isServiceNowRequestCancellation)(error))
602
1024
  throw error;
603
- return views;
1025
+ return { views, broken, failure: classifyReadFailure(error) };
604
1026
  }
605
- if (!Array.isArray(rows) || rows.length >= MAX_VIEW_SOURCE_ROWS)
606
- return views;
607
- const broken = new Set();
1027
+ if (!Array.isArray(rows))
1028
+ return { views, broken, failure: Object.freeze({ kind: "failed" }) };
1029
+ if (rows.length >= MAX_VIEW_SOURCE_ROWS)
1030
+ return { views, broken, failure: Object.freeze({ kind: "incomplete" }) };
608
1031
  for (const row of rows) {
609
1032
  if (typeof row !== "object" || row === null)
610
1033
  continue;
@@ -627,7 +1050,263 @@ async function viewSources(client, tables) {
627
1050
  }
628
1051
  for (const view of broken)
629
1052
  views.delete(view);
630
- return views;
1053
+ return { views, broken };
1054
+ }
1055
+ // ── Plan-bounded loader ────────────────────────────────────────────
1056
+ /**
1057
+ * The fields {@link loadFieldTypesInPlan} reads, by table. A tool that calls
1058
+ * it declares both tables in its access plan with at least these fields.
1059
+ */
1060
+ exports.PLAN_FIELD_TYPE_FIELDS = Object.freeze({
1061
+ sys_db_object: Object.freeze(["name", "super_class"]),
1062
+ sys_dictionary: Object.freeze(["name", "element", "internal_type"]),
1063
+ });
1064
+ /** The one dot-walk {@link loadFieldTypesInPlan} makes: a table's parent's name, one hop, into the same table. */
1065
+ exports.PLAN_FIELD_TYPE_DOT_WALKS = Object.freeze([
1066
+ Object.freeze({ from: "sys_db_object", field: "super_class", target: "sys_db_object" }),
1067
+ ]);
1068
+ /** `sys_db_object` levels read per call, at most: the dispatcher's 12-table chain. */
1069
+ exports.PLAN_CHAIN_LEVELS = 12;
1070
+ /** Tables in one chain, at most; a longer chain is incomplete. */
1071
+ const PLAN_CHAIN_TABLES = 16;
1072
+ const PLAN_PARENT_LINK = "super_class";
1073
+ const PLAN_PARENT_NAME = "super_class.name";
1074
+ /** The base table of all metadata, which extends nothing: never read. */
1075
+ const PLAN_METADATA_ROOT = "sys_metadata";
1076
+ /**
1077
+ * Field types for `tables`, read only from tables a tool can declare in its
1078
+ * own plan: `sys_db_object` one level per read (the stored `super_class`
1079
+ * reference, and the parent's name as a one-hop dot-walk,
1080
+ * {@link PLAN_FIELD_TYPE_DOT_WALKS}) and one instance-wide `sys_dictionary`
1081
+ * read of the hidden types. The two run in parallel. A chain ends only at a
1082
+ * row whose reference and parent name are both empty; a reference whose name
1083
+ * did not come back leaves the chain incomplete ({@link TableChain}).
1084
+ *
1085
+ * Unlike {@link loadFieldTypes} it never reads `sys_db_view_table` and keeps
1086
+ * nothing in the memo: a database view (no `sys_db_object` row) stays
1087
+ * unresolved, so every field on it is `unknown_type`. Otherwise the answer
1088
+ * has the same semantics:
1089
+ * - only rows of a hidden type ({@link isHiddenFieldType}) count, so a child's
1090
+ * row of another type never un-hides an inherited hidden field;
1091
+ * - a dictionary read that fails, is not 200, returns no hidden-typed row or
1092
+ * returns a full page gives `unavailable`;
1093
+ * - a table whose chain is unknown or incomplete is left out of `types`.
1094
+ *
1095
+ * A read that times out or returns a 5xx the client does not retry itself is
1096
+ * read once more after a short pause ({@link retryTransientOnce}): once for the
1097
+ * dictionary, and once shared by all the levels of the chain read. The first
1098
+ * level also asks for `sys_db_object`'s own row, to tell a table that does not
1099
+ * exist from a read that showed nothing. A chain read that fails keeps the
1100
+ * levels read before it, and sets `hierarchyRead` false. A cancelled read
1101
+ * rethrows.
1102
+ */
1103
+ async function loadFieldTypesInPlan(client, tablesCandidate, options = {}) {
1104
+ const tables = [...new Set([...tablesCandidate].map(normalizeName))].filter((name) => name !== undefined);
1105
+ const maxLevels = Math.max(0, Math.min(options.maxLevels ?? exports.PLAN_CHAIN_LEVELS, exports.PLAN_CHAIN_LEVELS));
1106
+ const cancelled = (error) => options.signal?.aborted === true || (0, client_js_1.isServiceNowRequestCancellation)(error);
1107
+ /** Table -> its parent: null when it extends nothing, a gap when the row named no usable parent. */
1108
+ const parents = new Map([[PLAN_METADATA_ROOT, null]]);
1109
+ /** Tables whose row was never asked for because the levels ran out. */
1110
+ const unread = new Set();
1111
+ const missing = new Set();
1112
+ let hierarchyRead = true;
1113
+ let dictionaryRows;
1114
+ let typesFailure;
1115
+ let chainsFailure;
1116
+ const retryOptions = { signal: options.signal };
1117
+ const readChains = async () => {
1118
+ if (options.readChains === false) {
1119
+ hierarchyRead = false;
1120
+ chainsFailure = Object.freeze({ kind: "policy", table: "sys_db_object" });
1121
+ return;
1122
+ }
1123
+ // One retry for every level of the chain read.
1124
+ const budget = { spent: false };
1125
+ let pending = tables.filter((table) => !parents.has(table));
1126
+ for (let level = 0; pending.length > 0; level += 1) {
1127
+ if (level >= maxLevels) {
1128
+ hierarchyRead = false;
1129
+ for (const table of pending)
1130
+ unread.add(table);
1131
+ return;
1132
+ }
1133
+ // The first level also asks for sys_db_object's own row: when it comes
1134
+ // back, a table with no row does not exist.
1135
+ const anchored = level === 0 && !pending.includes(CHAIN_ANCHOR_TABLE);
1136
+ const asked = anchored ? [...pending, CHAIN_ANCHOR_TABLE] : pending;
1137
+ const response = await retryTransientOnce(() => client.get("/api/now/table/sys_db_object", {
1138
+ sysparm_query: `nameIN${asked.join(",")}`,
1139
+ sysparm_fields: ["name", PLAN_PARENT_LINK, PLAN_PARENT_NAME].join(","),
1140
+ sysparm_limit: String(asked.length),
1141
+ sysparm_display_value: "false",
1142
+ sysparm_exclude_reference_link: "true",
1143
+ }), { ...retryOptions, budget });
1144
+ const next = new Set();
1145
+ let anchorSeen = false;
1146
+ const returned = new Set();
1147
+ for (const row of resultRows(response)) {
1148
+ const name = rawText(row.name)?.trim().toLowerCase();
1149
+ if (name === CHAIN_ANCHOR_TABLE)
1150
+ anchorSeen = true;
1151
+ if (name === undefined || !pending.includes(name))
1152
+ continue;
1153
+ returned.add(name);
1154
+ // Null when it extends nothing; a gap (the chain stops, unknown) for a
1155
+ // reference whose name did not come back, an absent field, or a
1156
+ // parent that is not a table name.
1157
+ const step = parentStepOf(row, PLAN_PARENT_LINK, PLAN_PARENT_NAME);
1158
+ const parent = "gap" in step ? Object.freeze({ gap: step.gap }) : step.parent;
1159
+ parents.set(name, parent);
1160
+ if (typeof parent === "string" && !parents.has(parent))
1161
+ next.add(parent);
1162
+ }
1163
+ if (level === 0) {
1164
+ if (anchorSeen) {
1165
+ for (const table of pending)
1166
+ if (!returned.has(table))
1167
+ missing.add(table);
1168
+ }
1169
+ else if (returned.size < pending.length) {
1170
+ // No row came back for the anchor, and some for the tables did not
1171
+ // either: the read showed this user nothing, so those are not "absent".
1172
+ chainsFailure = NO_ROWS_READABLE;
1173
+ }
1174
+ }
1175
+ pending = [...next].filter((table) => !parents.has(table));
1176
+ }
1177
+ };
1178
+ const readTypes = async () => {
1179
+ if (options.readTypes === false) {
1180
+ typesFailure = Object.freeze({ kind: "policy", table: "sys_dictionary" });
1181
+ return;
1182
+ }
1183
+ const response = await retryTransientOnce(() => client.getWithMeta("/api/now/table/sys_dictionary", {
1184
+ sysparm_query: `internal_typeIN${exports.HIDDEN_FIELD_TYPES.join(",")}`,
1185
+ sysparm_fields: exports.PLAN_FIELD_TYPE_FIELDS.sys_dictionary.join(","),
1186
+ sysparm_limit: String(exports.MAX_HIDDEN_DICTIONARY_ROWS),
1187
+ sysparm_display_value: "false",
1188
+ sysparm_exclude_reference_link: "true",
1189
+ }), retryOptions);
1190
+ if (response.status !== 200) {
1191
+ typesFailure = failedStatus(response.status);
1192
+ return;
1193
+ }
1194
+ const rows = resultRows(response.data);
1195
+ // No rows means they are hidden from this account (every instance has
1196
+ // password-typed fields), and a full page may be cut short: both are
1197
+ // unavailable, never "no hidden fields".
1198
+ if (rows.length === 0) {
1199
+ typesFailure = NO_ROWS_READABLE;
1200
+ return;
1201
+ }
1202
+ if (rows.length >= exports.MAX_HIDDEN_DICTIONARY_ROWS) {
1203
+ typesFailure = Object.freeze({ kind: "incomplete" });
1204
+ return;
1205
+ }
1206
+ const kept = [];
1207
+ for (const row of rows) {
1208
+ const entry = options.filterDictionaryRow?.(row) ?? row;
1209
+ const table = rawText(entry.name);
1210
+ const element = rawText(entry.element);
1211
+ const type = rawText(entry.internal_type);
1212
+ // Hidden-typed rows only, as the instance-wide loader keeps: a row of any
1213
+ // other type the server returned must not override an inherited one.
1214
+ if (table === undefined || element === undefined || !isHiddenFieldType(type))
1215
+ continue;
1216
+ kept.push({ table, element, internal_type: type });
1217
+ }
1218
+ // As the instance-wide loader: no hidden-typed row at all is unavailable.
1219
+ if (kept.length > 0)
1220
+ dictionaryRows = kept;
1221
+ else
1222
+ typesFailure = NO_ROWS_READABLE;
1223
+ };
1224
+ if (tables.length > 0) {
1225
+ await Promise.all([
1226
+ readChains().catch((error) => {
1227
+ if (cancelled(error))
1228
+ throw error;
1229
+ hierarchyRead = false;
1230
+ chainsFailure = classifyReadFailure(error);
1231
+ }),
1232
+ readTypes().catch((error) => {
1233
+ if (cancelled(error))
1234
+ throw error;
1235
+ dictionaryRows = undefined;
1236
+ typesFailure = classifyReadFailure(error);
1237
+ }),
1238
+ ]);
1239
+ }
1240
+ const chains = new Map();
1241
+ for (const table of tables) {
1242
+ const chain = planChainOf(table, parents, unread);
1243
+ if (chain !== undefined)
1244
+ chains.set(table, chain);
1245
+ }
1246
+ // Only complete chains resolve (fieldTypesFromRows leaves the rest out).
1247
+ const hierarchies = Object.fromEntries(chains);
1248
+ const types = dictionaryRows === undefined
1249
+ ? fieldTypesUnavailable(typesFailure)
1250
+ : fieldTypesFromRows(dictionaryRows, hierarchies);
1251
+ return Object.freeze({
1252
+ types,
1253
+ chains,
1254
+ hierarchyRead,
1255
+ ...(typesFailure === undefined || dictionaryRows !== undefined ? {} : { typesFailure }),
1256
+ ...(chainsFailure === undefined ? {} : { chainsFailure }),
1257
+ ...(missing.size === 0 ? {} : { missing }),
1258
+ });
1259
+ }
1260
+ const UNKNOWN_PARENT = Object.freeze({ gap: "malformed" });
1261
+ /**
1262
+ * A table's parent as the map holds it. Only a stored `null` means "extends
1263
+ * nothing"; a value that is absent is unknown, never empty.
1264
+ */
1265
+ function parentOf(parents, name) {
1266
+ const parent = parents.get(name);
1267
+ return parent === undefined ? UNKNOWN_PARENT : parent;
1268
+ }
1269
+ /** A requested table's chain from the parents read, or undefined when its row was not read. Exported for tests. */
1270
+ function planChainOf(table, parents, unread) {
1271
+ if (!parents.has(table))
1272
+ return undefined;
1273
+ const tables = [table];
1274
+ const incomplete = (gap) => Object.freeze({ tables: Object.freeze(tables), complete: false, gap });
1275
+ let current = parentOf(parents, table);
1276
+ while (current !== null) {
1277
+ if (typeof current === "object")
1278
+ return incomplete(current.gap);
1279
+ if (tables.includes(current))
1280
+ return incomplete("malformed");
1281
+ if (tables.length >= PLAN_CHAIN_TABLES)
1282
+ return incomplete("too_long");
1283
+ tables.push(current);
1284
+ const ancestor = current;
1285
+ current = parents.has(ancestor)
1286
+ ? parentOf(parents, ancestor)
1287
+ : Object.freeze({ gap: unread.has(ancestor) ? "too_long" : "no_row" });
1288
+ }
1289
+ return Object.freeze({ tables: Object.freeze(tables), complete: true });
1290
+ }
1291
+ /** Rows of a Table API response, objects only. */
1292
+ function resultRows(response) {
1293
+ const result = response?.result;
1294
+ return Array.isArray(result)
1295
+ ? result.filter((row) => typeof row === "object" && row !== null && !Array.isArray(row))
1296
+ : [];
1297
+ }
1298
+ /** A field value as text: a string, number or boolean, or the `value` of a pair. */
1299
+ function rawText(value, depth = 0) {
1300
+ if (typeof value === "string")
1301
+ return value;
1302
+ if (typeof value === "number" && Number.isFinite(value))
1303
+ return String(value);
1304
+ if (typeof value === "boolean")
1305
+ return String(value);
1306
+ if (depth < 2 && typeof value === "object" && value !== null && !Array.isArray(value)) {
1307
+ return rawText(value.value, depth + 1);
1308
+ }
1309
+ return undefined;
631
1310
  }
632
1311
  function storedText(candidate) {
633
1312
  if (typeof candidate === "string")
@@ -648,7 +1327,12 @@ function normalizeName(candidate) {
648
1327
  const HIDDEN_FIELD_SCOPE = new node_async_hooks_1.AsyncLocalStorage();
649
1328
  /** Run `callback` with `scope` as the call's hidden-typed fields. */
650
1329
  function runWithHiddenFieldScope(scope, callback) {
651
- return HIDDEN_FIELD_SCOPE.run(Object.freeze({ tables: scope.tables, unresolved: scope.unresolved }), callback);
1330
+ return HIDDEN_FIELD_SCOPE.run(Object.freeze({
1331
+ tables: scope.tables,
1332
+ unresolved: scope.unresolved,
1333
+ ...(scope.hierarchies === undefined ? {} : { hierarchies: scope.hierarchies }),
1334
+ ...(scope.views === undefined ? {} : { views: scope.views }),
1335
+ }), callback);
652
1336
  }
653
1337
  /** The scope of the running call, if the dispatcher set one. */
654
1338
  function currentHiddenFieldScope() {
@@ -662,6 +1346,8 @@ function currentHiddenFieldScope() {
662
1346
  */
663
1347
  function hiddenFieldScope(types, tables, namesOnly) {
664
1348
  const resolved = new Map();
1349
+ const hierarchies = new Map();
1350
+ const views = new Map();
665
1351
  let missing = types.state !== "available";
666
1352
  for (const candidate of tables) {
667
1353
  const table = normalizeName(candidate);
@@ -675,24 +1361,287 @@ function hiddenFieldScope(types, tables, namesOnly) {
675
1361
  continue;
676
1362
  }
677
1363
  resolved.set(table, hidden);
1364
+ if (types.state === "available") {
1365
+ const entry = types.tables.get(table);
1366
+ if (entry?.viewSources !== undefined)
1367
+ views.set(table, entry.viewSources);
1368
+ else if (entry !== undefined)
1369
+ hierarchies.set(table, entry.hierarchy);
1370
+ }
678
1371
  }
679
1372
  if (missing && !namesOnly)
680
1373
  return { degraded: false };
681
1374
  return {
682
- scope: Object.freeze({ tables: resolved, unresolved: namesOnly ? "names_only" : "deny" }),
1375
+ scope: Object.freeze({
1376
+ tables: resolved,
1377
+ unresolved: namesOnly ? "names_only" : "deny",
1378
+ hierarchies,
1379
+ views,
1380
+ }),
683
1381
  degraded: missing,
684
1382
  };
685
1383
  }
686
1384
  const EMPTY_SET = Object.freeze(new Set());
1385
+ const OPT_OUT_TAIL = '"fieldTypes": { "dictionary": "not_required" } on this profile to hide fields by name only.';
1386
+ /** After a grant: ", or set ...". */
1387
+ const OR_OPT_OUT = `, or set ${OPT_OUT_TAIL}`;
1388
+ /** Standing alone: " Set ...". */
1389
+ const ALONE_OPT_OUT = ` Set ${OPT_OUT_TAIL}`;
1390
+ const CAUSELESS_MESSAGE = "Field types could not be read from the instance, so no values are returned.";
1391
+ const POLICY_CLAUSE = "this profile does not grant read on sys_db_object and sys_dictionary (name, element, internal_type)";
1392
+ /**
1393
+ * The cause-less refusal: a loader that does not say why. It never begins with
1394
+ * "Access denied by policy", which is for a refusal this server's own policy
1395
+ * makes.
1396
+ */
1397
+ exports.FIELD_TYPES_UNAVAILABLE_MESSAGE = CAUSELESS_MESSAGE;
1398
+ /** The refusal for a table outside the call's resolved plan, a decision of this server's own plan. */
1399
+ function fieldTypesPlanDenialText(table) {
1400
+ const name = typeof table === "string" && FIELD_NAME.test(table) ? table : undefined;
1401
+ return (`Access denied by policy: ${name === undefined ? "a requested table is" : `"${name}" is`} not part of this ` +
1402
+ "call's plan, so its field types were not read.");
1403
+ }
1404
+ function validStatus(status) {
1405
+ return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599;
1406
+ }
1407
+ function statusClause(status) {
1408
+ return validStatus(status) ? ` (HTTP ${status})` : "";
1409
+ }
1410
+ /** What went wrong with one read, as a clause that follows "the" or stands alone. */
1411
+ function readClause(failure, read) {
1412
+ switch (failure.kind) {
1413
+ case "policy":
1414
+ return POLICY_CLAUSE;
1415
+ case "refused":
1416
+ return failure.status === 200
1417
+ ? `the instance returned no ${read} rows to the integration user (HTTP 200)`
1418
+ : `the instance refused the ${read} read${statusClause(failure.status)}`;
1419
+ case "transient": {
1420
+ const after = failure.retried === true ? " after retrying" : "";
1421
+ if (failure.timeout === true)
1422
+ return `the ${read} request timed out${after}`;
1423
+ if (failure.status !== undefined && validStatus(failure.status)) {
1424
+ return `the ${read} request returned HTTP ${failure.status}${after}`;
1425
+ }
1426
+ return `the ${read} request could not reach the instance${after}`;
1427
+ }
1428
+ case "incomplete":
1429
+ return read === "sys_dictionary"
1430
+ ? "sys_dictionary has more password-type fields than one read returns"
1431
+ : `${read} has more rows than one read returns`;
1432
+ case "failed":
1433
+ return `the ${read} read failed${statusClause(failure.status)}`;
1434
+ }
1435
+ }
1436
+ /** `subject`: the sentence already names the table, so a clause can say "its". */
1437
+ function gapClause(at, gap, subject = false) {
1438
+ const name = at !== undefined && FIELD_NAME.test(at) ? `"${at}"` : undefined;
1439
+ switch (gap) {
1440
+ case "parent_unreadable":
1441
+ return `the parent table of ${name ?? "a table"} could not be read (the instance did not return its name to the integration user)`;
1442
+ case "too_long":
1443
+ return `${subject ? "its" : "the"} table hierarchy is more than 12 tables deep`;
1444
+ case "malformed":
1445
+ return `the sys_db_object row of ${name ?? "a table"} does not name a valid parent`;
1446
+ case "no_row":
1447
+ return `no sys_db_object row of ${name ?? "a table"} is readable`;
1448
+ }
1449
+ }
1450
+ function grantClause(read) {
1451
+ return read === "sys_db_view_table"
1452
+ ? "Grant the integration user read access to sys_db_view_table"
1453
+ : "Grant the integration user read access to sys_dictionary and sys_db_object";
1454
+ }
1455
+ /** Surfaces that may name a table: the others take their tables from untrusted input. */
1456
+ function namesTables(surface) {
1457
+ return surface === "dispatcher" || surface === "history";
1458
+ }
1459
+ /**
1460
+ * Why field types are not known, as a clause with no sentence around it, or
1461
+ * undefined when the input names no cause. It never names a table on a
1462
+ * surface that does not {@link namesTables}.
1463
+ */
1464
+ function fieldTypesCauseClause(input) {
1465
+ const named = namesTables(input.surface);
1466
+ const problem = input.problem;
1467
+ if (problem?.kind === "not_found")
1468
+ return "a table has no row in sys_db_object";
1469
+ if (problem?.kind === "chain")
1470
+ return gapClause(named ? problem.at : undefined, problem.gap);
1471
+ const failure = problem?.kind === "read" ? problem.failure : input.failure;
1472
+ if (failure === undefined)
1473
+ return undefined;
1474
+ const read = problem?.kind === "read" ? (problem.read ?? "sys_db_object") : (input.read ?? "sys_dictionary");
1475
+ return readClause(failure, read);
1476
+ }
1477
+ /** How a sentence about one surface ends, by what the reader lost. */
1478
+ const SURFACE_TAIL = Object.freeze({
1479
+ history: Object.freeze({ types: ", so no values are shown.", hierarchy: ", so no values are shown." }),
1480
+ payload: Object.freeze({
1481
+ types: ", so password-type fields cannot be hidden; the payload is not shown.",
1482
+ hierarchy: ", so the payload is not shown.",
1483
+ }),
1484
+ evaluate: Object.freeze({
1485
+ types: "; password-typed field checks were not made.",
1486
+ hierarchy: "; some table checks were not made.",
1487
+ }),
1488
+ });
1489
+ const POLICY_CLAUSE_TEXT = "This profile does not grant read on sys_db_object and sys_dictionary (name, element, internal_type)";
1490
+ /**
1491
+ * The one source of the sentences that say why field types could not be read.
1492
+ * Only a validated table name (on the dispatcher and history, never where the
1493
+ * table came from a payload), an integer status and fixed words are
1494
+ * interpolated; no upstream text is ever part of one. "Access denied by
1495
+ * policy" is only for a cause of this server's own policy ({@link
1496
+ * FieldTypesReadFailure} `policy`) and for {@link fieldTypesPlanDenialText}.
1497
+ */
1498
+ function fieldTypesProblemText(input) {
1499
+ const optIn = input.optIn === true;
1500
+ const surface = input.surface;
1501
+ const table = input.table !== undefined && FIELD_NAME.test(input.table) ? input.table : undefined;
1502
+ const problem = input.problem;
1503
+ const failure = problem?.kind === "read" ? problem.failure : input.failure;
1504
+ const read = problem?.kind === "read" ? (problem.read ?? "sys_db_object") : (input.read ?? "sys_dictionary");
1505
+ if (surface !== "dispatcher") {
1506
+ const about = input.about ?? "types";
1507
+ const tail = SURFACE_TAIL[surface][about];
1508
+ const subject = about === "hierarchy" ? "Table hierarchies" : "Field types";
1509
+ if (failure?.kind === "policy")
1510
+ return `${POLICY_CLAUSE_TEXT}${tail}`;
1511
+ const clause = fieldTypesCauseClause(input);
1512
+ if (clause === undefined)
1513
+ return `${subject} could not be read${tail}`;
1514
+ const lead = problem?.kind === "chain"
1515
+ ? about === "hierarchy"
1516
+ ? "Table hierarchies could not be read in full"
1517
+ : "Field types could not be confirmed"
1518
+ : `${subject} could not be read`;
1519
+ return `${lead}: ${clause}${tail}`;
1520
+ }
1521
+ // The dispatcher's refusal, with what to do about it.
1522
+ if (problem?.kind === "not_found") {
1523
+ return table === undefined
1524
+ ? "A table does not exist on this instance: sys_db_object has no row for it. Check the table name."
1525
+ : `Table "${table}" does not exist on this instance: sys_db_object has no row for it. Check the table name.`;
1526
+ }
1527
+ if (problem?.kind === "chain") {
1528
+ const clause = gapClause(problem.at, problem.gap, table !== undefined);
1529
+ const subject = table === undefined ? "the table" : `"${table}"`;
1530
+ const fixable = problem.gap === "parent_unreadable" || problem.gap === "no_row";
1531
+ const remedy = fixable
1532
+ ? ` Grant the integration user read access to sys_db_object${optIn ? OR_OPT_OUT : "."}`
1533
+ : optIn
1534
+ ? ALONE_OPT_OUT
1535
+ : "";
1536
+ return `Field types for ${subject} could not be confirmed: ${clause}. No values were returned.${remedy}`;
1537
+ }
1538
+ if (failure === undefined)
1539
+ return CAUSELESS_MESSAGE;
1540
+ if (failure.kind === "policy") {
1541
+ return "Access denied by policy: this profile does not grant read on sys_db_object and sys_dictionary, so field types were not read and no values are returned.";
1542
+ }
1543
+ const clause = readClause(failure, read);
1544
+ switch (failure.kind) {
1545
+ case "refused":
1546
+ return (`Field types could not be read: ${clause}, so password-type fields can't be told apart and no values are returned. ` +
1547
+ `${grantClause(read)}${optIn ? OR_OPT_OUT : "."}`);
1548
+ case "transient":
1549
+ return `Field types are temporarily unavailable: ${clause}. No values were returned. Retry the call.`;
1550
+ case "incomplete":
1551
+ return `Field types could not be read in full: ${clause}, so no values are returned.${optIn ? ALONE_OPT_OUT : ""}`;
1552
+ case "failed":
1553
+ return `Field types could not be read: ${clause}. No values were returned.`;
1554
+ }
1555
+ }
1556
+ /**
1557
+ * The cause to report for a plan-bounded read of the tables `tables`: a table
1558
+ * `sys_db_object` has no row for, then why the chain read gave no answer, then
1559
+ * the first incomplete chain. Undefined when the loader knows none.
1560
+ */
1561
+ function planHierarchyProblem(loaded, tables) {
1562
+ if (loaded.missing !== undefined && loaded.missing.size > 0) {
1563
+ return { problem: Object.freeze({ kind: "not_found" }) };
1564
+ }
1565
+ if (loaded.chainsFailure !== undefined)
1566
+ return { failure: loaded.chainsFailure, read: "sys_db_object" };
1567
+ for (const table of tables) {
1568
+ const chain = loaded.chains.get(table);
1569
+ if (chain !== undefined && !chain.complete && chain.gap !== undefined) {
1570
+ return {
1571
+ problem: Object.freeze({
1572
+ kind: "chain",
1573
+ at: chain.tables[chain.tables.length - 1] ?? table,
1574
+ gap: chain.gap,
1575
+ }),
1576
+ };
1577
+ }
1578
+ }
1579
+ return undefined;
1580
+ }
1581
+ /** The cause to report when a plan-bounded read's field types are unavailable. */
1582
+ function planTypesProblem(loaded) {
1583
+ const failure = loaded.typesFailure ?? (loaded.types.state === "unavailable" ? loaded.types.cause : undefined);
1584
+ return failure === undefined ? undefined : { failure, read: "sys_dictionary" };
1585
+ }
687
1586
  /**
688
- * The fixed refusal when field types cannot be read and the profile has not
689
- * opted out. It names what to grant; it carries no table or field name.
1587
+ * Pick the one cause to report for a call over `tables` whose field types are
1588
+ * not usable, from what the loader found. A table that does not exist comes
1589
+ * first (the caller's to fix, and a retry cannot help), then the dictionary's
1590
+ * cause, then the first table's failed chain read, then its chain gap. The
1591
+ * result is a refusal; whether the call is refused at all is
1592
+ * {@link hiddenFieldScope}'s answer.
690
1593
  */
691
- exports.FIELD_TYPES_UNAVAILABLE_MESSAGE = "Access denied by policy: field types could not be read from the instance, so " +
692
- "password-type fields cannot be told apart from other fields. Grant the integration " +
693
- "user read access to sys_dictionary and sys_db_object (and sys_db_view_table for " +
694
- "database views), or set \"fieldTypes\": { \"dictionary\": \"not_required\" } on this " +
695
- "profile to hide fields by name only.";
1594
+ function fieldTypesRefusal(types, tables) {
1595
+ const names = [...tables].map(normalizeName).filter((name) => name !== undefined);
1596
+ const problems = types.problems;
1597
+ const withProblem = (kind) => names.find((name) => problems?.get(name)?.kind === kind);
1598
+ const notFound = withProblem("not_found");
1599
+ if (notFound !== undefined) {
1600
+ return refusalFor({ surface: "dispatcher", optIn: true, table: notFound, problem: problems.get(notFound) });
1601
+ }
1602
+ if (types.state === "unavailable" && types.cause !== undefined) {
1603
+ return refusalFor({ surface: "dispatcher", optIn: true, failure: types.cause });
1604
+ }
1605
+ const unreadable = withProblem("read");
1606
+ if (unreadable !== undefined) {
1607
+ return refusalFor({ surface: "dispatcher", optIn: true, table: unreadable, problem: problems.get(unreadable) });
1608
+ }
1609
+ const gap = withProblem("chain");
1610
+ if (gap !== undefined) {
1611
+ return refusalFor({ surface: "dispatcher", optIn: true, table: gap, problem: problems.get(gap) });
1612
+ }
1613
+ return Object.freeze({
1614
+ message: CAUSELESS_MESSAGE,
1615
+ policy: false,
1616
+ auditError: (0, tool_error_js_1.createToolError)("upstream", "retry_after_correction"),
1617
+ });
1618
+ }
1619
+ function refusalFor(input) {
1620
+ const failure = input.problem?.kind === "read" ? input.problem.failure : input.failure;
1621
+ return Object.freeze({
1622
+ message: fieldTypesProblemText(input),
1623
+ policy: failure?.kind === "policy",
1624
+ auditError: auditErrorFor(input),
1625
+ });
1626
+ }
1627
+ /** A bounded error for the audit record: a category and a retry decision, no text. */
1628
+ function auditErrorFor(input) {
1629
+ if (input.problem?.kind === "not_found")
1630
+ return (0, tool_error_js_1.createToolError)("not_found", "retry_after_correction");
1631
+ if (input.problem?.kind === "chain")
1632
+ return (0, tool_error_js_1.createToolError)("upstream", "retry_after_correction");
1633
+ const failure = input.problem?.kind === "read" ? input.problem.failure : input.failure;
1634
+ switch (failure?.kind) {
1635
+ case "refused":
1636
+ return (0, tool_error_js_1.createToolError)(failure.status === 401 ? "authentication" : "authorization", "retry_after_correction");
1637
+ case "transient":
1638
+ return (0, tool_error_js_1.createToolError)(failure.timeout === true ? "timeout" : "upstream", "retry_later");
1639
+ case "incomplete":
1640
+ return (0, tool_error_js_1.createToolError)("too_large", "retry_after_correction");
1641
+ default:
1642
+ return (0, tool_error_js_1.createToolError)("upstream", "do_not_retry");
1643
+ }
1644
+ }
696
1645
  const FIELD_TYPES_CONFIG_KEYS = Object.freeze(["dictionary"]);
697
1646
  const FIELD_TYPES_DICTIONARY_ENV = "SN_FIELD_TYPES_DICTIONARY";
698
1647
  /** A profile's `fieldTypes` is invalid; the message names only the key. */