@fgv/ts-extras 5.1.0-47 → 5.1.0-49
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.
- package/LICENSE +1 -1
- package/dist/packlets/ai-assist/completionClient.js +435 -0
- package/dist/packlets/ai-assist/completionClient.js.map +1 -0
- package/dist/packlets/ai-assist/embeddingClient.js +2 -2
- package/dist/packlets/ai-assist/embeddingClient.js.map +1 -1
- package/dist/packlets/ai-assist/endpoint.js +29 -0
- package/dist/packlets/ai-assist/endpoint.js.map +1 -1
- package/dist/packlets/ai-assist/http.js +48 -19
- package/dist/packlets/ai-assist/http.js.map +1 -1
- package/dist/packlets/ai-assist/imageGenerationClient.js +454 -0
- package/dist/packlets/ai-assist/imageGenerationClient.js.map +1 -0
- package/dist/packlets/ai-assist/index.js +3 -1
- package/dist/packlets/ai-assist/index.js.map +1 -1
- package/dist/packlets/ai-assist/jsonCompletion.js +1 -1
- package/dist/packlets/ai-assist/jsonCompletion.js.map +1 -1
- package/dist/packlets/ai-assist/listModelsClient.js +294 -0
- package/dist/packlets/ai-assist/listModelsClient.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +2 -5
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js +2 -1
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
- package/dist/packlets/crypto-utils/encryptedFile.js +37 -0
- package/dist/packlets/crypto-utils/encryptedFile.js.map +1 -1
- package/dist/packlets/crypto-utils/index.js +1 -1
- package/dist/packlets/crypto-utils/index.js.map +1 -1
- package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js +32 -0
- package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -1
- package/dist/ts-extras.d.ts +59 -4
- package/lib/packlets/ai-assist/completionClient.d.ts +74 -0
- package/lib/packlets/ai-assist/completionClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/completionClient.js +439 -0
- package/lib/packlets/ai-assist/completionClient.js.map +1 -0
- package/lib/packlets/ai-assist/embeddingClient.js +1 -1
- package/lib/packlets/ai-assist/embeddingClient.js.map +1 -1
- package/lib/packlets/ai-assist/endpoint.d.ts +21 -0
- package/lib/packlets/ai-assist/endpoint.d.ts.map +1 -1
- package/lib/packlets/ai-assist/endpoint.js +31 -0
- package/lib/packlets/ai-assist/endpoint.js.map +1 -1
- package/lib/packlets/ai-assist/http.d.ts +12 -2
- package/lib/packlets/ai-assist/http.d.ts.map +1 -1
- package/lib/packlets/ai-assist/http.js +49 -18
- package/lib/packlets/ai-assist/http.js.map +1 -1
- package/lib/packlets/ai-assist/imageGenerationClient.d.ts +46 -0
- package/lib/packlets/ai-assist/imageGenerationClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/imageGenerationClient.js +458 -0
- package/lib/packlets/ai-assist/imageGenerationClient.js.map +1 -0
- package/lib/packlets/ai-assist/index.d.ts +3 -1
- package/lib/packlets/ai-assist/index.d.ts.map +1 -1
- package/lib/packlets/ai-assist/index.js +9 -7
- package/lib/packlets/ai-assist/index.js.map +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.d.ts +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.d.ts.map +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.js +2 -2
- package/lib/packlets/ai-assist/jsonCompletion.js.map +1 -1
- package/lib/packlets/ai-assist/listModelsClient.d.ts +46 -0
- package/lib/packlets/ai-assist/listModelsClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/listModelsClient.js +298 -0
- package/lib/packlets/ai-assist/listModelsClient.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +2 -5
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js +2 -1
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
- package/lib/packlets/crypto-utils/encryptedFile.d.ts +25 -0
- package/lib/packlets/crypto-utils/encryptedFile.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/encryptedFile.js +38 -0
- package/lib/packlets/crypto-utils/encryptedFile.js.map +1 -1
- package/lib/packlets/crypto-utils/index.d.ts +1 -1
- package/lib/packlets/crypto-utils/index.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/index.js +2 -1
- package/lib/packlets/crypto-utils/index.js.map +1 -1
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts +30 -2
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts.map +1 -1
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js +32 -0
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -1
- package/package.json +7 -7
- package/dist/packlets/ai-assist/apiClient.js +0 -1236
- package/dist/packlets/ai-assist/apiClient.js.map +0 -1
- package/lib/packlets/ai-assist/apiClient.d.ts +0 -152
- package/lib/packlets/ai-assist/apiClient.d.ts.map +0 -1
- package/lib/packlets/ai-assist/apiClient.js +0 -1244
- package/lib/packlets/ai-assist/apiClient.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/anthropic.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;;;;;;;;;;;;;;;;;;;;;;AAudZ,kDAoEC;AAzhBD;;;;;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8BAA8B,MAAM,CAAC,KAAK,WAAW,SAAS,EAAE,CAAC,CAAC;IAChF,CAAC;IACD,MAAM,MAAM,GAAG,kBAAkB,aAAlB,kBAAkB,cAAlB,kBAAkB,GAAI,IAAI,GAAG,EAA6B,CAAC;IAC1E,MAAM,IAAI,GAAG,MAAM,IAAA,0BAAiB,EAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACzE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAA,kBAAO,EAAC,wBAAwB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;AACnG,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 * Streaming adapter for the Anthropic Messages API. Handles server tool\n * use (e.g. `web_search`) as unified `tool-event` markers and client-defined\n * tool calls (type `tool_use`) with B4 thinking-block accumulation.\n *\n * The ordered accumulation buffer preserves all content blocks from the\n * assistant turn in their original stream positions. The C3 continuation\n * builder reads this buffer to reconstruct the assistant turn for the\n * follow-up request.\n *\n * @packageDocumentation\n */\n\nimport { type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\nimport { type JsonObject } from '@fgv/ts-json-base';\n\nimport { buildAnthropicMessages } from '../chatRequestBuilders';\nimport {\n AiPrompt,\n DEFAULT_ANTHROPIC_MAX_TOKENS,\n type AiToolConfig,\n type IAiStreamEvent,\n type IChatMessage\n} from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { toAnthropicTools } from '../toolFormats';\nimport { anthropicEffortToBudgetTokens, type IResolvedThinkingConfig } from '../thinkingOptionsResolver';\nimport {\n IStreamApiConfig,\n MALFORMED_TOOL_USE_WARN_TAG,\n UNRECOGNIZED_EVENT_WARN_TAG,\n formatUnrecognizedEventPayloadPreview,\n openSseConnection,\n validateEventPayload\n} from './common';\n\n// ============================================================================\n// Accumulated block types (internal — used by C3 continuation builder)\n// ============================================================================\n\n/**\n * An accumulated `thinking` block from the assistant turn. The `thinking` text\n * and `signature` are both concatenated across their respective delta events.\n * The full block is passed to the C3 continuation builder for round-trip preservation.\n * @internal\n */\nexport interface IAccumulatedThinkingBlock {\n readonly type: 'thinking';\n thinking: string;\n signature: string;\n}\n\n/**\n * An accumulated `redacted_thinking` block from the assistant turn. The `data`\n * field is opaque and arrives complete in the `content_block_start` event — no\n * delta events follow. Passed through unmodified to the C3 continuation builder.\n * @internal\n */\nexport interface IAccumulatedRedactedThinkingBlock {\n readonly type: 'redacted_thinking';\n readonly data: string;\n}\n\n/**\n * An accumulated `text` block from the assistant turn.\n * @internal\n */\nexport interface IAccumulatedTextBlock {\n readonly type: 'text';\n text: string;\n}\n\n/**\n * An accumulated `tool_use` block from the assistant turn (client-defined tool call).\n * The `argsBuffer` is the concatenation of all `input_json_delta` chunks.\n * @internal\n */\nexport interface IAccumulatedToolUseBlock {\n readonly type: 'tool_use';\n readonly id: string;\n readonly name: string;\n argsBuffer: string;\n}\n\n/**\n * Discriminated union of all accumulated Anthropic content block types.\n * The ordered accumulation buffer is a `Map<number, IAccumulatedBlock>` keyed\n * by the SSE `index` field from `content_block_start` events.\n * @internal\n */\nexport type IAccumulatedBlock =\n | IAccumulatedThinkingBlock\n | IAccumulatedRedactedThinkingBlock\n | IAccumulatedTextBlock\n | IAccumulatedToolUseBlock;\n\n// ============================================================================\n// Event payload shapes\n// ============================================================================\n\n/**\n * Payload of a `content_block_start` SSE event with the `index` field.\n * The `index` field is optional for backward compatibility with providers that\n * omit it; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockStartPayload {\n readonly index?: number;\n readonly content_block: {\n readonly type?: string;\n readonly name?: string;\n readonly id?: string;\n readonly data?: string;\n };\n}\n\n/**\n * Payload of a `content_block_delta` SSE event. Various delta types are\n * discriminated on `delta.type`:\n * - `text_delta`: text content\n * - `input_json_delta`: tool argument accumulation\n * - `thinking_delta`: thinking text accumulation\n * - `signature_delta`: thinking signature accumulation (MUST be appended, not overwritten)\n *\n * The `index` field is optional; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockDeltaPayload {\n readonly index?: number;\n readonly delta: {\n readonly type?: string;\n readonly text?: string;\n readonly partial_json?: string;\n readonly thinking?: string;\n readonly signature?: string;\n };\n}\n\n/**\n * Payload of a `content_block_stop` SSE event.\n * The `index` field is optional; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockStopPayload {\n readonly index?: number;\n}\n\n/**\n * Payload of a `message_delta` SSE event carrying the final stop reason.\n * @internal\n */\ninterface IAnthropicMessageDeltaPayload {\n readonly delta: { readonly stop_reason?: string };\n}\n\n/**\n * Payload of an `error` SSE event.\n * @internal\n */\ninterface IAnthropicErrorPayload {\n readonly error?: { readonly message?: string };\n}\n\nconst anthropicContentBlockInner: Validator<{\n type?: string;\n name?: string;\n id?: string;\n data?: string;\n}> = Validators.object<{ type?: string; name?: string; id?: string; data?: string }>(\n {\n type: Validators.string.optional(),\n name: Validators.string.optional(),\n id: Validators.string.optional(),\n data: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'name', 'id', 'data'] } }\n);\n\nconst anthropicContentBlockStartPayload: Validator<IAnthropicContentBlockStartPayload> =\n Validators.object<IAnthropicContentBlockStartPayload>(\n {\n index: Validators.number.optional(),\n content_block: anthropicContentBlockInner\n },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicContentBlockDeltaInner: Validator<{\n type?: string;\n text?: string;\n partial_json?: string;\n thinking?: string;\n signature?: string;\n}> = Validators.object<{\n type?: string;\n text?: string;\n partial_json?: string;\n thinking?: string;\n signature?: string;\n}>(\n {\n type: Validators.string.optional(),\n text: Validators.string.optional(),\n partial_json: Validators.string.optional(),\n thinking: Validators.string.optional(),\n signature: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'text', 'partial_json', 'thinking', 'signature'] } }\n);\n\nconst anthropicContentBlockDeltaPayload: Validator<IAnthropicContentBlockDeltaPayload> =\n Validators.object<IAnthropicContentBlockDeltaPayload>(\n {\n index: Validators.number.optional(),\n delta: anthropicContentBlockDeltaInner\n },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicContentBlockStopPayload: Validator<IAnthropicContentBlockStopPayload> =\n Validators.object<IAnthropicContentBlockStopPayload>(\n { index: Validators.number.optional() },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicMessageDeltaInner: Validator<{ stop_reason?: string }> = Validators.object<{\n stop_reason?: string;\n}>({ stop_reason: Validators.string.optional() }, { options: { optionalFields: ['stop_reason'] } });\n\nconst anthropicMessageDeltaPayload: Validator<IAnthropicMessageDeltaPayload> =\n Validators.object<IAnthropicMessageDeltaPayload>({\n delta: anthropicMessageDeltaInner\n });\n\nconst anthropicErrorInner: Validator<{ message?: string }> = Validators.object<{ message?: string }>(\n { message: Validators.string.optional() },\n { options: { optionalFields: ['message'] } }\n);\n\nconst anthropicErrorPayload: Validator<IAnthropicErrorPayload> = Validators.object<IAnthropicErrorPayload>(\n { error: anthropicErrorInner.optional() },\n { options: { optionalFields: ['error'] } }\n);\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Recognized Anthropic Messages API SSE event names. Anything not in this set surfaces a\n * one-time `logger.warn` per stream — same rationale as the OpenAI Responses adapter's\n * `RECOGNIZED_OPENAI_RESPONSES_EVENTS` allowlist in `openaiResponses.ts`. Add to this set\n * when a new event type is observed and confirmed safe to ignore.\n *\n * @internal\n */\nconst RECOGNIZED_ANTHROPIC_EVENTS: ReadonlySet<string> = new Set<string>([\n // ---- handled by the translator ----\n 'content_block_start',\n 'content_block_delta',\n 'content_block_stop',\n 'message_delta',\n 'message_stop',\n 'error',\n // ---- lifecycle / heartbeats: intentionally silent ----\n 'message_start',\n 'ping'\n]);\n\n/**\n * Translates an Anthropic Messages API SSE stream into unified events.\n *\n * Maintains an ordered accumulation buffer (keyed by SSE `index`) for all\n * content blocks: `thinking`, `redacted_thinking`, `text`, and `tool_use`.\n * The buffer is available on the returned generator via `.accumulationBuffer`.\n *\n * Unrecognized event names are reported once per stream via `logger?.warn` —\n * see {@link RECOGNIZED_ANTHROPIC_EVENTS}.\n *\n * @internal\n */\nasync function* translateAnthropicStream(\n response: Response,\n accumulationBuffer: Map<number, IAccumulatedBlock>,\n logger?: Logging.ILogger\n): AsyncGenerator<IAiStreamEvent> {\n let fullText = '';\n let truncated = false;\n let stopped = false;\n // Track unrecognized event names we have already warned about, so a hot stream of\n // an unknown event type produces exactly one log line per name per stream.\n const warnedEvents = new Set<string>();\n\n try {\n /* c8 ignore next - body is non-null at this point per openSseConnection */\n if (!response.body) return;\n for await (const message of readSseEvents(response.body)) {\n const eventName = message.event;\n\n if (eventName === 'content_block_start') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockStartPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n const { index: rawIndex, content_block: block } = payload;\n const index = rawIndex ?? 0;\n\n if (block.type === 'thinking') {\n accumulationBuffer.set(index, { type: 'thinking', thinking: '', signature: '' });\n } else if (block.type === 'redacted_thinking') {\n accumulationBuffer.set(index, {\n type: 'redacted_thinking',\n /* c8 ignore next 1 - defensive: Anthropic always provides data for redacted_thinking */\n data: block.data ?? ''\n });\n } else if (block.type === 'text') {\n accumulationBuffer.set(index, { type: 'text', text: '' });\n } else if (block.type === 'tool_use') {\n // A tool_use block_start MUST carry a non-empty id and name: the id is the\n // sole correlation key for the follow-up tool_result, and dropping the block\n // silently (then ignoring its input_json_delta chunks at the delta handler\n // below) is exactly how an orphaned block leaves the harness without a clean\n // id and corrupts the continuation. Surface it loudly instead of dropping it.\n if (block.id && block.name) {\n accumulationBuffer.set(index, {\n type: 'tool_use',\n id: block.id,\n name: block.name,\n argsBuffer: ''\n });\n yield { type: 'client-tool-call-start', toolName: block.name, callId: block.id };\n } else {\n logger?.warn(\n `${MALFORMED_TOOL_USE_WARN_TAG} Anthropic streaming adapter: tool_use content_block_start ` +\n `at index ${index} is missing a usable id and/or name ` +\n `(id=${JSON.stringify(block.id)}, name=${JSON.stringify(block.name)}). ` +\n `No client tool call will be issued for this block; its argument deltas are dropped. ` +\n `This usually indicates provider drift or a truncated stream.`\n );\n }\n } else if (block.type === 'server_tool_use' && block.name === 'web_search') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'started' };\n } else if (block.type === 'web_search_tool_result') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'completed' };\n }\n } else if (eventName === 'content_block_delta') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockDeltaPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n const { index: rawDeltaIndex, delta } = payload;\n const index = rawDeltaIndex ?? 0;\n const block = accumulationBuffer.get(index);\n\n if (delta.type === 'text_delta' && typeof delta.text === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'text') {\n block.text += delta.text;\n }\n if (delta.text.length > 0) {\n fullText += delta.text;\n yield { type: 'text-delta', delta: delta.text };\n }\n } else if (delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'tool_use') {\n block.argsBuffer += delta.partial_json;\n }\n } else if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'thinking') {\n block.thinking += delta.thinking;\n }\n } else if (delta.type === 'signature_delta' && typeof delta.signature === 'string') {\n // CRITICAL (E5): signature must be APPENDED, not overwritten.\n // The signature is base64 arriving in multiple chunks.\n // Overwriting produces a truncated signature that Anthropic rejects with HTTP 400.\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'thinking') {\n block.signature += delta.signature;\n }\n }\n } else if (eventName === 'content_block_stop') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockStopPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n /* c8 ignore next 1 - defensive: payload.index ?? 0 null branch is unreachable */\n const block = accumulationBuffer.get(payload.index ?? 0);\n /* c8 ignore next 1 - defensive: block always exists when block_stop follows block_start */\n if (block?.type === 'tool_use') {\n let args: JsonObject;\n try {\n /* c8 ignore next 1 - defensive: argsBuffer || '{}' empty-string branch unreachable in tests */\n const parsed = JSON.parse(block.argsBuffer || '{}') as unknown;\n /* c8 ignore start - defensive: non-object/malformed parse defaults to empty object */\n args =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as JsonObject)\n : {};\n } catch {\n args = {};\n }\n /* c8 ignore stop */\n yield { type: 'client-tool-call-done', toolName: block.name, callId: block.id, args };\n }\n } else if (eventName === 'message_delta') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicMessageDeltaPayload);\n /* c8 ignore next 1 - defensive: payload?.delta null branch unreachable after validation */\n if (payload?.delta.stop_reason === 'max_tokens') {\n truncated = true;\n }\n } else if (eventName === 'message_stop') {\n stopped = true;\n } else if (eventName === 'error') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicErrorPayload);\n yield {\n type: 'error',\n /* c8 ignore next 1 - defensive: payload?.error null branch unreachable after validation */\n message: payload?.error?.message ?? 'Anthropic stream returned an error event'\n };\n return;\n } else if (\n typeof eventName === 'string' &&\n !RECOGNIZED_ANTHROPIC_EVENTS.has(eventName) &&\n !warnedEvents.has(eventName)\n ) {\n // Empirical drift instrument: an unrecognized Anthropic event surfaces as a one-time\n // warning per stream. Update RECOGNIZED_ANTHROPIC_EVENTS once the new event is either\n // handled or confirmed safe to ignore.\n warnedEvents.add(eventName);\n logger?.warn(\n `${UNRECOGNIZED_EVENT_WARN_TAG} Anthropic streaming adapter: unrecognized SSE event ` +\n `'${eventName}'. ` +\n `payload preview: ${formatUnrecognizedEventPayloadPreview(message.data)}. ` +\n `This may indicate provider drift — if the new event carries data the adapter ` +\n `should surface, add a handler; otherwise add the name to ` +\n `RECOGNIZED_ANTHROPIC_EVENTS.`\n );\n }\n }\n } catch (err: unknown) /* c8 ignore start - defensive: stream errors are always Error instances */ {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n return;\n } /* c8 ignore stop */\n\n if (stopped) {\n yield { type: 'done', truncated, fullText };\n } else {\n yield { type: 'error', message: 'Anthropic stream ended without a message_stop event' };\n }\n}\n\n// ============================================================================\n// Per-format request caller\n// ============================================================================\n\n/**\n * Issues a streaming Anthropic Messages request and returns the\n * unified-event iterable on success.\n *\n * @internal\n */\nexport async function callAnthropicStream(\n config: IStreamApiConfig,\n prompt: AiPrompt,\n messagesBefore: ReadonlyArray<IChatMessage> | undefined,\n temperature: number | undefined,\n tools: ReadonlyArray<AiToolConfig> | undefined,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n accumulationBuffer?: Map<number, IAccumulatedBlock>,\n continuationMessages?: ReadonlyArray<JsonObject>,\n useAdaptiveThinking: boolean = false,\n maxTokens?: number\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const url = `${config.baseUrl}/messages`;\n const messages = buildAnthropicMessages(prompt, {\n head: messagesBefore,\n rawTail: continuationMessages\n });\n const body: Record<string, unknown> = {\n model: config.model,\n system: prompt.system,\n messages,\n // Anthropic's Messages API requires max_tokens on every request — see\n // AiAssist.DEFAULT_ANTHROPIC_MAX_TOKENS for why only this provider defaults it.\n max_tokens: maxTokens ?? DEFAULT_ANTHROPIC_MAX_TOKENS,\n stream: true\n };\n // Temperature is sent only when explicitly provided (Claude-5 rejects any temperature). When\n // thinking is active it is also rejected — the completion/streaming paths validate this upstream,\n // and the effort gate here is the safety net for the (unguarded) client-tool path.\n if (resolvedThinking?.anthropicEffort === undefined) {\n if (temperature !== undefined) {\n body.temperature = temperature;\n }\n }\n if (resolvedThinking?.anthropicEffort !== undefined) {\n if (useAdaptiveThinking) {\n // Claude 5 family: adaptive thinking — no budget_tokens; effort moves to the\n // top-level output_config block. See AiAssist.isAdaptiveThinkingModel.\n body.thinking = { type: 'adaptive' };\n body.output_config = { effort: resolvedThinking.anthropicEffort };\n } else {\n body.thinking = {\n type: 'enabled',\n budget_tokens: anthropicEffortToBudgetTokens(resolvedThinking.anthropicEffort)\n };\n }\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(body, resolvedThinking.otherParams);\n }\n if (tools && tools.length > 0) {\n body.tools = toAnthropicTools(tools);\n }\n const headers: Record<string, string> = {\n 'x-api-key': config.apiKey,\n 'anthropic-version': '2023-06-01',\n 'anthropic-dangerous-direct-browser-access': 'true'\n };\n /* c8 ignore next 4 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';\n logger.info(`Anthropic streaming: model=${config.model}, tools=${toolTypes}`);\n }\n const buffer = accumulationBuffer ?? new Map<number, IAccumulatedBlock>();\n const conn = await openSseConnection(url, headers, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateAnthropicStream(response, buffer, logger)));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/anthropic.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;;;;;;;;;;;;;;;;;;;;;;AAwdZ,kDAgEC;AAthBD;;;;;;;;;;;GAWG;AAEH,4CAA0F;AAG1F,gEAAgE;AAChE,0CAAmD;AACnD,oCAMkB;AAClB,4CAAgE;AAChE,gDAAkD;AAClD,wEAAyG;AACzG,qCAOkB;AAiIlB,MAAM,0BAA0B,GAK3B,qBAAU,CAAC,MAAM,CACpB;IACE,IAAI,EAAE,qBAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAClC,IAAI,EAAE,qBAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAClC,EAAE,EAAE,qBAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAChC,IAAI,EAAE,qBAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;CACnC,EACD,EAAE,OAAO,EAAE,EAAE,cAAc,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,EAAE,EAAE,CAChE,CAAC;AAEF,MAAM,iCAAiC,GACrC,qBAAU,CAAC,MAAM,CACf;IACE,KAAK,EAAE,qBAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IACnC,aAAa,EAAE,0BAA0B;CAC1C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C;IACD,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,IAAA,8BAAgB,EAAC,KAAK,CAAC,CAAC;IACvC,CAAC;IACD,MAAM,OAAO,GAA2B,IAAA,+BAAoB,EAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC5E,0DAA0D;IAC1D,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,SAAS,GAAG,KAAK,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAC1F,MAAM,CAAC,IAAI,CAAC,8BAA8B,MAAM,CAAC,KAAK,WAAW,SAAS,EAAE,CAAC,CAAC;IAChF,CAAC;IACD,MAAM,MAAM,GAAG,kBAAkB,aAAlB,kBAAkB,cAAlB,kBAAkB,GAAI,IAAI,GAAG,EAA6B,CAAC;IAC1E,MAAM,IAAI,GAAG,MAAM,IAAA,0BAAiB,EAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACzE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAA,kBAAO,EAAC,wBAAwB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;AACnG,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 * Streaming adapter for the Anthropic Messages API. Handles server tool\n * use (e.g. `web_search`) as unified `tool-event` markers and client-defined\n * tool calls (type `tool_use`) with B4 thinking-block accumulation.\n *\n * The ordered accumulation buffer preserves all content blocks from the\n * assistant turn in their original stream positions. The C3 continuation\n * builder reads this buffer to reconstruct the assistant turn for the\n * follow-up request.\n *\n * @packageDocumentation\n */\n\nimport { type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\nimport { type JsonObject } from '@fgv/ts-json-base';\n\nimport { buildAnthropicMessages } from '../chatRequestBuilders';\nimport { anthropicAuthHeaders } from '../endpoint';\nimport {\n AiPrompt,\n DEFAULT_ANTHROPIC_MAX_TOKENS,\n type AiToolConfig,\n type IAiStreamEvent,\n type IChatMessage\n} from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { toAnthropicTools } from '../toolFormats';\nimport { anthropicEffortToBudgetTokens, type IResolvedThinkingConfig } from '../thinkingOptionsResolver';\nimport {\n IStreamApiConfig,\n MALFORMED_TOOL_USE_WARN_TAG,\n UNRECOGNIZED_EVENT_WARN_TAG,\n formatUnrecognizedEventPayloadPreview,\n openSseConnection,\n validateEventPayload\n} from './common';\n\n// ============================================================================\n// Accumulated block types (internal — used by C3 continuation builder)\n// ============================================================================\n\n/**\n * An accumulated `thinking` block from the assistant turn. The `thinking` text\n * and `signature` are both concatenated across their respective delta events.\n * The full block is passed to the C3 continuation builder for round-trip preservation.\n * @internal\n */\nexport interface IAccumulatedThinkingBlock {\n readonly type: 'thinking';\n thinking: string;\n signature: string;\n}\n\n/**\n * An accumulated `redacted_thinking` block from the assistant turn. The `data`\n * field is opaque and arrives complete in the `content_block_start` event — no\n * delta events follow. Passed through unmodified to the C3 continuation builder.\n * @internal\n */\nexport interface IAccumulatedRedactedThinkingBlock {\n readonly type: 'redacted_thinking';\n readonly data: string;\n}\n\n/**\n * An accumulated `text` block from the assistant turn.\n * @internal\n */\nexport interface IAccumulatedTextBlock {\n readonly type: 'text';\n text: string;\n}\n\n/**\n * An accumulated `tool_use` block from the assistant turn (client-defined tool call).\n * The `argsBuffer` is the concatenation of all `input_json_delta` chunks.\n * @internal\n */\nexport interface IAccumulatedToolUseBlock {\n readonly type: 'tool_use';\n readonly id: string;\n readonly name: string;\n argsBuffer: string;\n}\n\n/**\n * Discriminated union of all accumulated Anthropic content block types.\n * The ordered accumulation buffer is a `Map<number, IAccumulatedBlock>` keyed\n * by the SSE `index` field from `content_block_start` events.\n * @internal\n */\nexport type IAccumulatedBlock =\n | IAccumulatedThinkingBlock\n | IAccumulatedRedactedThinkingBlock\n | IAccumulatedTextBlock\n | IAccumulatedToolUseBlock;\n\n// ============================================================================\n// Event payload shapes\n// ============================================================================\n\n/**\n * Payload of a `content_block_start` SSE event with the `index` field.\n * The `index` field is optional for backward compatibility with providers that\n * omit it; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockStartPayload {\n readonly index?: number;\n readonly content_block: {\n readonly type?: string;\n readonly name?: string;\n readonly id?: string;\n readonly data?: string;\n };\n}\n\n/**\n * Payload of a `content_block_delta` SSE event. Various delta types are\n * discriminated on `delta.type`:\n * - `text_delta`: text content\n * - `input_json_delta`: tool argument accumulation\n * - `thinking_delta`: thinking text accumulation\n * - `signature_delta`: thinking signature accumulation (MUST be appended, not overwritten)\n *\n * The `index` field is optional; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockDeltaPayload {\n readonly index?: number;\n readonly delta: {\n readonly type?: string;\n readonly text?: string;\n readonly partial_json?: string;\n readonly thinking?: string;\n readonly signature?: string;\n };\n}\n\n/**\n * Payload of a `content_block_stop` SSE event.\n * The `index` field is optional; absent index defaults to 0 in the stream translator.\n * @internal\n */\ninterface IAnthropicContentBlockStopPayload {\n readonly index?: number;\n}\n\n/**\n * Payload of a `message_delta` SSE event carrying the final stop reason.\n * @internal\n */\ninterface IAnthropicMessageDeltaPayload {\n readonly delta: { readonly stop_reason?: string };\n}\n\n/**\n * Payload of an `error` SSE event.\n * @internal\n */\ninterface IAnthropicErrorPayload {\n readonly error?: { readonly message?: string };\n}\n\nconst anthropicContentBlockInner: Validator<{\n type?: string;\n name?: string;\n id?: string;\n data?: string;\n}> = Validators.object<{ type?: string; name?: string; id?: string; data?: string }>(\n {\n type: Validators.string.optional(),\n name: Validators.string.optional(),\n id: Validators.string.optional(),\n data: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'name', 'id', 'data'] } }\n);\n\nconst anthropicContentBlockStartPayload: Validator<IAnthropicContentBlockStartPayload> =\n Validators.object<IAnthropicContentBlockStartPayload>(\n {\n index: Validators.number.optional(),\n content_block: anthropicContentBlockInner\n },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicContentBlockDeltaInner: Validator<{\n type?: string;\n text?: string;\n partial_json?: string;\n thinking?: string;\n signature?: string;\n}> = Validators.object<{\n type?: string;\n text?: string;\n partial_json?: string;\n thinking?: string;\n signature?: string;\n}>(\n {\n type: Validators.string.optional(),\n text: Validators.string.optional(),\n partial_json: Validators.string.optional(),\n thinking: Validators.string.optional(),\n signature: Validators.string.optional()\n },\n { options: { optionalFields: ['type', 'text', 'partial_json', 'thinking', 'signature'] } }\n);\n\nconst anthropicContentBlockDeltaPayload: Validator<IAnthropicContentBlockDeltaPayload> =\n Validators.object<IAnthropicContentBlockDeltaPayload>(\n {\n index: Validators.number.optional(),\n delta: anthropicContentBlockDeltaInner\n },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicContentBlockStopPayload: Validator<IAnthropicContentBlockStopPayload> =\n Validators.object<IAnthropicContentBlockStopPayload>(\n { index: Validators.number.optional() },\n { options: { optionalFields: ['index'] } }\n );\n\nconst anthropicMessageDeltaInner: Validator<{ stop_reason?: string }> = Validators.object<{\n stop_reason?: string;\n}>({ stop_reason: Validators.string.optional() }, { options: { optionalFields: ['stop_reason'] } });\n\nconst anthropicMessageDeltaPayload: Validator<IAnthropicMessageDeltaPayload> =\n Validators.object<IAnthropicMessageDeltaPayload>({\n delta: anthropicMessageDeltaInner\n });\n\nconst anthropicErrorInner: Validator<{ message?: string }> = Validators.object<{ message?: string }>(\n { message: Validators.string.optional() },\n { options: { optionalFields: ['message'] } }\n);\n\nconst anthropicErrorPayload: Validator<IAnthropicErrorPayload> = Validators.object<IAnthropicErrorPayload>(\n { error: anthropicErrorInner.optional() },\n { options: { optionalFields: ['error'] } }\n);\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Recognized Anthropic Messages API SSE event names. Anything not in this set surfaces a\n * one-time `logger.warn` per stream — same rationale as the OpenAI Responses adapter's\n * `RECOGNIZED_OPENAI_RESPONSES_EVENTS` allowlist in `openaiResponses.ts`. Add to this set\n * when a new event type is observed and confirmed safe to ignore.\n *\n * @internal\n */\nconst RECOGNIZED_ANTHROPIC_EVENTS: ReadonlySet<string> = new Set<string>([\n // ---- handled by the translator ----\n 'content_block_start',\n 'content_block_delta',\n 'content_block_stop',\n 'message_delta',\n 'message_stop',\n 'error',\n // ---- lifecycle / heartbeats: intentionally silent ----\n 'message_start',\n 'ping'\n]);\n\n/**\n * Translates an Anthropic Messages API SSE stream into unified events.\n *\n * Maintains an ordered accumulation buffer (keyed by SSE `index`) for all\n * content blocks: `thinking`, `redacted_thinking`, `text`, and `tool_use`.\n * The buffer is available on the returned generator via `.accumulationBuffer`.\n *\n * Unrecognized event names are reported once per stream via `logger?.warn` —\n * see {@link RECOGNIZED_ANTHROPIC_EVENTS}.\n *\n * @internal\n */\nasync function* translateAnthropicStream(\n response: Response,\n accumulationBuffer: Map<number, IAccumulatedBlock>,\n logger?: Logging.ILogger\n): AsyncGenerator<IAiStreamEvent> {\n let fullText = '';\n let truncated = false;\n let stopped = false;\n // Track unrecognized event names we have already warned about, so a hot stream of\n // an unknown event type produces exactly one log line per name per stream.\n const warnedEvents = new Set<string>();\n\n try {\n /* c8 ignore next - body is non-null at this point per openSseConnection */\n if (!response.body) return;\n for await (const message of readSseEvents(response.body)) {\n const eventName = message.event;\n\n if (eventName === 'content_block_start') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockStartPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n const { index: rawIndex, content_block: block } = payload;\n const index = rawIndex ?? 0;\n\n if (block.type === 'thinking') {\n accumulationBuffer.set(index, { type: 'thinking', thinking: '', signature: '' });\n } else if (block.type === 'redacted_thinking') {\n accumulationBuffer.set(index, {\n type: 'redacted_thinking',\n /* c8 ignore next 1 - defensive: Anthropic always provides data for redacted_thinking */\n data: block.data ?? ''\n });\n } else if (block.type === 'text') {\n accumulationBuffer.set(index, { type: 'text', text: '' });\n } else if (block.type === 'tool_use') {\n // A tool_use block_start MUST carry a non-empty id and name: the id is the\n // sole correlation key for the follow-up tool_result, and dropping the block\n // silently (then ignoring its input_json_delta chunks at the delta handler\n // below) is exactly how an orphaned block leaves the harness without a clean\n // id and corrupts the continuation. Surface it loudly instead of dropping it.\n if (block.id && block.name) {\n accumulationBuffer.set(index, {\n type: 'tool_use',\n id: block.id,\n name: block.name,\n argsBuffer: ''\n });\n yield { type: 'client-tool-call-start', toolName: block.name, callId: block.id };\n } else {\n logger?.warn(\n `${MALFORMED_TOOL_USE_WARN_TAG} Anthropic streaming adapter: tool_use content_block_start ` +\n `at index ${index} is missing a usable id and/or name ` +\n `(id=${JSON.stringify(block.id)}, name=${JSON.stringify(block.name)}). ` +\n `No client tool call will be issued for this block; its argument deltas are dropped. ` +\n `This usually indicates provider drift or a truncated stream.`\n );\n }\n } else if (block.type === 'server_tool_use' && block.name === 'web_search') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'started' };\n } else if (block.type === 'web_search_tool_result') {\n yield { type: 'tool-event', toolType: 'web_search', phase: 'completed' };\n }\n } else if (eventName === 'content_block_delta') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockDeltaPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n const { index: rawDeltaIndex, delta } = payload;\n const index = rawDeltaIndex ?? 0;\n const block = accumulationBuffer.get(index);\n\n if (delta.type === 'text_delta' && typeof delta.text === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'text') {\n block.text += delta.text;\n }\n if (delta.text.length > 0) {\n fullText += delta.text;\n yield { type: 'text-delta', delta: delta.text };\n }\n } else if (delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'tool_use') {\n block.argsBuffer += delta.partial_json;\n }\n } else if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'thinking') {\n block.thinking += delta.thinking;\n }\n } else if (delta.type === 'signature_delta' && typeof delta.signature === 'string') {\n // CRITICAL (E5): signature must be APPENDED, not overwritten.\n // The signature is base64 arriving in multiple chunks.\n // Overwriting produces a truncated signature that Anthropic rejects with HTTP 400.\n /* c8 ignore next 1 - defensive: delta arrives only after block_start sets buffer entry */\n if (block?.type === 'thinking') {\n block.signature += delta.signature;\n }\n }\n } else if (eventName === 'content_block_stop') {\n const payload = validateEventPayload(\n parseSseEventJson(message.data),\n anthropicContentBlockStopPayload\n );\n /* c8 ignore next 1 - defensive: payload null branch unreachable after validation */\n if (!payload) continue;\n /* c8 ignore next 1 - defensive: payload.index ?? 0 null branch is unreachable */\n const block = accumulationBuffer.get(payload.index ?? 0);\n /* c8 ignore next 1 - defensive: block always exists when block_stop follows block_start */\n if (block?.type === 'tool_use') {\n let args: JsonObject;\n try {\n /* c8 ignore next 1 - defensive: argsBuffer || '{}' empty-string branch unreachable in tests */\n const parsed = JSON.parse(block.argsBuffer || '{}') as unknown;\n /* c8 ignore start - defensive: non-object/malformed parse defaults to empty object */\n args =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as JsonObject)\n : {};\n } catch {\n args = {};\n }\n /* c8 ignore stop */\n yield { type: 'client-tool-call-done', toolName: block.name, callId: block.id, args };\n }\n } else if (eventName === 'message_delta') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicMessageDeltaPayload);\n /* c8 ignore next 1 - defensive: payload?.delta null branch unreachable after validation */\n if (payload?.delta.stop_reason === 'max_tokens') {\n truncated = true;\n }\n } else if (eventName === 'message_stop') {\n stopped = true;\n } else if (eventName === 'error') {\n const payload = validateEventPayload(parseSseEventJson(message.data), anthropicErrorPayload);\n yield {\n type: 'error',\n /* c8 ignore next 1 - defensive: payload?.error null branch unreachable after validation */\n message: payload?.error?.message ?? 'Anthropic stream returned an error event'\n };\n return;\n } else if (\n typeof eventName === 'string' &&\n !RECOGNIZED_ANTHROPIC_EVENTS.has(eventName) &&\n !warnedEvents.has(eventName)\n ) {\n // Empirical drift instrument: an unrecognized Anthropic event surfaces as a one-time\n // warning per stream. Update RECOGNIZED_ANTHROPIC_EVENTS once the new event is either\n // handled or confirmed safe to ignore.\n warnedEvents.add(eventName);\n logger?.warn(\n `${UNRECOGNIZED_EVENT_WARN_TAG} Anthropic streaming adapter: unrecognized SSE event ` +\n `'${eventName}'. ` +\n `payload preview: ${formatUnrecognizedEventPayloadPreview(message.data)}. ` +\n `This may indicate provider drift — if the new event carries data the adapter ` +\n `should surface, add a handler; otherwise add the name to ` +\n `RECOGNIZED_ANTHROPIC_EVENTS.`\n );\n }\n }\n } catch (err: unknown) /* c8 ignore start - defensive: stream errors are always Error instances */ {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n return;\n } /* c8 ignore stop */\n\n if (stopped) {\n yield { type: 'done', truncated, fullText };\n } else {\n yield { type: 'error', message: 'Anthropic stream ended without a message_stop event' };\n }\n}\n\n// ============================================================================\n// Per-format request caller\n// ============================================================================\n\n/**\n * Issues a streaming Anthropic Messages request and returns the\n * unified-event iterable on success.\n *\n * @internal\n */\nexport async function callAnthropicStream(\n config: IStreamApiConfig,\n prompt: AiPrompt,\n messagesBefore: ReadonlyArray<IChatMessage> | undefined,\n temperature: number | undefined,\n tools: ReadonlyArray<AiToolConfig> | undefined,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n accumulationBuffer?: Map<number, IAccumulatedBlock>,\n continuationMessages?: ReadonlyArray<JsonObject>,\n useAdaptiveThinking: boolean = false,\n maxTokens?: number\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const url = `${config.baseUrl}/messages`;\n const messages = buildAnthropicMessages(prompt, {\n head: messagesBefore,\n rawTail: continuationMessages\n });\n const body: Record<string, unknown> = {\n model: config.model,\n system: prompt.system,\n messages,\n // Anthropic's Messages API requires max_tokens on every request — see\n // AiAssist.DEFAULT_ANTHROPIC_MAX_TOKENS for why only this provider defaults it.\n max_tokens: maxTokens ?? DEFAULT_ANTHROPIC_MAX_TOKENS,\n stream: true\n };\n // Temperature is sent only when explicitly provided (Claude-5 rejects any temperature). When\n // thinking is active it is also rejected — the completion/streaming paths validate this upstream,\n // and the effort gate here is the safety net for the (unguarded) client-tool path.\n if (resolvedThinking?.anthropicEffort === undefined) {\n if (temperature !== undefined) {\n body.temperature = temperature;\n }\n }\n if (resolvedThinking?.anthropicEffort !== undefined) {\n if (useAdaptiveThinking) {\n // Claude 5 family: adaptive thinking — no budget_tokens; effort moves to the\n // top-level output_config block. See AiAssist.isAdaptiveThinkingModel.\n body.thinking = { type: 'adaptive' };\n body.output_config = { effort: resolvedThinking.anthropicEffort };\n } else {\n body.thinking = {\n type: 'enabled',\n budget_tokens: anthropicEffortToBudgetTokens(resolvedThinking.anthropicEffort)\n };\n }\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(body, resolvedThinking.otherParams);\n }\n if (tools && tools.length > 0) {\n body.tools = toAnthropicTools(tools);\n }\n const headers: Record<string, string> = anthropicAuthHeaders(config.apiKey);\n /* c8 ignore next 4 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';\n logger.info(`Anthropic streaming: model=${config.model}, tools=${toolTypes}`);\n }\n const buffer = accumulationBuffer ?? new Map<number, IAccumulatedBlock>();\n const conn = await openSseConnection(url, headers, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateAnthropicStream(response, buffer, logger)));\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gemini.d.ts","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/gemini.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,EAAuC,MAAM,eAAe,CAAC;AAC1F,OAAO,EAAgB,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"gemini.d.ts","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/gemini.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,EAAuC,MAAM,eAAe,CAAC;AAC1F,OAAO,EAAgB,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAIlE,OAAO,EAAE,QAAQ,EAAE,KAAK,YAAY,EAAE,KAAK,cAAc,EAAE,KAAK,YAAY,EAAE,MAAM,UAAU,CAAC;AAG/F,OAAO,EAAE,KAAK,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,gBAAgB,EAA2C,MAAM,UAAU,CAAC;AAMrF;;;;;GAKG;AACH,MAAM,WAAW,8BAA8B;IAC7C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAC1B;;;;;;;OAOG;IACH,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;CACpC;AA2JD;;;;;GAKG;AACH,wBAAsB,gBAAgB,CACpC,MAAM,EAAE,gBAAgB,EACxB,MAAM,EAAE,QAAQ,EAChB,cAAc,EAAE,aAAa,CAAC,YAAY,CAAC,GAAG,SAAS,EACvD,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,KAAK,EAAE,aAAa,CAAC,YAAY,CAAC,GAAG,SAAS,EAC9C,MAAM,CAAC,EAAE,OAAO,CAAC,OAAO,EACxB,MAAM,CAAC,EAAE,WAAW,EACpB,gBAAgB,CAAC,EAAE,uBAAuB,EAC1C,aAAa,CAAC,EAAE,8BAA8B,EAAE,EAChD,oBAAoB,CAAC,EAAE,aAAa,CAAC,UAAU,CAAC,EAChD,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,cAAc,CAAC,CAAC,CAAC,CAsChD"}
|
|
@@ -54,6 +54,7 @@ exports.callGeminiStream = callGeminiStream;
|
|
|
54
54
|
const ts_utils_1 = require("@fgv/ts-utils");
|
|
55
55
|
const ts_json_base_1 = require("@fgv/ts-json-base");
|
|
56
56
|
const chatRequestBuilders_1 = require("../chatRequestBuilders");
|
|
57
|
+
const endpoint_1 = require("../endpoint");
|
|
57
58
|
const sseParser_1 = require("../sseParser");
|
|
58
59
|
const toolFormats_1 = require("../toolFormats");
|
|
59
60
|
const common_1 = require("./common");
|
|
@@ -197,7 +198,7 @@ async function callGeminiStream(config, prompt, messagesBefore, temperature, too
|
|
|
197
198
|
if (tools && tools.length > 0) {
|
|
198
199
|
body.tools = (0, toolFormats_1.toGeminiTools)(tools);
|
|
199
200
|
}
|
|
200
|
-
const headers =
|
|
201
|
+
const headers = (0, endpoint_1.geminiAuthHeader)(config.apiKey);
|
|
201
202
|
/* c8 ignore next 4 - optional logger diagnostic output */
|
|
202
203
|
if (logger) {
|
|
203
204
|
const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gemini.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/gemini.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;;;;;;;;;;;;;;;;;;;;;;AA+MZ,4CAkDC;AA/PD;;;;;;;;;;GAUG;AAEH,4CAA0F;AAC1F,oDAAkE;AAElE,gEAA6D;AAE7D,4CAAgE;AAChE,gDAA+C;AAE/C,qCAAqF;AA+DrF,MAAM,mBAAmB,GAA0B,qBAAU,CAAC,GAAG,CAC/D,YAAY,EACZ,CAAC,CAAC,EAAmB,EAAE,CAAC,IAAA,2BAAY,EAAC,CAAC,CAAC,CACxC,CAAC;AAEF,MAAM,uBAAuB,GAAoD,qBAAU,CAAC,MAAM,CAIhG;IACE,IAAI,EAAE,qBAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAClC,IAAI,EAAE,mBAAmB,CAAC,QAAQ,EAAE;CACrC,EACD,EAAE,OAAO,EAAE,EAAE,cAAc,EAAE,CAAC,MAAM,EAAE,MA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AK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,IAAA,2BAAa,EAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IACD,MAAM,OAAO,GAA2B,EAAE,gBAAgB,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC;IAC5E,0DAA0D;IAC1D,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,SAAS,GAAG,KAAK,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAC1F,MAAM,CAAC,IAAI,CAAC,2BAA2B,MAAM,CAAC,KAAK,WAAW,SAAS,EAAE,CAAC,CAAC;IAC7E,CAAC;IACD,MAAM,KAAK,GAAG,aAAa,aAAb,aAAa,cAAb,aAAa,GAAI,EAAE,CAAC;IAClC,MAAM,IAAI,GAAG,MAAM,IAAA,0BAAiB,EAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACzE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAA,kBAAO,EAAC,qBAAqB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;AACvF,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 * Streaming adapter for Gemini's `streamGenerateContent` endpoint. Gemini\n * emits no explicit tool-progress events even when `google_search` is\n * enabled — grounding metadata arrives attached to text chunks — so this\n * adapter never yields `tool-event`s.\n *\n * Client-defined tools (`functionCall` parts) are emitted as\n * `client-tool-call-done` immediately (no delta accumulation needed for Gemini).\n *\n * @packageDocumentation\n */\n\nimport { type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\nimport { isJsonObject, type JsonObject } from '@fgv/ts-json-base';\n\nimport { buildGeminiContents } from '../chatRequestBuilders';\nimport { AiPrompt, type AiToolConfig, type IAiStreamEvent, type IChatMessage } from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { toGeminiTools } from '../toolFormats';\nimport { type IResolvedThinkingConfig } from '../thinkingOptionsResolver';\nimport { IStreamApiConfig, openSseConnection, validateEventPayload } from './common';\n\n// ============================================================================\n// Accumulated call state (internal — used by C3 continuation builder)\n// ============================================================================\n\n/**\n * An accumulated function call from a Gemini stream. Gemini does not assign\n * call IDs; correlation is by tool name. Arguments arrive complete in the\n * `functionCall` part (no delta accumulation).\n * @internal\n */\nexport interface IAccumulatedGeminiFunctionCall {\n readonly name: string;\n readonly args: JsonObject;\n /**\n * The opaque thought signature Gemini stamps on a `functionCall` part when\n * thinking is enabled. It must be echoed back, verbatim, on the continuation's\n * model turn alongside the `functionCall`, or Gemini rejects the follow-up with\n * \"Function call is missing a thought_signature in functionCall parts\".\n * Absent when thinking is disabled. See\n * https://ai.google.dev/gemini-api/docs/thought-signatures.\n */\n readonly thoughtSignature?: string;\n}\n\n// ============================================================================\n// Event payload shapes\n// ============================================================================\n\n/**\n * One `parts[]` element in a Gemini streaming chunk. Text parts and\n * functionCall parts are both surfaced.\n * @internal\n */\ninterface IGeminiStreamPart {\n readonly text?: string;\n readonly functionCall?: { readonly name?: string; readonly args?: JsonObject };\n /**\n * The opaque thought signature attached to a `functionCall` part when thinking\n * is enabled. A sibling of `functionCall`/`text` at the part level (base64\n * string). Captured for replay on the continuation's model turn.\n */\n readonly thoughtSignature?: string;\n}\n\n/**\n * One `candidates[]` element in a Gemini streaming chunk.\n * @internal\n */\ninterface IGeminiStreamCandidate {\n readonly content?: { readonly parts?: ReadonlyArray<IGeminiStreamPart> };\n readonly finishReason?: string;\n}\n\n/**\n * One streaming chunk from `streamGenerateContent?alt=sse`.\n * @internal\n */\ninterface IGeminiStreamChunk {\n readonly candidates: ReadonlyArray<IGeminiStreamCandidate>;\n}\n\nconst jsonObjectValidator: Validator<JsonObject> = Validators.isA<JsonObject>(\n 'JsonObject',\n (v): v is JsonObject => isJsonObject(v)\n);\n\nconst geminiFunctionCallInner: Validator<{ name?: string; args?: JsonObject }> = Validators.object<{\n name?: string;\n args?: JsonObject;\n}>(\n {\n name: Validators.string.optional(),\n args: jsonObjectValidator.optional()\n },\n { options: { optionalFields: ['name', 'args'] } }\n);\n\nconst geminiStreamPart: Validator<IGeminiStreamPart> = Validators.object<IGeminiStreamPart>(\n {\n text: Validators.string.optional(),\n functionCall: geminiFunctionCallInner.optional(),\n thoughtSignature: Validators.string.optional()\n },\n { options: { optionalFields: ['text', 'functionCall', 'thoughtSignature'] } }\n);\n\nconst geminiStreamContent: Validator<{ parts?: ReadonlyArray<IGeminiStreamPart> }> = Validators.object<{\n parts?: ReadonlyArray<IGeminiStreamPart>;\n}>({ parts: Validators.arrayOf(geminiStreamPart).optional() }, { options: { optionalFields: ['parts'] } });\n\nconst geminiStreamCandidate: Validator<IGeminiStreamCandidate> = Validators.object<IGeminiStreamCandidate>(\n {\n content: geminiStreamContent.optional(),\n finishReason: Validators.string.optional()\n },\n { options: { optionalFields: ['content', 'finishReason'] } }\n);\n\nconst geminiStreamChunk: Validator<IGeminiStreamChunk> = Validators.object<IGeminiStreamChunk>({\n candidates: Validators.arrayOf(geminiStreamCandidate)\n});\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Translates a Gemini streamGenerateContent SSE stream into unified events.\n *\n * @internal\n */\nasync function* translateGeminiStream(\n response: Response,\n functionCalls: IAccumulatedGeminiFunctionCall[]\n): AsyncGenerator<IAiStreamEvent> {\n let fullText = '';\n let truncated = false;\n let receivedFinishReason = false;\n\n try {\n /* c8 ignore next - body is non-null at this point per openSseConnection */\n if (!response.body) return;\n for await (const message of readSseEvents(response.body)) {\n const json = parseSseEventJson(message.data);\n /* c8 ignore next 3 - defensive: malformed SSE events skipped */\n if (json === undefined) {\n continue;\n }\n const chunk = validateEventPayload(json, geminiStreamChunk);\n /* c8 ignore next 1 - defensive: chunk?.candidates optional chain unreachable after validation */\n const candidate = chunk?.candidates[0];\n /* c8 ignore next 3 - defensive: SSE events without candidates skipped */\n if (!candidate) {\n continue;\n }\n /* c8 ignore next 1 - defensive: candidate.content?.parts null branch unreachable after validation */\n const parts = candidate.content?.parts;\n if (parts) {\n for (const part of parts) {\n if (typeof part.text === 'string' && part.text.length > 0) {\n fullText += part.text;\n yield { type: 'text-delta', delta: part.text };\n /* c8 ignore next 1 - defensive: functionCall parts without a `name` are silently dropped (cannot construct a continuation builder entry without one) */\n } else if (part.functionCall?.name) {\n const { name, args } = part.functionCall;\n /* c8 ignore next 1 - defensive: Gemini always sends args; {} fallback unreachable in practice */\n const callArgs = args ?? {};\n // Capture the part-level thoughtSignature (sibling of functionCall) so the\n // continuation builder can replay it on the model turn. Reads as undefined\n // when thinking is disabled; the builder omits the key in that case.\n functionCalls.push({ name, args: callArgs, thoughtSignature: part.thoughtSignature });\n yield { type: 'client-tool-call-done', toolName: name, args: callArgs };\n }\n }\n }\n const finishReason = candidate.finishReason;\n if (typeof finishReason === 'string' && finishReason.length > 0) {\n truncated = finishReason === 'MAX_TOKENS';\n receivedFinishReason = true;\n }\n }\n } catch (err: unknown) /* c8 ignore start - defensive: stream errors are always Error instances */ {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n return;\n } /* c8 ignore stop */\n\n if (receivedFinishReason) {\n yield { type: 'done', truncated, fullText };\n } else {\n yield { type: 'error', message: 'Gemini stream ended without a finishReason' };\n }\n}\n\n// ============================================================================\n// Per-format request caller\n// ============================================================================\n\n/**\n * Issues a streaming Gemini request and returns the unified-event iterable\n * on success.\n *\n * @internal\n */\nexport async function callGeminiStream(\n config: IStreamApiConfig,\n prompt: AiPrompt,\n messagesBefore: ReadonlyArray<IChatMessage> | undefined,\n temperature: number | undefined,\n tools: ReadonlyArray<AiToolConfig> | undefined,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n functionCalls?: IAccumulatedGeminiFunctionCall[],\n continuationMessages?: ReadonlyArray<JsonObject>,\n maxTokens?: number\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const url = `${config.baseUrl}/models/${config.model}:streamGenerateContent?alt=sse`;\n const contents = buildGeminiContents(prompt, {\n head: messagesBefore,\n rawTail: continuationMessages\n });\n // Temperature is sent only when explicitly provided; otherwise Gemini's default applies.\n const generationConfig: Record<string, unknown> = {};\n if (temperature !== undefined) {\n generationConfig.temperature = temperature;\n }\n if (maxTokens !== undefined) {\n generationConfig.maxOutputTokens = maxTokens;\n }\n if (resolvedThinking?.geminiThinkingBudget !== undefined) {\n generationConfig.thinkingConfig = { thinkingBudget: resolvedThinking.geminiThinkingBudget };\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(generationConfig, resolvedThinking.otherParams);\n }\n const body: Record<string, unknown> = {\n systemInstruction: { parts: [{ text: prompt.system }] },\n contents,\n generationConfig\n };\n /* c8 ignore next 3 - tools branch not exercised in streaming tests */\n if (tools && tools.length > 0) {\n body.tools = toGeminiTools(tools);\n }\n const headers: Record<string, string> = { 'x-goog-api-key': config.apiKey };\n /* c8 ignore next 4 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';\n logger.info(`Gemini streaming: model=${config.model}, tools=${toolTypes}`);\n }\n const calls = functionCalls ?? [];\n const conn = await openSseConnection(url, headers, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateGeminiStream(response, calls)));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gemini.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/gemini.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;;;;;;;;;;;;;;;;;;;;;;AAgNZ,4CAkDC;AAhQD;;;;;;;;;;GAUG;AAEH,4CAA0F;AAC1F,oDAAkE;AAElE,gEAA6D;AAC7D,0CAA+C;AAE/C,4CAAgE;AAChE,gDAA+C;AAE/C,qCAAqF;AA+DrF,MAAM,mBAAmB,GAA0B,qBAAU,CAAC,GAAG,CAC/D,YAAY,EACZ,CAAC,CAAC,EAAmB,EAAE,CAAC,IAAA,2BAAY,EAAC,CAAC,CAAC,CACxC,CAAC;AAEF,MAAM,uBAAuB,GAAoD,qBAAU,CAAC,MAAM,CAIhG;IACE,IAAI,EAAE,qBAAU,CAAC,MAAM,CAAC,QAAQ,EAAE;IAClC,IAAI,EAAE,mBAAmB,CAAC,QAAQ,EAAE;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;QACR,gBAAgB;KACjB,CAAC;IACF,sEAAsE;IACtE,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,IAAA,2BAAa,EAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IACD,MAAM,OAAO,GAA2B,IAAA,2BAAgB,EAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACxE,0DAA0D;IAC1D,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,SAAS,GAAG,KAAK,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAC1F,MAAM,CAAC,IAAI,CAAC,2BAA2B,MAAM,CAAC,KAAK,WAAW,SAAS,EAAE,CAAC,CAAC;IAC7E,CAAC;IACD,MAAM,KAAK,GAAG,aAAa,aAAb,aAAa,cAAb,aAAa,GAAI,EAAE,CAAC;IAClC,MAAM,IAAI,GAAG,MAAM,IAAA,0BAAiB,EAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACzE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAA,kBAAO,EAAC,qBAAqB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;AACvF,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 * Streaming adapter for Gemini's `streamGenerateContent` endpoint. Gemini\n * emits no explicit tool-progress events even when `google_search` is\n * enabled — grounding metadata arrives attached to text chunks — so this\n * adapter never yields `tool-event`s.\n *\n * Client-defined tools (`functionCall` parts) are emitted as\n * `client-tool-call-done` immediately (no delta accumulation needed for Gemini).\n *\n * @packageDocumentation\n */\n\nimport { type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\nimport { isJsonObject, type JsonObject } from '@fgv/ts-json-base';\n\nimport { buildGeminiContents } from '../chatRequestBuilders';\nimport { geminiAuthHeader } from '../endpoint';\nimport { AiPrompt, type AiToolConfig, type IAiStreamEvent, type IChatMessage } from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { toGeminiTools } from '../toolFormats';\nimport { type IResolvedThinkingConfig } from '../thinkingOptionsResolver';\nimport { IStreamApiConfig, openSseConnection, validateEventPayload } from './common';\n\n// ============================================================================\n// Accumulated call state (internal — used by C3 continuation builder)\n// ============================================================================\n\n/**\n * An accumulated function call from a Gemini stream. Gemini does not assign\n * call IDs; correlation is by tool name. Arguments arrive complete in the\n * `functionCall` part (no delta accumulation).\n * @internal\n */\nexport interface IAccumulatedGeminiFunctionCall {\n readonly name: string;\n readonly args: JsonObject;\n /**\n * The opaque thought signature Gemini stamps on a `functionCall` part when\n * thinking is enabled. It must be echoed back, verbatim, on the continuation's\n * model turn alongside the `functionCall`, or Gemini rejects the follow-up with\n * \"Function call is missing a thought_signature in functionCall parts\".\n * Absent when thinking is disabled. See\n * https://ai.google.dev/gemini-api/docs/thought-signatures.\n */\n readonly thoughtSignature?: string;\n}\n\n// ============================================================================\n// Event payload shapes\n// ============================================================================\n\n/**\n * One `parts[]` element in a Gemini streaming chunk. Text parts and\n * functionCall parts are both surfaced.\n * @internal\n */\ninterface IGeminiStreamPart {\n readonly text?: string;\n readonly functionCall?: { readonly name?: string; readonly args?: JsonObject };\n /**\n * The opaque thought signature attached to a `functionCall` part when thinking\n * is enabled. A sibling of `functionCall`/`text` at the part level (base64\n * string). Captured for replay on the continuation's model turn.\n */\n readonly thoughtSignature?: string;\n}\n\n/**\n * One `candidates[]` element in a Gemini streaming chunk.\n * @internal\n */\ninterface IGeminiStreamCandidate {\n readonly content?: { readonly parts?: ReadonlyArray<IGeminiStreamPart> };\n readonly finishReason?: string;\n}\n\n/**\n * One streaming chunk from `streamGenerateContent?alt=sse`.\n * @internal\n */\ninterface IGeminiStreamChunk {\n readonly candidates: ReadonlyArray<IGeminiStreamCandidate>;\n}\n\nconst jsonObjectValidator: Validator<JsonObject> = Validators.isA<JsonObject>(\n 'JsonObject',\n (v): v is JsonObject => isJsonObject(v)\n);\n\nconst geminiFunctionCallInner: Validator<{ name?: string; args?: JsonObject }> = Validators.object<{\n name?: string;\n args?: JsonObject;\n}>(\n {\n name: Validators.string.optional(),\n args: jsonObjectValidator.optional()\n },\n { options: { optionalFields: ['name', 'args'] } }\n);\n\nconst geminiStreamPart: Validator<IGeminiStreamPart> = Validators.object<IGeminiStreamPart>(\n {\n text: Validators.string.optional(),\n functionCall: geminiFunctionCallInner.optional(),\n thoughtSignature: Validators.string.optional()\n },\n { options: { optionalFields: ['text', 'functionCall', 'thoughtSignature'] } }\n);\n\nconst geminiStreamContent: Validator<{ parts?: ReadonlyArray<IGeminiStreamPart> }> = Validators.object<{\n parts?: ReadonlyArray<IGeminiStreamPart>;\n}>({ parts: Validators.arrayOf(geminiStreamPart).optional() }, { options: { optionalFields: ['parts'] } });\n\nconst geminiStreamCandidate: Validator<IGeminiStreamCandidate> = Validators.object<IGeminiStreamCandidate>(\n {\n content: geminiStreamContent.optional(),\n finishReason: Validators.string.optional()\n },\n { options: { optionalFields: ['content', 'finishReason'] } }\n);\n\nconst geminiStreamChunk: Validator<IGeminiStreamChunk> = Validators.object<IGeminiStreamChunk>({\n candidates: Validators.arrayOf(geminiStreamCandidate)\n});\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Translates a Gemini streamGenerateContent SSE stream into unified events.\n *\n * @internal\n */\nasync function* translateGeminiStream(\n response: Response,\n functionCalls: IAccumulatedGeminiFunctionCall[]\n): AsyncGenerator<IAiStreamEvent> {\n let fullText = '';\n let truncated = false;\n let receivedFinishReason = false;\n\n try {\n /* c8 ignore next - body is non-null at this point per openSseConnection */\n if (!response.body) return;\n for await (const message of readSseEvents(response.body)) {\n const json = parseSseEventJson(message.data);\n /* c8 ignore next 3 - defensive: malformed SSE events skipped */\n if (json === undefined) {\n continue;\n }\n const chunk = validateEventPayload(json, geminiStreamChunk);\n /* c8 ignore next 1 - defensive: chunk?.candidates optional chain unreachable after validation */\n const candidate = chunk?.candidates[0];\n /* c8 ignore next 3 - defensive: SSE events without candidates skipped */\n if (!candidate) {\n continue;\n }\n /* c8 ignore next 1 - defensive: candidate.content?.parts null branch unreachable after validation */\n const parts = candidate.content?.parts;\n if (parts) {\n for (const part of parts) {\n if (typeof part.text === 'string' && part.text.length > 0) {\n fullText += part.text;\n yield { type: 'text-delta', delta: part.text };\n /* c8 ignore next 1 - defensive: functionCall parts without a `name` are silently dropped (cannot construct a continuation builder entry without one) */\n } else if (part.functionCall?.name) {\n const { name, args } = part.functionCall;\n /* c8 ignore next 1 - defensive: Gemini always sends args; {} fallback unreachable in practice */\n const callArgs = args ?? {};\n // Capture the part-level thoughtSignature (sibling of functionCall) so the\n // continuation builder can replay it on the model turn. Reads as undefined\n // when thinking is disabled; the builder omits the key in that case.\n functionCalls.push({ name, args: callArgs, thoughtSignature: part.thoughtSignature });\n yield { type: 'client-tool-call-done', toolName: name, args: callArgs };\n }\n }\n }\n const finishReason = candidate.finishReason;\n if (typeof finishReason === 'string' && finishReason.length > 0) {\n truncated = finishReason === 'MAX_TOKENS';\n receivedFinishReason = true;\n }\n }\n } catch (err: unknown) /* c8 ignore start - defensive: stream errors are always Error instances */ {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n return;\n } /* c8 ignore stop */\n\n if (receivedFinishReason) {\n yield { type: 'done', truncated, fullText };\n } else {\n yield { type: 'error', message: 'Gemini stream ended without a finishReason' };\n }\n}\n\n// ============================================================================\n// Per-format request caller\n// ============================================================================\n\n/**\n * Issues a streaming Gemini request and returns the unified-event iterable\n * on success.\n *\n * @internal\n */\nexport async function callGeminiStream(\n config: IStreamApiConfig,\n prompt: AiPrompt,\n messagesBefore: ReadonlyArray<IChatMessage> | undefined,\n temperature: number | undefined,\n tools: ReadonlyArray<AiToolConfig> | undefined,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n functionCalls?: IAccumulatedGeminiFunctionCall[],\n continuationMessages?: ReadonlyArray<JsonObject>,\n maxTokens?: number\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const url = `${config.baseUrl}/models/${config.model}:streamGenerateContent?alt=sse`;\n const contents = buildGeminiContents(prompt, {\n head: messagesBefore,\n rawTail: continuationMessages\n });\n // Temperature is sent only when explicitly provided; otherwise Gemini's default applies.\n const generationConfig: Record<string, unknown> = {};\n if (temperature !== undefined) {\n generationConfig.temperature = temperature;\n }\n if (maxTokens !== undefined) {\n generationConfig.maxOutputTokens = maxTokens;\n }\n if (resolvedThinking?.geminiThinkingBudget !== undefined) {\n generationConfig.thinkingConfig = { thinkingBudget: resolvedThinking.geminiThinkingBudget };\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(generationConfig, resolvedThinking.otherParams);\n }\n const body: Record<string, unknown> = {\n systemInstruction: { parts: [{ text: prompt.system }] },\n contents,\n generationConfig\n };\n /* c8 ignore next 3 - tools branch not exercised in streaming tests */\n if (tools && tools.length > 0) {\n body.tools = toGeminiTools(tools);\n }\n const headers: Record<string, string> = geminiAuthHeader(config.apiKey);\n /* c8 ignore next 4 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';\n logger.info(`Gemini streaming: model=${config.model}, tools=${toolTypes}`);\n }\n const calls = functionCalls ?? [];\n const conn = await openSseConnection(url, headers, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateGeminiStream(response, calls)));\n}\n"]}
|
|
@@ -15,6 +15,31 @@ export declare function toBase64(bytes: Uint8Array): string;
|
|
|
15
15
|
* @public
|
|
16
16
|
*/
|
|
17
17
|
export declare function fromBase64(base64: string): Uint8Array;
|
|
18
|
+
/**
|
|
19
|
+
* Decodes a base64 string to a `Uint8Array`, **rejecting input that is not
|
|
20
|
+
* well-formed base64** instead of silently salvaging what it can.
|
|
21
|
+
*
|
|
22
|
+
* @remarks
|
|
23
|
+
* The difference from {@link CryptoUtils.fromBase64 | fromBase64} is the failure
|
|
24
|
+
* mode, and it is the whole reason this exists. `fromBase64` is `Buffer`-first
|
|
25
|
+
* where a `Buffer` exists, and `Buffer.from(s, 'base64')` **discards** characters
|
|
26
|
+
* outside the base64 alphabet rather than complaining — so a corrupted or
|
|
27
|
+
* truncated payload decodes to plausible-looking garbage and the corruption is
|
|
28
|
+
* discovered, if ever, much further downstream. Use this variant whenever the
|
|
29
|
+
* base64 arrived from somewhere you do not control (a wire response, a file, user
|
|
30
|
+
* input) and a malformed value means "something is wrong", not "do your best".
|
|
31
|
+
*
|
|
32
|
+
* Implemented over `atob`, which rejects out-of-alphabet characters and bad
|
|
33
|
+
* lengths. Note it inherits `atob`'s one leniency: per the WHATWG forgiving-base64
|
|
34
|
+
* algorithm, ASCII whitespace inside the input is stripped rather than rejected.
|
|
35
|
+
* That is deliberate — line-wrapped base64 is common and benign — and it does not
|
|
36
|
+
* weaken the guarantee that matters here, which is that corrupt bytes fail loudly.
|
|
37
|
+
* @param base64 - Base64 string to decode.
|
|
38
|
+
* @returns `Success` with the decoded bytes, or `Failure` if `base64` is not
|
|
39
|
+
* well-formed.
|
|
40
|
+
* @public
|
|
41
|
+
*/
|
|
42
|
+
export declare function fromBase64Strict(base64: string): Result<Uint8Array>;
|
|
18
43
|
/**
|
|
19
44
|
* Parameters for creating an {@link CryptoUtils.IEncryptedFile | encrypted file}.
|
|
20
45
|
* @typeParam TMetadata - Type of optional unencrypted metadata
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"encryptedFile.d.ts","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/encryptedFile.ts"],"names":[],"mappings":"AAoBA,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAiB,SAAS,EAAQ,MAAM,EAAW,MAAM,eAAe,CAAC;AAGhF,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,oBAAoB,EAAmB,MAAM,SAAS,CAAC;AAMjG;;;;;GAKG;AAEH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAUlD;AAGD;;;;;GAKG;AAEH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAWrD;
|
|
1
|
+
{"version":3,"file":"encryptedFile.d.ts","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/encryptedFile.ts"],"names":[],"mappings":"AAoBA,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAiB,SAAS,EAAQ,MAAM,EAAW,MAAM,eAAe,CAAC;AAGhF,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,oBAAoB,EAAmB,MAAM,SAAS,CAAC;AAMjG;;;;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AAC,CAAC,CA6B3B;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,cAAc,CAAC,QAAQ,SAAS,SAAS,GAAG,SAAS,EAAE,SAAS,GAAG,SAAS,EAChG,IAAI,EAAE,SAAS,EACf,GAAG,EAAE,UAAU,EACf,cAAc,EAAE,eAAe,EAC/B,gBAAgB,CAAC,EAAE,SAAS,CAAC,QAAQ,CAAC,EACtC,iBAAiB,CAAC,EAAE,SAAS,CAAC,SAAS,CAAC,GACvC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAc3B"}
|
|
@@ -54,6 +54,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
54
54
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
55
55
|
exports.toBase64 = toBase64;
|
|
56
56
|
exports.fromBase64 = fromBase64;
|
|
57
|
+
exports.fromBase64Strict = fromBase64Strict;
|
|
57
58
|
exports.createEncryptedFile = createEncryptedFile;
|
|
58
59
|
exports.decryptFile = decryptFile;
|
|
59
60
|
exports.tryDecryptFile = tryDecryptFile;
|
|
@@ -102,6 +103,43 @@ function fromBase64(base64) {
|
|
|
102
103
|
}
|
|
103
104
|
return bytes;
|
|
104
105
|
}
|
|
106
|
+
/* c8 ignore stop */
|
|
107
|
+
/**
|
|
108
|
+
* Decodes a base64 string to a `Uint8Array`, **rejecting input that is not
|
|
109
|
+
* well-formed base64** instead of silently salvaging what it can.
|
|
110
|
+
*
|
|
111
|
+
* @remarks
|
|
112
|
+
* The difference from {@link CryptoUtils.fromBase64 | fromBase64} is the failure
|
|
113
|
+
* mode, and it is the whole reason this exists. `fromBase64` is `Buffer`-first
|
|
114
|
+
* where a `Buffer` exists, and `Buffer.from(s, 'base64')` **discards** characters
|
|
115
|
+
* outside the base64 alphabet rather than complaining — so a corrupted or
|
|
116
|
+
* truncated payload decodes to plausible-looking garbage and the corruption is
|
|
117
|
+
* discovered, if ever, much further downstream. Use this variant whenever the
|
|
118
|
+
* base64 arrived from somewhere you do not control (a wire response, a file, user
|
|
119
|
+
* input) and a malformed value means "something is wrong", not "do your best".
|
|
120
|
+
*
|
|
121
|
+
* Implemented over `atob`, which rejects out-of-alphabet characters and bad
|
|
122
|
+
* lengths. Note it inherits `atob`'s one leniency: per the WHATWG forgiving-base64
|
|
123
|
+
* algorithm, ASCII whitespace inside the input is stripped rather than rejected.
|
|
124
|
+
* That is deliberate — line-wrapped base64 is common and benign — and it does not
|
|
125
|
+
* weaken the guarantee that matters here, which is that corrupt bytes fail loudly.
|
|
126
|
+
* @param base64 - Base64 string to decode.
|
|
127
|
+
* @returns `Success` with the decoded bytes, or `Failure` if `base64` is not
|
|
128
|
+
* well-formed.
|
|
129
|
+
* @public
|
|
130
|
+
*/
|
|
131
|
+
function fromBase64Strict(base64) {
|
|
132
|
+
return (0, ts_utils_1.captureResult)(() => {
|
|
133
|
+
// `atob` yields a "binary string": one UTF-16 code unit per byte, each in
|
|
134
|
+
// 0..255, so `charCodeAt` reads the bytes back losslessly for all 256 values.
|
|
135
|
+
const binary = atob(base64);
|
|
136
|
+
const bytes = new Uint8Array(binary.length);
|
|
137
|
+
for (let i = 0; i < binary.length; i++) {
|
|
138
|
+
bytes[i] = binary.charCodeAt(i);
|
|
139
|
+
}
|
|
140
|
+
return bytes;
|
|
141
|
+
}).withErrorFormat(() => 'invalid base64 string');
|
|
142
|
+
}
|
|
105
143
|
// ============================================================================
|
|
106
144
|
// Encryption Functions
|
|
107
145
|
// ============================================================================
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"encryptedFile.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/encryptedFile.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,8EAA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EAAC,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,KAAK,CAAa,CAAC,CAAC,eAAe,CAClG,CAAC,CAAC,EAAE,EAAE,CAAC,8CAA8C,CAAC,EAAE,CACzD,CAAC;IAEF,qFAAqF;IACrF,IAAI,WAAW,CAAC,SAAS,EAAE,EAAE,CAAC;QAC5B,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,sCAAsC;IACtC,gFAAgF;IAChF,IAAI,gBAAgB,KAAK,SAAS,EAAE,CAAC;QACnC,OAAO,gBAAgB,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;IACrD,CAAC;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;AAED;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,cAAc,CAClC,IAAe,EACf,GAAe,EACf,cAA+B,EAC/B,gBAAsC,EACtC,iBAAwC;IAExC,kCAAkC;IAClC,IAAI,CAAC,IAAA,uBAAe,EAAC,IAAI,CAAC,EAAE,CAAC;QAC3B,OAAO,IAAA,eAAI,EAAC,uBAAuB,CAAC,CAAC;IACvC,CAAC;IAED,+CAA+C;IAC/C,MAAM,aAAa,GAAG,IAAA,yCAA4B,EAAC,iBAAiB,CAAC,CAAC;IACtE,MAAM,UAAU,GAAG,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/C,IAAI,UAAU,CAAC,SAAS,EAAE,EAAE,CAAC;QAC3B,OAAO,IAAA,eAAI,EAAC,kCAAkC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;IACtE,CAAC;IAED,OAAO,WAAW,CAAC,UAAU,CAAC,KAAK,EAAE,GAAG,EAAE,cAAc,EAAE,gBAAgB,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["// Copyright (c) 2024 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\nimport { JsonValue } from '@fgv/ts-json-base';\nimport { captureResult, Converter, fail, Result, succeed } from '@fgv/ts-utils';\nimport * as Constants from './constants';\nimport { createEncryptedFileConverter } from './converters';\nimport { ICryptoProvider, IEncryptedFile, IKeyDerivationParams, isEncryptedFile } from './model';\n\n// ============================================================================\n// Base64 Utilities\n// ============================================================================\n\n/**\n * Encodes a `Uint8Array` to a base64 string.\n * @param bytes - Bytes to encode\n * @returns Base64 string\n * @public\n */\n/* c8 ignore start - Browser-only fallback cannot be tested in Node.js environment */\nexport function toBase64(bytes: Uint8Array): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(bytes).toString('base64');\n }\n // Browser fallback\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n/* c8 ignore stop */\n\n/**\n * Decodes a base64 string to a `Uint8Array`.\n * @param base64 - Base64 string to decode\n * @returns Decoded bytes\n * @public\n */\n/* c8 ignore start - Browser-only fallback cannot be tested in Node.js environment */\nexport function fromBase64(base64: string): Uint8Array {\n if (typeof Buffer !== 'undefined') {\n return new Uint8Array(Buffer.from(base64, 'base64'));\n }\n // Browser fallback\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n/* c8 ignore stop */\n\n// ============================================================================\n// Create Encrypted File Parameters\n// ============================================================================\n\n/**\n * Parameters for creating an {@link CryptoUtils.IEncryptedFile | encrypted file}.\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @public\n */\nexport interface ICreateEncryptedFileParams<TMetadata = JsonValue> {\n /**\n * The JSON content to encrypt.\n */\n readonly content: JsonValue;\n\n /**\n * Name of the secret used for encryption.\n */\n readonly secretName: string;\n\n /**\n * The encryption key (32 bytes for AES-256).\n */\n readonly key: Uint8Array;\n\n /**\n * {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for encryption.\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * Optional metadata to include unencrypted.\n */\n readonly metadata?: TMetadata;\n\n /**\n * Optional converter to validate metadata before including.\n * If provided, metadata will be validated before encryption.\n */\n readonly metadataConverter?: Converter<TMetadata>;\n\n /**\n * Optional {@link CryptoUtils.IKeyDerivationParams | key derivation parameters}.\n * If provided, stores the salt and iterations used to derive the key from a password.\n * This allows decryption using only a password (the salt/iterations are read from the file).\n */\n readonly keyDerivation?: IKeyDerivationParams;\n}\n\n// ============================================================================\n// Encryption Functions\n// ============================================================================\n\n/**\n * Creates an {@link CryptoUtils.IEncryptedFile | encrypted file} from JSON content.\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @param params - Encryption parameters\n * @returns `Success` with encrypted file structure, or `Failure` with an error.\n * @public\n */\nexport async function createEncryptedFile<TMetadata = JsonValue>(\n params: ICreateEncryptedFileParams<TMetadata>\n): Promise<Result<IEncryptedFile<TMetadata>>> {\n const { content, secretName, key, metadata, metadataConverter, keyDerivation, cryptoProvider } = params;\n\n // Validate metadata if converter provided\n /* c8 ignore next 6 - metadata validation path exercised via higher-level tests */\n if (metadata !== undefined && metadataConverter !== undefined) {\n const metadataResult = metadataConverter.convert(metadata);\n if (metadataResult.isFailure()) {\n return fail(`Invalid metadata: ${metadataResult.message}`);\n }\n }\n\n // Serialize content to JSON string\n const jsonResult = captureResult(() => JSON.stringify(content));\n if (jsonResult.isFailure()) {\n return fail(`Failed to serialize content: ${jsonResult.message}`);\n }\n\n // Encrypt the JSON string\n const encryptResult = await cryptoProvider.encrypt(jsonResult.value, key);\n if (encryptResult.isFailure()) {\n return fail(`Encryption failed: ${encryptResult.message}`);\n }\n\n const { iv, authTag, encryptedData } = encryptResult.value;\n\n // Build the encrypted file structure\n const encryptedFile: IEncryptedFile<TMetadata> = {\n format: Constants.ENCRYPTED_FILE_FORMAT,\n secretName,\n algorithm: Constants.DEFAULT_ALGORITHM,\n iv: toBase64(iv),\n authTag: toBase64(authTag),\n encryptedData: toBase64(encryptedData),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(keyDerivation !== undefined ? { keyDerivation } : {})\n };\n\n return succeed(encryptedFile);\n}\n\n// ============================================================================\n// Decryption Functions\n// ============================================================================\n\n/**\n * Decrypts an {@link CryptoUtils.IEncryptedFile | encrypted file} and returns the JSON content.\n * @typeParam TPayload - Expected type of decrypted content\n * @param file - The encrypted file structure\n * @param key - The decryption key (32 bytes for AES-256)\n * @param cryptoProvider - {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for decryption\n * @param payloadConverter - Optional converter to validate and convert decrypted content\n * @returns `Success` with decrypted content, or `Failure` with an error.\n * @public\n */\nexport async function decryptFile<TPayload extends JsonValue = JsonValue>(\n file: IEncryptedFile<unknown>,\n key: Uint8Array,\n cryptoProvider: ICryptoProvider,\n payloadConverter?: Converter<TPayload>\n): Promise<Result<TPayload>> {\n // Decode base64 values\n const iv = fromBase64(file.iv);\n const authTag = fromBase64(file.authTag);\n const encryptedData = fromBase64(file.encryptedData);\n\n // Decrypt\n const decryptResult = await cryptoProvider.decrypt(encryptedData, key, iv, authTag);\n if (decryptResult.isFailure()) {\n return fail(decryptResult.message);\n }\n\n // Parse JSON\n const parseResult = captureResult(() => JSON.parse(decryptResult.value) as TPayload).withErrorFormat(\n (e) => `Failed to parse decrypted content as JSON: ${e}`\n );\n\n /* c8 ignore next 3 - JSON parse failure only occurs with corrupted encrypted data */\n if (parseResult.isFailure()) {\n return parseResult;\n }\n\n // Validate with converter if provided\n /* c8 ignore next 3 - payload converter path exercised via higher-level tests */\n if (payloadConverter !== undefined) {\n return payloadConverter.convert(parseResult.value);\n }\n\n return parseResult;\n}\n\n/**\n * Attempts to parse and decrypt a JSON object as an {@link CryptoUtils.IEncryptedFile | encrypted file}.\n * @typeParam TPayload - Expected type of decrypted content\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @param json - JSON object that may be an encrypted file\n * @param key - The decryption key (32 bytes for AES-256)\n * @param cryptoProvider - {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for decryption\n * @param payloadConverter - Optional converter to validate and convert decrypted content\n * @param metadataConverter - Optional converter to validate metadata before decryption\n * @returns `Success` with decrypted content, or `Failure` with an error (including if not encrypted)\n * @public\n */\nexport async function tryDecryptFile<TPayload extends JsonValue = JsonValue, TMetadata = JsonValue>(\n json: JsonValue,\n key: Uint8Array,\n cryptoProvider: ICryptoProvider,\n payloadConverter?: Converter<TPayload>,\n metadataConverter?: Converter<TMetadata>\n): Promise<Result<TPayload>> {\n // Check if it's an encrypted file\n if (!isEncryptedFile(json)) {\n return fail('Not an encrypted file');\n }\n\n // Validate and convert to typed encrypted file\n const fileConverter = createEncryptedFileConverter(metadataConverter);\n const fileResult = fileConverter.convert(json);\n if (fileResult.isFailure()) {\n return fail(`Invalid encrypted file format: ${fileResult.message}`);\n }\n\n return decryptFile(fileResult.value, key, cryptoProvider, payloadConverter);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"encryptedFile.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/encryptedFile.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gF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G;AACI,KAAK,UAAU,cAAc,CAClC,IAAe,EACf,GAAe,EACf,cAA+B,EAC/B,gBAAsC,EACtC,iBAAwC;IAExC,kCAAkC;IAClC,IAAI,CAAC,IAAA,uBAAe,EAAC,IAAI,CAAC,EAAE,CAAC;QAC3B,OAAO,IAAA,eAAI,EAAC,uBAAuB,CAAC,CAAC;IACvC,CAAC;IAED,+CAA+C;IAC/C,MAAM,aAAa,GAAG,IAAA,yCAA4B,EAAC,iBAAiB,CAAC,CAAC;IACtE,MAAM,UAAU,GAAG,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/C,IAAI,UAAU,CAAC,SAAS,EAAE,EAAE,CAAC;QAC3B,OAAO,IAAA,eAAI,EAAC,kCAAkC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;IACtE,CAAC;IAED,OAAO,WAAW,CAAC,UAAU,CAAC,KAAK,EAAE,GAAG,EAAE,cAAc,EAAE,gBAAgB,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["// Copyright (c) 2024 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\nimport { JsonValue } from '@fgv/ts-json-base';\nimport { captureResult, Converter, fail, Result, succeed } from '@fgv/ts-utils';\nimport * as Constants from './constants';\nimport { createEncryptedFileConverter } from './converters';\nimport { ICryptoProvider, IEncryptedFile, IKeyDerivationParams, isEncryptedFile } from './model';\n\n// ============================================================================\n// Base64 Utilities\n// ============================================================================\n\n/**\n * Encodes a `Uint8Array` to a base64 string.\n * @param bytes - Bytes to encode\n * @returns Base64 string\n * @public\n */\n/* c8 ignore start - Browser-only fallback cannot be tested in Node.js environment */\nexport function toBase64(bytes: Uint8Array): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(bytes).toString('base64');\n }\n // Browser fallback\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n/* c8 ignore stop */\n\n/**\n * Decodes a base64 string to a `Uint8Array`.\n * @param base64 - Base64 string to decode\n * @returns Decoded bytes\n * @public\n */\n/* c8 ignore start - Browser-only fallback cannot be tested in Node.js environment */\nexport function fromBase64(base64: string): Uint8Array {\n if (typeof Buffer !== 'undefined') {\n return new Uint8Array(Buffer.from(base64, 'base64'));\n }\n // Browser fallback\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n/* c8 ignore stop */\n\n/**\n * Decodes a base64 string to a `Uint8Array`, **rejecting input that is not\n * well-formed base64** instead of silently salvaging what it can.\n *\n * @remarks\n * The difference from {@link CryptoUtils.fromBase64 | fromBase64} is the failure\n * mode, and it is the whole reason this exists. `fromBase64` is `Buffer`-first\n * where a `Buffer` exists, and `Buffer.from(s, 'base64')` **discards** characters\n * outside the base64 alphabet rather than complaining — so a corrupted or\n * truncated payload decodes to plausible-looking garbage and the corruption is\n * discovered, if ever, much further downstream. Use this variant whenever the\n * base64 arrived from somewhere you do not control (a wire response, a file, user\n * input) and a malformed value means \"something is wrong\", not \"do your best\".\n *\n * Implemented over `atob`, which rejects out-of-alphabet characters and bad\n * lengths. Note it inherits `atob`'s one leniency: per the WHATWG forgiving-base64\n * algorithm, ASCII whitespace inside the input is stripped rather than rejected.\n * That is deliberate — line-wrapped base64 is common and benign — and it does not\n * weaken the guarantee that matters here, which is that corrupt bytes fail loudly.\n * @param base64 - Base64 string to decode.\n * @returns `Success` with the decoded bytes, or `Failure` if `base64` is not\n * well-formed.\n * @public\n */\nexport function fromBase64Strict(base64: string): Result<Uint8Array> {\n return captureResult(() => {\n // `atob` yields a \"binary string\": one UTF-16 code unit per byte, each in\n // 0..255, so `charCodeAt` reads the bytes back losslessly for all 256 values.\n const binary: string = atob(base64);\n const bytes: Uint8Array = new Uint8Array(binary.length);\n for (let i: number = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n }).withErrorFormat(() => 'invalid base64 string');\n}\n\n// ============================================================================\n// Create Encrypted File Parameters\n// ============================================================================\n\n/**\n * Parameters for creating an {@link CryptoUtils.IEncryptedFile | encrypted file}.\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @public\n */\nexport interface ICreateEncryptedFileParams<TMetadata = JsonValue> {\n /**\n * The JSON content to encrypt.\n */\n readonly content: JsonValue;\n\n /**\n * Name of the secret used for encryption.\n */\n readonly secretName: string;\n\n /**\n * The encryption key (32 bytes for AES-256).\n */\n readonly key: Uint8Array;\n\n /**\n * {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for encryption.\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * Optional metadata to include unencrypted.\n */\n readonly metadata?: TMetadata;\n\n /**\n * Optional converter to validate metadata before including.\n * If provided, metadata will be validated before encryption.\n */\n readonly metadataConverter?: Converter<TMetadata>;\n\n /**\n * Optional {@link CryptoUtils.IKeyDerivationParams | key derivation parameters}.\n * If provided, stores the salt and iterations used to derive the key from a password.\n * This allows decryption using only a password (the salt/iterations are read from the file).\n */\n readonly keyDerivation?: IKeyDerivationParams;\n}\n\n// ============================================================================\n// Encryption Functions\n// ============================================================================\n\n/**\n * Creates an {@link CryptoUtils.IEncryptedFile | encrypted file} from JSON content.\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @param params - Encryption parameters\n * @returns `Success` with encrypted file structure, or `Failure` with an error.\n * @public\n */\nexport async function createEncryptedFile<TMetadata = JsonValue>(\n params: ICreateEncryptedFileParams<TMetadata>\n): Promise<Result<IEncryptedFile<TMetadata>>> {\n const { content, secretName, key, metadata, metadataConverter, keyDerivation, cryptoProvider } = params;\n\n // Validate metadata if converter provided\n /* c8 ignore next 6 - metadata validation path exercised via higher-level tests */\n if (metadata !== undefined && metadataConverter !== undefined) {\n const metadataResult = metadataConverter.convert(metadata);\n if (metadataResult.isFailure()) {\n return fail(`Invalid metadata: ${metadataResult.message}`);\n }\n }\n\n // Serialize content to JSON string\n const jsonResult = captureResult(() => JSON.stringify(content));\n if (jsonResult.isFailure()) {\n return fail(`Failed to serialize content: ${jsonResult.message}`);\n }\n\n // Encrypt the JSON string\n const encryptResult = await cryptoProvider.encrypt(jsonResult.value, key);\n if (encryptResult.isFailure()) {\n return fail(`Encryption failed: ${encryptResult.message}`);\n }\n\n const { iv, authTag, encryptedData } = encryptResult.value;\n\n // Build the encrypted file structure\n const encryptedFile: IEncryptedFile<TMetadata> = {\n format: Constants.ENCRYPTED_FILE_FORMAT,\n secretName,\n algorithm: Constants.DEFAULT_ALGORITHM,\n iv: toBase64(iv),\n authTag: toBase64(authTag),\n encryptedData: toBase64(encryptedData),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(keyDerivation !== undefined ? { keyDerivation } : {})\n };\n\n return succeed(encryptedFile);\n}\n\n// ============================================================================\n// Decryption Functions\n// ============================================================================\n\n/**\n * Decrypts an {@link CryptoUtils.IEncryptedFile | encrypted file} and returns the JSON content.\n * @typeParam TPayload - Expected type of decrypted content\n * @param file - The encrypted file structure\n * @param key - The decryption key (32 bytes for AES-256)\n * @param cryptoProvider - {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for decryption\n * @param payloadConverter - Optional converter to validate and convert decrypted content\n * @returns `Success` with decrypted content, or `Failure` with an error.\n * @public\n */\nexport async function decryptFile<TPayload extends JsonValue = JsonValue>(\n file: IEncryptedFile<unknown>,\n key: Uint8Array,\n cryptoProvider: ICryptoProvider,\n payloadConverter?: Converter<TPayload>\n): Promise<Result<TPayload>> {\n // Decode base64 values\n const iv = fromBase64(file.iv);\n const authTag = fromBase64(file.authTag);\n const encryptedData = fromBase64(file.encryptedData);\n\n // Decrypt\n const decryptResult = await cryptoProvider.decrypt(encryptedData, key, iv, authTag);\n if (decryptResult.isFailure()) {\n return fail(decryptResult.message);\n }\n\n // Parse JSON\n const parseResult = captureResult(() => JSON.parse(decryptResult.value) as TPayload).withErrorFormat(\n (e) => `Failed to parse decrypted content as JSON: ${e}`\n );\n\n /* c8 ignore next 3 - JSON parse failure only occurs with corrupted encrypted data */\n if (parseResult.isFailure()) {\n return parseResult;\n }\n\n // Validate with converter if provided\n /* c8 ignore next 3 - payload converter path exercised via higher-level tests */\n if (payloadConverter !== undefined) {\n return payloadConverter.convert(parseResult.value);\n }\n\n return parseResult;\n}\n\n/**\n * Attempts to parse and decrypt a JSON object as an {@link CryptoUtils.IEncryptedFile | encrypted file}.\n * @typeParam TPayload - Expected type of decrypted content\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @param json - JSON object that may be an encrypted file\n * @param key - The decryption key (32 bytes for AES-256)\n * @param cryptoProvider - {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for decryption\n * @param payloadConverter - Optional converter to validate and convert decrypted content\n * @param metadataConverter - Optional converter to validate metadata before decryption\n * @returns `Success` with decrypted content, or `Failure` with an error (including if not encrypted)\n * @public\n */\nexport async function tryDecryptFile<TPayload extends JsonValue = JsonValue, TMetadata = JsonValue>(\n json: JsonValue,\n key: Uint8Array,\n cryptoProvider: ICryptoProvider,\n payloadConverter?: Converter<TPayload>,\n metadataConverter?: Converter<TMetadata>\n): Promise<Result<TPayload>> {\n // Check if it's an encrypted file\n if (!isEncryptedFile(json)) {\n return fail('Not an encrypted file');\n }\n\n // Validate and convert to typed encrypted file\n const fileConverter = createEncryptedFileConverter(metadataConverter);\n const fileResult = fileConverter.convert(json);\n if (fileResult.isFailure()) {\n return fail(`Invalid encrypted file format: ${fileResult.message}`);\n }\n\n return decryptFile(fileResult.value, key, cryptoProvider, payloadConverter);\n}\n"]}
|
|
@@ -13,7 +13,7 @@ export { DirectEncryptionProvider, IDirectEncryptionProviderParams } from './dir
|
|
|
13
13
|
export { IKeyPairAlgorithmParams, keyPairAlgorithmParams } from './keyPairAlgorithmParams';
|
|
14
14
|
export { deriveKeyPairFromSeed } from './seedDerivedKeyPair';
|
|
15
15
|
export { NodeCryptoProvider, nodeCryptoProvider } from './nodeCryptoProvider';
|
|
16
|
-
export { createEncryptedFile, decryptFile, fromBase64, ICreateEncryptedFileParams, toBase64, tryDecryptFile } from './encryptedFile';
|
|
16
|
+
export { createEncryptedFile, decryptFile, fromBase64, fromBase64Strict, ICreateEncryptedFileParams, toBase64, tryDecryptFile } from './encryptedFile';
|
|
17
17
|
export { base64UrlNoPadDecode, base64UrlNoPadEncode, exportPublicKeyAsMultibaseSpki, hexDecode, hexEncode, importPublicKeyFromMultibaseSpki, isValidMultibaseSpkiPublicKey, MultibaseSpkiPublicKeyRegExp, multibaseBase64UrlDecode, multibaseBase64UrlEncode, spkiToRawX25519 } from './spkiHelpers';
|
|
18
18
|
export { HpkeProvider, IHpkeSealResult } from './hpkeProvider';
|
|
19
19
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/index.ts"],"names":[],"mappings":"AAoBA;;;GAGG;AAGH,cAAc,SAAS,CAAC;AAGxB,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;A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A+B,EAAE,MAAM,4BAA4B,CAAC;AAGvG,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAG3F,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAG7D,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG9E,OAAO,EACL,mBAAmB,EACnB,WAAW,EACX,UAAU,EACV,gBAAgB,EAChB,0BAA0B,EAC1B,QAAQ,EACR,cAAc,EACf,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,8BAA8B,EAC9B,SAAS,EACT,SAAS,EACT,gCAAgC,EAChC,6BAA6B,EAC7B,4BAA4B,EAC5B,wBAAwB,EACxB,wBAAwB,EACxB,eAAe,EAChB,MAAM,eAAe,CAAC;AAGvB,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC"}
|
|
@@ -55,7 +55,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
55
55
|
};
|
|
56
56
|
})();
|
|
57
57
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
58
|
-
exports.HpkeProvider = exports.spkiToRawX25519 = exports.multibaseBase64UrlEncode = exports.multibaseBase64UrlDecode = exports.MultibaseSpkiPublicKeyRegExp = exports.isValidMultibaseSpkiPublicKey = exports.importPublicKeyFromMultibaseSpki = exports.hexEncode = exports.hexDecode = exports.exportPublicKeyAsMultibaseSpki = exports.base64UrlNoPadEncode = exports.base64UrlNoPadDecode = exports.tryDecryptFile = exports.toBase64 = exports.fromBase64 = exports.decryptFile = exports.createEncryptedFile = exports.nodeCryptoProvider = exports.NodeCryptoProvider = exports.deriveKeyPairFromSeed = exports.keyPairAlgorithmParams = exports.DirectEncryptionProvider = exports.Converters = exports.KeyStore = exports.Constants = void 0;
|
|
58
|
+
exports.HpkeProvider = exports.spkiToRawX25519 = exports.multibaseBase64UrlEncode = exports.multibaseBase64UrlDecode = exports.MultibaseSpkiPublicKeyRegExp = exports.isValidMultibaseSpkiPublicKey = exports.importPublicKeyFromMultibaseSpki = exports.hexEncode = exports.hexDecode = exports.exportPublicKeyAsMultibaseSpki = exports.base64UrlNoPadEncode = exports.base64UrlNoPadDecode = exports.tryDecryptFile = exports.toBase64 = exports.fromBase64Strict = exports.fromBase64 = exports.decryptFile = exports.createEncryptedFile = exports.nodeCryptoProvider = exports.NodeCryptoProvider = exports.deriveKeyPairFromSeed = exports.keyPairAlgorithmParams = exports.DirectEncryptionProvider = exports.Converters = exports.KeyStore = exports.Constants = void 0;
|
|
59
59
|
/**
|
|
60
60
|
* Crypto utilities for encrypted file handling and key management.
|
|
61
61
|
* @packageDocumentation
|
|
@@ -89,6 +89,7 @@ var encryptedFile_1 = require("./encryptedFile");
|
|
|
89
89
|
Object.defineProperty(exports, "createEncryptedFile", { enumerable: true, get: function () { return encryptedFile_1.createEncryptedFile; } });
|
|
90
90
|
Object.defineProperty(exports, "decryptFile", { enumerable: true, get: function () { return encryptedFile_1.decryptFile; } });
|
|
91
91
|
Object.defineProperty(exports, "fromBase64", { enumerable: true, get: function () { return encryptedFile_1.fromBase64; } });
|
|
92
|
+
Object.defineProperty(exports, "fromBase64Strict", { enumerable: true, get: function () { return encryptedFile_1.fromBase64Strict; } });
|
|
92
93
|
Object.defineProperty(exports, "toBase64", { enumerable: true, get: function () { return encryptedFile_1.toBase64; } });
|
|
93
94
|
Object.defineProperty(exports, "tryDecryptFile", { enumerable: true, get: function () { return encryptedFile_1.tryDecryptFile; } });
|
|
94
95
|
// Multibase/SPKI + base64url helpers
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/index.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3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6BAA6B;AAC7B,uEAAuG;AAA9F,oIAAA,wBAAwB,OAAA;AAEjC,8DAA8D;AAC9D,mEAA2F;AAAzD,gIAAA,sBAAsB,OAAA;AAExD,+EAA+E;AAC/E,2DAA6D;AAApD,2HAAA,qBAAqB,OAAA;AAE9B,qDAAqD;AACrD,2DAA8E;AAArE,wHAAA,kBAAkB,OAAA;AAAE,wHAAA,kBAAkB,OAAA;AAE/C,yBAAyB;AACzB,iDAQyB;AAPvB,oHAAA,mBAAmB,OAAA;AACnB,4GAAA,WAAW,OAAA;AACX,2GAAA,UAAU,OAAA;AACV,iHAAA,gBAAgB,OAAA;AAEhB,yGAAA,QAAQ,OAAA;AACR,+GAAA,cAAc,OAAA;AAGhB,qCAAqC;AACrC,6CAYuB;AAXrB,mHAAA,oBAAoB,OAAA;AACpB,mHAAA,oBAAoB,OAAA;AACpB,6HAAA,8BAA8B,OAAA;AAC9B,wGAAA,SAAS,OAAA;AACT,wGAAA,SAAS,OAAA;AACT,+HAAA,gCAAgC,OAAA;AAChC,4HAAA,6BAA6B,OAAA;AAC7B,2HAAA,4BAA4B,OAAA;AAC5B,uHAAA,wBAAwB,OAAA;AACxB,uHAAA,wBAAwB,OAAA;AACxB,8GAAA,eAAe,OAAA;AAGjB,qFAAqF;AACrF,+CAA+D;AAAtD,4GAAA,YAAY,OAAA","sourcesContent":["// Copyright (c) 2024 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 * Crypto utilities for encrypted file handling and key management.\n * @packageDocumentation\n */\n\n// Re-export all types from model\nexport * from './model';\n\n// Constants\nimport * as Constants from './constants';\nexport { Constants };\n\n// KeyStore namespace\nimport * as KeyStore from './keystore';\nexport { KeyStore };\n\n// Converters namespace\nimport * as Converters from './converters';\nexport { Converters };\n\n// Direct encryption provider\nexport { DirectEncryptionProvider, IDirectEncryptionProviderParams } from './directEncryptionProvider';\n\n// WebCrypto parameter table for asymmetric keypair algorithms\nexport { IKeyPairAlgorithmParams, keyPairAlgorithmParams } from './keyPairAlgorithmParams';\n\n// Deterministic seed → keypair derivation shared by the Node/browser providers\nexport { deriveKeyPairFromSeed } from './seedDerivedKeyPair';\n\n// Node.js crypto provider (Node.js environment only)\nexport { NodeCryptoProvider, nodeCryptoProvider } from './nodeCryptoProvider';\n\n// Encrypted file helpers\nexport {\n createEncryptedFile,\n decryptFile,\n fromBase64,\n fromBase64Strict,\n ICreateEncryptedFileParams,\n toBase64,\n tryDecryptFile\n} from './encryptedFile';\n\n// Multibase/SPKI + base64url helpers\nexport {\n base64UrlNoPadDecode,\n base64UrlNoPadEncode,\n exportPublicKeyAsMultibaseSpki,\n hexDecode,\n hexEncode,\n importPublicKeyFromMultibaseSpki,\n isValidMultibaseSpkiPublicKey,\n MultibaseSpkiPublicKeyRegExp,\n multibaseBase64UrlDecode,\n multibaseBase64UrlEncode,\n spkiToRawX25519\n} from './spkiHelpers';\n\n// HPKE base mode (RFC 9180) — DHKEM(X25519, HKDF-SHA256) + HKDF-SHA256 + AES-256-GCM\nexport { HpkeProvider, IHpkeSealResult } from './hpkeProvider';\n"]}
|
|
@@ -12,7 +12,7 @@ import { FileTree, JsonValue } from '@fgv/ts-json-base';
|
|
|
12
12
|
* undecoded bytes.
|
|
13
13
|
* @public
|
|
14
14
|
*/
|
|
15
|
-
export declare class ZipFileItem<TCT extends string = string> implements FileTree.IBinaryFileTreeFileItem<TCT> {
|
|
15
|
+
export declare class ZipFileItem<TCT extends string = string> implements FileTree.IBinaryFileTreeFileItem<TCT>, FileTree.IStrictTextFileTreeFileItem<TCT> {
|
|
16
16
|
/**
|
|
17
17
|
* Indicates that this `FileTree.FileTreeItem` is a file.
|
|
18
18
|
*/
|
|
@@ -45,6 +45,11 @@ export declare class ZipFileItem<TCT extends string = string> implements FileTre
|
|
|
45
45
|
* Text form of the entry, decoded lazily from the raw bytes on first text read.
|
|
46
46
|
*/
|
|
47
47
|
private _contents;
|
|
48
|
+
/**
|
|
49
|
+
* Whether `_bytes` is what the archive carried, rather than a re-encode of text
|
|
50
|
+
* supplied to the constructor. Only the former can answer "was this valid UTF-8?".
|
|
51
|
+
*/
|
|
52
|
+
private readonly _bytesAreOriginal;
|
|
48
53
|
/**
|
|
49
54
|
* The ZIP file tree accessors that created this item.
|
|
50
55
|
*/
|
|
@@ -93,6 +98,18 @@ export declare class ZipFileItem<TCT extends string = string> implements FileTre
|
|
|
93
98
|
* The returned array is the item's internal buffer and must not be modified.
|
|
94
99
|
*/
|
|
95
100
|
getRawBytes(): Result<Uint8Array>;
|
|
101
|
+
/**
|
|
102
|
+
* Gets the file's contents, decoding UTF-8 strictly.
|
|
103
|
+
*
|
|
104
|
+
* @remarks
|
|
105
|
+
* Decidable for an entry read out of the archive, which is byte-native: this
|
|
106
|
+
* item holds exactly the bytes the archive carried. An item constructed from
|
|
107
|
+
* already-decoded text fails instead — its bytes are a re-encode, so they are
|
|
108
|
+
* well-formed UTF-8 by construction and a success would say nothing.
|
|
109
|
+
* @returns `Success` with the decoded text; `Failure` if the entry's bytes are
|
|
110
|
+
* not valid UTF-8, or if this item never held the original bytes.
|
|
111
|
+
*/
|
|
112
|
+
getTextStrict(): Result<string>;
|
|
96
113
|
}
|
|
97
114
|
/**
|
|
98
115
|
* Implementation of `IFileTreeDirectoryItem` for directories in a ZIP archive.
|
|
@@ -138,7 +155,7 @@ export declare class ZipDirectoryItem<TCT extends string = string> implements Fi
|
|
|
138
155
|
* undecoded bytes.
|
|
139
156
|
* @public
|
|
140
157
|
*/
|
|
141
|
-
export declare class ZipFileTreeAccessors<TCT extends string = string> implements FileTree.IBinaryFileTreeAccessors<TCT> {
|
|
158
|
+
export declare class ZipFileTreeAccessors<TCT extends string = string> implements FileTree.IBinaryFileTreeAccessors<TCT>, FileTree.IStrictTextFileTreeAccessors<TCT> {
|
|
142
159
|
/**
|
|
143
160
|
* The unzipped file data.
|
|
144
161
|
*/
|
|
@@ -245,6 +262,17 @@ export declare class ZipFileTreeAccessors<TCT extends string = string> implement
|
|
|
245
262
|
* The returned array is the archive's internal buffer and must not be modified.
|
|
246
263
|
*/
|
|
247
264
|
getFileBytes(path: string): Result<Uint8Array>;
|
|
265
|
+
/**
|
|
266
|
+
* Gets the contents of a file in the file tree, decoding UTF-8 strictly.
|
|
267
|
+
*
|
|
268
|
+
* @remarks
|
|
269
|
+
* Always decidable here: ZIP entries are byte-native, so this store holds
|
|
270
|
+
* exactly the bytes the archive carried.
|
|
271
|
+
* @param path - Absolute path of the entry.
|
|
272
|
+
* @returns `Success` with the decoded text; `Failure` if the entry's bytes are
|
|
273
|
+
* not valid UTF-8.
|
|
274
|
+
*/
|
|
275
|
+
getFileTextStrict(path: string): Result<string>;
|
|
248
276
|
/**
|
|
249
277
|
* Resolves a path to the ZIP file item it names.
|
|
250
278
|
* @param path - Path of the entry to look up.
|