@fgv/ts-extras 5.1.0-55 → 5.1.0-56

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 (156) hide show
  1. package/CAPABILITIES.md +95 -0
  2. package/dist/packlets/ai-assist/cacheRequest.js +118 -0
  3. package/dist/packlets/ai-assist/cacheRequest.js.map +1 -0
  4. package/dist/packlets/ai-assist/chatRequestBuilders.js +70 -5
  5. package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
  6. package/dist/packlets/ai-assist/completionClient.js +122 -45
  7. package/dist/packlets/ai-assist/completionClient.js.map +1 -1
  8. package/dist/packlets/ai-assist/imageGenerationClient.js +1 -1
  9. package/dist/packlets/ai-assist/imageGenerationClient.js.map +1 -1
  10. package/dist/packlets/ai-assist/index.js +3 -1
  11. package/dist/packlets/ai-assist/index.js.map +1 -1
  12. package/dist/packlets/ai-assist/model.js.map +1 -1
  13. package/dist/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js +200 -0
  14. package/dist/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js.map +1 -0
  15. package/dist/packlets/ai-assist/promptCacheObservabilityHarness.js +137 -0
  16. package/dist/packlets/ai-assist/promptCacheObservabilityHarness.js.map +1 -0
  17. package/dist/packlets/ai-assist/promptCacheRoutingAbHarness.js +156 -0
  18. package/dist/packlets/ai-assist/promptCacheRoutingAbHarness.js.map +1 -0
  19. package/dist/packlets/ai-assist/promptCacheUsageMath.js +124 -0
  20. package/dist/packlets/ai-assist/promptCacheUsageMath.js.map +1 -0
  21. package/dist/packlets/ai-assist/registry.js +9 -11
  22. package/dist/packlets/ai-assist/registry.js.map +1 -1
  23. package/dist/packlets/ai-assist/streamUsageCapability.js +124 -0
  24. package/dist/packlets/ai-assist/streamUsageCapability.js.map +1 -0
  25. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +24 -5
  26. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
  27. package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +64 -33
  28. package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
  29. package/dist/packlets/ai-assist/streamingAdapters/common.js +25 -1
  30. package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
  31. package/dist/packlets/ai-assist/streamingAdapters/gemini.js +12 -5
  32. package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
  33. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +34 -8
  34. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
  35. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +22 -14
  36. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
  37. package/dist/packlets/ai-assist/streamingClient.js +3 -2
  38. package/dist/packlets/ai-assist/streamingClient.js.map +1 -1
  39. package/dist/packlets/ai-assist/thinkingOptionsResolver.js +18 -3
  40. package/dist/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -1
  41. package/dist/packlets/ai-assist/toolFormats.js +80 -0
  42. package/dist/packlets/ai-assist/toolFormats.js.map +1 -1
  43. package/dist/packlets/ai-assist/toolTypes.js +21 -0
  44. package/dist/packlets/ai-assist/toolTypes.js.map +1 -0
  45. package/dist/packlets/ai-assist/usageNormalization.js +178 -0
  46. package/dist/packlets/ai-assist/usageNormalization.js.map +1 -0
  47. package/dist/packlets/ai-assist/usageTypes.js +21 -0
  48. package/dist/packlets/ai-assist/usageTypes.js.map +1 -0
  49. package/dist/packlets/mustache/index.js.map +1 -1
  50. package/dist/packlets/mustache/interfaces.js.map +1 -1
  51. package/dist/packlets/mustache/mustacheTemplate.js +91 -0
  52. package/dist/packlets/mustache/mustacheTemplate.js.map +1 -1
  53. package/dist/ts-extras.d.ts +547 -30
  54. package/lib/packlets/ai-assist/cacheRequest.d.ts +100 -0
  55. package/lib/packlets/ai-assist/cacheRequest.d.ts.map +1 -0
  56. package/lib/packlets/ai-assist/cacheRequest.js +123 -0
  57. package/lib/packlets/ai-assist/cacheRequest.js.map +1 -0
  58. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +34 -4
  59. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -1
  60. package/lib/packlets/ai-assist/chatRequestBuilders.js +73 -5
  61. package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
  62. package/lib/packlets/ai-assist/completionClient.d.ts +6 -0
  63. package/lib/packlets/ai-assist/completionClient.d.ts.map +1 -1
  64. package/lib/packlets/ai-assist/completionClient.js +121 -44
  65. package/lib/packlets/ai-assist/completionClient.js.map +1 -1
  66. package/lib/packlets/ai-assist/imageGenerationClient.d.ts.map +1 -1
  67. package/lib/packlets/ai-assist/imageGenerationClient.js +1 -1
  68. package/lib/packlets/ai-assist/imageGenerationClient.js.map +1 -1
  69. package/lib/packlets/ai-assist/index.d.ts +7 -2
  70. package/lib/packlets/ai-assist/index.d.ts.map +1 -1
  71. package/lib/packlets/ai-assist/index.js +11 -1
  72. package/lib/packlets/ai-assist/index.js.map +1 -1
  73. package/lib/packlets/ai-assist/model.d.ts +59 -288
  74. package/lib/packlets/ai-assist/model.d.ts.map +1 -1
  75. package/lib/packlets/ai-assist/model.js.map +1 -1
  76. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.d.ts +124 -0
  77. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.d.ts.map +1 -0
  78. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js +208 -0
  79. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js.map +1 -0
  80. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.d.ts +77 -0
  81. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.d.ts.map +1 -0
  82. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.js +143 -0
  83. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.js.map +1 -0
  84. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.d.ts +84 -0
  85. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.d.ts.map +1 -0
  86. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.js +163 -0
  87. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.js.map +1 -0
  88. package/lib/packlets/ai-assist/promptCacheUsageMath.d.ts +105 -0
  89. package/lib/packlets/ai-assist/promptCacheUsageMath.d.ts.map +1 -0
  90. package/lib/packlets/ai-assist/promptCacheUsageMath.js +130 -0
  91. package/lib/packlets/ai-assist/promptCacheUsageMath.js.map +1 -0
  92. package/lib/packlets/ai-assist/registry.d.ts.map +1 -1
  93. package/lib/packlets/ai-assist/registry.js +9 -11
  94. package/lib/packlets/ai-assist/registry.js.map +1 -1
  95. package/lib/packlets/ai-assist/streamUsageCapability.d.ts +119 -0
  96. package/lib/packlets/ai-assist/streamUsageCapability.d.ts.map +1 -0
  97. package/lib/packlets/ai-assist/streamUsageCapability.js +130 -0
  98. package/lib/packlets/ai-assist/streamUsageCapability.js.map +1 -0
  99. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -1
  100. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +23 -4
  101. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
  102. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts +21 -12
  103. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts.map +1 -1
  104. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +64 -34
  105. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
  106. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +21 -0
  107. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -1
  108. package/lib/packlets/ai-assist/streamingAdapters/common.js +25 -1
  109. package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
  110. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -1
  111. package/lib/packlets/ai-assist/streamingAdapters/gemini.js +12 -5
  112. package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
  113. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +1 -1
  114. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -1
  115. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +33 -7
  116. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
  117. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +1 -1
  118. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -1
  119. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +21 -13
  120. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
  121. package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -1
  122. package/lib/packlets/ai-assist/streamingClient.js +3 -2
  123. package/lib/packlets/ai-assist/streamingClient.js.map +1 -1
  124. package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts.map +1 -1
  125. package/lib/packlets/ai-assist/thinkingOptionsResolver.js +18 -3
  126. package/lib/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -1
  127. package/lib/packlets/ai-assist/toolFormats.d.ts +55 -1
  128. package/lib/packlets/ai-assist/toolFormats.d.ts.map +1 -1
  129. package/lib/packlets/ai-assist/toolFormats.js +82 -0
  130. package/lib/packlets/ai-assist/toolFormats.js.map +1 -1
  131. package/lib/packlets/ai-assist/toolTypes.d.ts +328 -0
  132. package/lib/packlets/ai-assist/toolTypes.d.ts.map +1 -0
  133. package/lib/packlets/ai-assist/toolTypes.js +22 -0
  134. package/lib/packlets/ai-assist/toolTypes.js.map +1 -0
  135. package/lib/packlets/ai-assist/usageNormalization.d.ts +58 -0
  136. package/lib/packlets/ai-assist/usageNormalization.d.ts.map +1 -0
  137. package/lib/packlets/ai-assist/usageNormalization.js +184 -0
  138. package/lib/packlets/ai-assist/usageNormalization.js.map +1 -0
  139. package/lib/packlets/ai-assist/usageTypes.d.ts +84 -0
  140. package/lib/packlets/ai-assist/usageTypes.d.ts.map +1 -0
  141. package/lib/packlets/ai-assist/usageTypes.js +22 -0
  142. package/lib/packlets/ai-assist/usageTypes.js.map +1 -0
  143. package/lib/packlets/mustache/index.d.ts +1 -1
  144. package/lib/packlets/mustache/index.d.ts.map +1 -1
  145. package/lib/packlets/mustache/index.js.map +1 -1
  146. package/lib/packlets/mustache/interfaces.d.ts +30 -0
  147. package/lib/packlets/mustache/interfaces.d.ts.map +1 -1
  148. package/lib/packlets/mustache/interfaces.js.map +1 -1
  149. package/lib/packlets/mustache/mustacheTemplate.d.ts +56 -1
  150. package/lib/packlets/mustache/mustacheTemplate.d.ts.map +1 -1
  151. package/lib/packlets/mustache/mustacheTemplate.js +91 -0
  152. package/lib/packlets/mustache/mustacheTemplate.js.map +1 -1
  153. package/package.json +16 -16
  154. package/perf/promptCacheAnthropicBreakpoint.js +135 -0
  155. package/perf/promptCacheObservability.js +107 -0
  156. package/perf/promptCacheRoutingAb.js +105 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usageNormalization.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/usageNormalization.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;;AAiDZ,0DAuBC;AAkCD,4DA6BC;AAyCD,sEA4BC;AAkCD,oDA4BC;AAvPD,4CAA2D;AAgB3D,MAAM,iBAAiB,GAAkC,qBAAU,CAAC,MAAM,CAAqB;IAC7F,YAAY,EA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,QAAQ,EAAE;IAC9C,oBAAoB,EAAE,qBAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAClD,uBAAuB,EAAE,qBAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;CACtD,CAAC,CAAC;AAEH;;;;;;;;;;;;;;GAcG;AACH,SAAgB,oBAAoB,CAAC,GAA2B;IAC9D,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;QACtB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,MAAM,GAAG,cAAc,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC5C,IAAI,MAAM,CAAC,SAAS,EAAE,EAAE,CAAC;QACvB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,EACJ,gBAAgB,EAChB,oBAAoB,EAAE,YAAY,EAClC,uBAAuB,EAAE,iBAAiB,EAC3C,GAAG,MAAM,CAAC,KAAK,CAAC;IACjB,MAAM,mBAAmB,GACvB,iBAAiB,KAAK,SAAS,IAAI,gBAAgB,KAAK,SAAS;QAC/D,CAAC,CAAC,gBAAgB,GAAG,iBAAiB;QACtC,CAAC,CAAC,SAAS,CAAC;IAChB,OAAO;QACL,OAAO,EAAE,OAAO;QAChB,mBAAmB;QACnB,iBAAiB;QACjB,YAAY;QACZ,gBAAgB,EACd,mBAAmB,KAAK,SAAS,IAAI,iBAAiB,KAAK,SAAS;YAClE,CAAC,CAAC,mBAAmB,GAAG,iBAAiB;YACzC,CAAC,CAAC,SAAS;QACf,GAAG;KACJ,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Per-wire-shape `usage` block normalization, shared by the non-streaming\n * adapters (`completionClient.ts`) and the streaming adapters\n * (`streamingAdapters/*.ts`) so the same JSON layout is parsed once.\n *\n * @remarks\n * Every function here follows one rule throughout: a field that is absent\n * from the wire response stays absent on {@link AiAssist.IAiCompletionUsage} —\n * never defaulted to `0`, and never derived from a sibling field unless the\n * value that sibling would need is itself known. See `IAiCompletionUsage`\n * for why.\n * @packageDocumentation\n */\n\n/* eslint-disable @typescript-eslint/naming-convention -- wire field names are snake_case */\n\nimport { type JsonObject } from '@fgv/ts-json-base';\nimport { type Validator, Validators } from '@fgv/ts-utils';\n\nimport { type AiCacheReportingLevel, type IAiCompletionUsage } from './usageTypes';\n\n// ============================================================================\n// Anthropic Messages\n// ============================================================================\n\n/** @internal */\ninterface IAnthropicRawUsage {\n readonly input_tokens: number;\n readonly output_tokens?: number;\n readonly cache_creation_input_tokens?: number;\n readonly cache_read_input_tokens?: number;\n}\n\nconst anthropicRawUsage: Validator<IAnthropicRawUsage> = Validators.object<IAnthropicRawUsage>({\n input_tokens: Validators.number,\n output_tokens: Validators.number.optional(),\n cache_creation_input_tokens: Validators.number.optional(),\n cache_read_input_tokens: Validators.number.optional()\n});\n\n/**\n * Normalizes an Anthropic Messages API `usage` block. Anthropic always\n * reports both reads and writes, so `reports` is unconditionally\n * `'reads-and-writes'` — an absent `cache_creation_input_tokens` genuinely\n * means zero tokens were written this request.\n * @internal\n */\nexport function normalizeAnthropicUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = anthropicRawUsage.validate(raw);\n if (parsed.isFailure()) {\n return undefined;\n }\n const {\n input_tokens: uncachedInputTokens,\n output_tokens: outputTokens,\n cache_creation_input_tokens: cacheWriteTokens,\n cache_read_input_tokens: cachedInputTokens\n } = parsed.value;\n return {\n reports: 'reads-and-writes',\n uncachedInputTokens,\n cachedInputTokens,\n cacheWriteTokens,\n outputTokens,\n totalInputTokens: cachedInputTokens !== undefined ? uncachedInputTokens + cachedInputTokens : undefined,\n raw\n };\n}\n\n// ============================================================================\n// OpenAI / xAI Chat Completions\n// ============================================================================\n\n/** @internal */\ninterface IOpenAiChatPromptTokensDetails {\n readonly cached_tokens?: number;\n}\n\nconst openAiChatPromptTokensDetails: Validator<IOpenAiChatPromptTokensDetails> =\n Validators.object<IOpenAiChatPromptTokensDetails>({ cached_tokens: Validators.number.optional() });\n\n/** @internal */\ninterface IOpenAiChatRawUsage {\n readonly prompt_tokens?: number;\n readonly completion_tokens?: number;\n readonly prompt_tokens_details?: IOpenAiChatPromptTokensDetails;\n}\n\nconst openAiChatRawUsage: Validator<IOpenAiChatRawUsage> = Validators.object<IOpenAiChatRawUsage>({\n prompt_tokens: Validators.number.optional(),\n completion_tokens: Validators.number.optional(),\n prompt_tokens_details: openAiChatPromptTokensDetails.optional()\n});\n\n/**\n * Normalizes an OpenAI/xAI Chat Completions `usage` block. `reports` is\n * unconditionally `'reads'`: `cache_write_tokens` does not exist on this API\n * for any provider reached through it, so `cacheWriteTokens` is never set —\n * not even to `0`.\n * @internal\n */\nexport function normalizeOpenAiChatUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = openAiChatRawUsage.validate(raw);\n if (parsed.isFailure()) {\n return undefined;\n }\n const {\n prompt_tokens: promptTokens,\n completion_tokens: outputTokens,\n prompt_tokens_details\n } = parsed.value;\n const cachedInputTokens = prompt_tokens_details?.cached_tokens;\n const uncachedInputTokens =\n cachedInputTokens !== undefined && promptTokens !== undefined\n ? promptTokens - cachedInputTokens\n : undefined;\n return {\n reports: 'reads',\n uncachedInputTokens,\n cachedInputTokens,\n outputTokens,\n totalInputTokens:\n uncachedInputTokens !== undefined && cachedInputTokens !== undefined\n ? uncachedInputTokens + cachedInputTokens\n : undefined,\n raw\n };\n}\n\n// ============================================================================\n// OpenAI / xAI Responses\n// ============================================================================\n\n/** @internal */\ninterface IOpenAiResponsesInputTokensDetails {\n readonly cached_tokens?: number;\n readonly cache_write_tokens?: number;\n}\n\nconst openAiResponsesInputTokensDetails: Validator<IOpenAiResponsesInputTokensDetails> =\n Validators.object<IOpenAiResponsesInputTokensDetails>({\n cached_tokens: Validators.number.optional(),\n cache_write_tokens: Validators.number.optional()\n });\n\n/** @internal */\ninterface IOpenAiResponsesRawUsage {\n readonly input_tokens?: number;\n readonly output_tokens?: number;\n readonly input_tokens_details?: IOpenAiResponsesInputTokensDetails;\n}\n\nconst openAiResponsesRawUsage: Validator<IOpenAiResponsesRawUsage> =\n Validators.object<IOpenAiResponsesRawUsage>({\n input_tokens: Validators.number.optional(),\n output_tokens: Validators.number.optional(),\n input_tokens_details: openAiResponsesInputTokensDetails.optional()\n });\n\n/**\n * Normalizes an OpenAI/xAI Responses API `usage` block. This route is shared\n * by two providers that disagree about write reporting — OpenAI always sends\n * `cache_write_tokens` (even when `0`), xAI never does — so `reports` is\n * derived from field **presence**, not from provider identity: a wire that\n * sends the field, however small its value, is `'reads-and-writes'`; a wire\n * that omits it entirely is `'reads'`.\n * @internal\n */\nexport function normalizeOpenAiResponsesUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = openAiResponsesRawUsage.validate(raw);\n if (parsed.isFailure()) {\n return undefined;\n }\n const { input_tokens: inputTokens, output_tokens: outputTokens, input_tokens_details } = parsed.value;\n const cachedInputTokens = input_tokens_details?.cached_tokens;\n const cacheWriteTokens = input_tokens_details?.cache_write_tokens;\n const reports: AiCacheReportingLevel = cacheWriteTokens !== undefined ? 'reads-and-writes' : 'reads';\n const uncachedInputTokens =\n cachedInputTokens !== undefined && inputTokens !== undefined\n ? inputTokens - cachedInputTokens\n : undefined;\n return {\n reports,\n uncachedInputTokens,\n cachedInputTokens,\n cacheWriteTokens,\n outputTokens,\n totalInputTokens:\n uncachedInputTokens !== undefined && cachedInputTokens !== undefined\n ? uncachedInputTokens + cachedInputTokens\n : undefined,\n raw\n };\n}\n\n// ============================================================================\n// Gemini generateContent / streamGenerateContent\n// ============================================================================\n\n/** @internal */\ninterface IGeminiRawUsage {\n readonly promptTokenCount?: number;\n readonly candidatesTokenCount?: number;\n readonly cachedContentTokenCount?: number;\n}\n\nconst geminiRawUsage: Validator<IGeminiRawUsage> = Validators.object<IGeminiRawUsage>({\n promptTokenCount: Validators.number.optional(),\n candidatesTokenCount: Validators.number.optional(),\n cachedContentTokenCount: Validators.number.optional()\n});\n\n/**\n * Normalizes a Gemini `usageMetadata` block. `reports` is unconditionally\n * `'reads'` — Gemini has no cache-write concept in a `generateContent` call;\n * writes happen out-of-band via the explicit `cachedContents` resource,\n * out of scope per the design (§10).\n *\n * @remarks\n * The Gemini-specific footgun: `promptTokenCount` already **includes**\n * `cachedContentTokenCount` (it is the total effective prompt size), unlike\n * OpenAI where the cached figure sits in a sub-object alongside a separate\n * total. `uncachedInputTokens` subtracts to correct for it — but only when\n * `cachedContentTokenCount` is itself present, per the module's absent-means-\n * absent rule.\n * @internal\n */\nexport function normalizeGeminiUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = geminiRawUsage.validate(raw);\n if (parsed.isFailure()) {\n return undefined;\n }\n const {\n promptTokenCount,\n candidatesTokenCount: outputTokens,\n cachedContentTokenCount: cachedInputTokens\n } = parsed.value;\n const uncachedInputTokens =\n cachedInputTokens !== undefined && promptTokenCount !== undefined\n ? promptTokenCount - cachedInputTokens\n : undefined;\n return {\n reports: 'reads',\n uncachedInputTokens,\n cachedInputTokens,\n outputTokens,\n totalInputTokens:\n uncachedInputTokens !== undefined && cachedInputTokens !== undefined\n ? uncachedInputTokens + cachedInputTokens\n : undefined,\n raw\n };\n}\n"]}
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Completion usage types: what a provider's wire shape can report about
3
+ * prompt-cache reads/writes, and the normalized token accounting built from it.
4
+ *
5
+ * @remarks
6
+ * Its own module rather than part of `model.ts` because it depends on nothing
7
+ * there — `model.ts` imports it, not the reverse — and because `model.ts` was
8
+ * at the `max-lines` cap. Same rationale as `structuredOutputTypes.ts`.
9
+ * @packageDocumentation
10
+ */
11
+ import { type JsonObject } from '@fgv/ts-json-base';
12
+ /**
13
+ * What a provider's wire shape is able to report about prompt-cache usage,
14
+ * given that a usage block was present on the response at all.
15
+ *
16
+ * @remarks
17
+ * `'reads'` — cache reads are reported; cache writes cannot be (either the API
18
+ * has no write concept, or the field structurally does not exist on this route).
19
+ * `'reads-and-writes'` — both reads and writes are reported.
20
+ *
21
+ * There is deliberately no `'none'` member: "no usage was reported at all" is
22
+ * already expressed by {@link AiAssist.IAiCompletionResponse.usage} itself
23
+ * being absent, and a third value here would be a second, reachable-only-via-
24
+ * bug way to say the same thing — check `usage === undefined`, not a `reports`
25
+ * value, to detect that case.
26
+ *
27
+ * See {@link AiAssist.IAiCompletionUsage.reports} for why this is required
28
+ * rather than optional.
29
+ * @public
30
+ */
31
+ export type AiCacheReportingLevel = 'reads' | 'reads-and-writes';
32
+ /**
33
+ * Token accounting for a completion, normalized across providers.
34
+ *
35
+ * @remarks
36
+ * Every field but `reports` is best-effort: a provider's wire shape reports
37
+ * what it reports, and an absent field here means the corresponding wire
38
+ * field was itself absent — never a guessed zero. See `reports` for the one
39
+ * exception this rule has to be explicit about.
40
+ * @public
41
+ */
42
+ export interface IAiCompletionUsage {
43
+ /**
44
+ * What this response's wire shape *can* report about caching.
45
+ *
46
+ * @remarks
47
+ * **Required, not optional.** An optional field would make an absent
48
+ * `cacheWriteTokens` three-ways ambiguous — no write happened / this API
49
+ * cannot report writes / a build predating the field — and disambiguating
50
+ * exactly that is what this field exists for. Under `'reads-and-writes'`, an
51
+ * absent `cacheWriteTokens` genuinely means zero tokens were written this
52
+ * request — the actionable signal that a breakpoint did not take. Under
53
+ * `'reads'` it means the API cannot say, and inferring "zero writes" from it
54
+ * would be a fabricated fact. Same remedy as
55
+ * `IAiCompletionResponse.structuredOutput`.
56
+ */
57
+ readonly reports: AiCacheReportingLevel;
58
+ /** Input tokens **not** served from cache. Normalized — see `CAPABILITIES.md` for the per-provider table. */
59
+ readonly uncachedInputTokens?: number;
60
+ /** Input tokens served from cache. */
61
+ readonly cachedInputTokens?: number;
62
+ /**
63
+ * Input tokens written to cache.
64
+ *
65
+ * @remarks
66
+ * Two absence cases, disambiguated by `reports` — never by a `0` this field
67
+ * itself carries:
68
+ * - **`reports: 'reads-and-writes'` and this field absent** — the wire
69
+ * genuinely reported zero tokens written. Treat absence as `0`, not as
70
+ * unknown; this is the actionable "the breakpoint did not take" signal.
71
+ * - **`reports: 'reads'` and this field absent** — the API cannot report
72
+ * writes on this route at all (structurally unfillable, e.g. OpenAI/xAI
73
+ * Chat Completions). Never defaulted to `0` here — that would fabricate a
74
+ * fact the wire never stated.
75
+ */
76
+ readonly cacheWriteTokens?: number;
77
+ /** Generated output tokens. */
78
+ readonly outputTokens?: number;
79
+ /** Total input = uncached + cached, when both are known. */
80
+ readonly totalInputTokens?: number;
81
+ /** The provider's own usage block, unnormalized, for anything this shape drops. */
82
+ readonly raw?: JsonObject;
83
+ }
84
+ //# sourceMappingURL=usageTypes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usageTypes.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/usageTypes.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;GASG;AAEH,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,qBAAqB,GAAG,OAAO,GAAG,kBAAkB,CAAC;AAEjE;;;;;;;;;GASG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,OAAO,EAAE,qBAAqB,CAAC;IACxC,6GAA6G;IAC7G,QAAQ,CAAC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IACtC,sCAAsC;IACtC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACpC;;;;;;;;;;;;;OAaG;IACH,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,+BAA+B;IAC/B,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,4DAA4D;IAC5D,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,mFAAmF;IACnF,QAAQ,CAAC,GAAG,CAAC,EAAE,UAAU,CAAC;CAC3B"}
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ // Copyright (c) 2026 Erik Fortune
3
+ //
4
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ // of this software and associated documentation files (the "Software"), to deal
6
+ // in the Software without restriction, including without limitation the rights
7
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ // copies of the Software, and to permit persons to whom the Software is
9
+ // furnished to do so, subject to the following conditions:
10
+ //
11
+ // The above copyright notice and this permission notice shall be included in all
12
+ // copies or substantial portions of the Software.
13
+ //
14
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ // SOFTWARE.
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ //# sourceMappingURL=usageTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usageTypes.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/usageTypes.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Completion usage types: what a provider's wire shape can report about\n * prompt-cache reads/writes, and the normalized token accounting built from it.\n *\n * @remarks\n * Its own module rather than part of `model.ts` because it depends on nothing\n * there — `model.ts` imports it, not the reverse — and because `model.ts` was\n * at the `max-lines` cap. Same rationale as `structuredOutputTypes.ts`.\n * @packageDocumentation\n */\n\nimport { type JsonObject } from '@fgv/ts-json-base';\n\n/**\n * What a provider's wire shape is able to report about prompt-cache usage,\n * given that a usage block was present on the response at all.\n *\n * @remarks\n * `'reads'` — cache reads are reported; cache writes cannot be (either the API\n * has no write concept, or the field structurally does not exist on this route).\n * `'reads-and-writes'` — both reads and writes are reported.\n *\n * There is deliberately no `'none'` member: \"no usage was reported at all\" is\n * already expressed by {@link AiAssist.IAiCompletionResponse.usage} itself\n * being absent, and a third value here would be a second, reachable-only-via-\n * bug way to say the same thing — check `usage === undefined`, not a `reports`\n * value, to detect that case.\n *\n * See {@link AiAssist.IAiCompletionUsage.reports} for why this is required\n * rather than optional.\n * @public\n */\nexport type AiCacheReportingLevel = 'reads' | 'reads-and-writes';\n\n/**\n * Token accounting for a completion, normalized across providers.\n *\n * @remarks\n * Every field but `reports` is best-effort: a provider's wire shape reports\n * what it reports, and an absent field here means the corresponding wire\n * field was itself absent — never a guessed zero. See `reports` for the one\n * exception this rule has to be explicit about.\n * @public\n */\nexport interface IAiCompletionUsage {\n /**\n * What this response's wire shape *can* report about caching.\n *\n * @remarks\n * **Required, not optional.** An optional field would make an absent\n * `cacheWriteTokens` three-ways ambiguous — no write happened / this API\n * cannot report writes / a build predating the field — and disambiguating\n * exactly that is what this field exists for. Under `'reads-and-writes'`, an\n * absent `cacheWriteTokens` genuinely means zero tokens were written this\n * request — the actionable signal that a breakpoint did not take. Under\n * `'reads'` it means the API cannot say, and inferring \"zero writes\" from it\n * would be a fabricated fact. Same remedy as\n * `IAiCompletionResponse.structuredOutput`.\n */\n readonly reports: AiCacheReportingLevel;\n /** Input tokens **not** served from cache. Normalized — see `CAPABILITIES.md` for the per-provider table. */\n readonly uncachedInputTokens?: number;\n /** Input tokens served from cache. */\n readonly cachedInputTokens?: number;\n /**\n * Input tokens written to cache.\n *\n * @remarks\n * Two absence cases, disambiguated by `reports` — never by a `0` this field\n * itself carries:\n * - **`reports: 'reads-and-writes'` and this field absent** — the wire\n * genuinely reported zero tokens written. Treat absence as `0`, not as\n * unknown; this is the actionable \"the breakpoint did not take\" signal.\n * - **`reports: 'reads'` and this field absent** — the API cannot report\n * writes on this route at all (structurally unfillable, e.g. OpenAI/xAI\n * Chat Completions). Never defaulted to `0` here — that would fabricate a\n * fact the wire never stated.\n */\n readonly cacheWriteTokens?: number;\n /** Generated output tokens. */\n readonly outputTokens?: number;\n /** Total input = uncached + cached, when both are known. */\n readonly totalInputTokens?: number;\n /** The provider's own usage block, unnormalized, for anything this shape drops. */\n readonly raw?: JsonObject;\n}\n"]}
@@ -1,3 +1,3 @@
1
- export { IContextValidationResult, IMissingVariableDetail, IMustacheTemplateOptions, IVariableRef, MustacheEscapeStrategy, MustacheTokenType } from './interfaces';
1
+ export { IContextValidationResult, IMissingVariableDetail, IMustacheTemplateOptions, IRenderedSegment, IRenderedTemplate, IVariableRef, MustacheEscapeStrategy, MustacheTokenType } from './interfaces';
2
2
  export { MustacheTemplate } from './mustacheTemplate';
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/mustache/index.ts"],"names":[],"mappings":"AAsBA,OAAO,EACL,wBAAwB,EACxB,sBAAsB,EACtB,wBAAwB,EACxB,YAAY,EACZ,sBAAsB,EACtB,iBAAiB,EAClB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/mustache/index.ts"],"names":[],"mappings":"AAsBA,OAAO,EACL,wBAAwB,EACxB,sBAAsB,EACtB,wBAAwB,EACxB,gBAAgB,EAChB,iBAAiB,EACjB,YAAY,EACZ,sBAAsB,EACtB,iBAAiB,EAClB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/mustache/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAWH,uDAAsD;AAA7C,oHAAA,gBAAgB,OAAA","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport {\n IContextValidationResult,\n IMissingVariableDetail,\n IMustacheTemplateOptions,\n IVariableRef,\n MustacheEscapeStrategy,\n MustacheTokenType\n} from './interfaces';\n\nexport { MustacheTemplate } from './mustacheTemplate';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/mustache/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAaH,uDAAsD;AAA7C,oHAAA,gBAAgB,OAAA","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport {\n IContextValidationResult,\n IMissingVariableDetail,\n IMustacheTemplateOptions,\n IRenderedSegment,\n IRenderedTemplate,\n IVariableRef,\n MustacheEscapeStrategy,\n MustacheTokenType\n} from './interfaces';\n\nexport { MustacheTemplate } from './mustacheTemplate';\n"]}
@@ -3,6 +3,36 @@
3
3
  * @public
4
4
  */
5
5
  export type MustacheTokenType = 'text' | 'name' | '&' | '#' | '^' | '!' | '>' | '=';
6
+ /**
7
+ * One contiguous run of the rendered output, attributed to what produced it.
8
+ * @public
9
+ */
10
+ export interface IRenderedSegment {
11
+ /** `'literal'` for template text; `'substitution'` for an interpolated value. */
12
+ readonly kind: 'literal' | 'substitution';
13
+ /** Variable name, when `kind` is `'substitution'`. */
14
+ readonly name?: string;
15
+ /** Offset into `IRenderedTemplate.text`, in UTF-16 code units. */
16
+ readonly start: number;
17
+ /** Length in UTF-16 code units. May be `0` for a variable that rendered empty. */
18
+ readonly length: number;
19
+ /** `false` for a triple-stash / `{{&}}` interpolation, which bypasses escaping. */
20
+ readonly escaped: boolean;
21
+ }
22
+ /**
23
+ * A render plus the map of which part of the output came from where.
24
+ * @public
25
+ */
26
+ export interface IRenderedTemplate {
27
+ /** The rendered output — identical to what `MustacheTemplate.render` returns. */
28
+ readonly text: string;
29
+ /**
30
+ * Document-ordered, contiguous and gapless: every code unit of `text` belongs to exactly one
31
+ * segment, so concatenating them reproduces `text` exactly. That identity is verified before
32
+ * this is returned.
33
+ */
34
+ readonly segments: ReadonlyArray<IRenderedSegment>;
35
+ }
6
36
  /**
7
37
  * Represents a variable reference extracted from a Mustache template.
8
38
  * @public
@@ -1 +1 @@
1
- {"version":3,"file":"interfaces.d.ts","sourceRoot":"","sources":["../../../src/packlets/mustache/interfaces.ts"],"names":[],"mappings":"AAuBA;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GACzB,MAAM,GACN,MAAM,GACN,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,CAAC;AAER;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;IAEjC;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,iBAAiB,CAAC;IAEtC;;;OAGG;IACH,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;CAC7B;AAED;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;IAEhC;;;OAGG;IACH,QAAQ,CAAC,e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;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAE1B;;OAEG;IACH,QAAQ,CAAC,gBAAgB,EAAE,SAAS,MAAM,EAAE,CAAC;IAE7C;;OAEG;IACH,QAAQ,CAAC,gBAAgB,EAAE,SAAS,MAAM,EAAE,CAAC;IAE7C;;OAEG;IACH,QAAQ,CAAC,cAAc,EAAE,SAAS,sBAAsB,EAAE,CAAC;CAC5D;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,MAAM,sBAAsB,GAAG,MAAM,GAAG,MAAM,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC,CAAC;AAEnF;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACvC;;OAEG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAE1C;;OAEG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IAEnC;;OAEG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IAEnC;;;;;;;;;;;;;;;OAeG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,sBAAsB,CAAC;CAC1C;AAED;;;GAGG;AACH,MAAM,WAAW,gCAAgC;IAC/C,QAAQ,CAAC,IAAI,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,QAAQ,CAAC,eAAe,EAAE,OAAO,CAAC;IAClC,QAAQ,CAAC,eAAe,EAAE,OAAO,CAAC;IAClC,QAAQ,CAAC,MAAM,EAAE,sBAAsB,CAAC;CACzC"}
@@ -1 +1 @@
1
- {"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../../src/packlets/mustache/interfaces.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D;;;;;;;;;;;;;;;;;;;;GAoBG;;AA8JH,oBAAoB","sourcesContent":["/* c8 ignore start - Type definitions only, no runtime code */\n/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Type of a Mustache token as returned by Mustache.parse()\n * @public\n */\nexport type MustacheTokenType =\n | 'text' // Raw text\n | 'name' // {{ variable }} - escaped value\n | '&' // {{{ variable }}} or {{& variable }} - unescaped value\n | '#' // {{# section }} - section start\n | '^' // {{^ section }} - inverted section\n | '!' // {{! comment }} - comment\n | '>' // {{> partial }} - partial\n | '='; // {{= =}} - set delimiter\n\n/**\n * Represents a variable reference extracted from a Mustache template.\n * @public\n */\nexport interface IVariableRef {\n /**\n * The raw variable name as it appears in the template (e.g., 'user.name')\n */\n readonly name: string;\n\n /**\n * The path segments parsed from the variable name (e.g., ['user', 'name'])\n */\n readonly path: readonly string[];\n\n /**\n * The type of token this variable was extracted from\n */\n readonly tokenType: MustacheTokenType;\n\n /**\n * Whether this variable is used in a section context (# or ^)\n * Section variables may reference arrays/objects for iteration\n */\n readonly isSection: boolean;\n}\n\n/**\n * Details about a missing variable in context validation.\n * @public\n */\nexport interface IMissingVariableDetail {\n /**\n * The variable reference that is missing\n */\n readonly variable: IVariableRef;\n\n /**\n * The path segment where the lookup failed\n * (e.g., for 'user.profile.name' if 'profile' is missing, this would be 'profile')\n */\n readonly failedAtSegment?: string;\n\n /**\n * The parent path that exists (e.g., ['user'] if 'user' exists but 'user.profile' does not)\n */\n readonly existingPath: readonly string[];\n}\n\n/**\n * Result of context validation, containing details about missing variables.\n * @public\n */\nexport interface IContextValidationResult {\n /**\n * Whether the context is valid (has all required variables)\n */\n readonly isValid: boolean;\n\n /**\n * Variables that are present in the context\n */\n readonly presentVariables: readonly string[];\n\n /**\n * Variables that are missing from the context\n */\n readonly missingVariables: readonly string[];\n\n /**\n * Detailed information about each missing variable\n */\n readonly missingDetails: readonly IMissingVariableDetail[];\n}\n\n/**\n * Strategy applied to double-brace `{{name}}` tokens at render time.\n *\n * - `'html'`: the standard mustache.js HTML escape (back-compat default).\n * - `'none'`: verbatim passthrough — values are interpolated as-is\n * (coerced to `String`). Suitable for LLM-prompt rendering and other\n * non-HTML targets where `& → &amp;` corrupts the output.\n * - `(value) => string`: caller-supplied escape function.\n *\n * Note: triple-brace `{{{name}}}` (and `{{&name}}`) tokens are always\n * rendered unescaped regardless of this strategy — that is the standard\n * mustache.js semantics and is not affected by this option.\n *\n * @public\n */\nexport type MustacheEscapeStrategy = 'html' | 'none' | ((value: string) => string);\n\n/**\n * Options for template parsing and validation.\n * @public\n */\nexport interface IMustacheTemplateOptions {\n /**\n * Custom opening and closing tags (default: `['{{', '}}']`)\n */\n readonly tags?: readonly [string, string];\n\n /**\n * Whether to include comment tokens in variable extraction (default: false)\n */\n readonly includeComments?: boolean;\n\n /**\n * Whether to include partial references in variable extraction (default: false)\n */\n readonly includePartials?: boolean;\n\n /**\n * Escape strategy applied to double-brace `{{name}}` tokens at render\n * time. Default `'html'` preserves the existing mustache.js behavior\n * (back-compat).\n *\n * Pass `'none'` for LLM-prompt or other non-HTML targets where the\n * default `& → &amp;` escape would corrupt the output. Pass a custom\n * function for any other escape policy.\n *\n * The strategy is applied per-template via a private `Mustache.Writer`\n * instance; no global state on the `mustache` module is mutated, so\n * concurrent templates with different strategies are safe.\n *\n * Note: triple-brace `{{{name}}}` tokens are always rendered unescaped\n * regardless of strategy (standard mustache.js semantics).\n */\n readonly escape?: MustacheEscapeStrategy;\n}\n\n/**\n * Required version of options with all fields populated.\n * @internal\n */\nexport interface IRequiredMustacheTemplateOptions {\n readonly tags: [string, string];\n readonly includeComments: boolean;\n readonly includePartials: boolean;\n readonly escape: MustacheEscapeStrategy;\n}\n\n/* c8 ignore stop */\n"]}
1
+ {"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../../src/packlets/mustache/interfaces.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D;;;;;;;;;;;;;;;;;;;;GAoBG;;AA8LH,oBAAoB","sourcesContent":["/* c8 ignore start - Type definitions only, no runtime code */\n/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Type of a Mustache token as returned by Mustache.parse()\n * @public\n */\nexport type MustacheTokenType =\n | 'text' // Raw text\n | 'name' // {{ variable }} - escaped value\n | '&' // {{{ variable }}} or {{& variable }} - unescaped value\n | '#' // {{# section }} - section start\n | '^' // {{^ section }} - inverted section\n | '!' // {{! comment }} - comment\n | '>' // {{> partial }} - partial\n | '='; // {{= =}} - set delimiter\n\n/**\n * One contiguous run of the rendered output, attributed to what produced it.\n * @public\n */\nexport interface IRenderedSegment {\n /** `'literal'` for template text; `'substitution'` for an interpolated value. */\n readonly kind: 'literal' | 'substitution';\n /** Variable name, when `kind` is `'substitution'`. */\n readonly name?: string;\n /** Offset into `IRenderedTemplate.text`, in UTF-16 code units. */\n readonly start: number;\n /** Length in UTF-16 code units. May be `0` for a variable that rendered empty. */\n readonly length: number;\n /** `false` for a triple-stash / `{{&}}` interpolation, which bypasses escaping. */\n readonly escaped: boolean;\n}\n\n/**\n * A render plus the map of which part of the output came from where.\n * @public\n */\nexport interface IRenderedTemplate {\n /** The rendered output — identical to what `MustacheTemplate.render` returns. */\n readonly text: string;\n /**\n * Document-ordered, contiguous and gapless: every code unit of `text` belongs to exactly one\n * segment, so concatenating them reproduces `text` exactly. That identity is verified before\n * this is returned.\n */\n readonly segments: ReadonlyArray<IRenderedSegment>;\n}\n\n/**\n * Represents a variable reference extracted from a Mustache template.\n * @public\n */\nexport interface IVariableRef {\n /**\n * The raw variable name as it appears in the template (e.g., 'user.name')\n */\n readonly name: string;\n\n /**\n * The path segments parsed from the variable name (e.g., ['user', 'name'])\n */\n readonly path: readonly string[];\n\n /**\n * The type of token this variable was extracted from\n */\n readonly tokenType: MustacheTokenType;\n\n /**\n * Whether this variable is used in a section context (# or ^)\n * Section variables may reference arrays/objects for iteration\n */\n readonly isSection: boolean;\n}\n\n/**\n * Details about a missing variable in context validation.\n * @public\n */\nexport interface IMissingVariableDetail {\n /**\n * The variable reference that is missing\n */\n readonly variable: IVariableRef;\n\n /**\n * The path segment where the lookup failed\n * (e.g., for 'user.profile.name' if 'profile' is missing, this would be 'profile')\n */\n readonly failedAtSegment?: string;\n\n /**\n * The parent path that exists (e.g., ['user'] if 'user' exists but 'user.profile' does not)\n */\n readonly existingPath: readonly string[];\n}\n\n/**\n * Result of context validation, containing details about missing variables.\n * @public\n */\nexport interface IContextValidationResult {\n /**\n * Whether the context is valid (has all required variables)\n */\n readonly isValid: boolean;\n\n /**\n * Variables that are present in the context\n */\n readonly presentVariables: readonly string[];\n\n /**\n * Variables that are missing from the context\n */\n readonly missingVariables: readonly string[];\n\n /**\n * Detailed information about each missing variable\n */\n readonly missingDetails: readonly IMissingVariableDetail[];\n}\n\n/**\n * Strategy applied to double-brace `{{name}}` tokens at render time.\n *\n * - `'html'`: the standard mustache.js HTML escape (back-compat default).\n * - `'none'`: verbatim passthrough — values are interpolated as-is\n * (coerced to `String`). Suitable for LLM-prompt rendering and other\n * non-HTML targets where `& → &amp;` corrupts the output.\n * - `(value) => string`: caller-supplied escape function.\n *\n * Note: triple-brace `{{{name}}}` (and `{{&name}}`) tokens are always\n * rendered unescaped regardless of this strategy — that is the standard\n * mustache.js semantics and is not affected by this option.\n *\n * @public\n */\nexport type MustacheEscapeStrategy = 'html' | 'none' | ((value: string) => string);\n\n/**\n * Options for template parsing and validation.\n * @public\n */\nexport interface IMustacheTemplateOptions {\n /**\n * Custom opening and closing tags (default: `['{{', '}}']`)\n */\n readonly tags?: readonly [string, string];\n\n /**\n * Whether to include comment tokens in variable extraction (default: false)\n */\n readonly includeComments?: boolean;\n\n /**\n * Whether to include partial references in variable extraction (default: false)\n */\n readonly includePartials?: boolean;\n\n /**\n * Escape strategy applied to double-brace `{{name}}` tokens at render\n * time. Default `'html'` preserves the existing mustache.js behavior\n * (back-compat).\n *\n * Pass `'none'` for LLM-prompt or other non-HTML targets where the\n * default `& → &amp;` escape would corrupt the output. Pass a custom\n * function for any other escape policy.\n *\n * The strategy is applied per-template via a private `Mustache.Writer`\n * instance; no global state on the `mustache` module is mutated, so\n * concurrent templates with different strategies are safe.\n *\n * Note: triple-brace `{{{name}}}` tokens are always rendered unescaped\n * regardless of strategy (standard mustache.js semantics).\n */\n readonly escape?: MustacheEscapeStrategy;\n}\n\n/**\n * Required version of options with all fields populated.\n * @internal\n */\nexport interface IRequiredMustacheTemplateOptions {\n readonly tags: [string, string];\n readonly includeComments: boolean;\n readonly includePartials: boolean;\n readonly escape: MustacheEscapeStrategy;\n}\n\n/* c8 ignore stop */\n"]}
@@ -1,5 +1,5 @@
1
1
  import { Result } from '@fgv/ts-utils';
2
- import { IContextValidationResult, IMustacheTemplateOptions, IRequiredMustacheTemplateOptions, IVariableRef } from './interfaces';
2
+ import { IContextValidationResult, IMustacheTemplateOptions, IRequiredMustacheTemplateOptions, IVariableRef, IRenderedTemplate } from './interfaces';
3
3
  /**
4
4
  * A helper class for working with Mustache templates that provides
5
5
  * validation, variable extraction, and context validation utilities.
@@ -63,6 +63,61 @@ export declare class MustacheTemplate {
63
63
  * @returns Success with the rendered string, or Failure if rendering fails
64
64
  */
65
65
  render(context: unknown): Result<string>;
66
+ /**
67
+ * Renders the template and reports which part of the output came from where.
68
+ *
69
+ * @remarks
70
+ * The rendered `text` is identical to `render`'s. What is added is
71
+ * `segments`: a document-ordered, contiguous, gapless attribution of every code unit to either
72
+ * template literal text or a named interpolation. It answers "what is in this output, in what
73
+ * order, and how much of it is each part" — a prompt's composition, a generated document's
74
+ * section sizes, a diff-free view of where a template's bulk actually goes.
75
+ *
76
+ * **Offsets are computed during the render, never recovered afterwards.** Recovering them by
77
+ * searching the output for each substituted value is the obvious shortcut and it is unsound: a
78
+ * value can occur more than once, can render empty, can be a substring of the surrounding
79
+ * literal text, and can be altered by escaping between input and output. That failure is silent
80
+ * and produces plausible offsets, which is the worst property a diagnostic can have.
81
+ *
82
+ * **Sections, inverted sections and partials are refused, not approximated.** Their rendered
83
+ * output is not a linear image of the token order — a section may repeat its body, or omit it —
84
+ * so a segment list walked from the template would mis-describe the result. Failing names the
85
+ * construct. Comments and set-delimiter tags emit nothing and are skipped; because each
86
+ * interpolation is rendered from its already-parsed token rather than from a re-parsed slice of
87
+ * the template, a set-delimiter tag has no effect on what this produces.
88
+ *
89
+ * **Every context value is evaluated exactly once, as `render()` evaluates it.** A lambda in the
90
+ * context is therefore invoked the same number of times either way, and a context whose lambda
91
+ * answers differently per call is rendered rather than rejected — the returned `segments` always
92
+ * describe the returned `text`, whatever that text was. (The concatenation identity is asserted
93
+ * across every shape in this package's test suite, not re-checked at runtime: re-checking means
94
+ * a second full render, which is precisely what would double those invocations.)
95
+ *
96
+ * @param context - The context object for template rendering.
97
+ * @returns Success with the rendered text and its segment map, or Failure if the
98
+ * template contains a construct this cannot describe
99
+ */
100
+ renderWithSegments(context: unknown): Result<IRenderedTemplate>;
101
+ /**
102
+ * Renders one interpolation token against a prepared lookup context.
103
+ *
104
+ * @remarks
105
+ * Delegates to the same `Writer` primitives `render()` reaches through `renderTokens`, so the
106
+ * value semantics — dotted paths, lambdas, `null` and `undefined` rendering empty, non-string
107
+ * coercion — are mustache.js's rather than a reimplementation of them.
108
+ *
109
+ * The token is passed as a freshly built `[type, name]` array rather than the parsed span. Both
110
+ * primitives read only the name, and `@types/mustache` declares the parameter as `string[]`
111
+ * while a parsed span carries its source offsets as numbers — so handing over the span would
112
+ * need a cast to work around the typings. Building the pair the primitives actually read needs
113
+ * none.
114
+ *
115
+ * @param type - `'name'` for an escaped interpolation, `'&'` for an unescaped one.
116
+ * @param name - The interpolation's name (may be a dotted path).
117
+ * @param lookup - The context to resolve the name against.
118
+ * @returns The rendered value; empty when the name resolves to `null` or `undefined`.
119
+ */
120
+ private _renderInterpolation;
66
121
  /**
67
122
  * Validates the context and renders the template if validation passes.
68
123
  * @param context - The context object to validate and render with
@@ -1 +1 @@
1
- {"version":3,"file":"mustacheTemplate.d.ts","sourceRoot":"","sources":["../../../src/packlets/mustache/mustacheTemplate.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,MAAM,EAAgC,MAAM,eAAe,CAAC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;;;;;;;OAiCG;IACI,kBAAkB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC,iBAAiB,CAAC;IA0CtE;;;;;;;;;;;;;;;;;;OAkBG;IACH,OAAO,CAAC,oBAAoB;IAY5B;;;;OAIG;IACI,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC;IAU1D,OAAO,CAAC,MAAM,CAAC,eAAe;IAa9B,OAAO,CAAC,MAAM,CAAC,YAAY;IAO3B,OAAO,CAAC,2BAA2B;IA6CnC,OAAO,CAAC,UAAU;IAUlB,OAAO,CAAC,WAAW;CAgCpB"}
@@ -185,6 +185,97 @@ class MustacheTemplate {
185
185
  render(context) {
186
186
  return (0, ts_utils_1.captureResult)(() => this._writer.render(this.template, context, undefined, { escape: this._escapeFn }));
187
187
  }
188
+ /**
189
+ * Renders the template and reports which part of the output came from where.
190
+ *
191
+ * @remarks
192
+ * The rendered `text` is identical to `render`'s. What is added is
193
+ * `segments`: a document-ordered, contiguous, gapless attribution of every code unit to either
194
+ * template literal text or a named interpolation. It answers "what is in this output, in what
195
+ * order, and how much of it is each part" — a prompt's composition, a generated document's
196
+ * section sizes, a diff-free view of where a template's bulk actually goes.
197
+ *
198
+ * **Offsets are computed during the render, never recovered afterwards.** Recovering them by
199
+ * searching the output for each substituted value is the obvious shortcut and it is unsound: a
200
+ * value can occur more than once, can render empty, can be a substring of the surrounding
201
+ * literal text, and can be altered by escaping between input and output. That failure is silent
202
+ * and produces plausible offsets, which is the worst property a diagnostic can have.
203
+ *
204
+ * **Sections, inverted sections and partials are refused, not approximated.** Their rendered
205
+ * output is not a linear image of the token order — a section may repeat its body, or omit it —
206
+ * so a segment list walked from the template would mis-describe the result. Failing names the
207
+ * construct. Comments and set-delimiter tags emit nothing and are skipped; because each
208
+ * interpolation is rendered from its already-parsed token rather than from a re-parsed slice of
209
+ * the template, a set-delimiter tag has no effect on what this produces.
210
+ *
211
+ * **Every context value is evaluated exactly once, as `render()` evaluates it.** A lambda in the
212
+ * context is therefore invoked the same number of times either way, and a context whose lambda
213
+ * answers differently per call is rendered rather than rejected — the returned `segments` always
214
+ * describe the returned `text`, whatever that text was. (The concatenation identity is asserted
215
+ * across every shape in this package's test suite, not re-checked at runtime: re-checking means
216
+ * a second full render, which is precisely what would double those invocations.)
217
+ *
218
+ * @param context - The context object for template rendering.
219
+ * @returns Success with the rendered text and its segment map, or Failure if the
220
+ * template contains a construct this cannot describe
221
+ */
222
+ renderWithSegments(context) {
223
+ return (0, ts_utils_1.captureResult)(() => {
224
+ const segments = [];
225
+ const lookup = new mustache_1.default.Context(context);
226
+ let text = '';
227
+ for (const token of this._tokens) {
228
+ const type = token[0];
229
+ if (type === '!' || type === '=') {
230
+ continue; // emits nothing
231
+ }
232
+ if (type !== 'text' && type !== 'name' && type !== '&') {
233
+ throw new Error(`renderWithSegments does not support '${type}' tokens (sections, inverted sections ` +
234
+ `and partials render non-linearly, so a segment map walked from the template would ` +
235
+ `misdescribe the output). Use render() for this template.`);
236
+ }
237
+ const rendered = type === 'text' ? String(token[1]) : this._renderInterpolation(type, String(token[1]), lookup);
238
+ segments.push(Object.assign(Object.assign({ kind: type === 'text' ? 'literal' : 'substitution' }, (type === 'text' ? {} : { name: String(token[1]) })), { start: text.length, length: rendered.length, escaped: type === 'name' }));
239
+ text += rendered;
240
+ }
241
+ // Deliberately NOT re-rendered and compared against render() here. Such a check did once
242
+ // catch a real defect, but paying for it means a second full render — which invokes every
243
+ // lambda in the context a second time, so the check both doubles a caller's side effects
244
+ // and turns a context whose lambda answers differently per call into a failure on a
245
+ // template that renders fine. The identity is asserted in the test suite instead, where a
246
+ // second render costs nobody anything.
247
+ return { text, segments };
248
+ });
249
+ }
250
+ /**
251
+ * Renders one interpolation token against a prepared lookup context.
252
+ *
253
+ * @remarks
254
+ * Delegates to the same `Writer` primitives `render()` reaches through `renderTokens`, so the
255
+ * value semantics — dotted paths, lambdas, `null` and `undefined` rendering empty, non-string
256
+ * coercion — are mustache.js's rather than a reimplementation of them.
257
+ *
258
+ * The token is passed as a freshly built `[type, name]` array rather than the parsed span. Both
259
+ * primitives read only the name, and `@types/mustache` declares the parameter as `string[]`
260
+ * while a parsed span carries its source offsets as numbers — so handing over the span would
261
+ * need a cast to work around the typings. Building the pair the primitives actually read needs
262
+ * none.
263
+ *
264
+ * @param type - `'name'` for an escaped interpolation, `'&'` for an unescaped one.
265
+ * @param name - The interpolation's name (may be a dotted path).
266
+ * @param lookup - The context to resolve the name against.
267
+ * @returns The rendered value; empty when the name resolves to `null` or `undefined`.
268
+ */
269
+ _renderInterpolation(type, name, lookup) {
270
+ const token = [type, name];
271
+ const value = type === 'name'
272
+ ? this._writer.escapedValue(token, lookup, { escape: this._escapeFn })
273
+ : this._writer.unescapedValue(token, lookup);
274
+ // Both primitives guard with `if (value != null)` and so return `undefined` — never `null` —
275
+ // for an absent value, which is why only `undefined` is tested here. `renderTokens` appends
276
+ // nothing in that case and string-coerces everything else.
277
+ return value === undefined ? '' : String(value);
278
+ }
188
279
  /**
189
280
  * Validates the context and renders the template if validation passes.
190
281
  * @param context - The context object to validate and render with
@@ -1 +1 @@
1
- {"version":3,"file":"mustacheTemplate.js","sourceRoot":"","sources":["../../../src/packlets/mustache/mustacheTemplate.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;AAEH,4CAAqE;AACrE,wDAA2E;AAY3E;;GAEG;AACH,MAAM,eAAe,GAAqC;IACxD,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;IAClB,eAAe,EAAE,KAAK;IACtB,eAAe,EAAE,KAAK;IACtB,MAAM,EAAE,MAAM;CACf,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,eAAe,GAAqC;IACxD,GAAG,EAAE,OAAO;IACZ,GAAG,EAAE,MAAM;IACX,GAAG,EAAE,MAAM;IACX,GAAG,EAAE,QAAQ;IACb,GAAG,EAAE,OAAO;IACZ,GAAG,EAAE,QAAQ;IACb,GA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AAO,EAAE,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;YAC3D,CAAC;YAED,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC;YACvB,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC7B,CAAC;QAED,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;IACvC,CAAC;CACF;AAtQD,4CAsQC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result, captureResult, fail, succeed } from '@fgv/ts-utils';\nimport Mustache, { EscapeFunction, TemplateSpans, Writer } from 'mustache';\n\nimport {\n IContextValidationResult,\n IMissingVariableDetail,\n IMustacheTemplateOptions,\n IRequiredMustacheTemplateOptions,\n IVariableRef,\n MustacheEscapeStrategy,\n MustacheTokenType\n} from './interfaces';\n\n/**\n * Default options for MustacheTemplate\n */\nconst DEFAULT_OPTIONS: IRequiredMustacheTemplateOptions = {\n tags: ['{{', '}}'],\n includeComments: false,\n includePartials: false,\n escape: 'html'\n};\n\n/**\n * HTML entity map matching mustache.js's internal `escapeHtml`. Held\n * locally so the `'html'` escape strategy does not depend on the global\n * `Mustache.escape` (which other packlets — notably `experimental` —\n * mutate at module load and which mustache.js itself defines as\n * mutable). Per-instance escape avoids that shared-state coupling.\n */\nconst HTML_ENTITY_MAP: Readonly<Record<string, string>> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n '/': '&#x2F;',\n '`': '&#x60;',\n '=': '&#x3D;'\n};\n\nconst HTML_ESCAPE: EscapeFunction = (value) =>\n String(value).replace(/[&<>\"'`=/]/g, (ch) => HTML_ENTITY_MAP[ch]);\n\nconst PASSTHROUGH_ESCAPE: EscapeFunction = (value) => String(value);\n\n/**\n * Resolves a {@link MustacheEscapeStrategy} into the per-render\n * `escape` function understood by `Mustache.Writer.render`. The\n * resolved function is always non-`undefined` so the writer never\n * consults the (mutable, process-global) `Mustache.escape`.\n */\nfunction _resolveEscapeFunction(strategy: MustacheEscapeStrategy): EscapeFunction {\n if (strategy === 'html') {\n return HTML_ESCAPE;\n }\n if (strategy === 'none') {\n return PASSTHROUGH_ESCAPE;\n }\n return (value) => strategy(String(value));\n}\n\n/**\n * A helper class for working with Mustache templates that provides\n * validation, variable extraction, and context validation utilities.\n * @public\n */\nexport class MustacheTemplate {\n /**\n * The original template string\n */\n public readonly template: string;\n\n /**\n * The options used for parsing this template\n */\n public readonly options: Readonly<IRequiredMustacheTemplateOptions>;\n\n private readonly _tokens: TemplateSpans;\n private readonly _writer: Writer;\n private readonly _escapeFn: EscapeFunction;\n private _variables?: readonly IVariableRef[];\n\n private constructor(template: string, tokens: TemplateSpans, options: IRequiredMustacheTemplateOptions) {\n this.template = template;\n this._tokens = tokens;\n this.options = options;\n this._writer = new Mustache.Writer();\n this._escapeFn = _resolveEscapeFunction(options.escape);\n }\n\n /**\n * Creates a new MustacheTemplate instance.\n * @param template - The Mustache template string to parse\n * @param options - Optional parsing options\n * @returns Success with the template instance, or Failure if parsing fails\n */\n public static create(template: string, options?: IMustacheTemplateOptions): Result<MustacheTemplate> {\n const resolvedOptions = MustacheTemplate._resolveOptions(options);\n return MustacheTemplate._parseTokens(template, resolvedOptions).onSuccess((tokens) => {\n return succeed(new MustacheTemplate(template, tokens, resolvedOptions));\n });\n }\n\n /**\n * Validates that a template string has valid Mustache syntax.\n * @param template - The template string to validate\n * @param options - Optional parsing options\n * @returns Success with true if valid, or Failure with a descriptive error message\n */\n public static validate(template: string, options?: IMustacheTemplateOptions): Result<true> {\n const resolvedOptions = MustacheTemplate._resolveOptions(options);\n return MustacheTemplate._parseTokens(template, resolvedOptions).onSuccess(() => succeed(true as const));\n }\n\n /**\n * Checks if this template instance has valid syntax.\n * Always returns Success(true) since parsing succeeded in create().\n * @returns Success with true\n */\n public validate(): Result<true> {\n return succeed(true as const);\n }\n\n /**\n * Extracts all variable references from the template.\n * @returns An array of variable references found in the template\n */\n public extractVariables(): readonly IVariableRef[] {\n if (this._variables === undefined) {\n this._variables = this._extractVariablesFromTokens(this._tokens);\n }\n return this._variables;\n }\n\n /**\n * Extracts unique variable names from the template.\n * @returns An array of unique variable name strings (e.g., ['user.name', 'items'])\n */\n public extractVariableNames(): readonly string[] {\n const variables = this.extractVariables();\n const seen = new Set<string>();\n const names: string[] = [];\n\n for (const variable of variables) {\n if (!seen.has(variable.name)) {\n seen.add(variable.name);\n names.push(variable.name);\n }\n }\n\n return names;\n }\n\n /**\n * Validates that a context object has all required variables.\n * @param context - The context object to validate\n * @returns Success with validation result containing details about present/missing variables\n */\n public validateContext(context: unknown): Result<IContextValidationResult> {\n const variables = this.extractVariables();\n const presentVariables: string[] = [];\n const missingVariables: string[] = [];\n const missingDetails: IMissingVariableDetail[] = [];\n const checked = new Set<string>();\n\n for (const variable of variables) {\n if (checked.has(variable.name)) {\n continue;\n }\n checked.add(variable.name);\n\n const lookup = this._lookupPath(context, variable.path);\n\n if (lookup.found) {\n presentVariables.push(variable.name);\n } else {\n missingVariables.push(variable.name);\n missingDetails.push({\n variable,\n failedAtSegment: lookup.failedAt,\n existingPath: lookup.existingPath\n });\n }\n }\n\n return succeed({\n isValid: missingVariables.length === 0,\n presentVariables,\n missingVariables,\n missingDetails\n });\n }\n\n /**\n * Renders the template with the given context.\n * Use this for pre-validated contexts where you've already checked\n * that all required variables are present.\n * @param context - The context object for template rendering\n * @returns Success with the rendered string, or Failure if rendering fails\n */\n public render(context: unknown): Result<string> {\n return captureResult(() =>\n this._writer.render(this.template, context, undefined, { escape: this._escapeFn })\n );\n }\n\n /**\n * Validates the context and renders the template if validation passes.\n * @param context - The context object to validate and render with\n * @returns Success with the rendered string, or Failure with validation or render errors\n */\n public validateAndRender(context: unknown): Result<string> {\n return this.validateContext(context).onSuccess((validation) => {\n if (!validation.isValid) {\n const missing = validation.missingVariables.join(', ');\n return fail(`Missing required variables: ${missing}`);\n }\n return this.render(context);\n });\n }\n\n private static _resolveOptions(options?: IMustacheTemplateOptions): IRequiredMustacheTemplateOptions {\n if (options === undefined) {\n return DEFAULT_OPTIONS;\n }\n\n return {\n tags: options.tags ? [options.tags[0], options.tags[1]] : DEFAULT_OPTIONS.tags,\n includeComments: options.includeComments ?? DEFAULT_OPTIONS.includeComments,\n includePartials: options.includePartials ?? DEFAULT_OPTIONS.includePartials,\n escape: options.escape ?? DEFAULT_OPTIONS.escape\n };\n }\n\n private static _parseTokens(\n template: string,\n options: IRequiredMustacheTemplateOptions\n ): Result<TemplateSpans> {\n return captureResult(() => Mustache.parse(template, options.tags));\n }\n\n private _extractVariablesFromTokens(tokens: TemplateSpans): IVariableRef[] {\n const variables: IVariableRef[] = [];\n\n for (const token of tokens) {\n const type = token[0] as MustacheTokenType;\n const value = token[1] as string;\n\n // Skip text tokens\n if (type === 'text') {\n continue;\n }\n\n // Handle comments based on options\n if (type === '!' && !this.options.includeComments) {\n continue;\n }\n\n // Handle partials based on options\n if (type === '>' && !this.options.includePartials) {\n continue;\n }\n\n // Handle variable tokens: 'name', '&', '#', '^', and optionally '!', '>'\n if (type === 'name' || type === '&' || type === '#' || type === '^' || type === '!' || type === '>') {\n const isSection = type === '#' || type === '^';\n variables.push({\n name: value,\n path: this._parsePath(value),\n tokenType: type,\n isSection\n });\n }\n\n // Recursively extract from nested tokens in sections\n if ((type === '#' || type === '^') && token.length > 4) {\n const nestedTokens = token[4] as TemplateSpans;\n if (nestedTokens) {\n variables.push(...this._extractVariablesFromTokens(nestedTokens));\n }\n }\n }\n\n return variables;\n }\n\n private _parsePath(name: string): readonly string[] {\n // Handle special case of '.' which means current context\n if (name === '.') {\n return ['.'];\n }\n\n // Split on dots to get path segments\n return name.split('.').filter((segment) => segment.length > 0);\n }\n\n private _lookupPath(\n context: unknown,\n path: readonly string[]\n ): { found: boolean; existingPath: string[]; failedAt?: string } {\n // Handle '.' which always exists if context is not null/undefined\n if (path.length === 1 && path[0] === '.') {\n return { found: context !== undefined && context !== null, existingPath: [] };\n }\n\n let current: unknown = context;\n const existingPath: string[] = [];\n\n for (const segment of path) {\n if (current === undefined || current === null) {\n return { found: false, existingPath, failedAt: segment };\n }\n\n if (typeof current !== 'object') {\n return { found: false, existingPath, failedAt: segment };\n }\n\n const obj = current as Record<string, unknown>;\n if (!(segment in obj)) {\n return { found: false, existingPath, failedAt: segment };\n }\n\n current = obj[segment];\n existingPath.push(segment);\n }\n\n return { found: true, existingPath };\n }\n}\n"]}
1
+ {"version":3,"file":"mustacheTemplate.js","sourceRoot":"","sources":["../../../src/packlets/mustache/mustacheTemplate.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;AAEH,4CAAqE;AACrE,wDAAoF;AAcpF;;GAEG;AACH,MAAM,eAAe,GAAqC;IACxD,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;IAClB,eAAe,EAAE,KAAK;IACtB,eAAe,EAAE,KAAK;IACt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,CAAC,OAAO,CAAC,CAAC;QAC7B,CAAC;QAED,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;IACvC,CAAC;CACF;AAjXD,4CAiXC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result, captureResult, fail, succeed } from '@fgv/ts-utils';\nimport Mustache, { Context, EscapeFunction, TemplateSpans, Writer } from 'mustache';\n\nimport {\n IContextValidationResult,\n IMissingVariableDetail,\n IMustacheTemplateOptions,\n IRequiredMustacheTemplateOptions,\n IVariableRef,\n MustacheEscapeStrategy,\n MustacheTokenType,\n IRenderedSegment,\n IRenderedTemplate\n} from './interfaces';\n\n/**\n * Default options for MustacheTemplate\n */\nconst DEFAULT_OPTIONS: IRequiredMustacheTemplateOptions = {\n tags: ['{{', '}}'],\n includeComments: false,\n includePartials: false,\n escape: 'html'\n};\n\n/**\n * HTML entity map matching mustache.js's internal `escapeHtml`. Held\n * locally so the `'html'` escape strategy does not depend on the global\n * `Mustache.escape` (which other packlets — notably `experimental` —\n * mutate at module load and which mustache.js itself defines as\n * mutable). Per-instance escape avoids that shared-state coupling.\n */\nconst HTML_ENTITY_MAP: Readonly<Record<string, string>> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n '/': '&#x2F;',\n '`': '&#x60;',\n '=': '&#x3D;'\n};\n\nconst HTML_ESCAPE: EscapeFunction = (value) =>\n String(value).replace(/[&<>\"'`=/]/g, (ch) => HTML_ENTITY_MAP[ch]);\n\nconst PASSTHROUGH_ESCAPE: EscapeFunction = (value) => String(value);\n\n/**\n * Resolves a {@link MustacheEscapeStrategy} into the per-render\n * `escape` function understood by `Mustache.Writer.render`. The\n * resolved function is always non-`undefined` so the writer never\n * consults the (mutable, process-global) `Mustache.escape`.\n */\nfunction _resolveEscapeFunction(strategy: MustacheEscapeStrategy): EscapeFunction {\n if (strategy === 'html') {\n return HTML_ESCAPE;\n }\n if (strategy === 'none') {\n return PASSTHROUGH_ESCAPE;\n }\n return (value) => strategy(String(value));\n}\n\n/**\n * A helper class for working with Mustache templates that provides\n * validation, variable extraction, and context validation utilities.\n * @public\n */\nexport class MustacheTemplate {\n /**\n * The original template string\n */\n public readonly template: string;\n\n /**\n * The options used for parsing this template\n */\n public readonly options: Readonly<IRequiredMustacheTemplateOptions>;\n\n private readonly _tokens: TemplateSpans;\n private readonly _writer: Writer;\n private readonly _escapeFn: EscapeFunction;\n private _variables?: readonly IVariableRef[];\n\n private constructor(template: string, tokens: TemplateSpans, options: IRequiredMustacheTemplateOptions) {\n this.template = template;\n this._tokens = tokens;\n this.options = options;\n this._writer = new Mustache.Writer();\n this._escapeFn = _resolveEscapeFunction(options.escape);\n }\n\n /**\n * Creates a new MustacheTemplate instance.\n * @param template - The Mustache template string to parse\n * @param options - Optional parsing options\n * @returns Success with the template instance, or Failure if parsing fails\n */\n public static create(template: string, options?: IMustacheTemplateOptions): Result<MustacheTemplate> {\n const resolvedOptions = MustacheTemplate._resolveOptions(options);\n return MustacheTemplate._parseTokens(template, resolvedOptions).onSuccess((tokens) => {\n return succeed(new MustacheTemplate(template, tokens, resolvedOptions));\n });\n }\n\n /**\n * Validates that a template string has valid Mustache syntax.\n * @param template - The template string to validate\n * @param options - Optional parsing options\n * @returns Success with true if valid, or Failure with a descriptive error message\n */\n public static validate(template: string, options?: IMustacheTemplateOptions): Result<true> {\n const resolvedOptions = MustacheTemplate._resolveOptions(options);\n return MustacheTemplate._parseTokens(template, resolvedOptions).onSuccess(() => succeed(true as const));\n }\n\n /**\n * Checks if this template instance has valid syntax.\n * Always returns Success(true) since parsing succeeded in create().\n * @returns Success with true\n */\n public validate(): Result<true> {\n return succeed(true as const);\n }\n\n /**\n * Extracts all variable references from the template.\n * @returns An array of variable references found in the template\n */\n public extractVariables(): readonly IVariableRef[] {\n if (this._variables === undefined) {\n this._variables = this._extractVariablesFromTokens(this._tokens);\n }\n return this._variables;\n }\n\n /**\n * Extracts unique variable names from the template.\n * @returns An array of unique variable name strings (e.g., ['user.name', 'items'])\n */\n public extractVariableNames(): readonly string[] {\n const variables = this.extractVariables();\n const seen = new Set<string>();\n const names: string[] = [];\n\n for (const variable of variables) {\n if (!seen.has(variable.name)) {\n seen.add(variable.name);\n names.push(variable.name);\n }\n }\n\n return names;\n }\n\n /**\n * Validates that a context object has all required variables.\n * @param context - The context object to validate\n * @returns Success with validation result containing details about present/missing variables\n */\n public validateContext(context: unknown): Result<IContextValidationResult> {\n const variables = this.extractVariables();\n const presentVariables: string[] = [];\n const missingVariables: string[] = [];\n const missingDetails: IMissingVariableDetail[] = [];\n const checked = new Set<string>();\n\n for (const variable of variables) {\n if (checked.has(variable.name)) {\n continue;\n }\n checked.add(variable.name);\n\n const lookup = this._lookupPath(context, variable.path);\n\n if (lookup.found) {\n presentVariables.push(variable.name);\n } else {\n missingVariables.push(variable.name);\n missingDetails.push({\n variable,\n failedAtSegment: lookup.failedAt,\n existingPath: lookup.existingPath\n });\n }\n }\n\n return succeed({\n isValid: missingVariables.length === 0,\n presentVariables,\n missingVariables,\n missingDetails\n });\n }\n\n /**\n * Renders the template with the given context.\n * Use this for pre-validated contexts where you've already checked\n * that all required variables are present.\n * @param context - The context object for template rendering\n * @returns Success with the rendered string, or Failure if rendering fails\n */\n public render(context: unknown): Result<string> {\n return captureResult(() =>\n this._writer.render(this.template, context, undefined, { escape: this._escapeFn })\n );\n }\n\n /**\n * Renders the template and reports which part of the output came from where.\n *\n * @remarks\n * The rendered `text` is identical to `render`'s. What is added is\n * `segments`: a document-ordered, contiguous, gapless attribution of every code unit to either\n * template literal text or a named interpolation. It answers \"what is in this output, in what\n * order, and how much of it is each part\" — a prompt's composition, a generated document's\n * section sizes, a diff-free view of where a template's bulk actually goes.\n *\n * **Offsets are computed during the render, never recovered afterwards.** Recovering them by\n * searching the output for each substituted value is the obvious shortcut and it is unsound: a\n * value can occur more than once, can render empty, can be a substring of the surrounding\n * literal text, and can be altered by escaping between input and output. That failure is silent\n * and produces plausible offsets, which is the worst property a diagnostic can have.\n *\n * **Sections, inverted sections and partials are refused, not approximated.** Their rendered\n * output is not a linear image of the token order — a section may repeat its body, or omit it —\n * so a segment list walked from the template would mis-describe the result. Failing names the\n * construct. Comments and set-delimiter tags emit nothing and are skipped; because each\n * interpolation is rendered from its already-parsed token rather than from a re-parsed slice of\n * the template, a set-delimiter tag has no effect on what this produces.\n *\n * **Every context value is evaluated exactly once, as `render()` evaluates it.** A lambda in the\n * context is therefore invoked the same number of times either way, and a context whose lambda\n * answers differently per call is rendered rather than rejected — the returned `segments` always\n * describe the returned `text`, whatever that text was. (The concatenation identity is asserted\n * across every shape in this package's test suite, not re-checked at runtime: re-checking means\n * a second full render, which is precisely what would double those invocations.)\n *\n * @param context - The context object for template rendering.\n * @returns Success with the rendered text and its segment map, or Failure if the\n * template contains a construct this cannot describe\n */\n public renderWithSegments(context: unknown): Result<IRenderedTemplate> {\n return captureResult((): IRenderedTemplate => {\n const segments: IRenderedSegment[] = [];\n const lookup = new Mustache.Context(context);\n let text = '';\n\n for (const token of this._tokens) {\n const type = token[0] as MustacheTokenType;\n if (type === '!' || type === '=') {\n continue; // emits nothing\n }\n if (type !== 'text' && type !== 'name' && type !== '&') {\n throw new Error(\n `renderWithSegments does not support '${type}' tokens (sections, inverted sections ` +\n `and partials render non-linearly, so a segment map walked from the template would ` +\n `misdescribe the output). Use render() for this template.`\n );\n }\n\n const rendered =\n type === 'text' ? String(token[1]) : this._renderInterpolation(type, String(token[1]), lookup);\n\n segments.push({\n kind: type === 'text' ? 'literal' : 'substitution',\n ...(type === 'text' ? {} : { name: String(token[1]) }),\n start: text.length,\n length: rendered.length,\n escaped: type === 'name'\n });\n text += rendered;\n }\n\n // Deliberately NOT re-rendered and compared against render() here. Such a check did once\n // catch a real defect, but paying for it means a second full render — which invokes every\n // lambda in the context a second time, so the check both doubles a caller's side effects\n // and turns a context whose lambda answers differently per call into a failure on a\n // template that renders fine. The identity is asserted in the test suite instead, where a\n // second render costs nobody anything.\n return { text, segments };\n });\n }\n\n /**\n * Renders one interpolation token against a prepared lookup context.\n *\n * @remarks\n * Delegates to the same `Writer` primitives `render()` reaches through `renderTokens`, so the\n * value semantics — dotted paths, lambdas, `null` and `undefined` rendering empty, non-string\n * coercion — are mustache.js's rather than a reimplementation of them.\n *\n * The token is passed as a freshly built `[type, name]` array rather than the parsed span. Both\n * primitives read only the name, and `@types/mustache` declares the parameter as `string[]`\n * while a parsed span carries its source offsets as numbers — so handing over the span would\n * need a cast to work around the typings. Building the pair the primitives actually read needs\n * none.\n *\n * @param type - `'name'` for an escaped interpolation, `'&'` for an unescaped one.\n * @param name - The interpolation's name (may be a dotted path).\n * @param lookup - The context to resolve the name against.\n * @returns The rendered value; empty when the name resolves to `null` or `undefined`.\n */\n private _renderInterpolation(type: 'name' | '&', name: string, lookup: Context): string {\n const token: string[] = [type, name];\n const value =\n type === 'name'\n ? this._writer.escapedValue(token, lookup, { escape: this._escapeFn })\n : this._writer.unescapedValue(token, lookup);\n // Both primitives guard with `if (value != null)` and so return `undefined` — never `null` —\n // for an absent value, which is why only `undefined` is tested here. `renderTokens` appends\n // nothing in that case and string-coerces everything else.\n return value === undefined ? '' : String(value);\n }\n\n /**\n * Validates the context and renders the template if validation passes.\n * @param context - The context object to validate and render with\n * @returns Success with the rendered string, or Failure with validation or render errors\n */\n public validateAndRender(context: unknown): Result<string> {\n return this.validateContext(context).onSuccess((validation) => {\n if (!validation.isValid) {\n const missing = validation.missingVariables.join(', ');\n return fail(`Missing required variables: ${missing}`);\n }\n return this.render(context);\n });\n }\n\n private static _resolveOptions(options?: IMustacheTemplateOptions): IRequiredMustacheTemplateOptions {\n if (options === undefined) {\n return DEFAULT_OPTIONS;\n }\n\n return {\n tags: options.tags ? [options.tags[0], options.tags[1]] : DEFAULT_OPTIONS.tags,\n includeComments: options.includeComments ?? DEFAULT_OPTIONS.includeComments,\n includePartials: options.includePartials ?? DEFAULT_OPTIONS.includePartials,\n escape: options.escape ?? DEFAULT_OPTIONS.escape\n };\n }\n\n private static _parseTokens(\n template: string,\n options: IRequiredMustacheTemplateOptions\n ): Result<TemplateSpans> {\n return captureResult(() => Mustache.parse(template, options.tags));\n }\n\n private _extractVariablesFromTokens(tokens: TemplateSpans): IVariableRef[] {\n const variables: IVariableRef[] = [];\n\n for (const token of tokens) {\n const type = token[0] as MustacheTokenType;\n const value = token[1] as string;\n\n // Skip text tokens\n if (type === 'text') {\n continue;\n }\n\n // Handle comments based on options\n if (type === '!' && !this.options.includeComments) {\n continue;\n }\n\n // Handle partials based on options\n if (type === '>' && !this.options.includePartials) {\n continue;\n }\n\n // Handle variable tokens: 'name', '&', '#', '^', and optionally '!', '>'\n if (type === 'name' || type === '&' || type === '#' || type === '^' || type === '!' || type === '>') {\n const isSection = type === '#' || type === '^';\n variables.push({\n name: value,\n path: this._parsePath(value),\n tokenType: type,\n isSection\n });\n }\n\n // Recursively extract from nested tokens in sections\n if ((type === '#' || type === '^') && token.length > 4) {\n const nestedTokens = token[4] as TemplateSpans;\n if (nestedTokens) {\n variables.push(...this._extractVariablesFromTokens(nestedTokens));\n }\n }\n }\n\n return variables;\n }\n\n private _parsePath(name: string): readonly string[] {\n // Handle special case of '.' which means current context\n if (name === '.') {\n return ['.'];\n }\n\n // Split on dots to get path segments\n return name.split('.').filter((segment) => segment.length > 0);\n }\n\n private _lookupPath(\n context: unknown,\n path: readonly string[]\n ): { found: boolean; existingPath: string[]; failedAt?: string } {\n // Handle '.' which always exists if context is not null/undefined\n if (path.length === 1 && path[0] === '.') {\n return { found: context !== undefined && context !== null, existingPath: [] };\n }\n\n let current: unknown = context;\n const existingPath: string[] = [];\n\n for (const segment of path) {\n if (current === undefined || current === null) {\n return { found: false, existingPath, failedAt: segment };\n }\n\n if (typeof current !== 'object') {\n return { found: false, existingPath, failedAt: segment };\n }\n\n const obj = current as Record<string, unknown>;\n if (!(segment in obj)) {\n return { found: false, existingPath, failedAt: segment };\n }\n\n current = obj[segment];\n existingPath.push(segment);\n }\n\n return { found: true, existingPath };\n }\n}\n"]}