(rootSchema: JsonObject, commonSchema: JsonObject)
| 150 | } |
| 151 | |
| 152 | function bundleSchema(rootSchema: JsonObject, commonSchema: JsonObject): JsonObject { |
| 153 | if (typeof rootSchema.$id !== 'string' || rootSchema.$id.length === 0) { |
| 154 | throw new Error('Structured output schema must declare a non-empty $id.'); |
| 155 | } |
| 156 | |
| 157 | const pendingDefs = new Set<string>(); |
| 158 | const bundled = collectAndRewriteCommonRefs(cloneJson(rootSchema), pendingDefs); |
| 159 | if (!isRecord(bundled)) { |
| 160 | throw new Error('Structured output schema bundling produced a non-object root.'); |
| 161 | } |
| 162 | |
| 163 | const commonDefs = getCommonDefinitions(commonSchema); |
| 164 | const rootDefs = bundled.$defs; |
| 165 | const localDefsCandidate = rootDefs === undefined ? {} : cloneJson(rootDefs); |
| 166 | if (!isRecord(localDefsCandidate)) { |
| 167 | throw new Error('Structured output schema root $defs must be an object when present.'); |
| 168 | } |
| 169 | const localDefs = localDefsCandidate; |
| 170 | |
| 171 | const processedDefs = new Set<string>(); |
| 172 | while (pendingDefs.size > 0) { |
| 173 | const defName = pendingDefs.values().next().value; |
| 174 | if (defName === undefined) { |
| 175 | break; |
| 176 | } |
| 177 | pendingDefs.delete(defName); |
| 178 | if (processedDefs.has(defName)) { |
| 179 | continue; |
| 180 | } |
| 181 | |
| 182 | const commonDef = commonDefs[defName]; |
| 183 | if (commonDef === undefined) { |
| 184 | throw new Error(`Missing common structured output definition: ${defName}`); |
| 185 | } |
| 186 | |
| 187 | const rewrittenDef = collectAndRewriteCommonRefs(cloneJson(commonDef), pendingDefs); |
| 188 | mergeDefinition(localDefs, defName, rewrittenDef); |
| 189 | processedDefs.add(defName); |
| 190 | } |
| 191 | |
| 192 | if (Object.keys(localDefs).length > 0) { |
| 193 | bundled.$defs = localDefs; |
| 194 | } |
| 195 | |
| 196 | const serialized = JSON.stringify(bundled); |
| 197 | if (serialized.includes(COMMON_DEFS_REF_PREFIX)) { |
| 198 | throw new Error( |
| 199 | 'Structured output schema still contains external common $refs after bundling.', |
| 200 | ); |
| 201 | } |
| 202 | |
| 203 | return bundled; |
| 204 | } |
| 205 | |
| 206 | function inlineRegistrationSchemaResource(schema: JsonObject): { |
| 207 | schema: JsonObject; |
no test coverage detected