@valerypopoff/rivet2-core 2.15.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/cjs/bundle.cjs +4350 -2077
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +22 -3
  4. package/dist/cjs/interpolationRuntime.cjs.map +3 -3
  5. package/dist/cjs/interpolationSyntax.cjs +9 -5
  6. package/dist/cjs/interpolationSyntax.cjs.map +2 -2
  7. package/dist/esm/api/createProcessor.js +5 -2
  8. package/dist/esm/exports.js +2 -0
  9. package/dist/esm/model/GraphBoundaryCache.js +2 -1
  10. package/dist/esm/model/GraphProcessor.js +268 -6
  11. package/dist/esm/model/Nodes.js +10 -0
  12. package/dist/esm/model/ProjectBundle.js +235 -0
  13. package/dist/esm/model/SplitRunProcessor.js +28 -7
  14. package/dist/esm/model/StreamingWatchTopology.js +118 -8
  15. package/dist/esm/model/SubgraphProjectTarget.js +7 -0
  16. package/dist/esm/model/chat-v2/aiSdkBridge.js +7 -5
  17. package/dist/esm/model/chat-v2/chatV2Pipeline.js +13 -8
  18. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +19 -1
  19. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  20. package/dist/esm/model/chat-v2/llmChatV2Body.js +11 -8
  21. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +2 -0
  22. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +15 -1
  23. package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
  24. package/dist/esm/model/chat-v2/llmProfile.js +3 -0
  25. package/dist/esm/model/chat-v2/llmProfileBody.js +2 -2
  26. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -1
  27. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
  28. package/dist/esm/model/chat-v2/temperature.js +9 -0
  29. package/dist/esm/model/classifier/credentials.js +30 -4
  30. package/dist/esm/model/classifier/images.js +176 -0
  31. package/dist/esm/model/classifier/json.js +57 -0
  32. package/dist/esm/model/classifier/limits.js +270 -0
  33. package/dist/esm/model/classifier/openai.js +118 -0
  34. package/dist/esm/model/classifier/preparation.js +74 -0
  35. package/dist/esm/model/classifier/providers.js +260 -185
  36. package/dist/esm/model/classifier/questionHelpers.js +29 -45
  37. package/dist/esm/model/classifier/questions.js +53 -0
  38. package/dist/esm/model/classifier/response.js +75 -0
  39. package/dist/esm/model/classifier/state.js +204 -0
  40. package/dist/esm/model/nodeRunFailure.js +47 -0
  41. package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
  42. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +178 -138
  43. package/dist/esm/model/nodes/ClassifierQuestionNode.js +59 -15
  44. package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
  45. package/dist/esm/model/nodes/HttpCallNode.js +44 -75
  46. package/dist/esm/model/nodes/ImageNode.js +44 -3
  47. package/dist/esm/model/nodes/LLMChatV2Node.js +24 -3
  48. package/dist/esm/model/nodes/ObjectNode.js +29 -18
  49. package/dist/esm/model/nodes/PromptNode.js +2 -1
  50. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
  51. package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
  52. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
  53. package/dist/esm/model/nodes/StreamValueNode.js +38 -0
  54. package/dist/esm/model/nodes/SubGraphNode.js +196 -35
  55. package/dist/esm/model/nodes/ToBase64Node.js +106 -0
  56. package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
  57. package/dist/esm/recording/ExecutionRecorder.js +26 -0
  58. package/dist/esm/utils/base64.js +18 -15
  59. package/dist/esm/utils/errors.js +41 -0
  60. package/dist/esm/utils/interpolation.js +44 -22
  61. package/dist/esm/utils/interpolationSyntax.js +15 -6
  62. package/dist/esm/utils/serialization/serialization.js +3 -2
  63. package/dist/esm/utils/serialization/serializationUtils.js +6 -0
  64. package/dist/esm/utils/serialization/serialization_v4.js +15 -3
  65. package/dist/types/api/createProcessor.d.ts +7 -1
  66. package/dist/types/exports.d.ts +2 -0
  67. package/dist/types/model/CycleDetector.d.ts +1 -2
  68. package/dist/types/model/ExecutorProtocol.d.ts +2 -0
  69. package/dist/types/model/GraphBoundaryCache.d.ts +2 -0
  70. package/dist/types/model/GraphProcessor.d.ts +1 -0
  71. package/dist/types/model/Nodes.d.ts +6 -2
  72. package/dist/types/model/ProcessContext.d.ts +12 -0
  73. package/dist/types/model/ProjectBundle.d.ts +54 -0
  74. package/dist/types/model/ProjectReferenceLoader.d.ts +3 -0
  75. package/dist/types/model/StreamingWatchTopology.d.ts +11 -1
  76. package/dist/types/model/SubgraphProjectTarget.d.ts +38 -0
  77. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -1
  78. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  79. package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -1
  80. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +6 -6
  81. package/dist/types/model/chat-v2/temperature.d.ts +2 -0
  82. package/dist/types/model/classifier/credentials.d.ts +3 -1
  83. package/dist/types/model/classifier/images.d.ts +18 -0
  84. package/dist/types/model/classifier/json.d.ts +19 -0
  85. package/dist/types/model/classifier/limits.d.ts +42 -0
  86. package/dist/types/model/classifier/openai.d.ts +5 -0
  87. package/dist/types/model/classifier/preparation.d.ts +16 -0
  88. package/dist/types/model/classifier/providers.d.ts +67 -9
  89. package/dist/types/model/classifier/questionHelpers.d.ts +6 -4
  90. package/dist/types/model/classifier/questions.d.ts +4 -0
  91. package/dist/types/model/classifier/response.d.ts +4 -0
  92. package/dist/types/model/classifier/state.d.ts +37 -0
  93. package/dist/types/model/classifier/types.d.ts +2 -0
  94. package/dist/types/model/nodeRunFailure.d.ts +13 -0
  95. package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
  96. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +3 -0
  97. package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
  98. package/dist/types/model/nodes/ImageNode.d.ts +4 -0
  99. package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
  100. package/dist/types/model/nodes/ObjectNode.d.ts +2 -1
  101. package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
  102. package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
  103. package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
  104. package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
  105. package/dist/types/utils/base64.d.ts +1 -1
  106. package/dist/types/utils/errors.d.ts +4 -0
  107. package/dist/types/utils/interpolation.d.ts +13 -2
  108. package/dist/types/utils/interpolationSyntax.d.ts +1 -1
  109. package/dist/types/utils/serialization/serialization.d.ts +3 -1
  110. package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
  111. package/package.json +1 -1
@@ -47,7 +47,7 @@ function getOptionalNumberBodyField(label, value, usesInput) {
47
47
  if (usesInput) {
48
48
  return { label, value: '(Using Input)' };
49
49
  }
50
- return value === undefined ? undefined : { label, value: `${value}` };
50
+ return value == null || !Number.isFinite(value) ? undefined : { label, value: `${value}` };
51
51
  }
52
52
  function getOptionalStringBodyField(label, value, usesInput) {
53
53
  if (usesInput) {
@@ -177,15 +177,18 @@ function getBehaviorBodyFields(data) {
177
177
  ];
178
178
  }
179
179
  function getErrorBodyFields(data) {
180
- if (!data.retryOnNon200) {
181
- return [];
182
- }
183
180
  const repeatTimes = data.retryOnNon200RepeatTimes ?? DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES;
184
181
  const cooldownMs = data.retryOnNon200CooldownMs ?? DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS;
185
182
  return [
186
- { label: 'Retry on non-200', value: 'Enabled' },
187
- { label: 'Repeat times', value: `${repeatTimes}` },
188
- { label: 'Cooldown, ms', value: `${cooldownMs}` },
183
+ ...(data.errorOnNon200 !== false ? [{ label: 'Throw on non-2XX', value: 'Enabled' }] : []),
184
+ ...(data.catchRequestFailed ? [{ label: 'Catch all failures', value: 'Enabled' }] : []),
185
+ ...(data.retryOnNon200
186
+ ? [
187
+ { label: 'Retry on non-200', value: 'Enabled' },
188
+ { label: 'Repeat times', value: `${repeatTimes}` },
189
+ { label: 'Cooldown, ms', value: `${cooldownMs}` },
190
+ ]
191
+ : []),
189
192
  ];
190
193
  }
191
194
  function getAdvancedBodySection(data) {
@@ -241,7 +244,7 @@ function getParameterBodyFields(data) {
241
244
  : undefined;
242
245
  return [
243
246
  ...(reasoningEffort ? [{ label: 'Reasoning effort', value: reasoningEffort }] : []),
244
- { label: 'Temperature', value: data.useTemperatureInput ? '(Using Input)' : `${data.temperature}` },
247
+ getOptionalNumberBodyField('Temperature', data.temperature, data.useTemperatureInput),
245
248
  { label: 'Max output tokens', value: data.useMaxTokensInput ? '(Using Input)' : `${data.maxTokens}` },
246
249
  getOptionalNumberBodyField('Top P', data.topP, data.useTopPInput),
247
250
  getOptionalNumberBodyField('Top K', data.topK, data.useTopKInput),
@@ -58,6 +58,8 @@ export function createLLMChatV2NodeData() {
58
58
  autoContinueToolCalls: false,
59
59
  maxToolRounds: 3,
60
60
  retryOnNon200: false,
61
+ errorOnNon200: true,
62
+ catchRequestFailed: false,
61
63
  retryOnNon200RepeatTimes: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES,
62
64
  retryOnNon200CooldownMs: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS,
63
65
  outputLLMAttempts: false,
@@ -252,9 +252,10 @@ function getParameterEditors() {
252
252
  {
253
253
  type: 'number',
254
254
  label: 'Temperature',
255
- helperMessage: 'Provider-dependent; some reasoning models may ignore this setting.',
255
+ helperMessage: 'Leave blank to use the provider default. Some reasoning models may ignore this setting.',
256
256
  dataKey: 'temperature',
257
257
  useInputToggleDataKey: 'useTemperatureInput',
258
+ allowEmpty: true,
258
259
  min: 0,
259
260
  max: 2,
260
261
  step: 0.1,
@@ -559,6 +560,19 @@ function getProviderAdvancedEditors() {
559
560
  }
560
561
  function getErrorBehaviorEditors() {
561
562
  return group('Error behavior', [
563
+ {
564
+ type: 'toggle',
565
+ label: 'Fail on non-2XX status code',
566
+ dataKey: 'errorOnNon200',
567
+ defaultValue: true,
568
+ helperMessage: 'After retries and profile fallback, throw on a rejected HTTP request. When disabled, return Run failed and Run error; unavailable response outputs are excluded.',
569
+ },
570
+ {
571
+ type: 'toggle',
572
+ label: 'Catch all failures',
573
+ dataKey: 'catchRequestFailed',
574
+ helperMessage: 'Return any node execution failure through Run failed and Run error instead of stopping the graph. Explicit graph cancellation is never caught.',
575
+ },
562
576
  {
563
577
  type: 'toggle',
564
578
  label: 'Retry on non-200',
@@ -1,14 +1,34 @@
1
+ /** Repair legacy payloads on read or Save without mutating the supplied data. */
2
+ export function normalizeSerializedLLMTemperatureData(nodeType, data) {
3
+ if (!['llmChatV2', 'llmProfile'].includes(nodeType) || data == null || typeof data !== 'object')
4
+ return data;
5
+ const record = data;
6
+ if (!Object.hasOwn(record, 'temperature'))
7
+ return data;
8
+ if (record.temperature != null && !(typeof record.temperature === 'number' && Number.isNaN(record.temperature)))
9
+ return data;
10
+ const copy = { ...record };
11
+ delete copy.temperature;
12
+ return copy;
13
+ }
1
14
  /**
2
- * Serialized LLM Chat migrations live beside the node contract, rather than
15
+ * Serialized LLM Chat/Profile migrations live beside the node contract, rather than
3
16
  * making generic project serialization understand LLM-specific settings.
4
17
  * This is deliberately idempotent because deserialization can normalize a
5
18
  * graph more than once while it is imported or embedded in a prefab.
6
19
  */
7
20
  export function normalizeSerializedLLMChatV2Node(node) {
8
- if (node.type !== 'llmChatV2' || node.data == null || typeof node.data !== 'object') {
21
+ if (!['llmChatV2', 'llmProfile'].includes(node.type))
9
22
  return;
23
+ for (const variant of node.variants ?? []) {
24
+ variant.data = normalizeSerializedLLMTemperatureData(node.type, variant.data);
10
25
  }
26
+ node.data = normalizeSerializedLLMTemperatureData(node.type, node.data);
27
+ if (node.data == null || typeof node.data !== 'object')
28
+ return;
11
29
  const data = node.data;
30
+ if (node.type !== 'llmChatV2')
31
+ return;
12
32
  const hadLegacyRequestDiagnostics = data.outputRequestStatus === true || data.outputRequestError === true;
13
33
  if (hadLegacyRequestDiagnostics && !Object.hasOwn(data, 'outputLLMAttempts')) {
14
34
  data.outputLLMAttempts = true;
@@ -4,6 +4,7 @@ import { llmProfileBooleanDataKeys, llmProfileOptionalNumberDataKeys, llmProfile
4
4
  import { LLM_PROFILE_VALUE_VERSION, pickLLMChatV2ProfileData } from './llmProfileTypes.js';
5
5
  import { createRivetLLMProfileHealthIdentity } from './llmProfileHealthStore.js';
6
6
  import { normalizeChatV2CredentialNamesByProvider } from './chatV2CredentialNames.js';
7
+ import { normalizeTemperature } from './temperature.js';
7
8
  export { applyLLMProfileToNodeData, createDefaultLLMProfileValue, createLLMProfileNodeData, LLM_PROFILE_VALUE_VERSION, pickLLMChatV2ProfileData, } from './llmProfileTypes.js';
8
9
  const credentialSources = new Set([
9
10
  'input',
@@ -34,6 +35,8 @@ export function normalizeLLMProfileValue(value) {
34
35
  const configuration = normalizeConfiguration({
35
36
  ...defaults,
36
37
  ...value.configuration,
38
+ // Defaults seed new nodes, not missing values in an existing profile.
39
+ temperature: normalizeTemperature(value.configuration.temperature, 'LLM Profile temperature'),
37
40
  provider,
38
41
  model: model.trim(),
39
42
  });
@@ -9,7 +9,7 @@ function getOptionalNumberBodyField(label, value, usesInput) {
9
9
  if (usesInput) {
10
10
  return { label, value: '(Using Input)' };
11
11
  }
12
- return value === undefined ? undefined : { label, value: `${value}` };
12
+ return value == null || !Number.isFinite(value) ? undefined : { label, value: `${value}` };
13
13
  }
14
14
  function getOptionalStringBodyField(label, value, usesInput) {
15
15
  if (usesInput) {
@@ -159,7 +159,7 @@ export function getLLMProfileBodySections(data) {
159
159
  : []),
160
160
  ];
161
161
  const parameterFields = [
162
- { label: 'Temperature', value: data.useTemperatureInput ? '(Using Input)' : `${data.temperature}` },
162
+ getOptionalNumberBodyField('Temperature', data.temperature, data.useTemperatureInput),
163
163
  { label: 'Max output tokens', value: data.useMaxTokensInput ? '(Using Input)' : `${data.maxTokens}` },
164
164
  getOptionalNumberBodyField('Top P', data.topP, data.useTopPInput),
165
165
  getOptionalNumberBodyField('Top K', data.topK, data.useTopKInput),
@@ -1,7 +1,7 @@
1
1
  export const llmProfileFieldSpecs = [
2
2
  { key: 'model', inputId: 'model', valueKind: 'string' },
3
3
  { key: 'useModelInput', valueKind: 'boolean', resolvedInputToggle: true },
4
- { key: 'temperature', inputId: 'temperature', valueKind: 'required-number' },
4
+ { key: 'temperature', inputId: 'temperature', valueKind: 'optional-number' },
5
5
  { key: 'useTemperatureInput', valueKind: 'boolean', resolvedInputToggle: true },
6
6
  { key: 'topP', inputId: 'topP', valueKind: 'optional-number' },
7
7
  { key: 'useTopPInput', valueKind: 'boolean', resolvedInputToggle: true },
@@ -41,7 +41,7 @@ export function resolveLLMProfileNodeValue(params) {
41
41
  ...data,
42
42
  model,
43
43
  useModelInput: false,
44
- temperature: generation.temperature ?? data.temperature,
44
+ temperature: generation.temperature,
45
45
  useTemperatureInput: false,
46
46
  maxTokens: generation.maxTokens ?? data.maxTokens,
47
47
  useMaxTokensInput: false,
@@ -0,0 +1,9 @@
1
+ /** Empty historical editor values are unset, never the provider's explicit zero. */
2
+ export function normalizeTemperature(value, label = 'Temperature') {
3
+ if (value == null || (typeof value === 'number' && Number.isNaN(value)))
4
+ return undefined;
5
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
6
+ throw new Error(`${label} must be a finite number when provided.`);
7
+ }
8
+ return value;
9
+ }
@@ -1,8 +1,17 @@
1
1
  import { coerceTypeOptional } from '../../utils/coerceType.js';
2
+ import { classifierDataProperty, classifierInputDataValue } from './json.js';
2
3
  export const JEV_DEFAULT_CREDENTIAL_NAMES = {
3
4
  programmaticName: 'typesafeApiKey',
4
5
  environmentVariableName: 'TYPESAFE_API_KEY',
5
6
  };
7
+ export const LIQUID_DEFAULT_CREDENTIAL_NAMES = {
8
+ programmaticName: 'liquidApiKey',
9
+ environmentVariableName: 'LIQUID_API_KEY',
10
+ };
11
+ export const OPENAI_DEFAULT_CREDENTIAL_NAMES = {
12
+ programmaticName: 'openAiApiKey',
13
+ environmentVariableName: 'OPENAI_API_KEY',
14
+ };
6
15
  const programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
7
16
  const environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
8
17
  export function isValidClassifierProgrammaticCredentialName(name) {
@@ -41,17 +50,29 @@ export function getClassifierCredentialNamesForDisplay(value, defaults = JEV_DEF
41
50
  }
42
51
  }
43
52
  export function isDefaultClassifierCredentialNames(names, defaults = JEV_DEFAULT_CREDENTIAL_NAMES) {
44
- return names.programmaticName === defaults.programmaticName && names.environmentVariableName === defaults.environmentVariableName;
53
+ return (names.programmaticName === defaults.programmaticName &&
54
+ names.environmentVariableName === defaults.environmentVariableName);
45
55
  }
46
56
  export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, defaults, inputs, providerId, }) {
57
+ if (apiKeySource === 'classifier-settings') {
58
+ const read = (value, key) => value !== null && typeof value === 'object'
59
+ ? classifierDataProperty(value, key, 'Classifier settings credentials')
60
+ : undefined;
61
+ const saved = getNonEmptyString(read(read(read(context.settings, 'classifierProviders'), providerId), 'apiKey'));
62
+ if (!saved)
63
+ throw new Error(`Classifier settings API key for ${providerId} is not set. No automatic fallback is used.`);
64
+ return saved;
65
+ }
47
66
  if (apiKeySource === 'input') {
48
- const value = coerceTypeOptional(inputs['apiKey'], 'string')?.trim();
67
+ const value = coerceTypeOptional(classifierInputDataValue(inputs, 'apiKey'), 'string')?.trim();
49
68
  if (!value)
50
69
  throw new Error('API Key input is required when API key source is Input port.');
51
70
  return value;
52
71
  }
72
+ if (apiKeySource !== undefined && apiKeySource !== 'configured')
73
+ throw new Error('Unknown classifier API key source.');
53
74
  const names = normalizeClassifierCredentialNames(apiKeyNames, defaults);
54
- const namedValue = resolveNamedClassifierApiKey(context, names);
75
+ const namedValue = resolveNamedClassifierApiKey(context, names, providerId === 'openai' && isDefaultClassifierCredentialNames(names, defaults));
55
76
  if (namedValue)
56
77
  return namedValue;
57
78
  if (isDefaultClassifierCredentialNames(names, defaults)) {
@@ -67,10 +88,15 @@ export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, de
67
88
  }
68
89
  throw new Error(`${providerId === 'jev' ? 'Jev' : 'Classifier'} API key is not set. Pass ${names.programmaticName}, configure ${names.environmentVariableName}, or set the configured key in Settings > Classifier.`);
69
90
  }
70
- function resolveNamedClassifierApiKey(context, names) {
91
+ function resolveNamedClassifierApiKey(context, names, useLegacyOpenAIKey = false) {
71
92
  const programmaticValue = getNonEmptyString(context.settings?.[names.programmaticName]);
72
93
  if (programmaticValue)
73
94
  return programmaticValue;
95
+ if (useLegacyOpenAIKey) {
96
+ const legacy = getNonEmptyString(context.settings.openAiKey);
97
+ if (legacy)
98
+ return legacy;
99
+ }
74
100
  const environmentValue = getNonEmptyString(context.settings?.pluginEnv?.[names.environmentVariableName]);
75
101
  if (environmentValue)
76
102
  return environmentValue;
@@ -0,0 +1,176 @@
1
+ import { base64ToUint8Array, uint8ArrayToBase64Sync } from '../../utils/base64.js';
2
+ import { classifierDataProperty } from './json.js';
3
+ import { assertClassifierResourceLimits, classifierByteView, CLASSIFIER_LIMITS, } from './limits.js';
4
+ class InvalidClassifierImageError extends Error {
5
+ }
6
+ const invalidImage = () => new InvalidClassifierImageError('State images must contain inline base64 PNG, JPEG, GIF or WebP image data with valid headers and matching media type.');
7
+ function isBase64(value) {
8
+ // Avoid repeated regexp groups: they overflow the regexp stack on large images.
9
+ return value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value);
10
+ }
11
+ function jpegInfo(size, read, check) {
12
+ const byte = (offset) => read(offset, 1)[0];
13
+ const uint16 = (offset) => {
14
+ const bytes = read(offset, 2);
15
+ return (bytes[0] << 8) + bytes[1];
16
+ };
17
+ let offset = 2;
18
+ while (offset + 4 <= size) {
19
+ check?.();
20
+ if (byte(offset++) !== 0xff)
21
+ break;
22
+ while (byte(offset) === 0xff) {
23
+ if ((offset & 4095) === 0)
24
+ check?.();
25
+ offset++;
26
+ }
27
+ const marker = byte(offset++);
28
+ if (marker === undefined || marker === 0xda || marker === 0xd9)
29
+ break;
30
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7))
31
+ continue;
32
+ if (offset + 2 > size)
33
+ break;
34
+ const length = uint16(offset);
35
+ if (length < 2 || offset + length > size)
36
+ break;
37
+ if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker) && length >= 8)
38
+ return { mediaType: 'image/jpeg', width: uint16(offset + 5), height: uint16(offset + 3) };
39
+ offset += length;
40
+ }
41
+ return undefined;
42
+ }
43
+ /** Read image headers without a browser, filesystem access, or a decoder dependency. */
44
+ function imageInfo(bytes, check) {
45
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
46
+ const ascii = (offset, length) => String.fromCharCode(...bytes.subarray(offset, offset + length));
47
+ let info;
48
+ if (bytes.length >= 33 &&
49
+ ascii(0, 8) === '\x89PNG\r\n\x1a\n' &&
50
+ view.getUint32(8) === 13 &&
51
+ ascii(12, 4) === 'IHDR') {
52
+ info = { mediaType: 'image/png', width: view.getUint32(16), height: view.getUint32(20) };
53
+ }
54
+ else if (bytes.length >= 13 && ['GIF87a', 'GIF89a'].includes(ascii(0, 6))) {
55
+ info = { mediaType: 'image/gif', width: view.getUint16(6, true), height: view.getUint16(8, true) };
56
+ }
57
+ else if (bytes.length >= 25 && ascii(0, 4) === 'RIFF' && ascii(8, 4) === 'WEBP') {
58
+ const chunk = ascii(12, 4);
59
+ const uint24 = (offset) => bytes[offset] + (bytes[offset + 1] << 8) + (bytes[offset + 2] << 16);
60
+ if (chunk === 'VP8X' && bytes.length >= 30)
61
+ info = { mediaType: 'image/webp', width: uint24(24) + 1, height: uint24(27) + 1 };
62
+ else if (chunk === 'VP8 ' && bytes.length >= 30 && ascii(23, 3) === '\x9d\x01\x2a')
63
+ info = {
64
+ mediaType: 'image/webp',
65
+ width: view.getUint16(26, true) & 0x3fff,
66
+ height: view.getUint16(28, true) & 0x3fff,
67
+ };
68
+ else if (chunk === 'VP8L' && bytes[20] === 0x2f) {
69
+ const bits = view.getUint32(21, true);
70
+ info = { mediaType: 'image/webp', width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
71
+ }
72
+ }
73
+ else if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
74
+ info = jpegInfo(bytes.length, (offset, length) => bytes.subarray(offset, offset + length), check);
75
+ }
76
+ if (!info || info.width === 0 || info.height === 0)
77
+ throw invalidImage();
78
+ return info;
79
+ }
80
+ function base64ImageInfo(payload, check) {
81
+ // JPEG metadata may precede its dimensions. Skip segment bodies and decode
82
+ // only the byte windows needed by the same parser used for native images.
83
+ if (payload.startsWith('/9j/')) {
84
+ const size = (payload.length / 4) * 3 - (payload.endsWith('==') ? 2 : payload.endsWith('=') ? 1 : 0);
85
+ let start = -1;
86
+ let window = new Uint8Array();
87
+ const info = jpegInfo(size, (offset, length) => {
88
+ if (offset < start || offset + length > start + window.length) {
89
+ start = Math.floor(offset / 3) * 3;
90
+ // A small cache also bounds decoder calls for runs of JPEG fill bytes.
91
+ window = base64ToUint8Array(payload.slice((start / 3) * 4, (start / 3) * 4 + 4096));
92
+ }
93
+ return window.subarray(offset - start, offset - start + length);
94
+ }, check);
95
+ if (!info || info.width === 0 || info.height === 0)
96
+ throw invalidImage();
97
+ return info;
98
+ }
99
+ // PNG/GIF/WebP dimensions are in the first 36 bytes.
100
+ return imageInfo(base64ToUint8Array(payload.slice(0, 48)));
101
+ }
102
+ export function prepareNativeClassifierImage(value, check) {
103
+ if (!value || typeof value !== 'object')
104
+ throw invalidImage();
105
+ const data = classifierDataProperty(value, 'data');
106
+ const mediaType = classifierDataProperty(value, 'mediaType');
107
+ if (!(data instanceof Uint8Array))
108
+ throw invalidImage();
109
+ const bytes = classifierByteView(data);
110
+ assertClassifierResourceLimits(bytes, check);
111
+ const info = imageInfo(bytes, check);
112
+ if (info.mediaType !== mediaType)
113
+ throw invalidImage();
114
+ check?.();
115
+ return { ...info, dataUrl: `data:${info.mediaType};base64,${uint8ArrayToBase64Sync(bytes)}` };
116
+ }
117
+ export function nativeClassifierImage(value, check) {
118
+ return prepareNativeClassifierImage(value, check).dataUrl;
119
+ }
120
+ export function inspectClassifierImage(value, check) {
121
+ check?.();
122
+ if (typeof value !== 'string')
123
+ throw invalidImage();
124
+ const prefix = /^data:(image\/(?:png|jpeg|gif|webp));base64,/.exec(value);
125
+ if (!prefix)
126
+ throw invalidImage();
127
+ const payload = value.slice(prefix[0].length);
128
+ if (!isBase64(payload))
129
+ throw invalidImage();
130
+ const info = base64ImageInfo(payload, check);
131
+ if (info.mediaType !== prefix[1])
132
+ throw invalidImage();
133
+ return info;
134
+ }
135
+ /** Recognize image bytes, not merely strings using the base64 alphabet. */
136
+ export function classifierImageFromText(value, check) {
137
+ return prepareClassifierImageText(value, check)?.dataUrl;
138
+ }
139
+ export function prepareClassifierImageText(value, check) {
140
+ check?.();
141
+ if (value.length > CLASSIFIER_LIMITS.requestBytes)
142
+ throw new Error('Classifier image/text exceeds the 32 MiB input limit.');
143
+ if (value.startsWith('data:image/')) {
144
+ return { ...inspectClassifierImage(value, check), dataUrl: value };
145
+ }
146
+ if (!/^(?:iVBOR|\/9j\/|R0lGOD|UklGR)/.test(value) || !isBase64(value))
147
+ return undefined;
148
+ try {
149
+ const info = base64ImageInfo(value, check);
150
+ return { ...info, dataUrl: `data:${info.mediaType};base64,${value}` };
151
+ }
152
+ catch (error) {
153
+ if (error instanceof InvalidClassifierImageError)
154
+ return undefined;
155
+ throw error;
156
+ }
157
+ }
158
+ export function assertClassifierImages(value, check) {
159
+ if (!Array.isArray(value) || value.length > 128)
160
+ throw new Error('State must contain at most 128 images.');
161
+ for (const image of value)
162
+ inspectClassifierImage(image, check);
163
+ }
164
+ export function assertLiquidImageLimits(images, check) {
165
+ if (images.length > 8)
166
+ throw new Error('Liquid d1 State must contain at most 8 images.');
167
+ let patches = 0;
168
+ for (const { width, height } of images) {
169
+ check?.();
170
+ if (Math.max(width, height) / Math.min(width, height) > 100)
171
+ throw new Error('Liquid d1 images must have an aspect ratio at most 100:1.');
172
+ patches += Math.ceil(width / 32) * Math.ceil(height / 32);
173
+ }
174
+ if (patches > 10_000)
175
+ throw new Error('Liquid d1 images must contain at most 10,000 patches of 32 by 32 pixels in total.');
176
+ }
@@ -0,0 +1,57 @@
1
+ import { ClassifierValueBudget } from './limits.js';
2
+ /** Read evidence fields without invoking getters or accepting prototype-provided content. */
3
+ export function classifierDataProperty(value, key, label = 'State') {
4
+ const property = Object.getOwnPropertyDescriptor(value, key);
5
+ if (property ? !('value' in property) : key in value)
6
+ throw new Error(`${label} must use own data properties, not accessors or inherited fields.`);
7
+ return property?.value;
8
+ }
9
+ /** Snapshot only the selected port's wrapper; never read unrelated input getters. */
10
+ export function classifierInputDataValue(inputs, port) {
11
+ const label = `Classifier ${port} input`;
12
+ const input = classifierDataProperty(inputs, port, label);
13
+ if (input === undefined)
14
+ return undefined;
15
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
16
+ throw new Error(`${label} must contain a Rivet data value.`);
17
+ return {
18
+ type: classifierDataProperty(input, 'type', label),
19
+ value: classifierDataProperty(input, 'value', label),
20
+ };
21
+ }
22
+ /** Match JSON array order; never invoke a caller-provided iterator or index getter. */
23
+ export function* classifierArrayValues(value, label) {
24
+ for (let index = 0; index < value.length; index++) {
25
+ const property = Object.getOwnPropertyDescriptor(value, String(index));
26
+ if (!property || !('value' in property))
27
+ throw new Error(`${label} is not JSON-compatible: use own data properties, not accessors or sparse arrays.`);
28
+ yield property.value;
29
+ }
30
+ }
31
+ /** Validate the data JSON.stringify will read, without invoking property getters or array iterators. */
32
+ export function assertClassifierJson(value, label = 'State', allowUndefinedProperties = false, check, maxBytes) {
33
+ return new ClassifierValueBudget(check, maxBytes).inspect(value, { label, allowUndefinedProperties }).bytes;
34
+ }
35
+ /** Validate, account and detach JSON in one bounded walk, without serialization hooks. */
36
+ export function snapshotClassifierJson(value, label, budget, allowUndefinedProperties = false) {
37
+ return budget.inspect(value, { label, allowUndefinedProperties, copy: true }).value;
38
+ }
39
+ /** Root entry kinds are narrower than the JSON values allowed inside structured entries. */
40
+ export function assertClassifierEntryKind(value, label) {
41
+ if (value !== null && typeof value !== 'string' && typeof value !== 'object')
42
+ throw new Error(`${label} must contain only strings, null, objects, and arrays.`);
43
+ }
44
+ export function assertClassifierEntry(value, label) {
45
+ assertClassifierEntryKind(value, label);
46
+ assertClassifierJson(value, label);
47
+ }
48
+ export function assertClassifierInstructionsKind(value, label = 'Instructions') {
49
+ assertClassifierEntryKind(value, label);
50
+ if (value === null || (typeof value === 'string' && value.trim() === ''))
51
+ throw new Error(`${label} are required.`);
52
+ }
53
+ export function assertClassifierInstructions(value, label = 'Instructions') {
54
+ // Bound strings before trim(), which can otherwise scan an oversized authored value.
55
+ assertClassifierEntry(value, label);
56
+ assertClassifierInstructionsKind(value, label);
57
+ }